From pavlovevidence at gmail.com Sun Aug 1 00:08:51 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 31 Jul 2010 21:08:51 -0700 (PDT) Subject: Problem with Elementtree and XMLSchem instance type References: Message-ID: <96e47fd8-c939-48a2-9a2b-92afa720c8ac@k1g2000prl.googlegroups.com> On Jul 30, 6:21?am, Roland Hedberg wrote: > Hi! > > I have the following XML snippet: > > ? ? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > ? ? xmlns:fed="http://docs.oasis-open.org/wsfed/federation/200706" > ? ? xsi:type="fed:SecurityTokenServiceType"> > ? ? .... > > > This part after parsing with Elementtree gives me an Element instance > with the following properties: > > > tree.tag > > {urn:oasis:names:tc:SAML:2.0:metadata}RoleDescriptor> tree.keys() > > ['{http://www.w3.org/2001/XMLSchema-instance}type']> tree['{http://www.w3.org/2001/XMLSchema-instance}type'] > > fed:SecurityTokenServiceType > > And there is the problem, I've lost the coupling between the prefix > 'fed' and the namespace > "http://docs.oasis-open.org/wsfed/federation/200706". > > Is there any way I can get at the prefix <-> namespace mapping from an > Element instance ? > I've read the documentation I can find and there is nothing that tells > me how to get at the mapping. ElementTree doesn't have a way to do this. My general feeling is that ElementTree is a lot handier for reading and writing your own XML formats, than for handling XML files produced by other tools. The lxml package has an ElementTree like interface but with some methods to handle namespace abbreviations. Carl Banks From usernet at ilthio.net Sun Aug 1 01:17:50 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 1 Aug 2010 05:17:50 +0000 (UTC) Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 2010-08-01, Lawrence D'Oliveiro wrote: > In message , Tim Harig wrote: > >> It would be rewarding as it would make writing cross-platform charactor >> mode applications possible. > > I thought Windows users were allergic to command lines. To the best of my knowledge, there have never been any documentated cases of computer software related alleries. There are however several chemicals used in the process of constructing computer hardware componets which have been linked to allergy illnesses. Maybe Windows users are simply allergic to their computers. From breamoreboy at yahoo.co.uk Sun Aug 1 02:23:20 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Aug 2010 07:23:20 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 01/08/2010 06:17, Tim Harig wrote: > On 2010-08-01, Lawrence D'Oliveiro wrote: >> In message, Tim Harig wrote: >> >>> It would be rewarding as it would make writing cross-platform charactor >>> mode applications possible. >> >> I thought Windows users were allergic to command lines. > > To the best of my knowledge, there have never been any documentated > cases of computer software related alleries. There are however several > chemicals used in the process of constructing computer hardware componets > which have been linked to allergy illnesses. Maybe Windows users are > simply allergic to their computers. Windows users biggest allergy is to this strange world that involves "make" on other boxes, whatever that is, it strikes me as rather archaic. Personally I find double clicking on an msi file rather easier. Regards. Mark Lawrence. From legard4d at gmail.com Sun Aug 1 02:42:23 2010 From: legard4d at gmail.com (legard_new) Date: Sat, 31 Jul 2010 23:42:23 -0700 (PDT) Subject: Call CFUNCTYPE, class Structure, ctype, dll and Callback function problem References: <70faf0b4-fead-49ac-bf18-e182fd63bbff@j8g2000yqd.googlegroups.com> Message-ID: On Jul 31, 10:22?pm, "Mark Tolonen" wrote: > "legard_new" wrote in message > > news:70faf0b4-fead-49ac-bf18-e182fd63bbff at j8g2000yqd.googlegroups.com... > > > > > > > Hello, > > > I have a problem with calling Callback function with Python. I have a > > DLL file. > > > Below is a description in documentation. > > FUNCTION Callback > > Arguments: Callback ID integer read-only, immediate value > > CBackProc address read-only, immediate value > > Returns: status > > The Callback routine registers the callback routine for > > notification of a link state change. > > The callback procedure provided by the application must accept one > > parameter: > > the address of the structure containing the data. > > > CallbackID An integer identifying the callback routine being > > provided to the API. Can be one of 1 or 2. > > CBackProc The address of the callback procedure that the API will > > execute. > > > This procedure must accept one parameter, of type LinkStateStruct, > > passed by reference. > > > LinkStateStruct read-only, by reference > > OldState: byte > > NewState byte > > > The routine will return one of the following error codes: > > 1 - The callback address was successfully registered by the API. > > 2 - The API has not been initialised. > > 3 - The CallbackID value was not recognised as a valid link state > > callback. > > > Here is my little code in Python: > > > from ctypes import * > > class LinkStateStruct(Structure): > > ? ?_fields_ = [("OldState", c_byte), > > ? ? ? ? ? ? ? ?("NewState", c_byte)] > > demoapi=windll.LoadLibrary("D:\\DEMO.dll") > > #DECLARE CALLBACK FUNCTION > > g_HLSC = CFUNCTYPE(c_int, POINTER(LinkStateStruct)) > > def py_g_HLSC(x): > > ? ?print "CALLBACK__py_g_HLSC_FIRED->", x > > ? ?return 0 > > g__HLSC = g_HLSC(py_g_HLSC) > > status=demoapi.Callback(1,g__HLSC) > > print "Status=",status > > > My result is: > > Status= 1 > > > But Callback function is not executed. If think that i call g__HLSC > > witohout paramter that in document "The callback procedure > > > provided by the application must accept one parameter: the address of > > the structure containing the data.". I don't now how to do. > > I don't see anything wrong with your declarations. ?It indicates you > registered the callback successfully. ?Since the callback sounds like it > monitors changes in "link state" maybe it isn't changing. ?Perhaps you need > to call another function that causes this change. > > Here's a DLL I wrote to test your code, but I added a ChangeLinkState > function. ?When I call it after running your code the callback gets called, > so your code is working properly. > > (Compiled with Visual Studio 2008 "cl /MD /LD demo.c" > > typedef unsigned char BYTE; > > typedef struct tagLINKSTATE { > ?BYTE OldState, NewState; > > } LINKSTATE; > > typedef int (*CB)(LINKSTATE*); > > CB g_cb; > BYTE g_linkState; > > __declspec(dllexport) int __stdcall Callback(int a,CB cb) > { > ?g_cb = cb; > ?return 1; > > } > > __declspec(dllexport) void __stdcall ChangeLinkState(BYTE newState) > { > ?LINKSTATE state; > ?state.OldState = g_linkState; > ?state.NewState = newState; > ?g_linkState = newState; > ?g_cb(&state); > > } > > -Mark Thanks Mark for good news. >> Perhaps you need to call another function that causes this change. Exactly, i check again documentation and i must call another functions. Thanks for help. Best regards, Gregory From ldo at geek-central.gen.new_zealand Sun Aug 1 02:50:46 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 01 Aug 2010 18:50:46 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , Mark Lawrence wrote: > Personally I find double clicking on an msi file rather easier. Easier than apt-get dist-upgrade? From breamoreboy at yahoo.co.uk Sun Aug 1 03:03:13 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Aug 2010 08:03:13 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: > In message, Mark > Lawrence wrote: > >> Personally I find double clicking on an msi file rather easier. > > Easier than apt-get dist-upgrade? I'm sorry but I only do English, could you please translate. :) Mark Lawrence. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 1 03:16:21 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Aug 2010 07:16:21 GMT Subject: Docstrings and PEP 3174 References: Message-ID: <4c551f45$0$11091$c3e8da3@news.astraweb.com> On Sat, 31 Jul 2010 19:52:05 -0700, Carl Banks wrote: > PEP 3174 got me to thinking. > > There is now a subdirectory to deposit as many *.pyc files as you want > without cluttering the source directory (never mind the default case). > Which means you can pretty much write files with impunity. > > So I was wondering: what about a separate file just for docstrings. I'm not sure I understand what you mean by that? Do you mean that, when writing code for a function, you would open a second file for the docstring? If so, a big -INFINITY from me. The biggest advantage of docstrings is that the documentation is *right there* with the function when reading/writing code. If you're suggesting we should write them in another file, no thank you. If you mean a runtime optimization with no change to the source file, then maybe, tell me more. What I *think* you mean is that the coder would write: def spam(*args): "docs go here" pass as normal, but when it is compiled and loaded into memory, the docstring itself was *not* loaded until needed. If so, then I think you'd need to demonstrate significant practical benefit to make up for the complexity. I imagine Python-Dev will be very dubious. > __doc__ would become a descriptor that loads the docstring from the file > whenever it is referenced. "The file" being the source file, or a separate docstring file, or a temporary file generated by the compiler, or... ? > The vast majority of the time docstrings > just take up memory and do nothing, so why not lazy load those things? A guarded and provisional +0 on that. +1 if you can demonstrate real performance (memory or speed) gains. -- Steven From ldo at geek-central.gen.new_zealand Sun Aug 1 03:18:19 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 01 Aug 2010 19:18:19 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , Mark Lawrence wrote: > On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: > >> In message, Mark >> Lawrence wrote: >> >>> Personally I find double clicking on an msi file rather easier. >> >> Easier than apt-get dist-upgrade? > > I'm sorry but I only do English, could you please translate. :) I run Debian Unstable, which has new goodies coming out on a weekly basis. The last time I checked for updates, there were over 500 packages I had installed for which updates were available. It only took a command like the above to upgrade them all. How many .msi files would you have to click on to achieve the Windows equivalent? From steve at REMOVE-THIS-cybersource.com.au Sun Aug 1 03:38:44 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Aug 2010 07:38:44 GMT Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <8bfd5uF9gqU1@mid.individual.net> <4c52bc2d$0$11091$c3e8da3@news.astraweb.com> <8bhfcaF6ftU1@mid.individual.net> <4c53936d$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4c552483$0$11091$c3e8da3@news.astraweb.com> On Sat, 31 Jul 2010 13:29:25 +0000, Brian Victor wrote: > Steven D'Aprano wrote: >> On Sat, 31 Jul 2010 14:25:39 +1200, Gregory Ewing wrote: >> >>> Steven D'Aprano wrote: >>> >>>> A >>>> / \ >>>> C B >>>> \ / >>>> D >>>> / \ >>>> E F >>>> >>>> Yes, a super call might jog left from C to B, but only when being >>>> called from one of the lower classes D-F. That's still an upwards >>>> call relative to the originator, not sidewards. >>> >>> But it's not an upward call relative to the class mentioned in the >>> super() call, which is why I say it's misleading. >> >> Which class would that be? >> >> I think I'm going to need an example that demonstrates what you mean, >> because I can't make heads or tails of it. Are you suggesting that a >> call to super(C, self).method() from within C might call >> B.method(self)? > > Yes, it would. [snip example] Right, now I see what you mean. I don't have a problem with that behaviour, it is the correct behaviour, and you are making the call from D in the first place, so it *must* call B at some point. If you initiate the call from C instead: >>> C().test_mro() In C In A then B is not in C's MRO, and does not get called. This is the case I was referring to. I admit it did surprise me the first time I saw the example you gave. Hell, it *confused* me at first, until I realised that self inside the method isn't necessarily an instance of C, but could be an instance of a subclass of C (in this case, D), and then it was "Well duh, how obvious!" That's no different from a classic-style call to a superclass: # inside class C(B): B.method(self, *args) Inside B, method() gets called with an instance of C as self. Bringing it back to super(), since super(C, self) gets a D instance as argument, the MRO it looks at is D's MRO, and it all just works. I think the docs could make that a little more clear, but then, given how non- cooperative inheritance works exactly the same way, there's a good argument for saying the docs don't need to be changed at all. If the behaviour is confusing for super(), then it's confusing without super() too. See Guido's tutorial on cooperative multitasking for more detail: http://www.python.org/download/releases/2.2.3/descrintro/#cooperation > Since the idea of super() as I understand it is to make sure every class > in an object's hierarchy gets its method called, there's really no way > to implement super() in a way that didn't involve a non-superclass being > called by some class's super() call. You're reading the super() signature wrong. super(C, self) shouldn't be interpreted as "call C's superclasses from self". It means "starting just after C in the MRO, call self.__class__'s superclasses". super() never calls a non-superclass. If it did, it would be a huge bug, and inheritance would break. -- Steven From breamoreboy at yahoo.co.uk Sun Aug 1 03:52:17 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Aug 2010 08:52:17 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: > In message, Mark > Lawrence wrote: > >> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >> >>> In message, Mark >>> Lawrence wrote: >>> >>>> Personally I find double clicking on an msi file rather easier. >>> >>> Easier than apt-get dist-upgrade? >> >> I'm sorry but I only do English, could you please translate. :) > > I run Debian Unstable, which has new goodies coming out on a weekly basis. > The last time I checked for updates, there were over 500 packages I had > installed for which updates were available. It only took a command like the > above to upgrade them all. > > How many .msi files would you have to click on to achieve the Windows > equivalent? No idea, but your mental capacity is clearly infinitely higher than mine, as I simply couldn't cope with over 500 installed packages. What do they all do, make your lunch and fetch the beer from the fridge amongst other things? Cheers. Mark Lawrence. From greg.ewing at canterbury.ac.nz Sun Aug 1 04:21:08 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 01 Aug 2010 20:21:08 +1200 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <4c552483$0$11091$c3e8da3@news.astraweb.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <8bfd5uF9gqU1@mid.individual.net> <4c52bc2d$0$11091$c3e8da3@news.astraweb.com> <8bhfcaF6ftU1@mid.individual.net> <4c53936d$0$11091$c3e8da3@news.astraweb.com> <4c552483$0$11091$c3e8da3@news.astraweb.com> Message-ID: <8bkoitFpihU1@mid.individual.net> Steven D'Aprano wrote: > super(C, self) > > shouldn't be interpreted as "call C's superclasses from self". It means > "starting just after C in the MRO, call self.__class__'s superclasses". My contention is that nobody has any chance of guessing what it does based on the name "super". Superness doesn't come into it at all, except in the trivial sense that whatever class it picks will be in the mro of the second argument, which doesn't narrow it down much. So the word "super" here is little better than meaningless noise. If it were something like next_method(C, self) then one could claim with some justification that it stands for "call the next method found after C in the mro of self". -- Greg From greg.ewing at canterbury.ac.nz Sun Aug 1 04:26:21 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 01 Aug 2010 20:26:21 +1200 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: <8bkosiFpihU2@mid.individual.net> Lawrence D'Oliveiro wrote: > How many .msi files would you have to click on to achieve the Windows > equivalent? Don't you just leave the machine on overnight and wait for Microsoft to download all the stuff they think you should be using? -- Greg From greg.ewing at canterbury.ac.nz Sun Aug 1 04:30:22 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 01 Aug 2010 20:30:22 +1200 Subject: Docstrings and PEP 3174 In-Reply-To: <4c551f45$0$11091$c3e8da3@news.astraweb.com> References: <4c551f45$0$11091$c3e8da3@news.astraweb.com> Message-ID: <8bkp46FsbmU1@mid.individual.net> Steven D'Aprano wrote: > If you mean a runtime optimization with no change to the source file, > then maybe, tell me more. Note that you don't necessarily need a separate file for this. It could just be a separate part of the same file. -- Greg From georg at python.org Sun Aug 1 05:38:35 2010 From: georg at python.org (Georg Brandl) Date: Sun, 01 Aug 2010 11:38:35 +0200 Subject: [RELEASED] Python 3.2 alpha 1 Message-ID: <4C55409B.5000409@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the first alpha preview release of Python 3.2. Python 3.2 is a continuation of the efforts to improve and stabilize the Python 3.x line. Since the final release of Python 2.7, the 2.x line will only receive bugfixes, and new features are developed for 3.x only. Since PEP 3003, the Moratorium on Language Changes, is in effect, there are no changes in Python's syntax and built-in types in Python 3.2. Development efforts concentrated on the standard library and support for porting code to Python 3. Highlights are: * numerous improvements to the unittest module * PEP 3147, support for .pyc repository directories * an overhauled GIL implementation that reduces contention * many consistency and behavior fixes for numeric operations * countless fixes regarding string/unicode issues; among them full support for a bytes environment (filenames, environment variables) * a sysconfig module to access configuration information * a pure-Python implementation of the datetime module * additions to the shutil module, among them archive file support * improvements to pdb, the Python debugger For an extensive list of changes in 3.2, see Misc/NEWS in the Python distribution. To download Python 3.2 visit: http://www.python.org/download/releases/3.2/ 3.2 documentation can be found at: http://docs.python.org/3.2/ Please consider trying Python 3.2 with your code and reporting any bugs you may notice to: http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.2's contributors) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.16 (GNU/Linux) iEYEARECAAYFAkxVQJsACgkQN9GcIYhpnLBxIgCcCiVu/QUkFf0bYM2Vmi8St3mZ 2N4An04q36lr47OA+bslqG/4Zj7ZwVOX =iL8N -----END PGP SIGNATURE----- From ldo at geek-central.gen.new_zealand Sun Aug 1 06:17:02 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 01 Aug 2010 22:17:02 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <8bkosiFpihU2@mid.individual.net> Message-ID: In message <8bkosiFpihU2 at mid.individual.net>, Gregory Ewing wrote: > Don't you just leave the machine on overnight and wait > for Microsoft to download all the stuff they think > you should be using? That?s fine, but it doesn?t handle the non-Microsoft stuff. From news1234 at free.fr Sun Aug 1 06:27:12 2010 From: news1234 at free.fr (News123) Date: Sun, 01 Aug 2010 12:27:12 +0200 Subject: pylint scores In-Reply-To: References: <4C532577.8010906@free.fr> Message-ID: <4c554c01$0$6122$426a34cc@news.free.fr> Hi, On 07/31/2010 11:04 AM, Matteo Landi wrote: > What are the messages one should really care about while evaluating > its code using pylint? It's easy to get 5 scored with a "lot of public > methods" or bad named variables such as 'x' or 'y' .. Have you got any > config file to share? The most important ones are of course the errors. Some of them might be false, but in our team we agreed, that no file is allowed to report pylint errors. This means - just fixing errors (in most cases) - rewriting code (in a few cases) - masking errors with pylint directives in the source (some other few errrors) If you only want to see the errros, then just run pylint -E filename.py Note: This is a rather new but very useful switch.. It doesn't exist on Ubuntu 10.4's release pylint 0.19.0, but exists on pylint 0.21.1 Apart from that. You should discuss within your team, which errors you'd like to have ignored and adapt the pylintrc. This is a rather personal decision. For one project we disiabled for example following warnings: ## C0322 = "Operator not preceded by a space" ## C0323 = "Operator not followed by a space" ## C0324 = "Comma not followed by a space" As we did not have time to rewrite all of the existing code, that violated these rules. We prefered to 'hide' these warnings in order to sett the more important ones. On another new project however we did NOT comment therese rules and decided, that all new code should follow these rules We disabled some special global variables, which we'd like to have in lower case const-rgx ==((specialvar)|(v_[a-z_][a-z0-9_]*)|([A-Z_][A-Z0-9_]*)|(__.*__))$ you could also modify variables like # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 For some graphics module functions for example we wanted to be allowed to use variable names like x,y as they are completely meaningful names for pixel coordinates. so change the entry good-names good-names=x,y,ex,Run,_ Hope, that this gave you some ideas > > On Sat, Jul 31, 2010 at 2:48 AM, Dan Stromberg wrote: >> >> On Fri, Jul 30, 2010 at 12:18 PM, News123 wrote: >>> >>> On 07/30/2010 03:12 PM, wheres pythonmonks wrote: >>>> I am starting to use pylint to look at my code and I see that it gives a >>>> rating. >>>> What values do experienced python programmers get on code not >>>> targeting the benchmark? >>>> >>>> I wrote some code, tried to keep it under 80 characters per line, >>>> reasonable variable names, and I got: >>>> >>>> 0.12 / 10. >>>> >>>> Is this a good score for one not targeting the benchmark? (pylint >>>> running in default mode) >>>> >>> It's not a goodf core, but arrives easily if you never ran pylint before. >>> With very little effort you should be able to be above 5 >>> with a little more effort above 7 >>> >>> >>>> Somewhat related: Is the backslash the only way to extend arguments >>>> to statements over multiple lines? (e.g.) >>> >>> if you have an opening parenthesis, or bracked, then you don't need a >>> backslash >>> >>> so instead of >>> if longlonglonglonglonglonglonglongvar == \ >>> otherlonglonglonglongvar: >>> >>> you could also write: >>> >>> if (longlonglonglonglonglonglonglongvar == >>> otherlonglonglonglongvar): >>> >>> >>> same works of course with asserts. >>> >>>> >>>>>>> def f(x,y,z): return(x+y+z); >>>> ... >>>>>>> f(1,2, >>>> ... 3) >>>> 6 >>>>>>> assert f(1,2,3)>0, >>>> File "", line 1 >>>> assert f(1,2,3)>0, >>>> ^ >>>> SyntaxError: invalid syntax >>>>>>> >>>> >>>> In the above, I could split the arguments to f (I guess b/c of the >>>> parens) but not for assert. I could use a backslash, but I find this >>>> ugly -- it that my only (best?) option? >>>> >>>> [I really like to assert my code to correctness and I like using the >>>> second argument to assert, but this resulted in a lot of long lines >>>> that I was unable to break except with an ugly backslash.] >>>> >>>> W >>> >> IMO, the important thing about pylint's scoring is that it's but one way of >> many of producing good Python code. However, it's also one of the easier >> ways of producing good python code. >> I personally like to get my scores up near 10, by annotating in comments >> about the few things that pylint flags that I can't just code around. This >> requires jumping through some slightly silly hoops (EG the previously >> mentioned "too few public methods", which my various container classes >> always trip over), but going through this process is worthwhile for >> highlighting the hoops pylint can detect that -aren't- so silly. >> The one thing I like to leave unfixed is FIXME's - otherwise my preference >> would be to go for a score of 10 for production code. >> I also like to create a ./this-pylint script for my various projects, that >> have global overrides - things like identifier rules, line length, and... I >> don't get blanks instead of tabs. Blanks are fine if you don't understand >> tabs (or think someone in the future who doesn't understand tabs will need >> to work on your code), but tabs allow everyone to see code indented the way >> -they- want to see it, not just the way the original author wanted to see >> it. >> This script (./this-pylint) will also save output from the test in a text >> file, for make (or other dependency handling program) to use to avoid >> re-pylint'ing unmodified code. It'll give an error typically, if pytlint >> detects any errors other than FIXME's (excluding ones, as I mentioned >> before, that have a comment disabling the warning, of course). >> I'm more than a little sad that pylint doesn't seem to be moving to python 3 >> in any big hurry. >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > From usernet at ilthio.net Sun Aug 1 06:27:46 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 1 Aug 2010 10:27:46 +0000 (UTC) Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 2010-08-01, Mark Lawrence wrote: > On 01/08/2010 06:17, Tim Harig wrote: >> On 2010-08-01, Lawrence D'Oliveiro wrote: >>> In message, Tim Harig wrote: >>> >>>> It would be rewarding as it would make writing cross-platform charactor >>>> mode applications possible. >>> >>> I thought Windows users were allergic to command lines. >> >> To the best of my knowledge, there have never been any documentated >> cases of computer software related alleries. There are however several >> chemicals used in the process of constructing computer hardware componets >> which have been linked to allergy illnesses. Maybe Windows users are >> simply allergic to their computers. > > Windows users biggest allergy is to this strange world that involves > "make" on other boxes, whatever that is, it strikes me as rather > archaic. Personally I find double clicking on an msi file rather easier. I work with several thousand computers located on three different continents. Few of them have mice attached to them. If you think double clicking is a better method, be my guest; but, you need to get a package installed and configured on all of them before lunch. Its also kind of funny that I couldn't get the msi to work with a large percentage of the systems that I work with. Make works on all but one out of the box, and potentially on the last with the addition of SFU or Cygwin. With all that said, I am still not sure what the make/msi question has anything to do with packing a backup, cross platform, implementation of curses that allows the curses module to give Python a cross platform method of character mode manipulation. From thomas at jollans.com Sun Aug 1 06:32:19 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 01 Aug 2010 12:32:19 +0200 Subject: Normalizing A Vector In-Reply-To: References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <87sk2zhpcj.fsf@dpt-info.u-strasbg.fr> Message-ID: <4C554D33.6010903@jollans.com> On 08/01/2010 03:41 AM, Lawrence D'Oliveiro wrote: > In message <87sk2zhpcj.fsf at dpt-info.u-strasbg.fr>, Alain Ketterlin wrote: > >> Lawrence D'Oliveiro writes: >> >>> V = tuple \ >>> ( >>> x >>> / >>> l >>> for x in V >>> for l in >>> (math.sqrt(reduce(lambda a, b : a + b, (y * y for y in V), >>> 0)),) >>> ) >> >> You got the order wrong (it has to be for l ... for x ...) > > No, I deliberately put it in that order to ensure that the value for l can > only ever be evaulated once. > >> You're kind of lucky here, because the arglist to tuple() provides a >> scope that hides x and l. Be careful if you ever change tuple(...) to >> [...], because x and l would leak to the outer scope (with python 2.*). > > Interesting. However, using ?list( ... )? instead of ?[ ... ]? also prevents > the leakage. Yes. That's because the variable leakage of list comprehensions was never a good idea, and is kept in Python 2.x only for backwards compatibility. When generator expressions where introduced, it was done in such a way that the scope didn't leak (which probably wouldn't make any sense anyway since there's no guarantee a generator expression is executed at all before the next line) In Python 3, list comprehensions don't leak names any more - they act (nearly?) the same as like( ... expr ... ) now. From guandalino at gmail.com Sun Aug 1 07:01:15 2010 From: guandalino at gmail.com (guandalino) Date: Sun, 1 Aug 2010 04:01:15 -0700 (PDT) Subject: urllib2 test fails (2.7, linux) References: Message-ID: <02af1e8a-cd47-47ca-827e-52a531b36f22@l32g2000prn.googlegroups.com> On 22 Lug, 01:13, Terry Reedy wrote: > If you do not get an answer here, file a bug report. If you can, put > orsenthil,benjamin.peterson,ezio.melotti > on the nosy list, as they are recent committers to this file. Say I said > to do so if you want. Add tjreedy also so I can see responses and learn too. Done here: http://bugs.python.org/issue9446. Best regards, HAND. From news1234 at free.fr Sun Aug 1 07:08:53 2010 From: news1234 at free.fr (News123) Date: Sun, 01 Aug 2010 13:08:53 +0200 Subject: let optionparse.Optionparser ignore unknown command line switches. Message-ID: <4c5555c5$0$19337$426a74cc@news.free.fr> I wondered, whether there's a simple/standard way to let the Optionparser just ignore unknown command line switches. thanks in advance for any ideas From ldo at geek-central.gen.new_zealand Sun Aug 1 07:10:09 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 01 Aug 2010 23:10:09 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , Mark Lawrence wrote: > On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: > >> In message, Mark >> Lawrence wrote: >> >>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >>> >>>> In message, Mark >>>> Lawrence wrote: >>>> >>>>> Personally I find double clicking on an msi file rather easier. >>>> >>>> Easier than apt-get dist-upgrade? >>> >>> I'm sorry but I only do English, could you please translate. :) >> >> I run Debian Unstable, which has new goodies coming out on a weekly >> basis. The last time I checked for updates, there were over 500 packages >> I had installed for which updates were available. It only took a command >> like the above to upgrade them all. >> >> How many .msi files would you have to click on to achieve the Windows >> equivalent? > > ... I simply couldn't cope with over 500 installed packages. Precisely my point. Go back to playing with your .msi toys. Oh, and . From news1234 at free.fr Sun Aug 1 07:27:00 2010 From: news1234 at free.fr (News123) Date: Sun, 01 Aug 2010 13:27:00 +0200 Subject: let optionparse.Optionparser ignore unknown command line switches. In-Reply-To: <4c5555c5$0$19337$426a74cc@news.free.fr> References: <4c5555c5$0$19337$426a74cc@news.free.fr> Message-ID: <4c555a04$0$18011$426a74cc@news.free.fr> On 08/01/2010 01:08 PM, News123 wrote: > I wondered, whether there's a simple/standard way to let > the Optionparser just ignore unknown command line switches. > In order to illustrate, what I try to achieve: import optparse parser = optparse.OptionParser() parser.add_option("-t","--test",dest="test",action="store_true") argv=["tst.py","-t","--ignoreme_and_dont_fail"] try: (options,args)=parser.parse_args(argv) except: # due to --ignoreme_and_dont_fail # I will end up here and neither options nor # args will be populated print "parser error:" # However I would love to be able to see here # that options.test is true despite the # error, that occurred afterwards print "T",options.test From mohseni.aref at gmail.com Sun Aug 1 08:05:39 2010 From: mohseni.aref at gmail.com (Mohseniaref) Date: Sun, 1 Aug 2010 05:05:39 -0700 (PDT) Subject: how can I solve this erorr usr/lib/python2.6 : permisson denied Message-ID: <43e2d3fb-a0f9-468c-bd64-4516eed7dec5@u38g2000prh.googlegroups.com> Dear Friend I have this erorr after running pyhon script with header /usr/lib/python2.6 : permisson denied I change ownership with -hR in super user terminal From chare at labr.net Sun Aug 1 08:22:14 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 07:22:14 -0500 Subject: class doesn't open its window - newbie question Message-ID: I am a newbie to python, but not programming. I have a menubar item displaySubMenu.add_command(label="External", command=externalDisplay) externalDisplay is a new class, which I have already imported. The class is here: from Tkinter import * from datetime import datetime, date, time import urllib from PIL import Image #import Image # PIL required import ImageTk backColor = "Gray" highcolor = "Green" entryColor = "Cyan" okColor = "Green" warnColor = "Red" class externalDisplay(Frame): def __init__(self,callSign,nexrad): """Initialize yourself""" self.callSign = callSign self.nexrad = nexrad #"""Initialise the base class""" Frame.__init__(self) "Set the Window Title""" #self.title( "Test") self.findu = "http://www.findu.com/cgi-bin/radar-find.cgi?call=" + self.callSign + "&radar=" + self.nexrad """Display the main window" with a little bit of padding""" self.grid(padx=5,pady=5) self.CreateWidgets() def CreateWidgets(self): #"""Create all the widgets that we need""" self.f = Frame(self, bd=0, bg=backColor) self.title = "netcomm Online Radar" self.f.grid() # # Insert the date and time the radar image was updated # self.lblLastUpdate = Label(self.f, text="Last Updated: " + str(datetime.now()), bg=backColor) self.lblLastUpdate.grid( row=0, column=0, sticky=W) self.btnRefresh = Button(self.f, text="Refresh", command=handlesExternalDisplayByClick, bg=backColor,highlightbackground=okColor,highlightcolor=highcolor) self.btnRefresh.grid(row=0, column=1) self.btnRefresh = Button(self.f, text="Close", command=self.destroy, bg=backColor,highlightbackground=warnColor,highlightcolor=highcolor) self.btnRefresh.grid(row=0, column=2) # # Start the download from findu # # # This gets the image and saves it to the local disk as "image.png" # # NOTE - will ideally want to conver this to GIF and save it using # the date as part of the filename so the net can be re-created # for reporting and to create a flipbook of the radar images # urllib.urlretrieve(self.findu, "image.png") Image.open("image.png").save("image.gif") self.photo = PhotoImage(file="image.gif") # # create a canvas of the appropriate size for the image # self.w = Canvas(self.f, width=600, height=550) # # convert it into a photo item we can use in the display # self.netRadarImage = Label(self.w, image=self.photo) self.netRadarImage.image = self.photo self.w.grid(row=1, column=0, columnspan=3) self.netRadarImage.grid( row=1, column=0) def handlesExternalDisplayByClick(self): # # destroy the existing frame the radar is in # self.destroy() # # rebuild the radarWidgets # createRadarWidgets(frameRadar) def handlesRadarRefreshByClick(self): # # destroy the existing frame the radar is in # self.destroy() # # rebuild the radarWidgets # self.update() if __name__ == "__main__": guiFrame = externalDisplay("AE5PL-10","fws") guiFrame.mainloop() The problem is that the window defined in the class never appears, and I don't know why. I would like to get all of the code for the window into a single file which I import, but since I can't make this work right, I don't want to invest the time yet. Eve worse, is that when I run the code as a standalone module and click on the close button, I am left with a tk window instead of the app actually closing. Any suggestions are appreciated. From chare at labr.net Sun Aug 1 08:35:00 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 07:35:00 -0500 Subject: image resize doesn't work Message-ID: <2B79B253-B538-44DB-9796-77C2EFA6D3CC@labr.net> I have the following chunk of code. Although it seems to execute fine, no errors, the image is never resized. What am I missing? imagePNG = Image.open("image.png") photo = ImageTk.PhotoImage(imagePNG canvasWidth = 300 canvasHeight = 275 photo = ImagePNG.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) netRadarImage = Label(w, image=photo) From roy at panix.com Sun Aug 1 08:41:26 2010 From: roy at panix.com (Roy Smith) Date: Sun, 01 Aug 2010 08:41:26 -0400 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <8bkosiFpihU2@mid.individual.net> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message <8bkosiFpihU2 at mid.individual.net>, Gregory Ewing wrote: > > > Don't you just leave the machine on overnight and wait > > for Microsoft to download all the stuff they think > > you should be using? > > That???s fine, but it doesn???t handle the non-Microsoft stuff. You've apparently never worked in a big company. Your IT department downloads whatever *they* think you should be using. Eventually, your machine is so slow, you can't get any work done. From python at bdurham.com Sun Aug 1 09:12:46 2010 From: python at bdurham.com (python at bdurham.com) Date: Sun, 01 Aug 2010 09:12:46 -0400 Subject: Parse a string into argv-like list like OS does Message-ID: <1280668366.4854.1387755323@webmail.messagingengine.com> Before I reinvent the wheel, is there a module that provides a command-line like parser that I can use? By command-line like parser, I mean that I would like to pass a string to this function and get back a list in the same manner as the OS receives a command line string which it parses into discrete items (handling quoted strings, backslashes, etc) I have a bunch of command lines (as strings) and I would like to parse them into argv-like lists for analysis and documentation. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Sun Aug 1 09:28:01 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 01 Aug 2010 08:28:01 -0500 Subject: Parse a string into argv-like list like OS does In-Reply-To: <1280668366.4854.1387755323@webmail.messagingengine.com> References: <1280668366.4854.1387755323@webmail.messagingengine.com> Message-ID: <4C557661.6040907@tim.thechases.com> On 08/01/10 08:12, python at bdurham.com wrote: > Before I reinvent the wheel, is there a module that provides a > command-line like parser that I can use? By command-line like > parser, I mean that I would like to pass a string to this > function and get back a list in the same manner as the OS > receives a command line string which it parses into discrete > items (handling quoted strings, backslashes, etc) Sounds like the shlex module... http://docs.python.org/library/shlex.html -tkc From andrea.crotti.0 at gmail.com Sun Aug 1 09:28:23 2010 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Sun, 01 Aug 2010 15:28:23 +0200 Subject: how can I solve this erorr usr/lib/python2.6 : permisson denied References: <43e2d3fb-a0f9-468c-bd64-4516eed7dec5@u38g2000prh.googlegroups.com> Message-ID: Mohseniaref writes: > Dear Friend > I have this erorr after running pyhon script with header > /usr/lib/python2.6 : permisson denied > I change ownership with -hR in super user terminal Why /usr/lib... and not in bin? I guess this is the directory, of course if you put it in the header (shabang) it won't work. I use normally #!/usr/bin/env python From python at bdurham.com Sun Aug 1 09:42:47 2010 From: python at bdurham.com (python at bdurham.com) Date: Sun, 01 Aug 2010 09:42:47 -0400 Subject: Parse a string into argv-like list like OS does In-Reply-To: <4C557661.6040907@tim.thechases.com> References: <1280668366.4854.1387755323@webmail.messagingengine.com> <4C557661.6040907@tim.thechases.com> Message-ID: <1280670167.8260.1387757965@webmail.messagingengine.com> Tim, > Sounds like the shlex module... > http://docs.python.org/library/shlex.html Cheers for the link - that's *exactly* what I was searching for. For the archives: Here's an excellent tutorial on this module. http://www.oreillynet.com/onlamp/blog/2007/10/pymotw_shlex.html Malcolm From alain at dpt-info.u-strasbg.fr Sun Aug 1 09:59:38 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 01 Aug 2010 15:59:38 +0200 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <87sk2zhpcj.fsf@dpt-info.u-strasbg.fr> Message-ID: <87k4oah1rp.fsf@dpt-info.u-strasbg.fr> Lawrence D'Oliveiro writes: >>> V = tuple \ >>> ( >>> x >>> / >>> l >>> for x in V >>> for l in >>> (math.sqrt(reduce(lambda a, b : a + b, (y * y for y in V), >>> 0)),) >>> ) >> >> You got the order wrong (it has to be for l ... for x ...) > > No, I deliberately put it in that order to ensure that the value for l can > only ever be evaulated once. Try this (essentially equivalent to your code): def f(): print "hello" return 1 V = tuple( 1 for x in [1,2,3] for l in (f(),) ) How many "hello"s do you see? Comprehension are not loops spelled backwards. The values in: whatever for i ... for j ... are the values produced by the equivalent code: for i ... for j ... whatever -- Alain. From rantingrick at gmail.com Sun Aug 1 11:24:24 2010 From: rantingrick at gmail.com (rantingrick) Date: Sun, 1 Aug 2010 08:24:24 -0700 (PDT) Subject: image resize doesn't work References: Message-ID: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> On Aug 1, 7:35?am, Chris Hare wrote: > I have the following chunk of code. ?Although it seems to execute fine, no errors Not True! it contains syntax errors. Check the posted code and next time post all the code. From steveo at syslang.net Sun Aug 1 11:34:29 2010 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 01 Aug 2010 11:34:29 -0400 Subject: let optionparse.Optionparser ignore unknown command line switches. In-Reply-To: <4c555a04$0$18011$426a74cc@news.free.fr> References: <4c5555c5$0$19337$426a74cc@news.free.fr> <4c555a04$0$18011$426a74cc@news.free.fr> Message-ID: <4C559405.6030501@syslang.net> On 08/01/10 07:27, quoth News123: > On 08/01/2010 01:08 PM, News123 wrote: >> I wondered, whether there's a simple/standard way to let >> the Optionparser just ignore unknown command line switches. >> > > In order to illustrate, what I try to achieve: > > > import optparse > parser = optparse.OptionParser() > parser.add_option("-t","--test",dest="test",action="store_true") > argv=["tst.py","-t","--ignoreme_and_dont_fail"] > try: > (options,args)=parser.parse_args(argv) > except: > # due to --ignoreme_and_dont_fail > # I will end up here and neither options nor > # args will be populated > print "parser error:" > # However I would love to be able to see here > # that options.test is true despite the > # error, that occurred afterwards > print "T",options.test > You need to let us know *why* you want to do this. My psychotic imagination is contriving that you want to pass on the ignoremeanddontfail options to something else. If so, then you should be using -- instead of this. The other possible scheme to solve your unknown problem is to subclass OptionParser so it does what you want. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From chare at labr.net Sun Aug 1 11:36:07 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 10:36:07 -0500 Subject: image resize doesn't work In-Reply-To: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: On Aug 1, 2010, at 10:24 AM, rantingrick wrote: > On Aug 1, 7:35 am, Chris Hare wrote: >> I have the following chunk of code. Although it seems to execute fine, no errors > > Not True! it contains syntax errors. Check the posted code and next > time post all the code. > -- > http://mail.python.org/mailman/listinfo/python-list Hmmm... ok here is the code. I get no errors on my console when it execute urllib.urlretrieve(findu, "image.png") logging.debug("createRadarWidgets(): radar download complete") logging.debug("createRadarWidgets(): user has radarPanelSize of " + root.radarPanelSize.get()) # # open the image file # if os.path.exists("image.gif"): ctime = os.stat(dbPath)[ST_CTIME] print ctime filetime = datetime.fromtimestamp(ctime) filetime = filetime.strftime("%Y%m%d%H%M%S") print str(filetime) #filetime = datetime(ctime).isoformat() #print ctime imagePNG = Image.open("image.png") #photo = ImageTk.PhotoImage(imagePNG) Image.open("image.png").save("image.gif") image = Image.open("image.gif") photo = PhotoImage(file="image.gif") #photoimg = ImageTk.PhotoImage(photo) # # NOTE: - will want to track the size of the image displayed based upon # the actual screen resolution # Full/External = 600x550 - full file size # Large = 450x412 # Medium = 300x275 # Small = 150x137 # if root.radarPanelSize.get() == "Large": canvasWidth = 450 canvasHeight = 412 elif root.radarPanelSize.get() == "Medium": canvasWidth = 300 canvasHeight = 275 elif root.radarPanelSize.get() == "Small": canvasWidth = 150 canvasHeight = 137 logging.debug("createRadarWidgets(): creating image size " + str(canvasWidth) + "x" + str(canvasHeight)) # # create a canvas of the appropriate size for the image # w = Canvas(f, width=canvasWidth, height=canvasHeight) if root.radarPanelSize.get() == "Off": logging.debug("createRadarWidgets(): no net, no radar") netRadarImage = Label(w, text="No current radar") else: # # convert it into a photo item we can use in the display # # photo = photo.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) netRadarImage = Label(w, image=photo) netRadarImage.image = photo w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) From news1234 at free.fr Sun Aug 1 11:43:36 2010 From: news1234 at free.fr (News123) Date: Sun, 01 Aug 2010 17:43:36 +0200 Subject: let optionparse.Optionparser ignore unknown command line switches. In-Reply-To: References: <4c5555c5$0$19337$426a74cc@news.free.fr> <4c555a04$0$18011$426a74cc@news.free.fr> Message-ID: <4c559628$0$28678$426a74cc@news.free.fr> On 08/01/2010 05:34 PM, Steven W. Orr wrote: > On 08/01/10 07:27, quoth News123: >> On 08/01/2010 01:08 PM, News123 wrote: >>> I wondered, whether there's a simple/standard way to let >>> the Optionparser just ignore unknown command line switches. >>> >> >> In order to illustrate, what I try to achieve: >> >> >> import optparse >> parser = optparse.OptionParser() >> parser.add_option("-t","--test",dest="test",action="store_true") >> argv=["tst.py","-t","--ignoreme_and_dont_fail"] >> try: >> (options,args)=parser.parse_args(argv) >> except: >> # due to --ignoreme_and_dont_fail >> # I will end up here and neither options nor >> # args will be populated >> print "parser error:" >> # However I would love to be able to see here >> # that options.test is true despite the >> # error, that occurred afterwards >> print "T",options.test >> > > You need to let us know *why* you want to do this. My psychotic imagination is > contriving that you want to pass on the ignoremeanddontfail options to > something else. If so, then you should be using -- instead of this. The other > possible scheme to solve your unknown problem is to subclass OptionParser so > it does what you want. Hi Steven, '--' is good for many use cases, but not for the one I'm looking at. in my case one imported module should parse some of the options (but only the one it understands) already during import. the main program will have to parse the same options again. From nikos.the.gr33k at gmail.com Sun Aug 1 12:56:48 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sun, 1 Aug 2010 09:56:48 -0700 (PDT) Subject: Trying to set a cookie within a python script Message-ID: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> Hello fellow Python Coders! I don't see the error in my attempt to set a a cookie in this test script. Can you help please?! Thank you! [code] #!/usr/bin/python # -*- coding: utf-8 -*- import Cookie print ( "Content-type: text/html\n" ) cookie = Cookie.SimpleCookie() if cookie.has_key('visitor') == "nikos" #if visitor cookie exist print ( "??? ?? ????, ??? ?? ????, ??? ?? ??????. ?? ????? ? ???????? ??????????!!" ) cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire now else print ( "??? ?? ??? ??? ???? ??? ?? ?????? ??? ??????? ???? ??? ????????!!" ) cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year [/code] From joncle at googlemail.com Sun Aug 1 13:53:05 2010 From: joncle at googlemail.com (Jon Clements) Date: Sun, 1 Aug 2010 10:53:05 -0700 (PDT) Subject: let optionparse.Optionparser ignore unknown command line switches. References: <4c5555c5$0$19337$426a74cc@news.free.fr> <4c555a04$0$18011$426a74cc@news.free.fr> <4c559628$0$28678$426a74cc@news.free.fr> Message-ID: <8948edfa-2beb-4295-808e-11755f3d9128@p22g2000pre.googlegroups.com> On 1 Aug, 16:43, News123 wrote: > On 08/01/2010 05:34 PM, Steven W. Orr wrote: > > > > > On 08/01/10 07:27, quoth News123: > >> On 08/01/2010 01:08 PM, News123 wrote: > >>> I wondered, whether there's a simple/standard way to let > >>> the Optionparser just ignore unknown command line switches. > > >> In order to ?illustrate, what I try to achieve: > > >> import optparse > >> parser = optparse.OptionParser() > >> parser.add_option("-t","--test",dest="test",action="store_true") > >> argv=["tst.py","-t","--ignoreme_and_dont_fail"] > >> try: > >> ? ? (options,args)=parser.parse_args(argv) > >> except: > >> ? ? # due to --ignoreme_and_dont_fail > >> ? ? # I will end up here and neither options nor > >> ? ? # args will be populated > >> ? ? print "parser error:" > >> # However I would love to be able to see here > >> # that options.test is true despite the > >> # error, that occurred afterwards > >> print "T",options.test > > > You need to let us know *why* you want to do this. My psychotic imagination is > > contriving that you want to pass on the ignoremeanddontfail options to > > something else. If so, then you should be using -- instead of this. The other > > possible scheme to solve your unknown problem is to subclass OptionParser so > > it does what you want. > > Hi Steven, > > '--' is good for many use cases, but not for the one I'm looking at. > > in my case one imported module should parse some of the options (but > only the one it understands) already during import. > the main program will have to parse the same options again. Take it up a level. Dedicate a module (called app_configuration) or something to do the option parsing -- everything the application can support is listed there... It's a bad idea to ignore invalid options... When that's imported it runs the parsing for sys.argv whatever... and you guarantee a variable called app_settings (or whatever) is present in that module. Any module that needs the settings, just imports app_configuration and tries to take what it understands... Would that work for you? Jon. From __peter__ at web.de Sun Aug 1 14:08:28 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Aug 2010 20:08:28 +0200 Subject: image resize doesn't work References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: Chris Hare wrote: > On Aug 1, 2010, at 10:24 AM, rantingrick wrote: > >> On Aug 1, 7:35 am, Chris Hare wrote: >>> I have the following chunk of code. Although it seems to execute fine, >>> no errors >> >> Not True! it contains syntax errors. Check the posted code and next >> time post all the code. >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Hmmm... ok > here is the code. I get no errors on my console when it execute > > urllib.urlretrieve(findu, "image.png") I get a NameError on the very first line. >>> urllib.urlretrieve(findu, "image.png") Traceback (most recent call last): File "", line 1, in NameError: name 'urllib' is not defined When you want to demonstrate a problem try to make a self-contained example, i. e. one that can be run without the need for us guess the surrounding code. Remove everything that is irrelevant for the problem like the logging in code below and the png/gif conversion gymnastics. Anyway, here is a self-contained demo (you have to pass the filename of an image on the commandline): import Tkinter import ImageTk import Image import sys [filename] = sys.argv[1:] image = Image.open(filename) root = Tkinter.Tk() frame = Tkinter.Frame(root) frame.pack() label = Tkinter.Label(root) label.pack() def make_resize(percent): def resize(): width, height = image.size label.image = label["image"] = ImageTk.PhotoImage( image=image.resize((width*percent//100, height*percent//100))) return resize make_resize(100)() pairs = [ ("Small", 20), ("Medium", 50), ("Original", 100), ("Big", 200)] for i, (text, percent) in enumerate(pairs): button = Tkinter.Button(frame, text=text, command=make_resize(percent)) button.grid(row=0, column=i) root.mainloop() Peter From jjposner at optimum.net Sun Aug 1 14:37:34 2010 From: jjposner at optimum.net (John Posner) Date: Sun, 01 Aug 2010 14:37:34 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C545DF7.6040104@optimum.net> Message-ID: <4C55BEEE.8010503@optimum.net> On 7/31/2010 2:00 PM, Christian Heimes wrote: > > Your answer is confusing even me. ;) Yeah, I get that a lot. :-) > Let me try an easier to understand explanation. defaultdict *implements* > __missing__() to provide the default dict behavior. In my experience, the word *implements* is commonly used in two ways, nearly opposite to each other. Ex: My company just implemented a version-control system. Did your company (1) write the code for the version-control system, or did it (2) put the system in use, by downloading an installer from the Web and executing it? -John From chare at labr.net Sun Aug 1 15:08:44 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 14:08:44 -0500 Subject: image resize doesn't work In-Reply-To: References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: On Aug 1, 2010, at 1:08 PM, Peter Otten wrote: > Chris Hare wrote: > > >> On Aug 1, 2010, at 10:24 AM, rantingrick wrote: >> >>> On Aug 1, 7:35 am, Chris Hare wrote: >>>> I have the following chunk of code. Although it seems to execute fine, >>>> no errors >>> >>> Not True! it contains syntax errors. Check the posted code and next >>> time post all the code. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> Hmmm... ok >> here is the code. I get no errors on my console when it execute >> >> urllib.urlretrieve(findu, "image.png") > > I get a NameError on the very first line. > >>>> urllib.urlretrieve(findu, "image.png") > Traceback (most recent call last): > File "", line 1, in > NameError: name 'urllib' is not defined > > When you want to demonstrate a problem try to make a self-contained example, > i. e. one that can be run without the need for us guess the surrounding > code. Remove everything that is irrelevant for the problem like the logging > in code below and the png/gif conversion gymnastics. > > Anyway, here is a self-contained demo (you have to pass the filename of an > image on the commandline): > > import Tkinter > import ImageTk > import Image > import sys > > [filename] = sys.argv[1:] > > image = Image.open(filename) > > root = Tkinter.Tk() > frame = Tkinter.Frame(root) > frame.pack() > label = Tkinter.Label(root) > label.pack() > > def make_resize(percent): > def resize(): > width, height = image.size > label.image = label["image"] = ImageTk.PhotoImage( > image=image.resize((width*percent//100, height*percent//100))) > return resize > > make_resize(100)() > > pairs = [ > ("Small", 20), > ("Medium", 50), > ("Original", 100), > ("Big", 200)] > > for i, (text, percent) in enumerate(pairs): > button = Tkinter.Button(frame, text=text, command=make_resize(percent)) > button.grid(row=0, column=i) > > root.mainloop() > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list Thanks for the help. My one week of python is getting a workout. I have shortened it all down and made it a standalone example, using yours as a model. Your example, works, but it will take a lot of effort to retrofit it into the code I have. (which is maybe not a bad idea,). Anyway from Tkinter import * import ImageTk import Image import sys def sizeit(filename): image = Image.open(filename) w,h = image.size print w, h photo = ImageTk.PhotoImage(file=filename) canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) w,h = image.size print w, h netRadarImage = Label(frame, image=image) netRadarImage.image = photo w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) [filename] = sys.argv[1:] root = Tk() frame = Frame(root) frame.grid() sizeit(filename) root.mainloop() Just like yours it takes a filename. Unlike yours, mine gets an error that I can't figure out and is likely the root of the problem. When I run this code I get 600 550 <== ORIGINAL image size 450 412 <== resized image size Traceback (most recent call last): File "zztest.py", line 26, in sizeit(filename) File "zztest.py", line 16, in sizeit netRadarImage = Label(frame, image=image) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 2466, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1932, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "" doesn't exist So, my problem appeared to be the resize, but in fact is just getting it onto the label. What am I doing wrong? From cmpython at gmail.com Sun Aug 1 16:34:58 2010 From: cmpython at gmail.com (CM) Date: Sun, 1 Aug 2010 13:34:58 -0700 (PDT) Subject: exception handling with sqlite db errors Message-ID: <2a47b306-45d1-474a-9f8e-5b71eba629c9@p11g2000prf.googlegroups.com> I am using SQLite with Python 2.5 for an app and every now and then get an error when trying to write to the database. So far I haven't been careful about noting these down, but now I would like to address them. The two errors I've noticed are: 1) "database is locked" errors (probably due to write conflicts when using SQLite Database Browser to check and change the data while my app was trying to write to the db; this might be a problem for users if they too want to edit their data that way while running the app, though that scenario is pretty unlikely). 2) Today for the first time,"sqlite3.OperationalError: attempt to write a readonly database"--though I never set this database to be read-only. When I tried it a second time, it worked and didn't give this error. What I would like is a way to innoculate my app from these errors such that if they occur they don't cause any problems with the app. I'm not even sure if they do cause problems, since I can't figure out a way to reproduce the errors and see whether it causes the app to hang or not update the GUI properly, etc. Maybe it's not much of an issue, but I think it would be a shame if occasional hangs/crashes could be caused by these (rare?) database conflicts if there is a good approach for avoiding them. I guess I could put every last write to the db in a try/except block but I thought there should be a more general solution, since that will require many such exceptions and seems inelegant. Any suggestions for addressing this are appreciated. Che From __peter__ at web.de Sun Aug 1 17:32:56 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Aug 2010 23:32:56 +0200 Subject: image resize doesn't work References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: Chris Hare wrote: > Thanks for the help. My one week of python is getting a workout. > > I have shortened it all down and made it a standalone example, using yours > as a model. Your example, works, but it will take a lot of effort to > retrofit it into the code I have. (which is maybe not a bad idea,). You mean retrofit something that works into something tha doesn't? Seriously, you should never be afraid to throw away code, especially while you're still in the early phase of learning the language. > def sizeit(filename): > image = Image.open(filename) Now you have an Image > w,h = image.size > print w, h > photo = ImageTk.PhotoImage(file=filename) and now a photo, both created from the same file but otherwise independent > canvasWidth = 450 > canvasHeight = 412 > image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) Now you have a new resized Image > w,h = image.size > print w, h > netRadarImage = Label(frame, image=image) Label(image=...) expects a PhotoImage > netRadarImage.image = photo > w.grid(row=1, column=0, columnspan=3) Hmm... > netRadarImage.grid( row=1, column=0) Here's the fixed code: def sizeit(filename): image = Image.open(filename) canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS) photo = ImageTk.PhotoImage(image=image) netRadarImage = Label(frame, image=photo) netRadarImage.image = photo netRadarImage.grid(row=0, column=0) In plain English: - open the Image using the PIL - resize it - wrap it into a PhotoImage - wrap the PhotoImage into a Tkinter.Label either by passing it to the initialiser or by assigning to label["image"] - make sure the PhotoImage isn't garbage-collected e. g. by assigning to label.image Peter From chare at labr.net Sun Aug 1 18:11:57 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 17:11:57 -0500 Subject: image resize doesn't work In-Reply-To: References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: <37D9B818-DA6C-40D8-B8C5-185DFC8DAACD@labr.net> Thanks Peter - I know what I said sounded stupid :-) I have been working with Python for a week and as you know sometimes it is easier to learn by seeing what you did wrong as compared to what should have been done with the same example. I loved your code by the way - Thanks for help just another beginner .... On Aug 1, 2010, at 4:32 PM, Peter Otten wrote: > Chris Hare wrote: > >> Thanks for the help. My one week of python is getting a workout. >> >> I have shortened it all down and made it a standalone example, using yours >> as a model. Your example, works, but it will take a lot of effort to >> retrofit it into the code I have. (which is maybe not a bad idea,). > > You mean retrofit something that works into something tha doesn't? > Seriously, you should never be afraid to throw away code, especially while > you're still in the early phase of learning the language. > >> def sizeit(filename): >> image = Image.open(filename) > > Now you have an Image > >> w,h = image.size >> print w, h >> photo = ImageTk.PhotoImage(file=filename) > > and now a photo, both created from the same file but otherwise independent > >> canvasWidth = 450 >> canvasHeight = 412 >> image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) > > Now you have a new resized Image > >> w,h = image.size >> print w, h >> netRadarImage = Label(frame, image=image) > > Label(image=...) expects a PhotoImage > >> netRadarImage.image = photo >> w.grid(row=1, column=0, columnspan=3) > > Hmm... > >> netRadarImage.grid( row=1, column=0) > > Here's the fixed code: > > def sizeit(filename): > image = Image.open(filename) > canvasWidth = 450 > canvasHeight = 412 > image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS) > photo = ImageTk.PhotoImage(image=image) > netRadarImage = Label(frame, image=photo) > netRadarImage.image = photo > netRadarImage.grid(row=0, column=0) > > In plain English: > > - open the Image using the PIL > - resize it > - wrap it into a PhotoImage > - wrap the PhotoImage into a Tkinter.Label either by passing it to the > initialiser or by assigning to label["image"] > - make sure the PhotoImage isn't garbage-collected e. g. by assigning to > label.image > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list From chare at labr.net Sun Aug 1 18:15:26 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 17:15:26 -0500 Subject: beginner python GUI question Message-ID: <17F4F9B7-EB46-4FBB-9FCD-B74B861B105A@labr.net> I hope I can explain this correctly. I have a GUI, which is already being processed by a mainloop. I want to be able to open a second window so the user can interact with specific information in the second window. I pulled together this code example from Tkinter import * class Net: def __init__(self,tkWin): self.window = tkWin def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text="Again") button.bind("", self.Again) button.grid() def Again(self,event): win3 = Tk() x = Net(win3) x.show("window 3") root = Tk() root.title = "test" f = Frame(root,bg="Yellow") l = Label(f,text="window 1") f.grid() l.grid() win2 = Tk() x = Net(win2) x.show("window 2") if __name__ == "__main__": root.mainloop() Is this the right way to do things, or would you suggest something different? Thanks, Chris From chare at labr.net Sun Aug 1 18:33:58 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 17:33:58 -0500 Subject: image resize doesn't work In-Reply-To: References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: And I see now what I did wrong - thanks for putting up with the questions. On Aug 1, 2010, at 4:32 PM, Peter Otten wrote: > Chris Hare wrote: > >> Thanks for the help. My one week of python is getting a workout. >> >> I have shortened it all down and made it a standalone example, using yours >> as a model. Your example, works, but it will take a lot of effort to >> retrofit it into the code I have. (which is maybe not a bad idea,). > > You mean retrofit something that works into something tha doesn't? > Seriously, you should never be afraid to throw away code, especially while > you're still in the early phase of learning the language. > >> def sizeit(filename): >> image = Image.open(filename) > > Now you have an Image > >> w,h = image.size >> print w, h >> photo = ImageTk.PhotoImage(file=filename) > > and now a photo, both created from the same file but otherwise independent > >> canvasWidth = 450 >> canvasHeight = 412 >> image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) > > Now you have a new resized Image > >> w,h = image.size >> print w, h >> netRadarImage = Label(frame, image=image) > > Label(image=...) expects a PhotoImage > >> netRadarImage.image = photo >> w.grid(row=1, column=0, columnspan=3) > > Hmm... > >> netRadarImage.grid( row=1, column=0) > > Here's the fixed code: > > def sizeit(filename): > image = Image.open(filename) > canvasWidth = 450 > canvasHeight = 412 > image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS) > photo = ImageTk.PhotoImage(image=image) > netRadarImage = Label(frame, image=photo) > netRadarImage.image = photo > netRadarImage.grid(row=0, column=0) > > In plain English: > > - open the Image using the PIL > - resize it > - wrap it into a PhotoImage > - wrap the PhotoImage into a Tkinter.Label either by passing it to the > initialiser or by assigning to label["image"] > - make sure the PhotoImage isn't garbage-collected e. g. by assigning to > label.image > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list From candide at free.invalid Sun Aug 1 19:08:50 2010 From: candide at free.invalid (candide) Date: Mon, 02 Aug 2010 01:08:50 +0200 Subject: Why is python not written in C++ ? Message-ID: <4c55fe82$0$9111$426a34cc@news.free.fr> Python is an object oriented langage (OOL). The Python main implementation is written in pure and "old" C90. Is it for historical reasons? C is not an OOL and C++ strongly is. I wonder if it wouldn't be more suitable to implement an OOL with another one. Has it ever been planned to rewrite in C++ the historical implementation (of course in an object oriented design) ? From tjreedy at udel.edu Sun Aug 1 19:26:17 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Aug 2010 19:26:17 -0400 Subject: Docstrings and PEP 3174 In-Reply-To: <8bkp46FsbmU1@mid.individual.net> References: <4c551f45$0$11091$c3e8da3@news.astraweb.com> <8bkp46FsbmU1@mid.individual.net> Message-ID: On 8/1/2010 4:30 AM, Gregory Ewing wrote: > Steven D'Aprano wrote: > >> If you mean a runtime optimization with no change to the source file, >> then maybe, tell me more. > > Note that you don't necessarily need a separate file for this. > It could just be a separate part of the same file. Which is to say, all the docstrings in a modules *could* be placed at the end and not normally read in by the interpreter until needed. I have no idea what it does now, but I suspect not that. It might make module loading a bit faster. -- Terry Jan Reedy From tjreedy at udel.edu Sun Aug 1 19:31:42 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Aug 2010 19:31:42 -0400 Subject: how python works In-Reply-To: <930269.70649.qm@web50002.mail.re2.yahoo.com> References: <953403.23661.qm@web50003.mail.re2.yahoo.com> <930269.70649.qm@web50002.mail.re2.yahoo.com> Message-ID: On 7/30/2010 2:16 PM, Mahmood Naderan wrote: > So is it a compiler or interpreter? Python is a language. It does not 'work' in the sense of your subject line. CPython is a Python compiler/interpreter, as described. When loaded, it may be named python.exe, depending on system and installation. Jython and IronPython are also Python compiler/interpreters. There are also Python compilers of various sorts. -- Terry Jan Reedy From tjreedy at udel.edu Sun Aug 1 19:50:10 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Aug 2010 19:50:10 -0400 Subject: Normalizing A Vector In-Reply-To: References: Message-ID: On 7/30/2010 7:46 AM, Lawrence D'Oliveiro wrote: > Say a vector V is a tuple of 3 numbers, not all zero. You want to normalize > it (scale all components by the same factor) so its magnitude is 1. > > The usual way is something like this: > > L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) > V = (V[0] / L, V[1] / L, V[2] / L) > > What I don?t like is having that intermediate variable L leftover after the > computation. So, instead of fooling around with error-prone, hard-to-type constructions, just delete the damn thing! def L Compare those foolproof 5 chars to what at first did not work right and even what did. And, as other said, in most real applications, you will normalize in more than one place. In fact, you may well want a vlen function. def vlen(seq): return math.sqrt(sum(x*x for x in seq)) -- Terry Jan Reedy From me+list/python at ixokai.io Sun Aug 1 19:52:19 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sun, 01 Aug 2010 16:52:19 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4C5608B3.5030805@ixokai.io> On 8/1/10 4:08 PM, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? Portability if nothing else has been a strong reason to keep the Python implementation to standard C. Its not as bad as it used to be, but there's still quite a few differences between various C++ compilers. Even with the officially supported platforms shrinking of late, and talk of including some C++ in an isolated part of the CPython implementation (the UnladenSwallow JIT is C++, IIRC), rewriting the whole thing in C++ seems like a major waste of time. If you went and used the OO-features of C++, but then you run into a problem: Python's OO design is strikingly different from C++'s. There's no enforced encapsulation (on purpose), just as one example. That's not saying you -couldn't- match Python's OO design on top of C++, after all-- they've done it in Java, which has a hardcore interpretation of OOP. But what does that get you over the current status quo? C's leaner and meaner then C++. > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. Wny would this be more suitable? The Python idea of Object Orientedness doesn't line up with the C++ own *on purpose*, so why adopt one idea and design of OOP to implement a different one? > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? Have you actually looked at the "historical implementation"? It's actually quite object oriented. You don't have to have an object oriented language to use OO design. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From landimatte at gmail.com Sun Aug 1 19:56:14 2010 From: landimatte at gmail.com (Matteo Landi) Date: Mon, 2 Aug 2010 01:56:14 +0200 Subject: Normalizing A Vector In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 1:50 AM, Terry Reedy wrote: > On 7/30/2010 7:46 AM, Lawrence D'Oliveiro wrote: >> >> Say a vector V is a tuple of 3 numbers, not all zero. You want to >> normalize >> it (scale all components by the same factor) so its magnitude is 1. >> >> The usual way is something like this: >> >> ? ? L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) >> ? ? V = (V[0] / L, V[1] / L, V[2] / L) >> >> What I don?t like is having that intermediate variable L leftover after >> the >> computation. > > So, instead of fooling around with error-prone, hard-to-type constructions, > just delete the damn thing! > > def L del L :P > > Compare those foolproof 5 chars to what at first did not work right and even > what did. ?And, as other said, in most real applications, you will normalize > in more than one place. In fact, you may well want a vlen function. > > def vlen(seq): return math.sqrt(sum(x*x for x in seq)) > > -- > Terry Jan Reedy > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From tjreedy at udel.edu Sun Aug 1 20:01:59 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Aug 2010 20:01:59 -0400 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 8/1/2010 7:08 PM, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? Python was first released before C++. C is available on, and hence Python runs on, systems that do not have C++ available. > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. Python's object system is sufficiently different from that of C++ that I doubt the latter could used with much profit. > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? Proposed and rejected. Not every C programmer knows or wants to learn C++. -- Terry Jan Reedy From chare at labr.net Sun Aug 1 20:12:13 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 19:12:13 -0500 Subject: how best to clear objects from a frame Message-ID: <47F2D553-FDD9-45AA-BFB8-BEEBE6900253@labr.net> Here is the situation: I have a window with a bunch of widgets in it. I want to clear the objects in a given frame and recreate them to update them. The example below destroys the top level frame, and so I can't recreate the widgets. I am likely doing this wrong. should I be doing this in a class? Thanks for the help. from Tkinter import * def createLeftWidgets(left): # # Add the Net Status Section # conditions = LabelFrame(left, text="Net Conditions",bg="Gray") conditions.grid(row=0,column=0); button = Button(conditions, text="Refresh", command=refreshNetConditions, highlightbackground="Green") button.grid(row=0,column=1, sticky=E) cText = Text(conditions,bg="Gray") cText.insert(END, root.netHistory.get()) cText.config(height=12,width=40) cText.grid(row=1,column=0,columnspan=2) status = LabelFrame(left, text="Net Details",bg="Gray") status.grid(row=1,column=0,sticky=N+E+W+S); lblNetNumber = Label(status, text="Net Number") lblNetNumber.grid( row=19, column=0, columnspan=2,sticky=W) return(conditions) def refreshNetConditions(): global frameLeft frameLeft.destroy() root.netHistory.set( "inserting text\n" + root.netHistory.get()) createLeftWidgets(frameLeft) root = Tk() root.netHistory = StringVar() root.netHistory.set("goes into the text widget") frame = Frame(root) frame.grid() frameLeft = createLeftWidgets(frame) root.mainloop() From roy at panix.com Sun Aug 1 20:36:20 2010 From: roy at panix.com (Roy Smith) Date: Sun, 01 Aug 2010 20:36:20 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article <4c55fe82$0$9111$426a34cc at news.free.fr>, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? > > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. One thing that comes to mind is that it's much easier to distribute C libraries than C++ libraries. If I compile a main program with one C compiler and you compile a dynamically loaded library with another C compiler on the same box, the odds are pretty good they'll interoperate without any problems. Not at all so with C++ compilers. The linkage is *way* more complicated. Not just how the two compilers do name mangling, but how they handle exceptions, RVO, and a zillion other details. Pretty much the only way to make it work is to compile everything with exactly the same compiler. That would make it pretty close to impossible for people to take a Python core distribution and add their own extension modules to it. From ldo at geek-central.gen.new_zealand Sun Aug 1 20:41:04 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 02 Aug 2010 12:41:04 +1200 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <87sk2zhpcj.fsf@dpt-info.u-strasbg.fr> <87k4oah1rp.fsf@dpt-info.u-strasbg.fr> Message-ID: In message <87k4oah1rp.fsf at dpt-info.u-strasbg.fr>, Alain Ketterlin wrote: > Lawrence D'Oliveiro writes: > >> No, I deliberately put it in that order to ensure that the value for l >> can only ever be evaulated once. > > Try this (essentially equivalent to your code): > > def f(): > print "hello" > return 1 > > V = tuple( 1 for x in [1,2,3] for l in (f(),) ) > > How many "hello"s do you see? > > Comprehension are not loops spelled backwards. The values in: > > whatever for i ... for j ... > > are the values produced by the equivalent code: > > for i ... > for j ... > whatever Damn. I thought that e for i ... for j ... was equivalent to (e for i ...) for j ... Looks like I was wrong. From ldo at geek-central.gen.new_zealand Sun Aug 1 20:43:33 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 02 Aug 2010 12:43:33 +1200 Subject: Problem with Elementtree and XMLSchem instance type References: <96e47fd8-c939-48a2-9a2b-92afa720c8ac@k1g2000prl.googlegroups.com> Message-ID: In message <96e47fd8-c939-48a2-9a2b-92afa720c8ac at k1g2000prl.googlegroups.com>, Carl Banks wrote: > My general feeling is that ElementTree is a lot handier for reading > and writing your own XML formats, than for handling XML files produced > by other tools. Why is that? I?ve successfully used it to parse SVG files produced by Inkscape . From steve-REMOVE-THIS at cybersource.com.au Sun Aug 1 20:52:15 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 00:52:15 GMT Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> Message-ID: <4c5616bf$0$11113$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 09:56:48 -0700, ????? wrote: > Hello fellow Python Coders! > > I don't see the error in my attempt to set a a cookie in this test > script. Neither do I. What makes you think there is an error? What sort of error? Do you get a core dump, an exception, or something else? Please report what you get, and what you expect, and how they are different. -- Steven From steve-REMOVE-THIS at cybersource.com.au Sun Aug 1 20:56:29 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 00:56:29 GMT Subject: how can I solve this erorr usr/lib/python2.6 : permisson denied References: <43e2d3fb-a0f9-468c-bd64-4516eed7dec5@u38g2000prh.googlegroups.com> Message-ID: <4c5617bc$0$11113$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 05:05:39 -0700, Mohseniaref wrote: > Dear Friend > I have this erorr after running pyhon script with header > /usr/lib/python2.6 : permisson denied I change ownership with -hR in > super user terminal Please COPY AND PASTE (do NOT retype them): (1) the header from the script (2) the command you use to run the script (3) the error message you get (4) the command you use to change ownership (5) the result of that command (6) what happens if you try running the script again -- Steven From magawake at gmail.com Sun Aug 1 20:59:24 2010 From: magawake at gmail.com (Mag Gam) Date: Sun, 1 Aug 2010 20:59:24 -0400 Subject: timeit function Message-ID: Currently, I have a bash shell script which does timing for me. For example, if I have a Unix Command I typically run time against it for 10 times and then get an average. It works fine but I have to write a post processing script to get the time and then do a graph on matplotlib. I was wondering if the timeit function would be helpful in my case. I was thinking to open a subprocess to run the Unix command 10 times (instead of 1 million times) and then do the average and then do the graph. Any thoughts about this? Is timeit the right tool for what I am trying to do? TIA... From john at castleamber.com Sun Aug 1 21:05:29 2010 From: john at castleamber.com (John Bokma) Date: Sun, 01 Aug 2010 20:05:29 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <87pqy14yee.fsf@castleamber.com> Terry Reedy writes: > On 8/1/2010 7:08 PM, candide wrote: >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? > > Python was first released before C++. C++ was named C++ in 1983 (development on it started in 1979) and the first commercial implementation was released in 1985 [1]. Implementation of Python started in December 1989 [2]. So: no. (I was quite sure on this, since I started to program in C++ in the late 80's/early 90's IIRC). [1] http://en.wikipedia.org/wiki/C_plus_plus#History [2] http://en.wikipedia.org/wiki/Python_%28programming_language%29#History http://python-history.blogspot.com/2009/01/brief-timeline-of-python.html -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From john at castleamber.com Sun Aug 1 21:09:48 2010 From: john at castleamber.com (John Bokma) Date: Sun, 01 Aug 2010 20:09:48 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <87lj8p4y77.fsf@castleamber.com> Roy Smith writes: > In article <4c55fe82$0$9111$426a34cc at news.free.fr>, > candide wrote: > >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. > > One thing that comes to mind is that it's much easier to distribute C > libraries than C++ libraries. In the beginning of C++ there were programs that just converted C++ to C (frontends). At least that is how the C++ compiler Acorn sold worked. So I don't think your argument was much true back then. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From rechardchen at gmail.com Sun Aug 1 21:17:14 2010 From: rechardchen at gmail.com (rechardchen) Date: Mon, 02 Aug 2010 09:17:14 +0800 Subject: How to catch windows shutdown/reboot message Message-ID: I'm writing a python script which runs as a windowsxp service. The problem is how to catch the windows shutdown/reboot message and do some cleaning job when system is going down? The atexit module and signal module on windows dont seems to work. I guess the python win32api may be of help, but I am not familiar with it... Thank you From lists at cheimes.de Sun Aug 1 21:20:15 2010 From: lists at cheimes.de (Christian Heimes) Date: Mon, 02 Aug 2010 03:20:15 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: Am 02.08.2010 01:08, schrieb candide: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? Python is written in C89 to support as many platforms as possible. We deliberately don't use any new features and almost no compiler specific extensions to make the interpreter portable. AFAIK the only compiler specific feature used in Python are computed gotos and they are optional. > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. > > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? I like to say that the Python interpreter is written in object oriented C code. Every Python object evolved around PyObject and PyType structs that are extended (subclassed) to add additional members. Python won't gain anything useful from a pure C++ implementation. C++ would only add a major layer of complexity and scary features. In your opinion what would Python gain from a C++ implementation? Christian From pavlovevidence at gmail.com Sun Aug 1 21:30:52 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 1 Aug 2010 18:30:52 -0700 (PDT) Subject: Problem with Elementtree and XMLSchem instance type References: <96e47fd8-c939-48a2-9a2b-92afa720c8ac@k1g2000prl.googlegroups.com> Message-ID: <6627204c-d0b1-456d-94bd-76d946ad21d9@g6g2000pro.googlegroups.com> On Aug 1, 5:43?pm, Lawrence D'Oliveiro wrote: > In message > <96e47fd8-c939-48a2-9a2b-92afa720c... at k1g2000prl.googlegroups.com>, Carl > > Banks wrote: > > My general feeling is that ElementTree is a lot handier for reading > > and writing your own XML formats, than for handling XML files produced > > by other tools. > > Why is that? I?ve successfully used it to parse SVG files produced by > Inkscape . I said it was not handy, not that is was not useful. And you don't *have* to try to start an argument over every tiny thing you disagree with. Carl Banks From rechardchen at gmail.com Sun Aug 1 21:33:00 2010 From: rechardchen at gmail.com (rechardchen) Date: Mon, 02 Aug 2010 09:33:00 +0800 Subject: beginner python GUI question In-Reply-To: References: Message-ID: ? 2010-8-2 6:15, Chris Hare ??: > I hope I can explain this correctly. > > I have a GUI, which is already being processed by a mainloop. I want to be able to open a second window so the user can interact with specific information in the second window. I pulled together this code example > > from Tkinter import * > > class Net: > def __init__(self,tkWin): > self.window = tkWin > def show(self,t): > self.l = Label(self.window,text=t) > self.l.grid() > button = Button(self.window, text="Again") > button.bind("", self.Again) > button.grid() > def Again(self,event): > win3 = Tk() > x = Net(win3) > x.show("window 3") > > root = Tk() > root.title = "test" > f = Frame(root,bg="Yellow") > l = Label(f,text="window 1") > f.grid() > l.grid() > > win2 = Tk() > x = Net(win2) > x.show("window 2") > if __name__ == "__main__": > root.mainloop() > > Is this the right way to do things, or would you suggest something different? > > Thanks, > Chris > Using Tkinter.Toplevel may be better. :) From rtomek at ceti.com.pl Sun Aug 1 21:49:50 2010 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Mon, 2 Aug 2010 03:49:50 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <87lj8p4y77.fsf@castleamber.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> Message-ID: On Sun, 1 Aug 2010, John Bokma wrote: > In the beginning of C++ there were programs that just converted C++ to C > (frontends). At least that is how the C++ compiler Acorn sold worked. > So I don't think your argument was much true back then. Those that I (tried to) used on Amiga were based around the same concept. It seems, that Comeau C++ compiler (which I never tried) still requires C compiler as a backend (and is highly regarded by some). Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From pavlovevidence at gmail.com Sun Aug 1 22:13:04 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 1 Aug 2010 19:13:04 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> Message-ID: <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> On Aug 1, 6:09?pm, John Bokma wrote: > Roy Smith writes: > > In article <4c55fe82$0$9111$426a3... at news.free.fr>, > > ?candide wrote: > > >> Python is an object oriented langage (OOL). The Python main > >> implementation is written in pure and "old" C90. Is it for historical > >> reasons? > > >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > >> suitable to implement an OOL with another one. > > > One thing that comes to mind is that it's much easier to distribute C > > libraries than C++ libraries. > > In the beginning of C++ there were programs that just converted C++ to C > (frontends). At least that is how the C++ compiler Acorn sold worked. > So I don't think your argument was much true back then. No, it was that way back then too. They might all generate C code but different C code by different backends wouldn't be able to call each other natively. For instnace the function int foo(int); might be name-mangled this way in one cfront: foo$d and this way in another: ____int_foo__int_i The virtual table of this class: class Bar { virtual int foo(int); virtual int bar(int); }; might be generated like this in one cfront: struct Bar$$Vtable$ { int (*Bar$$bar$d)(int); int (*Bar$$foo$d)(int); }; and like this in another: struct ____class_Foo___vtable_ { int (*foo)(int); int (*bar)(int); }; So, just because they both generated C code, it doesn't mean they can call one another. Carl Banks From eliben at gmail.com Sun Aug 1 22:15:55 2010 From: eliben at gmail.com (Eli Bendersky) Date: Mon, 2 Aug 2010 05:15:55 +0300 Subject: co_firstlineno on decorated functions Message-ID: Hello, I've been tinkering with __code__.co_firstlineno for testing the trace.py module (Python Issue 9315), and ran into an interesting problem. Consider this code: def dummydecorator(f): return f def foo(a): return a @dummydecorator def bar(a): return a if __name__ == "__main__": print foo.__code__.co_firstlineno print bar.__code__.co_firstlineno ---- The first print out correctly specifies the line "def foo" is in. However, the second one points to the line with "@dummydecorator" instead of "def bar". [Python 2.6] The side-effects of this behavior can be easily seen in the output of modules like trace and profile. Would you say it's normal, or could this be considered a bug? Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Sun Aug 1 22:16:29 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 1 Aug 2010 19:16:29 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> Message-ID: >On 2 ???, 03:52, Steven D'Aprano wrote: > Neither do I. What makes you think there is an error? What sort of error? > Do you get a core dump, an exception, or something else? > > Please report what you get, and what you expect, and how they are > different. Hello Steven, Here is the script when it tries to run from my remote web server: http://www.webville.gr/cgi-bin/koukos.py Its seems the error is in this line of code, somwthing with time. 19 cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year From nikos.the.gr33k at gmail.com Sun Aug 1 22:20:04 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sun, 1 Aug 2010 19:20:04 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> Message-ID: <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> Also my greek print appear in funny encoding although i do use # -*- coding: utf-8 -*- From pavlovevidence at gmail.com Sun Aug 1 22:20:07 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 1 Aug 2010 19:20:07 -0700 (PDT) Subject: Docstrings and PEP 3174 References: <4c551f45$0$11091$c3e8da3@news.astraweb.com> <8bkp46FsbmU1@mid.individual.net> Message-ID: <5984b623-f051-41b1-b5e0-b5c8baf1918f@b4g2000pra.googlegroups.com> On Aug 1, 4:26?pm, Terry Reedy wrote: > On 8/1/2010 4:30 AM, Gregory Ewing wrote: > > > Steven D'Aprano wrote: > > >> If you mean a runtime optimization with no change to the source file, > >> then maybe, tell me more. > > > Note that you don't necessarily need a separate file for this. > > It could just be a separate part of the same file. > > Which is to say, all the docstrings in a modules *could* be placed at > the end and not normally read in by the interpreter until needed. I'm going to guess that they don't want that in *.pyc files. In PEP 3147 they proposed a fat-format file (so a glob for each version) and it was not popular. > I have > no idea what it does now, There's a short header, then the rest of the file is a single marshaled glob. > but I suspect not that. It might make module > loading a bit faster. True but still probably a small optimization. Carl Banks From marduk at letterboxes.org Sun Aug 1 22:34:07 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 01 Aug 2010 22:34:07 -0400 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <1280716447.927705.20.camel@paska> On Mon, 2010-08-02 at 01:08 +0200, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? > > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. > > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? Disclaimer: I am neither a C nor C++ programmer. In fact I can barely even program in Python ;-) I would propose that in fact most programming languages are implemented in C. Sun's (Oracle's) Java compiler and runtime are written in ANSI C. The core of the Gnu Compiler Collection (which includes C++ and Objective-C compilers) is written in C. The official Ruby is implemented in C. The Squeak Smalltalk implementation uses C instead of C++. I can't even think of a programming language that is implemented in C++ (maybe C++ is). C seems to be a good, portable language for writing interpreters and compilers. But I wonder if someone has/has tried to write a programming language in C++ and what were their experiences. From python at mrabarnett.plus.com Sun Aug 1 22:49:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 02 Aug 2010 03:49:15 +0100 Subject: Trying to set a cookie within a python script In-Reply-To: <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> Message-ID: <4C56322B.2000903@mrabarnett.plus.com> ????? wrote: > Also my greek print appear in funny encoding although i do use # -*- > coding: utf-8 -*- That line just tells Python what encoding the source file itself uses. It doesn't affect what the program does or how it runs. From benjamin at python.org Sun Aug 1 23:01:25 2010 From: benjamin at python.org (Benjamin Peterson) Date: Sun, 1 Aug 2010 22:01:25 -0500 Subject: [Python-Dev] [RELEASED] Python 3.2 alpha 1 In-Reply-To: <4C55409B.5000409@python.org> References: <4C55409B.5000409@python.org> Message-ID: Hey, Georg! Congrats on your first release! 2010/8/1 Georg Brandl : > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team, I'm happy to announce the > first alpha preview release of Python 3.2. > > Python 3.2 is a continuation of the efforts to improve and stabilize the > Python 3.x line. ?Since the final release of Python 2.7, the 2.x line > will only receive bugfixes, and new features are developed for 3.x only. > > Since PEP 3003, the Moratorium on Language Changes, is in effect, there > are no changes in Python's syntax and built-in types in Python 3.2. > Development efforts concentrated on the standard library and support for > porting code to Python 3. ?Highlights are: > > * numerous improvements to the unittest module > * PEP 3147, support for .pyc repository directories > * an overhauled GIL implementation that reduces contention > * many consistency and behavior fixes for numeric operations > * countless fixes regarding string/unicode issues; among them full > ?support for a bytes environment (filenames, environment variables) > * a sysconfig module to access configuration information > * a pure-Python implementation of the datetime module > * additions to the shutil module, among them archive file support > * improvements to pdb, the Python debugger > > For an extensive list of changes in 3.2, see Misc/NEWS in the Python > distribution. > > To download Python 3.2 visit: > > ? ? http://www.python.org/download/releases/3.2/ > > 3.2 documentation can be found at: > > ? ? http://docs.python.org/3.2/ > > Please consider trying Python 3.2 with your code and reporting any bugs > you may notice to: > > ? ? http://bugs.python.org/ > > > Enjoy! > > - -- > Georg Brandl, Release Manager > georg at python.org > (on behalf of the entire python-dev team and 3.2's contributors) > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v2.0.16 (GNU/Linux) > > iEYEARECAAYFAkxVQJsACgkQN9GcIYhpnLBxIgCcCiVu/QUkFf0bYM2Vmi8St3mZ > 2N4An04q36lr47OA+bslqG/4Zj7ZwVOX > =iL8N > -----END PGP SIGNATURE----- > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: http://mail.python.org/mailman/options/python-dev/benjamin%40python.org > -- Regards, Benjamin From rtomek at ceti.pl Sun Aug 1 23:04:59 2010 From: rtomek at ceti.pl (Tomasz Rola) Date: Mon, 2 Aug 2010 05:04:59 +0200 (CEST) Subject: Why is python not written in C++ ? In-Reply-To: <1280716447.927705.20.camel@paska> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <1280716447.927705.20.camel@paska> Message-ID: On Sun, 1 Aug 2010, Albert Hopkins wrote: > C seems to be a good, portable language for writing interpreters and > compilers. And one should not forget about performance. C++ was for a long time behind C, and even now some parts (like iostreams) should be avoided in fast code. BTW, C++ can be IMHO a bit tricky in situations when one would like to call back from JIT-generated code into parts written in C++... I mean things like virtual functions, overloading, code generated from templates, accessing private members etc. All those issues are non essential from the point of interpreting or JIT, yet they stand in a way. While this could be solved (with some headache, I suspect), C is far simpler and function calls or manipulating structs are actually trivial... Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From rantingrick at gmail.com Sun Aug 1 23:13:55 2010 From: rantingrick at gmail.com (rantingrick) Date: Sun, 1 Aug 2010 20:13:55 -0700 (PDT) Subject: how best to clear objects from a frame References: Message-ID: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> On Aug 1, 7:12?pm, Chris Hare wrote: > Here is the situation: > > I have a window with a bunch of widgets in it. ?I want to clear the objects in a given frame and recreate them to update them. ? You need to check out the "w.update" and "w.update_idletasks" methods available on all Tkinter widgets. Just FYI: to remove a widget from view without destroying it use "w.pack_forget" or "w.grid_forget". However if you are simply trying to refresh a widget use one of the update methods. From steve-REMOVE-THIS at cybersource.com.au Sun Aug 1 23:21:21 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 03:21:21 GMT Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> Message-ID: <4c5639b1$0$11113$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 19:16:29 -0700, ????? wrote: >>On 2 ???, 03:52, Steven D'Aprano >>wrote: > >> Neither do I. What makes you think there is an error? What sort of >> error? Do you get a core dump, an exception, or something else? >> >> Please report what you get, and what you expect, and how they are >> different. > > Hello Steven, > > Here is the script when it tries to run from my remote web server: > http://www.webville.gr/cgi-bin/koukos.py > > Its seems the error is in this line of code, somwthing with time. > > 19 cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) > #this cookie will expire in an year What error? Please copy and paste (do not retype) the entire error you get. -- Steven From steve-REMOVE-THIS at cybersource.com.au Sun Aug 1 23:23:08 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 03:23:08 GMT Subject: Docstrings and PEP 3174 References: <4c551f45$0$11091$c3e8da3@news.astraweb.com> <8bkp46FsbmU1@mid.individual.net> Message-ID: <4c563a1c$0$11113$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 20:30:22 +1200, Gregory Ewing wrote: > Steven D'Aprano wrote: > >> If you mean a runtime optimization with no change to the source file, >> then maybe, tell me more. > > Note that you don't necessarily need a separate file for this. It could > just be a separate part of the same file. I would disagree with any attempt to move the docstring away from immediately next to the function in the source file. You can currently do that if you insist, after all __doc__ is just an ordinary attribute: >>> def f(): ... pass ... >>> f.__doc__ = some_other_text I don't think we should do anything that *encourages* people to separate the code and docstrings in the source file. On the assumption that functions will continue to be written: def f(): """Doc string""" pass I like the proposal to make f.__doc__ a descriptor that lazily loads the doc string from disk when needed, rather than keeping the string in memory at all times. Whether this leads to enough memory savings to justify it is an open question. -- Steven From torriem at gmail.com Mon Aug 2 00:23:33 2010 From: torriem at gmail.com (Michael Torrie) Date: Sun, 01 Aug 2010 22:23:33 -0600 Subject: Why is python not written in C++ ? In-Reply-To: <87lj8p4y77.fsf@castleamber.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> Message-ID: <4C564845.9040909@gmail.com> On 08/01/2010 07:09 PM, John Bokma wrote: >> One thing that comes to mind is that it's much easier to distribute C >> libraries than C++ libraries. > > In the beginning of C++ there were programs that just converted C++ to C > (frontends). At least that is how the C++ compiler Acorn sold worked. > So I don't think your argument was much true back then. No, he is still right. Each C++ implementation did name mangling differently leading to "C" libraries that had incompatible names and signatures. Also each frontend could have generated incompatible vtables and other C++ structures. So C code generated by one C++ frontend could not easily call C code generated by another C++ frontend. So the same arguments that are made about C++ now were just as valid back then when C++ was merely a fancy preprocessor. From doug.garstang at gmail.com Mon Aug 2 01:09:23 2010 From: doug.garstang at gmail.com (Douglas Garstang) Date: Sun, 1 Aug 2010 22:09:23 -0700 Subject: Merging two dictionaries Message-ID: Anyone, I have the two dictionaries below. How can I merge them, such that: 1. The cluster dictionary contains the additional elements from the default dictionary. 2. Nothing is removed from the cluster dictionary. The idea here is that the two dictionaries are read from different files where, if the value isn't found in the cluster dictionary, it's pulled from the default one, and I can have a new dictionary reflecting this. The update() method on dictionaries doesn't seem to work. The resulting dictionary always seems to be the one passed as a parameter. default = { 'cluster': { 'platform': { 'elements': { 'data_sources': { 'elements': { 'db_min_pool_size': 10 }, }, }, }, } } cluster = { 'cluster': { 'name': 'Customer 1', 'description': 'Production', 'environment': 'production', 'platform': { 'elements': { 'data_source': { 'elements': { 'username': 'username', 'password': 'password' }, }, }, }, } } The resulting dictionary would therefore look like this: new_dict = { 'cluster': { 'name': 'Customer 1', 'description': 'Production', 'environment': 'production', 'platform': { 'elements': { 'data_source': { 'elements': { 'username': 'username', 'password': 'password', 'db_min_pool_size': 10 # This was added from the default. }, }, }, }, } } Thanks, Doug. -- Regards, Douglas Garstang http://www.linkedin.com/in/garstang Email: doug.garstang at gmail.com Cell: +1-805-340-5627 From michele.simionato at gmail.com Mon Aug 2 02:15:11 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Sun, 1 Aug 2010 23:15:11 -0700 (PDT) Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> Message-ID: On Jul 31, 5:08?am, Steven D'Aprano wrote: > I have read Michelle Simionato's articles on super in Python. One "l" please! I am a man! ;-) > > But Michelle is wrong to conclude that the problem lies with the concept > of *superclass*. The problem lies with the idea that there is ONE > superclass. By dismissing the entire concept, he is throwing out the baby > with the bathwater. I am actually more radical than that. From http://www.artima.com/weblogs/viewpost.jsp?thread=237121: """ In this series I have argued that super is tricky; I think nobody can dispute that. However the existence of dark corners is not a compelling argument against a language construct: after all, they are rare and there is an easy solution to their obscurity, i.e. documenting them. This is what I have being doing all along. On the other hand, one may wonder if all super warts aren't hints of some serious problem underlying. It may well be that the problem is not with super, nor with cooperative methods: the problem may be with multiple inheritance itself. """ Then I spend thousands of words in the "Mixin considered harmful" series and in other articles arguing against multiple inheritance and cooperative methods. They are just bad design IMO. Of course we are in the range of opinions, this is a tricky subject: many smart people agree with me and many others equally smart disagree. Still I believe that super is a red herring and that you should really start thinking: what advantages did multiple inheritance *really* bring into my code? Could have I done without? And what would have happen? These are the relevant question, not the exact meaning of super in hairy hierarchies. M. Simionato From no.email at nospam.invalid Mon Aug 2 02:21:22 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 01 Aug 2010 23:21:22 -0700 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> Message-ID: <7xmxt5357h.fsf@ruckus.brouhaha.com> Michele Simionato writes: > I am actually more radical than that. From > http://www.artima.com/weblogs/viewpost.jsp?thread=237121: > In this series I have argued that super is tricky; I think nobody can... When I look at that URL, I see a Java stack dump: java.lang.RuntimeException: com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid at com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112) ... Seems appropriate. From nikos.the.gr33k at gmail.com Mon Aug 2 02:39:34 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 1 Aug 2010 23:39:34 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> Message-ID: <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> If you just click in my web page to see the script run in action due to the cgitb module i use it will provide you both the source code that the error appears and the error as well. All you have to do is click here: http://www.webville.gr/cgi-bin/koukos.py As for the encoding why when i print greek characters they dont appear correctly in chrome in runtime? From V.vanBeveren at rijnhuizen.nl Mon Aug 2 02:41:36 2010 From: V.vanBeveren at rijnhuizen.nl (Vincent van Beveren) Date: Mon, 2 Aug 2010 08:41:36 +0200 Subject: The untimely dimise of a weak-reference In-Reply-To: <8bhi2fFifjU1@mid.individual.net> References: <8bhi2fFifjU1@mid.individual.net> Message-ID: <2926F4BC94217A43A2D21792DE88189339C58B6374@ex1.rijnh.nl> Hi Gregory, > You can create your own wrapper that keeps a weak reference to > the underlying object. Here's an example. > [...] Thanks for the code! Regards, Vincent From V.vanBeveren at rijnhuizen.nl Mon Aug 2 02:46:13 2010 From: V.vanBeveren at rijnhuizen.nl (Vincent van Beveren) Date: Mon, 2 Aug 2010 08:46:13 +0200 Subject: The untimely dimise of a weak-reference In-Reply-To: References: <2926F4BC94217A43A2D21792DE88189339C58B6373@ex1.rijnh.nl> Message-ID: <2926F4BC94217A43A2D21792DE88189339C58B6375@ex1.rijnh.nl> Hi Christiaan, > Instances of a class have no means of storing the bound method object. > The or unbound bound method is a simple and small wrapper that keeps a > reference to the class, "self" and the function object. Python keeps a > pool of empty method objects in a free list. The creation of a new bound > method just takes a few pointer assignments and three INCREFs. Okay, that also explains the consistent memory assignment. Maybe I'll create a bound-method caching object, see how slow/fast it is in comparison, and see what ever other issues I run into. Regards, Vincent -----Original Message----- From: python-list-bounces+v.vanbeveren=rijnhuizen.nl at python.org [mailto:python-list-bounces+v.vanbeveren=rijnhuizen.nl at python.org] On Behalf Of Christian Heimes Sent: vrijdag 30 juli 2010 16:44 To: python-list at python.org Subject: Re: The untimely dimise of a weak-reference Am 30.07.2010 16:06, schrieb Vincent van Beveren: > I did not know the object did not keep track of its bound methods. What advantage is there in creating a new bound method object each time its referenced? It seems kind of expensive. Christian -- http://mail.python.org/mailman/listinfo/python-list From sanjeeb25 at gmail.com Mon Aug 2 02:52:18 2010 From: sanjeeb25 at gmail.com (Sanjeeb) Date: Sun, 1 Aug 2010 23:52:18 -0700 (PDT) Subject: sending a file chunk by chunk instead as a whole to a web server Message-ID: Hi, I have a web client which send a file to a server as multipart form data, the sending of data is from http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/. I dont want to open the whole file to memory(at cliend end) and then send, i just want to send part by part, say chunk of 1024 bytes to the server and then assemble at the server end. Could some one suggest what would be the best way to do this? Regards -Sanjeeb From gherron at islandtraining.com Mon Aug 2 02:57:34 2010 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 01 Aug 2010 23:57:34 -0700 Subject: Merging two dictionaries In-Reply-To: References: <4C565E79.6090307@islandtraining.com> Message-ID: <4C566C5E.9000008@islandtraining.com> On 08/01/2010 11:11 PM, Douglas Garstang wrote: > On Sun, Aug 1, 2010 at 10:58 PM, Gary Herron wrote: > >> On 08/01/2010 10:09 PM, Douglas Garstang wrote: >> >>> Anyone, >>> >>> I have the two dictionaries below. How can I merge them, such that: >>> >>> 1. The cluster dictionary contains the additional elements from the >>> default dictionary. >>> 2. Nothing is removed from the cluster dictionary. >>> >>> The idea here is that the two dictionaries are read from different >>> files where, if the value isn't found in the cluster dictionary, it's >>> pulled from the default one, and I can have a new dictionary >>> reflecting this. The update() method on dictionaries doesn't seem to >>> work. The resulting dictionary always seems to be the one passed as a >>> parameter. >>> >>> default = { >>> 'cluster': { >>> 'platform': { >>> 'elements': { >>> 'data_sources': { >>> 'elements': { >>> 'db_min_pool_size': 10 >>> }, >>> }, >>> }, >>> }, >>> } >>> } >>> >>> cluster = { >>> 'cluster': { >>> 'name': 'Customer 1', >>> 'description': 'Production', >>> 'environment': 'production', >>> 'platform': { >>> 'elements': { >>> 'data_source': { >>> 'elements': { >>> 'username': 'username', >>> 'password': 'password' >>> }, >>> }, >>> }, >>> }, >>> } >>> } >>> >>> The resulting dictionary would therefore look like this: >>> >>> new_dict = { >>> 'cluster': { >>> 'name': 'Customer 1', >>> 'description': 'Production', >>> 'environment': 'production', >>> 'platform': { >>> 'elements': { >>> 'data_source': { >>> 'elements': { >>> 'username': 'username', >>> 'password': 'password', >>> 'db_min_pool_size': 10 # This was added from >>> the default. >>> }, >>> }, >>> }, >>> }, >>> } >>> } >>> >>> >>> Thanks, >>> Doug. >>> >>> >>> >> Your dictionaries are annoyingly complicated -- making it hard to see what's >> going on. Here I've replaced all the distractions of your dictionary >> nesting with a simple (string) value. Now when you try to update >> >> >>>>> default = {'cluster': 'some_value'} >>>>> cluster = {'cluster': 'another_value'} >>>>> cluster.update(default) >>>>> print cluster >>>>> >> {'cluster': 'some_value'} >> >> If you read up on what update is supposed to do, this is correct -- keys in >> default are inserted into cluster -- replacing values if they already exist. >> >> I believe update is not what you want for two reasons: >> >> 1. It's doubtful that you want a default to replace an existing value, and >> that's what update does. >> >> 2. I get the distinct impression that you are expecting the update to be >> applied recursively down through the hierarchy. Such is not the case. >> >> >> >> >> And I just have to ask: Of what use whatsoever is a dictionary (hierarchy) >> that contains *one* single value which needs a sequence of 6 keys to access? >> >> print >> default['cluster']['platform']['elements']['data_sources']['elements']['db_min_pool_size'] >> >>>>> 10 >>>>> >> Seems absurd unless there is lots more going on here. >> > Thanks. Any particular reason you replied off-list? > Huh? Oh hell. My mistake. (This is now back on the list -- where it should have been to start with.) > Anyway, I'm trying to model a cluster of servers in a yaml file that > gets edited by humans and a tree structure makes it easier to > understand the context of each invidual key. If it was arrange in a > flat fashion, each key would have to be longer in order to make it > unique and provide some context as to what the user was actually > editing. > > I actually didn't paste the whole dictionary. I cut it down to make it > easier to explain. When you see the full version, the multiple levels > make more sense. Tried various approaches so far, and none work. I > can't traverse the tree recursively because each time you recurse, you > lose the absolute position of the key your currently at, and then > there's no way to update the values. > > Doug. > Ok. Thanks for simplifying things before sending the question out to the list. You probably wouldn't have gotten a response otherwise. I'm not sure I believe the reasoning for the inability to recurse. It seems rather simple to recurse through the structures in tandem, adding any key:value found in the default to the other if not already present. Gary Herron From doug.garstang at gmail.com Mon Aug 2 03:06:16 2010 From: doug.garstang at gmail.com (Douglas Garstang) Date: Mon, 2 Aug 2010 00:06:16 -0700 Subject: Merging two dictionaries In-Reply-To: <4C566C5E.9000008@islandtraining.com> References: <4C565E79.6090307@islandtraining.com> <4C566C5E.9000008@islandtraining.com> Message-ID: On Sun, Aug 1, 2010 at 11:57 PM, Gary Herron wrote: > On 08/01/2010 11:11 PM, Douglas Garstang wrote: >> >> On Sun, Aug 1, 2010 at 10:58 PM, Gary Herron >> ?wrote: >> >>> >>> On 08/01/2010 10:09 PM, Douglas Garstang wrote: >>> >>>> >>>> Anyone, >>>> >>>> I have the two dictionaries below. How can I merge them, such that: >>>> >>>> 1. The cluster dictionary contains the additional elements from the >>>> default dictionary. >>>> 2. Nothing is removed from the cluster dictionary. >>>> >>>> The idea here is that the two dictionaries are read from different >>>> files where, if the value isn't found in the cluster dictionary, it's >>>> pulled from the default one, and I can have a new dictionary >>>> reflecting this. The update() method on dictionaries doesn't seem to >>>> work. The resulting dictionary always seems to be the one passed as a >>>> parameter. >>>> >>>> default = { >>>> ? ? 'cluster': { >>>> ? ? ? ? 'platform': { >>>> ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? 'data_sources': { >>>> ? ? ? ? ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'db_min_pool_size': 10 >>>> ? ? ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? }, >>>> ? ? ? ? }, >>>> ? ? } >>>> } >>>> >>>> cluster = { >>>> ? ? 'cluster': { >>>> ? ? ? ? 'name': 'Customer 1', >>>> ? ? ? ? 'description': 'Production', >>>> ? ? ? ? 'environment': 'production', >>>> ? ? ? ? 'platform': { >>>> ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? 'data_source': { >>>> ? ? ? ? ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'username': 'username', >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'password': 'password' >>>> ? ? ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? }, >>>> ? ? ? ? }, >>>> ? ? } >>>> } >>>> >>>> The resulting dictionary would therefore look like this: >>>> >>>> new_dict = { >>>> ? ? 'cluster': { >>>> ? ? ? ? 'name': 'Customer 1', >>>> ? ? ? ? 'description': 'Production', >>>> ? ? ? ? 'environment': 'production', >>>> ? ? ? ? 'platform': { >>>> ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? 'data_source': { >>>> ? ? ? ? ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'username': 'username', >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'password': 'password', >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'db_min_pool_size': 10 # This was added from >>>> the default. >>>> ? ? ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? }, >>>> ? ? ? ? }, >>>> ? ? } >>>> } >>>> >>>> >>>> Thanks, >>>> Doug. >>>> >>>> >>>> >>> >>> Your dictionaries are annoyingly complicated -- making it hard to see >>> what's >>> going on. ?Here I've replaced all the distractions of your dictionary >>> nesting with a simple (string) value. ?Now when you try to update >>> >>> >>>>>> >>>>>> default = {'cluster': 'some_value'} >>>>>> cluster = {'cluster': 'another_value'} >>>>>> cluster.update(default) >>>>>> print cluster >>>>>> >>> >>> {'cluster': 'some_value'} >>> >>> If you read up on what update is supposed to do, this is correct -- keys >>> in >>> default are inserted into cluster -- replacing values if they already >>> exist. >>> >>> I believe update is not what you want for two reasons: >>> >>> ?1. ?It's doubtful that you want a default to replace an existing value, >>> and >>> that's what update does. >>> >>> ?2. ?I get the distinct impression that you are expecting the update to >>> be >>> applied recursively down through the hierarchy. ?Such is not the case. >>> >>> >>> >>> >>> And I just have to ask: Of what use whatsoever is a dictionary >>> (hierarchy) >>> that contains *one* single value which needs a sequence of 6 keys to >>> access? >>> >>> print >>> >>> default['cluster']['platform']['elements']['data_sources']['elements']['db_min_pool_size'] >>> >>>>>> >>>>>> 10 >>>>>> >>> >>> Seems absurd unless there is lots more going on here. >>> >> >> Thanks. Any particular reason you replied off-list? >> > > Huh? ?Oh hell. ?My mistake. ?(This is now back on the list -- where it > should have been to start with.) > > >> Anyway, I'm trying to model a cluster of servers in a yaml file that >> gets edited by humans and a tree structure makes it easier to >> understand the context of each invidual key. If it was arrange in a >> flat fashion, each key would have to be longer in order to make it >> unique and provide some context as to what the user was actually >> editing. >> >> I actually didn't paste the whole dictionary. I cut it down to make it >> easier to explain. When you see the full version, the multiple levels >> make more sense. Tried various approaches so far, and none work. I >> can't traverse the tree recursively because each time you recurse, you >> lose the absolute position of the key your currently at, and then >> there's no way to update the values. >> >> Doug. >> > > Ok. ?Thanks for simplifying things before sending the question out to the > list. ?You probably wouldn't have gotten a response otherwise. > > I'm not sure I believe the reasoning for the inability to recurse. ?It seems > rather simple to recurse through the structures in tandem, adding any > key:value found in the default to the other if not already present. Actually, I had issues with trying recurse through the structures in tandem too. This didn't work: for a,b,c,d in ( cluster.iteritems(), default.iteritems() ): ... do something ... It returns an unpack error. Doug. From clp2 at rebertia.com Mon Aug 2 03:26:54 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 2 Aug 2010 00:26:54 -0700 Subject: Merging two dictionaries In-Reply-To: References: <4C565E79.6090307@islandtraining.com> <4C566C5E.9000008@islandtraining.com> Message-ID: On Mon, Aug 2, 2010 at 12:06 AM, Douglas Garstang wrote: > Actually, I had issues with trying recurse through the structures in > tandem too. This didn't work: > > for a,b,c,d in ( cluster.iteritems(), default.iteritems() ): > ? ?... do something ... > > It returns an unpack error. Well, yeah. That for-loop has several problems: - You're iterating over the items of a 2-tuple. It's just like: for a,b,c,d in [1, 2]: It's not treated any differently just because the items happen to be iterators themselves. The iterators aren't automagically iterated through in parallel just by putting them in a tuple. That would require a zip(). - iteritems() returns a sequence of 2-tuples. Even when zipped, these tuples don't get magically unpacked and repacked into 4-tuples: for a, b, c, d in zip([(1,2), (3,4)], [(5,6), (7,8)]): # still fails; can't unpack 2 separate tuples (i.e. (1,2) (5,6) ) directly into 4 variables; the nesting is wrong - iteritems() returns the keys in an arbitrary order; the two iteritems() calls won't be in any way "synchronized" so the keys match up Cheers, Chris -- http://blog.rebertia.com From no.email at nospam.invalid Mon Aug 2 03:47:11 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 02 Aug 2010 00:47:11 -0700 Subject: Merging two dictionaries References: Message-ID: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> Douglas Garstang writes: > default = {... > 'data_sources': { ... > cluster = {... > 'data_source': { ... Did you want both of those to say the same thing instead of one of them being 'data_source' and the other 'data_sources' ? If yes, then the following works for me: def merge(cluster, default): # destructively merge default into cluster for k,v in cluster.iteritems(): if k in default and type(v)==dict: assert type(default(k))==dict merge(v,default[k]) for k,v in default.iteritems(): if k not in cluster: cluster[k] = v From mail at timgolden.me.uk Mon Aug 2 04:00:17 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 02 Aug 2010 09:00:17 +0100 Subject: How to catch windows shutdown/reboot message In-Reply-To: References: Message-ID: <4C567B11.4060408@timgolden.me.uk> On 02/08/2010 02:17, rechardchen wrote: > I'm writing a python script which runs as a windowsxp service. > The problem is how to catch the windows shutdown/reboot message and do > some cleaning job when system is going down? > > The atexit module and signal module on windows dont seems to work. I > guess the python win32api may be of help, but I am not familiar with it... > Thank you Have a look at the SENS stuff: http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html TJG From newBlue at batbug.org Mon Aug 2 04:09:29 2010 From: newBlue at batbug.org (NewBlue) Date: Mon, 02 Aug 2010 16:09:29 +0800 Subject: Problem with Elementtree and XMLSchem instance type References: Message-ID: >>>>> "Lawrence" == Lawrence D'Oliveiro writes: Lawrence> In message Lawrence> , Lawrence> Roland Lawrence> Hedberg wrote: > And there is the problem, I've lost the coupling between the prefix >> 'fed' and the namespace >> "http://docs.oasis-open.org/wsfed/federation/200706". Lawrence> Why is this a problem? ???? -- ?????????????????? ????????????? My homepage:[http://211.92.88.40/~newblue] From __peter__ at web.de Mon Aug 2 04:09:35 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Aug 2010 10:09:35 +0200 Subject: Merging two dictionaries References: Message-ID: Douglas Garstang wrote: > I have the two dictionaries below. How can I merge them, such that: > > 1. The cluster dictionary contains the additional elements from the > default dictionary. > 2. Nothing is removed from the cluster dictionary. def inplace_merge(default, cluster): assert isinstance(default, dict) assert isinstance(cluster, dict) d = set(default) c = set(cluster) default_only = d - c both = d & c for key in both: dv = default[key] cv = cluster[key] if isinstance(cv, dict): inplace_merge(dv, cv) cluster.update((dk, default[dk]) for dk in default_only) should work once you've fixed your example dicts. Peter From thorsten at thorstenkampe.de Mon Aug 2 04:33:22 2010 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Aug 2010 10:33:22 +0200 Subject: How to capture all the environment variables from shell? References: <4C4E43D3.9070203@syslang.net> Message-ID: * Tim Chase (Mon, 26 Jul 2010 21:42:24 -0500) > On 07/26/10 21:26, Steven W. Orr wrote: > > Please! Never export anything from your .bashrc unless you > > really know what you're doing. Almost all exports should be > > done in your .bash_profile > > Could you elaborate on your reasoning why (or why-not)? I've > found that my .bash_profile doesn't get evaluated when I crank up > another terminal window, while my bashrc does. Thus I tend to > put my exports in my ~/.bashrc so they actually take effect in my > shell... ~/.bash_profile is only evaluated for login shells and ~/.bashrc only for non-login shells. Thus it's recommended to keep ~/.bash_profile empty (except a source statement for .bashrc) and put all your settings, aliases, exports, etc. in .bashrc. Thorsten From jeanmichel at sequans.com Mon Aug 2 04:50:03 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 02 Aug 2010 10:50:03 +0200 Subject: Access stdout from external program. In-Reply-To: <561066.47255.qm@web52905.mail.re2.yahoo.com> References: <561066.47255.qm@web52905.mail.re2.yahoo.com> Message-ID: <4C5686BB.7000508@sequans.com> Paul Lemelle wrote: > Hi JM, > > My last dumb question: When I try to run the below script as an > executable, I get the following error: > pttdev at pttTestVM:~$ ./argv.py 4 > import: unable to open X server `/tmp/launch-c8feFG/org.x:0' @ > import.c/ImportImageCommand/361. > ./argv.py: line 8: syntax error near unexpected token `print' > ./argv.py: line 8: ` print x' > > The script: > # Writing the output to a standard argv argument > > #!/usr/bin/env python > > import sys > > for x in sys.argv: > print x > > > #END > > Any idea why? > > Thanks, > Paul > Please don't remove python-list. I see 2 possibilities: 1/ this is related to the open X server, for that I can't help you, something related to your exported display if you're remotely logged on the machine 2/ you are using python 2.x syntax within a python 3 interpreter. Try "print (x)". JM From s.selvamsiva at gmail.com Mon Aug 2 04:59:49 2010 From: s.selvamsiva at gmail.com (S.Selvam) Date: Mon, 2 Aug 2010 14:29:49 +0530 Subject: Capturing running Application Message-ID: Hi all, I am using python 2.6(running ubuntu 9.10 ). I want to display the amount of time spent( by an user) among all the running applications like Gedit, Firefox, GIMP and display the result graphically. For eg: Firefox: 60% Gedit:25% Terminal:15% I think, i need to capture the currently focussed application, update the time spent in some format and display it graphically. I am not sure about the modules that need to be used.I welcome your ideas. -- Regards, S.Selvam " I am because we are " -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.wintle at teamrubber.com Mon Aug 2 05:00:58 2010 From: tim.wintle at teamrubber.com (Tim Wintle) Date: Mon, 02 Aug 2010 10:00:58 +0100 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <1280739658.10380.8.camel@tim-laptop> On Sun, 2010-08-01 at 20:01 -0400, Terry Reedy wrote: > Not every C programmer knows or wants to learn C++. I think Terry is the only person that's mentioned this - but I'd like to give extra support to it - I for one prefer C to C++ (as someone that writes quite a lot of C extension modules). And as Stephen mentioned - just because C is not an OO language, doesn't mean you can't write OO code in it - you just have to pass an instance of the class method is defined on in as the first parameter (like you do in Python). Tim From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 2 05:10:26 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 02 Aug 2010 11:10:26 +0200 Subject: The untimely dimise of a weak-reference In-Reply-To: <8bhi2fFifjU1@mid.individual.net> References: <8bhi2fFifjU1@mid.individual.net> Message-ID: <4c568b59$0$14545$426a34cc@news.free.fr> Gregory Ewing a ?crit : (snip) > import weakref > > class weakmethod(object): > > def __init__(self, bm): > self.ref = weakref.ref(bm.im_self) > self.func = bm.im_func > > def __call__(self, *args, **kwds): > obj = self.ref() > if obj is None: > raise ValueError("Calling dead weak method") > self.func(obj, *args, **kwds) Would be better with : return self.func(obj, *args, *kwds) From jeanmichel at sequans.com Mon Aug 2 05:23:30 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 02 Aug 2010 11:23:30 +0200 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <7xmxt5357h.fsf@ruckus.brouhaha.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> <7xmxt5357h.fsf@ruckus.brouhaha.com> Message-ID: <4C568E92.50907@sequans.com> Paul Rubin wrote: > Michele Simionato writes: > >> I am actually more radical than that. From >> http://www.artima.com/weblogs/viewpost.jsp?thread=237121: >> In this series I have argued that super is tricky; I think nobody can... >> > > When I look at that URL, I see a Java stack dump: > > java.lang.RuntimeException: com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid > at com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112) > ... > > Seems appropriate. > remove the ending double dot. JM From steve-REMOVE-THIS at cybersource.com.au Mon Aug 2 05:44:35 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 09:44:35 GMT Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> Message-ID: <4c569382$0$28655$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 23:39:34 -0700, ????? wrote: > If you just click in my web page to see the script run in action due to > the cgitb module i use it will provide you both the source code that the > error appears and the error as well. > > All you have to do is click here: > http://www.webville.gr/cgi-bin/koukos.py I'll do this just once, but next time, don't expect others to track down the error message for you. We're volunteers, we don't owe you anything, so if you want us to help, you make it easy for us. Some people have access to email, but not web. If you can't be bothered to copy and paste the error message into an email or news post, why should we be bothered to help you? The error you are getting is: NameError: name 'time' is not defined That tells you that you don't have a function called time() defined anywhere. You need to import the time module first: import time and then use the fully qualified function name time.time(), or do: from time import time and then use the function alone time(). > As for the encoding why when i print greek characters they dont appear > correctly in chrome in runtime? What encoding does the web page claim to be? You need to check the document encoding, and see that it matches the document encoding you are actually using. -- Steven From steve-REMOVE-THIS at cybersource.com.au Mon Aug 2 05:45:59 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 09:45:59 GMT Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4c5693d7$0$28655$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 23:15:11 -0700, Michele Simionato wrote: > On Jul 31, 5:08?am, Steven D'Aprano cybersource.com.au> wrote: >> I have read Michelle Simionato's articles on super in Python. > > One "l" please! I am a man! ;-) My apologies. You'd think I would know the difference between Michele and Michelle :( [snip] > Still I believe that super is a red herring and that you should really > start thinking: what advantages did > multiple inheritance *really* bring into my code? Could have I done > without? And what would have happen? > These are the relevant question, not the exact meaning of super in hairy > hierarchies. Yes, these are very good points. It's always worth looking at alternatives to subclassing in the first place. Far too often it's not just the first idiom people think of, but the *only* idiom they think of. -- Steven From bartc at freeuk.com Mon Aug 2 05:55:50 2010 From: bartc at freeuk.com (Bartc) Date: Mon, 2 Aug 2010 10:55:50 +0100 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> Message-ID: <6Dw5o.72330$Ds3.63060@hurricane> "Alain Ketterlin" wrote in message news:877hkdhyl5.fsf at dpt-info.u-strasbg.fr... > Lawrence D'Oliveiro writes: > >> Say a vector V is a tuple of 3 numbers, not all zero. You want to >> normalize >> it (scale all components by the same factor) so its magnitude is 1. >> >> The usual way is something like this: >> >> L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) >> V = (V[0] / L, V[1] / L, V[2] / L) > Your best bet is to define a function that does the normalization. Your > (local) name will disappear at the end of the call. If you want it to > work for any vector size: > > def norm(V): > L = math.sqrt( sum( [x**2 for x in V] ) ) > return [ x/L for x in V ] There's a cost involved in using those fancy constructions. I found the following to be about twice as fast, when vectors are known to have 3 elements: def norm3d(v): L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2])) return (v[0]/L,v[1]/L,v[2]/L) (Strangely, changing those divides to multiplies made it slower.) -- Bartc From alain at dpt-info.u-strasbg.fr Mon Aug 2 06:19:36 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Mon, 02 Aug 2010 12:19:36 +0200 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <6Dw5o.72330$Ds3.63060@hurricane> Message-ID: <87fwyxgvuv.fsf@dpt-info.u-strasbg.fr> "Bartc" writes: >> def norm(V): >> L = math.sqrt( sum( [x**2 for x in V] ) ) >> return [ x/L for x in V ] > > There's a cost involved in using those fancy constructions. Sure. The above has three loops that take some time. > I found the following to be about twice as fast, when vectors are > known to have 3 elements: > > def norm3d(v): > L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2])) > return (v[0]/L,v[1]/L,v[2]/L) > > (Strangely, changing those divides to multiplies made it slower.) You mean by setting L to 1.0 / math.sqrt(...) and using v[0]*L etc.? I think * and / have the same cost on floats, and the added / adds some cost. But what you observe is probably caused by the overloading of "*", that needs more type checks. You may try with operator.mul to see if the call compensates the cost of type checking, but I doubt it. -- Alain. From alanwilter at gmail.com Mon Aug 2 06:37:05 2010 From: alanwilter at gmail.com (Alan) Date: Mon, 2 Aug 2010 11:37:05 +0100 Subject: python3: signal.signal/singal.alarm not working as expected Message-ID: Hi there, I have this example code to illustrate a problem I am having with python3. It works fine with python 2.6 and 2.7 but does not with python 3.1. Please, can someone tell me why or how to fix this example? from __future__ import print_function import os, subprocess, signal def signal_handler( signum, frame ): print( "PID: %s" % pid ) print( "Timed out! Process %s killed, max exec time (%ss) exceeded" % (pid, timeTol ) ) os.kill( int( pid ), 15 ) raise Exception( "Taking too long to finish... aborting!" ) if __name__ == '__main__': timeTol = 5 cmd = 'find /' signal.signal(signal.SIGALRM, signal_handler) signal.alarm(timeTol) p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout = subprocess.PIPE) pid = p.pid out = str( p.communicate()[0].decode() ) print(out) Many thanks, Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From bartc at freeuk.com Mon Aug 2 07:32:41 2010 From: bartc at freeuk.com (Bartc) Date: Mon, 2 Aug 2010 12:32:41 +0100 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr><6Dw5o.72330$Ds3.63060@hurricane> <87fwyxgvuv.fsf@dpt-info.u-strasbg.fr> Message-ID: <02y5o.243$e47.58@hurricane> "Alain Ketterlin" wrote in message news:87fwyxgvuv.fsf at dpt-info.u-strasbg.fr... > "Bartc" writes: >> def norm3d(v): >> L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2])) >> return (v[0]/L,v[1]/L,v[2]/L) >> >> (Strangely, changing those divides to multiplies made it slower.) > > You mean by setting L to 1.0 / math.sqrt(...) and using v[0]*L etc.? Yes. > I think * and / have the same cost on floats, and the added / adds > some cost. I expected no measurable difference, not running Python anyway (I tried it in gcc and using divides increased runtimes by 50%, corresponding to some 1% for Python). I would naturally have written it using multiplies, and was just surprised at a 3-4% slowdown. > But what you observe is probably caused by the overloading of > "*", that needs more type checks. That sounds reasonable. -- Bartc From chare at labr.net Mon Aug 2 07:46:05 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 06:46:05 -0500 Subject: beginner python GUI question In-Reply-To: References: Message-ID: <283352C2-4A6B-470D-B82C-12D2F130578B@labr.net> On Aug 1, 2010, at 8:33 PM, rechardchen wrote: > ? 2010-8-2 6:15, Chris Hare ??: >> I hope I can explain this correctly. >> >> I have a GUI, which is already being processed by a mainloop. I want to be able to open a second window so the user can interact with specific information in the second window. I pulled together this code example >> >> from Tkinter import * >> >> class Net: >> def __init__(self,tkWin): >> self.window = tkWin >> def show(self,t): >> self.l = Label(self.window,text=t) >> self.l.grid() >> button = Button(self.window, text="Again") >> button.bind("", self.Again) >> button.grid() >> def Again(self,event): >> win3 = Tk() >> x = Net(win3) >> x.show("window 3") >> >> root = Tk() >> root.title = "test" >> f = Frame(root,bg="Yellow") >> l = Label(f,text="window 1") >> f.grid() >> l.grid() >> >> win2 = Tk() >> x = Net(win2) >> x.show("window 2") >> if __name__ == "__main__": >> root.mainloop() >> >> Is this the right way to do things, or would you suggest something different? >> >> Thanks, >> Chris >> > Using Tkinter.Toplevel may be better. :) > -- > http://mail.python.org/mailman/listinfo/python-list I thought that would be a good idea, so I changed the code a bit to this: from Tkinter import * class Net: def __init__(self): self.window = Toplevel() def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text="Again") button.bind("", self.Again) button2 = Button(self.window, text="Dismiss") button2.bind("", self.window.destroy) button.grid() button2.grid() def Again(self,event): x = Net() x.show("window 3") root = Tk() root.title = "test" f = Frame(root,bg="Yellow") l = Label(f,text="window 1") f.grid() l.grid() x = Net() x.show("window 2") if __name__ == "__main__": root.mainloop() I put the call to Topevel into the Class. This however, gets me an error message Traceback (most recent call last): File "a.py", line 27, in x = Net() File "a.py", line 5, in __init__ self.window = Toplevel() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1978, in __init__ self.title(root.title()) TypeError: 'str' object is not callable I should think it would work, but I don't understand why it doesn't. Thanks From santiago.caracol at gmail.com Mon Aug 2 08:12:37 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Mon, 2 Aug 2010 05:12:37 -0700 (PDT) Subject: run subprocesses in parallel Message-ID: Hello, I want to run several subprocesses. Like so: p1 = Popen("mycmd1" + " myarg", shell=True) p2 = Popen("mycmd2" + " myarg", shell=True) ... pn = Popen("mycmdn" + " myarg", shell=True) What would be the most elegant and secure way to run all n subprocesses in parallel? Santiago From lists at cheimes.de Mon Aug 2 08:21:38 2010 From: lists at cheimes.de (Christian Heimes) Date: Mon, 02 Aug 2010 14:21:38 +0200 Subject: run subprocesses in parallel In-Reply-To: References: Message-ID: > I want to run several subprocesses. Like so: > > p1 = Popen("mycmd1" + " myarg", shell=True) > p2 = Popen("mycmd2" + " myarg", shell=True) > .... > pn = Popen("mycmdn" + " myarg", shell=True) > > What would be the most elegant and secure way to run all n > subprocesses in parallel? They already run in parallel. Depending on your command this may not be secure due to race conditions. You might want to drop shell=True and use a list as arguments instead. The shell=True argument is frowned upon and should only be used if your really, really need a shell. From __peter__ at web.de Mon Aug 2 08:25:49 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Aug 2010 14:25:49 +0200 Subject: beginner python GUI question References: Message-ID: Chris Hare wrote: >>> root = Tk() >>> root.title = "test" > I should think it would work, but I don't understand why it doesn't. Try root.title("test") title() is a method that you are hiding with your attribute leading to problems later on. By the way, what kind of documentation are you using for your efforts? Here's a concise one: http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html Also, effbot.org has a lot of information that you best access via Google. Peter From rechardchen at gmail.com Mon Aug 2 08:31:04 2010 From: rechardchen at gmail.com (rechardchen) Date: Mon, 02 Aug 2010 20:31:04 +0800 Subject: How to catch windows shutdown/reboot message In-Reply-To: References: Message-ID: ? 2010-8-2 16:00, Tim Golden ??: > On 02/08/2010 02:17, rechardchen wrote: >> I'm writing a python script which runs as a windowsxp service. >> The problem is how to catch the windows shutdown/reboot message and do >> some cleaning job when system is going down? >> >> The atexit module and signal module on windows dont seems to work. I >> guess the python win32api may be of help, but I am not familiar with >> it... >> Thank you > > Have a look at the SENS stuff: > > http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html > > TJG Thanks, the extended handler functionality works. :) From nikos.the.gr33k at gmail.com Mon Aug 2 08:32:49 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 2 Aug 2010 05:32:49 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: Steven, First of all thank you for your response. I cant beleive i neglected to import the time module! The only reason that i asked you guys to follow the link was for you to see the actualt coding and error report as python produces it by itself with all the relative characteristics. Of course it was not due to boredom and there was no need to be aggresive with me as this wasn't the case. I thouigh that by giving the URL was easier for you guys. Now the script runs but for some reason only the code block within the 'else' tun each time: This: else: print "??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? ?? ??????! ?? ????? ????? ? ??????? ??????????!!" cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year The cookie is only get set and never expires i changed the if with this if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist but still no luck. As for the encoding Notepad++, which is what i use for an editor say its UTF-8 without BOM. Isn't this what i'm supposed to use? My Python scripts only containes english and greek letters, so i though usign UTF-8 is the way to go. No?! Please if you explain to me in greater detail! From chare at labr.net Mon Aug 2 08:49:38 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 07:49:38 -0500 Subject: beginner python GUI question In-Reply-To: References: Message-ID: <5200041A-5B00-4E95-8229-0DD1C5078229@labr.net> On Aug 2, 2010, at 7:25 AM, Peter Otten wrote: > Chris Hare wrote: > >>>> root = Tk() >>>> root.title = "test" > >> I should think it would work, but I don't understand why it doesn't. > > Try > > root.title("test") > > title() is a method that you are hiding with your attribute leading to > problems later on. > > By the way, what kind of documentation are you using for your efforts? > > Here's a concise one: > > http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html > > Also, effbot.org has a lot of information that you best access via Google. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list I have several python books and I have been using effbot and various other sources. Thanks for the help. Your suggestion (and a couple others I added) got my example working exactly like I want it, so I can incorporate that into my program. Thanks again. Chris From flebber.crue at gmail.com Mon Aug 2 09:13:46 2010 From: flebber.crue at gmail.com (flebber) Date: Mon, 2 Aug 2010 06:13:46 -0700 (PDT) Subject: Mechanize - save to XML or CSV Message-ID: <1c0fcd51-4097-492f-891e-f224556ab62f@n19g2000prf.googlegroups.com> HI guys and gals this is probably a simple question but I can't find the answer directly in the docs for python mechanize. http://pypi.python.org/pypi/mechanize/ Is it possible to retrieve and save a web page data as xml or a csv file? From simon at brunningonline.net Mon Aug 2 09:41:20 2010 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 2 Aug 2010 14:41:20 +0100 Subject: Mechanize - save to XML or CSV In-Reply-To: <1c0fcd51-4097-492f-891e-f224556ab62f@n19g2000prf.googlegroups.com> References: <1c0fcd51-4097-492f-891e-f224556ab62f@n19g2000prf.googlegroups.com> Message-ID: On 2 August 2010 14:13, flebber wrote: > HI guys and gals this is probably a simple question but I can't find > the answer directly in the docs for python mechanize. > > http://pypi.python.org/pypi/mechanize/ > > Is it possible to retrieve and save a web page data as xml or a csv > file? Sure, but mechanize only does the first half of the job. You retrieve the data using mechanize, then use another module for the save-as bit. ElementTree for XML and csv for, um, for csv are both in the standard library. -- Cheers, Simon B. From invalid at invalid.invalid Mon Aug 2 10:42:21 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 2 Aug 2010 14:42:21 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 2010-08-02, Christian Heimes wrote: > In your opinion what would Python gain from a C++ implementation? Greater buzzword-compliance -- an important characteristic highly prized by Human-Resources poeple and mid-level managers here in the US. ;) -- Grant From amyjack1 at rediffmail.com Mon Aug 2 10:48:19 2010 From: amyjack1 at rediffmail.com (amyjack1 at rediffmail.com) Date: Mon, 2 Aug 2010 07:48:19 -0700 (PDT) Subject: AMY JACKSON HOT PICTURES including upcoming movies, biography, Message-ID: <1cb19434-2cf2-40d2-8e90-bb68ae6a25be@l32g2000prn.googlegroups.com> AMY JACKSON HOT PICTURES including upcoming movies, biography, http://amyjacksons.blogspot.com From megerea at gmail.com Mon Aug 2 11:00:39 2010 From: megerea at gmail.com (Mallan4) Date: Mon, 2 Aug 2010 08:00:39 -0700 (PDT) Subject: Simple Data Entry Work Message-ID: Hi there you need a job to work at the comfort of your home, here are the two links to earn you the money you want Note:you have to be hard working in order to earn big,give it a try and register, you have nothing to loose no registration charges http://www.dataentrywork.net/?id=27096 http://www.websitetester.biz/index.php?lang=en&ref=6a823270ced424cbba5ff86b04eeb5f2 join our team and get started to receive forms to fill up then submit and earn more money as much as you want!.. Registration is for free as we also need someone who are looking for an opportunity to be successful!. You have an option to choose your method of payment, either PayPal or Wire Transfer. From breamoreboy at yahoo.co.uk Mon Aug 2 11:21:33 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 16:21:33 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 01/08/2010 12:10, Lawrence D'Oliveiro wrote: > In message, Mark > Lawrence wrote: > >> On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: >> >>> In message, Mark >>> Lawrence wrote: >>> >>>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >>>> >>>>> In message, Mark >>>>> Lawrence wrote: >>>>> >>>>>> Personally I find double clicking on an msi file rather easier. >>>>> >>>>> Easier than apt-get dist-upgrade? >>>> >>>> I'm sorry but I only do English, could you please translate. :) >>> >>> I run Debian Unstable, which has new goodies coming out on a weekly >>> basis. The last time I checked for updates, there were over 500 packages >>> I had installed for which updates were available. It only took a command >>> like the above to upgrade them all. >>> >>> How many .msi files would you have to click on to achieve the Windows >>> equivalent? >> >> ... I simply couldn't cope with over 500 installed packages. > > Precisely my point. Go back to playing with your .msi toys. > > Oh, and. Repeating what was obviously deliberately snipped. "No idea, but your mental capacity is clearly infinitely higher than mine, as I simply couldn't cope with over 500 installed packages. What do they all do, make your lunch and fetch the beer from the fridge amongst other things?" How does any user or an admin cope with 500 packages? Can Python help here, assume an eight hour working day? c:\Python31\Lib>python Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 8*60*60/500 57.6 So every working day you have 57.6 seconds to use each package. Strangely I don't think anyone will get too much done. Am I in cloud cuckoo land or are you? As it happens, I'm also not a windows fan, did most of my work on VMS. Which to repeat myself stands for Very Much Safer. Thinking of which did *nix ever get around to providing proper clustering, or does VMS still rule? Mark Lawrence. From breamoreboy at yahoo.co.uk Mon Aug 2 11:35:53 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 16:35:53 +0100 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <4C568E92.50907@sequans.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> <7xmxt5357h.fsf@ruckus.brouhaha.com> <4C568E92.50907@sequans.com> Message-ID: On 02/08/2010 10:23, Jean-Michel Pichavant wrote: > Paul Rubin wrote: >> Michele Simionato writes: >>> I am actually more radical than that. From >>> http://www.artima.com/weblogs/viewpost.jsp?thread=237121: >>> In this series I have argued that super is tricky; I think nobody can... >> >> When I look at that URL, I see a Java stack dump: >> >> java.lang.RuntimeException: >> com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid >> at >> com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112) >> >> ... >> >> Seems appropriate. > remove the ending double dot. > > JM aka the colon. :) Cheers. Mark Lawrence From breamoreboy at yahoo.co.uk Mon Aug 2 11:37:05 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 16:37:05 +0100 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> Message-ID: On 02/08/2010 07:15, Michele Simionato wrote: > On Jul 31, 5:08 am, Steven D'Aprano cybersource.com.au> wrote: >> I have read Michelle Simionato's articles on super in Python. > > One "l" please! I am a man! ;-) > Please prove it, get your bits out!!! :) > > M. Simionato From benjamin.kaplan at case.edu Mon Aug 2 11:41:20 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 2 Aug 2010 08:41:20 -0700 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On Mon, Aug 2, 2010 at 8:21 AM, Mark Lawrence wrote: > On 01/08/2010 12:10, Lawrence D'Oliveiro wrote: > >> In message, Mark >> Lawrence wrote: >> >> On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: >>> >>> In message, Mark >>>> Lawrence wrote: >>>> >>>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >>>>> >>>>> In message, Mark >>>>>> Lawrence wrote: >>>>>> >>>>>> Personally I find double clicking on an msi file rather easier. >>>>>>> >>>>>> >>>>>> Easier than apt-get dist-upgrade? >>>>>> >>>>> >>>>> I'm sorry but I only do English, could you please translate. :) >>>>> >>>> >>>> I run Debian Unstable, which has new goodies coming out on a weekly >>>> basis. The last time I checked for updates, there were over 500 packages >>>> I had installed for which updates were available. It only took a command >>>> like the above to upgrade them all. >>>> >>>> How many .msi files would you have to click on to achieve the Windows >>>> equivalent? >>>> >>> >>> ... I simply couldn't cope with over 500 installed packages. >>> >> >> Precisely my point. Go back to playing with your .msi toys. >> >> Oh, and. >> > > Repeating what was obviously deliberately snipped. > > "No idea, but your mental capacity is clearly infinitely higher than mine, > as I simply couldn't cope with over 500 installed packages. What do they > all do, make your lunch and fetch the beer from the fridge amongst other > things?" > > How does any user or an admin cope with 500 packages? Can Python help > here, assume an eight hour working day? > > c:\Python31\Lib>python > Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> 8*60*60/500 > 57.6 > > So every working day you have 57.6 seconds to use each package. Strangely I > don't think anyone will get too much done. Am I in cloud cuckoo land or are > you? > > You seem to be mistaken as to what a "package" is. Python : * python * python-minimal * python2.6 * libbz2 * libc6 * libdb4.8 * libncursesw5 * libreadline6 * mime-support * python2.6-minimal * libssl0.9.8 * zlib1g * debconf * perl-base * dpkg * coreutils * lzma * libacl1 * libattr1 * libselinux1 * libgcc1 * libstdc++6 * gcc-4.4-base * libncurses5 * readline-common So these are the packages needed just to run Python in Ubuntu. It doesn't include the packages required for the kernel, the desktop environment, the window manager, the terminal, and whatever else you want running. In my fairly clean Ubuntu VM (I use it almost exclusively for testing), I have close to 1500 packages installed. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From magguru.chinnamnaidu at gmail.com Mon Aug 2 11:50:12 2010 From: magguru.chinnamnaidu at gmail.com (paypal cash) Date: Mon, 2 Aug 2010 08:50:12 -0700 (PDT) Subject: THANKS GOD! I GOT $2000 FROM PAYPAL.... Message-ID: <23d822e9-d554-4c35-b1af-c19fba0722d4@v35g2000prn.googlegroups.com> THANKS GOD! I GOT $2000 FROM PAYPAL At http://ukcollegegirls.co.cc I have hidden the PayPal Form link in an image. in that website On Top Side Above search box , click on image and enter your PayPal id And Your name. From cournape at gmail.com Mon Aug 2 12:11:44 2010 From: cournape at gmail.com (David Cournapeau) Date: Tue, 3 Aug 2010 01:11:44 +0900 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On Mon, Aug 2, 2010 at 10:20 AM, Christian Heimes wrote: > > In your opinion what would Python gain from a C++ implementation? The elusive advantages of "OO" in C++ are relatively minor compared to RIIA which would make reference counting much easier to deal with. But even that is not a strong enough argument for C++. The little C++ we have in scipy had causes a lot of headache - C++ portability is still an issue once you are outside the 4-5 main OS/Compilers combinations, David From thomas at jollans.com Mon Aug 2 12:15:53 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 18:15:53 +0200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4C56EF39.2060600@jollans.com> On 08/02/2010 04:42 PM, Grant Edwards wrote: > On 2010-08-02, Christian Heimes wrote: > >> In your opinion what would Python gain from a C++ implementation? > > Greater buzzword-compliance -- an important characteristic highly > prized by Human-Resources poeple and mid-level managers here in the > US. > > ;) > C++Python would never beat IronPython on that front From breamoreboy at yahoo.co.uk Mon Aug 2 12:27:22 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 17:27:22 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 02/08/2010 16:41, Benjamin Kaplan wrote: > On Mon, Aug 2, 2010 at 8:21 AM, Mark Lawrencewrote: > >> On 01/08/2010 12:10, Lawrence D'Oliveiro wrote: >> >>> In message, Mark >>> Lawrence wrote: >>> >>> On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: >>>> >>>> In message, Mark >>>>> Lawrence wrote: >>>>> >>>>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >>>>>> >>>>>> In message, Mark >>>>>>> Lawrence wrote: >>>>>>> >>>>>>> Personally I find double clicking on an msi file rather easier. >>>>>>>> >>>>>>> >>>>>>> Easier than apt-get dist-upgrade? >>>>>>> >>>>>> >>>>>> I'm sorry but I only do English, could you please translate. :) >>>>>> >>>>> >>>>> I run Debian Unstable, which has new goodies coming out on a weekly >>>>> basis. The last time I checked for updates, there were over 500 packages >>>>> I had installed for which updates were available. It only took a command >>>>> like the above to upgrade them all. >>>>> >>>>> How many .msi files would you have to click on to achieve the Windows >>>>> equivalent? >>>>> >>>> >>>> ... I simply couldn't cope with over 500 installed packages. >>>> >>> >>> Precisely my point. Go back to playing with your .msi toys. >>> >>> Oh, and. >>> >> >> Repeating what was obviously deliberately snipped. >> >> "No idea, but your mental capacity is clearly infinitely higher than mine, >> as I simply couldn't cope with over 500 installed packages. What do they >> all do, make your lunch and fetch the beer from the fridge amongst other >> things?" >> >> How does any user or an admin cope with 500 packages? Can Python help >> here, assume an eight hour working day? >> >> c:\Python31\Lib>python >> Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit >> (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> 8*60*60/500 >> 57.6 >> >> So every working day you have 57.6 seconds to use each package. Strangely I >> don't think anyone will get too much done. Am I in cloud cuckoo land or are >> you? >> >> > You seem to be mistaken as to what a "package" is. > > Python : > * python > * python-minimal > * python2.6 > * libbz2 > * libc6 > * libdb4.8 > * libncursesw5 > * libreadline6 > * mime-support > * python2.6-minimal > * libssl0.9.8 > * zlib1g > * debconf > * perl-base > * dpkg > * coreutils > * lzma > * libacl1 > * libattr1 > * libselinux1 > * libgcc1 > * libstdc++6 > * gcc-4.4-base > * libncurses5 > * readline-common > > So these are the packages needed just to run Python in Ubuntu. It doesn't > include the packages required for the kernel, the desktop environment, the > window manager, the terminal, and whatever else you want running. In my > fairly clean Ubuntu VM (I use it almost exclusively for testing), I have > close to 1500 packages installed. > >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > I'll stick with my msi files and/or windows update then, unless I have the luck to get back to VMS. As I said earlier it strikes me that this *nix stuff is simply archaic. Kindest regards. Mark Lawrence. From ethan at stoneleaf.us Mon Aug 2 12:37:51 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 02 Aug 2010 09:37:51 -0700 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <4c552483$0$11091$c3e8da3@news.astraweb.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <8bfd5uF9gqU1@mid.individual.net> <4c52bc2d$0$11091$c3e8da3@news.astraweb.com> <8bhfcaF6ftU1@mid.individual.net> <4c53936d$0$11091$c3e8da3@news.astraweb.com> <4c552483$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C56F45F.2010509@stoneleaf.us> Steven D'Aprano wrote: > On Sat, 31 Jul 2010 13:29:25 +0000, Brian Victor wrote: > >> Steven D'Aprano wrote: >>> On Sat, 31 Jul 2010 14:25:39 +1200, Gregory Ewing wrote: >>> >>>> Steven D'Aprano wrote: >>>> >>>>> A >>>>> / \ >>>>> C B >>>>> \ / >>>>> D >>>>> / \ >>>>> E F >>>>> >>>>> Yes, a super call might jog left from C to B, but only when being >>>>> called from one of the lower classes D-F. That's still an upwards >>>>> call relative to the originator, not sidewards. >>>> But it's not an upward call relative to the class mentioned in the >>>> super() call, which is why I say it's misleading. >>> Which class would that be? >>> >>> I think I'm going to need an example that demonstrates what you mean, >>> because I can't make heads or tails of it. Are you suggesting that a >>> call to super(C, self).method() from within C might call >>> B.method(self)? >> Yes, it would. > [snip example] > > Right, now I see what you mean. I don't have a problem with that > behaviour, it is the correct behaviour, and you are making the call from > D in the first place, so it *must* call B at some point. > > If you initiate the call from C instead: [snip] I think the point is that when D initiates the super() chain, and C calls super, B will then get its turn -- which has to seem arbitrary from C's point of view. ~Ethan~ From doug.garstang at gmail.com Mon Aug 2 12:42:09 2010 From: doug.garstang at gmail.com (Douglas Garstang) Date: Mon, 2 Aug 2010 09:42:09 -0700 Subject: Merging two dictionaries In-Reply-To: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> References: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> Message-ID: On Mon, Aug 2, 2010 at 12:47 AM, Paul Rubin wrote: > Douglas Garstang writes: >> default = {... >> ? ? ? ? ? ? ? ? 'data_sources': { ... >> cluster = {... >> ? ? ? ? ? ? ? ? 'data_source': { ... > > Did you want both of those to say the same thing instead of one > of them being 'data_source' and the other 'data_sources' ? > > If yes, then the following works for me: > > ? ?def merge(cluster, default): > ? ? ? ?# destructively merge default into cluster > ? ? ? ?for k,v in cluster.iteritems(): > ? ? ? ? ? ?if k in default and type(v)==dict: > ? ? ? ? ? ? ? ?assert type(default(k))==dict > ? ? ? ? ? ? ? ?merge(v,default[k]) > ? ? ? ?for k,v in default.iteritems(): > ? ? ? ? ? ?if k not in cluster: > ? ? ? ? ? ? ? ?cluster[k] = v > -- > http://mail.python.org/mailman/listinfo/python-list > Hmmm, using that gives me: Traceback (most recent call last): File "./test4.py", line 48, in ? merge(cluster, default) File "./test4.py", line 42, in merge assert type(default(k))==dict TypeError: 'dict' object is not callable where line 42 is 'assert type(default(k))==dict', and the inputs are: default = { 'cluster': { 'platform': { 'elements': { 'data_sources': { 'elements': { 'db_min_pool_size': 10 }, }, }, }, } } cluster = { 'cluster': { 'name': 'Customer 1', 'description': 'Customer Production', 'environment': 'production', 'platform': { 'elements': { 'data_source': { 'elements': { 'username': 'username', 'password': 'password' }, }, }, }, } } and it's called with: merge(cluster, default) Doug. From __peter__ at web.de Mon Aug 2 12:50:52 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Aug 2010 18:50:52 +0200 Subject: Merging two dictionaries References: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> Message-ID: Douglas Garstang wrote: > On Mon, Aug 2, 2010 at 12:47 AM, Paul Rubin wrote: >> If yes, then the following works for me: >> >> def merge(cluster, default): >> # destructively merge default into cluster >> for k,v in cluster.iteritems(): >> if k in default and type(v)==dict: >> assert type(default(k))==dict >> merge(v,default[k]) >> for k,v in default.iteritems(): >> if k not in cluster: >> cluster[k] = v >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Hmmm, using that gives me: > > Traceback (most recent call last): > File "./test4.py", line 48, in ? > merge(cluster, default) > File "./test4.py", line 42, in merge > assert type(default(k))==dict > TypeError: 'dict' object is not callable > > where line 42 is 'assert type(default(k))==dict', and the inputs are: Not making an attempt to understand the code that you are about to use? default(k) should be default[k] Peter From drobinow at gmail.com Mon Aug 2 12:51:30 2010 From: drobinow at gmail.com (David Robinow) Date: Mon, 2 Aug 2010 12:51:30 -0400 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan wrote: >... > So these are the packages needed just to run Python in Ubuntu. It doesn't > include the packages required for the kernel, the desktop environment, the > window manager, the terminal, and whatever else you want running. In my > fairly clean Ubuntu VM (I use it almost exclusively for testing), I have > close to 1500 packages installed. As an admittedly stupid comparison, I have 1579 DLLs in my \windows\system32 directory. Some number of these have been upgraded by Windows Update. This is XP Service Pack 3. I'm not sure if this means that Windows is better because it has more packages or that it is worse because it's got too many. :) From donn.ingle at gmail.com Mon Aug 2 12:53:39 2010 From: donn.ingle at gmail.com (donn) Date: Mon, 02 Aug 2010 18:53:39 +0200 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> <7xmxt5357h.fsf@ruckus.brouhaha.com> <4C568E92.50907@sequans.com> Message-ID: <4C56F813.2080106@gmail.com> On 02/08/2010 17:35, Mark Lawrence wrote: > aka the colon. :) Ha. This is a case of the colon being the appendix! \d From doug.garstang at gmail.com Mon Aug 2 12:59:07 2010 From: doug.garstang at gmail.com (Douglas Garstang) Date: Mon, 2 Aug 2010 09:59:07 -0700 Subject: Merging two dictionaries In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 1:09 AM, Peter Otten <__peter__ at web.de> wrote: > Douglas Garstang wrote: > >> I have the two dictionaries below. How can I merge them, such that: >> >> 1. The cluster dictionary contains the additional elements from the >> default dictionary. >> 2. Nothing is removed from the cluster dictionary. > > def inplace_merge(default, cluster): > ? ?assert isinstance(default, dict) > ? ?assert isinstance(cluster, dict) > > ? ?d = set(default) > ? ?c = set(cluster) > ? ?default_only = d - c > ? ?both = d & c > ? ?for key in both: > ? ? ? ?dv = default[key] > ? ? ? ?cv = cluster[key] > ? ? ? ?if isinstance(cv, dict): > ? ? ? ? ? ?inplace_merge(dv, cv) > ? ?cluster.update((dk, default[dk]) for dk in default_only) > > should work once you've fixed your example dicts. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > Wooo! I think that did it! From nobody at nowhere.com Mon Aug 2 13:10:06 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 02 Aug 2010 18:10:06 +0100 Subject: run subprocesses in parallel References: Message-ID: On Mon, 02 Aug 2010 14:21:38 +0200, Christian Heimes wrote: > You might want to drop shell=True and use > a list as arguments instead. The two issues (whether "shell" is True/False and whether the command is a list or string) are orthogonal. You should always use a list for the command, unless you are given a string (e.g. by the user) which must be executed verbatim. > The shell=True argument is frowned upon and > should only be used if your really, really need a shell. It's the use of a string (rather than a list) for the command which is particularly frowned upon, as this tends to be error prone if any of the arguments contain characters which are significant to the shell (most commonly spaces, although other characters are also problematic). On Unix, using a list for the command effectively necessitates that shell=False (if you use a list with shell=True, the first element in the list is executed as the command, with any remaining elements used to initialise $1, $2, etc). On Windows, the list is converted to a string in the same way regardless of whether shell is True or False. The shell parameter determines whether the string is passed directly to CreateProcess or whether it has "%COMSPEC% /c " prepended to it. If shell is False, the first element in the list (the program) must refer to a binary executable and include the .exe (etc) extension. If shell is True, the program can be a batch file, Python script, etc, and will be executed according to its extension. From aahz at pythoncraft.com Mon Aug 2 13:29:03 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2010 10:29:03 -0700 Subject: Accumulate function in python References: <94c7c397-d644-4909-8b4b-709a9728901e@y21g2000pro.googlegroups.com> <7xpqyjgvjm.fsf@ruckus.brouhaha.com> Message-ID: In article <7xpqyjgvjm.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >I think Peter Otten's solution involving a generator is the one most in >the current Python spirit. It's cleaner (for my tastes) than the ones >that use things like list.append. Agreed -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From no.email at nospam.invalid Mon Aug 2 13:31:55 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 02 Aug 2010 10:31:55 -0700 Subject: Merging two dictionaries References: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> Message-ID: <7xvd7ssyyc.fsf@ruckus.brouhaha.com> Douglas Garstang writes: > where line 42 is 'assert type(default(k))==dict', and the inputs are: Woops, cut and paste error. default(k) should say default[k]. Or you could remove the assertion altogether. From nagle at animats.com Mon Aug 2 13:34:25 2010 From: nagle at animats.com (John Nagle) Date: Mon, 02 Aug 2010 10:34:25 -0700 Subject: Behavior of re.split on empty strings is unexpected Message-ID: <4c5701a0$0$1638$742ec2ed@news.sonic.net> The regular expression "split" behaves slightly differently than string split: >>> import re >>> kresplit = re.compile(r'[^\w\&]+',re.UNICODE) >>> kresplit2.split(" HELLO THERE ") ['', 'HELLO', 'THERE', ''] >>> kresplit2.split("VERISIGN INC.") ['VERISIGN', 'INC', ''] I'd thought that "split" would never produce an empty string, but it will. The regular string split operation doesn't yield empty strings: >>> " HELLO THERE ".split() ['HELLO', 'THERE'] If I try to get the functionality of string split with re: >>> s2 = " HELLO THERE " >>> kresplit4 = re.compile(r'\W+', re.UNICODE) >>> kresplit4.split(s2) ['', 'HELLO', 'THERE', ''] I still get empty strings. The documentation just describes re.split as "Split string by the occurrences of pattern", which is not too helpful. John Nagle From maj_sawalha at yahoo.com Mon Aug 2 13:46:11 2010 From: maj_sawalha at yahoo.com (Majdi Sawalha) Date: Mon, 2 Aug 2010 10:46:11 -0700 (PDT) Subject: constructing and using large lexicon in a program Message-ID: <119487.45857.qm@web113614.mail.gq1.yahoo.com> Dear List members, I am developing a morphological analyzer that depends on a large lexicon. i construct a Lexicon class that reades a text file?and construct a dictionary of the lexicon entries.? the other class will use the lexicon class to chech if the word is found in the lexicon. the problem that this takes long time as?each time?an object of that class created, then?it needs to call the lexicon many times. then when the lexicon is called it re-construct the lexicon again. is there any way to construct the lexicon one time during the?execution of the program? and then the other modules will?search the already?constructed?lexicon. best regards Majdi ? Faculty of Engineering School of Computing University of Leeds Leeds, LS2 9JT UK http://www.comp.leeds.ac.uk/sawalha -------------- next part -------------- An HTML attachment was scrubbed... URL: From torriem at gmail.com Mon Aug 2 13:52:42 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 02 Aug 2010 11:52:42 -0600 Subject: constructing and using large lexicon in a program In-Reply-To: <119487.45857.qm@web113614.mail.gq1.yahoo.com> References: <119487.45857.qm@web113614.mail.gq1.yahoo.com> Message-ID: <4C5705EA.50705@gmail.com> On 08/02/2010 11:46 AM, Majdi Sawalha wrote: > I am developing a morphological analyzer that depends on a large lexicon. i > construct a Lexicon class that reades a text file and construct a dictionary of > the lexicon entries. > the other class will use the lexicon class to chech if the word is found in the > lexicon. the problem that this takes long time as each time an object of that > class created, then it needs to call the lexicon many times. then when the > lexicon is called it re-construct the lexicon again. is there any way to > construct the lexicon one time during the execution of the program? and then the > other modules will search the already constructed lexicon. Can you not create a module that, upon import, initializes this lexicon as a module attribute? Modules are by definition singleton objects, which is the pattern that you probably need. Any other module could import this module and get the already-created lexicon object. From __peter__ at web.de Mon Aug 2 14:01:21 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Aug 2010 20:01:21 +0200 Subject: Behavior of re.split on empty strings is unexpected References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > The regular string split operation doesn't yield empty strings: > > >>> " HELLO THERE ".split() > ['HELLO', 'THERE'] Note that invocation without separator argument (or None as the separator) is special in that respect: >>> " hello there ".split(" ") ['', 'hello', 'there', ''] Peter From python at mrabarnett.plus.com Mon Aug 2 14:02:47 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 02 Aug 2010 19:02:47 +0100 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <4c5701a0$0$1638$742ec2ed@news.sonic.net> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: <4C570847.6030906@mrabarnett.plus.com> John Nagle wrote: > The regular expression "split" behaves slightly differently than string > split: > > >>> import re > >>> kresplit = re.compile(r'[^\w\&]+',re.UNICODE) > > >>> kresplit2.split(" HELLO THERE ") > ['', 'HELLO', 'THERE', ''] > > >>> kresplit2.split("VERISIGN INC.") > ['VERISIGN', 'INC', ''] > > I'd thought that "split" would never produce an empty string, but > it will. > > The regular string split operation doesn't yield empty strings: > > >>> " HELLO THERE ".split() > ['HELLO', 'THERE'] > Yes it does. >>> " HELLO THERE ".split(" ") ['', '', '', 'HELLO', '', '', '', 'THERE', '', '', ''] > If I try to get the functionality of string split with re: > > >>> s2 = " HELLO THERE " > >>> kresplit4 = re.compile(r'\W+', re.UNICODE) > >>> kresplit4.split(s2) > ['', 'HELLO', 'THERE', ''] > > I still get empty strings. > > The documentation just describes re.split as "Split string by the > occurrences of pattern", which is not too helpful. > It's the plain str.split() which is unusual in that: 1. it splits on sequences of whitespace instead of one per occurrence; 2. it discards leading and trailing sequences of whitespace. Compare: >>> " A B ".split(" ") ['', '', 'A', '', 'B', '', ''] with: >>> " A B ".split() ['A', 'B'] It just happens that the unusual one is the most commonly used one, if you see what I mean! :-) From benjamin.kaplan at case.edu Mon Aug 2 14:14:07 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 2 Aug 2010 11:14:07 -0700 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On Mon, Aug 2, 2010 at 9:51 AM, David Robinow wrote: > On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan > wrote: > >... > > So these are the packages needed just to run Python in Ubuntu. It doesn't > > include the packages required for the kernel, the desktop environment, > the > > window manager, the terminal, and whatever else you want running. In my > > fairly clean Ubuntu VM (I use it almost exclusively for testing), I have > > close to 1500 packages installed. > As an admittedly stupid comparison, I have 1579 DLLs in my > \windows\system32 directory. > Some number of these have been upgraded by Windows Update. This is XP > Service Pack 3. > I'm not sure if this means that Windows is better because it has more > packages or that it is worse because it's got too many. :) > -- > A package is usually more than one file. http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Mon Aug 2 15:33:25 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 14:33:25 -0500 Subject: namespaces, scoping and variables Message-ID: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> I am having a problem getting around this variable namespace thing. Consider these code bits File a.py from Tkinter import * import a1 def doAgain(): x = a1.Net() x.show("Again!") root = Tk() root.title("test") f = Frame(root,bg="Yellow") l = Button(root,text="window 1",command=doAgain) f.grid() l.grid() a = 5 x = a1.Net() x.show("window 2") if __name__ == "__main__": root.mainloop() File a1.py from Tkinter import * class Net: def __init__(self): self.window = Toplevel() def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text="Again") button.bind("", self.Again) button2 = Button(self.window, text="Dismiss") button2.bind("", self.hide) button.grid() button2.grid() def Again(self,event): x = Net() x.show(a) def hide(self,event): self.window.destroy() When I run a.py, it imports a1.py and click on the Again button, I get the error Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ return self.func(*args) File "/Volumes/Development/py/a1.py", line 17, in Again x.show(a) NameError: global name 'a' is not defined I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using global a in a1.py doesn't change anything. since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. Thanks, Chris From nagle at animats.com Mon Aug 2 15:41:13 2010 From: nagle at animats.com (John Nagle) Date: Mon, 02 Aug 2010 12:41:13 -0700 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: <4c571f58$0$1674$742ec2ed@news.sonic.net> On 8/2/2010 11:02 AM, MRAB wrote: > John Nagle wrote: >> The regular expression "split" behaves slightly differently than >> string split: occurrences of pattern", which is not too helpful. >> > It's the plain str.split() which is unusual in that: > > 1. it splits on sequences of whitespace instead of one per occurrence; That can be emulated with the obvious regular expression: re.compile(r'\W+') > 2. it discards leading and trailing sequences of whitespace. But that can't, or at least I can't figure out how to do it. > It just happens that the unusual one is the most commonly used one, if > you see what I mean! :-) The no-argument form of "split" shouldn't be that much of a special case. John Nagle From thomas at jollans.com Mon Aug 2 15:48:13 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 21:48:13 +0200 Subject: namespaces, scoping and variables In-Reply-To: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> Message-ID: <4C5720FD.2080104@jollans.com> On 08/02/2010 09:33 PM, Chris Hare wrote: > I am having a problem getting around this variable namespace thing. > > Consider these code bits > > File a.py > from Tkinter import * > import a1 > > def doAgain(): > x = a1.Net() > x.show("Again!") > > root = Tk() > root.title("test") > f = Frame(root,bg="Yellow") > l = Button(root,text="window 1",command=doAgain) > f.grid() > l.grid() > a = 5 > x = a1.Net() > x.show("window 2") > if __name__ == "__main__": > root.mainloop() > > File a1.py > from Tkinter import * > > class Net: > def __init__(self): > self.window = Toplevel() > def show(self,t): > self.l = Label(self.window,text=t) > self.l.grid() > button = Button(self.window, text="Again") > button.bind("", self.Again) > button2 = Button(self.window, text="Dismiss") > button2.bind("", self.hide) > button.grid() > button2.grid() > def Again(self,event): > x = Net() > x.show(a) > def hide(self,event): > self.window.destroy() > > > When I run a.py, it imports a1.py and click on the Again button, I get the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "/Volumes/Development/py/a1.py", line 17, in Again > x.show(a) > NameError: global name 'a' is not defined > > I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using > > global a > > in a1.py doesn't change anything. > > since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. "global" in Python isn't the same as "global" in C, or in PHP. "Global" is, in essence, a shorter way of saying "within the scope of this module" -- which keeps the "global" nice and clean. You should probably just pass in the object you call "a" when creating the object that uses it, or when calling the function/method when calling it. If you don't want to do that, you can simply import the module where your global data is stored -- beware of "from XYZ import ...", though - that copies the variables, and won't do you much good here. From thomas at jollans.com Mon Aug 2 15:52:09 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 21:52:09 +0200 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <4c571f58$0$1674$742ec2ed@news.sonic.net> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <4c571f58$0$1674$742ec2ed@news.sonic.net> Message-ID: <4C5721E9.3040307@jollans.com> On 08/02/2010 09:41 PM, John Nagle wrote: > On 8/2/2010 11:02 AM, MRAB wrote: >> John Nagle wrote: >>> The regular expression "split" behaves slightly differently than >>> string split: > occurrences of pattern", which is not too helpful. >>> >> It's the plain str.split() which is unusual in that: >> >> 1. it splits on sequences of whitespace instead of one per occurrence; > > That can be emulated with the obvious regular expression: > > re.compile(r'\W+') > >> 2. it discards leading and trailing sequences of whitespace. > > But that can't, or at least I can't figure out how to do it. [ s in rexp.split(long_s) if s ] > >> It just happens that the unusual one is the most commonly used one, if >> you see what I mean! :-) > > The no-argument form of "split" shouldn't be that much of a special > case. > > John Nagle > From davea at ieee.org Mon Aug 2 15:54:44 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 02 Aug 2010 15:54:44 -0400 Subject: namespaces, scoping and variables In-Reply-To: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> Message-ID: <4C572284.6000906@ieee.org> Chris Hare wrote: > I am having a problem getting around this variable namespace thing. > > Consider these code bits > > File a.py > from Tkinter import * > import a1 > > def doAgain(): > x =1.Net() > x.show("Again!") > > root =k() > root.title("test") > f =rame(root,bg="Yellow") > l =utton(root,text="window 1",command=doAgain) > f.grid() > l.grid() > a = > x =1.Net() > x.show("window 2") > if __name__ ="__main__": > root.mainloop() > > File a1.py > from Tkinter import * > > class Net: > def __init__(self): > self.window =oplevel() > def show(self,t): > self.l =abel(self.window,text=t) > self.l.grid() > button =utton(self.window, text="Again") > button.bind("", self.Again) > button2 =utton(self.window, text="Dismiss") > button2.bind("", self.hide) > button.grid() > button2.grid() > def Again(self,event): > x =et() > x.show(a) > def hide(self,event): > self.window.destroy() > > > When I run a.py, it imports a1.py and click on the Again button, I get the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "/Volumes/Development/py/a1.py", line 17, in Again > x.show(a) > NameError: global name 'a' is not defined > > I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using > > global a > > in a1.py doesn't change anything. > > since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. > > Thanks, > Chris > > > First rule is never have circular referencing between modules. In other words, since a.py imports a1.py, a.py can refer to things in a1.py, but never the other way around. Any time you need to look backwards, find another means. One approach is to create another module c.py as a container to hold those things that both a and a1 need. That way they both import c, and there's no problem. Another approach is to pass the global from a.py into a1.py, and use it that way. And since you only have these two modules, you could just define it in a1.py, and reference it from a.py as a1.a I would point out that using the same name for a module and a global variable is bad practice. it certainly makes it hard to describe in this case. HTH, DaveA From mithrandiragainwiki at mailinator.com Mon Aug 2 15:58:34 2010 From: mithrandiragainwiki at mailinator.com (Mithrandir) Date: Mon, 02 Aug 2010 12:58:34 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 08/01/2010 07:34 PM, Albert Hopkins wrote: > On Mon, 2010-08-02 at 01:08 +0200, candide wrote: >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. >> >> Has it ever been planned to rewrite in C++ the historical implementation >> (of course in an object oriented design) ? > > Disclaimer: I am neither a C nor C++ programmer. In fact I can barely > even program in Python ;-) > > I would propose that in fact most programming languages are implemented > in C. Sun's (Oracle's) Java compiler and runtime are written in ANSI C. > The core of the Gnu Compiler Collection (which includes C++ and > Objective-C compilers) is written in C. The official Ruby is > implemented in C. The Squeak Smalltalk implementation uses C instead of > C++. I can't even think of a programming language that is implemented > in C++ (maybe C++ is). > > C seems to be a good, portable language for writing interpreters and > compilers. > > But I wonder if someone has/has tried to write a programming language in > C++ and what were their experiences. > (Sorry if this is a double post, but apparently my last one didn't go through.) I know that LOLCode has a .NET implementation (1), although it's "very much alpha." And someone was apparently working on a C++ only implementation of LOLCode (2), although that was 3 years ago. LOLCode itself is very much alpha anyway and development seems to be very slow (or dead.) Python has a way of extending it's modules with C or C++ (3). 1: http://lolcode.com/implementations/lolcode.net 2: http://forum.lolcode.com/viewtopic.php?id=14 3: http://docs.python.org/release/2.5.2/ext/intro.html - -- People should read more. https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain "All that is gold does not glitter, not all those who wander are lost; the old that is strong does not wither, deep roots are not reached by the frost. - From the ashes a fire shall be woken, a light from the shadows shall spring; renewed shall be blade that was broken, the crownless again shall be king." -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJMVyNqAAoJEKo37V1xH7gTeOUH/2/KYc4busZbATSB09ZUgW+v BmydxDTZaPQd0B56JWSeUiz0/kZrufdDrVc3XUTNNF2oa8ExW51IgsaZOxn2UJGv ydplycT1axs5hrzDG72v2Oo7/poPDxSsvpF58dBsb0XSI25I+orHKrTQpwvKz9cf x6nzahUoygTbaVqZUyxCW2Tc7Rv4T2gpskssD8sIYqaRNofNnPbf3h3NA+q4LMkR +F2UF3r1RE1jwJhs6RNAvUJBdLrHkA3isRsjQE38l6AioLdeTs2yrRtc+6xUkAig RxR11qLZl5OOer/Jrmg1My0+ZTYGnIcAfChxPh1YnHuYbp+H7doqLjlKIkoXZms= =F9Ou -----END PGP SIGNATURE----- From python at mrabarnett.plus.com Mon Aug 2 16:03:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 02 Aug 2010 21:03:18 +0100 Subject: namespaces, scoping and variables In-Reply-To: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> Message-ID: <4C572486.1030308@mrabarnett.plus.com> Chris Hare wrote: > I am having a problem getting around this variable namespace thing. > > Consider these code bits > > File a.py > from Tkinter import * > import a1 > > def doAgain(): > x = a1.Net() > x.show("Again!") > > root = Tk() > root.title("test") > f = Frame(root,bg="Yellow") > l = Button(root,text="window 1",command=doAgain) > f.grid() > l.grid() > a = 5 > x = a1.Net() > x.show("window 2") > if __name__ == "__main__": > root.mainloop() > > File a1.py > from Tkinter import * > > class Net: > def __init__(self): > self.window = Toplevel() > def show(self,t): > self.l = Label(self.window,text=t) > self.l.grid() > button = Button(self.window, text="Again") > button.bind("", self.Again) > button2 = Button(self.window, text="Dismiss") > button2.bind("", self.hide) > button.grid() > button2.grid() > def Again(self,event): > x = Net() > x.show(a) > def hide(self,event): > self.window.destroy() > > > When I run a.py, it imports a1.py and click on the Again button, I get the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "/Volumes/Development/py/a1.py", line 17, in Again > x.show(a) > NameError: global name 'a' is not defined > > I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using > > global a > > in a1.py doesn't change anything. > > since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. > Why in a database? If you need the modules to share it then you could put it in a shared module and refer to it there: File a.py --------- import my_globals ... my_globals.a = 5 File a1.py ---------- import my_globals ... x.show(my_globals.a) From ethan at stoneleaf.us Mon Aug 2 16:04:01 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 02 Aug 2010 13:04:01 -0700 Subject: namespaces, scoping and variables In-Reply-To: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> Message-ID: <4C5724B1.8060403@stoneleaf.us> Chris Hare wrote: > I am having a problem getting around this variable namespace thing. > > Consider these code bits > > File a.py > from Tkinter import * > import a1 > > def doAgain(): > x = a1.Net() > x.show("Again!") > > root = Tk() > root.title("test") > f = Frame(root,bg="Yellow") > l = Button(root,text="window 1",command=doAgain) > f.grid() > l.grid() > a = 5 > x = a1.Net() > x.show("window 2") > if __name__ == "__main__": > root.mainloop() > > File a1.py > from Tkinter import * > > class Net: > def __init__(self): > self.window = Toplevel() > def show(self,t): > self.l = Label(self.window,text=t) > self.l.grid() > button = Button(self.window, text="Again") > button.bind("", self.Again) > button2 = Button(self.window, text="Dismiss") > button2.bind("", self.hide) > button.grid() > button2.grid() > def Again(self,event): > x = Net() > x.show(a) > def hide(self,event): > self.window.destroy() > > > When I run a.py, it imports a1.py and click on the Again button, I get the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "/Volumes/Development/py/a1.py", line 17, in Again > x.show(a) > NameError: global name 'a' is not defined > > I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using > > global a > > in a1.py doesn't change anything. The global keyword does not make a variable global. It tells the interpreter that the variable in question can be find in the module scope, not the function/method scope. In other words, the variable is global to the module, but not to the whole program. What you'll need to do is pass a into Net when you instanciate it, like so (untested): def doAgain(): x = a1.Net(a) x.show("Again!") and in Net: class Net: def __init__(self, some_number): self.some_number = some_number self.window = Toplevel() . . . def Again(self,event): x = Net(self.some_number) x.show() Keep in mind, though, that if you change a in a.py after you've instanciated Net, your Net instance will not see the change. For the change to show up, a would need to be mutable, and you would have to mutate it. The other option is to change the Net instance's some_number directly (i.e. x.some_number = 9). Hope this helps. ~Ethan~ From chare at labr.net Mon Aug 2 16:12:03 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 15:12:03 -0500 Subject: namespaces, scoping and variables In-Reply-To: <4C572486.1030308@mrabarnett.plus.com> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> <4C572486.1030308@mrabarnett.plus.com> Message-ID: Thanks to everyone for answering my question. I think its clear now. I'll just go the "stuff 'em in a module and import that" route. Chris On Aug 2, 2010, at 3:03 PM, MRAB wrote: > Chris Hare wrote: >> I am having a problem getting around this variable namespace thing. >> Consider these code bits >> File a.py >> from Tkinter import * >> import a1 >> def doAgain(): >> x = a1.Net() >> x.show("Again!") >> root = Tk() >> root.title("test") >> f = Frame(root,bg="Yellow") >> l = Button(root,text="window 1",command=doAgain) >> f.grid() >> l.grid() >> a = 5 >> x = a1.Net() >> x.show("window 2") >> if __name__ == "__main__": >> root.mainloop() >> File a1.py >> from Tkinter import * >> class Net: >> def __init__(self): >> self.window = Toplevel() >> def show(self,t): >> self.l = Label(self.window,text=t) >> self.l.grid() >> button = Button(self.window, text="Again") >> button.bind("", self.Again) >> button2 = Button(self.window, text="Dismiss") >> button2.bind("", self.hide) >> button.grid() >> button2.grid() >> def Again(self,event): >> x = Net() >> x.show(a) >> def hide(self,event): >> self.window.destroy() >> When I run a.py, it imports a1.py and click on the Again button, I get the error >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ >> return self.func(*args) >> File "/Volumes/Development/py/a1.py", line 17, in Again >> x.show(a) >> NameError: global name 'a' is not defined >> I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using >> global a >> in a1.py doesn't change anything. >> since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. > Why in a database? If you need the modules to share it then you could > put it in a shared module and refer to it there: > > File a.py > --------- > import my_globals > ... > my_globals.a = 5 > > > File a1.py > ---------- > import my_globals > ... > x.show(my_globals.a) > -- > http://mail.python.org/mailman/listinfo/python-list From nikos.the.gr33k at gmail.com Mon Aug 2 16:13:21 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 2 Aug 2010 13:13:21 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: <40feea21-78ac-4bcc-903f-046a411c677e@l25g2000prn.googlegroups.com> Hello, any ideas?! From chare at labr.net Mon Aug 2 16:17:36 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 15:17:36 -0500 Subject: how best to clear objects from a frame In-Reply-To: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> References: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> Message-ID: On Aug 1, 2010, at 10:13 PM, rantingrick wrote: > On Aug 1, 7:12 pm, Chris Hare wrote: >> Here is the situation: >> >> I have a window with a bunch of widgets in it. I want to clear the objects in a given frame and recreate them to update them. > > You need to check out the "w.update" and "w.update_idletasks" methods > available on all Tkinter widgets. Just FYI: to remove a widget from > view without destroying it use "w.pack_forget" or "w.grid_forget". > However if you are simply trying to refresh a widget use one of the > update methods. > -- > http://mail.python.org/mailman/listinfo/python-list I will have a look at those. Consider a frame with a label and a button. How do I address the label to change it from another function in the class? From rantingrick at gmail.com Mon Aug 2 16:43:33 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 2 Aug 2010 13:43:33 -0700 (PDT) Subject: namespaces, scoping and variables References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> <4C572486.1030308@mrabarnett.plus.com> Message-ID: <48558d95-aaaa-4a6e-9ffb-68d4f2429c62@w15g2000pro.googlegroups.com> On Aug 2, 3:12?pm, Chris Hare wrote: > Thanks to everyone for answering my question. ?I think its clear now. ?I'll just go the "stuff 'em in a module and import that" route. Chris, first of all i want you to know that this message is not meant to offend but it may offend you -- hopefully your a rational person and can deal with criticism. This code is horrible. What are you trying to do exactly? Is this purely academic or are you actually using this code for a real purpose? The "Net" class looks like a dialog. Are you wishing to create a dialog? If so, then you would be better off subclassing tkSimpleDialog.Dialog instead of rolling your own. Please explain what you are trying to do from a users perspective so we can properly guide you. Also you should use 4 space indention and never use tabs. This is the accepted way. Although Python does allow freedom i would suggest that coding in a uniformly accepted manner is more productive for the entire community. Google "Python Style Guide" for more info. Thanks From thomas at jollans.com Mon Aug 2 16:48:18 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 22:48:18 +0200 Subject: Trying to set a cookie within a python script In-Reply-To: <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> Message-ID: <4C572F12.2060003@jollans.com> On 08/02/2010 04:20 AM, ????? wrote: > Also my greek print appear in funny encoding although i do use # -*- > coding: utf-8 -*- That's because you never told the web browser which encoding you're using. Content-Type: text/html; charset=UTF-8 From thomas at jollans.com Mon Aug 2 16:57:15 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 22:57:15 +0200 Subject: Trying to set a cookie within a python script In-Reply-To: References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4C57312B.6070606@jollans.com> On 08/02/2010 10:13 PM, ????? wrote: > Hello, any ideas?! That's no way to treat a friendly volunteer mailing list like this one! On 08/02/2010 02:32 PM, ????? wrote: > As for the encoding Notepad++, which is what i use for an editor say > its UTF-8 without BOM. > > Isn't this what i'm supposed to use? > > My Python scripts only containes english and greek letters, so i > though usign UTF-8 is the way to go. No?! Please if you explain to me > in greater detail! As I said, you have to tell the browser what you're up to. Also, I just checked the link (shame on me), and you're not using UTF-8 at all. You're using some weird Windows-xyz or ISO-8859-xyz Greek codepage from the previous millennium. (which obviously my browser didn't know, it thought you were using ISO-8859-1, because that's what my browser does, which you weren't) So: tripple-check that * your file is * Python knows that * the web browser knows that From news1234 at free.fr Mon Aug 2 17:18:19 2010 From: news1234 at free.fr (News123) Date: Mon, 02 Aug 2010 23:18:19 +0200 Subject: let optionparse.Optionparser ignore unknown command line switches. In-Reply-To: <8948edfa-2beb-4295-808e-11755f3d9128@p22g2000pre.googlegroups.com> References: <4c5555c5$0$19337$426a74cc@news.free.fr> <4c555a04$0$18011$426a74cc@news.free.fr> <4c559628$0$28678$426a74cc@news.free.fr> <8948edfa-2beb-4295-808e-11755f3d9128@p22g2000pre.googlegroups.com> Message-ID: <4c57361b$0$23959$426a34cc@news.free.fr> On 08/01/2010 07:53 PM, Jon Clements wrote: > On 1 Aug, 16:43, News123 wrote: >> On 08/01/2010 05:34 PM, Steven W. Orr wrote: >> >> >> >>> On 08/01/10 07:27, quoth News123: >>>> On 08/01/2010 01:08 PM, News123 wrote: >>>>> I wondered, whether there's a simple/standard way to let >>>>> the Optionparser just ignore unknown command line switches. >> >>>> In order to illustrate, what I try to achieve: >> >>>> import optparse >>>> parser = optparse.OptionParser() >>>> parser.add_option("-t","--test",dest="test",action="store_true") >>>> argv=["tst.py","-t","--ignoreme_and_dont_fail"] >>>> try: >>>> (options,args)=parser.parse_args(argv) >>>> except: >>>> # due to --ignoreme_and_dont_fail >>>> # I will end up here and neither options nor >>>> # args will be populated >>>> print "parser error:" >>>> # However I would love to be able to see here >>>> # that options.test is true despite the >>>> # error, that occurred afterwards >>>> print "T",options.test >> >> in my case one imported module should parse some of the options (but >> only the one it understands) already during import. >> the main program will have to parse the same options again. > > Take it up a level. > > Dedicate a module (called app_configuration) or something to do the > option parsing -- everything the application can support is listed > there... It's a bad idea to ignore invalid options... Well the main application would abort the program. I'ts jsut one module which would like to pre-fetch some options. > > When that's imported it runs the parsing for sys.argv whatever... and > you guarantee a variable called app_settings (or whatever) is present > in that module. > > Any module that needs the settings, just imports app_configuration and > tries to take what it understands... > > Would that work for you? > It's not really what I'm looking for, though it might be what I'll end up doing. currently I have several apps all importing one module, but all parsing different options. There's one common option and I'd like to have one module behaving differently depending on this option. My idea was to just change this one module and leave everything else unmodified. Another not so nice solution, which could be a very quick and dirty hack (to be removed lateron) would be to just add to this one module if "--myoption" in sys.argv: dosomething but I'd have prefered a real Optionparser (ignoring unknown options) I could even make sure, that the unknown options follow the common options. From nagle at animats.com Mon Aug 2 17:22:25 2010 From: nagle at animats.com (John Nagle) Date: Mon, 02 Aug 2010 14:22:25 -0700 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <4c571f58$0$1674$742ec2ed@news.sonic.net> Message-ID: <4c57370f$0$1676$742ec2ed@news.sonic.net> On 8/2/2010 12:52 PM, Thomas Jollans wrote: > On 08/02/2010 09:41 PM, John Nagle wrote: >> On 8/2/2010 11:02 AM, MRAB wrote: >>> John Nagle wrote: >>>> The regular expression "split" behaves slightly differently than >>>> string split: >> occurrences of pattern", which is not too helpful. >>>> >>> It's the plain str.split() which is unusual in that: >>> >>> 1. it splits on sequences of whitespace instead of one per occurrence; >> >> That can be emulated with the obvious regular expression: >> >> re.compile(r'\W+') >> >>> 2. it discards leading and trailing sequences of whitespace. >> >> But that can't, or at least I can't figure out how to do it. > > [ s in rexp.split(long_s) if s ] Of course I can discard the blank strings afterward, but is there some way to do it in the "split" operation? If not, then the default case for "split()" is too non-standard. (Also, "if s" won't work; if s != '' might) John Nagle From zdenekmaxa at yahoo.co.uk Mon Aug 2 17:27:37 2010 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Mon, 02 Aug 2010 23:27:37 +0200 Subject: checking that process binds a port, fuser functionality Message-ID: <4C573849.7040804@yahoo.co.uk> Hello, I need to start a process (using subprocess.Popen()) and wait until the new process either fails or successfully binds a specified port. The fuser command seems to be indented exactly for this purpose. Could anyone please provided a hint to a handy Python library to do this or would the advice be to parse fuser command output? This needs to happen on Linux and Python 2.4. Thanks a lot in advance. Zdenek From breamoreboy at yahoo.co.uk Mon Aug 2 17:28:49 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 22:28:49 +0100 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <4C56F813.2080106@gmail.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> <7xmxt5357h.fsf@ruckus.brouhaha.com> <4C568E92.50907@sequans.co m> <4C56F813.2080106@gmail.com> Message-ID: On 02/08/2010 17:53, donn wrote: > On 02/08/2010 17:35, Mark Lawrence wrote: >> aka the colon. :) > Ha. This is a case of the colon being the appendix! > > \d Is there a better newsgroup in the world than c.l.py? No! Kindest regards. Mark Lawrence. From benjamin.kaplan at case.edu Mon Aug 2 17:35:41 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 2 Aug 2010 14:35:41 -0700 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <4c57370f$0$1676$742ec2ed@news.sonic.net> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <4c571f58$0$1674$742ec2ed@news.sonic.net> <4c57370f$0$1676$742ec2ed@news.sonic.net> Message-ID: On Mon, Aug 2, 2010 at 2:22 PM, John Nagle wrote: > On 8/2/2010 12:52 PM, Thomas Jollans wrote: > >> On 08/02/2010 09:41 PM, John Nagle wrote: >> >>> On 8/2/2010 11:02 AM, MRAB wrote: >>> >>>> John Nagle wrote: >>>> >>>>> The regular expression "split" behaves slightly differently than >>>>> string split: >>>>> >>>> occurrences of pattern", which is not too helpful. >>> >>>> >>>>> It's the plain str.split() which is unusual in that: >>>> >>>> 1. it splits on sequences of whitespace instead of one per occurrence; >>>> >>> >>> That can be emulated with the obvious regular expression: >>> >>> re.compile(r'\W+') >>> >>> 2. it discards leading and trailing sequences of whitespace. >>>> >>> >>> But that can't, or at least I can't figure out how to do it. >>> >> >> [ s in rexp.split(long_s) if s ] >> > > Of course I can discard the blank strings afterward, but > is there some way to do it in the "split" operation? If > not, then the default case for "split()" is too non-standard. > > (Also, "if s" won't work; if s != '' might) > > John Nagle > -- > What makes it non-standard? The fact that it's not a 1-line regex? The default case for str.split is designed to handle the most common case: you want to break a string into words, where a word is defined as a sequence of non-whitespace characters. > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Aug 2 17:35:52 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 22:35:52 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 02/08/2010 19:14, Benjamin Kaplan wrote: > On Mon, Aug 2, 2010 at 9:51 AM, David Robinow wrote: > >> On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan >> wrote: >>> ... >>> So these are the packages needed just to run Python in Ubuntu. It doesn't >>> include the packages required for the kernel, the desktop environment, >> the >>> window manager, the terminal, and whatever else you want running. In my >>> fairly clean Ubuntu VM (I use it almost exclusively for testing), I have >>> close to 1500 packages installed. >> As an admittedly stupid comparison, I have 1579 DLLs in my >> \windows\system32 directory. >> Some number of these have been upgraded by Windows Update. This is XP >> Service Pack 3. >> I'm not sure if this means that Windows is better because it has more >> packages or that it is worse because it's got too many. :) >> -- >> > > A package is usually more than one file. > http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist > > >> http://mail.python.org/mailman/listinfo/python-list >> > This is all very well, but what is the unladen airspeed velocity of a swallow in flight? Answers on a postcard please, given that I expect both direction and speed! Kindest regards. Mark Lawrence. From breamoreboy at yahoo.co.uk Mon Aug 2 17:42:32 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 22:42:32 +0100 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 02/08/2010 00:08, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? > > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. > > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? I can't understand why any serious programmer mentions C++. As soon as I read it, I have to rush either to the kitchen to find a bowl to throw up in, or head for the toilet so I can talk to the great white telephone. Kindest regards. Mark Lawrence. From breamoreboy at yahoo.co.uk Mon Aug 2 17:52:27 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 22:52:27 +0100 Subject: how best to clear objects from a frame In-Reply-To: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> References: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> Message-ID: On 02/08/2010 04:13, rantingrick wrote: > On Aug 1, 7:12 pm, Chris Hare wrote: >> Here is the situation: >> >> I have a window with a bunch of widgets in it. I want to clear the objects in a given frame and recreate them to update them. > > You need to check out the "w.update" and "w.update_idletasks" methods > available on all Tkinter widgets. Just FYI: to remove a widget from > view without destroying it use "w.pack_forget" or "w.grid_forget". > However if you are simply trying to refresh a widget use one of the > update methods. I don't understand the technical content of this thread, but I'm very pleased to see rantingrick being positive, well done!!! :) I know that we've crossed swords in the past but believe that bygones should be bygones. Can we call it quits and help to take Python forward? Kindest regards. Mark Lawrence. From peter.milliken at gmail.com Mon Aug 2 17:56:22 2010 From: peter.milliken at gmail.com (Peter) Date: Mon, 2 Aug 2010 14:56:22 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On Aug 3, 7:42?am, Mark Lawrence wrote: > On 02/08/2010 00:08, candide wrote: > > I can't understand why any serious programmer mentions C++. As soon as I > read it, I have to rush either to the kitchen to find a bowl to throw up > in, or head for the toilet so I can talk to the great white telephone. > > Kindest regards. > > Mark Lawrence. With you there Mark - IMO C++ is an abortion that should never have seen the light of day. The idea of experimenting with creating an OO language by extending C wasn't such a bad idea for a "play thing" (by Stroustrop) but the fact that it somehow escaped from the Lab and people picked it up and ran with it on a commercial basis is just plain wrong! Personally I liken it to one of those genetically engineered diseases they play around with in biological warfare labs - and unfortunately this one escaped! It has probably set the computing industry back untold years in terms of advancement... Unfortunately I am forced to use it in my day to day life, but at the end of every day I go home and use a purgative to get it out of my system. But there are many deluded youngsters out there who just don't seem to know any better, but then the signs of the breakdown of society surround us on a daily basis and I guess C++ is just another signpost on the way... Peter From torriem at gmail.com Mon Aug 2 18:06:00 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 02 Aug 2010 16:06:00 -0600 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4C574148.3090606@gmail.com> On 08/02/2010 03:42 PM, Mark Lawrence wrote: > I can't understand why any serious programmer mentions C++. As soon as I > read it, I have to rush either to the kitchen to find a bowl to throw up > in, or head for the toilet so I can talk to the great white telephone. Sometimes, C++ is just the right tool for the job, despite all its warts. For example, programming GTK apps with GTKmm in C++ is way more pleasant than using C (but nowhere as pleasant as Python). C++'s object semantics (guaranteed destruction, scoping, etc) can sometimes work very well when you need the speed of a compiled language, but don't want to be quite as low-level as C. In this case, C++ is certainly not a better tool for the job than C. But plenty of serious programmers know how to leverage C++ and do so quite successfully. Just because C++ makes you ill in no way proves that C++ is unfit for certain purposes. From thomas at jollans.com Mon Aug 2 18:07:58 2010 From: thomas at jollans.com (Thomas Jollans) Date: Tue, 03 Aug 2010 00:07:58 +0200 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <4c57370f$0$1676$742ec2ed@news.sonic.net> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <4c571f58$0$1674$742ec2ed@news.sonic.net> <4c57370f$0$1676$742ec2ed@news.sonic.net> Message-ID: <4C5741BE.4000503@jollans.com> On 08/02/2010 11:22 PM, John Nagle wrote: >> [ s in rexp.split(long_s) if s ] > > Of course I can discard the blank strings afterward, but > is there some way to do it in the "split" operation? If > not, then the default case for "split()" is too non-standard. > > (Also, "if s" won't work; if s != '' might) Of course it will work. Empty sequences are considered false in Python. Python 3.1.2 (release31-maint, Jul 8 2010, 09:18:08) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> sprexp = re.compile(r'\s+') >>> [s for s in sprexp.split(' spaces every where ! ') if s] ['spaces', 'every', 'where', '!'] >>> list(filter(bool, sprexp.split(' more spaces \r\n\t\t '))) ['more', 'spaces'] >>> (of course, the list comprehension I posted earlier was missing a couple of words, which was very careless of me) From troabarton69 at hotmail.com Mon Aug 2 18:07:59 2010 From: troabarton69 at hotmail.com (ben owen) Date: Mon, 2 Aug 2010 17:07:59 -0500 Subject: Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning Message-ID: Hi everyone, I'm new to this and was needing help with trying to learn/work with Python 2.7 on my computer. I'm running Windows 7 and trying to learn python programming from an older book from 1999 by Mark Lutz and David Ascher my boss gave me, and for some reason none of my script/modules for the exercises are working on my comp. Mostly they give either a syntax error on the python command line or something about the file/module not being found on the windows command line. Also, does anyone where i can find/get something similar to the book for my own? Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Mon Aug 2 18:18:30 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 15:18:30 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> On 2 Aug, 01:08, candide wrote: > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? OO programming is possible in C. Just take a look at GNOME and GTK. Perl is written in C++. That is not enough to make me want to use it ;) To be honest, C++ can be a great tool. But very few know how to use it correctly. C++ textbooks are also written by people who don't understand the language, and teach bad habits. The typical examples revealing incompetence are use of new[] instead of std::vector, and dynamic resourse allocation outside contructors. C++ compilers used to be bloatware generators; C++ compilers of 2010 are not comparable to those of 1990. C++ is also a PITA for portability. It is not sufficient for Python to only build with Microsoft Visual Studio. From no.email at nospam.invalid Mon Aug 2 18:27:25 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 02 Aug 2010 15:27:25 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <7x62zslkfm.fsf@ruckus.brouhaha.com> Michael Torrie writes: > Sometimes, C++ is just the right tool for the job, despite all its > warts.... C++'s object semantics (guaranteed destruction, scoping, > etc) can sometimes work very well when you need the speed of a > compiled language, but don't want to be quite as low-level as C. > > In this case, C++ is certainly not a better tool for the job than C. The stuff C++ adds to C is a mix of good and bad, and it's reasonably possible to use just the good stuff and ignore the bad. At that point you've got a pure improvement over C, although a lot of C's shortcomings can't be papered over and still remain. Certain folks in the functional-programming community consider OO to be a 1980's or 1990's approach that didn't work out, and that what it was really trying to supply was polymorphism. C++ programs these days apparently tend to use template-based generics rather than objects and inheritance for that purpose. I've never programmed in Ada but I'm intrigued by these articles: http://adahome.com/Ammo/cpp2ada.html http://www.adaic.org/whyada/ada-vs-c/cada_art.html I have the impression that Ada has an undeservedly bad rap because of its early implementations and its origins in military bureaucracy. I'd certainly consider it as an alternative to C or C++ if I had to write a big program in a traditional procedural language. From sturlamolden at yahoo.no Mon Aug 2 18:28:56 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 15:28:56 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <1280716447.927705.20.camel@paska> Message-ID: On 2 Aug, 05:04, Tomasz Rola wrote: > And one should not forget about performance. C++ was for a long time > behind C, and even now some parts (like iostreams) should be avoided in > fast code. For fast I/O one must use platform specific APIs, such as Windows' i/o completion ports and memory mapping. iostreams in C++ and stdio in C are ok for less demanding tasks. From prologic at shortcircuit.net.au Mon Aug 2 18:32:08 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 08:32:08 +1000 Subject: Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 8:07 AM, ben owen wrote: > Hi everyone, I'm new to this and was needing help with trying to learn/work > with Python 2.7 on my computer. I'm running Windows 7 and trying to learn > python programming from an older book from 1999 by Mark Lutz and David > Ascher my boss gave me, and for some reason none of my script/modules for > the exercises are working on my comp. Mostly they give either a syntax error > on the python command line or something about the file/module not being > found on the windows command line. Also, does anyone where i can find/get > something similar to the book for my own? Start with the mighty fine Python tutorial on the Python Documentation website (1) cheers James 1. http://docs.python.org/ -- -- James Mills -- -- "Problems are solved by method" From sturlamolden at yahoo.no Mon Aug 2 18:54:52 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 15:54:52 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> On 3 Aug, 00:27, Paul Rubin wrote: > Certain folks in the functional-programming community consider OO to be > a 1980's or 1990's approach that didn't work out, and that what it was > really trying to supply was polymorphism. ?C++ programs these days > apparently tend to use template-based generics rather than objects and > inheritance for that purpose. ? It avoids virtual function calls at the expense of unreable code and errors that are nearly impossible to trace. It seems many thinks this is a good idea because Microsoft did this with ATL and WTL. There are also those who thinks template metaprogramming is a good idea. But who uses a C++ compiler to dumb to unroll a for loop? In my experience, trying to outsmart a modern compiler is almost always a bad idea. > I have the impression that Ada has an undeservedly bad rap because of > its early implementations and its origins in military bureaucracy. ? It is annyingly verbose, reminds me of Pascal (I hate the looks of it), and is rumoured to produce slow bloatware. And don't forget Ariane 5 ;) > I'd > certainly consider it as an alternative to C or C++ if I had to write a > big program in a traditional procedural language. I still prefer Fortran 95 :-) From aahz at pythoncraft.com Mon Aug 2 19:03:10 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2010 16:03:10 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Peter wrote: >On Aug 3, 7:42=A0am, Mark Lawrence wrote: >> On 02/08/2010 00:08, candide wrote: >> >> I can't understand why any serious programmer mentions C++. As soon as I >> read it, I have to rush either to the kitchen to find a bowl to throw up >> in, or head for the toilet so I can talk to the great white telephone. > >With you there Mark - IMO C++ is an abortion that should never have >seen the light of day. The idea of experimenting with creating an OO >language by extending C wasn't such a bad idea for a "play thing" (by >Stroustrop) but the fact that it somehow escaped from the Lab and >people picked it up and ran with it on a commercial basis is just >plain wrong! http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From martin at address-in-sig.invalid Mon Aug 2 19:14:53 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Mon, 2 Aug 2010 23:14:53 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: On Mon, 02 Aug 2010 15:54:52 -0700, sturlamolden wrote: > On 3 Aug, 00:27, Paul Rubin wrote: > >> Certain folks in the functional-programming community consider OO to be >> a 1980's or 1990's approach that didn't work out, and that what it was >> really trying to supply was polymorphism. ?C++ programs these days >> apparently tend to use template-based generics rather than objects and >> inheritance for that purpose. > > It avoids virtual function calls at the expense of unreable code and > errors that are nearly impossible to trace. It seems many thinks this is > a good idea because Microsoft did this with ATL and WTL. There are also > those who thinks template metaprogramming is a good idea. But who uses a > C++ compiler to dumb to unroll a for loop? In my experience, trying to > outsmart a modern compiler is almost always a bad idea. > >> I have the impression that Ada has an undeservedly bad rap because of >> its early implementations and its origins in military bureaucracy. > > It is annyingly verbose, reminds me of Pascal (I hate the looks of it), > and is rumoured to produce slow bloatware. > And don't forget Ariane 5 ;) > This had nothing to do with Ada per se and everything to do with shortcuts: - re-use of an Ariane 4 component without changing its parameters to match the Ariane 5 flight profile - not removing Ariane 4-only code intended to handle launch holds and not used at all in Ariane 5 - a programming fault that allowed an exception code to be sent to another component as if it was valid data. Inadequate testing allowed all these to be flown without finding the errors. Bottom line: All this would still have happened regardless of the programming language used. However, don't just listen to me: read the final report on Ariane 501 here: http://www.di.unito.it/~damiani/ariane5rep.html -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From sturlamolden at yahoo.no Mon Aug 2 19:28:23 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 16:28:23 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: <74421501-4ad2-44a4-8ffd-ca1b40358c9d@i24g2000yqa.googlegroups.com> On 3 Aug, 01:14, Martin Gregorie wrote: > Bottom line: All this would still have happened regardless of the > programming language used. I am quite sure C and Fortran makes it unlikely for an unhandled exception to trigger the autodestruct sequence. But it's nice to know when flying that modern avionics is programmed in a language where this is possible. ;) From breamoreboy at yahoo.co.uk Mon Aug 2 19:31:38 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Aug 2010 00:31:38 +0100 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 03/08/2010 00:03, Aahz wrote: > In article, > Peter wrote: >> On Aug 3, 7:42=A0am, Mark Lawrence wrote: >>> On 02/08/2010 00:08, candide wrote: >>> >>> I can't understand why any serious programmer mentions C++. As soon as I >>> read it, I have to rush either to the kitchen to find a bowl to throw up >>> in, or head for the toilet so I can talk to the great white telephone. >> >> With you there Mark - IMO C++ is an abortion that should never have >> seen the light of day. The idea of experimenting with creating an OO >> language by extending C wasn't such a bad idea for a "play thing" (by >> Stroustrop) but the fact that it somehow escaped from the Lab and >> people picked it up and ran with it on a commercial basis is just >> plain wrong! > > http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html Haven't been able to read this properly as the stomach has been shaking too much to control the mouse and/or arrow keys/page up/down etc. Hum, marks out of 10, 1.649072354865927**trillions. For the cryptographers, is this a decent random number? Kindest regards. Mark Lawrence From breamoreboy at yahoo.co.uk Mon Aug 2 19:37:02 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Aug 2010 00:37:02 +0100 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: On 03/08/2010 00:14, Martin Gregorie wrote: > On Mon, 02 Aug 2010 15:54:52 -0700, sturlamolden wrote: > >> On 3 Aug, 00:27, Paul Rubin wrote: >> >>> Certain folks in the functional-programming community consider OO to be >>> a 1980's or 1990's approach that didn't work out, and that what it was >>> really trying to supply was polymorphism. C++ programs these days >>> apparently tend to use template-based generics rather than objects and >>> inheritance for that purpose. >> >> It avoids virtual function calls at the expense of unreable code and >> errors that are nearly impossible to trace. It seems many thinks this is >> a good idea because Microsoft did this with ATL and WTL. There are also >> those who thinks template metaprogramming is a good idea. But who uses a >> C++ compiler to dumb to unroll a for loop? In my experience, trying to >> outsmart a modern compiler is almost always a bad idea. >> >>> I have the impression that Ada has an undeservedly bad rap because of >>> its early implementations and its origins in military bureaucracy. >> >> It is annyingly verbose, reminds me of Pascal (I hate the looks of it), >> and is rumoured to produce slow bloatware. > >> And don't forget Ariane 5 ;) >> > This had nothing to do with Ada per se and everything to do with > shortcuts: > > - re-use of an Ariane 4 component without changing its parameters > to match the Ariane 5 flight profile > - not removing Ariane 4-only code intended to handle launch holds > and not used at all in Ariane 5 > - a programming fault that allowed an exception code to be sent > to another component as if it was valid data. > > Inadequate testing allowed all these to be flown without finding the > errors. > > Bottom line: All this would still have happened regardless of the > programming language used. However, don't just listen to me: read the > final report on Ariane 501 here: > > http://www.di.unito.it/~damiani/ariane5rep.html > > A bug is a bug is a bug? Except in my code. Never written a bug in my life. Cross my heart and hope to die. Of course I'm lying. :) Kindest regards. Mark Lawrence. From ben+python at benfinney.id.au Mon Aug 2 19:38:16 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 03 Aug 2010 09:38:16 +1000 Subject: Package management (was: Why is there no platform independent way of clearing a terminal?) References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: <87aap44mc7.fsf_-_@benfinney.id.au> Mark Lawrence writes: > How does any user or an admin cope with 500 packages? Operating systems with good package management come with tools that help the administrator do this job easily. Also, operating systems with good package management encourage the small-pieces-loosely-joined philosophy to apply to packages also: the packages tend to be smaller and more focussed, and fit together in more well-defined ways, than those on other OSen. This isn't automatic, but the support of a good package management system allows a robust policy to be implemented by the vendor for good quality packages in the OS. So ?installing 500 packages? is not an unusual nor onerous thing to do on such an OS. The job of making them all work well together is delegated upstream, to one's distribution vendor. But the fact that they're small pieces, loosely joined, means that if any one of them is causing a problem, it's far more likely that a motivated administrator can do something about it locally, rather than being at the mercy of the vendor. > Can Python help here, assume an eight hour working day? Sadly, Python's package management is rather lacking by these standards. The Distutils legacy assumption of ?package recipient, system administrator, and end user are all the same person?, among other design decisions, makes it unusually difficult to have the necessary separation of concerns between OS packaging, system administration, and end user. There have been great strides in recent years to improve the Distutils shortcomings (see the Distutils forum archives for the details), but the changes are in part backward-incompatible, and it will be some time before Python is on a par with, e.g., Perl in this area. > So every working day you have 57.6 seconds to use each package. Your mistaken assumption is that one would use these packages separate from each other. That's like assuming that the limit of usefulness of modules in a Python program is how much one can use each of them separate from all the others. In both cases, they're not used separately most of the time; they're used in conjunction, and their distinction is more to enable the people responsible for maintaining them to do so as distinct pieces when it makes sense to do so, and as larger aggregate collections when that makes sense. OS packages are not only applications. They are any discrete, coherent ?piece? of an operating system; applications usually encompass one or several packages, and most packages are not applications. -- \ ?We must respect the other fellow's religion, but only in the | `\ sense and to the extent that we respect his theory that his | _o__) wife is beautiful and his children smart.? ?Henry L. Mencken | Ben Finney From python at mrabarnett.plus.com Mon Aug 2 19:41:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Aug 2010 00:41:15 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: <4C57579B.8060405@mrabarnett.plus.com> Mark Lawrence wrote: > On 02/08/2010 19:14, Benjamin Kaplan wrote: >> On Mon, Aug 2, 2010 at 9:51 AM, David Robinow wrote: >> >>> On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan >>> wrote: >>>> ... >>>> So these are the packages needed just to run Python in Ubuntu. It >>>> doesn't >>>> include the packages required for the kernel, the desktop environment, >>> the >>>> window manager, the terminal, and whatever else you want running. In my >>>> fairly clean Ubuntu VM (I use it almost exclusively for testing), I >>>> have >>>> close to 1500 packages installed. >>> As an admittedly stupid comparison, I have 1579 DLLs in my >>> \windows\system32 directory. >>> Some number of these have been upgraded by Windows Update. This is XP >>> Service Pack 3. >>> I'm not sure if this means that Windows is better because it has more >>> packages or that it is worse because it's got too many. :) >>> -- >>> >> >> A package is usually more than one file. >> http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist >> >> >> >>> http://mail.python.org/mailman/listinfo/python-list >>> >> > > This is all very well, but what is the unladen airspeed velocity of a > swallow in flight? Answers on a postcard please, given that I expect > both direction and speed! > African or European? :-) From sturlamolden at yahoo.no Mon Aug 2 19:49:23 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 16:49:23 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: <44a35af9-3861-4538-948c-ca80e130802f@f33g2000yqe.googlegroups.com> On 3 Aug, 01:37, Mark Lawrence wrote: > A bug is a bug is a bug? According to Grace Hopper, a bug might be a moth, in which case the best debugger is a pair of forceps. From a.pfrengle at gmail.com Mon Aug 2 19:52:25 2010 From: a.pfrengle at gmail.com (Andreas Pfrengle) Date: Mon, 2 Aug 2010 16:52:25 -0700 (PDT) Subject: simple integer subclass Message-ID: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> I'm trying to define a subclass of int called int1. An int1-object shall behave exactly like an int-object, with the only difference that the displayed value shall be value + 1 (it will be used to display array indices starting at 1 instead of 0). Right now I have: class int1(int): def __str__(self): return int.__str__(self + 1) However, if I calculate with int1 and int- (or other number) objects, the result is always coerced to an int (or other number object), e.g: a = int1(5) b = 5 print a # "6" print a+b #"10" How can I tell int1 to be the "default integer object"? Do I need to overload *every* mathematical operation method of int, or is there an easier way? From lists at cheimes.de Mon Aug 2 19:55:22 2010 From: lists at cheimes.de (Christian Heimes) Date: Tue, 03 Aug 2010 01:55:22 +0200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: Am 03.08.2010 01:03, schrieb Aahz: > http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html I don't understand why the URL contains the word "joke". Every word is true. Hell yeah! :) Christian From carey.tilden at gmail.com Mon Aug 2 20:05:14 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Mon, 2 Aug 2010 17:05:14 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Mon, Aug 2, 2010 at 3:18 PM, sturlamolden wrote: > > Perl is written in C++. That is not enough to make me want to use > it ;) I realize this was meant to be funny, but it's not true, and detracts from the point you were trying to make. Maybe skip the pointless jabs at Perl and stick to things you know more about. From chare at labr.net Mon Aug 2 20:06:26 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 19:06:26 -0500 Subject: calling a class method from a menu in a different class Message-ID: <425A7322-BD8E-48FC-80AE-0C0A3C423F70@labr.net> What I am trying to do is call a class function from a menu, for example displaySubMenu.add_radiobutton(label="Medium", variable=radarPanelSize, command=radarWidgets.refresh) class radarWidgets: def __init__(self,root): self.window = root def refresh(self): global radar global refreshTimer self.refreshTimer.cancel() logging.debug("handlesRadarRefreshByTimer()") # # destroy the existing frame the radar is in # self.w.destroy() self.lblLastUpdate.destroy() self.btnRefresh.destroy() # # rebuild the radarWidgets # self.createImage() self.refreshTimer = threading.Timer( 900, self.refresh) self.refreshTimer.start() This doesn't work because the instance of radarWidgets was defined in a different class ...... class mainDisplay: def __init__(self,root): self.window = root def show(self): # # Configure the base frame # base=Frame(self.window,bg=backColor,width=1200, height=800) base.grid() frameRadar = Frame(base, bd=0, bg=backColor) frameRadar.grid(row=2,column=1,sticky=N+E+S+W) # radar = radarWidgets(frameRadar) radar.show() so the actual instance is called "radar". If I put the instance name in the menu item, I get an error that "radar" is unknown. If I use RadarWidgets.refresh ins the command for the menu, I get the error: TypeError: unbound method refresh() must be called with radarWidgets instance as first argument (got nothing instead) Any ideas? Thanks! From peter.milliken at gmail.com Mon Aug 2 20:17:35 2010 From: peter.milliken at gmail.com (Peter) Date: Mon, 2 Aug 2010 17:17:35 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: On Aug 3, 8:27?am, Paul Rubin wrote: ... > > Certain folks in the functional-programming community consider OO to be > a 1980's or 1990's approach that didn't work out, and that what it was > really trying to supply was polymorphism. ?C++ programs these days > apparently tend to use template-based generics rather than objects and > inheritance for that purpose. ? > > I've never programmed in Ada but I'm intrigued by these articles: > > ?http://adahome.com/Ammo/cpp2ada.html > ?http://www.adaic.org/whyada/ada-vs-c/cada_art.html > > I have the impression that Ada has an undeservedly bad rap because of > its early implementations and its origins in military bureaucracy. ?I'd > certainly consider it as an alternative to C or C++ if I had to write a > big program in a traditional procedural language. I used to work for defence contractors - Ada (IMO :-)) is the very best OO language for real-time and embedded systems. It scales fantastically well to large, multi-platform jobs as well. If I had my way we would use it where I work now (biomedical field) but that isn't an option - too many folk are brought up on a steady diet of C/C++ and therefore don't know any better, plus there is a dearth of Ada compilers for the CPU's that we use here (all embedded work). I have used fortran, C, C++, some Java, Ada (and Python :-)), if I had my choice for the type of programming I do here at work, it would definitely go to Ada by a country mile. Having said that though, I won't replace Python with it on my desktop for the type of stuff I do around the fringes of my job (test scripts etc) and my personal programming :-) But for anyone who wants to expand their horizons, learning Ada would be an excellent choice (although like any learning activity, unless you have a concrete goal in mind you will probably just waste your time :-)). It is not an easy language to just pick up and run with because the strong type-checking FORCES you to think about and design your program very carefully from the very beginning - something that many programmers find an abhorrence for :-) But I always used to tell people - by the time I got a program to compile then I figured 99% of the bugs were already discovered! Try that with C/C++ or almost any other language you care to name :-) Peter From samwyse at gmail.com Mon Aug 2 20:19:46 2010 From: samwyse at gmail.com (samwyse) Date: Mon, 2 Aug 2010 17:19:46 -0700 (PDT) Subject: simple (I hope!) problem Message-ID: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> I'm writing for the Google app engine and have stubbed my toe yet again on a simple obstacle. Non-trivial app engines programs require the import of several modules that aren't normally in my PYTHONPATH. I'd like to be able to test my code outside of the app engine framework. I've tried several solutions in the past that worked but weren't particularly elegant or portable. Now I've had a new idea. Here's my latest attempt: import os, re if __name__ == '__main__': pass else from google.appengine.ext import webapp register = webapp.template.create_template_register() This works great, except my code makes use of the resister object in several places, like this: register.filter(emptylines) Fortunately, I don't need the functionality of the object, I just want something that won't generate an error when I use it. So, what is the quickest way to to create such an object (replacing the 'pass' in my first snippet). My solution is this: class C: def filter(self, *args, **kwds): pass register = C() but it seems like I should be able to do something "better", as measured by lines of code, faking more than just a 'filter' method, or both. Any ideas? Thanks! From samwyse at gmail.com Mon Aug 2 20:24:51 2010 From: samwyse at gmail.com (samwyse) Date: Mon, 2 Aug 2010 17:24:51 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> Message-ID: On Aug 2, 6:52?pm, Andreas Pfrengle wrote: > I'm trying to define a subclass of int called int1. An int1-object > shall behave exactly like an int-object, with the only difference that > the displayed value shall be value + 1 (it will be used to display > array indices starting at 1 instead of 0). Right now I have: > > class int1(int): > ? ? def __str__(self): > ? ? ? ? return int.__str__(self + 1) > > However, if I calculate with int1 and int- (or other number) objects, > the result is always coerced to an int (or other number object), e.g: > a = int1(5) > b = 5 > print a ? ? ?# "6" > print a+b ?#"10" > > How can I tell int1 to be the "default integer object"? Do I need to > overload *every* mathematical operation method of int, or is there an > easier way? I had a similar problem a few years ago, and couldn't find a solution then. The thread from back then may shed some light on your problem. http://groups.google.com/group/comp.lang.python/browse_thread/thread/10cfe2affc265ac/2ad03b121c1c6489 From no.email at nospam.invalid Mon Aug 2 20:31:24 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 02 Aug 2010 17:31:24 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: <7xy6cobkpv.fsf@ruckus.brouhaha.com> sturlamolden writes: > It is annyingly verbose, reminds me of Pascal (I hate the looks of > it), and is rumoured to produce slow bloatware. The earliest Ada compilers were terrible, but they are about like C compilers now, so the output code is ok (see Alioth shootout for example). I agree about the verbosity but I don't think that's too big a problem in the sorts of systems that need to be written in such languages. > And don't forget Ariane 5 ;) I have looked into that a few times and I do wonder whether the language or release process could have been of any help. One possibility is using something like SPARK to ensure the absence of overflow exceptions. Another is automatic test generation something like http://www.stanford.edu/~engler/klee-osdi-2008.pdf but that approach was probably unknown at the time. From roy at panix.com Mon Aug 2 20:47:42 2010 From: roy at panix.com (Roy Smith) Date: Mon, 02 Aug 2010 20:47:42 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: In article <0ed1fb16-87cb-4fb9-85b2-08d876445d5d at q22g2000yqm.googlegroups.com>, sturlamolden wrote: > The typical examples revealing incompetence are use of > new[] instead of std::vector To be fair, there were usable C++ compilers before there were usable STL implementations. Thus, it should not be surprising to find older C++ code bases eschewing the use of STL. That's not to say that this trend should be propagated in current educational material. > and dynamic resourse allocation outside contructors. This one I don't understand. Yes, I get RAII, but surely there are valid reasons to allocate memory outside of constructors. Containers which resize themselves (such as std::vector) are one obvious example. From samwyse at gmail.com Mon Aug 2 20:53:12 2010 From: samwyse at gmail.com (samwyse) Date: Mon, 2 Aug 2010 17:53:12 -0700 (PDT) Subject: Behavior of re.split on empty strings is unexpected References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: <52ae410e-789e-41ad-bf0a-1d060d03019d@x21g2000yqa.googlegroups.com> On Aug 2, 12:34?pm, John Nagle wrote: > The regular expression "split" behaves slightly differently than string > split: I'm going to argue that it's the string split that's behaving oddly. To see why, let's first look at some simple CSV values: cat,dog ,missing,,values, How many fields are on each line and what are they? Here's what re.split(',') says: >>> re.split(',', 'cat,dog') ['cat', 'dog'] >>> re.split(',', ',missing,,values,') ['', 'missing', '', 'values', ''] Note that the presence of missing values is clearly flagged via the presence of empty strings in the results. Now let's look at string split: >>> 'cat,dog'.split(',') ['cat', 'dog'] >>> ',missing,,values,'.split(',') ['', 'missing', '', 'values', ''] It's the same results. Let's try it again, but replacing the commas with spaces. >>> re.split(' ', 'cat dog') ['cat', 'dog'] >>> re.split(' ', ' missing values ') ['', 'missing', '', 'values', ''] >>> 'cat dog'.split(' ') ['cat', 'dog'] >>> ' missing values '.split(' ') ['', 'missing', '', 'values', ''] It's the same results; however many people don't like these results because they feel that whitespace occupies a privileged role. People generally agree that a string of consecutive commas means missing values, but a string of consecutive spaces just means someone held the space-bar down too long. To accommodate this viewpoint, the string split is special-cased to behave differently when None is passed as a separator. First, it splits on any number of whitespace characters, like this: >>> re.split('\s+', ' missing values ') ['', 'missing', 'values', ''] >>> re.split('\s+', 'cat dog') ['cat', 'dog'] But it also eliminates any empty strings from the head and tail of the list, because that's what people generally expect when splitting on whitespace: >>> 'cat dog'.split(None) ['cat', 'dog'] >>> ' missing values '.split(None) ['missing', 'values'] From roy at panix.com Mon Aug 2 21:03:55 2010 From: roy at panix.com (Roy Smith) Date: Mon, 02 Aug 2010 21:03:55 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html The same story has been floating around for eons, just with the names changed. I saw one where Wirth was ostensibly making fun of the people who didn't understand that Pascal was all just a joke. I'm sure if you go back far enough, you can find a McCarthy / Lisp version. It probably goes something like, "So, anyway, we tried to figure out what was the most absurd way to abuse punctuation we could imagine. Somebody suggested that every program would have to end with 37 close parentheses. When we finally stopped laughing, we started sketching out a grammar on the chalkboard that would let us do that". From pavlovevidence at gmail.com Mon Aug 2 21:22:48 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 2 Aug 2010 18:22:48 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> Message-ID: <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> On Aug 2, 4:52?pm, Andreas Pfrengle wrote: > I'm trying to define a subclass of int called int1. An int1-object > shall behave exactly like an int-object, with the only difference that > the displayed value shall be value + 1 (it will be used to display > array indices starting at 1 instead of 0). Right now I have: > > class int1(int): > ? ? def __str__(self): > ? ? ? ? return int.__str__(self + 1) > > However, if I calculate with int1 and int- (or other number) objects, > the result is always coerced to an int (or other number object), e.g: > a = int1(5) > b = 5 > print a ? ? ?# "6" > print a+b ?#"10" > > How can I tell int1 to be the "default integer object"? Do I need to > overload *every* mathematical operation method of int, or is there an > easier way? (Preface: I normally don't offer recommendations without answering the question as asked, but once in a while it has to be done.) I **highly** recommend against this approach. You are creating an object that differs from a built-in, int, in a highly misleading way that only makes sense in a very limited context, and this object's modified behavior gives no clue that it's been modified in such as way. (That is, it's not possible to tell if the object's not a regular int just by looking at __str__()'s return value.) To make matters worse, you want to program this object to coerce other integers, so there's a risk of these objects escaping from the context where they make sense. This is just a bad idea. The type is not the place to implement behavior that makes sense only in a limited context. Instead, do something like this: print "Item %d is %s." % (i+1, s[i]) Carl Banks From ldo at geek-central.gen.new_zealand Mon Aug 2 21:56:27 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 03 Aug 2010 13:56:27 +1200 Subject: Problem with Elementtree and XMLSchem instance type References: <96e47fd8-c939-48a2-9a2b-92afa720c8ac@k1g2000prl.googlegroups.com> <6627204c-d0b1-456d-94bd-76d946ad21d9@g6g2000pro.googlegroups.com> Message-ID: In message <6627204c-d0b1-456d-94bd-76d946ad21d9 at g6g2000pro.googlegroups.com>, Carl Banks wrote: > On Aug 1, 5:43 pm, Lawrence D'Oliveiro > wrote: > >> In message >> <96e47fd8-c939-48a2-9a2b-92afa720c... at k1g2000prl.googlegroups.com>, Carl >> Banks wrote: >> >>> My general feeling is that ElementTree is a lot handier for reading >>> and writing your own XML formats, than for handling XML files produced >>> by other tools. >> >> Why is that? I?ve successfully used it to parse SVG files produced by >> Inkscape . > > I said it was not handy, not that is was not useful. If you want to split hairs, I didn?t say it was ?useful?, and I certainly found it very ?handy? for that purpose. > And you don't *have* to try to start an argument over every tiny thing > you disagree with. What else is USENET for? :) From ldo at geek-central.gen.new_zealand Mon Aug 2 21:57:57 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 03 Aug 2010 13:57:57 +1200 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <6Dw5o.72330$Ds3.63060@hurricane> Message-ID: In message <6Dw5o.72330$Ds3.63060 at hurricane>, Bartc wrote: > There's a cost involved in using those fancy constructions. Sure. But at the point that starts to matter, you have to ask yourself why you?re not rewriting the CPU-intensive part in C. From sturlamolden at yahoo.no Mon Aug 2 22:03:09 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 19:03:09 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> On 3 Aug, 02:47, Roy Smith wrote: > This one I don't understand. ?Yes, I get RAII, but surely there are > valid reasons to allocate memory outside of constructors. ?Containers > which resize themselves (such as std::vector) are one obvious example. That is because an exception might skip an arbitrarily placed delete[] or std::fclose when it rewinds the stack, so to avoid resource leaks they must be places inside a destructor of an object on the stack (which will be called). This is unsafe, anyone who writes this in C++ should be flogged: void foobar() { std::FILE *fid = fopen("whatever"); // some code here std::fclose(fid); } This idiom is safer : struct File { std::FILE *fid; File(const char *name) { // acquire resource in constructor fid = std::fopen(name); if (!fid) throw some_exception; } ~File() { // free resource in destructor if(fid) std::flose(fid); } }; void foobar() { File file("whatever"); // some code here } It is for the very same reason we should use std::vector instead of new[] for arrays. It is why new and delete should only be used inside constructors/destructors. It also why C++ has references in addition to pointers. Which means this is bad in C++, as new and delete is arbitrarily placed: void foobar() { File *myfile = new File("whatever); // some code here delete myfile; } An object should go on the stack, because if an exception is thrown, we need the destructor call. Which is why this (as shown above) is ok: void foobar() { File file("whatever"); // some code here } This is the kind of gotchas that allows C++ to shoot your leg off. In comparison C is much more forgiving, because there is no exceptions (unless you use setjmp/longjmp). This is ok in C, but not in C++: void foobar() { FILE *fid = fopen("whatever"); // some code here fclose(fid); } For the same reason we can place malloc and free wherever we like in C code. But in C++ we must restrict std::malloc and std::free (as well as new and delete) to constructor and destructor pairs. This kind of design is mandatory to make safe C++ programs. But it is not enforced by the compiler. And since the majority of C++ programmers don't obey by these rules, Java and C# tends to produce far less runtime errors and memory/resource leaks. And C++ textbooks tends to avoid teaching these important details. I'm inclined to believe it is because the authors don't understand it themselves. Objects on the stack are also required for operator overloading in C+ +. A common novice mistake is this: std::vector *myvec = new std::vector(10); myvec[5] = 10.0; // why does the compiler complain????? And then the novice will spend hours contemplating why the stupid compiler claims the type of myvec[5] is std::vector. There was recently a post to the Cython mailing list claiming there is a bug in Cython's auto-generated C++ because of this. But this is how it should be: std::vector myvec(10); myvec[5] = 10.0; // ok And now we see why C++ has references, as that is how we can efficiently reference and object on the stack without getting the operator overloading problem above. C++ is good, but most programmers are better off with C. It has fewer gotchas. And if we need OOP, we have Python... Sturla From drsalists at gmail.com Mon Aug 2 22:22:03 2010 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 2 Aug 2010 19:22:03 -0700 Subject: constructing and using large lexicon in a program In-Reply-To: <119487.45857.qm@web113614.mail.gq1.yahoo.com> References: <119487.45857.qm@web113614.mail.gq1.yahoo.com> Message-ID: On Mon, Aug 2, 2010 at 10:46 AM, Majdi Sawalha wrote: > Dear List members, > > I am developing a morphological analyzer that depends on a large lexicon. i > construct a Lexicon class that reades a text file and construct a dictionary > of the lexicon entries. > the other class will use the lexicon class to chech if the word is found in > the lexicon. the problem that this takes long time as each time an object of > that class created, then it needs to call the lexicon many times. then when > the lexicon is called it re-construct the lexicon again. is there any way to > construct the lexicon one time during the execution of the program? and then > the other modules will search the already constructed lexicon. > > best regards > Majdi > > > Faculty of Engineering > School of Computing > University of Leeds > Leeds, LS2 9JT > UK > http://www.comp.leeds.ac.uk/sawalha > > > -- > http://mail.python.org/mailman/listinfo/python-list > > You want an object with a global lifetime. I often wish Python had a nice equivalent to static variables in C. Sometimes people suggest doing this with a function or method argument that takes a default value that looks like it would be different each time the function is called, but in reality, it's evaluated once when the function/method is created. EG: $ cat t #!/usr/local/cpython-2.7/bin/python import time def fn(x = time.time()): print x for i in xrange(5): fn() time.sleep(1) benchbox-dstromberg:~/src/global-lifetime i486-pc-linux-gnu 13955 - above cmd done 2010 Mon Aug 02 07:16 PM $ ./t 1280801789.33 1280801789.33 1280801789.33 1280801789.33 1280801789.33 benchbox-dstromberg:~/src/global-lifetime i486-pc-linux-gnu 13955 - above cmd done 2010 Mon Aug 02 07:16 PM IOW, it's printing the same time each iteration, despite having a 10 millisecond precision and a 1 second sleep between each call. BTW, for storing a truly large lexicon, you might be better off with a trie than a dictionary (AKA hash table), though I'm sure some lexicons aren't huge enough to require it. One simple way of doing a trie would be to mkdir an empty directory, and then for each ith subdirectory depth beneath that, have it correspond to the ith character of your word in your lexicon. That's probably not a terribly efficient trie, but I think it may get the point across - you're not storing common prefixes over and over. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Mon Aug 2 22:25:05 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 19:25:05 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> Message-ID: <2b473423-0a22-4f4d-943f-31ea2d6020e6@z10g2000yqb.googlegroups.com> On 3 Aug, 04:03, sturlamolden wrote: > struct File { > ? ? std::FILE *fid; > ? ? File(const char *name) { > ? ? ? ? // acquire resource in constructor > ? ? ? ? fid = std::fopen(name); > ? ? ? ? if (!fid) throw some_exception; > ? ? } > ? ? ~File() { > ? ? ? ? // free resource in destructor > ? ? ? ? if(fid) std::flose(fid); > ? ? } > > }; And since this is comp.lang.python, I'll add in that this sometimes applies to Python as well. Python, like C++, can have the call stack rewinded by an exception. If we call some raw OS resource allocation, e.g. malloc or fopen using ctypes, we have to place a deallocation in __del__ (and make sure the object is newer put in a reference cycle). The safer option, however, is to use a C extension object, which is guaranteed to have the destructor called (that is, __dealloc__ when using Cython or Pyrex). If we place raw resource allocation arbitrarily in Python code, it is just as bad as in C++. But in Python, programmers avoid this trap by mostly never allocating raw OS resources from within Python code. E.g. Python's file object is programmed to close itself on garbage collection, unlike a pointer retured from fopen using ctypes. Sturla From pavanhousework at gmail.com Mon Aug 2 22:28:20 2010 From: pavanhousework at gmail.com (pink) Date: Mon, 2 Aug 2010 19:28:20 -0700 (PDT) Subject: Get sony/dell laptaps 100% free Message-ID: <84f1e360-0843-489b-acd2-e5d027adf448@h40g2000pro.googlegroups.com> Free sony/dell laptops ?.no need money? No need registration fee?.no need shipping charges?..details available on my website. I have hidden the free laptap trick and registration form LINK in an BIG SIZE IMAGES at the TOP of my BLOG. .click any image and Get it free laptap within 2 days.. my website is http://femalebodies.co.cc/ From sturlamolden at yahoo.no Mon Aug 2 22:37:46 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 19:37:46 -0700 (PDT) Subject: Normalizing A Vector References: Message-ID: On 30 Jul, 13:46, Lawrence D'Oliveiro wrote: > Say a vector V is a tuple of 3 numbers, not all zero. You want to normalize > it (scale all components by the same factor) so its magnitude is 1. > > The usual way is something like this: > > ? ? L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) > ? ? V = (V[0] / L, V[1] / L, V[2] / L) > > What I don?t like is having that intermediate variable L leftover after the > computation. L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) V = (V[0] / L, V[1] / L, V[2] / L) del L But this is the kind of programming tasks where NumPy is nice: V[:] = V / np.sqrt((V**2).sum()) Sturla From jiazhao62 at yahoo.com Mon Aug 2 22:46:47 2010 From: jiazhao62 at yahoo.com (world-trade) Date: Mon, 2 Aug 2010 19:46:47 -0700 (PDT) Subject: paypal wholesale gucci shoes (paypal payment) Message-ID: <83151cc5-f578-4348-8dc8-f5cd587ff9d7@l32g2000prn.googlegroups.com> paypal wholesale d&g shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale gucci shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale lv shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale NBA shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale nike (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale adidas shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale chanel shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale bape hoody (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale antick jeans (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale diesel jeans (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale artful dudger (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale bag(lv gucci coach chanel d&g dior ed fendi ) (paypal payment)(http://www.24hours-buy.com/ ) paypal wholesale clothing (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale lrg,jeans,hoody, (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale evisu jeans,hoody,shirt (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale Prada (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale Puma (paypal payment)( http://www.24hours-buy.com/ ) paypal wholesale Sand (paypal payment)( http://www.24hours-buy.com/ ) paypal wholesale Shox (paypal payment)( http://www.24hours-buy.com/ ) paypal wholesale soccer (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale LV (paypal payment)( http://www.24hours-buy.com/ ) paypal wholesale Versace (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale Women (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale Y-3 (paypal payment)( http://www.24hours-buy.com/ ) From roy at panix.com Mon Aug 2 22:46:50 2010 From: roy at panix.com (Roy Smith) Date: Mon, 02 Aug 2010 22:46:50 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> Message-ID: In article <7d95c0d3-718d-4958-9364-263c833f1835 at i24g2000yqa.googlegroups.com>, sturlamolden wrote: > On 3 Aug, 02:47, Roy Smith wrote: > > > This one I don't understand. ?Yes, I get RAII, but surely there are > > valid reasons to allocate memory outside of constructors. ?Containers > > which resize themselves (such as std::vector) are one obvious example. > > That is because an exception might skip an arbitrarily placed delete[] > or std::fclose when it rewinds the stack... Well, OK, but there's still nothing wrong with allocating memory outside of constructors, as long as you make sure the destructor cleans it up. Or you have made some other arrangements to make sure it's cleaned up (try/catch, auto_pointer, etc). From jjposner at optimum.net Mon Aug 2 23:00:51 2010 From: jjposner at optimum.net (John Posner) Date: Mon, 02 Aug 2010 23:00:51 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C578663.8000804@optimum.net> On 7/31/2010 1:31 PM, John Posner wrote: > > Caveat -- there's another description of defaultdict here: > > http://docs.python.org/library/collections.html#collections.defaultdict > > ... and it's bogus. This other description claims that __missing__ is a > method of defaultdict, not of dict. Following is a possible replacement for the bogus description. Comments welcome. I intend to submit a Python doc bug, and I'd like to have a clean alternative to propose. -------------- class collections.defaultdict([default_factory[, ...]]) defaultdict is a dict subclass that can guarantee success on key lookups: if a key does not currently exist in a defaultdict object, a "default value factory" is called to provide a value for that key. The "default value factory" is a callable object (typically, a function) that takes no arguments. You specify this callable as the first argument to defaultdict(). Additional defaultdict() arguments are the same as for dict(). The "default value factory" callable is stored as an attribute, default_factory, of the newly created defaultdict object. If you call defaultdict() with no arguments, or with None as the first argument, the default_factory attribute is set to None. You can reassign the default_factory attribute of an existing defaultdict object to another callable, or to None. When a lookup of a non-existent key is performed in a defaultdict object, its default_factory attribute is evaluated, and the resulting object is called: * If the call produces a value, that value is returned as the result of the lookup. In addition, the key-value pair is inserted into the defaultdict. * If the call raises an exception, it is propagated unchanged. * If the default_factory attribute evaluates to None, a KeyError exception is raised, with the non-existent key as its argument. (The defaultdict behaves exactly like a standard dict in this case.) From rantingrick at gmail.com Mon Aug 2 23:31:20 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 2 Aug 2010 20:31:20 -0700 (PDT) Subject: calling a class method from a menu in a different class References: Message-ID: Chris, It looks as if you are calling a class object and not an instance object. However i cannot be for sure because you are using improper Python style. All classes should be capwords. But here again you have used camelcase for the class identifiers "radarWidgets" and "mainDisplay", which is bad bad bad!! You been asking multiple questions about this code for the last couple of days (and thats fine). However, maybe you would do everyone a favor by posting the entire code so we can offer suggestions. Just seeing seeing a snipit here and a snipit there is not helping because we don't know where else you may be screwing up that we cannot see. It seems you're committing many faux pas with not only your coding style but also your coding practices. I've seen overuse of globals and bad styles and on and on. So post the entire code so myself and others can go through this mess and get it sorted out. If you keep on with your bad habits you're never going to become proficient with Python. I am sorry if this post seems condescending because that is not the case. From rantingrick at gmail.com Mon Aug 2 23:36:48 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 2 Aug 2010 20:36:48 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> Message-ID: <052ff22f-c083-487f-9c97-b45f54754758@f33g2000yqe.googlegroups.com> On Aug 2, 6:52?pm, Andreas Pfrengle wrote: > I'm trying to define a subclass of int called int1. An int1-object > shall behave exactly like an int-object, with the only difference that > the displayed value shall be value + 1 (it will be used to display > array indices starting at 1 instead of 0) Is zero based indexing that bad for you? I also think this is a very bad idea unless you can offer a sensible use case -- for which i cannot imagine. From rantingrick at gmail.com Mon Aug 2 23:42:14 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 2 Aug 2010 20:42:14 -0700 (PDT) Subject: Behavior of re.split on empty strings is unexpected References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <52ae410e-789e-41ad-bf0a-1d060d03019d@x21g2000yqa.googlegroups.com> Message-ID: On Aug 2, 7:53?pm, samwyse wrote: > It's the same results; however many people don't like these results > because they feel that whitespace occupies a privileged role. ?People > generally agree that a string of consecutive commas means missing > values, but a string of consecutive spaces just means someone held the > space-bar down too long. ?To accommodate this viewpoint, the string > split is special-cased to behave differently when None is passed as a > separator. ?First, it splits on any number of whitespace characters, > like this: Well we could have created another method like "splitstrip()". However then folks would complain that they must remember two methods that are almost identical. Uggh, you just can't win. There is always the naysayers no matter what you do! PS: Great post by the way. Highly informative for the pynoobs. From aahz at pythoncraft.com Tue Aug 3 00:02:59 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2010 21:02:59 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Roy Smith wrote: >In article , aahz at pythoncraft.com (Aahz) >wrote: >> >> http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html > >The same story has been floating around for eons, just with the names >changed. I saw one where Wirth was ostensibly making fun of the people >who didn't understand that Pascal was all just a joke. > >I'm sure if you go back far enough, you can find a McCarthy / Lisp >version. It probably goes something like, "So, anyway, we tried to >figure out what was the most absurd way to abuse punctuation we could >imagine. Somebody suggested that every program would have to end with >37 close parentheses. When we finally stopped laughing, we started >sketching out a grammar on the chalkboard that would let us do that". http://www.netfunny.com/rhf/jokes/90q2/lispcode.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ (You knew I was going to post that, right?) From aahz at pythoncraft.com Tue Aug 3 00:05:29 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2010 21:05:29 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> <2b473423-0a22-4f4d-943f-31ea2d6020e6@z10g2000yqb.googlegroups.com> Message-ID: In article <2b473423-0a22-4f4d-943f-31ea2d6020e6 at z10g2000yqb.googlegroups.com>, sturlamolden wrote: > >And since this is comp.lang.python, I'll add in that this sometimes >applies to Python as well. Python, like C++, can have the call stack >rewinded by an exception. If we call some raw OS resource allocation, >e.g. malloc or fopen using ctypes, we have to place a deallocation in >__del__ (and make sure the object is newer put in a reference cycle). >The safer option, however, is to use a C extension object, which is >guaranteed to have the destructor called (that is, __dealloc__ when >using Cython or Pyrex). Actually, with Python 2.6 or later, the Pythonic solution is to use ``with``. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From hashah1985 at gmail.com Tue Aug 3 00:06:54 2010 From: hashah1985 at gmail.com (Hiral Shah) Date: Mon, 2 Aug 2010 21:06:54 -0700 Subject: Seeking help with urllib2 response reading Message-ID: Hi All, I am facing problem reading response from urllib2 request. i.e. with read() method. I am trying to access XMLAPI using python. I am getting weird behavior from server, when reading response.Code for calling XMLAPI is as follows: headers = {'Content-type': 'application/x-www-form-urlencoded'} request = urllib2.Request(siteXMLAPIURL,xmlStr,headers) response = urllib2.urlopen(request) print response.read() In above code: xmlStr: is String containing XML request siteXMLAPIURL: URL of the site to send request. It is in form " https://xxx.xxx.com/XXXService/XXXService Problem Description: I am calling URL for creating product by passing methodname(CreateProduct), productId, productCreateDate, productCreateTime etc in XML form. Call to XMLAPI always succeed and product is created on site. But when I call .read() method to print response, then "productCreateTimes" gets changed on server !! For example, Case 1: Not using .read() method. (i.e. commenting print line in above code) Calling API by passing productCreateTime = 08/02/10 08:00:00,and then product is being created with time 08/02/10 08:00:00. i.e. everything is fine here Now, Case 2: Using read() method (i.e. having print line is code) Calling API by passing productCreateTime = 08/02/10 08:00:00 and then product is being created with time 08/02/10 09:00:00. Here, server is adding one more hour to productCrateTime. Which is really strange for me!! FYI: If I access same API with java, everything is fine all time. I am unable to understand why read() method is changing server behavior!! Can anyone please guide me in same? Thank you so much for your time. Waiting for your reply. Thanks, Hiral -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Tue Aug 3 01:01:23 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 2 Aug 2010 22:01:23 -0700 Subject: Trying to run Python 2.7 on Windows 7 and any suggestions onbooks/websites for "dummies guide to python" type learning References: Message-ID: "ben owen" wrote in message news:SNT124-W51CDF963A687DD653CC804CCAD0 at phx.gbl... Hi everyone, I'm new to this and was needing help with trying to learn/work with Python 2.7 on my computer. I'm running Windows 7 and trying to learn python programming from an older book from 1999 by Mark Lutz and David Ascher my boss gave me, and for some reason none of my script/modules for the exercises are working on my comp. Mostly they give either a syntax error on the python command line or something about the file/module not being found on the windows command line. Also, does anyone where i can find/get something similar to the book for my own? Ben ---------------- Post actual code and actual results including error messages (cut-n-paste) and you'll get better answers. Google is your friend for finding books and tutorials. -Mark From sanjeeb25 at gmail.com Tue Aug 3 01:03:14 2010 From: sanjeeb25 at gmail.com (Sanjeeb) Date: Mon, 2 Aug 2010 22:03:14 -0700 (PDT) Subject: sending a file chunk by chunk instead as a whole to a web server References: Message-ID: On Aug 2, 11:52?am, Sanjeeb wrote: > Hi, > I have a web client which send a file to a server as multipart form > data, the sending of data is fromhttp://code.activestate.com/recipes/146306-http-client-to-post-using-.... > > I dont want to open the whole file to memory(at cliend end) and then > send, i just want to send part by part, say chunk of 1024 bytes to the > server and then assemble at the server end. > > Could some one suggest what would be the best way to do this? > > Regards > -Sanjeeb Hey any taker for this question??? From kushal.kumaran+python at gmail.com Tue Aug 3 01:15:27 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 3 Aug 2010 10:45:27 +0530 Subject: sending a file chunk by chunk instead as a whole to a web server In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 12:22 PM, Sanjeeb wrote: > Hi, > I have a web client which send a file to a server as multipart form > data, the sending of data is from > http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/. > > I dont want to open the whole file to memory(at cliend end) and then > send, i just want to send part by part, say chunk of 1024 bytes to the > server and then assemble at the server end. > > Could some one suggest what would be the best way to do this? > There's no reason why sending the whole file implies reading the whole file into memory at one time. You can just read your desired chunk size and send it, then read the next chunk, and so on. You might have to first find the total size to calculate what to set Content-Length to. ISTR questions of this nature have been asked in the past on this list. -- regards, kushal From michele.simionato at gmail.com Tue Aug 3 01:28:15 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 2 Aug 2010 22:28:15 -0700 (PDT) Subject: let optionparse.Optionparser ignore unknown command line switches. References: <4c5555c5$0$19337$426a74cc@news.free.fr> Message-ID: On Aug 1, 1:08?pm, News123 wrote: > I wondered, whether there's a simple/standard way to let > the Optionparser just ignore unknown command line switches. > > thanks in advance for any ideas I will plug in my own work on plac: http://pypi.python.org/pypi/plac Your problem would be solved as follows: import plac @plac.annotations(test=('a flag', 'flag', 't')) def main(test, *ignore): print test, ignore if __name__ == '__main__': plac.call(main, ["-t","--ignoreme_and_dont_fail"]) From ryan at rfk.id.au Tue Aug 3 01:52:32 2010 From: ryan at rfk.id.au (Ryan Kelly) Date: Tue, 03 Aug 2010 15:52:32 +1000 Subject: sending a file chunk by chunk instead as a whole to a web server In-Reply-To: References: Message-ID: <1280814752.2158.62.camel@durian> On Tue, 2010-08-03 at 10:45 +0530, Kushal Kumaran wrote: > On Mon, Aug 2, 2010 at 12:22 PM, Sanjeeb wrote: > > Hi, > > I have a web client which send a file to a server as multipart form > > data, the sending of data is from > > http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/. > > > > I dont want to open the whole file to memory(at cliend end) and then > > send, i just want to send part by part, say chunk of 1024 bytes to the > > server and then assemble at the server end. > > > > Could some one suggest what would be the best way to do this? > > > > There's no reason why sending the whole file implies reading the whole > file into memory at one time. You can just read your desired chunk > size and send it, then read the next chunk, and so on. You might have > to first find the total size to calculate what to set Content-Length > to. More concretely, you would restructure the encode_multipart_formdata() function as a generator, yielding chunks of data to send one at a time. Something like this: def post_multipart(host,selector,fields,files): ...snip... h.endheaders() for chunk in encode_multipart_formdata_chunks(fields,files): h.send(chunk) errcode, errmsg, headers = h.getreply() return h.file.read() def encode_multipart_formdata(fields,files): BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' for (key, value) in fields: yield '--' + BOUNDARY yield 'Content-Disposition: form-data; name="%s"' % key yield '' yield value for (key, filename, value) in files: yield '--' + BOUNDARY yield 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename) ...etc... ...etc... There are many improvements to make, but this should get you started. For example, you'll need to calculate the total content-length rather than just calling len(body) to obtain it. That's left as an exercise to the reader. Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From nikos.the.gr33k at gmail.com Tue Aug 3 02:03:18 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 2 Aug 2010 23:03:18 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> >On 2 ???, 23:57, Thomas Jollans wrote: > So: tripple-check that > > ?* your file is > ?* Python knows that > ?* the web browser knows that Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 / n''' and it worked. I'am still pretty confused about the encodings. Please tell me the difference between 3 things. a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 without BOM. b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed to tell browser that the contents of this python script as in UTF-8 and to handle it as such? c) print ''' Content-Type: text/html; charset=UTF-8 /n''' Please explain to me as simple as you can because from the time with php and perl encodings not only gave me a hard time but also caused my program to produce internal server errors so i need to understand the differences. ========================= Also in the other problem with the cookie iam trying to set: ========================= if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist print "Next time i will count you" cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire now else: print "I wont be counting you any more" cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year ========================= Why always the code block pertainign to 'else' get exectuted ane never the code of 'if' The idea is who ever runs 'koukos.py' to set/unset himself out of the counter count so i need i way to set/unset the browser cookie! Thanks you! From nikos.the.gr33k at gmail.com Tue Aug 3 02:03:18 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 2 Aug 2010 23:03:18 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> >On 2 ???, 23:57, Thomas Jollans wrote: > So: tripple-check that > > ?* your file is > ?* Python knows that > ?* the web browser knows that Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 / n''' and it worked. I'am still pretty confused about the encodings. Please tell me the difference between 3 things. a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 without BOM. b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed to tell browser that the contents of this python script as in UTF-8 and to handle it as such? c) print ''' Content-Type: text/html; charset=UTF-8 /n''' Please explain to me as simple as you can because from the time with php and perl encodings not only gave me a hard time but also caused my program to produce internal server errors so i need to understand the differences. ========================= Also in the other problem with the cookie iam trying to set: ========================= if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist print "Next time i will count you" cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire now else: print "I wont be counting you any more" cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year ========================= Why always the code block pertainign to 'else' get exectuted ane never the code of 'if' The idea is who ever runs 'koukos.py' to set/unset himself out of the counter count so i need i way to set/unset the browser cookie! Thanks you! From steve-REMOVE-THIS at cybersource.com.au Tue Aug 3 02:20:12 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2010 06:20:12 GMT Subject: simple (I hope!) problem References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> Message-ID: <4c57b51c$0$28663$c3e8da3@news.astraweb.com> On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote: > Fortunately, I don't need the functionality of the object, I just want > something that won't generate an error when I use it. So, what is the > quickest way to to create such an object (replacing the 'pass' in my > first snippet). My solution is this: > > class C: > def filter(self, *args, **kwds): > pass > register = C() > > but it seems like I should be able to do something "better", as measured > by lines of code, faking more than just a 'filter' method, or both. Any > ideas? Thanks! You want a variation on the Null Object design pattern. class NullWithMethods(object): def __getattr__(self, name): return self def __call__(self, *args, **kwargs): pass And in action: >>> c = NullWithMethods() >>> c.spam("hello", "world") >>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42) -- Steven From alanwilter at gmail.com Tue Aug 3 02:35:30 2010 From: alanwilter at gmail.com (Alan) Date: Tue, 3 Aug 2010 07:35:30 +0100 Subject: please, help with python 3.1 Message-ID: Hello List, Please, can someone at least try this code below in python 3 and report me back whether it works or not? Because for me this code works in python 2.6 but not with python 3.1. Thanks! from __future__ import print_function import os, subprocess, signal def signal_handler( signum, frame ): print( "PID: %s" % pid ) print( "Timed out! Process %s killed, max exec time (%ss) exceeded" % (pid, timeTol ) ) os.kill( int( pid ), 15 ) raise Exception( "Taking too long to finish... aborting!" ) if __name__ == '__main__': timeTol = 5 cmd = 'find /' signal.signal(signal.SIGALRM, signal_handler) signal.alarm(timeTol) p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout = subprocess.PIPE) pid = p.pid out = str( p.communicate()[0].decode() ) print(out) Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Aug 3 03:11:35 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 00:11:35 -0700 Subject: please, help with python 3.1 In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 11:35 PM, Alan wrote: > Hello List, > Please, can someone at least try this code below in python 3 and report me > back whether it works or not? Because for me this code works in python 2.6 > but not with python 3.1. Thanks! Please specify *in exactly what way* the code is not working. Is an exception being thrown? Then include the full traceback. Is the behavior not what you expected/intended? Then say what it's doing vs. what you want it to do. Cheers, Chris -- Getting Debugging Help 101: Don't just say "there's a problem". Say what the problem is. http://blog.rebertia.com From rantingrick at gmail.com Tue Aug 3 03:23:36 2010 From: rantingrick at gmail.com (rantingrick) Date: Tue, 3 Aug 2010 00:23:36 -0700 (PDT) Subject: please, help with python 3.1 References: Message-ID: <49143c92-7011-436f-a0e7-072ed3ce0c4b@f33g2000yqe.googlegroups.com> On Aug 3, 2:11?am, Chris Rebert wrote: > On Mon, Aug 2, 2010 at 11:35 PM, Alan wrote: > > Hello List, > > Please, can someone at least try this code below in python 3 and report me > > back whether it works or not? Because for me this code works in python 2.6 > > but not with python 3.1. Thanks! Oh my Gawd! Python3x is not backwards compatible! 8^O You know it would be nice if you "esteemed" Pythonista's would send out a newsletter or something before making changes that could break code. We are trying to maintain a code base out here you know. Geez! From clp2 at rebertia.com Tue Aug 3 03:28:04 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 00:28:04 -0700 Subject: please, help with python 3.1 In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Alan Date: Tue, Aug 3, 2010 at 12:25 AM Subject: Re: please, help with python 3.1 To: Chris Rebert Sorry, I will explain. I am using for a task 'find /' expecting this to last longer, usually much longer than 5 sec. If you run the code I sent in python 2.6, it will stop after 5 sec and print messages. If you run the same code in python3 (and if your task last more than 5 sec as expected, otherwise replace "cmd = 'find /'" with something suitable), python3 alarm doesn't work and the job is not stopped after 5 sec, taking minutes to finish. I hope it may help you to help me. Thanks, Alan On Tue, Aug 3, 2010 at 08:11, Chris Rebert wrote: > > On Mon, Aug 2, 2010 at 11:35 PM, Alan wrote: > > Hello List, > > Please, can someone at least try this code below in python 3 and report me > > back whether it works or not? Because for me this code works in python 2.6 > > but not with python 3.1. Thanks! > > Please specify *in exactly what way* the code is not working. > Is an exception being thrown? Then include the full traceback. > Is the behavior not what you expected/intended? Then say what it's > doing vs. what you want it to do. > > Cheers, > Chris > -- > Getting Debugging Help 101: Don't just say "there's a problem". Say > what the problem is. > http://blog.rebertia.com -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< From rantingrick at gmail.com Tue Aug 3 03:36:40 2010 From: rantingrick at gmail.com (rantingrick) Date: Tue, 3 Aug 2010 00:36:40 -0700 (PDT) Subject: Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning References: Message-ID: <96774aef-5dba-4db8-8d96-65d731148ef4@q35g2000yqn.googlegroups.com> On Aug 2, 5:32?pm, James Mills wrote: > On Tue, Aug 3, 2010 at 8:07 AM, ben owen wrote: > > Hi everyone, I'm new to this and was needing help with trying to learn/work > > with Python 2.7 on my computer. I'm running Windows 7 and trying to learn > > python programming from an older book from 1999 by Mark Lutz and David > > Ascher my boss gave me, First of all why are you trusting your boss to provide adequate manuals? Your boss is obviously an idiot because if he knew anything about Python then why would need you? And why the heck would he give you reading material that is 11 years old? All you have to do is type "Python Tutorial" into any search engine to find tons of tuts available. > > and for some reason none of my script/modules for > > the exercises are working on my comp. Mostly they give either a syntax error > > on the python command line or something about the file/module not being > > found on the windows command line. Changes were made in Python3.0 that are not backwards compatible. What version of Python do you have installed currently and what version is the tutorial/book intended for? These would be good questions to ask yourself. Be aware that current releases of Python2.7 and Python3.1.2 are available for download free of charge (psst: all you have to do is sign over your soul to Guido, but who needs a soul anyway?). Heck, at one time they were even giving out free t-shirts and coffee mugs to first 100 downloads. From clp2 at rebertia.com Tue Aug 3 03:39:45 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 00:39:45 -0700 Subject: Trying to set a cookie within a python script In-Reply-To: <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: 2010/8/2 ????? : >>On 2 ???, 23:57, Thomas Jollans wrote: > >> So: tripple-check that >> >> ?* your file is >> ?* Python knows that >> ?* the web browser knows that > > Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 / > n''' and it worked. > I'am still pretty confused about the encodings. > > Please tell me the difference between 3 things. > > a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 > without BOM. That affects what encoding the text file comprising the source code itself is in. > b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed > to tell browser that the contents of this python script as in UTF-8 > and to handle it as such? This tells Python what encoding the text file comprising the source code itself is in. > c) print ''' Content-Type: text/html; charset=UTF-8 /n''' This tells the web browser what encoding the HTML you're sending it is in. Said HTML is output by your Python script and must match the encoding you specify in (c). Unless you have Unicode string literals in the source code itself, (a) and (b) don't matter much. (c) is quite crucial. Cheers, Chris -- http://blog.rebertia.com From rantingrick at gmail.com Tue Aug 3 03:42:49 2010 From: rantingrick at gmail.com (rantingrick) Date: Tue, 3 Aug 2010 00:42:49 -0700 (PDT) Subject: please, help with python 3.1 References: Message-ID: On Aug 3, 2:28?am, Chris Rebert wrote: > ---------- Forwarded message ---------- > From: Alan > Date: Tue, Aug 3, 2010 at 12:25 AM > Subject: Re: please, help with python 3.1 > To: Chris Rebert > > Sorry, > I will explain. Well it looks like he forgot to post the traceback! From __peter__ at web.de Tue Aug 3 04:00:26 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Aug 2010 10:00:26 +0200 Subject: constructing and using large lexicon in a program References: <119487.45857.qm@web113614.mail.gq1.yahoo.com> Message-ID: Majdi Sawalha wrote: > I am developing a morphological analyzer that depends on a large lexicon. > i construct a Lexicon class that reades a text file and construct a > dictionary of the lexicon entries. > the other class will use the lexicon class to chech if the word is found > in the lexicon. the problem that this takes long time as each time an > object of that class created, then it needs to call the lexicon many > times. then when the lexicon is called it re-construct the lexicon again. > is there any way to construct the lexicon one time during the execution of > the program? and then the other modules will search the already > constructed lexicon. Normally you just structure your application accordingly. Load the dictionary once and then pass it around explicitly: import loader import user_one import user_two filename = ... large_dict = loader.load(filename) user_one.use_dict(large_dict) user_two.use_dict(large_dict) You may also try a caching scheme to avoid parsing the text file unless it has changed. Here's a simple example: $ cat cachedemo.py import cPickle as pickle import os def load_from_text(filename): # replace with your code with open(filename) as instream: return dict(line.strip().split(None, 1) for line in instream) def load(filename, cached=None): if cached is None: cached = filename + ".pickle" if os.path.exists(cached) and os.path.getmtime(filename) <= os.path.getmtime(cached): print "using pickle" with open(cached, "rb") as instream: return pickle.load(instream) else: print "loading from text" d = load_from_text(filename) with open(cached, "wb") as out: pickle.dump(d, out, pickle.HIGHEST_PROTOCOL) return d if __name__ == "__main__": if not os.path.exists("tmp.txt"): print "creating example data" with open("tmp.txt", "w") as out: out.write("""\ alpha value for alpha beta BETA gamma GAMMA """) print load("tmp.txt") $ python cachedemo.py creating example data loading from text {'alpha': 'value for alpha', 'beta': 'BETA', 'gamma': 'GAMMA'} $ python cachedemo.py using pickle {'alpha': 'value for alpha', 'beta': 'BETA', 'gamma': 'GAMMA'} $ echo 'delta modified text' >> tmp.txt $ python cachedemo.py loading from text {'alpha': 'value for alpha', 'beta': 'BETA', 'gamma': 'GAMMA', 'delta': 'modified text'} $ python cachedemo.py using pickle {'alpha': 'value for alpha', 'beta': 'BETA', 'gamma': 'GAMMA', 'delta': 'modified text'} Peter From davea at ieee.org Tue Aug 3 04:10:15 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 03 Aug 2010 04:10:15 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: <4C57CEE7.2090407@ieee.org> ????????????????????????????????? wrote: >> On 2 ???, 23:57, Thomas Jollans wrote: >> > > >> So: tripple-check that >> >> * your file is >> * Python knows that >> * the web browser knows that >> > > Thank you! i used print ''' Content-Type: text/html; charset=F-8 / > n''' and it worked. > I'am still pretty confused about the encodings. > > Please tell me the difference between 3 things. > > a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 > without BOM. > b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed > to tell browser that the contents of this python script as in UTF-8 > and to handle it as such? > c) print ''' Content-Type: text/html; charset=F-8 /n''' > > Please explain to me as simple as you can because from the time with > php and perl encodings not only gave me a hard time but also caused my > program to produce internal server errors so i need to understand the > differences. > > There actually should be more than 3 things here. To understand the distinctions you have to see who handles which data, and how. a) a text editor takes keystrokes and cut/paste info and other data, and produces a stream of (unicode) characters. It then encodes each of those character into one or more bytes and saves it to a file. You have to tell Notepad++ how to do that encoding. Note that unless it's saving a BOM, there's no clue in the file what encoding it used. b) The python compiler has to interpret the bytes it finds (spec. within string literals and comments), and decode them into unicode for its own work. It uses the 'coding:' comment to decide how to do this. But once the file has been compiled, that comment is totally irrelevant, and ignored. c1) Your python code has to decide how to encode its information when writing to stdout. There are several ways to accomplish that. c2) The browser sees only what was sent to stdout, starting with the "Content-Type..." line. It uses that line to decide how to decode the rest of the stream. Let me reemphasize, the browser does not see any of the python code, or comments. DaveA From s.selvamsiva at gmail.com Tue Aug 3 04:15:44 2010 From: s.selvamsiva at gmail.com (S.Selvam) Date: Tue, 3 Aug 2010 13:45:44 +0530 Subject: web and standalone access Message-ID: Hi all, I have a case where my application needs to run as a standalone application and also allow web based access. What could the best python framework to implement it. Note : I found Openobject( openerp ) to be of this kind. I hope i can get more ideas here . -- Regards, S.Selvam " I am because we are " -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Tue Aug 3 04:25:08 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 18:25:08 +1000 Subject: web and standalone access In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 6:15 PM, S.Selvam wrote: > I have a case where my application needs to run as a standalone application > and also allow web based access. > > What could the best python framework to implement it. Both CherryPy and circuits.web sport a "single click 'n run" capability using python's webbrowser module. 1. http://tools.cherrypy.org/wiki/SingleClickAndRun 2. http://bitbucket.org/prologic/circuits/src/tip/examples/web/singleclickandrun.py I'm sure there are many other suitable frameworks and way of doing this. I've been experimenting myself with embedded circuits.web with pygtk and webkit with some success (similar to Adobe Air). cheers James -- -- James Mills -- -- "Problems are solved by method" From nobody at nowhere.com Tue Aug 3 04:32:58 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 03 Aug 2010 09:32:58 +0100 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 02 Aug 2010 17:17:35 -0700, Peter wrote: > But I always used to tell > people - by the time I got a program to compile then I figured 99% of > the bugs were already discovered! Try that with C/C++ or almost any > other language you care to name :-) ML and Haskell are also quite good for this (although I wish they supported integer subranges). Also, the statelessness of FP eliminates entire classes of bugs. From nobody at nowhere.com Tue Aug 3 04:36:16 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 03 Aug 2010 09:36:16 +0100 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Mon, 02 Aug 2010 15:18:30 -0700, sturlamolden wrote: >> Has it ever been planned to rewrite in C++ the historical implementation >> (of course in an object oriented design) ? > > OO programming is possible in C. Just take a look at GNOME and GTK. One feature which can't readily be implemented in C is the automatic clean-up side of the RAII idiom. From clp2 at rebertia.com Tue Aug 3 04:37:14 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 01:37:14 -0700 Subject: Performance ordered dictionary vs normal dictionary In-Reply-To: References: <899AA0B8-A382-4B07-BC1B-7E9704F42A66@gmail.com> <8E369CBF-A2D2-406C-8AD6-22A85258D449@gmail.com> Message-ID: On Fri, Jul 30, 2010 at 9:18 PM, Dan Stromberg wrote: > On Wed, Jul 28, 2010 at 11:11 PM, Chris Rebert wrote: >> (You are aware that the "ordered" in OrderedDict means that its keys >> are ordered, and not that, say, a list containing OrderedDicts can be >> sorted, right?) > > > Actually, a collections.OrderedDict saves things not in key order, but in > chronological order: Well yeah, that's why I specifically said "ordered" as opposed to the less awkward and more obvious but completely inaccurate "sorted" (== your "key order"). - Chris From parvini_navid at yahoo.com Tue Aug 3 04:45:29 2010 From: parvini_navid at yahoo.com (Navid Parvini) Date: Tue, 3 Aug 2010 01:45:29 -0700 (PDT) Subject: PIL Message-ID: <882435.39022.qm@web51008.mail.re2.yahoo.com> Dear All, I want to convert a .png file to .xpm using PIL. I used the following command: Image.open( "t1.png").save("a1.xpm"). But it doesn't work and I could not convert it. Would you please help me and let me know that how can I convert/save .xpm files in PIL. Thank you in advance. Thanks. Navid -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Aug 3 04:46:21 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 01:46:21 -0700 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Tue, Aug 3, 2010 at 1:36 AM, Nobody wrote: > On Mon, 02 Aug 2010 15:18:30 -0700, sturlamolden wrote: >>> Has it ever been planned to rewrite in C++ the historical implementation >>> (of course in an object oriented design) ? >> >> OO programming is possible in C. ?Just take a look at GNOME and GTK. > > One feature which can't readily be implemented in C is the automatic > clean-up side of the RAII idiom. That's not directly related to object-orientation though. Cheers, Chris From nobody at nowhere.com Tue Aug 3 04:47:55 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 03 Aug 2010 09:47:55 +0100 Subject: checking that process binds a port, fuser functionality References: Message-ID: On Mon, 02 Aug 2010 23:27:37 +0200, Zdenek Maxa wrote: > I need to start a process (using subprocess.Popen()) and wait until the > new process either fails or successfully binds a specified port. The > fuser command seems to be indented exactly for this purpose. Could > anyone please provided a hint to a handy Python library to do this or > would the advice be to parse fuser command output? > > This needs to happen on Linux and Python 2.4. fuser (when applied to a TCP socket) scans /proc/net/tcp to obtain the inode number, then scans /proc/[1-9]*/fd/* for a reference to the inode. This requires sufficient privileges to enumerate the /proc//fd directories (i.e. if you aren't running as root, fuser will ignore any processes which you don't own). If you just need to wait until *something* is listening on that port, you could try connect()ing to it. Alternatively, you can monitor /proc/net/tcp until the relevant port appears. If you know which process will be using the port, you can just scan the /proc//fd directory for that process, rather than checking all processes. You still need to use /proc/net/tcp to obtain the inode number. From prologic at shortcircuit.net.au Tue Aug 3 04:48:24 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 18:48:24 +1000 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Tue, Aug 3, 2010 at 6:36 PM, Nobody wrote: > One feature which can't readily be implemented in C is the automatic > clean-up side of the RAII idiom. C is a Turing-Complete Language is it not ? If so, therefore is it not true "anything" can be implemented ? Even the "automated clean-up side of the RAIL idiom" ? cheers James -- -- James Mills -- -- "Problems are solved by method" From prologic at shortcircuit.net.au Tue Aug 3 04:55:14 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 18:55:14 +1000 Subject: PIL In-Reply-To: <882435.39022.qm@web51008.mail.re2.yahoo.com> References: <882435.39022.qm@web51008.mail.re2.yahoo.com> Message-ID: On Tue, Aug 3, 2010 at 6:45 PM, Navid Parvini wrote: > I want to convert a .png file to .xpm using PIL. I used the following > command: > Image.open( "t1.png").save("a1.xpm"). But it doesn't work and I could not > convert it. > > Would you please help me and let me know that how can I convert/save .xpm > files in PIL. > Reading PIL's documentation might help. Try: $ pydoc Image cheers James -- -- James Mills -- -- "Problems are solved by method" -------------- next part -------------- An HTML attachment was scrubbed... URL: From landimatte at gmail.com Tue Aug 3 04:55:25 2010 From: landimatte at gmail.com (Matteo Landi) Date: Tue, 3 Aug 2010 10:55:25 +0200 Subject: PIL In-Reply-To: <882435.39022.qm@web51008.mail.re2.yahoo.com> References: <882435.39022.qm@web51008.mail.re2.yahoo.com> Message-ID: I don't think yours is a permitted conversion[1]. It seems that PIL supports xpm format only for reading, but I could be wrong. Regards. [1] http://www.daniweb.com/forums/thread260074.html On Tue, Aug 3, 2010 at 10:45 AM, Navid Parvini wrote: > Dear All, > > I want to convert a .png file to .xpm using PIL. I used the following > command: > Image.open( "t1.png").save("a1.xpm"). But it doesn't work and I could not > convert it. > > Would you please help me and let me know that how can I convert/save .xpm > files in PIL. > > Thank you in advance. > > Thanks. > Navid > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Matteo Landi http://www.matteolandi.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Aug 3 04:56:20 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 01:56:20 -0700 Subject: PIL In-Reply-To: <882435.39022.qm@web51008.mail.re2.yahoo.com> References: <882435.39022.qm@web51008.mail.re2.yahoo.com> Message-ID: On Tue, Aug 3, 2010 at 1:45 AM, Navid Parvini wrote: > Dear All, > > I want to convert a .png file to .xpm using PIL. I used the following command: > Image.open( "t1.png").save("a1.xpm"). But it doesn't work and I could not convert it. > > Would you please help me and let me know that how can I convert/save .xpm files in PIL. PIL only supports reading .XPM, not writing .XPM: http://www.pythonware.com/library/pil/handbook/format-xpm.htm Cheers, Chris -- http://blog.rebertia.com From steve-REMOVE-THIS at cybersource.com.au Tue Aug 3 05:04:08 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2010 09:04:08 GMT Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: <4c57db88$0$11101$c3e8da3@news.astraweb.com> On Tue, 03 Aug 2010 18:48:24 +1000, James Mills wrote: > On Tue, Aug 3, 2010 at 6:36 PM, Nobody wrote: >> One feature which can't readily be implemented in C is the automatic >> clean-up side of the RAII idiom. > > C is a Turing-Complete Language is it not ? > > If so, therefore is it not true "anything" can be implemented ? Even the > "automated clean-up side of the RAIL idiom" ? True, but Nobody said it can't *readily* be implemented, not that it can't be. -- Steven From nikos.the.gr33k at gmail.com Tue Aug 3 05:06:05 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Tue, 03 Aug 2010 12:06:05 +0300 Subject: Trying to set a cookie within a python script In-Reply-To: References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: <4C57DBFD.5040107@gmail.com> ???? 3/8/2010 10:39 ??, ?/? Chris Rebert ??????: >> Please tell me the difference between 3 things. >> >> a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 >> without BOM. > That affects what encoding the text file comprising the source code > itself is in. What does this practically mean? Perhaps you mean that it affects the way this file will be stored in the hard disk? For example is it different to say to Notapad++ to save it as 'Asci'i and different to save it as 'UTF-8 without BOM'? What should i use? My script only containes python code(english) and greek chars inside print statemetns. >> b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed >> to tell browser that the contents of this python script as in UTF-8 >> and to handle it as such? > This tells Python what encoding the text file comprising the source > code itself is in. > What practically does this mean? What difference does it have with (a) ? >> c) print ''' Content-Type: text/html; charset=UTF-8 /n''' > This tells the web browser what encoding the HTML you're sending it is > in. Said HTML is output by your Python script and must match the > encoding you specify in (c). When a python script runs it produces html output or only after the python's output to the Web Server the html output is produced? From steve-REMOVE-THIS at cybersource.com.au Tue Aug 3 05:07:29 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2010 09:07:29 GMT Subject: please, help with python 3.1 References: Message-ID: <4c57dc50$0$11101$c3e8da3@news.astraweb.com> Hello Alan, I'm sorry, I can't see the code you say you posted. I can't see ANY of your posts, only the replies from Chris Rebert. Are you using Google Groups to post? If so, many people here will have difficulty seeing your posts, as Google Groups is notorious for allowing spammers, and in self-defence many mailing lists and newsgroups just ignore anything from Google Groups. Looking at the message Chris forwarded: [quote] I am using for a task 'find /' expecting this to last longer, usually much longer than 5 sec. If you run the code I sent in python 2.6, it will stop after 5 sec and print messages. If you run the same code in python3 (and if your task last more than 5 sec as expected, otherwise replace "cmd = 'find /'" with something suitable), python3 alarm doesn't work and the job is not stopped after 5 sec, taking minutes to finish. [end quote] I'm sorry, but I can't make heads or tails of that. At the very least, you need to explain what code you are using, and what the problem is. What do you mean "python3 alarm doesn't work"? What alarm? What do you mean it doesn't work? Just saying "it doesn't work" is pointless. Is the problem that your code runs in seconds under Python 2.6 and takes minutes under Python 3.1? Are you sure you are using 3.1 and not 3.0? 3.0 is VERY slow and should be avoided. We may need to see your code, and some sample data, in order to have any hope of helping you. Regards, Steven. On Tue, 03 Aug 2010 00:28:04 -0700, Chris Rebert wrote: > ---------- Forwarded message ---------- From: Alan > > Date: Tue, Aug 3, 2010 at 12:25 AM > Subject: Re: please, help with python 3.1 To: Chris Rebert > > > Sorry, > I will explain. I am using for a task 'find /' expecting this to last > longer, usually much longer than 5 sec. If you run the code I sent in > python 2.6, it will stop after 5 sec and print messages. > If you run the same code in python3 (and if your task last more than 5 > sec as expected, otherwise replace "cmd = 'find /'" with something > suitable), python3 alarm doesn't work and the job is not stopped after 5 > sec, taking minutes to finish. > I hope it may help you to help me. > Thanks, > Alan > > On Tue, Aug 3, 2010 at 08:11, Chris Rebert wrote: >> >> On Mon, Aug 2, 2010 at 11:35 PM, Alan wrote: >> > Hello List, >> > Please, can someone at least try this code below in python 3 and >> > report me back whether it works or not? Because for me this code >> > works in python 2.6 but not with python 3.1. Thanks! >> >> Please specify *in exactly what way* the code is not working. Is an >> exception being thrown? Then include the full traceback. Is the >> behavior not what you expected/intended? Then say what it's doing vs. >> what you want it to do. >> >> Cheers, >> Chris >> -- >> Getting Debugging Help 101: Don't just say "there's a problem". Say >> what the problem is. >> http://blog.rebertia.com -- Steven From prologic at shortcircuit.net.au Tue Aug 3 05:23:00 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 19:23:00 +1000 Subject: Why is python not written in C++ ? In-Reply-To: <4c57db88$0$11101$c3e8da3@news.astraweb.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> <4c57db88$0$11101$c3e8da3@news.astraweb.com> Message-ID: On Tue, Aug 3, 2010 at 7:04 PM, Steven D'Aprano wrote: > True, but Nobody said it can't *readily* be implemented, not that it > can't be. So he did too :) I read that as "really" :/ --James -- -- James Mills -- -- "Problems are solved by method" From awilter at ebi.ac.uk Tue Aug 3 05:28:49 2010 From: awilter at ebi.ac.uk (Alan Wilter Sousa da Silva) Date: Tue, 3 Aug 2010 10:28:49 +0100 Subject: please, help with python 3.1 In-Reply-To: References: Message-ID: Ok: Here goes the code again and results: from __future__ import print_function import os, subprocess, signal def signal_handler( signum, frame ): print( "PID: %s" % pid ) print( "Timed out! Process %s killed, max exec time (%ss) exceeded" % (pid, timeTol ) ) os.kill( int( pid ), 15 ) raise Exception( "Taking too long to finish... aborting!" ) if __name__ == '__main__': timeTol = 5 cmd = 'find /' signal.signal(signal.SIGALRM, signal_handler) signal.alarm(timeTol) p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout = subprocess.PIPE) pid = p.pid out = str( p.communicate()[0].decode() ) print(out) ---------------------------------------------------- time python2.6 timout.py PID: 27644 Timed out! Process 27644 killed, max exec time (5s) exceeded Traceback (most recent call last): File "timout.py", line 23, in out = str( p.communicate()[0].decode() ) File "/sw/lib/python2.6/subprocess.py", line 693, in communicate stdout = self.stdout.read() File "timout.py", line 9, in signal_handler raise Exception( "Taking too long to finish... aborting!" ) Exception: Taking too long to finish... aborting! python2.6 timout.py 0.10s user 0.47s system 11% cpu 5.113 total #### WORKED as expected #### ---------------------------------------------------- Now with python3.1: ---------------------------------------------------- time python3.1 timout.py PID: 27687 Timed out! Process 27687 killed, max exec time (5s) exceeded Traceback (most recent call last): File "timout.py", line 23, in out = str( p.communicate()[0].decode() ) File "/sw/lib/python3.1/subprocess.py", line 719, in communicate stdout = self.stdout.read() File "timout.py", line 9, in signal_handler raise Exception( "Taking too long to finish... aborting!" ) Exception: Taking too long to finish... aborting! python3.1 timout.py 0.52s user 3.88s system 19% cpu 22.841 total #### It prints essentially the same thing with a *very* *big* difference it takes 22 seconds and actually the alarm only works when the whole task ('find /') is finished. ---------------------------------------------------- I hope it's better now. Thanks, Alan On Tue, Aug 3, 2010 at 08:42, rantingrick wrote: > On Aug 3, 2:28 am, Chris Rebert wrote: > > ---------- Forwarded message ---------- > > From: Alan > > Date: Tue, Aug 3, 2010 at 12:25 AM > > Subject: Re: please, help with python 3.1 > > To: Chris Rebert > > > > Sorry, > > I will explain. > > Well it looks like he forgot to post the traceback! > -- > http://mail.python.org/mailman/listinfo/python-list > -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at castleamber.com Tue Aug 3 05:29:35 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 04:29:35 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> Message-ID: <87d3u0niww.fsf@castleamber.com> Carl Banks writes: > On Aug 1, 6:09?pm, John Bokma wrote: >> Roy Smith writes: >> > In article <4c55fe82$0$9111$426a3... at news.free.fr>, >> > ?candide wrote: >> >> >> Python is an object oriented langage (OOL). The Python main >> >> implementation is written in pure and "old" C90. Is it for historical >> >> reasons? >> >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> >> suitable to implement an OOL with another one. >> >> > One thing that comes to mind is that it's much easier to distribute C >> > libraries than C++ libraries. >> >> In the beginning of C++ there were programs that just converted C++ to C >> (frontends). At least that is how the C++ compiler Acorn sold worked. >> So I don't think your argument was much true back then. > > No, it was that way back then too. They might all generate C code but > different C code by different backends wouldn't be able to call each > other natively. If you convert C++ to C, and compile the C code then that's not different from compiling the C code itself, correct? > For instnace the function > > int foo(int); > > might be name-mangled this way in one cfront: > > foo$d > > and this way in another: > > ____int_foo__int_i But they call both the C libraries in the same way. > The virtual table of this class: > > class Bar { > virtual int foo(int); > virtual int bar(int); > }; > > might be generated like this in one cfront: > > struct Bar$$Vtable$ { > int (*Bar$$bar$d)(int); > int (*Bar$$foo$d)(int); > }; > > and like this in another: > > struct ____class_Foo___vtable_ { > int (*foo)(int); > int (*bar)(int); > }; > > > So, just because they both generated C code, it doesn't mean they can > call one another. Why would they need to call each other? The compiled C++ code ends up as being compiled generated C code. It has been a while, but I am quite sure that the Acorn C++ front end I used could dump the actual generated C code. And this generated code should compile with a normal C compiler on a different platform. The only exception I can think of is if the front end comes with libraries you have to link against. But since this should be C as well (since there is no native C++), I don't see any problem to recreate those libraries. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From jeanmichel at sequans.com Tue Aug 3 05:33:36 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 03 Aug 2010 11:33:36 +0200 Subject: namespaces, scoping and variables In-Reply-To: <48558d95-aaaa-4a6e-9ffb-68d4f2429c62@w15g2000pro.googlegroups.com> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> <4C572486.1030308@mrabarnett.plus.com> <48558d95-aaaa-4a6e-9ffb-68d4f2429c62@w15g2000pro.googlegroups.com> Message-ID: <4C57E270.7000201@sequans.com> rantingrick wrote: > On Aug 2, 3:12 pm, Chris Hare wrote: > > Also you should use 4 space indention and never use tabs. This is the > accepted way. Then ask yourself why tabs are still in python 3. Nice troll by the way. JM From john at castleamber.com Tue Aug 3 05:34:49 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 04:34:49 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <877hk8nio6.fsf@castleamber.com> Albert Hopkins writes: > But I wonder if someone has/has tried to write a programming language in > C++ and what were their experiences. The Low Level Virtual Machine (LLVM) is a compiler infrastructure, written in C++, which is designed for compile-time, link-time, run-time, and "idle-time" optimization of programs written in arbitrary programming languages. Originally implemented for C/C++, the language-independent design (and the success) of LLVM has since spawned a wide variety of front ends, including Objective-C, Fortran, Ada, Haskell, Java bytecode, Python, Ruby, ActionScript, GLSL, and others. http://en.wikipedia.org/wiki/LLVM Unladen Swallow is a branch of Python intended to be fully compatible and significantly faster. It uses LLVM's optimization passes and JIT compiler. http://llvm.org/ProjectsWithLLVM/#unladenswallow -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From john at castleamber.com Tue Aug 3 05:38:35 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 04:38:35 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> Message-ID: <8739uwnihw.fsf@castleamber.com> Michael Torrie writes: > On 08/01/2010 07:09 PM, John Bokma wrote: >>> One thing that comes to mind is that it's much easier to distribute C >>> libraries than C++ libraries. >> >> In the beginning of C++ there were programs that just converted C++ to C >> (frontends). At least that is how the C++ compiler Acorn sold worked. >> So I don't think your argument was much true back then. > > No, he is still right. Each C++ implementation did name mangling > differently leading to "C" libraries that had incompatible names and > signatures. Also each frontend could have generated incompatible > vtables and other C++ structures. So C code generated by one C++ > frontend could not easily call C code generated by another C++ frontend. > So the same arguments that are made about C++ now were just as valid > back then when C++ was merely a fancy preprocessor. See my other post: I understand that two C++ preprocessors can't call each others generated code, but if one uses C++ and knows that one can only use shared C libraries on target systems, and not C++ libraries that might be present (or more likely not: C++ was new in those days). -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From nobody at nowhere.com Tue Aug 3 05:45:06 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 03 Aug 2010 10:45:06 +0100 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Tue, 03 Aug 2010 18:48:24 +1000, James Mills wrote: >> One feature which can't readily be implemented in C is the automatic >> clean-up side of the RAII idiom. > > C is a Turing-Complete Language is it not ? > > If so, therefore is it not true "anything" can be implemented ? > Even the "automated clean-up side of the RAIL idiom" ? By "automated", I mean the fact that destructors get called automatically when a local variable goes out of scope, whether by reaching the end of the block, return, break, continue, or an exception. In C, the clean-up has to be made explicit, i.e. not "automated". From no.email at nospam.invalid Tue Aug 3 05:48:30 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 02:48:30 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: <7xy6co6n81.fsf@ruckus.brouhaha.com> Nobody writes: > One feature which can't readily be implemented in C is the automatic > clean-up side of the RAII idiom. I once did that by having an explicit stack of finalization records linked through the call stack. The "throw" routine would traverse the links to call the finalizers, until it found the matching "catch" which contained a longjmp target. It wasn't as crazy as this makes it sound. From jeanmichel at sequans.com Tue Aug 3 06:09:21 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 03 Aug 2010 12:09:21 +0200 Subject: simple (I hope!) problem In-Reply-To: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> Message-ID: <4C57EAD1.5090709@sequans.com> samwyse wrote: > I'm writing for the Google app engine and have stubbed my toe yet > again on a simple obstacle. Non-trivial app engines programs require > the import of several modules that aren't normally in my PYTHONPATH. > I'd like to be able to test my code outside of the app engine > framework. I've tried several solutions in the past that worked but > weren't particularly elegant or portable. Now I've had a new idea. > Here's my latest attempt: > > import os, re > if __name__ == '__main__': > pass > else > from google.appengine.ext import webapp > register = webapp.template.create_template_register() > > This works great, except my code makes use of the resister object in > several places, like this: > > register.filter(emptylines) > > Fortunately, I don't need the functionality of the object, I just want > something that won't generate an error when I use it. So, what is the > quickest way to to create such an object (replacing the 'pass' in my > first snippet). My solution is this: > > class C: > def filter(self, *args, **kwds): > pass > register = C() > > but it seems like I should be able to do something "better", as > measured by lines of code, faking more than just a 'filter' method, or > both. Any ideas? Thanks! > here is a class that accepts any method call without generating an error: class Stub(object): @staticmethod def stub(*arg, **kwarg): pass def __getattribute__(self, name): return Stub.stub s = Stub() s.foo('bar') s.bar s.bar('', '', 5) JM From a.pfrengle at gmail.com Tue Aug 3 06:15:56 2010 From: a.pfrengle at gmail.com (Andreas Pfrengle) Date: Tue, 3 Aug 2010 03:15:56 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> Message-ID: On 3 Aug., 03:22, Carl Banks wrote:> > You are creating an object that differs from a built-in, int, in a > highly misleading way that only makes sense in a very limited context, > and this object's modified behavior gives no clue that it's been > modified in such as way. ?(That is, it's not possible to tell if the > object's not a regular int just by looking at __str__()'s return > value.) ?To make matters worse, you want to program this object to > coerce other integers, so there's a risk of these objects escaping > from the context where they make sense. > > This is just a bad idea. ?The type is not the place to implement > behavior that makes sense only in a limited context. ?Instead, do > something like this: > > print "Item %d is %s." % (i+1, s[i]) I see your concerns. I started with the approach to add +1 directly before displaying the int. However, since there are some variables that shall be displayed normally and others that are indices I want to show starting at 1, I thought the easiest way would be to define a type that does the job, then I would only need to define it once and not take care everywhere whether I have a normal variable or a displayed index. Thinking about it, it might really be dangerous to coerce always to int1, since sometimes I might want a normal int as result (I can't tell yet for sure). I'm just thinking about only overloading the operations if the int1 is on the left-hand side (so __op__ coerces to int1, while __rop__ doesn't). This would make operations non-commutative - but I also would need to put more brains in every calculation, which could finally take more effort than only "upgrading" the display :-??? Seems I end up with your suggestion - if noone else has an idea ;-) The application will be a browsergame, and most gamers start counting at 1, so they would probably wonder about a "level 0 item" ;-) If there didn't already exist lots of code, I would redesign the whole data-structure - I think that's "lessons learned" for the next project -.- From jldunn2000 at gmail.com Tue Aug 3 06:21:07 2010 From: jldunn2000 at gmail.com (loial) Date: Tue, 3 Aug 2010 03:21:07 -0700 (PDT) Subject: Get name of file from directory into variable Message-ID: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> In a unix shell script I can do something like this to look in a directory and get the name of a file or files into a variable : MYFILE=`ls /home/mydir/JOHN*.xml` Can I do this in one line in python? From alex at moreati.org.uk Tue Aug 3 06:31:02 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 3 Aug 2010 03:31:02 -0700 (PDT) Subject: Get name of file from directory into variable References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: On Aug 3, 11:21?am, loial wrote: > In a unix shell script I can do something like this to look in a > directory and get the name of a file or files into a variable : > > MYFILE=`ls /home/mydir/JOHN*.xml` > > Can I do this in one line in python? Depends if you count imports. import glob my_files = glob.glob('/home/mydir/JOHN*.xml') Regards, Alex From landimatte at gmail.com Tue Aug 3 06:34:43 2010 From: landimatte at gmail.com (Matteo Landi) Date: Tue, 3 Aug 2010 12:34:43 +0200 Subject: Get name of file from directory into variable In-Reply-To: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: I suggest you to take a look at walk function inside the os module [1]; IIRC, on the list you would find a discussion on how to create a wrapper for os.walk with support for filters or wildcards. Regards. [1] http://docs.python.org/library/os.html?highlight=os.walk#os.walk On Tue, Aug 3, 2010 at 12:21 PM, loial wrote: > In a unix shell script I can do something like this to look in a > directory and get the name of a file or files into a variable : > > MYFILE=`ls /home/mydir/JOHN*.xml` > > > Can I do this in one line in python? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From jldunn2000 at gmail.com Tue Aug 3 06:41:00 2010 From: jldunn2000 at gmail.com (loial) Date: Tue, 3 Aug 2010 03:41:00 -0700 (PDT) Subject: Get name of file from directory into variable References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: <9aec7fa4-a8a5-4dfc-9376-a93e13e93d18@u26g2000yqu.googlegroups.com> On 3 Aug, 11:31, Alex Willmer wrote: > On Aug 3, 11:21?am, loial wrote: > > > In a unix shell script I can do something like this to look in a > > directory and get the name of a file or files into a variable : > > > MYFILE=`ls /home/mydir/JOHN*.xml` > > > Can I do this in one line in python? > > Depends if you count imports. > > import glob > my_files = glob.glob('/home/mydir/JOHN*.xml') > > Regards, Alex Cheers From rory at campbell-lange.net Tue Aug 3 06:44:10 2010 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Tue, 3 Aug 2010 11:44:10 +0100 Subject: Get name of file from directory into variable In-Reply-To: References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: <20100803104410.GA21889@campbell-lange.net> On 03/08/10, Alex Willmer (alex at moreati.org.uk) wrote: > On Aug 3, 11:21?am, loial wrote: > > In a unix shell script I can do something like this to look in a > > directory and get the name of a file or files into a variable : > > > > MYFILE=`ls /home/mydir/JOHN*.xml` > > > > Can I do this in one line in python? > > import glob > my_files = glob.glob('/home/mydir/JOHN*.xml') import os; my_files = [f for f in os.listdir('/home/mydir/') if 'JOHN' in f and 'xml' in f] But in fact glob uses os.listdir and fnmatch.fnmatch functions internally, so is definitely the way to go. http://docs.python.org/library/glob.html -- Rory Campbell-Lange rory at campbell-lange.net From roy at panix.com Tue Aug 3 07:06:27 2010 From: roy at panix.com (Roy Smith) Date: Tue, 03 Aug 2010 07:06:27 -0400 Subject: checking that process binds a port, fuser functionality References: Message-ID: In article , Nobody wrote: > On Mon, 02 Aug 2010 23:27:37 +0200, Zdenek Maxa wrote: > > > I need to start a process (using subprocess.Popen()) and wait until the > > new process either fails or successfully binds a specified port. > > If you just need to wait until *something* is listening on that port, you > could try connect()ing to it. This certainly seems like the logical way to me. It's straight-forward, simple, and portable. From landimatte at gmail.com Tue Aug 3 07:14:29 2010 From: landimatte at gmail.com (Matteo Landi) Date: Tue, 3 Aug 2010 13:14:29 +0200 Subject: Get name of file from directory into variable In-Reply-To: <20100803104410.GA21889@campbell-lange.net> References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> <20100803104410.GA21889@campbell-lange.net> Message-ID: Ops I miss the "one line" request, so my previous answer was definitely OT. glob seems to be your solution. On Tue, Aug 3, 2010 at 12:44 PM, Rory Campbell-Lange wrote: > On 03/08/10, Alex Willmer (alex at moreati.org.uk) wrote: >> On Aug 3, 11:21?am, loial wrote: >> > In a unix shell script I can do something like this to look in a >> > directory and get the name of a file or files into a variable : >> > >> > MYFILE=`ls /home/mydir/JOHN*.xml` >> > >> > Can I do this in one line in python? >> >> import glob >> my_files = glob.glob('/home/mydir/JOHN*.xml') > > import os; my_files = [f for f in os.listdir('/home/mydir/') if 'JOHN' in f and 'xml' in f] > > But in fact glob uses os.listdir and fnmatch.fnmatch functions > internally, so is definitely the way to go. > > http://docs.python.org/library/glob.html > > -- > Rory Campbell-Lange > rory at campbell-lange.net > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From magguru.chinnamnaidu at gmail.com Tue Aug 3 07:15:46 2010 From: magguru.chinnamnaidu at gmail.com (paypal cash) Date: Tue, 3 Aug 2010 04:15:46 -0700 (PDT) Subject: I GOT $2500 FROM PAYPAL.... Message-ID: <359ecaa3-ff1a-4939-873e-5555ee83d47b@f20g2000pro.googlegroups.com> I GOT $2500 FROM PAYPAL At http://2050videos.co.cc i have hidden the PayPal Form link in an image. in that website On Top Side Above search box , click on image and enter your PayPal id And Your name. From chare at labr.net Tue Aug 3 07:19:54 2010 From: chare at labr.net (Chris Hare) Date: Tue, 03 Aug 2010 06:19:54 -0500 Subject: calling a class method from a menu in a different class In-Reply-To: References: Message-ID: <778AE856-C4E8-4693-9159-537D3D0C7E6A@labr.net> No offense taken. I'll get getting the Google Python Style Guide today. I'll package up the code tonight and it to the group. Fortunately ( or unfortunately), it is all in one file right now. On Aug 2, 2010, at 10:31 PM, rantingrick wrote: > > Chris, > > It looks as if you are calling a class object and not an instance > object. However i cannot be for sure because you are using improper > Python style. All classes should be capwords. But here again you have > used camelcase for the class identifiers "radarWidgets" and > "mainDisplay", which is bad bad bad!! > > You been asking multiple questions about this code for the last couple > of days (and thats fine). However, maybe you would do everyone a favor > by posting the entire code so we can offer suggestions. Just seeing > seeing a snipit here and a snipit there is not helping because we > don't know where else you may be screwing up that we cannot see. > > It seems you're committing many faux pas with not only your coding > style but also your coding practices. I've seen overuse of globals and > bad styles and on and on. So post the entire code so myself and others > can go through this mess and get it sorted out. If you keep on with > your bad habits you're never going to become proficient with Python. > > I am sorry if this post seems condescending because that is not the > case. > -- > http://mail.python.org/mailman/listinfo/python-list From chare at labr.net Tue Aug 3 07:30:56 2010 From: chare at labr.net (Chris Hare) Date: Tue, 03 Aug 2010 06:30:56 -0500 Subject: calling a class method from a menu in a different class In-Reply-To: References: Message-ID: <2A9644F5-6668-4584-8D73-A99B13DBB144@labr.net> Oh and Risk, I know I was calling the class object. class 1 creates the instance object class 2 tries to use the instance object so the problem is how to make class 2 knowledgable of instance object? I guess I could pass the instance object into the class, since class1 creates the instance and also calls class 2. On Aug 2, 2010, at 10:31 PM, rantingrick wrote: > > Chris, > > It looks as if you are calling a class object and not an instance > object. However i cannot be for sure because you are using improper > Python style. All classes should be capwords. But here again you have > used camelcase for the class identifiers "radarWidgets" and > "mainDisplay", which is bad bad bad!! > > You been asking multiple questions about this code for the last couple > of days (and thats fine). However, maybe you would do everyone a favor > by posting the entire code so we can offer suggestions. Just seeing > seeing a snipit here and a snipit there is not helping because we > don't know where else you may be screwing up that we cannot see. > > It seems you're committing many faux pas with not only your coding > style but also your coding practices. I've seen overuse of globals and > bad styles and on and on. So post the entire code so myself and others > can go through this mess and get it sorted out. If you keep on with > your bad habits you're never going to become proficient with Python. > > I am sorry if this post seems condescending because that is not the > case. > -- > http://mail.python.org/mailman/listinfo/python-list From tania786786 at gmail.com Tue Aug 3 07:45:30 2010 From: tania786786 at gmail.com (tania tani) Date: Tue, 3 Aug 2010 04:45:30 -0700 (PDT) Subject: JUST TAKE 1 MIN ADD .AND GET 10 $ PER ADD $ 50 % OF THE REF.....ITS FREE Message-ID: <8e1a64ef-9e94-45ea-91ef-38e6b3ed2406@q16g2000prf.googlegroups.com> http://www.fineptc.com/index.php?ref=imranraza460 Hello my dear friend I hope you will be fine. i want to tell you the authentic way to make money with no investment . 1 just click on the obove link 2 create your account on the website. 3 then click on the "" view adds"" tab 4 There will be 6 or seven adds 5 click on a particular add and watch it for 1 min .. 6 this one minute add will give you 10 dollars 7 hence watch other adds one by one 8 finally you will find 60 dollars on you status by checking "' my account "' 9 You have earn 60 dollars you can repeat you view adds again on next day moreover if you introduce a new guy with your reffence you will be entitled to get 50% of the reffferl.....................trust me its free and its really works CLICK ON THE ABOVE LINK..........RIGHT NOW also try this link as anotherhttp://www.bigextracash.com/aft/9b6cc578.html From solipsis at pitrou.net Tue Aug 3 07:45:31 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Tue, 3 Aug 2010 13:45:31 +0200 Subject: please, help with python 3.1 References: Message-ID: <20100803134531.49ca4892@pitrou.net> On Tue, 3 Aug 2010 10:28:49 +0100 Alan Wilter Sousa da Silva wrote: > Now with python3.1: > > ---------------------------------------------------- > time python3.1 timout.py > PID: 27687 > Timed out! Process 27687 killed, max exec time (5s) exceeded > Traceback (most recent call last): > File "timout.py", line 23, in > out = str( p.communicate()[0].decode() ) > File "/sw/lib/python3.1/subprocess.py", line 719, in communicate > stdout = self.stdout.read() > File "timout.py", line 9, in signal_handler > raise Exception( "Taking too long to finish... aborting!" ) > Exception: Taking too long to finish... aborting! > python3.1 timout.py 0.52s user 3.88s system 19% cpu 22.841 total > > #### It prints essentially the same thing with a *very* *big* difference it > takes 22 seconds and actually the alarm only works when the whole task > ('find /') is finished. This seems to be a bug. Can you report it at http://bugs.python.org ? Thanks Antoine. From mohseni.aref at gmail.com Tue Aug 3 08:16:21 2010 From: mohseni.aref at gmail.com (Mohseniaref) Date: Tue, 3 Aug 2010 05:16:21 -0700 (PDT) Subject: how can I solve this erorr usr/lib/python2.6 : permisson denied References: <43e2d3fb-a0f9-468c-bd64-4516eed7dec5@u38g2000prh.googlegroups.com> <4c5617bc$0$11113$c3e8da3@news.astraweb.com> Message-ID: thanks I fix it and change path to bin folder From wherespythonmonks at gmail.com Tue Aug 3 08:46:16 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Tue, 3 Aug 2010 08:46:16 -0400 Subject: subclassing versus object redefinition Message-ID: Hi! I have a class (supposed to be an abstract base class): In python (as opposed to static languages like C++) I don't seed to subclass the base class, but instead I can simply override the behavior of stub methods and values. Is there a preference between between subclassing (C++ approach) and overriding methods/data in an instance? From a design perspective? I think I prefer the override/redefine approach because it result in a thinner class hierarchy. It seems like inheriting an ABC is needed only when I must share instances (between multiple parts of the code, or if the subclass is instantiated in different places...) Thoughts? W From rantingrick at gmail.com Tue Aug 3 09:06:14 2010 From: rantingrick at gmail.com (rantingrick) Date: Tue, 3 Aug 2010 06:06:14 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> Message-ID: <6d669b8a-f61d-4053-83e6-88ebae39770e@u26g2000yqu.googlegroups.com> > On Aug 3, 5:15?am, Andreas Pfrengle wrote: > > Seems I end up with your suggestion - if noone else has an idea ;-) START_COUNTING_FROM_HERE = 1 From fabiofz at gmail.com Tue Aug 3 09:12:26 2010 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 3 Aug 2010 10:12:26 -0300 Subject: Pydev 1.6.1 Released Message-ID: Hi All, Pydev 1.6.1 has been released Details on Pydev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: ------------------------------- * **Debugger** * **Critical Fix: issue that prevented the debugger from working with Python 3 solved** * Improving socket connection handling * **Launching** * Restart last launch and terminate all launches actions created * Restart last: **Ctrl+Shift+F9** (in pydev editor) * Terminate all: **Ctrl+Alt+F9** (in pydev editor) * Buttons were also added to pydev consoles * **Utilities** * **2to3**: Right-clicking a folder or file will show an option in the Pydev menu to convert from python 2 to python 3 (note that lib2to3 must available in the python installation). * Defining execfile in a Python 3 interactive console so that Ctrl+Alt+Enter works. * Fixed issue in the code style preferences page (switched value shown). * com.ziclix.python.sql added to the forced builtins in a Jython install by default. * Improved some icons when on a dark theme (patch from Kenneth Belitzky) What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer Aptana http://aptana.com/ Pydev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com From benedict.verheyen at gmail.com Tue Aug 3 09:16:11 2010 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Tue, 03 Aug 2010 15:16:11 +0200 Subject: cPickle error when caching data Message-ID: Hi i get the following error when trying to set data in the cache of a django application. The error is however a python error as it involves pickling and i can reproduce it in a shell. The error i get is this: cPickle.PicklingError: Can't pickle : attribute lookup management.views.Stats failed Stats is a class i use to hold a couple of values, a string (user) and a number (calls), that are then used in a template. These are pickable, right? The data i want to pickle is the return value of this function: def calc_stats_topcallers(): stats_all = {} # cPickle doesn't like this class class Stats(object): def __init__(self): self.calls = None self.user = None current_year = datetime.datetime.now().year archive_year = current_year - 4 years = xrange(archive_year, current_year+1) for year in years: stats_year = [] counts = {} # Initialize count dict # If we don't do this, we get a KeyError for user in User.objects.all(): counts[user]=0 # Count the times an initiator has been calling for i in Call.objects.filter(date_created__year=year): for _init in i.initiator.all(): counts[_init] += 1 # Sort the dictionary count_sorted = sorted(counts.items(), lambda x, y: cmp(x[1], y[1]), reverse=True) # Take top 30 callers for user_stat in count_sorted[0:30]: if ( user_stat[1] > 0 ): st = Stats() st.calls = user_stat[1] st.user = user_stat[0] stats_year.append(st) stats_all[year]=stats_year stats_sorted = sorted(stats_all.items(), lambda x, y: cmp(x[0], y[0]), reverse=True) return stats_sorted When i run the function and pickle the data using a python shell, i get the error. How do i solve this as i haven't got a clue. Thanks, Benedict From nikos.the.gr33k at gmail.com Tue Aug 3 09:24:44 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Tue, 3 Aug 2010 06:24:44 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: > On 3 ???, 11:10, Dave Angel wrote: > a) a text editor takes keystrokes and cut/paste info and other data, and > produces a stream of (unicode) characters. ?It then encodes each of ? > those character into one or more bytes and saves it to a file. ?You have > to tell Notepad++ how to do that encoding. ?Note that unless it's saving > a BOM, there's no clue in the file what encoding it used. So actually when i'm selecting an encoding from Notepad++'s options iam basically telling the editor the way the it's suppose to store those streams of characters to the hard disk drive. Different encodings equals different ways of storting the data to the media, correct? > b) The python compiler has to interpret the bytes it finds (spec. within > string literals and comments), and decode them into unicode for its own > work. ?It uses the 'coding:' comment to decide how to do this. ?But once > the file has been compiled, that comment is totally irrelevant, and ignored. What is a "String Literal" ? Basically if i understood you right, this line of code tells Python the opposite thign from (a). (a) told the editor how to store data to the media, while (b) tells the python compiler how to retrive these data from the media(how to read it, that is!) Right? > c1) Your python code has to decide how to encode its information when > writing to stdout. ?There are several ways to accomplish that. what other ways except the prin '''Content-Type blah blah... ''' ? > c2) The browser sees only what was sent to stdout, starting with the > "Content-Type..." line. ?It uses that line to decide how to decode the > rest of the stream. ?Let me reemphasize, the browser does not see any of > the python code, or comments. I was under the impression the the stdout of a cgi python script was the web server itself since this is the one app that awaits for the data to be displayed. When a python script runs it produces html output that time or only after the python's output to the Web Server the html output is produced? And something else please. My cgi python scripts contains english and greek letters, hence this is an indication of tellign the editor to save the file to disk as utf-8 right? Well i told Notepad++ to save ti as Ascii and also removed the '# -*- coding: utf-8 -*-' line. and only used print ''' Content-Type: text/html; charset=UTF-8 /n''' So, how the editor managed to save the file as ascii although my file coaniens characters that are beyond the usual 7-bit ascci set? and how could the python compiler 'read them and executed them' ? I shoulds have saved in utf-8 and have inside the script the line so the compiler knew to open it as utf-8. How come it dit work as ascii both in stroing and retreiving!! From jeanmichel at sequans.com Tue Aug 3 09:41:39 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 03 Aug 2010 15:41:39 +0200 Subject: simple integer subclass In-Reply-To: References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> Message-ID: <4C581C93.7070908@sequans.com> Andreas Pfrengle wrote: > On 3 Aug., 03:22, Carl Banks wrote:> > >> You are creating an object that differs from a built-in, int, in a >> highly misleading way that only makes sense in a very limited context, >> and this object's modified behavior gives no clue that it's been >> modified in such as way. (That is, it's not possible to tell if the >> object's not a regular int just by looking at __str__()'s return >> value.) To make matters worse, you want to program this object to >> coerce other integers, so there's a risk of these objects escaping >> from the context where they make sense. >> >> This is just a bad idea. The type is not the place to implement >> behavior that makes sense only in a limited context. Instead, do >> something like this: >> >> print "Item %d is %s." % (i+1, s[i]) >> > > I see your concerns. I started with the approach to add +1 directly > before displaying the int. However, since there are some variables > that shall be displayed normally and others that are indices I want to > show starting at 1, I thought the easiest way would be to define a > type that does the job, then I would only need to define it once and > not take care everywhere whether I have a normal variable or a > displayed index. > Thinking about it, it might really be dangerous to coerce always to > int1, since sometimes I might want a normal int as result (I can't > tell yet for sure). > I'm just thinking about only overloading the operations if the int1 is > on the left-hand side (so __op__ coerces to int1, while __rop__ > doesn't). This would make operations non-commutative - but I also > would need to put more brains in every calculation, which could > finally take more effort than only "upgrading" the display :-??? > Seems I end up with your suggestion - if noone else has an idea ;-) > > The application will be a browsergame, and most gamers start counting > at 1, so they would probably wonder about a "level 0 item" ;-) > If there didn't already exist lots of code, I would redesign the whole > data-structure - I think that's "lessons learned" for the next project > -.- > The level of an item is attribute of this item, not an index in a list. You may have an issue with your design, using an improper structure. In a more general manner, given your example I don't see why you should expose the index of an element in an internal list to the user. JM From jeanmichel at sequans.com Tue Aug 3 09:44:15 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 03 Aug 2010 15:44:15 +0200 Subject: simple integer subclass In-Reply-To: <4C581C93.7070908@sequans.com> References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> <4C581C93.7070908@sequans.com> Message-ID: <4C581D2F.8020101@sequans.com> Jean-Michel Pichavant wrote: > Andreas Pfrengle wrote: >> On 3 Aug., 03:22, Carl Banks wrote:> >> >>> You are creating an object that differs from a built-in, int, in a >>> highly misleading way that only makes sense in a very limited context, >>> and this object's modified behavior gives no clue that it's been >>> modified in such as way. (That is, it's not possible to tell if the >>> object's not a regular int just by looking at __str__()'s return >>> value.) To make matters worse, you want to program this object to >>> coerce other integers, so there's a risk of these objects escaping >>> from the context where they make sense. >>> >>> This is just a bad idea. The type is not the place to implement >>> behavior that makes sense only in a limited context. Instead, do >>> something like this: >>> >>> print "Item %d is %s." % (i+1, s[i]) >>> >> >> I see your concerns. I started with the approach to add +1 directly >> before displaying the int. However, since there are some variables >> that shall be displayed normally and others that are indices I want to >> show starting at 1, I thought the easiest way would be to define a >> type that does the job, then I would only need to define it once and >> not take care everywhere whether I have a normal variable or a >> displayed index. >> Thinking about it, it might really be dangerous to coerce always to >> int1, since sometimes I might want a normal int as result (I can't >> tell yet for sure). >> I'm just thinking about only overloading the operations if the int1 is >> on the left-hand side (so __op__ coerces to int1, while __rop__ >> doesn't). This would make operations non-commutative - but I also >> would need to put more brains in every calculation, which could >> finally take more effort than only "upgrading" the display :-??? >> Seems I end up with your suggestion - if noone else has an idea ;-) >> >> The application will be a browsergame, and most gamers start counting >> at 1, so they would probably wonder about a "level 0 item" ;-) >> If there didn't already exist lots of code, I would redesign the whole >> data-structure - I think that's "lessons learned" for the next project >> -.- >> > The level of an item is attribute of this item, not an index in a list. > You may have an issue with your design, using an improper structure. > > In a more general manner, given your example I don't see why you > should expose the index of an element in an internal list to the user. > > JM > "If there didn't already exist lots of code, I would redesign the whole data-structure" sorry I didn't get this one at first read, my comment is pretty much useless. JM From invalid at invalid.invalid Tue Aug 3 10:05:13 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 3 Aug 2010 14:05:13 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 2010-08-02, Aahz wrote: > In article , > Peter wrote: >>On Aug 3, 7:42=A0am, Mark Lawrence wrote: >>> On 02/08/2010 00:08, candide wrote: >>> >>> I can't understand why any serious programmer mentions C++. As soon >>> as I read it, I have to rush either to the kitchen to find a bowl to >>> throw up in, or head for the toilet so I can talk to the great white >>> telephone. >> >>With you there Mark - IMO C++ is an abortion that should never have >>seen the light of day. The idea of experimenting with creating an OO >>language by extending C wasn't such a bad idea for a "play thing" (by >>Stroustrop) but the fact that it somehow escaped from the Lab and >>people picked it up and ran with it on a commercial basis is just >>plain wrong! > > http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html It's funny (and sad) because it's so close to being true. (The effect, I mean, not necissarly the intent.) There's no computing problem so simple that it can't be solved in a complex and obtuse manner in C++. I know that's true of any language, but from what I've seen over the years, it "more true" in C++. -- Grant Edwards grant.b.edwards Yow! Should I get locked at in the PRINCICAL'S gmail.com OFFICE today -- or have a VASECTOMY?? From downaold at gmail.com Tue Aug 3 10:06:20 2010 From: downaold at gmail.com (Roald de Vries) Date: Tue, 3 Aug 2010 16:06:20 +0200 Subject: subclassing versus object redefinition In-Reply-To: References: Message-ID: <6D04E823-EBEB-452E-A4FE-DAE8F5F481C3@gmail.com> On Aug 3, 2010, at 2:46 PM, wheres pythonmonks wrote: > Hi! > > I have a class (supposed to be an abstract base class): > In python (as opposed to static languages like C++) I don't seed to > subclass the base class, but instead I can simply override the > behavior of stub methods and values. > Is there a preference between between subclassing (C++ approach) and > overriding methods/data in an instance? From a design perspective? > I think I prefer the override/redefine approach because it result in a > thinner class hierarchy. > > It seems like inheriting an ABC is needed only when I must share > instances (between multiple parts of the code, or if the subclass is > instantiated in different places...) > > Thoughts? 1) some things are just not possible in instances, like overriding operators 2) abstract base classes are not supposed to be instantiable, so if you are able to do it anyway, that is a hack 3) adding stuff to instances is less reusable that adding stuff to (sub)classes 4) if I'm reading your code and want to know what an object is like, I look at the class, not through your whole program to collect all bits and pieces of information spread out over it 5) why would you want a thinner class hierarchy? So I would go for inheritance. Cheers, Roald From invalid at invalid.invalid Tue Aug 3 10:11:41 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 3 Aug 2010 14:11:41 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-02, Paul Rubin wrote: > Michael Torrie writes: >> Sometimes, C++ is just the right tool for the job, despite all its >> warts.... C++'s object semantics (guaranteed destruction, scoping, >> etc) can sometimes work very well when you need the speed of a >> compiled language, but don't want to be quite as low-level as C. >> >> In this case, C++ is certainly not a better tool for the job than C. > > The stuff C++ adds to C is a mix of good and bad, and it's reasonably > possible to use just the good stuff and ignore the bad. Except nobody does. ;) > I've never programmed in Ada but I'm intrigued by these articles: > > http://adahome.com/Ammo/cpp2ada.html > http://www.adaic.org/whyada/ada-vs-c/cada_art.html > > I have the impression that Ada has an undeservedly bad rap because of > its early implementations and its origins in military bureaucracy. > I'd certainly consider it as an alternative to C or C++ if I had to > write a big program in a traditional procedural language. I've always thought Ada was a pretty nice embedded/systems languages, but some of the initial implementations were indede horrible. The one I used for a little while ran on VAX/VMS but didn't use the VMS filesystem, editors, or other utilities. The Ada enviroment was a completely closed, walled system. It kept it's "files" in some sort of opaque database and they could only be accessed, edited, compiled, etc. from within the Ada development enviornment (a system with really, really awful editing and build tools). There was a way to import/export files, but it wasn't easy. Still, the Ada-environment tools were _so_ bad that people exported a file, edited it using some VMS-based editor and the re-imported it whenever a change needed to be made. Apparently the intent was to provide the identically awful user-torturing-experience regardless of OS. -- Grant Edwards grant.b.edwards Yow! I represent a at sardine!! gmail.com From zdenekmaxa at yahoo.co.uk Tue Aug 3 10:32:45 2010 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Tue, 03 Aug 2010 16:32:45 +0200 Subject: checking that process binds a port, fuser functionality In-Reply-To: References: Message-ID: <4C58288D.6070606@yahoo.co.uk> -------- Original Message -------- Subject: Re: checking that process binds a port, fuser functionality From: Roy Smith To: python-list at python.org Date: Tue Aug 03 2010 13:06:27 GMT+0200 (CEST) > In article , > Nobody wrote: > >> On Mon, 02 Aug 2010 23:27:37 +0200, Zdenek Maxa wrote: >> >>> I need to start a process (using subprocess.Popen()) and wait until the >>> new process either fails or successfully binds a specified port. >> If you just need to wait until *something* is listening on that port, you >> could try connect()ing to it. > > This certainly seems like the logical way to me. It's straight-forward, > simple, and portable. Yes, but I need a check that certain known process's PID listens on a defined port. connect() would certainly work, but I may end up connecting to a different process. I forgot to mention that my master daemon starts processes in question as external applications, defines port they should bind but starts them via different user via sudo, which makes checking /proc/net/tcp not possible. Well, seems it's turning out not straight-forward, but thanks a lot for your thoughts anyway! Zdenek From wherespythonmonks at gmail.com Tue Aug 3 10:38:25 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Tue, 3 Aug 2010 10:38:25 -0400 Subject: subclassing versus object redefinition In-Reply-To: <6D04E823-EBEB-452E-A4FE-DAE8F5F481C3@gmail.com> References: <6D04E823-EBEB-452E-A4FE-DAE8F5F481C3@gmail.com> Message-ID: Roald: First, I must admit, I didn't know I could create an ABC in python. Now I see (http://docs.python.org/library/abc.html). Thank you. I think that the crux of the matter is in points #3, #4, and #5 that you raised: 3) adding stuff to instances is less reusable that adding stuff to (sub)classes 4) if I'm reading your code and want to know what an object is like, I look at the class, not through your whole program to collect all bits and pieces of information spread out over it On #3: Not clear that all possible specializations warrant factorization into a class. Indeed, this may result in "premature abstraction" -- and make the code less clear. Also, it will freeze in the base classes, making future refactoring a headache. On #4: Unless I misunderstood something, there is nothing in python that ensures that a class definition is localized. So, putting definitions in classes, does not guarantee that the definition is at a single location in the code. 5) why would you want a thinner class hierarchy? The yo-yo anti-patten: http://en.wikipedia.org/wiki/Yo-yo_problem I have a pretty strong preference for using a small number of useful objects, instead of having code littered with objects strewn across the namespace. Maybe there is a Python ABC tutorial out there that can enlighten me? W On Tue, Aug 3, 2010 at 10:06 AM, Roald de Vries wrote: > On Aug 3, 2010, at 2:46 PM, wheres pythonmonks wrote: >> >> Hi! >> >> I have a class (supposed to be an abstract base class): >> In python (as opposed to static languages like C++) I don't seed to >> subclass the base class, but instead I can simply override the >> behavior of stub methods and values. >> Is there a preference between between subclassing (C++ approach) and >> overriding methods/data in an instance? ?From a design perspective? >> I think I prefer the override/redefine approach because it result in a >> thinner class hierarchy. >> >> It seems like inheriting an ABC is needed only when I must share >> instances (between multiple parts of the code, or if the subclass is >> instantiated in different places...) >> >> Thoughts? > > 1) some things are just not possible in instances, like overriding operators > 2) abstract base classes are not supposed to be instantiable, so if you are > able to do it anyway, that is a hack > 3) adding stuff to instances is less reusable that adding stuff to > (sub)classes > 4) if I'm reading your code and want to know what an object is like, I look > at the class, not through your whole program to collect all bits and pieces > of information spread out over it > 5) why would you want a thinner class hierarchy? > > So I would go for inheritance. > > Cheers, Roald > > From roy at panix.com Tue Aug 3 10:43:13 2010 From: roy at panix.com (Roy Smith) Date: Tue, 3 Aug 2010 07:43:13 -0700 (PDT) Subject: checking that process binds a port, fuser functionality References: Message-ID: <6db6f26e-8447-4679-9f89-bf1a323b1845@q35g2000yqn.googlegroups.com> On Aug 3, 10:32?am, Zdenek Maxa wrote: > Yes, but I need a check that certain known process's PID listens on a > defined port. connect() would certainly work, but I may end up > connecting to a different process. Then you need to define your protocol such that the client and server engage in some sort of identification / authentication exchange when they connect. Client: Who are you? Server: I am PID 12345 Client: That's not who I was expecting, I'm going away! Depending on how secure you need this to be, the exchange might include some kind of cryptographic signature. From __peter__ at web.de Tue Aug 3 11:01:05 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Aug 2010 17:01:05 +0200 Subject: cPickle error when caching data References: Message-ID: Benedict Verheyen wrote: > i get the following error when trying to set data in the cache of a django > application. The error is however a python error as it involves pickling > and i can reproduce it in a shell. > The error i get is this: > cPickle.PicklingError: Can't pickle : > attribute lookup management.views.Stats failed > > Stats is a class i use to hold a couple of values, a string (user) and a > number (calls), that are then used in a template. These are pickable, > right? The data i want to pickle is the return value of this function: > > def calc_stats_topcallers(): > stats_all = {} > # cPickle doesn't like this class > class Stats(object): > def __init__(self): > self.calls = None > self.user = None You can only pickle instances of classes that are reachable by the import system as only the qualified name of the class is stored, not the bytecode to generate it. Move your class out of the function into the global module scope and you should be OK. Peter From downaold at gmail.com Tue Aug 3 11:31:07 2010 From: downaold at gmail.com (Roald de Vries) Date: Tue, 3 Aug 2010 17:31:07 +0200 Subject: subclassing versus object redefinition In-Reply-To: References: <6D04E823-EBEB-452E-A4FE-DAE8F5F481C3@gmail.com> Message-ID: <995E4DE8-6E33-4C12-8DF7-601D7B77A780@gmail.com> Hi W, On Aug 3, 2010, at 4:38 PM, wheres pythonmonks wrote: > I think that the crux of the matter is in points #3, #4, and #5 that > you raised: I think #2 is important too: a program is supposed to do what you expect, and I don't expect instantiation of an ABC. > On #3: Not clear that all possible specializations warrant > factorization into a class. Indeed, this may result in "premature > abstraction" -- and make the code less clear. Also, it will freeze in > the base classes, making future refactoring a headache. I agree (for small specializations only). > On #4: Unless I misunderstood something, there is nothing in python > that ensures that a class definition is localized. So, putting > definitions in classes, does not guarantee that the definition is at a > single location in the code. That's right, but with classes it is possible (and encouraged) to keep things in a single location. The other option necessarily puts things where I don't expect them. > 5) why would you want a thinner class hierarchy? > > The yo-yo anti-patten: > http://en.wikipedia.org/wiki/Yo-yo_problem > > I have a pretty strong preference for using a small number of useful > objects, instead of having code littered with objects strewn across > the namespace. I see the point, but I would like to remark that if a program does what you expect, you won't need to understand the whole inheritance graph. > Maybe there is a Python ABC tutorial out there that can enlighten me? http://docs.python.org/library/abc.html http://www.doughellmann.com/PyMOTW/abc/ Cheers, Roald PS: most people in this list prefer not top posting From benedict.verheyen at gmail.com Tue Aug 3 11:37:22 2010 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Tue, 03 Aug 2010 17:37:22 +0200 Subject: cPickle error when caching data In-Reply-To: References: Message-ID: On 3/08/2010 17:01, Peter Otten wrote: > You can only pickle instances of classes that are reachable by the import > system as only the qualified name of the class is stored, not the bytecode > to generate it. Move your class out of the function into the global module > scope and you should be OK. > > Peter Thanks Peter, that solved the problem ! Regards, Benedict From davea at ieee.org Tue Aug 3 11:41:36 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 03 Aug 2010 11:41:36 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: <4C5838B0.9030305@ieee.org> ????? wrote: >> On 3 ???, 11:10, Dave Angel wrote: >> > > >> a) a text editor takes keystrokes and cut/paste info and other data, and >> produces a stream of (unicode) characters. It then encodes each of >> those character into one or more bytes and saves it to a file. You have >> to tell Notepad++ how to do that encoding. Note that unless it's saving >> a BOM, there's no clue in the file what encoding it used. >> > > So actually when i'm selecting an encoding from Notepad++'s options > iam basically telling the editor the way the it's suppose to store > those streams of characters to the hard disk drive. > > Different encodings equals different ways of storting the data to the > media, correct? > > Exactly. The file is a stream of bytes, and Unicode has more than 256 possible characters. Further, even the subset of characters that *do* take one byte are different for different encodings. So you need to tell the editor what encoding you want to use. > >> b) The python compiler has to interpret the bytes it finds (spec. within >> string literals and comments), and decode them into unicode for its own >> work. It uses the 'coding:' comment to decide how to do this. But once >> the file has been compiled, that comment is totally irrelevant, and ignored. >> > > What is a "String Literal" ? > > In python, a string literal is enclosed by single quotes, double quotes, or triples. myvar = u"tell me more" myvar = u'hello world' The u prefix is used in python 2.x to convert to Unicode; it's not needed in 3.x and I forget which one you're using. these are affected by the coding comment, but myvar = myfile.readline() is not. > Basically if i understood you right, this line of code tells Python > the opposite thign from (a). > (a) told the editor how to store data to the media, while (b) tells > the python compiler how to retrive these data from the media(how to > read it, that is!) Right? > > > >> c1) Your python code has to decide how to encode its information when >> writing to stdout. There are several ways to accomplish that. >> > > what other ways except the prin '''Content-Type blah blah... ''' ? > > > You can use the write() method of sys.stdout, or various equivalents, such as the one produced by io.open(). You can probably also use fdopen(1, "w") But probably the easiest is to do something like: sys.stdout = codecs.getwriter('utf8')(sys.stdout) and then print to stdout will use the utf8 encoding for its output. >> c2) The browser sees only what was sent to stdout, starting with the >> "Content-Type..." line. It uses that line to decide how to decode the >> rest of the stream. Let me reemphasize, the browser does not see any of >> the python code, or comments. >> > > I was under the impression the the stdout of a cgi python script was > the web server itself since this is the one app that awaits for the > data to be displayed. > > When a python script runs it produces html output that time or only > after the > python's output to the Web Server the html output is produced? > > > I don't understand your wording. Certainly the server launches the python script, and captures stdout. It then sends that stream of bytes out over tcp/ip to the waiting browser. You ask when does it become html ? I don't think the question has meaning. > And something else please. > My cgi python scripts contains english and greek letters, hence this > is an indication of tellign the editor to save the file to disk as > utf-8 right? > > Well i told Notepad++ to save ti as Ascii and also removed the '# -*- > coding: utf-8 -*-' line. > > and only used print ''' Content-Type: text/html; charset=UTF-8 /n''' > > So, how the editor managed to save the file as ascii although my file > coaniens characters that are beyond the usual 7-bit ascci set? > > I don't know Notepad++, so I don't know how it handles a character outside the legal ASCII range. So I'd only be guessing. But I'm guessing it ignored the ASCII restriction, and just wrote the bottom 8 bits of each character. That'll work for some of the non-ASCII characters. > and how could the python compiler 'read them and executed them' ? > > I'd only be speculating, since I've seen only a few lines of your source. Perhaps you're using Python 2.x, and not specifying u"" for those literals, which is unreasonable, but does tend to work for *some* of the second 128 characters. > I shoulds have saved in utf-8 and have inside the script the line so > the compiler knew to open it as utf-8. How come it dit work as ascii > both in stroing and retreiving!! > > > Since you have the setup that shows this effect, why not take a look at the file, and see whether there are any non-ASCII characters (codes above hex 7f) in it ? And whether there's a BOM. Then you can examine the unicode characters produced. by changing your source code. The more I think about it, the more I suspect your confusion comes because maybe you're not using the u-prefix on your literals. That can lead to some very subtle bugs, and code that works for a while, then fails in inexplicable ways. DaveA From downaold at gmail.com Tue Aug 3 11:43:21 2010 From: downaold at gmail.com (Roald de Vries) Date: Tue, 3 Aug 2010 17:43:21 +0200 Subject: simple integer subclass In-Reply-To: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> Message-ID: Hi Andreas, On Aug 3, 2010, at 1:52 AM, Andreas Pfrengle wrote: > I'm trying to define a subclass of int called int1. An int1-object > shall behave exactly like an int-object, with the only difference that > the displayed value shall be value + 1 (it will be used to display > array indices starting at 1 instead of 0). Right now I have: > > class int1(int): > def __str__(self): > return int.__str__(self + 1) > > However, if I calculate with int1 and int- (or other number) objects, > the result is always coerced to an int (or other number object), e.g: > a = int1(5) > b = 5 > print a # "6" > print a+b #"10" > > How can I tell int1 to be the "default integer object"? Do I need to > overload *every* mathematical operation method of int, or is there an > easier way? Maybe you could use: 1) a dict with keys 1..n 2) a simple list (or iterable) subclass with 1-based indices. class list1(list): def __new__(cls, *args, **kwargs): return list.__new__(cls, *args, **kwargs) def __getitem__(self, key): return list.__getitem__(self, key-1) ... etcetera Cheers, Roald From pavlovevidence at gmail.com Tue Aug 3 12:15:14 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 3 Aug 2010 09:15:14 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> <87d3u0niww.fsf@castleamber.com> Message-ID: <14050e2d-50b2-4f21-bcef-9c2b56bd5755@i18g2000pro.googlegroups.com> On Aug 3, 2:29?am, John Bokma wrote: > Carl Banks writes: > > On Aug 1, 6:09?pm, John Bokma wrote: > >> Roy Smith writes: > >> > In article <4c55fe82$0$9111$426a3... at news.free.fr>, > >> > ?candide wrote: > > >> >> Python is an object oriented langage (OOL). The Python main > >> >> implementation is written in pure and "old" C90. Is it for historical > >> >> reasons? > > >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > >> >> suitable to implement an OOL with another one. > > >> > One thing that comes to mind is that it's much easier to distribute C > >> > libraries than C++ libraries. > > >> In the beginning of C++ there were programs that just converted C++ to C > >> (frontends). At least that is how the C++ compiler Acorn sold worked. > >> So I don't think your argument was much true back then. > > > No, it was that way back then too. ?They might all generate C code but > > different C code by different backends wouldn't be able to call each > > other natively. > > If you convert C++ to C, and compile the C code then that's not > different from compiling the C code itself, correct? > > > > For instnace the function > > > int foo(int); > > > might be name-mangled this way in one cfront: > > > foo$d > > > and this way in another: > > > ____int_foo__int_i > > But they call both the C libraries in the same way. Go look at the original claim, the one that you responded to. "It's much easier to distribute C libraries than C++ libraries." Of course they can both call C libraries. All modern C++ compilers can too, not just cfronts. What almost no C++ compiler or C++ front can do is call a C++ library that a different C++ compiler or C++ front generated. (Unless they export function calls with C linkage, but that's not too helpful since the ostensible benefit of C++ is function overloading and subclassing and such, which you can't do at all between different compilers or fronts.) Hence, "It's much easier to distribute C libraries than C++ libraries." [snip rest of post that misses the point] Carl Banks From rushikesh.busetty at gmail.com Tue Aug 3 12:53:50 2010 From: rushikesh.busetty at gmail.com (RUSHIKESH BUSETTY) Date: Tue, 3 Aug 2010 09:53:50 -0700 (PDT) Subject: FULLY HOT ENTERTAINMENT Message-ID: AMISHAPATEL HOT BOOBS http://babes-devi.blogspot.com/2010/07/amishpatel-latest-photos.html ARCHANA UNSEENED EXPOSING PHOTOS http://babes-devi.blogspot.com/2010/07/archana-unseened-photos.html KATRINA KAIF HOT SEXY PHOTOS http://babes-devi.blogspot.com/2010/07/katrina-sexy-looking-photos.html THISHA HOT WET PHOTOS http://babes-devi.blogspot.com/2010/06/thrisha-hot-wet-photos.html SEXY CHARMI IN A BATHROOM http://babes-devi.blogspot.com/2010/06/charmi-in-bath.html KAJALAGARWAL IN A ROMANTIC FEEL http://babes-devi.blogspot.com/2010/06/kajal-hot-photos.html NAMITHA IN A BEACH http://babes-devi.blogspot.com/2010/06/nayagarala-namitha.html From ethan at stoneleaf.us Tue Aug 3 12:54:46 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 09:54:46 -0700 Subject: default behavior In-Reply-To: <4C578663.8000804@optimum.net> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> Message-ID: <4C5849D6.4060809@stoneleaf.us> John Posner wrote: > On 7/31/2010 1:31 PM, John Posner wrote: >> >> Caveat -- there's another description of defaultdict here: >> >> http://docs.python.org/library/collections.html#collections.defaultdict >> >> ... and it's bogus. This other description claims that __missing__ is a >> method of defaultdict, not of dict. > > Following is a possible replacement for the bogus description. Comments > welcome. I intend to submit a Python doc bug, and I'd like to have a > clean alternative to propose. > > -------------- > > class collections.defaultdict([default_factory[, ...]]) > > defaultdict is a dict subclass that can guarantee success on key > lookups: if a key does not currently exist in a defaultdict object, a > "default value factory" is called to provide a value for that key. The > "default value factory" is a callable object (typically, a function) > that takes no arguments. You specify this callable as the first argument > to defaultdict(). Additional defaultdict() arguments are the same as for > dict(). > > The "default value factory" callable is stored as an attribute, > default_factory, of the newly created defaultdict object. If you call > defaultdict() with no arguments, or with None as the first argument, the > default_factory attribute is set to None. You can reassign the > default_factory attribute of an existing defaultdict object to another > callable, or to None. > > When a lookup of a non-existent key is performed in a defaultdict > object, its default_factory attribute is evaluated, and the resulting > object is called: > > * If the call produces a value, that value is returned as the result of > the lookup. In addition, the key-value pair is inserted into the > defaultdict. > > * If the call raises an exception, it is propagated unchanged. > > * If the default_factory attribute evaluates to None, a KeyError > exception is raised, with the non-existent key as its argument. (The > defaultdict behaves exactly like a standard dict in this case.) I think mentioning how __missing__ plays into all this would be helpful. Perhaps in the first paragraph, after the colon: if a key does not currently exist in a defaultdict object, __missing__ will be called with that key, which in turn will call a "default value factory" to provide a value for that key. ~Ethan~ From ethan at stoneleaf.us Tue Aug 3 13:02:10 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 10:02:10 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <8739uwnihw.fsf@castleamber.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <8739uwnihw.fsf@castleamber.com> Message-ID: <4C584B92.8070601@stoneleaf.us> John Bokma wrote: > Michael Torrie writes: > >> On 08/01/2010 07:09 PM, John Bokma wrote: >>>> One thing that comes to mind is that it's much easier to distribute C >>>> libraries than C++ libraries. >>> In the beginning of C++ there were programs that just converted C++ to C >>> (frontends). At least that is how the C++ compiler Acorn sold worked. >>> So I don't think your argument was much true back then. >> No, he is still right. Each C++ implementation did name mangling >> differently leading to "C" libraries that had incompatible names and >> signatures. Also each frontend could have generated incompatible >> vtables and other C++ structures. So C code generated by one C++ >> frontend could not easily call C code generated by another C++ frontend. >> So the same arguments that are made about C++ now were just as valid >> back then when C++ was merely a fancy preprocessor. > > See my other post: I understand that two C++ preprocessors can't call > each others generated code, but if one uses C++ and knows that one can > only use shared C libraries on target systems, and not C++ libraries > that might be present (or more likely not: C++ was new in those days). So if Python were written in C++, and an extension was written in C++, how could the two call each other? ~Ethan~ From nikos.the.gr33k at gmail.com Tue Aug 3 13:17:28 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Tue, 3 Aug 2010 10:17:28 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> >On 3 ???, 18:41, Dave Angel wrote: > > Different encodings equal different ways of storing the data to the > > media, correct? > > Exactly. The file is a stream of bytes, and Unicode has more than 256 > possible characters. Further, even the subset of characters that *do* > take one byte are different for different encodings. So you need to tell > the editor what encoding you want to use. For example an 'a' char in iso-8859-1 is stored different than an 'a' char in iso-8859-7 and an 'a' char of utf-8 ? > > What is a "String Literal" ? > > In python, a string literal is enclosed by single quotes, double quotes, > or triples. > myvar = u"tell me more" > myvar = u'hello world' > The u prefix is used in python 2.x to convert to Unicode; it's not > needed in 3.x and I forget which one you're using. I use Python 2.4 and never used the u prefix. i Still don't understand the difference between a 'string' and a 'string literal' If i save a file as iso-8859-1 but in some of my variabels i use greek characters instead of telling the browser to change encoding and save the file as utf-8 i can just use the u prefix like your examples to save the variables as iso-8859-1 ? > I don't understand your wording. Certainly the server launches the > python script, and captures stdout. It then sends that stream of bytes > out over tcp/ip to the waiting browser. You ask when does it become html > ? I don't think the question has meaning. http cliens send request to http server(apache) , apache call python interpreter python call mysql to handle SQL queries right? My question is what is the difference of the python's script output and the web server's output to the http client? Who is producing the html code? the python output or the apache web server after it receive the python's output? > The more I think about it, the more I suspect your confusion comes > because maybe you're not using the u-prefix on your literals. That can > lead to some very subtle bugs, and code that works for a while, then > fails in inexplicable ways. I'm not sure whatr exaclty the do just yet. For example if i say mymessage = "????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the 2nd its a utf-8 one? So one script can be in some encoding and some parts of the script like th2 2nd varible can be in another? ============================== Also can you please help me in my cookie problem as to why only the else block executed each time and never the if? here is the code: [code] if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist print "??? ??? ??????? ???????? ??? ?? ?? ????????? ?? ????????? ?????????? ??? ???????!" cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire now else: print "??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? ?? ??????! ?? ????? ????? ? ??????? ??????????!!" cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year [/code] How do i check if the cookie is set and why if set never gets unset?! From lesande at gmail.com Tue Aug 3 13:34:48 2010 From: lesande at gmail.com (Lee Sander) Date: Tue, 3 Aug 2010 10:34:48 -0700 (PDT) Subject: finding homopolymers in both directions Message-ID: Hi, Suppose I have a string such as this 'aabccccccefggggghiiijkr' I would like to print out all the positions that are flanked by a run of symbols. So for example, I would like to the output for the above input as follows: 2 b 1 aa 2 b -1 cccccc 10 e -1 cccccc 11 f 1 ggggg 17 h 1 iii 17 h -1 ggggg where the first column is the position of interest, the next column is the entry at that position, 1 if the following column refers to a runs that come after and -1 if the runs come before I can do this easily for forward (shown below) but not clear how to do this backwards. I would really appreciate it if someone can help with this problem. I feel like a regex solution would be possible but I am not too good with regex. The code for forward is as follows: def homopolymericSites(Seq): Seq=Seq.upper() i=0 len_seq=len(Seq)-1# hack to prevent boundary condition while i < len_seq: bi=Seq[i] k=1 # go to the start of a homopolymer while 1: if i+k >= len_seq: break # no more sequence left if bi==Seq[i+k]: k+=1 else: break if k>1: # homopolymer length i=i+k id_of_chr_which_proceeds_homopolymer=Seq[i] # note not i+1 pos_of_chr_which_proceeds_homopolymer=i+1 # +1 to convert it to 1- index notation id_of_homopolymer=Seq[i-1] length_of_homopolymer=k print "%s\t%s/%s\t%s" %(pos_of_chr_which_proceeds_homopolymer, id_of_chr_which_proceeds_homopolymer, id_of_homopolymer, length_of_homopolymer) else: i+=1 From nagle at animats.com Tue Aug 3 13:41:57 2010 From: nagle at animats.com (John Nagle) Date: Tue, 03 Aug 2010 10:41:57 -0700 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <52ae410e-789e-41ad-bf0a-1d060d03019d@x21g2000yqa.googlegroups.com> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <52ae410e-789e-41ad-bf0a-1d060d03019d@x21g2000yqa.googlegroups.com> Message-ID: <4c5854e8$0$1608$742ec2ed@news.sonic.net> On 8/2/2010 5:53 PM, samwyse wrote: > On Aug 2, 12:34 pm, John Nagle wrote: >> The regular expression "split" behaves slightly differently than string >> split: > > I'm going to argue that it's the string split that's behaving oddly. I tend to agree. It doesn't seem to be possible to get the same semantics with any regular expression split. The default "split" has a special case for head and tail whitespace, and there's no way to express that with a regular expression split. Applying "strip" first will work, of course. The documentation should reflect that. John Nagle From nagle at animats.com Tue Aug 3 13:44:03 2010 From: nagle at animats.com (John Nagle) Date: Tue, 03 Aug 2010 10:44:03 -0700 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4c585565$0$1608$742ec2ed@news.sonic.net> On 8/1/2010 5:36 PM, Roy Smith wrote: > In article<4c55fe82$0$9111$426a34cc at news.free.fr>, > candide wrote: > >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. > > One thing that comes to mind is that it's much easier to distribute C > libraries than C++ libraries. > > If I compile a main program with one C compiler and you compile a > dynamically loaded library with another C compiler on the same box, the > odds are pretty good they'll interoperate without any problems. Not for Python. Extensions have to be built with essentially the same version of the same C compiler used for building Python. This is a major headache. John Nagle From bazwal at ftml.net Tue Aug 3 13:56:55 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 03 Aug 2010 18:56:55 +0100 Subject: regular expressions and the LOCALE flag Message-ID: <4C585867.8090207@ftml.net> the python docs say that re.LOCALE makes certain character classes "dependent on the current locale". here's what i currently see on my system: >>> import re, locale >>> locale.getdefaultlocale() ('en_GB', 'UTF8') >>> locale.getlocale() (None, None) >>> re.findall(r'\w', u'a b c \xe5 \xe6 \xe7', re.L) [u'a', u'b', u'c'] >>> locale.setlocale(locale.LC_ALL, 'en_GB.ISO 8859-1') 'en_GB.ISO 8859-1' >>> re.findall(r'\w', u'\xe5 \xe6 \xe7 a b c', re.L) [u'\xe5', u'\xe6', u'\xe7', u'a', u'b', u'c'] >>> locale.setlocale(locale.LC_ALL, 'en_GB.UTF-8') 'en_GB.UTF-8' >>> re.findall(r'\w', u'a b c \xe5 \xe6 \xe7', re.L) [u'a', u'b', u'c'] it seems wrong to me that re.LOCALE fails to give the "right" result when the local encoding is utf8 - i think it should give the same result as re.UNICODE. is this a bug, or does the documentation just need to be made clearer? From davea at ieee.org Tue Aug 3 14:00:17 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 03 Aug 2010 14:00:17 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> Message-ID: <4C585931.6060401@ieee.org> ????? wrote: >> On 3 ???, 18:41, Dave Angel wrote: >> >>> Different encodings equal different ways of storing the data to the >>> media, correct? >>> >> Exactly. The file is a stream of bytes, and Unicode has more than 256 >> possible characters. Further, even the subset of characters that *do* >> take one byte are different for different encodings. So you need to tell >> the editor what encoding you want to use. >> > > For example an 'a' char in iso-8859-1 is stored different than an 'a' > char in iso-8859-7 and an 'a' char of utf-8 ? > > > Nope, the ASCII subset is identical. It's the ones between 80 and ff that differ, and of course not all of those. Further, some of the codes that are one byte in 8859 are two bytes in utf-8. You *could* just decide that you're going to hardwire the assumption that you'll be dealing with a single character set that does fit in 8 bits, and most of this complexity goes away. But if you do that, do *NOT* use utf-8. But if you do want to be able to handle more than 256 characters, or more than one encoding, read on. Many people confuse encoding and decoding. A unicode character is an abstraction which represents a raw character. For convenience, the first 128 code points map directly onto the 7 bit encoding called ASCII. But before Unicode there were several other extensions to 256, which were incompatible with each other. For example, a byte which might be a European character in one such encoding might be a kata-kana character in another one. Each encoding was 8 bits, but it was difficult for a single program to handle more than one such encoding. So along comes unicode, which is typically implemented in 16 or 32 bit cells. And it has an 8 bit encoding called utf-8 which uses one byte for the first 192 characters (I think), and two bytes for some more, and three bytes beyond that. You encode unicode to utf-8, or to 8859, or to ... You decode utf-8 or 8859, or cp1252 , or ... to unicode >>> What is a "String Literal" ? >>> >> In python, a string literal is enclosed by single quotes, double quotes, >> or triples. >> myvar ="tell me more" >> myvar ='hello world' >> The u prefix is used in python 2.x to convert to Unicode; it's not >> needed in 3.x and I forget which one you're using. >> > > I use Python 2.4 and never used the u prefix. > > Then you'd better hope you never manipulate those literals. For example, the second character of some international characters expressed in utf8 may be a percent symbol, which would mess up string formatting. > i Still don't understand the difference between a 'string' and a > 'string literal' > > A string is an object containing characters. A string literal is one of the ways you create such an object. When you create it that way, you need to make sure the compiler knows the correct encoding, by using the encoding: line at beginning of file. > If i save a file as iso-8859-1 but in some of my variabels i use greek > characters instead of telling the browser to change encoding and save > the file as utf-8 i can just use the u prefix like your examples to > save the variables as iso-8859-1 ? > > >> I don't understand your wording. Certainly the server launches the >> python script, and captures stdout. It then sends that stream of bytes >> out over tcp/ip to the waiting browser. You ask when does it become html >> ? I don't think the question has meaning. >> > > http cliens send request to http server(apache) , apache call python > interpreter python call mysql to handle SQL queries right? > > My question is what is the difference of the python's script output > and the web server's output to the http client? > > The web server wraps a few characters before and after your html stream, but it shouldn't touch the stream itself. > Who is producing the html code? the python output or the apache web > server after it receive the python's output? > > > see above. >> The more I think about it, the more I suspect your confusion comes >> because maybe you're not using the u-prefix on your literals. That can >> lead to some very subtle bugs, and code that works for a while, then >> fails in inexplicable ways. >> > > I'm not sure whatr exaclty the do just yet. > > For example if i say mymessage = "????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the > 2nd its a utf-8 one? > > No, the first is an 8 bit copy of whatever bytes your editor happened to save. The second is unicode, which may be either 16 or 32 bits per character, depending on OS platform. Neither is utf-8. > So one script can be in some encoding and some parts of the script > like th2 2nd varible can be in another? > > mymessage = u"????????" creates an object that is *not* encoded. Encoding is taking the unicode stream and representing it as a stream of bytes, which may or may have more bytes than the original has characters. > ============================ > Also can you please help me in my cookie problem as to why only the > else block executed each time and never the if? > > here is the code: > > [code] > if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') = > 'nikos': #if visitor cookie exist > print "??? ??? ??????? ???????? ??? ?? ?? ????????? ?? ????????? > ?????????? ??? ???????!" > cookie['visitor'] = 'nikos', time() - 1 ) #this cookie will expire > now > else: > print "??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? ?? ??????! > ?? ????? ????? ? ??????? ??????????!!" > cookie['visitor'] = 'nikos', time() + 60*60*24*365 ) #this cookie > will expire in an year > [/code] > > How do i check if the cookie is set and why if set never gets unset?! > > I personally haven't done any cookie code. If I were debugging this, I'd factor out the multiple parts of that if statement, and find out which one isn't true. From here I can't guess. DaveA From benjamin.kaplan at case.edu Tue Aug 3 14:16:25 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 3 Aug 2010 11:16:25 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <4c585565$0$1608$742ec2ed@news.sonic.net> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4c585565$0$1608$742ec2ed@news.sonic.net> Message-ID: On Tue, Aug 3, 2010 at 10:44 AM, John Nagle wrote: > On 8/1/2010 5:36 PM, Roy Smith wrote: > >> In article<4c55fe82$0$9111$426a34cc at news.free.fr>, >> candide wrote: >> >> Python is an object oriented langage (OOL). The Python main >>> implementation is written in pure and "old" C90. Is it for historical >>> reasons? >>> >>> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >>> suitable to implement an OOL with another one. >>> >> >> One thing that comes to mind is that it's much easier to distribute C >> libraries than C++ libraries. >> >> If I compile a main program with one C compiler and you compile a >> dynamically loaded library with another C compiler on the same box, the >> odds are pretty good they'll interoperate without any problems. >> > > Not for Python. Extensions have to be built with essentially the > same version of the same C compiler used for building Python. This > is a major headache. > > John Nagle > -- > Pretty sure that's only one Windows, and only because they need to be linked to the same version of MSVC. It's not a compiler issue, it's incompatible library versions. > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 3 14:31:35 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Aug 2010 20:31:35 +0200 Subject: finding homopolymers in both directions References: Message-ID: Lee Sander wrote: > Hi, > Suppose I have a string such as this > 'aabccccccefggggghiiijkr' > > I would like to print out all the positions that are flanked by a run > of symbols. > So for example, I would like to the output for the above input as > follows: > > 2 b 1 aa > 2 b -1 cccccc > 10 e -1 cccccc > 11 f 1 ggggg > 17 h 1 iii > 17 h -1 ggggg > > where the first column is the position of interest, the next column is > the entry at that position, > 1 if the following column refers to a runs that come after and -1 if > the runs come before Trying to follow your spec I came up with from itertools import groupby from collections import namedtuple Item = namedtuple("Item", "pos key size") def compact(seq): pos = 0 for key, group in groupby(seq): size = len(list(group)) yield Item(pos, key, size) pos += size def window(items): items = iter(items) prev = None cur = next(items) for nxt in items: yield prev, cur, nxt prev = cur cur = nxt yield prev, cur, None items = compact("aabccccccefggggghiiijkr") for prev, cur, nxt in window(items): if cur.size == 1: if prev is not None: if prev.size > 1: print cur.pos, cur.key, -1, prev.key*prev.size if nxt is not None: if nxt.size > 1: print cur.pos, cur.key, 1, nxt.key*nxt.size However, this gives a slightly differenct output: $ python homopolymers.py 2 b -1 aa 2 b 1 cccccc 9 e -1 cccccc 10 f 1 ggggg 16 h -1 ggggg 16 h 1 iii 20 j -1 iii Peter From no.email at nospam.invalid Tue Aug 3 14:35:45 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 11:35:45 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <7xvd7rh7cu.fsf@ruckus.brouhaha.com> Grant Edwards writes: > There's no computing problem so simple that it can't be solved in a > complex and obtuse manner in C++. > > I know that's true of any language, but from what I've seen over the > years, it "more true" in C++. http://www.willamette.edu/~fruehr/haskell/evolution.html From python at mrabarnett.plus.com Tue Aug 3 14:40:38 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Aug 2010 19:40:38 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C585867.8090207@ftml.net> References: <4C585867.8090207@ftml.net> Message-ID: <4C5862A6.6030101@mrabarnett.plus.com> Baz Walter wrote: > the python docs say that re.LOCALE makes certain character classes > "dependent on the current locale". > > here's what i currently see on my system: > > >>> import re, locale > >>> locale.getdefaultlocale() > ('en_GB', 'UTF8') > >>> locale.getlocale() > (None, None) > >>> re.findall(r'\w', u'a b c \xe5 \xe6 \xe7', re.L) > [u'a', u'b', u'c'] > >>> locale.setlocale(locale.LC_ALL, 'en_GB.ISO 8859-1') > 'en_GB.ISO 8859-1' > >>> re.findall(r'\w', u'\xe5 \xe6 \xe7 a b c', re.L) > [u'\xe5', u'\xe6', u'\xe7', u'a', u'b', u'c'] > >>> locale.setlocale(locale.LC_ALL, 'en_GB.UTF-8') > 'en_GB.UTF-8' > >>> re.findall(r'\w', u'a b c \xe5 \xe6 \xe7', re.L) > [u'a', u'b', u'c'] > > it seems wrong to me that re.LOCALE fails to give the "right" result > when the local encoding is utf8 - i think it should give the same result > as re.UNICODE. > > is this a bug, or does the documentation just need to be made clearer? re.LOCALE just passes the character to the underlying C library. It really only works on bytestrings which have 1 byte per character. UTF-8 encodes codepoints outside the ASCII range to multiple bytes per codepoint, and the re module will treat each of those bytes as a separate character. And, BTW, none of your examples pass a UTF-8 bytestring to re.findall: all those string literals starting with the 'u' prefix are Unicode strings! Locale encodings are more trouble than they're worth. Unicode is better. :-) From dotancohen at gmail.com Tue Aug 3 14:53:00 2010 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 3 Aug 2010 21:53:00 +0300 Subject: Trying to set a cookie within a python script In-Reply-To: <4C5838B0.9030305@ieee.org> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <4C5838B0.9030305@ieee.org> Message-ID: On Tue, Aug 3, 2010 at 18:41, Dave Angel wrote: > I don't understand your wording. Certainly the server launches the python > script, and captures stdout. It then sends that stream of bytes out over > tcp/ip to the waiting browser. You ask when does it become html ? I don't > think the question has meaning. > ?HTML is just plain text. So the answer to the question is that ideally, the plain text that is sent to stdout would already be HTML. print ( "My Greek Page\n" ) -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From joe at goldthwaites.com Tue Aug 3 14:59:16 2010 From: joe at goldthwaites.com (Joe Goldthwaite) Date: Tue, 3 Aug 2010 11:59:16 -0700 Subject: locale and number formatting. Message-ID: <8462203B6D4F4122B98E6131F573C2CB@NewMBP> I've been working with some developers on a project. Our standard number formatting for the entire web site is comma separated with no decimals. Currency is formatted with the dollar sign. This is basically how they did it; import locale def currency(value): return locale.currency(value, grouping=True) def formatnumber(value): value = locale.currency(value, grouping=True) value = value.replace('$',''); try: value = value[:-3]; except: value = value; return value; The "formatnumber" function looks awkward. I'm not even sure what exactly they're trying to accomplish. They're stripping off the last three characters but since the number is formatted by the currency function, it might have parenthesis. I don't see this working correctly with negative numbers. That got me looking in to the locale module again. I'm having trouble understanding some of the python documentation on the subject. I've searched the web and even searched through all my safaribooksonline to see if I could get more information on how to improve the code but I'm just not getting it. Lets take the first step; def currency(value): return locale.currency(value, grouping=True) This is pretty simple. My problem is that I want all my currency numbers formatted with zero decimal places. There doesn't seem to be an option to round the value down. I thought that maybe I could change the 'frac_digits' setting to zero but I can't seem to find a way to change it. I've found a number of different functions that accomplish this but they're written from scratch. I'd really like to use a standard library function to do it if possible. With the 'formatnumber" function could be replaced with; def formatnumber(value): return locale.format('%0.0f', value, 1) This inserts the commas and rounds off the decimals. It doesn't handle putting parens around the negative numbers. Is there a better way to do this? I tried looking up the options for local.format_string which seems to allow custom "C" formatting but I couldn't find any examples of what the custom "C" formatting would look like. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 3 15:04:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Aug 2010 20:04:07 +0100 Subject: Trying to set a cookie within a python script In-Reply-To: <4C585931.6060401@ieee.org> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <4C585931.6060401@ieee.org> Message-ID: <4C586827.1030903@mrabarnett.plus.com> Dave Angel wrote: > ????? wrote: >>> On 3 ???, 18:41, Dave Angel wrote: >>> >>>> Different encodings equal different ways of storing the data to the >>>> media, correct? >>>> >>> Exactly. The file is a stream of bytes, and Unicode has more than 256 >>> possible characters. Further, even the subset of characters that *do* >>> take one byte are different for different encodings. So you need to tell >>> the editor what encoding you want to use. >>> >> >> For example an 'a' char in iso-8859-1 is stored different than an 'a' >> char in iso-8859-7 and an 'a' char of utf-8 ? >> >> >> > Nope, the ASCII subset is identical. It's the ones between 80 and ff > that differ, and of course not all of those. Further, some of the codes > that are one byte in 8859 are two bytes in utf-8. > > You *could* just decide that you're going to hardwire the assumption > that you'll be dealing with a single character set that does fit in 8 > bits, and most of this complexity goes away. But if you do that, do > *NOT* use utf-8. > > But if you do want to be able to handle more than 256 characters, or > more than one encoding, read on. > > Many people confuse encoding and decoding. A unicode character is an > abstraction which represents a raw character. For convenience, the first > 128 code points map directly onto the 7 bit encoding called ASCII. But > before Unicode there were several other extensions to 256, which were > incompatible with each other. For example, a byte which might be a > European character in one such encoding might be a kata-kana character > in another one. Each encoding was 8 bits, but it was difficult for a > single program to handle more than one such encoding. > One encoding might be ASCII + accented Latin, another ASCII + Greek, another ASCII + Cyrillic, etc. If you wanted ASCII + accented Latin + Greek then you'd need more than 1 byte per character. If you're working with multiple alphabets it gets very messy, which is where Unicode comes in. It contains all those characters, and UTF-8 can encode all of them in a straightforward manner. > So along comes unicode, which is typically implemented in 16 or 32 bit > cells. And it has an 8 bit encoding called utf-8 which uses one byte for > the first 192 characters (I think), and two bytes for some more, and > three bytes beyond that. > [snip] In UTF-8 the first 128 codepoints are encoded to 1 byte. From bazwal at ftml.net Tue Aug 3 15:40:01 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 03 Aug 2010 20:40:01 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C5862A6.6030101@mrabarnett.plus.com> References: <4C585867.8090207@ftml.net> <4C5862A6.6030101@mrabarnett.plus.com> Message-ID: <4C587091.8040901@ftml.net> On 03/08/10 19:40, MRAB wrote: > Baz Walter wrote: >> the python docs say that re.LOCALE makes certain character classes >> "dependent on the current locale". > > re.LOCALE just passes the character to the underlying C library. It > really only works on bytestrings which have 1 byte per character. the re docs don't specify 8-bit encodings: they just refer to the 'current locale'. > And, BTW, none of your examples pass a UTF-8 bytestring to re.findall: > all those string literals starting with the 'u' prefix are Unicode > strings! not sure what you mean by this: if the string was encoded as utf8, '\w' still wouldn't match any of the non-ascii characters. > Locale encodings are more trouble than they're worth. Unicode is better. > :-) yes, i'm really just trying to decide whether i should offer 'locale' as an option in my program. given the unintuitive way re.LOCALE works, i'm not sure that i should. are you saying that it only really makes sense for *bytestrings* to be used with re.LOCALE? if so, the re docs certainly don't make that clear. From wherespythonmonks at gmail.com Tue Aug 3 16:17:04 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Tue, 3 Aug 2010 16:17:04 -0400 Subject: None is negative? Message-ID: I did the google search... I must be blind as I don't see any hits... None is negative in Python? (v2.6) http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >>> if None < -9999999.99: print "hi" hi >>> >>> if -9999999 > None: print "hi" hi >>> Is there a way to have the comparison raise an exception? W From benjamin.kaplan at case.edu Tue Aug 3 16:24:22 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 3 Aug 2010 13:24:22 -0700 Subject: None is negative? In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 1:17 PM, wheres pythonmonks wrote: > > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? ?(v2.6) > > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > > >>> if None < -9999999.99: print "hi" > > hi > >>> > > >>> if -9999999 > None: print "hi" > > hi > >>> > > Is there a way to have the comparison raise an exception? > > W Use Python 3. One of the (backwards-incompatible) changes was to have comparisons of incompatible types raise exceptions. The behavior in Python 2 (not just with None, but with other built-in types as well) was to return an arbitrary but consistent result. From python at mrabarnett.plus.com Tue Aug 3 16:24:55 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Aug 2010 21:24:55 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C587091.8040901@ftml.net> References: <4C585867.8090207@ftml.net> <4C5862A6.6030101@mrabarnett.plus.com> <4C587091.8040901@ftml.net> Message-ID: <4C587B17.7050905@mrabarnett.plus.com> Baz Walter wrote: > On 03/08/10 19:40, MRAB wrote: >> Baz Walter wrote: >>> the python docs say that re.LOCALE makes certain character classes >>> "dependent on the current locale". >> >> re.LOCALE just passes the character to the underlying C library. It >> really only works on bytestrings which have 1 byte per character. > > the re docs don't specify 8-bit encodings: they just refer to the > 'current locale'. > >> And, BTW, none of your examples pass a UTF-8 bytestring to re.findall: >> all those string literals starting with the 'u' prefix are Unicode >> strings! > > not sure what you mean by this: if the string was encoded as utf8, '\w' > still wouldn't match any of the non-ascii characters. > Strings with the 'u' prefix are Unicode strings, not bytestrings. They don't have an encoding. A UTF-8 string is a bytestring in which the bytes represent Unicode codepoints encoded as UTF-8. >> Locale encodings are more trouble than they're worth. Unicode is better. >> :-) > > yes, i'm really just trying to decide whether i should offer 'locale' as > an option in my program. given the unintuitive way re.LOCALE works, i'm > not sure that i should. > > are you saying that it only really makes sense for *bytestrings* to be > used with re.LOCALE? > > if so, the re docs certainly don't make that clear. The re module can match against 3 types of string: 1. ASCII (default in Python 2): bytestring with characters in the ASCII range (1 byte per character). However, it doesn't complain if it sees bytes/characters outside the ASCII range. 2. LOCALE: bytestring with characters in the current locale (but only 1 byte per character). Characters are categorised according to the underlying C library; for example, 'a' is a letter if isalpha('a') returns true. 3. UNICODE (default in Python 3): Unicode string. From mithrandiragainwiki at mailinator.com Tue Aug 3 16:28:49 2010 From: mithrandiragainwiki at mailinator.com (Mithrandir) Date: Tue, 03 Aug 2010 13:28:49 -0700 Subject: None is negative? References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 08/03/2010 01:17 PM, wheres pythonmonks wrote: > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? (v2.6) > > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > >>>> if None < -9999999.99: print "hi" > > hi >>>> > >>>> if -9999999 > None: print "hi" > > hi >>>> > > Is there a way to have the comparison raise an exception? > > W I believe it's also because None lacks any binary value at all, whereas - -99999999.99 or 0 have a value in binary. For example: if None < 0: print "hi" >>> hi if None > 0: print "hi" >>> But in human terms, None == 0 and None > -9999999.99. - -- People should read more. https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain "All that is gold does not glitter, not all those who wander are lost; the old that is strong does not wither, deep roots are not reached by the frost. - From the ashes a fire shall be woken, a light from the shadows shall spring; renewed shall be blade that was broken, the crownless again shall be king." -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJMWHwBAAoJEKo37V1xH7gTgvYH/j1j0fgKI5mlzIp4urxhh6Ki 49LVsZjVsISyD+NzvgV5b8hk0S9Ad+gpqaf8fBQJS36Ye1KtupA7W7CTr54roaK0 ZBN3o4XxPdRjxXeHnBUNi3bqjGMzDdIIFZbE/qKalxTj0ZYgtlCgnMiYXLEeeY5z L0dzfn/qoMr6PjAtdlB9yp5amHcUeRzDos3hp13flsAj9Vq/pHyJmlPazME/vE0f 381bMXP52ud71BGcm8gRWdDqhJOUdJ52NZeEk0fKcxHsRvscjt1nQmCRp4IMDtFl ws++tXcl0pY7KSAATb5dzzkhr/BJnKGb1JHRlQMMB0EEdtNOzJaDh63qbvSzTJI= =9jHw -----END PGP SIGNATURE----- From invalid at invalid.invalid Tue Aug 3 16:29:17 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 3 Aug 2010 20:29:17 +0000 (UTC) Subject: None is negative? References: Message-ID: On 2010-08-03, wheres pythonmonks wrote: > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? (v2.6) Not really. > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > >>>> if None < -9999999.99: print "hi" > > hi >>>> > >>>> if -9999999 > None: print "hi" > > hi >>>> > > Is there a way to have the comparison raise an exception? Use Python 3.x. Or perhaps there's a "from future import xxxx" way to do that as well... Is there a list of available "from future" features somewhere? I can't seem to figure out how to get Python itself to give me a list -- my copy of Python 2.6 insists there's not module named future. -- Grant Edwards grant.b.edwards Yow! I have a very good at DENTAL PLAN. Thank you. gmail.com From nad at acm.org Tue Aug 3 16:30:08 2010 From: nad at acm.org (Ned Deily) Date: Tue, 03 Aug 2010 13:30:08 -0700 Subject: None is negative? References: Message-ID: In article , wheres pythonmonks wrote: > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? (v2.6) > > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > > >>> if None < -9999999.99: print "hi" > > hi > >>> > > >>> if -9999999 > None: print "hi" > > hi > >>> > > Is there a way to have the comparison raise an exception? This is a well-known wart in Python 2. The behavior has been changed in Python 3. $ python Python 2.6.5 (r265:79063, Jul 15 2010, 01:53:46) [GCC 4.2.1 (Apple Inc. build 5659)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> None < -9.9 True >>> $ python3 Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> None < -9.9 Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: NoneType() < float() >>> -- Ned Deily, nad at acm.org From invalid at invalid.invalid Tue Aug 3 16:32:46 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 3 Aug 2010 20:32:46 +0000 (UTC) Subject: None is negative? References: Message-ID: On 2010-08-03, Grant Edwards wrote: > On 2010-08-03, wheres pythonmonks wrote: > >> I did the google search... I must be blind as I don't see any hits... >> >> None is negative in Python? (v2.6) > > Not really. > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >> >>>>> if None < -9999999.99: print "hi" >> >> hi >>>>> >> >>>>> if -9999999 > None: print "hi" >> >> hi >>>>> >> >> Is there a way to have the comparison raise an exception? > > Use Python 3.x. Or perhaps there's a "from future import xxxx" way to > do that as well... Is there a list of available "from future" > features somewhere? I can't seem to figure out how to get Python > itself to give me a list -- my copy of Python 2.6 insists there's not > module named future. Doh! It's "__future__" not "future". And it doesn't appear that you can import the "unorderable types" behavior. -- Grant Edwards grant.b.edwards Yow! Uh-oh!! I'm having at TOO MUCH FUN!! gmail.com From mithrandiragainwiki at mailinator.com Tue Aug 3 16:34:40 2010 From: mithrandiragainwiki at mailinator.com (Mithrandir) Date: Tue, 03 Aug 2010 13:34:40 -0700 Subject: None is negative? References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 08/03/2010 01:28 PM, Mithrandir wrote: > On 08/03/2010 01:17 PM, wheres pythonmonks wrote: >> I did the google search... I must be blind as I don't see any hits... > >> None is negative in Python? (v2.6) > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > >>>>> if None < -9999999.99: print "hi" > >> hi >>>>> > >>>>> if -9999999 > None: print "hi" > >> hi >>>>> > >> Is there a way to have the comparison raise an exception? > >> W > > I believe it's also because None lacks any binary value at all, whereas > -99999999.99 or 0 have a value in binary. > > For example: > > if None < 0: print "hi" > >>>> hi > > if None > 0: print "hi" > >>>> > > But in human terms, None == 0 and None > -9999999.99. > That and/or it works out better in Python 3. :) - -- People should read more. https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain "All that is gold does not glitter, not all those who wander are lost; the old that is strong does not wither, deep roots are not reached by the frost. - From the ashes a fire shall be woken, a light from the shadows shall spring; renewed shall be blade that was broken, the crownless again shall be king." -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJMWH1gAAoJEKo37V1xH7gTPSIH/igigROvz8NOy/Km5SEAPtUE 08Brr46qeqZzkKPxV/r8wH2uD4eIhHoaBUN0oOv+7FT1UoP89eg7E0eC7U8FtzXY 5uwgEXG4xHTLPCERK4UkX799zD6oVQ7eeoSmnKmbotXEbUEjZ6TONq3ErXZBn6g0 FqHX6S/GdrVvIvqjuePYNJYYC/CsF3qXDpkM69Iye0MqGsZGPaKsrmsCa2cPVI+P ZZ67nXeHEsgYZ91utu4Hb4yOtmZf8MFqFqyD8aYF2Tr1P3uEBe8WOUqIPGRkwrFF Nxw1Ne/pw2v++CDLbJUS6+rpN52IYEeBLawtUarc/iG4RG+KFE7Z0ss8jSr75+c= =uXl5 -----END PGP SIGNATURE----- From davea at ieee.org Tue Aug 3 16:41:54 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 03 Aug 2010 16:41:54 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: <4C586827.1030903@mrabarnett.plus.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <4C585931.6060401@ieee.org> <4C586827.1030903@mrabarnett.plus.com> Message-ID: <4C587F12.3000507@ieee.org> MRAB wrote: >
Dave > Angel wrote: >> ????? wrote: >>>> On 3 ???, 18:41, Dave Angel wrote: >>>>> Different encodings equal different ways of storing the data to the >>>>> media, correct? >>>> Exactly. The file is a stream of bytes, and Unicode has more than 256 >>>> possible characters. Further, even the subset of characters that *do* >>>> take one byte are different for different encodings. So you need to >>>> tell >>>> the editor what encoding you want to use. >>> >>> For example an 'a' char in iso-8859-1 is stored different than an 'a' >>> char in iso-8859-7 and an 'a' char of utf-8 ? >>> >>> >> Nope, the ASCII subset is identical. It's the ones between 80 and ff >> that differ, and of course not all of those. Further, some of the >> codes that are one byte in 8859 are two bytes in utf-8. >> >> You *could* just decide that you're going to hardwire the assumption >> that you'll be dealing with a single character set that does fit in 8 >> bits, and most of this complexity goes away. But if you do that, do >> *NOT* use utf-8. >> >> But if you do want to be able to handle more than 256 characters, or >> more than one encoding, read on. >> >> Many people confuse encoding and decoding. A unicode character is an >> abstraction which represents a raw character. For convenience, the >> first 128 code points map directly onto the 7 bit encoding called >> ASCII. But before Unicode there were several other extensions to 256, >> which were incompatible with each other. For example, a byte which >> might be a European character in one such encoding might be a >> kata-kana character in another one. Each encoding was 8 bits, but it >> was difficult for a single program to handle more than one such >> encoding. >> > One encoding might be ASCII + accented Latin, another ASCII + Greek, > another ASCII + Cyrillic, etc. If you wanted ASCII + accented Latin + > Greek then you'd need more than 1 byte per character. > > If you're working with multiple alphabets it gets very messy, which is > where Unicode comes in. It contains all those characters, and UTF-8 can > encode all of them in a straightforward manner. > >> So along comes unicode, which is typically implemented in 16 or 32 >> bit cells. And it has an 8 bit encoding called utf-8 which uses one >> byte for the first 192 characters (I think), and two bytes for some >> more, and three bytes beyond that. >> > [snip] > In UTF-8 the first 128 codepoints are encoded to 1 byte. > > Thanks for the correction. As I said, I wasn't sure. I did utf-8 encoder and decoder about a dozen years ago, and I remember parts of it use the top two bits specially. But I've checked now, and you're right, the cutoff is 7f. DaveA From clp2 at rebertia.com Tue Aug 3 16:42:21 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 13:42:21 -0700 Subject: None is negative? In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 1:29 PM, Grant Edwards wrote: > On 2010-08-03, wheres pythonmonks wrote: > >> I did the google search... I must be blind as I don't see any hits... >> >> None is negative in Python? ?(v2.6) > > Not really. > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >> >>>>> if None < -9999999.99: print "hi" >> >> hi >>>>> >> >>>>> if -9999999 > None: print "hi" >> >> hi >>>>> >> >> Is there a way to have the comparison raise an exception? > > Use Python 3.x. ?Or perhaps there's a "from future import xxxx" way to > do that as well... ?Is there a list of available "from future" > features somewhere? ?I can't seem to figure out how to get Python > itself to give me a list -- my copy of Python 2.6 insists there's not > module named future. The module is named __future__. But there's no __future__ import to change the comparison behavior: Python 2.7 (r27:82500, Jul 27 2010, 23:28:51) >>> __future__.all_feature_names ['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals'] Cheers, Chris -- http://blog.rebertia.com From ethan at stoneleaf.us Tue Aug 3 16:43:44 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 13:43:44 -0700 Subject: None is negative? In-Reply-To: References: Message-ID: <4C587F80.4070605@stoneleaf.us> Grant Edwards wrote: > On 2010-08-03, wheres pythonmonks wrote: > >> I did the google search... I must be blind as I don't see any hits... >> >> None is negative in Python? (v2.6) > > Not really. > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >> >>>>> if None < -9999999.99: print "hi" >> hi >>>>> if -9999999 > None: print "hi" >> hi >> Is there a way to have the comparison raise an exception? > > Use Python 3.x. Or perhaps there's a "from future import xxxx" way to > do that as well... Is there a list of available "from future" > features somewhere? I can't seem to figure out how to get Python > itself to give me a list -- my copy of Python 2.6 insists there's not > module named future. > In 2.5 & 2.6 it's __future__. ~Ethan~ From benjamin.kaplan at case.edu Tue Aug 3 16:45:04 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 3 Aug 2010 13:45:04 -0700 Subject: None is negative? In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 1:29 PM, Grant Edwards wrote: > On 2010-08-03, wheres pythonmonks wrote: > >> I did the google search... I must be blind as I don't see any hits... >> >> None is negative in Python? ?(v2.6) > > Not really. > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >> >>>>> if None < -9999999.99: print "hi" >> >> hi >>>>> >> >>>>> if -9999999 > None: print "hi" >> >> hi >>>>> >> >> Is there a way to have the comparison raise an exception? > > Use Python 3.x. ?Or perhaps there's a "from future import xxxx" way to > do that as well... ?Is there a list of available "from future" > features somewhere? ?I can't seem to figure out how to get Python > itself to give me a list -- my copy of Python 2.6 insists there's not > module named future. > > -- That would be because it's __future__, not future. >>> import __future___ >>> help(__future__) Help on module __future__: NAME __future__ - Record of phased-in incompatible language changes. FILE c:\program files (x86)\ironpython 2.6 for .net 4.0\lib\__future__.py DESCRIPTION Each line is of the form: FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease "," CompilerFlag ")" where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples of the same form as sys.version_info: (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int PY_MINOR_VERSION, # the 1; an int PY_MICRO_VERSION, # the 0; an int PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string PY_RELEASE_SERIAL # the 3; an int ) OptionalRelease records the first release in which from __future__ import FeatureName was accepted. In the case of MandatoryReleases that have not yet occurred, MandatoryRelease predicts the release in which the feature will become par of the language. Else MandatoryRelease records when the feature became part of the language in releases at or after that, modules no longer need from __future__ import FeatureName to use the feature in question, but may continue to use such imports. MandatoryRelease may also be None, meaning that a planned feature got dropped. Instances of class _Feature have two corresponding methods, .getOptionalRelease() and .getMandatoryRelease(). CompilerFlag is the (bitfield) flag that should be passed in the fourth argument to the builtin function compile() to enable the feature in dynamically compiled code. This flag is stored in the .compiler_flag attribute on _Future instances. These values must match the appropriate #defines of CO_xxx flags in Include/compile.h. No feature line is ever to be deleted from this file. DATA __all__ = ['all_feature_names', 'nested_scopes', 'generators', 'divisi... absolute_import = _Feature((2, 5, 0, 'alpha', 1), (2, 7, 0, 'alpha', 0... all_feature_names = ['nested_scopes', 'generators', 'division', 'absol... division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192... generators = _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), 0) nested_scopes = _Feature((2, 1, 0, 'beta', 1), (2, 2, 0, 'alpha', 0), ... print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)... unicode_literals = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', ... with_statement = _Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0)... Hm, looks like whatever IronPython is using to display the text is cutting the lines short. That could be a problem. Anyway, you get the idea. From jjposner at optimum.net Tue Aug 3 17:24:53 2010 From: jjposner at optimum.net (John Posner) Date: Tue, 03 Aug 2010 17:24:53 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> Message-ID: <4C588925.1060505@optimum.net> On 8/3/2010 12:54 PM, Ethan Furman wrote: > I think mentioning how __missing__ plays into all this would be helpful. > Perhaps in the first paragraph, after the colon: > > if a key does not currently exist in a defaultdict object, __missing__ > will be called with that key, which in turn will call a "default value > factory" to provide a value for that key. Thanks, Ethan. As I said (or at least implied) to Christian earlier in this thread, I don't want to repeat the mistake of the current description: confusing the functionality provided *by* the defaultdict class with underlying functionality (the dict type's __missing__ protocol) that is used in the definition of the class. So I'd rather not mention __missing__ in the first paragraph, which describes the functionality provided *by* the defaultdict class. How about adding this para at the end: defaultdict is defined using functionality that is available to *any* subclass of dict: a missing-key lookup automatically causes the subclass's __missing__ method to be called, with the non-existent key as its argument. The method's return value becomes the result of the lookup. BTW, I couldn't *find* the coding of defaultdict in the Python 2.6 library. File collections.py contains this code: from _abcoll import * import _abcoll __all__ += _abcoll.__all__ from _collections import deque, defaultdict ... but I ran into a dead end after that. :-( I believe that the following *could be* the definition of defaultdict: class defaultdict(dict): def __init__(self, factory, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.default_factory = factory def __missing__(self, key): """provide value for missing key""" value = self.default_factory() # call factory with no args self[key] = value return value -John From lists at cheimes.de Tue Aug 3 17:47:23 2010 From: lists at cheimes.de (Christian Heimes) Date: Tue, 03 Aug 2010 23:47:23 +0200 Subject: default behavior In-Reply-To: <4C588925.1060505@optimum.net> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> Message-ID: > So I'd rather not mention __missing__ in the first paragraph, which > describes the functionality provided *by* the defaultdict class. How > about adding this para at the end: > > defaultdict is defined using functionality that is available to *any* > subclass of dict: a missing-key lookup automatically causes the > subclass's __missing__ method to be called, with the non-existent key > as its argument. The method's return value becomes the result of the > lookup. Your proposal sounds like a good idea. By the way do you have a CS degree? Your wording sounds like you are used write theses on a CS degree level. No offense. ;) > BTW, I couldn't *find* the coding of defaultdict in the Python 2.6 > library. File collections.py contains this code: > > from _abcoll import * > import _abcoll > __all__ += _abcoll.__all__ > > from _collections import deque, defaultdict defaultdict is implemented in C. You can read up the source code at http://svn.python.org/view/python/trunk/Modules/_collectionsmodule.c?revision=81029&view=markup . Search for "defaultdict type". The C code isn't complicated. You should understand the concept even if you are not familiar with the C API of Python. > class defaultdict(dict): > def __init__(self, factory, *args, **kwargs): > dict.__init__(self, *args, **kwargs) > self.default_factory = factory > > def __missing__(self, key): > """provide value for missing key""" > value = self.default_factory() # call factory with no args > self[key] = value > return value The type also implements __repr__(), copy() and __reduce__(). The latter is used by the pickle protocol. Without a new __reduce__ method, the default_factory would no survive a pickle/unpickle cycle. For a pure Python implementation you'd have to add __slots__ = "default_factory", too. Otherwise every defaultdict instance would gain an unncessary __dict__ attribute, too. Christian From jjposner at optimum.net Tue Aug 3 18:04:27 2010 From: jjposner at optimum.net (John Posner) Date: Tue, 03 Aug 2010 18:04:27 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> Message-ID: <4C58926B.6000108@optimum.net> On 8/3/2010 5:47 PM, Christian Heimes wrote: >> So I'd rather not mention __missing__ in the first paragraph, which >> describes the functionality provided *by* the defaultdict class. How >> about adding this para at the end: >> >> defaultdict is defined using functionality that is available to *any* >> subclass of dict: a missing-key lookup automatically causes the >> subclass's __missing__ method to be called, with the non-existent key >> as its argument. The method's return value becomes the result of the >> lookup. > > Your proposal sounds like a good idea. Tx. > By the way do you have a CS degree? Your wording sounds like you are > used write theses on a CS degree level. No offense. ;) No CS degree (coulda, woulda, shoulda). I think what you're hearing is 30+ years of tech writing for computer software companies. -John From ethan at stoneleaf.us Tue Aug 3 18:07:01 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 15:07:01 -0700 Subject: default behavior In-Reply-To: <4C588925.1060505@optimum.net> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> Message-ID: <4C589305.40903@stoneleaf.us> John Posner wrote: > On 8/3/2010 12:54 PM, Ethan Furman wrote: > > > >> I think mentioning how __missing__ plays into all this would be helpful. >> Perhaps in the first paragraph, after the colon: >> >> if a key does not currently exist in a defaultdict object, __missing__ >> will be called with that key, which in turn will call a "default value >> factory" to provide a value for that key. > > Thanks, Ethan. As I said (or at least implied) to Christian earlier in > this thread, I don't want to repeat the mistake of the current > description: confusing the functionality provided *by* the defaultdict > class with underlying functionality (the dict type's __missing__ > protocol) that is used in the definition of the class. I just went and read the entry that had the bogus claim -- personally, I didn't see any confusion. I would like to point out the __missing__ is *not* part of dicts (tested on 2.5 and 2.6 -- don't have 2.7 installed yet). Having said that, I think your final paragraph is better than my first paragraph edit. > So I'd rather not mention __missing__ in the first paragraph, which > describes the functionality provided *by* the defaultdict class. How > about adding this para at the end: > > defaultdict is defined using functionality that is available to *any* > subclass of dict: a missing-key lookup automatically causes the > subclass's __missing__ method to be called, with the non-existent key > as its argument. The method's return value becomes the result of the > lookup. > > BTW, I couldn't *find* the coding of defaultdict in the Python 2.6 > library. File collections.py contains this code: > > from _abcoll import * > import _abcoll > __all__ += _abcoll.__all__ > > from _collections import deque, defaultdict > > ... but I ran into a dead end after that. :-( I believe that the > following *could be* the definition of defaultdict: > > class defaultdict(dict): > def __init__(self, factory, *args, **kwargs): > dict.__init__(self, *args, **kwargs) > self.default_factory = factory > > def __missing__(self, key): > """provide value for missing key""" > value = self.default_factory() # call factory with no args > self[key] = value > return value I think it's more along these lines: class defaultdict(dict): def __init__(self, factory=None, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.default_factory = factory def __missing__(self, key): "provide value for missing key" if self.default_factory is None: raise KeyError("blah blah blah") value = self.default_factory() self[key] = value return value ~Ethan~ From ethan at stoneleaf.us Tue Aug 3 18:15:40 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 15:15:40 -0700 Subject: default behavior In-Reply-To: <4C578663.8000804@optimum.net> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> Message-ID: <4C58950C.3060906@stoneleaf.us> John Posner wrote: > On 7/31/2010 1:31 PM, John Posner wrote: >> >> Caveat -- there's another description of defaultdict here: >> >> http://docs.python.org/library/collections.html#collections.defaultdict >> >> ... and it's bogus. This other description claims that __missing__ is a >> method of defaultdict, not of dict. __missing__ isn't a method of dict: --> print dir(dict()) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] I will agree that the current defaultdict description does not make it clear that __missing__ can be defined for *any* subclass of dict, although the dict description does go over this... is that the confusion you are talking about? If not, could you explain? ~Ethan~ From john at castleamber.com Tue Aug 3 18:19:36 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 17:19:36 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> <87d3u0niww.fsf@castleamber.com> <14050e2d-50b2-4f21-bcef-9c2b56bd5755@i18g2000pro.googlegroups.com> Message-ID: <87aap3uyo7.fsf@castleamber.com> Carl Banks writes: > On Aug 3, 2:29?am, John Bokma wrote: [..] >> But they call both the C libraries in the same way. > > Go look at the original claim, the one that you responded to. "It's > much easier to distribute C libraries than C++ libraries." Yup, and if I read it correctly the claim was: and that's why C++ was not chosen. I doubt it. > Hence, "It's much easier to distribute C libraries than C++ > libraries." Yup, but still doesn't exclude C++ from being used to implement a programming language. And I would appreciate some respect, especially from someone who's too lazy to do some editing before posting, thank you. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From john at castleamber.com Tue Aug 3 18:20:49 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 17:20:49 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <8739uwnihw.fsf@castleamber.com> Message-ID: <8762zruym6.fsf@castleamber.com> Ethan Furman writes: > John Bokma wrote: >> Michael Torrie writes: >> >>> On 08/01/2010 07:09 PM, John Bokma wrote: >>>>> One thing that comes to mind is that it's much easier to >>>>> distribute C libraries than C++ libraries. >>>> In the beginning of C++ there were programs that just converted C++ to C >>>> (frontends). At least that is how the C++ compiler Acorn sold worked. >>>> So I don't think your argument was much true back then. >>> No, he is still right. Each C++ implementation did name mangling >>> differently leading to "C" libraries that had incompatible names and >>> signatures. Also each frontend could have generated incompatible >>> vtables and other C++ structures. So C code generated by one C++ >>> frontend could not easily call C code generated by another C++ frontend. >>> So the same arguments that are made about C++ now were just as valid >>> back then when C++ was merely a fancy preprocessor. >> >> See my other post: I understand that two C++ preprocessors can't call >> each others generated code, but if one uses C++ and knows that one can >> only use shared C libraries on target systems, and not C++ libraries >> that might be present (or more likely not: C++ was new in those days). > > So if Python were written in C++, and an extension was written in C++, > how could the two call each other? Via C. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From lists at cheimes.de Tue Aug 3 18:35:30 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 04 Aug 2010 00:35:30 +0200 Subject: default behavior In-Reply-To: <4C589305.40903@stoneleaf.us> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> Message-ID: > I just went and read the entry that had the bogus claim -- personally, I > didn't see any confusion. I would like to point out the __missing__ is > *not* part of dicts (tested on 2.5 and 2.6 -- don't have 2.7 installed yet). I beg your pardon but you are wrong. __missing__ is available for all *subclasses* of dict since Python 2.5. See http://svn.python.org/view/python/branches/release25-maint/Objects/dictobject.c?revision=81031&view=markup >>> class mydict(dict): ... def __missing__(self, key): ... print "__missing__", key ... raise KeyError(key) ... >>> m = mydict() >>> m[1] __missing__ 1 Traceback (most recent call last): File "", line 1, in File "", line 4, in __missing__ KeyError: 1 Christian From ethan at stoneleaf.us Tue Aug 3 18:48:02 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 15:48:02 -0700 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> Message-ID: <4C589CA2.1040709@stoneleaf.us> Christian Heimes wrote: >> I just went and read the entry that had the bogus claim -- personally, I >> didn't see any confusion. I would like to point out the __missing__ is >> *not* part of dicts (tested on 2.5 and 2.6 -- don't have 2.7 installed yet). > > I beg your pardon but you are wrong. __missing__ is available for all > *subclasses* of dict since Python 2.5. See > http://svn.python.org/view/python/branches/release25-maint/Objects/dictobject.c?revision=81031&view=markup > >>>> class mydict(dict): > ... def __missing__(self, key): > ... print "__missing__", key > ... raise KeyError(key) > ... >>>> m = mydict() >>>> m[1] > __missing__ 1 > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in __missing__ > KeyError: 1 Perhaps punctuation will help clarify my intent: __missing__ is *not* part of (dict)s, as shown by dir(dict()): ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] And, just to state what is hopefully obvious, if you don't create __missing__ yourself, it still isn't in the subclass: --> class somedict(dict): ... "Is __missing__ defined if I don't define it? Nope." ... --> sd = somedict() --> sd[1] Traceback (most recent call last): File "", line 1, in KeyError: 1 --> dir(sd) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] ~Ethan~ From ethan at stoneleaf.us Tue Aug 3 18:52:34 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 15:52:34 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <8762zruym6.fsf@castleamber.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <8739uwnihw.fsf@castleamber.com> <8762zruym6.fsf@castleamber.com> Message-ID: <4C589DB2.6060108@stoneleaf.us> John Bokma wrote: > Ethan Furman writes: > >> John Bokma wrote: >>> Michael Torrie writes: >>> >>>> On 08/01/2010 07:09 PM, John Bokma wrote: >>>>>> One thing that comes to mind is that it's much easier to >>>>>> distribute C libraries than C++ libraries. >>>>> In the beginning of C++ there were programs that just converted C++ to C >>>>> (frontends). At least that is how the C++ compiler Acorn sold worked. >>>>> So I don't think your argument was much true back then. >>>> No, he is still right. Each C++ implementation did name mangling >>>> differently leading to "C" libraries that had incompatible names and >>>> signatures. Also each frontend could have generated incompatible >>>> vtables and other C++ structures. So C code generated by one C++ >>>> frontend could not easily call C code generated by another C++ frontend. >>>> So the same arguments that are made about C++ now were just as valid >>>> back then when C++ was merely a fancy preprocessor. >>> See my other post: I understand that two C++ preprocessors can't call >>> each others generated code, but if one uses C++ and knows that one can >>> only use shared C libraries on target systems, and not C++ libraries >>> that might be present (or more likely not: C++ was new in those days). >> So if Python were written in C++, and an extension was written in C++, >> how could the two call each other? > > Via C. Huh? Presumably Python itself is not a library, and the extension may not be a library, at some point they will have different name mangling schemes... are you suggesting that after going through the effort if writing all this in C++ you would then have to write a wrapper in C so the two could talk to each other? ~Ethan~ From pavlovevidence at gmail.com Tue Aug 3 18:56:17 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 3 Aug 2010 15:56:17 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> <87d3u0niww.fsf@castleamber.com> <14050e2d-50b2-4f21-bcef-9c2b56bd5755@i18g2000pro.googlegroups.com> <87aap3uyo7.fsf@castleamber.com> Message-ID: <45daa26c-80d2-44a9-a804-651eb984990a@y11g2000yqm.googlegroups.com> On Aug 3, 3:19?pm, John Bokma wrote: > Carl Banks writes: > > On Aug 3, 2:29?am, John Bokma wrote: > > [..] > > >> But they call both the C libraries in the same way. > > > Go look at the original claim, the one that you responded to. ?"It's > > much easier to distribute C libraries than C++ libraries." > > Yup, and if I read it correctly the claim was: and that's why C++ was > not chosen. I doubt it. I think it was. Not necessarily that GvR made a list of reasons to choose C over C++. But the fact that C++ has almost no interoperability between compilers except via regular C linkage is a major cultural reason why it's avoided for programs that need extensible APIs like Python, which is why language implementors try to avoid it. The availability of C++ fronts that translate to C isn't the slightest bit relevant to this. > > Hence, "It's much easier to distribute C libraries than C++ > > libraries." > > Yup, but still doesn't exclude C++ from being used to implement a > programming language. Well, if you want to write a language that people can write extensions for using something other than the same C++ compiler you used, then your only option is to use "C" external linkage which means that whatever OOP advantages C++ gives you aren't going to be available to extensions. This is true even if you use a C++ front instead of a compiler. Carl Banks From roy at panix.com Tue Aug 3 19:05:23 2010 From: roy at panix.com (Roy Smith) Date: Tue, 03 Aug 2010 19:05:23 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> <87d3u0niww.fsf@castleamber.com> <14050e2d-50b2-4f21-bcef-9c2b56bd5755@i18g2000pro.googlegroups.com> <87aap3uyo7.fsf@castleamber.com> Message-ID: In article <87aap3uyo7.fsf at castleamber.com>, John Bokma wrote: > > Go look at the original claim, the one that you responded to. "It's > > much easier to distribute C libraries than C++ libraries." > > Yup, and if I read it correctly the claim was: and that's why C++ was > not chosen. I doubt it. I didn't intend to claim quite that much. I'm just saying it's a consideration. I was not privy to the original design decisions. From martin at v.loewis.de Tue Aug 3 19:13:11 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 04 Aug 2010 01:13:11 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? Around the time Guido coined the term "Python 3000" (i.e. in 2000), he also said at a few occasions that it would be written in C++. He subsequently dropped the idea, for the reasons that people have been discussing. Regards, Martin From bazwal at ftml.net Tue Aug 3 19:27:55 2010 From: bazwal at ftml.net (Baz Walter) Date: Wed, 04 Aug 2010 00:27:55 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C587B17.7050905@mrabarnett.plus.com> References: <4C585867.8090207@ftml.net> <4C5862A6.6030101@mrabarnett.plus.com> <4C587091.8040901@ftml.net> <4C587B17.7050905@mrabarnett.plus.com> Message-ID: <4C58A5FB.2010606@ftml.net> On 03/08/10 21:24, MRAB wrote: >>> And, BTW, none of your examples pass a UTF-8 bytestring to re.findall: >>> all those string literals starting with the 'u' prefix are Unicode >>> strings! >> >> not sure what you mean by this: if the string was encoded as utf8, >> '\w' still wouldn't match any of the non-ascii characters. >> > Strings with the 'u' prefix are Unicode strings, not bytestrings. They > don't have an encoding. well, they do if they are given one, as i suggested! to be explicit, if the local encoding is 'utf8', none of the following will get a hit: (1) re.findall(r'\w', '\xe5 \xe6 \xe7', re.L) (2) re.findall(r'\w', u'\xe5 \xe6 \xe7'.encode('utf8'), re.L) (3) re.findall(r'\w', u'\xe5 \xe6 \xe7', re.L) so i still don't know what you meant about passing a 'UTF-8 bytestring' in your first comment :) only (3) could feasibly get a hit - and then only if the re module was smart enough to fall back to re.UNICODE for utf8 (and any other encodings of unicode it might know about). > 2. LOCALE: bytestring with characters in the current locale (but only 1 > byte per character). Characters are categorised according to the > underlying C library; for example, 'a' is a letter if isalpha('a') > returns true. this is actually what my question was about. i suspected something like this might be the case, but i can't actually see it stated anywhere in the docs. maybe it's just me, but 'current locale' doesn't naturally imply 'only 8-bit encodings'. i would have thought it implied 'whatever encoding is discovered on the local system' - and these days, that's very commonly utf8. is there actually a use case for it working the way it currently does? it seems just broken to have it depending so heavily on implementation details. > 3. UNICODE (default in Python 3): Unicode string. i've just read the python3 re docs, and they do now make an explicit distinction between matching bytes (with the new re.ASCII flag) and matching textual characters (i.e. unicode, the default). the re.LOCALE flag is still there, and there are now warnings about it's unreliability - but it still doesn't state that it can only work properly if the local encoding is 8-bit. From greg.ewing at canterbury.ac.nz Tue Aug 3 19:54:45 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 04 Aug 2010 11:54:45 +1200 Subject: The untimely dimise of a weak-reference In-Reply-To: <4c568b59$0$14545$426a34cc@news.free.fr> References: <8bhi2fFifjU1@mid.individual.net> <4c568b59$0$14545$426a34cc@news.free.fr> Message-ID: <8bro1bFcucU1@mid.individual.net> Bruno Desthuilliers wrote: > Would be better with : > > return self.func(obj, *args, *kwds) Thanks -- well spotted! -- Greg From borg at gone.com Tue Aug 3 20:05:04 2010 From: borg at gone.com (THE BORG) Date: Wed, 4 Aug 2010 01:05:04 +0100 Subject: Air force one shoes ( http://www.brandtrade99.com/ In-Reply-To: References: Message-ID: Now don't all rush, and form an ordery queue PLEASE! We are sure you all want Air force one shoes. From ldo at geek-central.gen.new_zealand Tue Aug 3 20:11:17 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 12:11:17 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: In message , Grant Edwards wrote: > I've always thought Ada was a pretty nice embedded/systems languages, > but some of the initial implementations were indede horrible. Well, there?s GNAT, the GNU Ada implementation. Seems pretty robust and complete, while offering backward compatibility with some of those ?initial implementations?, presumably because people have so much code already written for them. Disclaimer: the most complicated Ada program I?ve ever written is this . Or maybe this . :) From lists at cheimes.de Tue Aug 3 20:16:32 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 04 Aug 2010 02:16:32 +0200 Subject: default behavior In-Reply-To: <4C589CA2.1040709@stoneleaf.us> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> <4C589CA2.1040709@stoneleaf.us> Message-ID: > Perhaps punctuation will help clarify my intent: > > __missing__ is *not* part of (dict)s, as shown by dir(dict()): Indeed, that's correct. Can we agree, that __missing__ is an optional feature of the dict interface, that can be implemented in subclasses of dict? Christian From python at mrabarnett.plus.com Tue Aug 3 20:24:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 04 Aug 2010 01:24:59 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C58A5FB.2010606@ftml.net> References: <4C585867.8090207@ftml.net> <4C5862A6.6030101@mrabarnett.plus.com> <4C587091.8040901@ftml.net> <4C587B17.7050905@mrabarnett.plus.com> <4C58A5FB.2010606@ftml.net> Message-ID: <4C58B35B.4040206@mrabarnett.plus.com> Baz Walter wrote: > On 03/08/10 21:24, MRAB wrote: >>>> And, BTW, none of your examples pass a UTF-8 bytestring to >>>> re.findall: all those string literals starting with the 'u' prefix >>>> are Unicode strings! >>> >>> not sure what you mean by this: if the string was encoded as utf8, >>> '\w' still wouldn't match any of the non-ascii characters. >>> >> Strings with the 'u' prefix are Unicode strings, not bytestrings. >> They don't have an encoding. > > well, they do if they are given one, as i suggested! > > to be explicit, if the local encoding is 'utf8', none of the following > will get a hit: > > (1) re.findall(r'\w', '\xe5 \xe6 \xe7', re.L) This passes, for example, 0xE5 to the C library function isalnum() to check whether it's alphanumeric. Apparently it's returning false when the locale is set to UTF-8. > (2) re.findall(r'\w', u'\xe5 \xe6 \xe7'.encode('utf8'), re.L) u'\xe5' is encoded to '\xc3\xa5'. Both 0xC3 and 0xA5 are passed to the C library function isalnum() to check whether they're alphanumeric. Apparently it's returning false for both when the locale is set to UTF-8. > (3) re.findall(r'\w', u'\xe5 \xe6 \xe7', re.L) > Same as (1) above. > so i still don't know what you meant about passing a 'UTF-8 > bytestring' in your first comment :) > > only (3) could feasibly get a hit - and then only if the re module was > smart enough to fall back to re.UNICODE for utf8 (and any other > encodings of unicode it might know about). > LOCALE was really intended for all those 1-byte-per-character character sets like CP1252. Trying to implement regex when different characters occupy different numbers of bytes is, well, challenging! :-) >> 2. LOCALE: bytestring with characters in the current locale (but only >> 1 byte per character). Characters are categorised according to the >> underlying C library; for example, 'a' is a letter if isalpha('a') >> returns true. > > this is actually what my question was about. i suspected something > like this might be the case, but i can't actually see it stated > anywhere in the docs. maybe it's just me, but 'current locale' doesn't > naturally imply 'only 8-bit encodings'. i would have thought it > implied 'whatever encoding is discovered on the local system' - and > these days, that's very commonly utf8. > > is there actually a use case for it working the way it currently does? > it seems just broken to have it depending so heavily on implementation > details. > As I said, it's for old-style 1-byte-per-character character sets. If you have UTF-8, then you can decode to Unicode. Is it broken? Well, it works well enough for its intended use. Could the re module work with bytes which represent characters in an arbitrary encoding? Would you like to have a go at implementing it? I wouldn't... It would be easier to just decode to Unicode and work with that. >> 3. UNICODE (default in Python 3): Unicode string. > > i've just read the python3 re docs, and they do now make an explicit > distinction between matching bytes (with the new re.ASCII flag) and > matching textual characters (i.e. unicode, the default). the re.LOCALE > flag is still there, and there are now warnings about it's > unreliability - but it still doesn't state that it can only work > properly if the local encoding is 8-bit. The recommendation for text is to use UTF-8 externally (input, output and storage in files) and Unicode internally when processing. From ethan at stoneleaf.us Tue Aug 3 21:09:32 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 18:09:32 -0700 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> <4C589CA2.1040709@stoneleaf.us> Message-ID: <4C58BDCC.1030407@stoneleaf.us> Christian Heimes wrote: >> Perhaps punctuation will help clarify my intent: >> >> __missing__ is *not* part of (dict)s, as shown by dir(dict()): > > Indeed, that's correct. Can we agree, that __missing__ is an optional > feature of the dict interface, that can be implemented in subclasses of > dict? Absolutely. ~Ethan~ From howe.steven at gmail.com Tue Aug 3 21:34:30 2010 From: howe.steven at gmail.com (GrayShark) Date: Tue, 03 Aug 2010 20:34:30 -0500 Subject: PIL References: <882435.39022.qm@web51008.mail.re2.yahoo.com> Message-ID: As we seem to be at an impasse with respect to PIL and xpm, I know gimp does support saving as xpm and that gimp has a python language console. Perhaps parvini_navid at yahoo.com, could look to the gimp mailing list for help? Steven On Tue, 03 Aug 2010 01:56:20 -0700, Chris Rebert wrote: > On Tue, Aug 3, 2010 at 1:45 AM, Navid Parvini > wrote: >> Dear All, >> >> I want to convert a .png file to .xpm using PIL. I used the following >> command: Image.open( "t1.png").save("a1.xpm"). But it doesn't work and >> I could not convert it. >> >> Would you please help me and let me know that how can I convert/save >> .xpm files in PIL. > > PIL only supports reading .XPM, not writing .XPM: > http://www.pythonware.com/library/pil/handbook/format-xpm.htm > > Cheers, > Chris From nikos.the.gr33k at gmail.com Tue Aug 3 21:41:42 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Tue, 3 Aug 2010 18:41:42 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> Message-ID: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> >On 3 ???, 21:00, Dave Angel wrote: > A string is an object containing characters. A string literal is one of > the ways you create such an object. When you create it that way, you > need to make sure the compiler knows the correct encoding, by using the > encoding: line at beginning of file. mymessage = "????????" <==== string mymessage = u"????????" <==== string literal? So, a string literal is one of the encodings i use to create a string object? Can the encodign of a python script file be in iso-8859-7 which means the file contents is saved to the hdd as greek-iso but the part of this variabel value mymessage = u"????????" is saved as utf-8 ot the opposite? have the file saved as utf-8 but one variuable value as greek encoding? Encodings still give me headaches. I try to understand them as different ways to store data in a media. Tell me something. What encoding should i pick for my scripts knowing that only contain english + greek chars?? iso-8859-7 or utf-8 and why? Can i save the sting lets say "?????" in different encodings and still print out correctly in browser? ascii = the standard english character set only, right? > The web server wraps a few characters before and after your html stream, > but it shouldn't touch the stream itself. So the pythoon compiler using the cgi module is the one that is producing the html output that immediately after send to the web server, right? > > For example if i say mymessage = "????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the > > 2nd its a utf-8 one? > > No, the first is an 8 bit copy of whatever bytes your editor happened to > save. But since mymessage = "????????" is a string containing greek characaters why the editor doesn't save it as such? It reminds me of varibles an valeus where if you say a = 5 , a var becomes instantly an integer variable while a = 'hello' , become instantly a string variable > mymessage = u"????????" > > creates an object that is *not* encoded. Because it isn't saved by the editor yet? In what satet is this object in before it gets encoded? And it egts encoded the minute i tell the editor to save the file? > Encoding is taking the unicode > stream and representing it as a stream of bytes, which may or may have > more bytes than the original has characters. So this line mymessage = u"????????" what it does is tell the browser thats when its time to save the whole file to save this string as utf-8? If yes, then if were to save the above string as greek encoding how was i suppose to right it? Also if u ise the 'coding line' in the beggining of the file is there a need for using the u literal? > I personally haven't done any cookie code. If I were debugging this, I'd > factor out the multiple parts of that if statement, and find out which > one isn't true. From here I can't guess. I did what you say and foudn out that both of the if condition parts were always false thast why the if code blck never got executed. And it is alwsy wrong because the cookie never gets set. So can you please tell me why this line cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year never created a cookie? From invalid at invalid.invalid Tue Aug 3 21:57:09 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 01:57:09 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> I've always thought Ada was a pretty nice embedded/systems languages, >> but some of the initial implementations were indede horrible. > > Well, there?s GNAT, the GNU Ada implementation. Seems pretty robust and > complete, while offering backward compatibility with some of those ?initial > implementations?, presumably because people have so much code already > written for them. Yep, I've installed Gnat a couple times with the intention of playing around with it, but there's pretty much zero chance I could sell it at the office in place of C/C++ for embedded stuff, and for desktop stuff it's just way to easy to get programs done using Python. I also looked at Modula-3 once, and thought it had some real promise, but I think it's probably deader than Ada now. -- Grant From no.email at nospam.invalid Tue Aug 3 22:07:26 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 19:07:26 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Grant Edwards writes: > Yep, I've installed Gnat a couple times with the intention of playing > around with it, but there's pretty much zero chance I could sell it at > the office in place of C/C++ for embedded stuff, I wonder what the issues are. From everything I've heard, it's a pretty good compiler. It does ok against C/C++ in the Alioth shootouts. I haven't written anything in it beyond "hello world" but I've looked at the wikibook about it and that intro piece that I linked earlier. It's more verbose than C, so coding in it takes more keystrokes, but it looks to me like the general coding approach (modulo the extra keystrokes) should be similar to that of C, Algol, and so on, and the results should be quite a bit more reliable. Mozilla is fed up with C++ and seems to be working on its own language, called Rust: http://lambda-the-ultimate.org/node/4009 From kerensaelise at hotmail.com Tue Aug 3 22:14:30 2010 From: kerensaelise at hotmail.com (elsa) Date: Tue, 3 Aug 2010 19:14:30 -0700 (PDT) Subject: parsing tab and newline delimited text Message-ID: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Hi, I have a large file of text I need to parse. Individual 'entries' are separated by newline characters, while fields within each entry are separated by tab characters. So, an individual entry might have this form (in printed form): Title date position data with each field separated by tabs, and a newline at the end of data. So, I thought I could simply open a file, read each line in in turn, and parse it.... f=open('MyFile') line=f.readline() parts=line.split('\t') etc... However, 'data' is a fairly random string of characters. Because the files I'm processing are large, there is a good chance that in every file, there is a data field that might look like this: 899998dlKKlS\lk3#kdf\nllllKK99 or like this: LLLSDKJJJdkkf334$\ttttks)))K99 so, you see the random strings '\n' and '\t' are stopping me from being able to parse my file correctly. Any suggestions on how to overcome this problem would be greatly appreciated. Many thanks, Elsa From prologic at shortcircuit.net.au Tue Aug 3 22:32:10 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 4 Aug 2010 12:32:10 +1000 Subject: parsing tab and newline delimited text In-Reply-To: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: On Wed, Aug 4, 2010 at 12:14 PM, elsa wrote: > I have a large file of text I need to parse. Individual 'entries' are > separated by newline characters, while fields within each entry are > separated by tab characters. Sounds to me like a job of the csv module. cheers James -- -- James Mills -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Tue Aug 3 22:36:20 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 3 Aug 2010 19:36:20 -0700 Subject: Trying to set a cookie within a python script In-Reply-To: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: 2010/8/3 ????? : >>On 3 ???, 21:00, Dave Angel wrote: > >> A string is an object containing characters. A string literal is one of >> the ways you create such an object. When you create it that way, you >> need to make sure the compiler knows the correct encoding, by using the >> encoding: line at beginning of file. > > > mymessage = "????????" ? <==== string > mymessage = u"????????" ?<==== string literal? Not quite. A literal is the actual string in the file, those letters between the quotes: "????????" <=== String literal (a literal value of the string/str type) u"????????" <=== Unicode literal (a literal value of the Unicode type. The bytes on the page will be converted to unicode using the file's encoding) mymessage <==== String (not literal, because it's a value) > > So, a string literal is one of the encodings i use to create a string > object? > > Can the encodign of a python script file be in iso-8859-7 which means > the file contents is saved to the hdd as greek-iso but the part of > this variabel value mymessage = u"????????" is saved as utf-8 ot the > opposite? > The compiler does not see u"????????" on the page. All it sees is the bytes ['0x75', '0x22', '0xea', '0xe1', '0xeb', '0xe7', '0xec', '0xdd', '0xf1', '0xe1', '0x22'] Now the compiler knows that the sequence 0x75 0x22 (Stuff) 0x22 means to create a Unicode literal. So it takes those bytes ('0xea', '0xe1', '0xeb', '0xe7', '0xec', '0xdd', '0xf1', '0xe1') and decodes them using the pages encoding, in your case ISO-8859-7. At this point, they don't have an encoding. They aren't bytes as far as you are concerned, they are code points. Internally, they're stored as either UTF-16 or UTF-32 depending on how Python was compiled, but that doesn't matter. You can treat them as if they are characters. > have the file saved as utf-8 but one variuable value as greek > encoding? > Sure you can. A unicode literal will always have the encoding of the file. But a string is just a sequence of bytes (forget about the characters that show up on the page for now). If you do "\xce\xba\xce\xb1\xce\xbb\xce\xb7\xce\xbc\xce\xad\xcf\x81\xce\xb1".encode('UTF-8') Then Python will take that sequence of bytes and interpret them as UTF-8. That will give you the same Unicode string you started out with: u"????????" > Encodings still give me headaches. I try to understand them as > different ways to store data in a media. > > Tell me something. What encoding should i pick for my scripts knowing > that only contain english + greek chars?? > iso-8859-7 or utf-8 and why? > > Can i save the sting lets say "?????" in different encodings and still > print out correctly in browser? > > ascii = the standard english character set only, right? > Yes. >> The web server wraps a few characters before and after your html stream, >> but it shouldn't touch the stream itself. > > So the pythoon compiler using the cgi module is the one that is > producing the html output that immediately after send to the web > server, right? > > >> > For example if i say mymessage = "????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the >> > 2nd its a utf-8 one? No. They both are in whatever encoding your file is using. But the first one will be interpreted as a sequence of bytes. the second one will be interpreted as a sequence of characters. For a single-byte encoding like ISO-8859-7, it doesn't make a difference. But if you were to encode it in UTF-8, the first one would have a length of 16 (because the Greek characters are all 2 bytes) and the 2nd one would have a length of 8. >> >> No, the first is an 8 bit copy of whatever bytes your editor happened to >> save. > > But since mymessage = "????????" is a string containing greek > characaters why the editor doesn't save it as such? > Because you don't save characters, you save bytes. \xce\xba\xce\xb1\xce\xbb\xce\xb7\xce\xbc\xce\xad\xcf\x81\xce\xb1 is your String in UTF-8 \xea\xe1\xeb\xe7\xec\xdd\xf1\xe1 is that exact same string in ISO-8859-7 They are two different ways of representing the same characters > It reminds me of varibles an valeus where if you say > > a = 5 , a var becomes instantly an integer variable > while > a = 'hello' , become instantly a string variable > > >> mymessage = u"????????" >> >> creates an object that is *not* encoded. > > Because it isn't saved by the editor yet? In what satet is this object > in before it gets encoded? > And it egts encoded the minute i tell the editor to save the file? > >> Encoding is taking the unicode >> stream and representing it as a stream of bytes, which may or may have >> more bytes than the original has characters. > > > So this line mymessage = u"????????" what it does is tell the browser > thats when its time to save the whole file to save this string as > utf-8? > > If yes, then if were to save the above string as greek encoding how > was i suppose to right it? > > Also if u ise the 'coding line' in the beggining of the file is there > a need for using the u literal? > >> I personally haven't done any cookie code. If I were debugging this, I'd >> factor out the multiple parts of that if statement, and find out which >> one isn't true. From here I can't guess. > > I did what you say and foudn out that both of the if condition parts > were always false thast why the if code blck never got executed. > > And it is alwsy wrong because the cookie never gets set. > > So can you please tell me why this line > > cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) ? ? ? ? ?#this cookie > will expire in an year > > never created a cookie? > -- > http://mail.python.org/mailman/listinfo/python-list > From invalid at invalid.invalid Tue Aug 3 22:41:01 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 02:41:01 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Paul Rubin wrote: > Grant Edwards writes: > >> Yep, I've installed Gnat a couple times with the intention of playing >> around with it, but there's pretty much zero chance I could sell it >> at the office in place of C/C++ for embedded stuff, > > I wonder what the issues are. The issue that would prevent its use where I work is the inability to hire anybody who knows Ada. You can't hire anybody who knows C++ either, but you can hire lots of people who claim they do. [I'm not convinced that there are more than about 6 people on the planet who know C++ well enough that they should be writing real projects in it.] That said, the last time I looked the Ada spec was only something like 100 pages long, so a case could be made that it won't take long to learn. I don't know how long the C++ language spec is, but I'm betting it's closer to 1000 than 100. But I failed when I tried to get people to use Python, so I doubt I'd have any better luck with Ada. > From everything I've heard, it's a pretty good compiler. I think it's probably a very good compiler. It's the compiler users that are the issue. > It does ok against C/C++ in the Alioth shootouts. I haven't written > anything in it beyond "hello world" but I've looked at the wikibook > about it and that intro piece that I linked earlier. It's more > verbose than C, The verbosity always bugged me a little. To my eyes all the sugar gets in the way of seeing the code. Somebody should invent a language where indentation defines the blocks. > so coding in it takes more keystrokes, but it looks to me like the > general coding approach (modulo the extra keystrokes) should be > similar to that of C, Algol, and so on, and the results should be > quite a bit more reliable. Indeed. > Mozilla is fed up with C++ and seems to be working on its own language, > called Rust: > > http://lambda-the-ultimate.org/node/4009 Great! The world needs one more computer language... -- Grant From jjposner at optimum.net Tue Aug 3 22:49:06 2010 From: jjposner at optimum.net (John Posner) Date: Tue, 03 Aug 2010 22:49:06 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> Message-ID: <4C58D522.9070509@optimum.net> On 8/3/2010 6:48 PM, Ethan Furman wrote: > Christian Heimes wrote: >>> I just went and read the entry that had the bogus claim -- >>> personally, I didn't see any confusion. I would like to point out the >>> __missing__ is *not* part of dicts (tested on 2.5 and 2.6 -- don't >>> have 2.7 installed yet). >> >> I beg your pardon but you are wrong. __missing__ is available for all >> *subclasses* of dict since Python 2.5. See >> http://svn.python.org/view/python/branches/release25-maint/Objects/dictobject.c?revision=81031&view=markup >> >> >>>>> class mydict(dict): >> ... def __missing__(self, key): >> ... print "__missing__", key >> ... raise KeyError(key) >> ... >>>>> m = mydict() >>>>> m[1] >> __missing__ 1 >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 4, in __missing__ >> KeyError: 1 > > Perhaps punctuation will help clarify my intent: > > __missing__ is *not* part of (dict)s, as shown by dir(dict()): > > ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', > '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', > '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', > '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', > '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', > 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', > 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', > 'values'] > > And, just to state what is hopefully obvious, if you don't create > __missing__ yourself, it still isn't in the subclass: Right, a __missing__ method does not magically appear in the subclass. Rather, the subclass is allowed (but not required) to define a method named __missing__, which will "magically" be called in certain situations. Here's a dict subclass that uses the "magic" for a purpose that has nothing to do with default values: class BadKeyTrackerDict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.bad_keys = set([]) def __missing__(self, key): """ add missing key to "bad keys" set """ self.bad_keys.add(key) raise KeyError Note that "defaultdict" is nowhere in sight here. It's the dict class (or type) itself that provides the magic -- but only for its subclasses. > > --> class somedict(dict): > ... "Is __missing__ defined if I don't define it? Nope." > ... > --> sd = somedict() > --> sd[1] > Traceback (most recent call last): > File "", line 1, in > KeyError: 1 > --> dir(sd) > ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', > '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__', > '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', > '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', > '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', > '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', > 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', > 'setdefault', 'update', 'values'] > > ~Ethan~ -John From python at mrabarnett.plus.com Tue Aug 3 22:49:22 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 04 Aug 2010 03:49:22 +0100 Subject: Trying to set a cookie within a python script In-Reply-To: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: <4C58D532.3010709@mrabarnett.plus.com> ????? wrote: >> On 3 ???, 21:00, Dave Angel wrote: > >> A string is an object containing characters. A string literal is one of >> the ways you create such an object. When you create it that way, you >> need to make sure the compiler knows the correct encoding, by using the >> encoding: line at beginning of file. > [snip] > Tell me something. What encoding should i pick for my scripts knowing > that only contain english + greek chars?? > iso-8859-7 or utf-8 and why? > This is easy to answer: UTF-8 with the: # -*- coding: UTF-8 -*- comment to tell Python that your script file is encoded in UTF-8. I was once given a file in a language I don't know (translations for display messages). Some of the text didn't look quite right. It took me a while to figure out that it was written on a machine which used CP1250 and my machine used CP1252. If everybody used the same encoding then such problems wouldn't occur, and UTF-8 can handle any characters which are in Unicode: Latin, Greek, Cyrillic, Arabic, etc. From python.list at tim.thechases.com Tue Aug 3 22:49:57 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 03 Aug 2010 21:49:57 -0500 Subject: parsing tab and newline delimited text In-Reply-To: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: <4C58D555.3000307@tim.thechases.com> On 08/03/10 21:14, elsa wrote: > I have a large file of text I need to parse. Individual 'entries' are > separated by newline characters, while fields within each entry are > separated by tab characters. > > So, an individual entry might have this form (in printed form): > > Title date position data > > with each field separated by tabs, and a newline at the end of data. > So, I thought I could simply open a file, read each line in in turn, > and parse it.... > > f=open('MyFile') > line=f.readline() > parts=line.split('\t') > > etc... > > However, 'data' is a fairly random string of characters. Because the > files I'm processing are large, there is a good chance that in every > file, there is a data field that might look like this: > > 899998dlKKlS\lk3#kdf\nllllKK99 My first question is whether the line contains actual newline/tab characters within the field data, or the string-representation of the line. For one of the lines in question, what does print repr(line) (or "print line.encode('hex')") produce? If the line has extra literal tabs, then you may be stuck; if the line has escaped text (a backslash followed by an "n" or "t", i.e. 2 characters) then it's pretty straight-forward. Ideally, you'd see something like >>> print repr(line) 'MyTitle\t2010-08-02\t42\t89998dlKKlS\\lk3#kdf\\nlllKK99' ^tab ^tab ^tab ^backslash^ where the backslashes are literal. If you know that it's the last ("data") field that can contain such characters, you can at least catch non-newline characters by only splitting the first N splits: parts = line.split('\t', 3) That doesn't solve the newline problem, but your file's definition prevents you from being able to discern filedata = 'title1\tdate1\tpos1\tdata1\nxxxx\tyyyy\tzzzz\twwww\n' Would xxxx/yyyy/zzzz/wwww be a continuation of data1 or are they the items in the next row? -tkc From no.email at nospam.invalid Tue Aug 3 23:02:09 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 20:02:09 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: <7xfwyvw05q.fsf@ruckus.brouhaha.com> Grant Edwards writes: > The issue that would prevent its use where I work is the inability to > hire anybody who knows Ada. ... > That said, the last time I looked the Ada spec was only something like > 100 pages long, so a case could be made that it won't take long to > learn. Well, I don't know Ada (I've read about it but not written actual code), so maybe I shouldn't be the one saying this, but geez, it's another imperative, procedural language, like Algol or Pascal or even C. Its type is much more serious than C's but shouldn't be a problem for anyone who uses C++ or Java generics. It also has a real module system unlike more commonly used languages, but 1) that part seems easy to understand; and 2) usually that's used for multi-programmer projects, so as long as there's some reasonable proportion of experienced users on the team, the inter-module interfaces should be sensible and less experienced users can just program to existing interfaces and/or get some help from others. Ada's module system is much simpler than (say) ML's. > I don't know how long the C++ language spec is, but I'm > betting it's closer to 1000 than 100. I don't know about an official spec. Stroustrup's "The C++ programming language" is about 1000 pp, but it's a textbook, with lots of examples, exercises, etc. I read through an earlier (shorter) edition in a couple of evenings a long time ago and it all made sense. It has some hairy aspects like the notorious template metaprogramming, but most users simply won't get involved with that. Python has its own obscure and confusing features if that matters. I think I'm a reasonably good Python programmer but I've never written a special metaclass and wouldn't really know how to. From python at mrabarnett.plus.com Tue Aug 3 23:05:56 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 04 Aug 2010 04:05:56 +0100 Subject: parsing tab and newline delimited text In-Reply-To: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: <4C58D914.6090907@mrabarnett.plus.com> elsa wrote: > Hi, > > I have a large file of text I need to parse. Individual 'entries' are > separated by newline characters, while fields within each entry are > separated by tab characters. > > So, an individual entry might have this form (in printed form): > > Title date position data > > with each field separated by tabs, and a newline at the end of data. > So, I thought I could simply open a file, read each line in in turn, > and parse it.... > > f=open('MyFile') > line=f.readline() > parts=line.split('\t') > > etc... > > However, 'data' is a fairly random string of characters. Because the > files I'm processing are large, there is a good chance that in every > file, there is a data field that might look like this: > > 899998dlKKlS\lk3#kdf\nllllKK99 > > or like this: > > LLLSDKJJJdkkf334$\ttttks)))K99 > > so, you see the random strings '\n' and '\t' are stopping me from > being able to parse my file correctly. Any > suggestions on how to overcome this problem would be greatly > appreciated. > When you say random strings '\n', etc, are they the backslash character \ followed by the letter n? If so, then you don't have a problem. They are \ followed by n. If, on the other hand, by '\n' you mean the newline character, then, well, that's a newline character, and there's (probably) nothing you can do about it. From sturlamolden at yahoo.no Tue Aug 3 23:08:03 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 3 Aug 2010 20:08:03 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: On 4 Aug, 04:41, Grant Edwards wrote: > The issue that would prevent its use where I work is the inability to > hire anybody who knows Ada. ?You can't hire anybody who knows C++ > either, but you can hire lots of people who claim they do. ? That is very true. From nikos.the.gr33k at gmail.com Tue Aug 3 23:08:46 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Tue, 3 Aug 2010 20:08:46 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: <0c4d0b86-b5b6-48f9-ba26-b8c344df2d83@t20g2000yqa.googlegroups.com> For the cookie problem iam tryign houts now and even this aint working: ======================================== cookie = Cookie.SimpleCookie() if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist print "Cookie Unset" cookie['visitor'] = 'nikos' cookie['visitor']['expires'] = -1 #this cookie will expire now else: print "Cookie is set!" cookie['visitor'] = 'nikos' cookie['visitor']['expires'] = 1000 #this cookie will expire now ======================================== i tried in IDLE enviroment as well and for some reason even with a single number isnated of time() function the cookie is never set, because the print of >>>print os.environ.get('HTTP_COOKIE') result to None :( From kerensaelise at hotmail.com Tue Aug 3 23:35:34 2010 From: kerensaelise at hotmail.com (elsa) Date: Tue, 3 Aug 2010 20:35:34 -0700 (PDT) Subject: parsing tab and newline delimited text References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: <5ac28f2f-a751-4856-ba4d-c766eafe80e2@s17g2000prh.googlegroups.com> On Aug 4, 12:49?pm, Tim Chase wrote: > On 08/03/10 21:14, elsa wrote: > > > > > I have a large file of text I need to parse. Individual 'entries' are > > separated by newline characters, while fields within each entry are > > separated by tab characters. > > > So, an individual entry might have this form (in printed form): > > > Title ? ?date ? position ? data > > > with each field separated by tabs, and a newline at the end of data. > > So, I thought I could simply open a file, read each line in in turn, > > and parse it.... > > > f=open('MyFile') > > line=f.readline() > > parts=line.split('\t') > > > etc... > > > However, 'data' is a fairly random string of characters. Because the > > files I'm processing are large, there is a good chance that in every > > file, there is a data field that might look like this: > > > 899998dlKKlS\lk3#kdf\nllllKK99 > > My first question is whether the line contains actual newline/tab > characters within the field data, or the string-representation of > the line. ?For one of the lines in question, what does > > ? ?print repr(line) here is what I get at the interactive prompt: >>> line = """IIIIIIIIIIIIIIIIIIIIIG=4448>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIG666HIIIIII;;;IIIIIIEIIII??55 ... :E?IEEEEFHGCACIIIII699;66IG11G???IIIIIIIIIIIIG???GGGII@@@@GG?;; 9>CCIIIIIIIIIIICCCCGHHIIIGEEDBB?9951//////6=ABB=EEGII98AEIECCC>>;A=F@;; 44//11::=<>> line 'IIIIIIIIIIIIIIIIIIIIIG=4448>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIG666HIIIIII;;;IIIIIIEIIII?? 55\n:E?IEEEEFHGCACIIIII699;66IG11G???IIIIIIIIIIIIG???GGGII@@@@GG?;; 9>CCIIIIIIIIIIICCCCGHHIIIGEEDBB?9951//////6=ABB=EEGII98AEIECCC>>;A=F@;; 44//11::=<>> print repr(line) 'IIIIIIIIIIIIIIIIIIIIIG=4448>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIG666HIIIIII;;;IIIIIIEIIII?? 55\n:E?IEEEEFHGCACIIIII699;66IG11G???IIIIIIIIIIIIG???GGGII@@@@GG?;; 9>CCIIIIIIIIIIICCCCGHHIIIGEEDBB?9951//////6=ABB=EEGII98AEIECCC>>;A=F@;; 44//11::=< <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: On Aug 3, 7:07?pm, Paul Rubin wrote: > Mozilla is fed up with C++ and seems to be working on its own language, > called Rust: > > ? ?http://lambda-the-ultimate.org/node/4009 That looks much better than Go. It's like all the cool features of Go without the annoying polemics. I'm starting to get the feeling one of these languages is going to hit a sweet spot and turn C into the next Cobol. Carl Banks From murraywk at gmail.com Tue Aug 3 23:39:22 2010 From: murraywk at gmail.com (wazza) Date: Tue, 3 Aug 2010 20:39:22 -0700 (PDT) Subject: Loading pyd fails with "The operating system cannot run %1" Message-ID: <65b65b69-a5e9-4356-a2a9-85c4a508edb7@g6g2000pro.googlegroups.com> Running python 2.6 (r26:66714) on Win Xp Pro SP3, I receive the following message: python -v -v -v >>> import functions . . # trying U:\wss\v72212\components\trm\python\lib\lib\site-packages \_fk_cl.pyd # clear[2] __file__ # clear[2] __package__ # clear[2] __path__ # clear[2] __name__ # clear[2] __doc__ # clear[2] __name__ # clear[2] __file__ Traceback (most recent call last): File "", line 1, in File "u:\wss\v72212\components\trm\python\lib\lib\site-packages \functions.py", line 1, in import FK.Core File "U:\wss\v72212\components\trm\python\lib\lib\site-packages\FK \Core\__init__.py", line 19, in from _fk_cl import * ImportError: DLL load failed: The operating system cannot run %1. Tracking this back, this represents an error code in windows: ERROR_INVALID_ORDINAL 182 (0xB6) The web has been unhelpful on what this represents. This works for people on other computers with the same configuration. I have python 2.6 loaded locally. Any ideas? I thought perhaps file associations in windows, but there are none for .pyd files. From navkirats at gmail.com Wed Aug 4 00:00:22 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 09:30:22 +0530 Subject: Global variables problem Message-ID: Hey guys, I am using a multiprocessing program, where the new process is supposed to change a variable in the main class that it branches out from. This is somehow not working, following is an approximate code. Would really appreciate any insight into this matter: var = {} class Something(): def set_var(self): global var var = somevalue def get_var(self): return var def newprocess(self): self.set_var() def do_multiprocessing(self): while true: self.get_var() new_process = process(target=newprocess) new_process.start() I am really confused here ! Any help would be awesome : ) Regards, Nav From roy at panix.com Wed Aug 4 00:00:41 2010 From: roy at panix.com (Roy Smith) Date: Wed, 04 Aug 2010 00:00:41 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In article , sturlamolden wrote: > On 4 Aug, 04:41, Grant Edwards wrote: > > > The issue that would prevent its use where I work is the inability to > > hire anybody who knows Ada. ?You can't hire anybody who knows C++ > > either, but you can hire lots of people who claim they do. ? > > That is very true. I suspect there are less than 100 people in the world who "know C++" in the sense that they know every feature, every detail, every quirk. These are the people who sit on the standards committee, write the books we all buy, etc. There are, however, a lot of people who know a large enough subset of C++ to be productive and to write effective, safe, quality code within those boundaries. These people know what they don't know and either avoid using those features, or know where (and when) to look it up. I put myself in that camp. The problem is, there are also a very large number of people who put "expert C++" on their resumes and know just enough to be dangerous. The real problem is that it's sometimes difficult to distinguish between the members of the latter two groups in an interview. From cbrauchli at gmail.com Wed Aug 4 00:01:38 2010 From: cbrauchli at gmail.com (Chris Brauchli) Date: Tue, 3 Aug 2010 21:01:38 -0700 (PDT) Subject: Python Script Cannot Write to Directory Message-ID: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> Hi, I am writing a script that, at one point, copies a file from directory A to directory B. Directory B can only be written to by root, but the script is always called with sudo, so this shouldn't be an issue, but it is. I have tried using shutil.copy() and calling "sudo cp " with os.popen to no avail. I cannot get the script to copy a file to directory B. The strange thing is if I run the python interpreter (as sudo) and type in shutil.copy it works. It also works if I try to copy the file to a less protected directory. It only happens when I try to copy a file to directory B from a python script. Any ideas why this is happening? If more information is needed or something isn't clear let me know. Thanks for helping. Chris From ddasilva at umd.edu Wed Aug 4 00:16:51 2010 From: ddasilva at umd.edu (Daniel da Silva) Date: Tue, 3 Aug 2010 21:16:51 -0700 Subject: Global variables problem In-Reply-To: References: Message-ID: Please post approximate code that actually works and displays the problem. On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: > Hey guys, > > I am using a multiprocessing program, where the new process is supposed to > change a variable in the main class that it branches out from. This is > somehow not working, following is an approximate code. Would really > appreciate any insight into this matter: > > > var = {} > > class Something(): > > def set_var(self): > global var > var = somevalue > > def get_var(self): > return var > > def newprocess(self): > self.set_var() > > def do_multiprocessing(self): > while true: > self.get_var() > new_process = process(target=newprocess) > new_process.start() > > > I am really confused here ! > > Any help would be awesome : ) > > Regards, > Nav > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From navkirats at gmail.com Wed Aug 4 00:48:52 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 10:18:52 +0530 Subject: Global variables problem In-Reply-To: References: Message-ID: On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: > Please post approximate code that actually works and displays the problem. > > On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: > Hey guys, > > I am using a multiprocessing program, where the new process is supposed to change a variable in the main class that it branches out from. This is somehow not working, following is an approximate code. Would really appreciate any insight into this matter: > > > var = {} > > class Something(): > > def set_var(self): > global var > var = somevalue > > def get_var(self): > return var > > def newprocess(self): > self.set_var() > > def do_multiprocessing(self): > while true: > self.get_var() > new_process = process(target=newprocess) > new_process.start() > > > I am really confused here ! > > Any help would be awesome : ) > > Regards, > Nav > > -- > http://mail.python.org/mailman/listinfo/python-list > This is a working code, streamlined, but it is where the problem is: from multiprocessing import * dicts = 0 print('global ', dicts) class WebServer(): def set_sessionInfo(self): global dicts dicts = dicts + 1 def get_sessionInfo(self): return dicts def handle_connection(self): self.set_sessionInfo() def serve_forever(self): for x in range(10): p = Process(target=self.handle_connection) p.start() print(self.get_sessionInfo()) ws = WebServer() ws.serve_forever() print(dicts) -------------- next part -------------- An HTML attachment was scrubbed... URL: From marduk at letterboxes.org Wed Aug 4 00:57:33 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 04 Aug 2010 00:57:33 -0400 Subject: Python Script Cannot Write to Directory In-Reply-To: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> Message-ID: <1280897853.161893.0.camel@paska> On Tue, 2010-08-03 at 21:01 -0700, Chris Brauchli wrote: > Hi, > > I am writing a script that, at one point, copies a file from directory > A to directory B. Directory B can only be written to by root, but the > script is always called with sudo, so this shouldn't be an issue, but > it is. I have tried using shutil.copy() and calling "sudo cp " with > os.popen to no avail. I cannot get the script to copy a file to > directory B. The strange thing is if I run the python interpreter (as > sudo) and type in shutil.copy it works. It also works if I try to copy > the file to a less protected directory. It only happens when I try to > copy a file to directory B from a python script. > > Any ideas why this is happening? If more information is needed or > something isn't clear let me know. Thanks for helping. > > Chris Code? Traceback? From ldo at geek-central.gen.new_zealand Wed Aug 4 01:36:31 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 17:36:31 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In message <7xmxt3uo4h.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > It's more verbose than C, so coding in it takes more keystrokes, but it > looks to me like the general coding approach (modulo the extra keystrokes) > should be similar to that of C, Algol, and so on, and the results should > be quite a bit more reliable. I believe the life-support software on the International Space Station is written in Ada. Would anybody feel happier if that had been done in C++? From ldo at geek-central.gen.new_zealand Wed Aug 4 01:44:00 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 17:44 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In message , Grant Edwards wrote: > That said, the last time I looked the Ada spec was only something like > 100 pages long, so a case could be made that it won't take long to > learn. I don't know how long the C++ language spec is, but I'm > betting it's closer to 1000 than 100. I have a copy of ?The C++ Standard (Incorporating Technical Corrigendum No. 1)? on my bookshelf. Let?s see ... flip-flip ... the highest page number is 782. Definitely closer to 1000 than 100. As for Ada ... I don?t have any printed manual, but dpkg-query -L ada-reference-manual | grep -c html/aarm95tc1 counts 353 HTML pages for the annotated reference. I found it fairly tedious to read the lot. But then, I didn?t even try to do that with the C++ spec... From ldo at geek-central.gen.new_zealand Wed Aug 4 01:45:03 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 17:45:03 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In message , Roy Smith wrote: > There are, however, a lot of people who know a large enough subset of > C++ to be productive ... I think there are some language features, knowledge of which has a negative impact on productivity. :) From murraywk at gmail.com Wed Aug 4 01:45:31 2010 From: murraywk at gmail.com (wazza) Date: Tue, 3 Aug 2010 22:45:31 -0700 (PDT) Subject: Loading pyd fails with "The operating system cannot run %1" References: <65b65b69-a5e9-4356-a2a9-85c4a508edb7@g6g2000pro.googlegroups.com> Message-ID: <5e20ece0-e056-42b0-a2c4-3b3bc9cfff36@s24g2000pri.googlegroups.com> On Aug 4, 1:39?pm, wazza wrote: > Running python 2.6 (r26:66714) ?on Win Xp Pro SP3, I receive the > following message: > python -v -v -v>>> import functions > > . > . > > # trying U:\wss\v72212\components\trm\python\lib\lib\site-packages > \_fk_cl.pyd > # ? clear[2] __file__ > # ? clear[2] __package__ > # ? clear[2] __path__ > # ? clear[2] __name__ > # ? clear[2] __doc__ > # ? clear[2] __name__ > # ? clear[2] __file__ > Traceback (most recent call last): > ? File "", line 1, in > ? File "u:\wss\v72212\components\trm\python\lib\lib\site-packages > \functions.py", line 1, in > ? ? import FK.Core > ? File "U:\wss\v72212\components\trm\python\lib\lib\site-packages\FK > \Core\__init__.py", line 19, in > ? ? from _fk_cl import * > ImportError: DLL load failed: The operating system cannot run %1. > > Tracking this back, this represents an error code in windows: > > ERROR_INVALID_ORDINAL > 182 (0xB6) > > The web has been unhelpful on what this represents. > > This works for people on other computers with the same configuration. > I have python 2.6 loaded locally. > > Any ideas? I thought perhaps file associations in windows, but there > are none for .pyd files. OK Fixed it myself (maybe I should have looked deeper ebfore raising this post. I used dependency walker to check the dependencies of the pyd file. It indicated that libeay.dll had a problem (at least one module has an unresolved improt due to a missing export function in an implicity dependent module. Looked and sure enough it was in /windows/system32, dated 4/3/2008. There were 5 other instances on the box, from things like Yahoo widget engine, Landesk and vmware infrastructure server libeay.dll is part of the ssl library and must mismatch with some other parts of the application. In time honored manner, deleted from /windows/system32 (did not bother unregistering) and the problem is solved. From no.email at nospam.invalid Wed Aug 4 01:58:45 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 22:58:45 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: <7xeieevrze.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > I believe the life-support software on the International Space Station is > written in Ada. Would anybody feel happier if that had been done in C++? Take a look at the articles on C bug-finding on Dawson Engler's page: http://www.stanford.edu/~engler/ They are about tools that found 100's of bugs in various large C programs including Linux and OpenBSD. Most of those bugs would probably not have been possible in Ada. Program bugs are generally either subtle errors or dumb ones. Humans always will make dumb errors from time to time, and C does almost nothing to prevent them (C++ used properly is somewhat better). Ada doesn't prevent the subtle ones but appears much better than C or C++ at preventing the dumb kind. I'm not sure what the hiring issue is. I think anyone skilled in C++ or Java can pick up Ada pretty easily. It's mostly a subset of C++ with different surface syntax. From ddasilva at umd.edu Wed Aug 4 02:02:25 2010 From: ddasilva at umd.edu (Daniel da Silva) Date: Tue, 3 Aug 2010 23:02:25 -0700 Subject: simple (I hope!) problem In-Reply-To: <4C57EAD1.5090709@sequans.com> References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> <4C57EAD1.5090709@sequans.com> Message-ID: Why not just add the google app engine lib subdirectories to your python path? On Tue, Aug 3, 2010 at 3:09 AM, Jean-Michel Pichavant < jeanmichel at sequans.com> wrote: > samwyse wrote: > >> I'm writing for the Google app engine and have stubbed my toe yet >> again on a simple obstacle. Non-trivial app engines programs require >> the import of several modules that aren't normally in my PYTHONPATH. >> I'd like to be able to test my code outside of the app engine >> framework. I've tried several solutions in the past that worked but >> weren't particularly elegant or portable. Now I've had a new idea. >> Here's my latest attempt: >> >> import os, re >> if __name__ == '__main__': >> pass >> else >> from google.appengine.ext import webapp >> register = webapp.template.create_template_register() >> >> This works great, except my code makes use of the resister object in >> several places, like this: >> >> register.filter(emptylines) >> >> Fortunately, I don't need the functionality of the object, I just want >> something that won't generate an error when I use it. So, what is the >> quickest way to to create such an object (replacing the 'pass' in my >> first snippet). My solution is this: >> >> class C: >> def filter(self, *args, **kwds): >> pass >> register = C() >> >> but it seems like I should be able to do something "better", as >> measured by lines of code, faking more than just a 'filter' method, or >> both. Any ideas? Thanks! >> >> > > here is a class that accepts any method call without generating an error: > > class Stub(object): > @staticmethod > def stub(*arg, **kwarg): > pass > def __getattribute__(self, name): > return Stub.stub > > > s = Stub() > s.foo('bar') > s.bar > s.bar('', '', 5) > > > JM > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nyamatongwe+thunder at gmail.com Wed Aug 4 02:10:29 2010 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 04 Aug 2010 16:10:29 +1000 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: Grant Edwards: > That said, the last time I looked the Ada spec was only something like > 100 pages long, so a case could be made that it won't take long to > learn. I don't know how long the C++ language spec is, but I'm > betting it's closer to 1000 than 100. The Ada 2012 Language Reference Manual is 860 pages and the Ada 2005 LRM was 790 pages. The annotated versions are even longer http://www.ada-auth.org/standards/ada12.html Neil From ddasilva at umd.edu Wed Aug 4 02:12:22 2010 From: ddasilva at umd.edu (Daniel da Silva) Date: Tue, 3 Aug 2010 23:12:22 -0700 Subject: Global variables problem In-Reply-To: References: Message-ID: Your problem lies somewhere in the use of the Process class, not with global variables. If you replace your "p = ..." and "p.start()" lines with a direct call to self.handle_connection(), your code works as expected. I don't know much about the multiprocessing module, so I can't really comment on what you're doing wrong, but I hope this points you in the right direction. Sorry I couldn't be of more help, Daniel On Tue, Aug 3, 2010 at 9:48 PM, Navkirat Singh wrote: > > On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: > > Please post approximate code that actually works and displays the problem. > > On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: > >> Hey guys, >> >> I am using a multiprocessing program, where the new process is supposed to >> change a variable in the main class that it branches out from. This is >> somehow not working, following is an approximate code. Would really >> appreciate any insight into this matter: >> >> >> var = {} >> >> class Something(): >> >> def set_var(self): >> global var >> var = somevalue >> >> def get_var(self): >> return var >> >> def newprocess(self): >> self.set_var() >> >> def do_multiprocessing(self): >> while true: >> self.get_var() >> new_process = process(target=newprocess) >> new_process.start() >> >> >> I am really confused here ! >> >> Any help would be awesome : ) >> >> Regards, >> Nav >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > This is a working code, streamlined, but it is where the problem is: > > from multiprocessing import * > > dicts = 0 > print('global ', dicts) > > class WebServer(): > def set_sessionInfo(self): > global dicts > dicts = dicts + 1 > def get_sessionInfo(self): > return dicts > > def handle_connection(self): > self.set_sessionInfo() > def serve_forever(self): > for x in range(10): > p = Process(target=self.handle_connection) > p.start() > print(self.get_sessionInfo()) > ws = WebServer() > ws.serve_forever() > print(dicts) > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Wed Aug 4 02:34:19 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 3 Aug 2010 23:34:19 -0700 (PDT) Subject: parsing tab and newline delimited text References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: On Aug 4, 12:14?pm, elsa wrote: > So, an individual entry might have this form (in printed form): > > Title ? ?date ? position ? data > > with each field separated by tabs, and a newline at the end of data. As James posted, the csv module is ideal for this sort of thing. Dealing with delimited text seems obvious but, as with most things, there are some edge cases that can bite you, so it's generally best to use utility code that has already dealt with them. If you're using Python 2.6+ you can use it in conjunction with namedtuple for some very easy record retrieval: >>> import csv >>> from collections import namedtuple >>> Record = namedtuple('Record', 'title date position data') >>> tabReader = csv.reader(open('test.txt','rb'), delimiter='\t') >>> for record in (Record(*row) for row in tabReader): ... print record.title, record.data ... title1 data1\t\n\n\t title2 data2\t\t\t\t title3 data3\n\n\n\n Hope this helps. From navkirats at gmail.com Wed Aug 4 03:11:48 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 12:41:48 +0530 Subject: Global variables problem In-Reply-To: References: Message-ID: <10BD3E87-FCC3-4C93-BD72-B8D3BBA4544B@gmail.com> Thanks a lot guys !! I solved the problem: In the lines: >> new_process = process(target=newprocess) >> new_process.start() The target=newprocess is pointing towards a variable, instead of a function. So, appending a () will make it goto that function, thereby changing the global variable : ) Thanks, Nav On 04-Aug-2010, at 11:42 AM, Daniel da Silva wrote: > Your problem lies somewhere in the use of the Process class, not with global variables. > > If you replace your "p = ..." and "p.start()" lines with a direct call to self.handle_connection(), your code works as expected. I don't know much about the multiprocessing module, so I can't really comment on what you're doing wrong, but I hope this points you in the right direction. > > Sorry I couldn't be of more help, > > Daniel > > > On Tue, Aug 3, 2010 at 9:48 PM, Navkirat Singh wrote: > > On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: > >> Please post approximate code that actually works and displays the problem. >> >> On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: >> Hey guys, >> >> I am using a multiprocessing program, where the new process is supposed to change a variable in the main class that it branches out from. This is somehow not working, following is an approximate code. Would really appreciate any insight into this matter: >> >> >> var = {} >> >> class Something(): >> >> def set_var(self): >> global var >> var = somevalue >> >> def get_var(self): >> return var >> >> def newprocess(self): >> self.set_var() >> >> def do_multiprocessing(self): >> while true: >> self.get_var() >> new_process = process(target=newprocess) >> new_process.start() >> >> >> I am really confused here ! >> >> Any help would be awesome : ) >> >> Regards, >> Nav >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > This is a working code, streamlined, but it is where the problem is: > > from multiprocessing import * > > dicts = 0 > print('global ', dicts) > > class WebServer(): > > def set_sessionInfo(self): > global dicts > dicts = dicts + 1 > > def get_sessionInfo(self): > return dicts > > def handle_connection(self): > self.set_sessionInfo() > > def serve_forever(self): > for x in range(10): > p = Process(target=self.handle_connection) > p.start() > print(self.get_sessionInfo()) > > ws = WebServer() > ws.serve_forever() > print(dicts) > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From news1234 at free.fr Wed Aug 4 03:21:20 2010 From: news1234 at free.fr (News123) Date: Wed, 04 Aug 2010 09:21:20 +0200 Subject: Python Script Cannot Write to Directory In-Reply-To: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> Message-ID: <4c5914f0$0$9192$426a74cc@news.free.fr> On 08/04/2010 06:01 AM, Chris Brauchli wrote: > Hi, > > I am writing a script that, at one point, copies a file from directory > A to directory B. Directory B can only be written to by root, but the > script is always called with sudo, so this shouldn't be an issue, but > it is. I have tried using shutil.copy() and calling "sudo cp " with > os.popen to no avail. I cannot get the script to copy a file to > directory B. The strange thing is if I run the python interpreter (as > sudo) and type in shutil.copy it works. It also works if I try to copy > the file to a less protected directory. It only happens when I try to > copy a file to directory B from a python script. > > Any ideas why this is happening? If more information is needed or > something isn't clear let me know. Thanks for helping. > a fiew suggestions suggestions: 1,) open a terminal window with sudo -s and make ALL of the following tests from this window. 2.) tell use the exact permissions of your destination directory ls -ld DESTINATION_DIRECTORY 3.) verify, whether the file you want to copy exists already in the destination directory ls -l DESTINATION_DIRECTORY/DSTNTN_FILE_NAME 3.) try following python import os print os.getcwd() import shutil shutil("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") 4.) try the same from a shell window cp YOUR_SOURCE_FILE_NAME DESTINATION_DIRECTORY/DSTNTN_FILE_NAME From clp2 at rebertia.com Wed Aug 4 03:27:53 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 4 Aug 2010 00:27:53 -0700 Subject: Python Script Cannot Write to Directory In-Reply-To: <4c5914f0$0$9192$426a74cc@news.free.fr> References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> Message-ID: On Wed, Aug 4, 2010 at 12:21 AM, News123 wrote: > 3.) try following python > > import os > print os.getcwd() > import shutil > shutil("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") WTF; modules aren't callable. Typo? Cheers, Chris -- http://blog.rebertia.com From navkirats at gmail.com Wed Aug 4 03:47:27 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 13:17:27 +0530 Subject: Global variables problem In-Reply-To: <10BD3E87-FCC3-4C93-BD72-B8D3BBA4544B@gmail.com> References: <10BD3E87-FCC3-4C93-BD72-B8D3BBA4544B@gmail.com> Message-ID: <9BEC53A5-C8AD-43A0-8901-99F9143FA764@gmail.com> : ( False alarm, the earlier solution breaks multiprocessing. Whats happening here is the child needs to change a variable in the parent process, So I think I am looking at shared memory (maybe). Any suggestions? Regards, Nav On 04-Aug-2010, at 12:41 PM, Navkirat Singh wrote: > Thanks a lot guys !! > > I solved the problem: > > In the lines: > >>> new_process = process(target=newprocess) >>> new_process.start() > > > > The target=newprocess is pointing towards a variable, instead of a function. So, appending a () will make it goto that function, thereby changing the global variable : ) > > Thanks, > Nav > > > On 04-Aug-2010, at 11:42 AM, Daniel da Silva wrote: > >> Your problem lies somewhere in the use of the Process class, not with global variables. >> >> If you replace your "p = ..." and "p.start()" lines with a direct call to self.handle_connection(), your code works as expected. I don't know much about the multiprocessing module, so I can't really comment on what you're doing wrong, but I hope this points you in the right direction. >> >> Sorry I couldn't be of more help, >> >> Daniel >> >> >> On Tue, Aug 3, 2010 at 9:48 PM, Navkirat Singh wrote: >> >> On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: >> >>> Please post approximate code that actually works and displays the problem. >>> >>> On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: >>> Hey guys, >>> >>> I am using a multiprocessing program, where the new process is supposed to change a variable in the main class that it branches out from. This is somehow not working, following is an approximate code. Would really appreciate any insight into this matter: >>> >>> >>> var = {} >>> >>> class Something(): >>> >>> def set_var(self): >>> global var >>> var = somevalue >>> >>> def get_var(self): >>> return var >>> >>> def newprocess(self): >>> self.set_var() >>> >>> def do_multiprocessing(self): >>> while true: >>> self.get_var() >>> new_process = process(target=newprocess) >>> new_process.start() >>> >>> >>> I am really confused here ! >>> >>> Any help would be awesome : ) >>> >>> Regards, >>> Nav >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> This is a working code, streamlined, but it is where the problem is: >> >> from multiprocessing import * >> >> dicts = 0 >> print('global ', dicts) >> >> class WebServer(): >> >> def set_sessionInfo(self): >> global dicts >> dicts = dicts + 1 >> >> def get_sessionInfo(self): >> return dicts >> >> def handle_connection(self): >> self.set_sessionInfo() >> >> def serve_forever(self): >> for x in range(10): >> p = Process(target=self.handle_connection) >> p.start() >> print(self.get_sessionInfo()) >> >> ws = WebServer() >> ws.serve_forever() >> print(dicts) >> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Aug 4 03:53:00 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 4 Aug 2010 00:53:00 -0700 (PDT) Subject: Urrlib2 IncompleteRead error References: <4c0a0495-4728-40f9-ba2e-660466129a06@v23g2000vbi.googlegroups.com> Message-ID: <915a7702-8ae2-4b61-922e-45ca490c4183@u26g2000yqu.googlegroups.com> On 27 jul, 11:00, dirknbr wrote: > I am running urllib2.request and get this response when I do the read. > Any ideas what causes this? > > return response.read() > ? File "C:\Python26\lib\socket.py", line 329, in read > ? ? data = self._sock.recv(rbufsize) > ? File "C:\Python26\lib\httplib.py", line 518, in read > ? ? return self._read_chunked(amt) > ? File "C:\Python26\lib\httplib.py", line 561, in _read_chunked > ? ? raise IncompleteRead(''.join(value)) > IncompleteRead: IncompleteRead(3235 bytes read) Looks like a server error; a chunked transfer encoding finished before reaching the expected size. -- Gabriel Genellina From dotancohen at gmail.com Wed Aug 4 04:01:25 2010 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 4 Aug 2010 11:01:25 +0300 Subject: Trying to set a cookie within a python script In-Reply-To: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: 2010/8/4 ????? : > Encodings still give me headaches. I try to understand them as > different ways to store data in a media. > > Tell me something. What encoding should i pick for my scripts knowing > that only contain english + greek chars?? > iso-8859-7 or utf-8 and why? > Always use UTF-8, every modern system supports it, and it will let you use any arbitrary character that you need, such as maybe a smiley or a Euro sign. You will avoid headaches with databases and files and all sorts of other things that you don't yet expect. Declare it in the HTTP header, and in the HTML meta tag. Trust me, I maintain gibberish.co.il which specializes in encoding problems. Just use UTF-8 everywhere and you will save a lot of headaches. > Can i save the sting lets say "?????" in different encodings and still > print out correctly in browser? > No. > ascii = the standard english character set only, right? > Pretty much, plus the numbers, some symbols, and a few nonprinting characters. Read here: http://en.wikipedia.org/wiki/Ascii -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From ldo at geek-central.gen.new_zealand Wed Aug 4 04:17:03 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 20:17:03 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In message , Neil Hodgson wrote: > The Ada 2012 Language Reference Manual is 860 pages and the Ada 2005 > LRM was 790 pages. The annotated versions are even longer > http://www.ada-auth.org/standards/ada12.html Yeah, unfortunately the language was designed by a committee which was trying to meet a specification laid down by another committee set up by the US military. It seems apt to describe the resulting design as ?bulletproof?, but ?elegant? or ?concise? ... not so much. From landimatte at gmail.com Wed Aug 4 04:18:06 2010 From: landimatte at gmail.com (Matteo Landi) Date: Wed, 4 Aug 2010 10:18:06 +0200 Subject: Global variables problem In-Reply-To: <9BEC53A5-C8AD-43A0-8901-99F9143FA764@gmail.com> References: <10BD3E87-FCC3-4C93-BD72-B8D3BBA4544B@gmail.com> <9BEC53A5-C8AD-43A0-8901-99F9143FA764@gmail.com> Message-ID: Usually, modify global variables in a multi-thread/multi-process scenario is not the right to operate: you better re-implement your solution in a way that the shared resource is either protected with synchronized objects or accessed by a single thread/process (and in this case, it won't be a shared resource anymore). Think about the the needs of the shared resources: in this extremely simple example, you can see that the increment of the session number could be done by the server before spawning the child, but obviously this is not a real scenario. If you can't give up with shared resources, I recommend you to create a synchronized object owned by the server but shared with the children (take a look at the args keywords of the Process constructor). Regards. On Wed, Aug 4, 2010 at 9:47 AM, Navkirat Singh wrote: > ?: ( > False alarm, the earlier solution breaks multiprocessing. Whats happening > here is the child needs to change a variable in the parent process, So I > think I am looking at shared memory (maybe). Any suggestions? > Regards, > Nav > > > On 04-Aug-2010, at 12:41 PM, Navkirat Singh wrote: > > Thanks a lot guys !! > I solved the problem: > In the lines: >>> >>> new_process = process(target=newprocess) >>> ? ? ? ? ? ? ? ? ? ? ? ?new_process.start() > > The target=newprocess is pointing towards a variable, instead of a function. > So, appending a () will make it goto that function, thereby changing the > global variable : ) > Thanks, > Nav > > On 04-Aug-2010, at 11:42 AM, Daniel da Silva wrote: > > Your problem lies somewhere in the use of the Process class, not with global > variables. > > If you replace your "p = ..." and "p.start()" lines with a direct call to > self.handle_connection(), your code works as expected. I don't know much > about the multiprocessing module, so I can't really comment on what you're > doing wrong, but I hope this points you in the right direction. > > Sorry I couldn't be of more help, > > Daniel > > > On Tue, Aug 3, 2010 at 9:48 PM, Navkirat Singh wrote: >> >> On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: >> >> Please post approximate code that actually works and displays the problem. >> >> On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh >> wrote: >>> >>> Hey guys, >>> >>> I am using a multiprocessing program, where the new process is supposed >>> to change a variable in the main class that it branches out from. This is >>> somehow not working, following is an approximate code. Would really >>> appreciate any insight into this matter: >>> >>> >>> var = {} >>> >>> class Something(): >>> >>> ? ? ? ?def set_var(self): >>> ? ? ? ? ? ? ? ?global var >>> ? ? ? ? ? ? ? ?var = somevalue >>> >>> ? ? ? ?def get_var(self): >>> ? ? ? ? ? ? ? ?return var >>> >>> ? ? ? ?def newprocess(self): >>> ? ? ? ? ? ? ? ?self.set_var() >>> >>> ? ? ? ?def do_multiprocessing(self): >>> ? ? ? ? ? ? ? ?while true: >>> ? ? ? ? ? ? ? ? ? ? ? ?self.get_var() >>> ? ? ? ? ? ? ? ? ? ? ? ?new_process = process(target=newprocess) >>> ? ? ? ? ? ? ? ? ? ? ? ?new_process.start() >>> >>> >>> I am really confused here ! >>> >>> Any help would be awesome : ) >>> >>> Regards, >>> Nav >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> >> This is a working code, streamlined, but it is where the problem is: >> from multiprocessing import * >> dicts = 0 >> print('global ', dicts) >> class WebServer(): >> def set_sessionInfo(self): >> global dicts >> dicts = dicts + 1 >> def get_sessionInfo(self): >> return dicts >> def handle_connection(self): >> self.set_sessionInfo() >> def serve_forever(self): >> for x in range(10): >> p = Process(target=self.handle_connection) >> p.start() >> print(self.get_sessionInfo()) >> ws = WebServer() >> ws.serve_forever() >> print(dicts) >> > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Matteo Landi http://www.matteolandi.net/ From ldo at geek-central.gen.new_zealand Wed Aug 4 04:19:37 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 20:19:37 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: In message , Nobody wrote: > One feature which can't readily be implemented in C is the automatic > clean-up side of the RAII idiom. Use do-once blocks . From landimatte at gmail.com Wed Aug 4 04:20:50 2010 From: landimatte at gmail.com (Matteo Landi) Date: Wed, 4 Aug 2010 10:20:50 +0200 Subject: Python Script Cannot Write to Directory In-Reply-To: References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> Message-ID: On Wed, Aug 4, 2010 at 9:27 AM, Chris Rebert wrote: > On Wed, Aug 4, 2010 at 12:21 AM, News123 wrote: > >> 3.) try following python >> >> import os >> print os.getcwd() >> import shutil >> shutil("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") > > WTF; modules aren't callable. Typo? I suppose he/she would have written: shutil.copyfile("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") Cheers. > > Cheers, > Chris > -- > http://blog.rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From ldo at geek-central.gen.new_zealand Wed Aug 4 04:20:51 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 20:20:51 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> Message-ID: In message <7d95c0d3-718d-4958-9364-263c833f1835 at i24g2000yqa.googlegroups.com>, sturlamolden wrote: > This is unsafe, anyone who writes this in C++ should be flogged: Only if they?re using exceptions. Otherwise, it?s fine. From maral.nikfar at gmail.com Wed Aug 4 05:12:44 2010 From: maral.nikfar at gmail.com (sarah) Date: Wed, 4 Aug 2010 02:12:44 -0700 (PDT) Subject: error: (113, 'Software caused connection abort')0 Message-ID: hi i face with this problem when i want to run this command on cygwin: python httpd.py 8000 example-300-1k-rigid.py Dfghfji12d52s35s2sswee9E with this error :0 Exception happened during processing of request from ('127.0.0.1', 35868) Traceback (most recent call last): File "/usr/local/lib/python2.5/SocketServer.py", line 222, in handle_reque self.process_request(request, client_address) File "/usr/local/lib/python2.5/SocketServer.py", line 241, in process_requ self.finish_request(request, client_address) File "/usr/local/lib/python2.5/SocketServer.py", line 254, in finish_reque self.RequestHandlerClass(request, client_address, self) File "/usr/local/lib/python2.5/SocketServer.py", line 522, in __init__ self.handle() File "/usr/local/lib/python2.5/BaseHTTPServer.py", line 316, in handle self.handle_one_request() File "/usr/local/lib/python2.5/BaseHTTPServer.py", line 310, in handle_one uest method() File "/usr/local/lib/python2.5/SimpleHTTPServer.py", line 46, in do_GET self.copyfile(f, self.wfile) File "/usr/local/lib/python2.5/SimpleHTTPServer.py", line 175, in copyfile shutil.copyfileobj(source, outputfile) File "/usr/local/lib/python2.5/shutil.py", line 29, in copyfileobj fdst.write(buf) File "/usr/local/lib/python2.5/socket.py", line 274, in write self.flush() File "/usr/local/lib/python2.5/socket.py", line 261, in flush self._sock.sendall(buffer) error: (104, 'Connection reset by peer') please help me i am hurry!1 From jeanmichel at sequans.com Wed Aug 4 05:15:44 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 04 Aug 2010 11:15:44 +0200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: <4C592FC0.5080603@sequans.com> Carl Banks wrote: > On Aug 3, 7:07 pm, Paul Rubin wrote: > >> Mozilla is fed up with C++ and seems to be working on its own language, >> called Rust: >> >> http://lambda-the-ultimate.org/node/4009 >> > > That looks much better than Go. > > It's like all the cool features of Go without the annoying polemics. > I'm starting to get the feeling one of these languages is going to hit > a sweet spot and turn C into the next Cobol. > > > Carl Banks > I hope you're right, for our children sanity :) JM From navkirats at gmail.com Wed Aug 4 05:20:59 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 14:50:59 +0530 Subject: Difference between queues and pipes in multiprocessing Message-ID: <5E121D65-6150-4CC6-A35D-7834A81131AC@gmail.com> Hi, I was wondering what are the differences between queues and pipes implemented using multiprocessing python module. Am I correct if I say, in pipes, if another process writes to one receiving end concurrently, then an error will be raised and in queues the later processes data will just queued up? Thanks Nav From jeanmichel at sequans.com Wed Aug 4 05:24:30 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 04 Aug 2010 11:24:30 +0200 Subject: Global variables problem In-Reply-To: References: Message-ID: <4C5931CE.6010400@sequans.com> Navkirat Singh wrote: > > On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: > >> Please post approximate code that actually works and displays the >> problem. >> >> On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh > > wrote: >> >> Hey guys, >> >> I am using a multiprocessing program, where the new process is >> supposed to change a variable in the main class that it branches >> out from. This is somehow not working, following is an >> approximate code. Would really appreciate any insight into this >> matter: >> >> >> var = {} >> >> class Something(): >> >> def set_var(self): >> global var >> var = somevalue >> >> def get_var(self): >> return var >> >> def newprocess(self): >> self.set_var() >> >> def do_multiprocessing(self): >> while true: >> self.get_var() >> new_process = process(target=newprocess) >> new_process.start() >> >> >> I am really confused here ! >> >> Any help would be awesome : ) >> >> Regards, >> Nav >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > This is a working code, streamlined, but it is where the problem is: > > from multiprocessing import * > > dicts = 0 > print('global ', dicts) > > class WebServer(): > def set_sessionInfo(self): > global dicts > dicts = dicts + 1 > def get_sessionInfo(self): > return dicts > > def handle_connection(self): > self.set_sessionInfo() > def serve_forever(self): > for x in range(10): > p = Process(target=self.handle_connection) > p.start() > print(self.get_sessionInfo()) > ws = WebServer() > ws.serve_forever() > print(dicts) > > "As mentioned above, when doing concurrent programming it is usually best to avoid using shared state as far as possible. This is particularly true when using multiple processes. However, if you really do need to use some shared data then multiprocessing provides a couple of ways of doing so." source : http://docs.python.org/library/multiprocessing.html Read it, everything is explained with examples, including how to properly solve your problem. "When using multiple processes, one generally uses message passing for communication between processes and avoids having to use any synchronization primitives like locks." JM From steve at REMOVE-THIS-cybersource.com.au Wed Aug 4 05:29:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2010 09:29:37 GMT Subject: Python Script Cannot Write to Directory References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> Message-ID: <4c593301$0$28669$c3e8da3@news.astraweb.com> On Tue, 03 Aug 2010 21:01:38 -0700, Chris Brauchli wrote: > Hi, > > I am writing a script that, at one point, copies a file from directory A > to directory B. Directory B can only be written to by root, but the > script is always called with sudo, so this shouldn't be an issue, but it > is. I have tried using shutil.copy() and calling "sudo cp " with > os.popen to no avail. I cannot get the script to copy a file to > directory B. [...] > Any ideas why this is happening? If more information is needed or > something isn't clear let me know. Thanks for helping. Without seeing the traceback and the actual line of code that fails, and preferably the full set of permissions on the directory, we'd be guessing. Now, I love to play "debug the program by making wild guesses" with other people's code, but you might not like my suggestions :) -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Aug 4 05:33:38 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2010 09:33:38 GMT Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> <0c4d0b86-b5b6-48f9-ba26-b8c344df2d83@t20g2000yqa.googlegroups.com> Message-ID: <4c5933f2$0$28669$c3e8da3@news.astraweb.com> On Tue, 03 Aug 2010 20:08:46 -0700, ????? wrote: > i tried in IDLE enviroment as well and for some reason even with a > single number isnated of time() function the cookie is never set, > because the print of > >>>>print os.environ.get('HTTP_COOKIE') > > result to > > None What happens if you open up a NEW xterm and do this? echo $HTTP_COOKIE Or, to put it another way... are you sure that the environment variable is actually being set? -- Steven From prologic at shortcircuit.net.au Wed Aug 4 05:44:01 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 4 Aug 2010 19:44:01 +1000 Subject: Difference between queues and pipes in multiprocessing In-Reply-To: <5E121D65-6150-4CC6-A35D-7834A81131AC@gmail.com> References: <5E121D65-6150-4CC6-A35D-7834A81131AC@gmail.com> Message-ID: On Wed, Aug 4, 2010 at 7:20 PM, Navkirat Singh wrote: > I was wondering what are the differences between queues and pipes implemented using multiprocessing python module. Am I correct if I say, in pipes, if another process writes to one receiving end concurrently, then an error will be raised and in queues the later processes data will just queued up? basically a Queue is a syncronization primitive used to share and pass data to and from parent/child processes. A pipe is as the name suggests, a socket pair connected end-to-end allowing for full-duplex communications. cheers James -- -- James Mills -- -- "Problems are solved by method" From jldunn2000 at gmail.com Wed Aug 4 06:13:52 2010 From: jldunn2000 at gmail.com (loial) Date: Wed, 4 Aug 2010 03:13:52 -0700 (PDT) Subject: lpr via subprocess in 2.4 Message-ID: <5adbfea2-3154-4dbf-90a6-a2a81d38a287@l14g2000yql.googlegroups.com> I am am trying to run the following command via subprocess lpr -P printqueue filetoprint I cannot seem to get it to work and return stderr I think the issue is how to specify the arguments I am trying subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) but get error : Traceback (most recent call last): File "testopen.py", line 6, in ? subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) File "/usr/python2.4/lib/python2.4/subprocess.py", line 558, in __in it__ errread, errwrite) File "/usr/python2.4/lib/python2.4/subprocess.py", line 991, in _exe cute_child raise child_exception OSError: [Errno 2] No such file or directory From h.b.furuseth at usit.uio.no Wed Aug 4 06:15:14 2010 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Wed, 04 Aug 2010 12:15:14 +0200 Subject: Python package to read .7z archives? Message-ID: Is there an equivalent of zipfile.py for .7z archives? I have one which extracts an archive member by running 7z e -so, but that's a *slow* way to read one file at a time. Google found me some python interfaces to lzma, but apparently they only handle single compressed files, not .7z archives. (Actually another archive format would be fine if it is competitive. I'm just looking to compress my .zips better. I need a Python module to extract members reasonably fast, but slow compression would be OK.) -- Hallvard From __peter__ at web.de Wed Aug 4 07:08:39 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Aug 2010 13:08:39 +0200 Subject: lpr via subprocess in 2.4 References: <5adbfea2-3154-4dbf-90a6-a2a81d38a287@l14g2000yql.googlegroups.com> Message-ID: loial wrote: > I am am trying to run the following command via subprocess > > lpr -P printqueue filetoprint > > I cannot seem to get it to work and return stderr > > I think the issue is how to specify the arguments > > I am trying > > subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) This looks for an executable called "lpr -P"; try subprocess.Popen(['lpr', '-P' ,'laserlpr','/etc/hosts'], shell=False) > but get error : > > Traceback (most recent call last): > File "testopen.py", line 6, in ? > subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) > File "/usr/python2.4/lib/python2.4/subprocess.py", line 558, in __in > it__ > errread, errwrite) > File "/usr/python2.4/lib/python2.4/subprocess.py", line 991, in _exe > cute_child > raise child_exception > OSError: [Errno 2] No such file or directory From g.rodola at gmail.com Wed Aug 4 07:32:23 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Wed, 4 Aug 2010 13:32:23 +0200 Subject: Python package to read .7z archives? In-Reply-To: References: Message-ID: 2010/8/4 Hallvard B Furuseth : > Is there an equivalent of zipfile.py for .7z archives? > I have one which extracts an archive member by running 7z e -so, > but that's a *slow* way to read one file at a time. > > Google found me some python interfaces to lzma, but apparently they > only handle single compressed files, not .7z archives. > > (Actually another archive format would be fine if it is competitive. > I'm just looking to compress my .zips better. ?I need a Python module > to extract members reasonably fast, but slow compression would be OK.) > > -- > Hallvard > -- > http://mail.python.org/mailman/listinfo/python-list > http://bugs.python.org/issue5689 --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ From carrierphasejitter at yahoo.com Wed Aug 4 07:33:58 2010 From: carrierphasejitter at yahoo.com (Aitor Garcia) Date: Wed, 4 Aug 2010 04:33:58 -0700 (PDT) Subject: parsing a c project Message-ID: <410079.5090.qm@web51608.mail.re2.yahoo.com> Hi, I need to know the memory locations of all variables in a C project including variables allocated inside structs. What I want to do in to expand the structs into its basic elements (floats, int16 and int8). In a header file (example.h) I have the following definitions. struct house{ float area; int8 rooms; int16 visits; }; struct car{ float price; int8 color; }; I have been able to extract from the project the name of every struct, the type of the struct and the beginning address of each struct. example_list=[] example_list.append(['house1','struct house','000082d0') example_list.append(['house2','struct house','00003000') example_list.append(['car1','struct car','00004000') I need an output like this. house1_struct_house_area float 000082d0 house1_struct_house_rooms int8 000082d4 house1_struct_house_visits int16 000082d5 house2_struct_house_area float 00003000 house2_struct_house_rooms int8 00003004 house2_struct_house_visits int16 00003005 car1_struct_car_price float 00004000 car1_struct_car_color int8 00004004 How can I efficiently do this in Python ? I do not have very clear which element of Python should I use to store the struct list or class I would be very grateful if someone could give me some pointers. Aitor From jldunn2000 at gmail.com Wed Aug 4 07:38:18 2010 From: jldunn2000 at gmail.com (loial) Date: Wed, 4 Aug 2010 04:38:18 -0700 (PDT) Subject: lpr via subprocess in 2.4 References: <5adbfea2-3154-4dbf-90a6-a2a81d38a287@l14g2000yql.googlegroups.com> Message-ID: Thanks...that worked. I have also been trying to get the return code and standard error. How do I access these? #!/usr/bin/python import os import subprocess process=subprocess.Popen(['lpr', '-P' ,'raserlpr','/etc/hosts'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print process.communicate() On 4 Aug, 12:08, Peter Otten <__pete... at web.de> wrote: > loial wrote: > > I am am trying to run the following command via subprocess > > > lpr -P printqueue filetoprint > > > I cannot seem to get it to work and return stderr > > > I think the issue is how to specify the arguments > > > I am trying > > > subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) > > This looks for an executable called "lpr -P"; try > > subprocess.Popen(['lpr', '-P' ,'laserlpr','/etc/hosts'], shell=False) > > > > > but get error : > > > Traceback (most recent call last): > > ? File "testopen.py", line 6, in ? > > ? ? subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) > > ? File "/usr/python2.4/lib/python2.4/subprocess.py", line 558, in __in > > it__ > > ? ? errread, errwrite) > > ? File "/usr/python2.4/lib/python2.4/subprocess.py", line 991, in _exe > > cute_child > > ? ? raise child_exception > > OSError: [Errno 2] No such file or directory- Hide quoted text - > > - Show quoted text - From prologic at shortcircuit.net.au Wed Aug 4 07:50:24 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 4 Aug 2010 21:50:24 +1000 Subject: lpr via subprocess in 2.4 In-Reply-To: References: <5adbfea2-3154-4dbf-90a6-a2a81d38a287@l14g2000yql.googlegroups.com> Message-ID: On Wed, Aug 4, 2010 at 9:38 PM, loial wrote: > I have also been trying to get the return code and standard error. p = Popen("..., stderr=PIPE) Look up the docs for subprocess.Popen cheers James -- -- James Mills -- -- "Problems are solved by method" From h.b.furuseth at usit.uio.no Wed Aug 4 08:11:38 2010 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Wed, 04 Aug 2010 14:11:38 +0200 Subject: Python package to read .7z archives? References: Message-ID: Giampaolo Rodol? writes: > 2010/8/4 Hallvard B Furuseth : >> Is there an equivalent of zipfile.py for .7z archives? >> I have one which extracts an archive member by running 7z e -so, >> but that's a *slow* way to read one file at a time. >> >> Google found me some python interfaces to lzma, but apparently they >> only handle single compressed files, not .7z archives. >> >> (Actually another archive format would be fine if it is competitive. >> I'm just looking to compress my .zips better. ?I need a Python module >> to extract members reasonably fast, but slow compression would be OK.) > > http://bugs.python.org/issue5689 [For lzma/xz compressed tar archives] Thanks, but extraction of individual members from .tar.xz looks inherently slow. To locate the member, you need to decompress the entire portion of the archive preceding the member. -- Hallvard From bob.aalsma at aalsmacons.nl Wed Aug 4 09:10:09 2010 From: bob.aalsma at aalsmacons.nl (BobAalsma) Date: Wed, 4 Aug 2010 06:10:09 -0700 (PDT) Subject: newbie problem with str.replace Message-ID: I'm working on a set of scripts and I can't get a replace to work in the script - please help. The scripts show no errors, work properly apart from the replace, all variables are filled as expected, the scripts works properly when the commands are copied to the Python shell. Text Main: .. from LeadDevice_klant_nieuw_bewerken_bestanden import omkattenBoom, omkattenNaam ... # # (3) omkatten bestandsnamen: # print 'Omkatten bestandsnamen' omkattenNaam(AANGRIJPINGSPUNT, KLANTNAAM_OUT, KLANTNAAM_IN, ZOEKSET1_OUT, ZOEKSET1_IN, ZOEKSET2_OUT, ZOEKSET2_IN) # .... Text LeadDevice_klant_nieuw_bewerken_bestanden: import os import distutils.core ... def omkattenNaam(AANGRIJPINGSPUNT, KLANTNAAM_OUT, KLANTNAAM_IN, ZOEKSET1_OUT, ZOEKSET1_IN, ZOEKSET2_OUT, ZOEKSET2_IN): # # Strings opbouwen voordat aan de lussen gewerkt wordt: # beginpunt = AANGRIJPINGSPUNT + KLANTNAAM_IN + '/' # ZOEKSET1_OUT_LOWER = ZOEKSET1_OUT.lower() ZOEKSET1_IN_LOWER = ZOEKSET1_IN.lower() ZOEKSET2_OUT_LOWER = ZOEKSET2_OUT.lower() ZOEKSET2_IN_LOWER = ZOEKSET2_IN.lower() # # Lussen: # for root, dirs, files in os.walk(beginpunt, topdown = False): for bestandsnaam in dirs and files: # bestandsnaam_nieuw = bestandsnaam bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) From __peter__ at web.de Wed Aug 4 09:22:22 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Aug 2010 15:22:22 +0200 Subject: newbie problem with str.replace References: Message-ID: BobAalsma wrote: Although [it] may not be obvious at first unless you're Dutch... > bestandsnaam_nieuw = bestandsnaam > bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) str.replace() does not modify a string, it creates a new one. This doesn't work: >>> s = "that's all folks" >>> s.replace("all", "nothing") "that's nothing folks" >>> s "that's all folks" But this does: >>> old = "that's all folks" >>> new = old.replace("all", "nothing") >>> new "that's nothing folks" Peter From anthony.tolle at gmail.com Wed Aug 4 09:22:51 2010 From: anthony.tolle at gmail.com (Anthony Tolle) Date: Wed, 4 Aug 2010 06:22:51 -0700 (PDT) Subject: newbie problem with str.replace References: Message-ID: On Aug 4, 9:10?am, BobAalsma wrote: > ? ? ? ? ? ? ? ? ? ? ? ? # > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw = bestandsnaam > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) The replace method does not modify the string (strings are immutable). You need to use the retun value of the method in an assignment, like so: bestandsnaam_nieuw = bestandsnaam.replace(KLANTNAAM_OUT,KLANTNAAM_IN) This will not change the value of bestandsnaam From bob.aalsma at aalsmacons.nl Wed Aug 4 09:25:31 2010 From: bob.aalsma at aalsmacons.nl (BobAalsma) Date: Wed, 4 Aug 2010 06:25:31 -0700 (PDT) Subject: newbie problem with str.replace References: Message-ID: On Aug 4, 3:22?pm, Anthony Tolle wrote: > On Aug 4, 9:10?am, BobAalsma wrote: > > > ? ? ? ? ? ? ? ? ? ? ? ? # > > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw = bestandsnaam > > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) > > The replace method does not modify the string (strings are immutable). > > You need to use the retun value of the method in an assignment, like > so: > > bestandsnaam_nieuw = bestandsnaam.replace(KLANTNAAM_OUT,KLANTNAAM_IN) > > This will not change the value of bestandsnaam YESS! Thanks, this is what I wanted to achieve but could not find Regards, Bob From mrmakent at cox.net Wed Aug 4 09:30:13 2010 From: mrmakent at cox.net (Mike Kent) Date: Wed, 4 Aug 2010 06:30:13 -0700 (PDT) Subject: newbie problem with str.replace References: Message-ID: <0ece6c99-1c8f-4055-9ed9-4f63b4ed4b2d@j8g2000yqd.googlegroups.com> On Aug 4, 9:10?am, BobAalsma wrote: > I'm working on a set of scripts and I can't get a replace to work in > the script - please help. > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) I'm not sure what you are intending to do here, but string.replace does not do its replacement in-place. It returns a copy of the original string, with the replacement done in the copy. You are not assigning the string returned by string.replace to anything, therefore, it is immediately thrown away. Secondly, and this is just a guess, but since you are doing the string.replace inside of an os.walk loop, you appear to be trying to do a filename change. I hope you realize that this will in no way change the name of the file *on disk*; it will only change it in memory. From vicente.soler at gmail.com Wed Aug 4 09:35:35 2010 From: vicente.soler at gmail.com (vsoler) Date: Wed, 4 Aug 2010 06:35:35 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) Message-ID: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> Hi all, I just installed python 3.1.2 where I used to have python 2.6.4. I'm working on Win7. The IDLE GUI works, but I get the following message when trying to open *.py files written for py 2.6 The Application cannot locate win32ui.pyd (or Python) (126) Should I change the PATH in Windows? Should I change the PYTHONPATH? I am a bit lost. Everything worked fine with 2.6. Moreover, when I try to open an old *.py file, I sometimes get a message saying that the file should be converted to UTF-8. What does this mean? I'm also trying to use the 2to3 converter, but I cannot see where the converted files are written to! Any help is highly appreciated. Vicente Soler From joncle at googlemail.com Wed Aug 4 09:36:34 2010 From: joncle at googlemail.com (Jon Clements) Date: Wed, 4 Aug 2010 06:36:34 -0700 (PDT) Subject: parsing a c project References: Message-ID: <74a5afa7-f4df-486b-9424-a3f680222026@q35g2000yqn.googlegroups.com> On 4 Aug, 12:33, Aitor Garcia wrote: > Hi, > > I need to know the memory locations of all variables in a C project including > variables allocated inside structs. Pray tell us why? > > What I want to do in to expand the structs into its basic elements (floats, > int16 and int8). > > In a ?header file (example.h) I have the following definitions. > > struct house{ > ? float area; > > ? int8 rooms; > ? int16 visits; > > }; > > struct car{ > ? float price; > ? int8 color; > > }; > > I have been able to extract from the project the name of every struct, the type of the struct and the beginning address of each struct. How have you done this? What compiler and debugger/profiler are you using? etc... The memory address is going to possibly change every time, unless you're talking static variables within an applications own address space (even then I'm not 100% sure -- I haven't had to touch C in 2 years, so I'd declare myself rusty). > > example_list=[] > example_list.append(['house1','struct house','000082d0') > example_list.append(['house2','struct house','00003000') > example_list.append(['car1','struct car','00004000') > > I need an output like this. > > house1_struct_house_area float 000082d0 > house1_struct_house_rooms int8 000082d4 > house1_struct_house_visits int16 000082d5 > house2_struct_house_area float 00003000 > house2_struct_house_rooms int8 00003004 > house2_struct_house_visits int16 00003005 > car1_struct_car_price float 00004000 > car1_struct_car_color int8 00004004 > > How can I efficiently do this in Python ? Well using the pyparsing library, it's extremely easy to parse the C grammar. But that's not what you're asking. > > I do not have very clear which element of Python should I use > to store the struct list or class > > I would be very grateful if someone could give me some pointers. An un-intended C pun :) ? If you let the list know the use-case, then we might stand a chance of giving you some reference (C++ pun?) Jon. From invalid at invalid.invalid Wed Aug 4 10:11:29 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 14:11:29 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Paul Rubin wrote: > Grant Edwards writes: >> The issue that would prevent its use where I work is the inability to >> hire anybody who knows Ada. ... >> That said, the last time I looked the Ada spec was only something like >> 100 pages long, so a case could be made that it won't take long to >> learn. > > Well, I don't know Ada (I've read about it but not written actual > code), so maybe I shouldn't be the one saying this, but geez, it's > another imperative, procedural language, like Algol or Pascal or even > C. Its type is much more serious than C's but shouldn't be a problem > for anyone who uses C++ or Java generics. I agree 100%. > It also has a real module system unlike more commonly used languages, > but 1) that part seems easy to understand; and 2) usually that's used > for multi-programmer projects, so as long as there's some reasonable > proportion of experienced users on the team, the inter-module > interfaces should be sensible and less experienced users can just > program to existing interfaces and/or get some help from others. > Ada's module system is much simpler than (say) ML's. > >> I don't know how long the C++ language spec is, but I'm betting it's >> closer to 1000 than 100. > > I don't know about an official spec. Stroustrup's "The C++ > programming language" is about 1000 pp, but it's a textbook, with > lots of examples, exercises, etc. I read through an earlier > (shorter) edition in a couple of evenings a long time ago and it all > made sense. It has some hairy aspects like the notorious template > metaprogramming, but most users simply won't get involved with that. > Python has its own obscure and confusing features if that matters. I couldn't get anybody to use Python either. :/ The problem has nothing to do with the relative merits of the languages. The problem is inertia. > I think I'm a reasonably good Python programmer but I've never > written a special metaclass and wouldn't really know how to. -- Grant Edwards grant.b.edwards Yow! I would like to at urinate in an OVULAR, gmail.com porcelain pool -- From invalid at invalid.invalid Wed Aug 4 10:14:07 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 14:14:07 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Paul Rubin wrote: > I'm not sure what the hiring issue is. I think anyone skilled in C++ > or Java can pick up Ada pretty easily. It's mostly a subset of C++ > with different surface syntax. In my experience, the hiring issue is "we're already behind schedule and short-handed, we don't have the time or resources to teach people a new language." -- Grant Edwards grant.b.edwards Yow! Did YOU find a at DIGITAL WATCH in YOUR box gmail.com of VELVEETA? From invalid at invalid.invalid Wed Aug 4 10:15:40 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 14:15:40 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Neil Hodgson wrote: > Grant Edwards: > >> That said, the last time I looked the Ada spec was only something like >> 100 pages long, so a case could be made that it won't take long to >> learn. I don't know how long the C++ language spec is, but I'm >> betting it's closer to 1000 than 100. > > The Ada 2012 Language Reference Manual is 860 pages and the Ada 2005 > LRM was 790 pages. The annotated versions are even longer > http://www.ada-auth.org/standards/ada12.html Wow. That's grown a lot over the years. I used to have a paper copy, (single-sided), and it was only about 1cm thick. Ok, I guess that was probably 20 years ago... -- Grant Edwards grant.b.edwards Yow! I wonder if I ought at to tell them about my gmail.com PREVIOUS LIFE as a COMPLETE STRANGER? From davea at ieee.org Wed Aug 4 11:30:40 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 04 Aug 2010 11:30:40 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: <4C5987A0.1090903@ieee.org> ????? wrote: >> On 3 ???, 21:00, Dave Angel wrote: >> > > >> A string is an object containing characters. A string literal is one of >> the ways you create such an object. When you create it that way, you >> need to make sure the compiler knows the correct encoding, by using the >> encoding: line at beginning of file. >> > > > mymessage = "????????" <==== string > mymessage = u"????????" <==== string literal? > > So, a string literal is one of the encodings i use to create a string > object? > > No, both lines take a string literal, create an object, and bind a name to that object. In the first case, the object is a string, and in the second it's a unicode-string. But the literal is the stuff after the equals sign in both these cases. Think about numbers for a moment. When you say salary = 4.1 you've got a numeric literal that's three characters long, and a name that's six characters long. When the interpreter encounters this line, it builds an object of type float, whose value approximates 4.1, according to the language rules. It then binds the name salary to this object. > Can the encodign of a python script file be in iso-8859-7 which means > the file contents is saved to the hdd as greek-iso but the part of > this variabel value mymessage ="????????" is saved as utf-8 ot the > opposite? > > A given file needs to have a single encoding, or you're in big trouble. So a script file is encoded by the text editor in a single encoding method, which is not saved to the file (except indirectly if you specify BOM). It's up to you to add a line to the beginning to tell Python how to decode the file. One decoding for one file. > have the file saved as utf-8 but one variuable value as greek > encoding? > > Variables are not saved to source (script) files. Literals are in the file. > Encodings still give me headaches. I try to understand them as > different ways to store data in a media. > > Tell me something. What encoding should i pick for my scripts knowing > that only contain english + greek chars?? > iso-8859-7 or utf-8 and why? > > Depends on how sure you are that your program will never need characters outside your greek character set. Remember Y2K? > Can i save the sting lets say "?????" in different encodings and still > print out correctly in browser? > > ascii =he standard english character set only, right? > > >> The web server wraps a few characters before and after your html stream, >> but it shouldn't touch the stream itself. >> > > So the pythoon compiler using the cgi module is the one that is > producing the html output that immediately after send to the web > server, right? > > > >>> For example if i say mymessage =????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the >>> 2nd its a utf-8 one? >>> >> No, the first is an 8 bit copy of whatever bytes your editor happened to >> save. >> > > But since mymessage =????????" is a string containing greek > characaters why the editor doesn't save it as such? > > Because the editor is editing text, not python objects. It's job is solely to represent all your keystrokes in some consistent manner so that they can be interpreted later by some other program, possibly a compiler. > It reminds me of varibles an valeus where if you say > > a = 5, a var becomes instantly an integer variable > while > a = 'hello' , become instantly a string variable > > > >> mymessage = u"????????" >> >> creates an object that is *not* encoded. >> > > Because it isn't saved by the editor yet? In what satet is this object > in before it gets encoded? > And it egts encoded the minute i tell the editor to save the file? > > You're confusing timeframes here. Notepad++ doesn't know Python, and it's long gone by the time the compiler deals with that line. In Notepad++, there are no python objects, encoded or not. >> Encoding is taking the unicode >> stream and representing it as a stream of bytes, which may or may have >> more bytes than the original has characters. >> > > > So this line mymessage = u"????????" what it does is tell the browser > thats when its time to save the whole file to save this string as > utf-8? > > No idea what you mean. The browser isn't saving anything; it doesn't even get involved till after the python code has completed. > If yes, then if were to save the above string as greek encoding how > was i suppose to right it? > > Also if u ise the 'coding line' in the beggining of the file is there > a need for using the u literal? > > If you don't use the u literal, then don't even try to use utf-8. You'll find that strings have the wrong lengths, and therefore subscripts and formatting will sometimes fail in strange ways. >> I personally haven't done any cookie code. If I were debugging this, I'd >> factor out the multiple parts of that if statement, and find out which >> one isn't true. From here I can't guess. >> > > I did what you say and foudn out that both of the if condition parts > were always false thast why the if code blck never got executed. > > And it is alwsy wrong because the cookie never gets set. > > So can you please tell me why this line > > cookie['visitor'] = 'nikos', time() + 60*60*24*365 ) #this cookie > will expire in an year > > never created a cookie? > > As I said, I've never coded with cookies. But to create a cookie, you have to communicate with a browser, and that takes lots more than just adding an item to a map. Further, your getenv() will normally give you the state of the environment at the time your program was launched, so I wouldn't expect it to change. If I had to guess how cookies are done in CGI, I'd say that you probably have to talk to the CGI server and terminate, and that afterwards there'd be a new launch of your code, from which you could check that environment variable to see the results of the cookie. DaveA From alex at moreati.org.uk Wed Aug 4 11:41:49 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Wed, 4 Aug 2010 08:41:49 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) References: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> Message-ID: <0c661f1a-2b71-473b-90f7-133ab195bbaf@g19g2000yqc.googlegroups.com> On Aug 4, 2:35?pm, vsoler wrote: > Hi all, > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > working on Win7. > > The IDLE GUI works, but I get the following message when trying to > open *.py files written for py 2.6 > > ? ? ? ? The Application cannot locate win32ui.pyd (or Python) (126) > win32ui is part of the PyWin32 package. Most likely you have a version of PyWin32 for Python 2.6 installed, you should uninstall that and install PyWin32 for Python 3.1. Downloads are at http://sourceforge.net/projects/pywin32/files/ You should do the same for any other third party packages that are installed. > Moreover, when I try to open an old *.py file, I sometimes get a > message saying that the file should be converted to UTF-8. What does > this mean? Those files contain non-ascii characters (e.g. ?, ?, ?). Non-ascii characters must be encoded when saved using and encoding. UTF-8 is one such encoding, and it was chosen as the default .py encoding for Python 3.x. Those files are probably in iso8859, cp432, or perhaps UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite text editor, or declare the encoding so Python 3 knows it. More info: http://www.joelonsoftware.com/articles/Unicode.html http://docs.python.org/howto/unicode > I'm also trying to use the 2to3 converter, but I cannot see where the > converted files are written to! I think 2to3 prints a diff of the file changes to the console. The -w command line option should modify files in place. From steveo at syslang.net Wed Aug 4 11:44:12 2010 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 04 Aug 2010 11:44:12 -0400 Subject: Get name of file from directory into variable In-Reply-To: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: <4C598ACC.6050509@syslang.net> On 08/03/10 06:21, quoth loial: > In a unix shell script I can do something like this to look in a > directory and get the name of a file or files into a variable : > > MYFILE=`ls /home/mydir/JOHN*.xml` > > > Can I do this in one line in python? > Sorry, but I just can't help myself. Yeah, it's one shell line, but why the extra process, setup of pipes, teardown, and all the rest when you can just say MYFILE=/home/mydir/JOHN*.xml After all, your way just starts a subshell which runs ls in a grandchild process and creates a pipe to read back what the subshell writes. All the subhell does is to run ls on what the shell globs. And without any options to the ls command, you're just as well off by using echo instead of ls. MYFILE=`echo /home/mydir/JOHN*.xml` Since echo is probably a builtin, you'd be creating a child but no grandchild. Other than that, the use of glob in python answers your question well (unless someone wants to write up how to do it in python by use of the subprocess module along with the glob module...) -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From aahz at pythoncraft.com Wed Aug 4 12:01:32 2010 From: aahz at pythoncraft.com (Aahz) Date: 4 Aug 2010 09:01:32 -0700 Subject: error: (113, 'Software caused connection abort')0 References: Message-ID: In article , sarah wrote: > > i face with this problem when i want to run this command on cygwin: > python httpd.py 8000 example-300-1k-rigid.py Make sure the webclient service is running. (May not have anything to do with your problem, but it's something I had a problem with recently.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From vicente.soler at gmail.com Wed Aug 4 12:19:01 2010 From: vicente.soler at gmail.com (vsoler) Date: Wed, 4 Aug 2010 09:19:01 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) References: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> <0c661f1a-2b71-473b-90f7-133ab195bbaf@g19g2000yqc.googlegroups.com> Message-ID: <2308f42f-a92d-49ea-819c-f12eba5c8c24@l14g2000yql.googlegroups.com> On Aug 4, 5:41?pm, Alex Willmer wrote: > On Aug 4, 2:35?pm, vsoler wrote: > > > Hi all, > > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > > working on Win7. > > > The IDLE GUI works, but I get the following message when trying to > > open *.py files written for py 2.6 > > > ? ? ? ? The Application cannot locate win32ui.pyd (or Python) (126) > > win32ui is part of the PyWin32 package. Most likely you have a version > of PyWin32 for Python 2.6 installed, you should uninstall that and > install PyWin32 for Python 3.1. Downloads are athttp://sourceforge.net/projects/pywin32/files/ > > You should do the same for any other third party packages that are > installed. > > > Moreover, when I try to open an old *.py file, I sometimes get a > > message saying that the file should be converted to UTF-8. What does > > this mean? > > Those files contain non-ascii characters (e.g. ?, ?, ?). Non-ascii > characters must be encoded when saved using and encoding. UTF-8 is one > such encoding, and it was chosen as the default .py encoding for > Python 3.x. Those files are probably in iso8859, cp432, or perhaps > UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite > text editor, or declare the encoding so Python 3 knows it. More info: > > http://www.joelonsoftware.com/articles/Unicode.htmlhttp://docs.python.org/howto/unicode > > > I'm also trying to use the 2to3 converter, but I cannot see where the > > converted files are written to! > > I think 2to3 prints a diff of the file changes to the console. The -w > command line option should modify files in place. Thank you Alex for your detailes reply. Before switching to Python 3.1.2 I removed all my Python 2.6 packages (python, pywin32, numpy, wxpython). However, the removal was not complete since some files could not be removed. Additionally, I still see my C:\python26 directory which is suposed not to exist any longer. If I go to the Control Panel, I cannot see any of the above suposedly removed programs as pending of removal, so I really do not know what more to do. I was even thinking of removing the C:\python26 directory with the Supr key, but I always heard that it is not a good idea, the Registry could become inconsistent. Additionally, I have not found in my Win7 system nay utility for fixing it, should it become corrupt. Perhaps my questions concern a bit more the Operating system (windows) than they do python, but since I am fond of python and I definitely would like to become somehow proficient at it, I would like to solve the problem that I have. I would not like to take a lot of your time, but, do you have any hints as to what I should do to 'tune' my PC? Thank you very much for your help. Vicente Soler From chare at labr.net Wed Aug 4 12:40:32 2010 From: chare at labr.net (Chris Hare) Date: Wed, 04 Aug 2010 11:40:32 -0500 Subject: problem adding a scrollbar to a text widget Message-ID: <4A9BB587-E1EF-4272-8E65-6511415CAEE5@labr.net> Here is my chunk of code. I can't figure out what I am doing wrong to put my scrollbar on the right hand side of the text box. from Tkinter import * def showLogFile(): top = Toplevel() f = Frame(top, bd=0, bg="Gray") top.title = "netcomm log file" f.grid() sc = Scrollbar(top) sc.grid() t = Text(f, yscrollcommand = sc.set) sc.config(command=t.yview) t.insert(END,"This is a line of text") t.config(height=20,width=80,bg="Gray") button = Button(f, text="Dismiss", command=top.destroy, highlightbackground="Red") t.grid() button.grid() showLogFile() mainloop() From eliben at gmail.com Wed Aug 4 12:40:37 2010 From: eliben at gmail.com (Eli Bendersky) Date: Wed, 4 Aug 2010 19:40:37 +0300 Subject: parsing a c project In-Reply-To: <410079.5090.qm@web51608.mail.re2.yahoo.com> References: <410079.5090.qm@web51608.mail.re2.yahoo.com> Message-ID: On Wed, Aug 4, 2010 at 14:33, Aitor Garcia wrote: > Hi, > > I need to know the memory locations of all variables in a C project > including > variables allocated inside structs. > Aitor, try the pycparser project (http://code.google.com/p/pycparser/) - it's a complete ISO C parser in pure Python. It has been used for tasks similar to this one (parsing of struct/union declarations for various purposes). Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.post Wed Aug 4 13:13:59 2010 From: no.email at please.post (kj) Date: Wed, 4 Aug 2010 17:13:59 +0000 (UTC) Subject: XML parsing: SAX/expat & yield Message-ID: I want to write code that parses a file that is far bigger than the amount of memory I can count on. Therefore, I want to stay as far away as possible from anything that produces a memory-resident DOM tree. The top-level structure of this xml is very simple: it's just a very long list of "records". All the complexity of the data is at the level of the individual records, but these records are tiny in size (relative to the size of the entire file). So the ideal would be a "parser-iterator", which parses just enough of the file to "yield" (in the generator sense) the next record, thereby returning control to the caller; the caller can process the record, delete it from memory, and return control to the parser-iterator; once parser-iterator regains control, it repeats this sequence starting where it left off. The problem, as I see it, is that SAX-type parsers like expat want to do everything with callbacks, which is not readily compatible with the generator paradigm I just described. Is there a way to get an xml.parsers.expat parser (or any other SAX-type parser) to stop at a particular point to yield a value? The only approach I can think of is to have the appropriate parser callbacks throw an exception wherever a yield would have been. The exception-handling code would have the actual yield statement, followed by code that restarts the parser where it left off. Additional logic would be necessary to implement the piecemeal reading of the input file into memory. But I'm not very conversant with SAX parsers, and even less with generators, so all this may be unnecessary, or way off. Any other tricks/suggestions for turning a SAX parsers into a generator, please let me know. ~K From __peter__ at web.de Wed Aug 4 13:22:54 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Aug 2010 19:22:54 +0200 Subject: XML parsing: SAX/expat & yield References: Message-ID: kj wrote: > I want to write code that parses a file that is far bigger than > the amount of memory I can count on. Therefore, I want to stay as > far away as possible from anything that produces a memory-resident > DOM tree. > > The top-level structure of this xml is very simple: it's just a > very long list of "records". All the complexity of the data is at > the level of the individual records, but these records are tiny in > size (relative to the size of the entire file). > > So the ideal would be a "parser-iterator", which parses just enough > of the file to "yield" (in the generator sense) the next record, > thereby returning control to the caller; the caller can process > the record, delete it from memory, and return control to the > parser-iterator; once parser-iterator regains control, it repeats > this sequence starting where it left off. How about http://effbot.org/zone/element-iterparse.htm#incremental-parsing Peter From alex at moreati.org.uk Wed Aug 4 13:52:22 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Wed, 4 Aug 2010 10:52:22 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) References: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> <0c661f1a-2b71-473b-90f7-133ab195bbaf@g19g2000yqc.googlegroups.com> <2308f42f-a92d-49ea-819c-f12eba5c8c24@l14g2000yql.googlegroups.com> Message-ID: <1075909d-a727-4145-90ca-4b5444144816@k19g2000yqc.googlegroups.com> On Aug 4, 5:19?pm, vsoler wrote: > On Aug 4, 5:41?pm, Alex Willmer wrote: > > > > > > > On Aug 4, 2:35?pm, vsoler wrote: > > > > Hi all, > > > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > > > working on Win7. > > > > The IDLE GUI works, but I get the following message when trying to > > > open *.py files written for py 2.6 > > > > ? ? ? ? The Application cannot locate win32ui.pyd (or Python) (126) > > > win32ui is part of the PyWin32 package. Most likely you have a version > > of PyWin32 for Python 2.6 installed, you should uninstall that and > > install PyWin32 for Python 3.1. Downloads are athttp://sourceforge.net/projects/pywin32/files/ > > > You should do the same for any other third party packages that are > > installed. > > > > Moreover, when I try to open an old *.py file, I sometimes get a > > > message saying that the file should be converted to UTF-8. What does > > > this mean? > > > Those files contain non-ascii characters (e.g. ?, ?, ?). Non-ascii > > characters must be encoded when saved using and encoding. UTF-8 is one > > such encoding, and it was chosen as the default .py encoding for > > Python 3.x. Those files are probably in iso8859, cp432, or perhaps > > UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite > > text editor, or declare the encoding so Python 3 knows it. More info: > > >http://www.joelonsoftware.com/articles/Unicode.htmlhttp://docs.python... > > > > I'm also trying to use the 2to3 converter, but I cannot see where the > > > converted files are written to! > > > I think 2to3 prints a diff of the file changes to the console. The -w > > command line option should modify files in place. > > Thank you Alex for your detailes reply. > > Before switching to Python 3.1.2 I removed all my Python 2.6 packages > (python, pywin32, numpy, wxpython). However, the removal was not > complete since some files could not be removed. Additionally, I still > see my C:\python26 directory which is suposed not to exist any longer. It probably contains one or two files the installers weren't aware of. E.g. a module you added manually, a log, a .pyc > I would not like to take a lot of your time, but, do you have any > hints as to what I should do to 'tune' my PC? Take a backup then either delete the Python26 directory, or rename it. Any problems, reverse the process. From dotancohen at gmail.com Wed Aug 4 14:09:35 2010 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 4 Aug 2010 21:09:35 +0300 Subject: Trying to set a cookie within a python script In-Reply-To: <4C5987A0.1090903@ieee.org> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> <4C5987A0.1090903@ieee.org> Message-ID: On Wed, Aug 4, 2010 at 18:30, Dave Angel wrote: > Depends on how sure you are that your program will never need characters > outside your greek character set. Remember Y2K? > Don't forget that the Euro symbol is outside the Greek character set. -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From donn.ingle at gmail.com Wed Aug 4 14:22:14 2010 From: donn.ingle at gmail.com (donn) Date: Wed, 04 Aug 2010 20:22:14 +0200 Subject: Trying to set a cookie within a python script In-Reply-To: References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> <4C5987A0.1090903@ieee.org> Message-ID: <4C59AFD6.4020206@gmail.com> On 04/08/2010 20:09, Dotan Cohen wrote: > Don't forget that the Euro symbol is outside the Greek character set. I could make some kind of economic joke here, but I'm also broke :D \d From steve.ferg.bitbucket at gmail.com Wed Aug 4 14:28:48 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Wed, 4 Aug 2010 11:28:48 -0700 (PDT) Subject: python terminology on classes References: Message-ID: <8e60e2db-205d-4b8b-9c19-1d46e2318cb8@h20g2000vbs.googlegroups.com> > Seriously, we can't keep doing your thinking for you. ?The answers > to all your questions are section 9 of the tutorial. This is is just the kind of newbie-hostile smart-ass reply that we do not want to see on comp.lang.python. Let's try again: I think that the answers to all your questions are section 9 of the tutorial. http://docs.python.org/py3k/tutorial/index.html Why don't you take a look at it, and then come back again if you still have questions. From vicente.soler at gmail.com Wed Aug 4 14:50:08 2010 From: vicente.soler at gmail.com (vsoler) Date: Wed, 4 Aug 2010 11:50:08 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) References: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> <0c661f1a-2b71-473b-90f7-133ab195bbaf@g19g2000yqc.googlegroups.com> <2308f42f-a92d-49ea-819c-f12eba5c8c24@l14g2000yql.googlegroups.com> <1075909d-a727-4145-90ca-4b5444144816@k19g2000yqc.googlegroups.com> Message-ID: <27fc4dce-238f-4498-a5c4-a9a6514ee4c0@y11g2000yqm.googlegroups.com> On Aug 4, 7:52?pm, Alex Willmer wrote: > On Aug 4, 5:19?pm, vsoler wrote: > > > > > On Aug 4, 5:41?pm, Alex Willmer wrote: > > > > On Aug 4, 2:35?pm, vsoler wrote: > > > > > Hi all, > > > > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > > > > working on Win7. > > > > > The IDLE GUI works, but I get the following message when trying to > > > > open *.py files written for py 2.6 > > > > > ? ? ? ? The Application cannot locate win32ui.pyd (or Python) (126) > > > > win32ui is part of the PyWin32 package. Most likely you have a version > > > of PyWin32 for Python 2.6 installed, you should uninstall that and > > > install PyWin32 for Python 3.1. Downloads are athttp://sourceforge.net/projects/pywin32/files/ > > > > You should do the same for any other third party packages that are > > > installed. > > > > > Moreover, when I try to open an old *.py file, I sometimes get a > > > > message saying that the file should be converted to UTF-8. What does > > > > this mean? > > > > Those files contain non-ascii characters (e.g. ?, ?, ?). Non-ascii > > > characters must be encoded when saved using and encoding. UTF-8 is one > > > such encoding, and it was chosen as the default .py encoding for > > > Python 3.x. Those files are probably in iso8859, cp432, or perhaps > > > UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite > > > text editor, or declare the encoding so Python 3 knows it. More info: > > > >http://www.joelonsoftware.com/articles/Unicode.htmlhttp://docs.python... > > > > > I'm also trying to use the 2to3 converter, but I cannot see where the > > > > converted files are written to! > > > > I think 2to3 prints a diff of the file changes to the console. The -w > > > command line option should modify files in place. > > > Thank you Alex for your detailes reply. > > > Before switching to Python 3.1.2 I removed all my Python 2.6 packages > > (python, pywin32, numpy, wxpython). However, the removal was not > > complete since some files could not be removed. Additionally, I still > > see my C:\python26 directory which is suposed not to exist any longer. > > It probably contains one or two files the installers weren't aware of. > E.g. a module you added manually, a log, a .pyc > > > I would not like to take a lot of your time, but, do you have any > > hints as to what I should do to 'tune' my PC? > > Take a backup then either delete the Python26 directory, or rename it. > Any problems, reverse the process. Thank you very much Alex From chare at labr.net Wed Aug 4 15:44:13 2010 From: chare at labr.net (Chris Hare) Date: Wed, 04 Aug 2010 14:44:13 -0500 Subject: running a piece of code at specific intervals? Message-ID: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> Don't say cron : I want to have a section of my code executed at 15 minute intervals. I am using Threading.timer, but it is causing a problem sinxe I am using sqlite3 and the thread support gives me an error, which aborts part of my code. So, is there an alternative to threading.timer? From ericjvandervelden at gmail.com Wed Aug 4 15:58:18 2010 From: ericjvandervelden at gmail.com (Eric J. Van der Velden) Date: Wed, 4 Aug 2010 12:58:18 -0700 (PDT) Subject: __init__ as a lambda Message-ID: Hello, Suppose class C: def __init__(self,name):self.name=name I was wondering if I could make the __init__ a lambda function, but class C: __init__=lambda self,self.name:None and then later, C('Hello') does not work; the first argument, self, is assigned all rigth, but you cannot write the second argument with a dot, self.name . Or can I somehow? Thanks, Eric J. From davea at ieee.org Wed Aug 4 16:07:41 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 04 Aug 2010 16:07:41 -0400 Subject: running a piece of code at specific intervals? In-Reply-To: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> References: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> Message-ID: <4C59C88D.5090707@ieee.org> Chris Hare wrote: > Don't say cron : > > I want to have a section of my code executed at 15 minute intervals. I am using Threading.timer, but it is causing a problem sinxe I am using sqlite3 and the thread support gives me an error, which aborts part of my code. > > So, is there an alternative to threading.timer? > > Depends on how that "section of code" relates to the rest of your code. If it's independent of the rest, then you can use subprocess to launch a separate process. That won't interfere with your main code. But of course if your main code is blocked for 20 minutes, it'll never get to the part which should run the subprocess. If your main code is running wxPython, you can set a timer, and just trigger an event like all the others. But without knowing more about your two pieces of code, the only reliable answer is 'cron'. DaveA From jyoung79 at kc.rr.com Wed Aug 4 16:08:20 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Wed, 4 Aug 2010 20:08:20 +0000 Subject: BundleBuilder Question Message-ID: <20100804200820.1IR1H.80013.root@cdptpa-web19-z02> I stumbled upon an article about bundlebuilder, so I was testing it a little. At first it wouldn't work and had this in the error: IOError: [Errno 2] No such file or directory: '/System/Library/Frameworks/Python.framework/Versions/2.6/Resources/English.lproj' I'm currently running OS X 10.6 with python2.6 as the default (looks to be 64 bit). I followed that path and found that the 'English.lproj' directory was not there. I admit I'm not sure what I'm doing, but I went to a 10.5 Leopard machine and found that Python2.5 had this 'English.lproj' directory so I copied it over to my Python2.6 on OS 10.6. Bundlebuilder then successfully created a standalone app. I'm just wondering if it's a good idea to copy that English.lproj directory from Python2.5 to Python2.6? What exactly is this directory for? Looks like it only contains a "InfoPlist.strings" file. Thanks. Jay From jhjaggars at gmail.com Wed Aug 4 16:10:47 2010 From: jhjaggars at gmail.com (Jesse Jaggars) Date: Wed, 4 Aug 2010 15:10:47 -0500 Subject: running a piece of code at specific intervals? In-Reply-To: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> References: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> Message-ID: On Wed, Aug 4, 2010 at 2:44 PM, Chris Hare wrote: > Don't say cron : > > I want to have a section of my code executed at 15 minute intervals. ?I am using Threading.timer, but it is causing a problem sinxe I am using sqlite3 and the thread support gives me an error, which aborts part of my code. > > So, is there an alternative to threading.timer? > > > -- > http://mail.python.org/mailman/listinfo/python-list > Take a look at sched. http://docs.python.org/library/sched.html From jfine at pytex.org Wed Aug 4 16:15:33 2010 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 04 Aug 2010 21:15:33 +0100 Subject: A new syntax for writing tests Message-ID: Hi I just discovered today a new syntax for writing tests. The basic idea is to write a function that contains some statements, and run it via a decorator. I wonder if anyone had seen this pattern before, and how you feel about it. For myself, I quite like it. Let's suppose we want to test this trivial (of course) class. class Adder(object): def __init__(self): self.value = 0 def plus(self, delta): self.value += delta The test the class you need a runner. In this case it is quite simple. def runner(script, expect): '''Create an adder, run script, expect value.''' adder = Adder() script(adder) return adder.value We can now create (and run if we wish) a test. To do this we write @testit(runner, 4) def whatever(a): '''Two plus two is four.''' a.plus(2) a.plus(2) Depending on the exact value of the testit decorator (which in the end is up to you) we can store the test, or execute it immediately, or do something else. The simplest implementation prints: OK: Two plus two is four. for this passing test, and Fail: Two plus four is five. expect 5 actual 6 for a test that fails. Here is the testit decorator used to produce the above output: def testit(runner, expect): '''Test statements decorator.''' def next(script): actual = runner(script, expect) if actual == expect: print 'OK:', script.__doc__ else: print 'Fail:', script.__doc__ print ' expect', expect print ' actual', actual return next You can pick this code, for at least the next 30 days, at http://dpaste.com/hold/225056/ For me the key benefit is that writing the test is really easy. Here's a test I wrote earlier today. @testit(runner, '''''') def whatever(tb): tb.start('a', {'att': 'value'}) tb.start('b') tb.end('b') tb.end('a') If the test has a set-up and tear-down, this can be handled in the runner, as can the test script raising an expected or unexpected exception. -- Jonathan From thomas at jollans.com Wed Aug 4 16:17:28 2010 From: thomas at jollans.com (Thomas Jollans) Date: Wed, 04 Aug 2010 22:17:28 +0200 Subject: None is negative? In-Reply-To: References: Message-ID: <4C59CAD8.20904@jollans.com> On 08/03/2010 10:17 PM, wheres pythonmonks wrote: > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? (v2.6) > > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > >>>> if None < -9999999.99: print "hi" > > hi >>>> > >>>> if -9999999 > None: print "hi" > > hi >>>> > > Is there a way to have the comparison raise an exception? > > W Not only was it negative, it was, in fact: >>> None < float('-Inf') True From nad at acm.org Wed Aug 4 16:34:50 2010 From: nad at acm.org (Ned Deily) Date: Wed, 04 Aug 2010 13:34:50 -0700 Subject: BundleBuilder Question References: <20100804200820.1IR1H.80013.root@cdptpa-web19-z02> Message-ID: In article <20100804200820.1IR1H.80013.root at cdptpa-web19-z02>, wrote: > I stumbled upon an article about bundlebuilder, so I was testing it a little. > At first it wouldn't work and had this in the error: > > IOError: [Errno 2] No such file or directory: > '/System/Library/Frameworks/Python.framework/Versions/2.6/Resources/English.lp > roj' > [...] This was a bug that has been fixed in subsequent maintenance releases of Python 2.6. See http://bugs.python.org/issue4937 -- Ned Deily, nad at acm.org From sschwarzer at sschwarzer.net Wed Aug 4 16:41:42 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 04 Aug 2010 22:41:42 +0200 Subject: [ANN] Websourcebrowser 0.4a released Message-ID: Hello, I'm happy to announce the release of Websourcebrowser 0.4a. Websourcebrowser is a program intended to get a quick overview of a project's source code. The program is controlled from a web browser which displays a directory tree and a source code file side by side. The homepage of the project is at http://websourcebrowser.sschwarzer.net/ The download of version 0.4a is at http://websourcebrowser.sschwarzer.net/download *** Note that this is still an alpha release. *** I use the program regularly to dive into new projects, but I consider it in the alpha stage because it has been used and tested by only a few other people than me. On Windows, this version doesn't seem to work with IE 8.0 whereas it works with Firefox 3.6.8. I know the software could be improved a lot. For some ideas, look at http://websourcebrowser.sschwarzer.net/trac/wiki/Ideas http://websourcebrowser.sschwarzer.net/trac/browser/todo.txt If I implement this alone, it'll probably take years, given that Websourcebrowser is a spare time project (beside my other project, ftputil). So it would be great to get more developers on board. Of course, I'm thankful for feedback on the mailing list (subscription required to avoid spam, sorry), http://codespeak.net/mailman/listinfo/websourcebrowser or via private e-mail. If you encounter problems, you may also file a bug report at http://websourcebrowser.sschwarzer.net/trac/newticket *** You need to log in as user wsbuser with password wsb . *** Stefan From no.email at please.post Wed Aug 4 17:49:53 2010 From: no.email at please.post (kj) Date: Wed, 4 Aug 2010 21:49:53 +0000 (UTC) Subject: XML parsing: SAX/expat & yield References: Message-ID: In Peter Otten <__peter__ at web.de> writes: >How about >http://effbot.org/zone/element-iterparse.htm#incremental-parsing Exactly! Thanks! ~K From christopherbl at gmail.com Wed Aug 4 18:08:11 2010 From: christopherbl at gmail.com (Christopher Barrington-Leigh) Date: Wed, 4 Aug 2010 15:08:11 -0700 (PDT) Subject: scipy / stats : quantiles using sample weights from survey data Message-ID: <94bb6313-1b09-4eeb-9969-07d76048a361@m35g2000prn.googlegroups.com> There is a function scipy.stats.mstats.mquantiles that returns quantiles for a vector of data. But my data should not be uniformly weighted in an estimate of the distribution, since they are from a survey and come with estimated sampling weights based on the stratification used in sampling. Is there a routine to calculate these quantiles taking into account the survey weights? I can find nothing, so maybe you have had the same problem and written something. Thanks! From no.email at please.post Wed Aug 4 18:15:04 2010 From: no.email at please.post (kj) Date: Wed, 4 Aug 2010 22:15:04 +0000 (UTC) Subject: how to pretty-print Python dict with unicode? Message-ID: Is there a simple way to get Python to pretty-print a dict whose values contain Unicode? (Of course, the goal here is that these printed values are human-readable.) If I run the following simple script: from pprint import pprint x = u'\u6c17\u304c\u9055\u3046' print '{%s: %s}' % (u'x', x) print {u'x': x} pprint({u'x': x}) The first print statement produces perfectly readable Japanese, but the remaining statements both produce the line {u'x': u'\u6c17\u304c\u9055\u3046'} I've tried everything I can think of (including a lot of crazy stuff) short of re-writing pprint from scratch (which I think would be faster than grokking it and hacking at it). Isn't there an easier way to do this? Thanks! ~K From aahz at pythoncraft.com Wed Aug 4 18:20:32 2010 From: aahz at pythoncraft.com (Aahz) Date: 4 Aug 2010 15:20:32 -0700 Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c4c4e6f$0$11094$c3e8da3@news.astraweb.com> Message-ID: In article , Nobody wrote: > >Java's checked exception mechanism was based on real-world experience of >the pitfalls of abstract types. And that experience was gained in >environments where interface specifications were far more detailed than is >the norm in the Python world. There are a number of people who claim that checked exceptions are the wrong answer: http://www.mindview.net/Etc/Discussions/CheckedExceptions -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From barry at python.org Wed Aug 4 18:27:44 2010 From: barry at python.org (Barry Warsaw) Date: Wed, 4 Aug 2010 18:27:44 -0400 Subject: Python 2.6.6 release candidate 1 now available Message-ID: <20100804182744.4a473a38@heresy> Hello fellow Pythoneers and Pythonistas, The source tarballs and Windows installers for the first (and hopefully only) Python 2.6.6 release candidate is now available: http://www.python.org/download/releases/2.6.6/ As usual, we would love it if you could download, install, and test these with your favorite projects and environments. A truly impressive number of bug have been fixed since Python 2.6.5, with the full NEWS file available here: http://www.python.org/download/releases/2.6.6/NEWS.txt Barring complications, we expect to release Python 2.6.6 final on August 16, 2010. Please note that with the release of Python 2.7 final on July 3, 2010, and in accordance with Python policy, Python 2.6.6 is the last scheduled bug fix maintenance release of the 2.6 series. Because of this, your testing of this release candidate will help immensely. We will of course continue to support security fixes in Python 2.6 for quite some time. My thanks go out to everyone who has helped contribute fixes great and small, and much testing and bug tracker gardening for Python 2.6.6. The excellent folks on #python-dev are true Pythonic heros too. Enjoy, -Barry (on behalf of the Python development community) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: not available URL: From rhodri at wildebst.demon.co.uk Wed Aug 4 18:33:17 2010 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Wed, 04 Aug 2010 23:33:17 +0100 Subject: python terminology on classes References: <8e60e2db-205d-4b8b-9c19-1d46e2318cb8@h20g2000vbs.googlegroups.com> Message-ID: On Wed, 04 Aug 2010 19:28:48 +0100, Steve Ferg wrote: >> Seriously, we can't keep doing your thinking for you. The answers >> to all your questions are section 9 of the tutorial. > > This is is just the kind of newbie-hostile smart-ass reply that we do > not want to see on comp.lang.python. > > Let's try again: > > I think that the answers to all your questions are section 9 of the > tutorial. > http://docs.python.org/py3k/tutorial/index.html > > Why don't you take a look at it, and then come back again if you still > have questions. With Peng Yu, we've been through that quite a lot. It seemed time to be a little sharper in the hope that learning might emerge. -- Rhodri James *-* Wildebeest Herder to the Masses From sschwarzer at sschwarzer.net Wed Aug 4 18:36:46 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 05 Aug 2010 00:36:46 +0200 Subject: __init__ as a lambda In-Reply-To: References: Message-ID: <4C59EB7E.30905@sschwarzer.net> Hi Eric, On 2010-08-04 21:58, Eric J. Van der Velden wrote: > class C: > def __init__(self,name):self.name=name > > I was wondering if I could make the __init__ a lambda function, but > > class C: > __init__=lambda self,self.name:None > > and then later, > > C('Hello') > > does not work; the first argument, self, is assigned all rigth, but > you cannot write the second argument with a dot, self.name . The "problem" is that in a lambda function the part after the colon has to be an expression. However, you have used an assignment there which isn't an expression in Python but a statement. For example, you can use f = lambda x: sys.stdout.write(str(x)) (sys.stdout.write(str(x)) is an expression) but not f = lambda x: print x (print x is a statement in Python versions < 3) Stefan From ldo at geek-central.gen.new_zealand Wed Aug 4 18:44:10 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 10:44:10 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: In message , Grant Edwards wrote: > In my experience, the hiring issue is "we're already behind schedule > and short-handed, we don't have the time or resources to teach people > a new language." Most people seem to need tutorials or handholding of some sort. Look at the number of questions in this group which could be answered just by reading the reference manual. From ldo at geek-central.gen.new_zealand Wed Aug 4 18:45:30 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 10:45:30 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In message , Grant Edwards wrote: > The problem has nothing to do with the relative merits of the > languages. The problem is inertia. So how was C++ able to get popular in the first place? And how was Java able to grab some share from it? From ldo at geek-central.gen.new_zealand Wed Aug 4 18:47:10 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 10:47:10 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , David Robinow wrote: > As an admittedly stupid comparison, I have 1579 DLLs in my > \windows\system32 directory. > Some number of these have been upgraded by Windows Update. What about the ones that aren?t? How do you maintain those? From ldo at geek-central.gen.new_zealand Wed Aug 4 18:50:03 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 10:50:03 +1200 Subject: Package management (was: Why is there no platform independent way of clearing a terminal?) References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <87aap44mc7.fsf_-_@benfinney.id.au> Message-ID: In message <87aap44mc7.fsf_-_ at benfinney.id.au>, Ben Finney wrote: > Sadly, Python's package management is rather lacking by these standards. > The Distutils legacy assumption of ?package recipient, system > administrator, and end user are all the same person?, among other design > decisions, makes it unusually difficult to have the necessary separation > of concerns between OS packaging, system administration, and end user. Doesn?t matter. I?m pretty sure Debian has a way of automatically turning a distutils build into a .deb package with all the right dependencies. :) From ben+python at benfinney.id.au Wed Aug 4 19:00:08 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 05 Aug 2010 09:00:08 +1000 Subject: Questions, newbies, and community (was: python terminology on classes) References: <8e60e2db-205d-4b8b-9c19-1d46e2318cb8@h20g2000vbs.googlegroups.com> Message-ID: <87tyna2dc7.fsf_-_@benfinney.id.au> "Rhodri James" writes: > On Wed, 04 Aug 2010 19:28:48 +0100, Steve Ferg > wrote: > > >> Seriously, we can't keep doing your thinking for you. The answers > >> to all your questions are section 9 of the tutorial. > > > > This is is just the kind of newbie-hostile smart-ass reply that we do > > not want to see on comp.lang.python. [?] > With Peng Yu, we've been through that quite a lot. It seemed time to > be a little sharper in the hope that learning might emerge. As someone who generally deplores sharp replies to newbies for the negative effect on the community as a whole and on later newcomers in particular: I have to agree with Rhodri here. This specific case has reached a point where some sharpness is warranted, in my opinion. Peng Yu, please take Rhodri's reply in a spirit of mentoring. You have all the tools at your disposal and they have been pointed out to you numerous times. When asking a question of others, please demonstrate that you have exhausted the existing resources you clearly know you have available to you. -- \ ?What we usually pray to God is not that His will be done, but | `\ that He approve ours.? ?Helga Bergold Gross | _o__) | Ben Finney From no.email at nospam.invalid Wed Aug 4 19:02:46 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 04 Aug 2010 16:02:46 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: <7xocdi56cp.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > > The Ada 2012 Language Reference Manual is 860 pages ... > Yeah, unfortunately the language was designed by a committee ... > It seems apt to describe the resulting design as ?bulletproof?, but > ?elegant? or ?concise? ... not so much. I'd say the Ada standardizers went to a great deal of trouble to specify and document stuff that other languages simply leave undefined, leaving developers relying on implementation-specific behavior that's not part of the standard. Ada itself is not necessarily more complicated. From pavlovevidence at gmail.com Wed Aug 4 19:03:11 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Aug 2010 16:03:11 -0700 (PDT) Subject: __init__ as a lambda References: Message-ID: <512aefcc-dea0-41ad-bc08-e9594b545870@y11g2000yqm.googlegroups.com> On Aug 4, 12:58?pm, "Eric J. Van der Velden" wrote: > Hello, > > Suppose > > class C: > ?def __init__(self,name):self.name=name > > I was wondering if I could make the __init__ a lambda function, but > > class C: > ?__init__=lambda self,self.name:None > > and then later, > > C('Hello') > > does not work; the first argument, self, is assigned all rigth, but > you cannot write the second argument with a dot, ?self.name . > Or can I somehow? __init__=lambda self,name:setattr(self,'name',name) However if you actually do this, you need to be smacked upside the head. Carl Banks From invalid at invalid.invalid Wed Aug 4 19:04:50 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 23:04:50 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> The problem has nothing to do with the relative merits of the >> languages. The problem is inertia. > > So how was C++ able to get popular in the first place? Building on C's popularity helped. > And how was Java able to grab some share from it? Good question. Both IBM and Sun put a lot of effort/money behind Java. -- Grant From chare at labr.net Wed Aug 4 19:22:03 2010 From: chare at labr.net (Chris Hare) Date: Wed, 04 Aug 2010 18:22:03 -0500 Subject: adding optionMenu items in code Message-ID: <346DD2AA-04A4-49B6-94DD-31B6DEFCB3A0@labr.net> I have an option menu self.w = OptionMenu(self.frameNewNet, self.variable, "one", "two", "three") Is there a way to add items to this programmatically, i.e. using values from a database? From no.email at nospam.invalid Wed Aug 4 19:23:52 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 04 Aug 2010 16:23:52 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: <7xk4o655dj.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > So how was C++ able to get popular in the first place? And how was > Java able to grab some share from it? C++ made improvements over C that were necessary and welcome for controlling the complexity of large programs, while remaining mostly upward compatible with C. Java abandoned C compatibility and added memory safety and GC. That got rid of legacy-related pain and improved program reliability and eased debugging considerably, at some cost in performance. Java was also on the OO bandwagon of the 1990's, which translated into good marketing back then, but is part of the cause of the massive bureaucracy and bloat in the Java runtime environment. C++ seems to have made something of a comeback because of this, and Java now has generics patterned after C++'s. From benjamin.kaplan at case.edu Wed Aug 4 19:24:29 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 4 Aug 2010 16:24:29 -0700 Subject: how to pretty-print Python dict with unicode? In-Reply-To: References: Message-ID: On Wed, Aug 4, 2010 at 3:15 PM, kj wrote: > > > > Is there a simple way to get Python to pretty-print a dict whose > values contain Unicode? ?(Of course, the goal here is that these > printed values are human-readable.) > > If I run the following simple script: > > from pprint import pprint > x = u'\u6c17\u304c\u9055\u3046' > print '{%s: %s}' % (u'x', x) > print {u'x': x} > pprint({u'x': x}) > > The first print statement produces perfectly readable Japaneuse, > but the remaining statements both produce the line > > {u'x': u'\u6c17\u304c\u9055\u3046'} > > I've tried everything I can think of (including a lot of crazy > stuff) short of re-writing pprint from scratch (which I think would > be faster than grokking it and hacking at it). > > Isn't there an easier way to do this? > > Thanks! > > ~K use Python 3? http://www.python.org/dev/peps/pep-3138/ Or just iterate over the items and print them out yourself. The reason you see the escaped values is that str(dict()) calls repr on all the items. If you convert them to strings using str instead of repr(), it will work the way you want. From vlastimil.brom at gmail.com Wed Aug 4 19:28:01 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 5 Aug 2010 01:28:01 +0200 Subject: how to pretty-print Python dict with unicode? In-Reply-To: References: Message-ID: 2010/8/5 kj : > > Is there a simple way to get Python to pretty-print a dict whose > values contain Unicode? (Of course, the goal here is that these > printed values are human-readable.) > > If I run the following simple script: > > from pprint import pprint > x = u'\u6c17\u304c\u9055\u3046' > print '{%s: %s}' % (u'x', x) > print {u'x': x} > pprint({u'x': x}) > > The first print statement produces perfectly readable Japanese, > but the remaining statements both produce the line > > {u'x': u'\u6c17\u304c\u9055\u3046'} > > I've tried everything I can think of (including a lot of crazy > stuff) short of re-writing pprint from scratch (which I think would > be faster than grokking it and hacking at it). > > Isn't there an easier way to do this? > > Thanks! > > ~K > -- > http://mail.python.org/mailman/listinfo/python-list > I am not sure it helps, others will probably offer more elegant suggestions, but if the dict is one-dimensional (i.e. it doesn't contain any other containers or mappings - dicts, lists etc., but only strings, numbers, you can use a simple print with a string conversion in a loop or join the dict to a single printable string. Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> d = {1: u'\u6c17\u304c\u9055\u3046', 2: u'\u6c17\u304c\u9055\u3046', 3: u'\u6c17\u304c\u9055\u3046', } >>> for k, v in d.items(): print "%s: %s" % (k, v) 1: ???? 2: ???? 3: ???? >>> for k, v in d.items(): print "%s: %s," % (k, v), 1: ????, 2: ????, 3: ????, >>> >>> print "".join("%s: %s, " % (k, v) for k, v in d.iteritems()) 1: ????, 2: ????, 3: ????, >>> Or you can use python 3, where repr() behaves directly like you would need (also for arbitrarily nested data structers, unlike the simple approach above): Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> d = {1: '\u6c17\u304c\u9055\u3046', 2: '\u6c17\u304c\u9055\u3046', 3: '\u6c17\u304c\u9055\u3046', } >>> d {1: '????', 2: '????', 3: '????'} >>> (It might be possible to replace the sys.stdout to use str() as needed on python 2.x too, but I am not sure if it would be worth it.) vbr From nagle at animats.com Wed Aug 4 19:28:29 2010 From: nagle at animats.com (John Nagle) Date: Wed, 04 Aug 2010 16:28:29 -0700 Subject: __init__ as a lambda In-Reply-To: References: Message-ID: <4c59f79f$0$1590$742ec2ed@news.sonic.net> On 8/4/2010 12:58 PM, Eric J. Van der Velden wrote: > Hello, > > Suppose > > class C: > def __init__(self,name):self.name=name > > I was wondering if I could make the __init__ a lambda Python is not a functional language. Attempts to make it one make it worse. There's this mindset that loops are somehow "bad". This leads to list comprehensions, multiline lambdas, more elaborate generators, weird conditional expression syntax, and related cruft. Most of these features are of marginal, if not negative, value. Unfortunately, some of them have gone into Python. John Nagle From nikos.the.gr33k at gmail.com Wed Aug 4 19:40:45 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Wed, 4 Aug 2010 16:40:45 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format Message-ID: Okey, i have many hours now struggling to convert a mysql datetime field that i retreive to a string of this format '%d %b, %H:%M' I google a lot but couldnt found out how to format it being a string Here si the code so far: try: cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) except MySQLdb.Error: print( "Error %d: %s" % (e.args[0], e.args[1]) ) else: #display results print ( '''

( ?????????? ) ----- ( ?????????? ) ----- ( ?????????? )


''' ) print ( '''''' ) results = cursor.fetchall() for row in results: print ( ''' ''' ) for entry in row: entry = datetime.datetime.strftime( entry, '%d %b, %H:%M' ) #!!! this is wrong! print ( ''' ''' % entry ) sys.exit(0) Apart from that i don't know how iam supposed to print it, because the date string is the 3rd string in every row of the dataset. Please help me out! From ben+python at benfinney.id.au Wed Aug 4 19:56:26 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 05 Aug 2010 09:56:26 +1000 Subject: Package management References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <87aap44mc7.fsf_-_@benfinney.id.au> Message-ID: <87pqxy2aqd.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > In message <87aap44mc7.fsf_-_ at benfinney.id.au>, Ben Finney wrote: > > > Sadly, Python's package management is rather lacking by these > > standards. The Distutils legacy assumption of ?package recipient, > > system administrator, and end user are all the same person?, among > > other design decisions, makes it unusually difficult to have the > > necessary separation of concerns between OS packaging, system > > administration, and end user. > > Doesn?t matter. I?m pretty sure Debian has a way of automatically > turning a distutils build into a .deb package with all the right > dependencies. :) Your certainty is no comfort to those who have to do the work of actually making those packages. Have you ever tried to make such a package and get it into Debian? The automation you speak of must be made and maintained by people, and they can only automate to the extent that the Distutils output allows. Have you spoken about this with the people who did that work, and what did they say to give you your certainty? If not, on what do you base your certainty? -- \ ?Any sufficiently advanced bug is indistinguishable from a | `\ feature.? ?Rich Kulawiec | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Wed Aug 4 20:19:20 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 12:19:20 +1200 Subject: Package management References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <87aap44mc7.fsf_-_@benfinney.id.au> <87pqxy2aqd.fsf@benfinney.id.au> Message-ID: In message <87pqxy2aqd.fsf at benfinney.id.au>, Ben Finney wrote: > Have you ever tried to make such a package and get it into Debian? I have found it very easy to recreate the same steps used by the package maintainers. For instance, ?apt-get source ? brings down the exact same source files used by the maintainer to build the package. Also, ?apt- get build-dep ? will make sure you have the right development tools installed to do the build. Then dpkg-buildpackage will build your own version of the package, in exactly the same way that the maintainers do it. > The automation you speak of must be made and maintained by people, and > they can only automate to the extent that the Distutils output allows. They seem to manage it OK. Just for fun, I tried building the python-cairo package from source, and among the output that flew by was for i in 2.5 2.6; do \ python$i-dbg ./setup.py build; \ done So they have found a way to automate the package build using distutils, rather than bypassing it. Also it manages to perform useful-looking checks like dpkg-shlibdeps: warning: dependency on libpthread.so.0 could be avoided if "debian/python-cairo/usr/lib/pyshared/python2.6/cairo/_cairo.so debian/python-cairo/usr/lib/pyshared/python2.5/cairo/_cairo.so" were not uselessly linked against it (they use none of its symbols). Oversight in the upstream build procedure, perhaps? Anyway, now I have my own .deb files, ready for installation. From pavlovevidence at gmail.com Wed Aug 4 21:07:44 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Aug 2010 18:07:44 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On Aug 4, 4:04?pm, Grant Edwards wrote: > On 2010-08-04, Lawrence D'Oliveiro wrote: > > > In message , Grant Edwards wrote: > > >> The problem has nothing to do with the relative merits of the > >> languages. ?The problem is inertia. > > > So how was C++ able to get popular in the first place? > > Building on C's popularity helped. AT&T + Money + C backward compatibility > > And how was Java able to grab some share from it? > > Good question. ?Both IBM and Sun put a lot of effort/money behind > Java. Sun + IBM + Money + 90s Web trinkets Carl Banks (haven't seen a Java applet in ages) From pavlovevidence at gmail.com Wed Aug 4 21:19:38 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Aug 2010 18:19:38 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> <7xk4o655dj.fsf@ruckus.brouhaha.com> Message-ID: <96e7627b-47f8-49e2-9aff-3ed74267b2cb@l14g2000yql.googlegroups.com> On Aug 4, 4:23?pm, Paul Rubin wrote: >?Java was also on the OO bandwagon of the 1990's, which > translated into good marketing back then, but is part of the cause of > the massive bureaucracy and bloat in the Java runtime environment. ?C++ > seems to have made something of a comeback because of this, and Java now > has generics patterned after C++'s. When I first studied Java, my first impression of the language was that it had a Prime Directive that, "other than single inheritance and being kinda like C, don't do anything C++ did". Not a bad policy, actually. However, omitting generics was probably the second worst thing about Java (the worst thing being the awful AWT design). Carl Banks From drobinow at gmail.com Wed Aug 4 22:20:44 2010 From: drobinow at gmail.com (David Robinow) Date: Wed, 4 Aug 2010 22:20:44 -0400 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On Wed, Aug 4, 2010 at 6:47 PM, Lawrence D'Oliveiro wrote: > In message , David > Robinow wrote: > >> ?As an admittedly stupid comparison, I have 1579 DLLs in my >> \windows\system32 directory. >> Some number of these have been upgraded by Windows Update. > > What about the ones that aren?t? How do you maintain those? Lawrence, you've been asking a lot of off-topic questions about Microsoft Windows. I think it's wonderful that you're so open to new ideas, but suggest that you take it to a Windows group, where I'm sure you'll get a friendly response. From roy at panix.com Wed Aug 4 22:56:41 2010 From: roy at panix.com (Roy Smith) Date: Wed, 04 Aug 2010 22:56:41 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > > > The problem has nothing to do with the relative merits of the > > languages. The problem is inertia. > > So how was C++ able to get popular in the first place? And how was Java able > to grab some share from it? C++, for all its flaws, had one powerful feature which made it very popular. It is a superset of C. Whatever that may mean from a technical standpoint, it made the language feel safe and comfortable and low-risk to managers. From a more technical standpoint, it had the very real advantage of being able to include all the C system headers and link against C system libraries. As for Java, that's easy. You could launch Java applets from inside a web browser. In those days, anything related to the web was a one-way express ticket to fame and fortune. From steve-REMOVE-THIS at cybersource.com.au Wed Aug 4 23:18:39 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 05 Aug 2010 03:18:39 GMT Subject: __init__ as a lambda References: Message-ID: <4c5a2d8e$0$11096$c3e8da3@news.astraweb.com> On Wed, 04 Aug 2010 12:58:18 -0700, Eric J. Van der Velden wrote: > Hello, > > Suppose > > class C: > def __init__(self,name):self.name=name > > I was wondering if I could make the __init__ a lambda function, Of course you can. Lambdas aren't special types of functions, they are *syntax* for creating a function consisting of a single expression, and your __init__ function is a single expression. These two are almost identical: def spam(a, b): return a+b spam = lambda a, b: a+b The only(?) differences are spam.func_name or spam.__name__. > but > > class C: > __init__=lambda self,self.name:None > > and then later, > > C('Hello') > > does not work; the first argument, self, is assigned all rigth, but you > cannot write the second argument with a dot, self.name . That gives a syntax error no matter whether you use it in a lambda form or an ordinary function: >>> def f(self,self.name): File "", line 1 def f(self,self.name): ^ SyntaxError: invalid syntax So the problem has nothing to do with lambda. What you want is: lambda self: self.name = None but of course that doesn't work either, because self.name = None is not an expression, it's a statement. So: class C: __init__ = lambda self: setattr(self, 'name', None) But don't do this. Seriously. Just because it is syntactically valid and does what you want, doesn't mean you should do it. Unless you have really good reason, and saving a single line of source code is a *bad* reason, just stick to the standard idiom that everyone can read without going "WTF is this guy doing this for???". class C: def __init__(self): self.name = None -- Steven From thatiumeshchandra at gmail.com Thu Aug 5 00:14:06 2010 From: thatiumeshchandra at gmail.com (rosy us) Date: Wed, 4 Aug 2010 21:14:06 -0700 (PDT) Subject: 100% without investment online part time jobs..(adsense, datawork, neobux..more jobs) Message-ID: 100% without investment?.no registration fee?no need money? Online part time jobs?(googleadsense, dataentry?etc)all type of jobs? work from home..daily 2-3 hours?earn more money without any risk.. Full details at http://adsensejobworkfulldetails.co.cc/ More adsense tips,secrets,increasing money ,seo..also available? From nagle at animats.com Thu Aug 5 00:33:31 2010 From: nagle at animats.com (John Nagle) Date: Wed, 04 Aug 2010 21:33:31 -0700 Subject: A useful, but painful, one-liner to edit money amounts Message-ID: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> There's got to be a better way to do this: def editmoney(n) : return((",".join(reduce(lambda lst, item : (lst + [item]) if item else lst, re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) >>> editmoney(0) '0' >>> editmoney(13535) '13,535' >>> editmoney(-14535) '-14,535' >>> editmoney(123456) '123,456' >>> editmoney(1234567890) '1,234,567,890' >>> editmoney(-1234) '-1,234' The basic idea here is that we want to split the string of digits into groups of 3 digits, aligned at the right. Because regular expressions are right to left, we have to reverse the string to do that, then reverse again at the end. s[::-1} reverses an interable. "split" with a capturing group introduces empty strings into the list. Hence the "reduce" and lambda to get rid of them. Any better ideas? (Yes, I know there's a built-in feature for this scheduled for Python 2.7.) John Nagle From samwyse at gmail.com Thu Aug 5 01:43:25 2010 From: samwyse at gmail.com (samwyse) Date: Wed, 4 Aug 2010 22:43:25 -0700 (PDT) Subject: simple (I hope!) problem References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> <4c57b51c$0$28663$c3e8da3@news.astraweb.com> Message-ID: On Aug 3, 1:20?am, Steven D'Aprano wrote: > On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote: > > Fortunately, I don't need the functionality of the object, I just want > > something that won't generate an error when I use it. ?So, what is the > > quickest way to to create such an object (replacing the 'pass' in my > > first snippet). ?My solution is this: > > > ? ? class C: > > ? ? ? ? def filter(self, *args, **kwds): > > ? ? ? ? ? ? pass > > ? ? register = C() > > > but it seems like I should be able to do something "better", as measured > > by lines of code, faking more than just a 'filter' method, or both. ?Any > > ideas? ?Thanks! > > You want a variation on the Null Object design pattern. > > class NullWithMethods(object): > ? ? def __getattr__(self, name): > ? ? ? ? return self > ? ? def __call__(self, *args, **kwargs): > ? ? ? ? pass > > And in action: > > >>> c = NullWithMethods() > >>> c.spam("hello", "world") > >>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42) > > -- > Steven JM emailed me a good solution, but yours is great! Thanks! From no.email at nospam.invalid Thu Aug 5 02:03:02 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 04 Aug 2010 23:03:02 -0700 Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <7xocdha961.fsf@ruckus.brouhaha.com> John Nagle writes: > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) Too obscure. I usually use something like this: def editmoney(n): if n < 0: return '-' + editmoney(-n) if n >= 1000: return editmoney(n // 1000) + ',%03d'% (n % 1000) return '%d'% n From steve-REMOVE-THIS at cybersource.com.au Thu Aug 5 02:20:58 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 05 Aug 2010 06:20:58 GMT Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <4c5a584a$0$11096$c3e8da3@news.astraweb.com> On Wed, 04 Aug 2010 21:33:31 -0700, John Nagle wrote: > There's got to be a better way to do this: > > > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) What does the name "editmoney" mean? Why the obfuscated one-liner? It's not like you're using it in-line, you're putting it in a function, so who cares if it's one line or twenty? def group_digits(n, size=3, sep=','): """Group int n in groups of size digits separated by sep.""" s = str(n) m = len(s) % size head = s[0:m] tail = s[m:] groups = [tail[i*size:(i+1)*size] for i in range(len(tail)//size)] tail = sep.join(groups) if head and tail: return head + sep + tail elif tail: return tail else: return head >>> group_digits(0) '0' >>> group_digits(1234567890) '1,234,567,890' >>> group_digits(1234567890, 4, ';') '12;3456;7890' Additional error checking, a better docstring, and extending it to support negative numbers is left as an exercise. -- Steven From ddasilva at umd.edu Thu Aug 5 02:26:01 2010 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 4 Aug 2010 23:26:01 -0700 Subject: newbie problem with str.replace In-Reply-To: <0ece6c99-1c8f-4055-9ed9-4f63b4ed4b2d@j8g2000yqd.googlegroups.com> References: <0ece6c99-1c8f-4055-9ed9-4f63b4ed4b2d@j8g2000yqd.googlegroups.com> Message-ID: Also, for bestandsnaam in dirs and files: is probably not doing what you want. Use + to concatenate lists. Daniel On Wed, Aug 4, 2010 at 6:30 AM, Mike Kent wrote: > On Aug 4, 9:10 am, BobAalsma wrote: > > I'm working on a set of scripts and I can't get a replace to work in > > the script - please help. > > > > bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) > > I'm not sure what you are intending to do here, but string.replace > does not do its replacement in-place. It returns a copy of the > original string, with the replacement done in the copy. You are not > assigning the string returned by string.replace to anything, > therefore, it is immediately thrown away. > > Secondly, and this is just a guess, but since you are doing the > string.replace inside of an os.walk loop, you appear to be trying to > do a filename change. I hope you realize that this will in no way > change the name of the file *on disk*; it will only change it in > memory. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Aug 5 02:30:09 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Aug 2010 08:30:09 +0200 Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > There's got to be a better way to do this: > > > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) > > > >>> editmoney(0) > '0' > >>> editmoney(13535) > '13,535' > >>> editmoney(-14535) > '-14,535' > >>> editmoney(123456) > '123,456' > >>> editmoney(1234567890) > '1,234,567,890' > >>> editmoney(-1234) > '-1,234' > > The basic idea here is that we want to split the string of digits > into groups of 3 digits, aligned at the right. Because regular > expressions are right to left, we have to reverse the string to > do that, then reverse again at the end. s[::-1} reverses an > interable. > > "split" with a capturing group introduces empty strings into the > list. Hence the "reduce" and lambda to get rid of them. > > Any better ideas? > > (Yes, I know there's a built-in feature for this scheduled for > Python 2.7.) >>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) 'en_US.UTF8' >>> print locale.currency(13535, grouping=True) $13,535.00 >>> print locale.format("%d", 13535, grouping=True) 13,535 >>> locale.setlocale(locale.LC_ALL, "") 'de_DE.UTF-8' >>> print locale.currency(13535, grouping=True) 13.535,00 ? >>> print locale.format("%d", 13535, grouping=True) 13.535 Peter From debatem1 at gmail.com Thu Aug 5 03:22:57 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 5 Aug 2010 00:22:57 -0700 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: On Wed, Aug 4, 2010 at 11:30 PM, Peter Otten <__peter__ at web.de> wrote: > John Nagle wrote: > >> There's got to be a better way to do this: >> >> >> def editmoney(n) : >> ? ? ?return((",".join(reduce(lambda lst, item : (lst + [item]) if >> ? ? ? ? ?item else lst, >> ? ? ? ? ?re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) >> >> >> ?>>> editmoney(0) >> '0' >> ?>>> editmoney(13535) >> '13,535' >> ?>>> editmoney(-14535) >> '-14,535' >> ?>>> editmoney(123456) >> '123,456' >> ?>>> editmoney(1234567890) >> '1,234,567,890' >> ?>>> editmoney(-1234) >> '-1,234' >> >> The basic idea here is that we want to split the string of digits >> into groups of 3 digits, aligned at the right. ?Because regular >> expressions are right to left, we have to reverse the string to >> do that, then reverse again at the end. ?s[::-1} reverses an >> interable. >> >> "split" with a capturing group introduces empty strings into the >> list. ?Hence the "reduce" and lambda to get rid of them. >> >> Any better ideas? >> >> (Yes, I know there's a built-in feature for this scheduled for >> Python 2.7.) > > >>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) > 'en_US.UTF8' >>>> print locale.currency(13535, grouping=True) > $13,535.00 >>>> print locale.format("%d", 13535, grouping=True) > 13,535 > >>>> locale.setlocale(locale.LC_ALL, "") > 'de_DE.UTF-8' >>>> print locale.currency(13535, grouping=True) > 13.535,00 ? >>>> print locale.format("%d", 13535, grouping=True) > 13.535 > > Peter I had literally no idea this existed. Thanks. Geremy Condra From none at none.com Thu Aug 5 03:25:36 2010 From: none at none.com (Brandon McCombs) Date: Thu, 05 Aug 2010 03:25:36 -0400 Subject: new to python - trouble calling a function from another function Message-ID: Hello, I'm building an elevator simulator for a class assignment. I recently ran into a roadblock and don't know how to fix it. For some reason, in my checkQueue function below, the call to self.goUp() is never executed. It is on the last line of code I pasted in. I can put print statements before and after the call and I have a print statement in goUp() itself. Only the print statements before and after the call are executed. The one inside goUp() is never executed because goUp() never seems to be executed. How can that be? I don't get any errors when the script executes. Surely this isn't some limitation I'm encountering? thanks sorry about the formatting --------------------------------------------- class Elevator(Process): def __init__(self,name): Process.__init__(self,name=name) self.numPassengers = 0 self.passengerList = [] self.passengerWaitQ = [] self.currentFloor = 1 self.idle = 1 self.newPassengers = 0 def goUp(self): print "here" bubbleSort(self.passengerList, len(self.passengerList)) self.currentFloor += 1 if len(self.passengerList) > 0: for p in self.passengerList: if self.currentFloor == p.destination: yield (p.destination - self.currenteFloor) * TRAVELTIME, self reactivate(p) p.inBuilding() else: self.goUp() def checkQueue(self): if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < MAXCAPACITY: if len(self.passengerWaitQ) < MAXCAPACITY: self.newPassengers = len(self.passengerWaitQ) else: self.newPassengers = MAXCAPACITY - len(self.passengerList) for i in range(0,self.newPassengers): self.passengerList.append(self.passengerWaitQ.pop()) self.goUp() From navkirats at gmail.com Thu Aug 5 03:36:12 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 5 Aug 2010 13:06:12 +0530 Subject: new to python - trouble calling a function from another function In-Reply-To: References: Message-ID: <2D98CECE-39EF-4972-9AD9-F856B07FB9D1@gmail.com> I was looking at the code, I dont have much time to go through it, but I might have found a typo - yield (p.destination - self.currenteFloor) , I think it should be currentFloor.Maybe thats your problem. Will look into the code more later. Regards, Nav On 05-Aug-2010, at 12:55 PM, Brandon McCombs wrote: > Hello, > > I'm building an elevator simulator for a class assignment. I recently ran into a roadblock and don't know how to fix it. For some reason, in my checkQueue function below, the call to self.goUp() is never executed. It is on the last line of code I pasted in. I can put print statements before and after the call and I have a print statement in goUp() itself. Only the print statements before and after the call are executed. The one inside goUp() is never executed because goUp() never seems to be executed. How can that be? I don't get any errors when the script executes. Surely this isn't some limitation I'm encountering? > > thanks > > sorry about the formatting > > --------------------------------------------- > class Elevator(Process): > def __init__(self,name): > Process.__init__(self,name=name) > self.numPassengers = 0 > self.passengerList = [] > self.passengerWaitQ = [] > self.currentFloor = 1 > self.idle = 1 > self.newPassengers = 0 > def goUp(self): > print "here" > bubbleSort(self.passengerList, len(self.passengerList)) > self.currentFloor += 1 > if len(self.passengerList) > 0: > for p in self.passengerList: > if self.currentFloor == p.destination: > yield (p.destination - self.currenteFloor) * TRAVELTIME, self > reactivate(p) > p.inBuilding() > else: > self.goUp() > > def checkQueue(self): > if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < MAXCAPACITY: > if len(self.passengerWaitQ) < MAXCAPACITY: > self.newPassengers = len(self.passengerWaitQ) > else: > self.newPassengers = MAXCAPACITY - len(self.passengerList) > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() > -- > http://mail.python.org/mailman/listinfo/python-list From news1234 at free.fr Thu Aug 5 03:49:20 2010 From: news1234 at free.fr (News123) Date: Thu, 05 Aug 2010 09:49:20 +0200 Subject: Python Script Cannot Write to Directory In-Reply-To: References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> Message-ID: <4c5a6d00$0$29614$426a34cc@news.free.fr> On 08/04/2010 09:27 AM, Chris Rebert wrote: > On Wed, Aug 4, 2010 at 12:21 AM, News123 wrote: > >> 3.) try following python >> >> import os >> print os.getcwd() >> import shutil >> shutil("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") > > WTF; modules aren't callable. Typo? > Indeed. This is a typo and Matteo Landi's right about what I meant: shutil.copyfile("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") What remains is: I think the answers to my questions will help to reveal the cause of the problem. The original question lacks necessary information as file permissions / directory permissions etc. / the exact error message. From steve-REMOVE-THIS at cybersource.com.au Thu Aug 5 04:29:54 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 05 Aug 2010 08:29:54 GMT Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <4c5a7682$0$11096$c3e8da3@news.astraweb.com> On Thu, 05 Aug 2010 00:22:57 -0700, geremy condra wrote: >>>>> locale.setlocale(locale.LC_ALL, "") >> 'de_DE.UTF-8' >>>>> print locale.currency(13535, grouping=True) >> 13.535,00 ? >>>>> print locale.format("%d", 13535, grouping=True) >> 13.535 >> >> Peter > > I had literally no idea this existed. Thanks. I knew it existed, but completely forgot about it. Thanks also Peter. -- Steven From jeanmichel at sequans.com Thu Aug 5 05:17:05 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 11:17:05 +0200 Subject: A new syntax for writing tests In-Reply-To: References: Message-ID: <4C5A8191.1090907@sequans.com> Jonathan Fine wrote: > Hi > > I just discovered today a new syntax for writing tests. The basic > idea is to write a function that contains some statements, and run it > via a decorator. I wonder if anyone had seen this pattern before, and > how you feel about it. For myself, I quite like it. > > Let's suppose we want to test this trivial (of course) class. > class Adder(object): > > def __init__(self): > self.value = 0 > > def plus(self, delta): > self.value += delta > > The test the class you need a runner. In this case it is quite simple. > > def runner(script, expect): > '''Create an adder, run script, expect value.''' > > adder = Adder() > script(adder) > return adder.value > > We can now create (and run if we wish) a test. To do this we write > > @testit(runner, 4) > def whatever(a): > '''Two plus two is four.''' > > a.plus(2) > a.plus(2) > > Depending on the exact value of the testit decorator (which in the end > is up to you) we can store the test, or execute it immediately, or do > something else. > > The simplest implementation prints: > OK: Two plus two is four. > for this passing test, and > Fail: Two plus four is five. > expect 5 > actual 6 > for a test that fails. > > Here is the testit decorator used to produce the above output: > > def testit(runner, expect): > '''Test statements decorator.''' > > def next(script): > actual = runner(script, expect) > if actual == expect: > print 'OK:', script.__doc__ > else: > print 'Fail:', script.__doc__ > print ' expect', expect > print ' actual', actual > > return next > > > You can pick this code, for at least the next 30 days, at > http://dpaste.com/hold/225056/ > > For me the key benefit is that writing the test is really easy. > Here's a test I wrote earlier today. > > @testit(runner, '''''') > def whatever(tb): > tb.start('a', {'att': 'value'}) > tb.start('b') > tb.end('b') > tb.end('a') > > If the test has a set-up and tear-down, this can be handled in the > runner, as can the test script raising an expected or unexpected > exception. > Hi, "The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users." source http://docs.python.org/library/unittest.html As you can see, a much more featured test framework already exists. There's nothing wrong in a new test framework, but it has to be better than the existing one in some situations. JM From jeanmichel at sequans.com Thu Aug 5 05:32:06 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 11:32:06 +0200 Subject: simple (I hope!) problem In-Reply-To: References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> <4c57b51c$0$28663$c3e8da3@news.astraweb.com> Message-ID: <4C5A8516.3070201@sequans.com> samwyse wrote: > On Aug 3, 1:20 am, Steven D'Aprano T... at cybersource.com.au> wrote: > >> On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote: >> >>> Fortunately, I don't need the functionality of the object, I just want >>> something that won't generate an error when I use it. So, what is the >>> quickest way to to create such an object (replacing the 'pass' in my >>> first snippet). My solution is this: >>> >>> class C: >>> def filter(self, *args, **kwds): >>> pass >>> register = C() >>> >>> but it seems like I should be able to do something "better", as measured >>> by lines of code, faking more than just a 'filter' method, or both. Any >>> ideas? Thanks! >>> >> You want a variation on the Null Object design pattern. >> >> class NullWithMethods(object): >> def __getattr__(self, name): >> return self >> def __call__(self, *args, **kwargs): >> pass >> >> And in action: >> >> >>>>> c = NullWithMethods() >>>>> c.spam("hello", "world") >>>>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42) >>>>> >> -- >> Steven >> > > JM emailed me a good solution, but yours is great! Thanks! > The version I gave you overrides __getattribute__. To be honest, overriding __getattr__ is a better solution.Just in case you don't know the difference, __getattr__ is called only if the attribute is not found while __getattribute__ is actually called to find the attribute. JM From sschwarzer at sschwarzer.net Thu Aug 5 05:49:48 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 05 Aug 2010 11:49:48 +0200 Subject: simple integer subclass In-Reply-To: References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> Message-ID: <4C5A893C.6060807@sschwarzer.net> Hi Andreas, On 2010-08-03 12:15, Andreas Pfrengle wrote: > On 3 Aug., 03:22, Carl Banks wrote:> > Thinking about it, it might really be dangerous to coerce always to > int1, since sometimes I might want a normal int as result (I can't > tell yet for sure). Yes, that way your problem may shift from inconvenient to outright hairy. ;-) > The application will be a browsergame, and most gamers start counting > at 1, so they would probably wonder about a "level 0 item" ;-) > If there didn't already exist lots of code, I would redesign the whole > data-structure - I think that's "lessons learned" for the next project What about def _index_to_level(index): return index + 1 with this or a different name? This admittedly is longer than writing `something + 1` but in the latter case you might wonder what the addition is for, i. e. if it's really a level offset calculation or something else. Stefan From joncle at googlemail.com Thu Aug 5 05:50:05 2010 From: joncle at googlemail.com (Jon Clements) Date: Thu, 5 Aug 2010 02:50:05 -0700 (PDT) Subject: new to python - trouble calling a function from another function References: Message-ID: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> On 5 Aug, 08:25, Brandon McCombs wrote: > Hello, > > I'm building an elevator simulator for a class assignment. I recently > ran into a roadblock and don't know how to fix it. For some reason, in > my checkQueue function below, the call to self.goUp() is never executed. > It is on the last line of code I pasted in. I can put print statements > before and after the call and I have a print statement in goUp() itself. > ? Only the print statements before and after the call are executed. The > one inside goUp() is never executed because goUp() never seems to be > executed. How can that be? I don't get any errors when the script > executes. Surely this isn't some limitation I'm encountering? > > thanks > > sorry about the formatting > > --------------------------------------------- > class Elevator(Process): > def __init__(self,name): > ? ? ? ? Process.__init__(self,name=name) > ? ? ? ? self.numPassengers = 0 > ? ? ? ? self.passengerList = [] > ? ? ? ? self.passengerWaitQ = [] > ? ? ? ? self.currentFloor = 1 > ? ? ? ? self.idle = 1 > ? ? ? ? self.newPassengers = 0 > def goUp(self): > ? ? ? ? print "here" > ? ? ? ? bubbleSort(self.passengerList, len(self.passengerList)) > ? ? ? ? self.currentFloor += 1 > ? ? ? ? if len(self.passengerList) > 0: > ? ? ? ? ? ?for p in self.passengerList: > ? ? ? ? ? ? ? if self.currentFloor == p.destination: > ? ? ? ? ? ? ? ? yield (p.destination - self.currenteFloor) * TRAVELTIME, self > ? ? ? ? ? ? ? ? reactivate(p) > ? ? ? ? ? ? ? ? p.inBuilding() > ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? self.goUp() > > def checkQueue(self): > ? ? ? ? if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < > MAXCAPACITY: > ? ? ? ? if len(self.passengerWaitQ) < MAXCAPACITY: > ? ? ? ? ? ? self.newPassengers = len(self.passengerWaitQ) > ? ? ? ? else: > ? ? ? ? ? ? ?self.newPassengers = MAXCAPACITY - len(self.passengerList) > ? ? ? ? for i in range(0,self.newPassengers): > ? ? ? ? ? self.passengerList.append(self.passengerWaitQ.pop()) > ? ? ? ? self.goUp() Hi Brandon, Nice one at having a good crack at coding before posting! >From your posted code, I'm struggling to see what's trying to be taught to you for this class assignment. As a note it'll be worth reading PEP 8 regarding naming conventions, because it looks very Java-ish to me! (I might be taking too much a real-world approach in the following, but do with it as you will...) I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere. Although what I'm thinking is that different Elevators will have different capacities and different floors they service. An Elevator is *not* going to know its number of passengers (the most it could do is capacity based on weight restrictions) therefore it's not going to know the number of new passengers on each floor either. A couple of things that'd be worthwhile: 1) Post the requirements for your assignment - what's it supposed to output etc... 2) Go find an elevator, take a pen and pad with you, and stand in it for 30 mins or so, and see how the real thing deals with situations and make notes. ie, does it queue requests, or decide to take the next nearest floor, when does it stop and open etc...? hth Jon. From Juergen.Hermann at 1und1.de Thu Aug 5 06:07:55 2010 From: Juergen.Hermann at 1und1.de (jhermann) Date: Thu, 5 Aug 2010 03:07:55 -0700 (PDT) Subject: Behavior of re.split on empty strings is unexpected References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: <110d416f-858b-4568-bea2-3471f5dcfae9@x25g2000yqj.googlegroups.com> On Aug 2, 7:34?pm, John Nagle wrote: > ?>>> s2 = " ? HELLO ? THERE ?" > ?>>> kresplit4 = re.compile(r'\W+', re.UNICODE) > ?>>> kresplit4.split(s2) > ['', 'HELLO', 'THERE', ''] > > I still get empty strings. >>> re.findall(r"\w+", " a b c ") ['a', 'b', 'c'] From lie.1296 at gmail.com Thu Aug 5 06:27:15 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 05 Aug 2010 20:27:15 +1000 Subject: Nice way to cast a homogeneous tuple In-Reply-To: <5lp5i7-f5u.ln1@satorlaser.homedns.org> References: <4C50305E.3010603@otenet.gr> <4C503122.3060208@otenet.gr> <5lp5i7-f5u.ln1@satorlaser.homedns.org> Message-ID: On Wed, 28 Jul 2010 15:58:29 +0200, Ulrich Eckhardt wrote: > wheres pythonmonks wrote: > > Thanks ... I thought int was a type-cast (like in C++) so I assumed I > > couldn't reference it. > Firstly, "int" is a class. Python doesn't make a distinction between builtin > types and class types like C++, where you e.g. can't derive from builtin > types. That wasn't true until recently with class and type unification. In some older versions of python you cannot derive from build in types either. From ldo at geek-central.gen.new_zealand Thu Aug 5 06:33:39 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 22:33:39 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xocdi56cp.fsf@ruckus.brouhaha.com> Message-ID: In message <7xocdi56cp.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > I'd say the Ada standardizers went to a great deal of trouble to specify > and document stuff that other languages simply leave undefined, leaving > developers relying on implementation-specific behavior that's not part > of the standard. OK, I have a copy of K&R 2nd Ed on a shelf within reach here. Can you point out some behaviour that C programmers might need to rely on, that is not specified in that document? > Ada itself is not necessarily more complicated. It is. Look at its baroque type structure. Hint: why is type A is B; a syntax error? From ldo at geek-central.gen.new_zealand Thu Aug 5 06:34:31 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 22:34:31 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In message , Roy Smith wrote: > C++, for all its flaws, had one powerful feature which made it very > popular. It is a superset of C. Actually, it never was. From eckhardt at satorlaser.com Thu Aug 5 06:35:50 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 05 Aug 2010 12:35:50 +0200 Subject: new to python - trouble calling a function from another function References: Message-ID: <6pgqi7-unn.ln1@satorlaser.homedns.org> Brandon McCombs wrote: > I'm building an elevator simulator for a class assignment. I recently > ran into a roadblock and don't know how to fix it. For some reason, in > my checkQueue function below, the call to self.goUp() is never executed. [...] > sorry about the formatting While I can certainly forgive you the formatting (my problem is rather that you didn't reduce the code to the smallest possible example), Python wont. Python is a language where whitespace is significant and can subtly change the meaning of your code. Example: > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() The formatting here is completely removed, but there are two conceivable ways this could be formatted: # variant 1 for i in range(0,self.newPassengers): self.passengerList.append(self.passengerWaitQ.pop()) self.goUp() #variant 2 for i in range(0,self.newPassengers): self.passengerList.append(self.passengerWaitQ.pop()) self.goUp() Someone already mentioned PEP 8 (search the web!). These PEPs could be called the standards governing Python behaviour, and PEP 8 actually defines several things concerning the formatting of sourcecode. Apply it unless you have a good reason not to. Further, you should run Python with "-t" as argument on the commandline. This will give you warnings when it encounters inconsistent tab/spaces usage. This can make a difference. Example: #variant 3 for i in range(0,self.newPassengers): self.passengerList.append(self.passengerWaitQ.pop()) self.goUp() If your editor is set to four spaces per tab, this will look like variant 2, with 8 spaces it will look like variant 1. I don't know (and don't care, since PEP-8 mandates four spaces) which interpretation Python actually uses. Lastly, you can simplify your check_queue() function. First, determine the number of free places inside the elevator. Then, you simply append that many passengers from the waiting list to the passenger list: free = MAX_CAPACITY - len(self.passengers) new_passengers = self.passenger_wait_queue[:free] self.passenger_wait_queue = self.passenger_wait_queue[free:] self.passengers += new_passengers This uses the fact that list indices are automatically truncated to a valid range, so requesting the elements 0 to 10 from a 5-element list will only yield those five elements, not raise an exception. It's up to you though which version is clearer to you. I would perhaps bail out if "free == 0" and then also not call go_up() lateron. Cheers and good luck! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From ldo at geek-central.gen.new_zealand Thu Aug 5 06:36:10 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 22:36:10 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , David Robinow wrote: > Lawrence, you've been asking a lot of off-topic questions about > Microsoft Windows. You?ve got to be kidding. Look at the number of Windows-specific questions this groups is already full of. From lie.1296 at gmail.com Thu Aug 5 06:39:25 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 05 Aug 2010 20:39:25 +1000 Subject: Nice way to cast a homogeneous tuple In-Reply-To: References: Message-ID: On Wed, 28 Jul 2010 09:15:24 -0400, wheres pythonmonks wrote: > A new python convert is now looking for a replacement for another perl idiom. A functional alternative: l = ... seqint = compose(map, int) print f(seqint(l)) From chris at simplistix.co.uk Thu Aug 5 07:06:17 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 12:06:17 +0100 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <4C5A9B29.2020901@simplistix.co.uk> Peter Otten wrote: >>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) > 'en_US.UTF8' >>>> print locale.currency(13535, grouping=True) > $13,535.00 Okay, so if I'm writing a wsgi app, and I want to format depending on the choices of the currently logged in users, what would you recommend? I can't do setlocale, since that would affect all users, and in a mult-threaded environment that would be bad. Does that mean the whole locale package is useless to all web-app builders? Chris From chris at simplistix.co.uk Thu Aug 5 07:16:33 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 12:16:33 +0100 Subject: subprocess escaping POpen?! Message-ID: <4C5A9D91.9000504@simplistix.co.uk> Hi All, I have a script that does the following: from subprocess import Popen,PIPE,STDOUT def execute(command,cwd): return Popen( command, stderr=STDOUT, stdout=PIPE, universal_newlines=True, cwd=cwd, shell=True, ).communicate()[0] captured = execute('svn up .') Now, if the subversion update requires authentication credentials, it manages to write to the console running the above script, *and* read input from it too. This is a bit baffling to me, I thought Popen.communicate() was happily hoovering all the output to stdout and stderr into the result returned from communicate? And, indeed, if I change the script instead to do: import sys f = open('test.py','w') f.write('import sys; sys.stderr.write("Hello!\\n")') f.close() captured = execute('test.py') ...then the output is indeed captured. So, what is svn doing differently? How is it escaping its jail? Chris From paul.nospam at rudin.co.uk Thu Aug 5 07:20:14 2010 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 05 Aug 2010 12:20:14 +0100 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: <8739utnw5t.fsf@rudin.co.uk> Lawrence D'Oliveiro writes: > In message , Roy Smith wrote: > >> C++, for all its flaws, had one powerful feature which made it very >> popular. It is a superset of C. > > Actually, it never was. Wondering off topic a bit - I am reminded of something I once read in some MS blurb... it described something as an "extended subset" of some standard or another. (Think about it :)) From wolfgang at rohdewald.de Thu Aug 5 07:22:11 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Thu, 5 Aug 2010 13:22:11 +0200 Subject: subprocess escaping POpen?! In-Reply-To: <4C5A9D91.9000504@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> Message-ID: <201008051322.11456.wolfgang@rohdewald.de> On Donnerstag 05 August 2010, Chris Withers wrote: > ...then the output is indeed captured. So, what is svn doing > differently? How is it escaping its jail? maybe it does not read from stdin but directly from /dev/tty -- Wolfgang From chris at simplistix.co.uk Thu Aug 5 07:23:35 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 12:23:35 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <201008051322.11456.wolfgang@rohdewald.de> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> Message-ID: <4C5A9F37.80708@simplistix.co.uk> Wolfgang Rohdewald wrote: > On Donnerstag 05 August 2010, Chris Withers wrote: >> ...then the output is indeed captured. So, what is svn doing >> differently? How is it escaping its jail? > > maybe it does not read from stdin but directly from /dev/tty But why only the request for auth credentials? Chris From jeanmichel at sequans.com Thu Aug 5 07:38:32 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 13:38:32 +0200 Subject: subprocess escaping POpen?! In-Reply-To: <4C5A9D91.9000504@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> Message-ID: <4C5AA2B8.3020806@sequans.com> Chris Withers wrote: > Hi All, > > I have a script that does the following: > > from subprocess import Popen,PIPE,STDOUT > > def execute(command,cwd): > return Popen( > command, > stderr=STDOUT, > stdout=PIPE, > universal_newlines=True, > cwd=cwd, > shell=True, > ).communicate()[0] > > captured = execute('svn up .') > > Now, if the subversion update requires authentication credentials, it > manages to write to the console running the above script, *and* read > input from it too. > > This is a bit baffling to me, I thought Popen.communicate() was > happily hoovering all the output to stdout and stderr into the result > returned from communicate? > > And, indeed, if I change the script instead to do: > > import sys > f = open('test.py','w') > f.write('import sys; sys.stderr.write("Hello!\\n")') > f.close() > captured = execute('test.py') > > ...then the output is indeed captured. So, what is svn doing > differently? How is it escaping its jail? > > Chris > You did not redirect stdin, so it is expected you can still read input from the console. And it looks like svn is writting the credentials prompt on stderr. You may want to look at http://pysvn.tigris.org/docs/pysvn.html though. JM From pict100 at gmail.com Thu Aug 5 07:56:38 2010 From: pict100 at gmail.com (DarkBlue) Date: Thu, 5 Aug 2010 04:56:38 -0700 (PDT) Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <9b4bd0c2-8912-4a60-9a12-b7b8586aba84@i4g2000prf.googlegroups.com> On Aug 5, 7:06?pm, Chris Withers wrote: > Peter Otten wrote: > >>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) > > 'en_US.UTF8' > >>>> print locale.currency(13535, grouping=True) > > $13,535.00 > > Okay, so if I'm writing a wsgi app, and I want to format depending on > the choices of the currently logged in users, what would you recommend? > > I can't do setlocale, since that would affect all users, and in a > mult-threaded environment that would be bad. > > Does that mean the whole locale package is useless to all web-app builders? > > Chris from re import * class editmoney(float): def __init__(self,mymoney): self.mymoney = mymoney def __str__(self): temp = "%.2f" % self.mymoney profile = compile(r"(\d)(\d\d\d[.,])") while 1: temp, count = subn(profile,r"\1,\2",temp) if not count: break return temp From chris at simplistix.co.uk Thu Aug 5 07:58:20 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 12:58:20 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AA2B8.3020806@sequans.com> References: <4C5A9D91.9000504@simplistix.co.uk> <4C5AA2B8.3020806@sequans.com> Message-ID: <4C5AA75C.3080700@simplistix.co.uk> Jean-Michel Pichavant wrote: > You did not redirect stdin, so it is expected you can still read input > from the console. Okay, so if I definitely wanted no input, what should I pass as the stdin parameter to the POpen constructor? > And it looks like svn is writting the credentials > prompt on stderr. ...which, as you can see from the code I posted, is piped to STDOUT, which is then PIPE'd through to the calling python so that communicate()'s return value will contain the output. As I explained, I can't reproduce this by replacing svn with a simple python script that writes to stderr. So, what is svn doing? > You may want to look at http://pysvn.tigris.org/docs/pysvn.html though. Yeah, we were using that, but found it excruciatingly painful due to its dependency on a subversion source install due to its c extension. cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From christoffer at viken.me Thu Aug 5 08:01:32 2010 From: christoffer at viken.me (Christoffer Viken) Date: Thu, 5 Aug 2010 14:01:32 +0200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: C++ is actually not that bad. Can't compare it to C, but nothing compares to C... I think the bad reputation it got (and still has) is from Microsoft's visual studio IDE (that was and still is horrible) A lot of good applications are written in C++, but many bad ones as well. Sorry for swearing in the church, but I'm pulling out PHP as an example. Easy on beginners, the fat that you can jump in and out of PHP mode helps too. It attracts a lot of beginner developers, and most of them write bad code. It does not make the language a bad language, in fact PHP5 is pretty good, but it means that there is a lot of bad code out there, but then we have gems like MediaWiki and Drupal that is really good software. You can write bad code in any language, and many languages get a bad reputation because a lot of bad code is written in it. The real test is not how bad code you can write, but the limit for how good code you can write without jumping trough (too manny) hoops. On Thu, Aug 5, 2010 at 12:34 PM, Lawrence D'Oliveiro wrote: > In message , Roy Smith wrote: > > > C++, for all its flaws, had one powerful feature which made it very > > popular. It is a superset of C. > > Actually, it never was. > -- > http://mail.python.org/mailman/listinfo/python-list > -- ----------Desktop Browser, Google Apps --------- Christoffer Viken / CVi i=0 str="kI4dJMtXAv0m3cUiPKx8H" while i<=20: if i%3 and not i%4: print str[i], i=i+1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From markken at gmail.com Thu Aug 5 08:04:36 2010 From: markken at gmail.com (Marcos Prieto) Date: Thu, 5 Aug 2010 05:04:36 -0700 (PDT) Subject: PyInt_FromLong gives segfault on small numbers (<257) Message-ID: <5db89057-3281-495a-80e4-2e76d7235da6@d17g2000yqb.googlegroups.com> Hi, I'm trying to call python (python 2.6) functions from C++ using MS VC+ + 6.0 and any calls to PyInt_FromLong with numbers below 257 give me exceptions, no problems with bigger numbers PyObject *pValue; pValue = PyInt_FromLong(1L); (or pValue = PyInt_FromLong(1); Any ideas of what can I be doing wrong? Thanks, Marcos. From ryan at rfk.id.au Thu Aug 5 08:11:05 2010 From: ryan at rfk.id.au (Ryan Kelly) Date: Thu, 05 Aug 2010 22:11:05 +1000 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AA75C.3080700@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <4C5AA2B8.3020806@sequans.com> <4C5AA75C.3080700@simplistix.co.uk> Message-ID: <1281010265.1554.2.camel@durian> On Thu, 2010-08-05 at 12:58 +0100, Chris Withers wrote: > Jean-Michel Pichavant wrote: > > You did not redirect stdin, so it is expected you can still read input > > from the console. > > Okay, so if I definitely wanted no input, what should I pass as the > stdin parameter to the POpen constructor? The cross-platform equivalent of /dev/null: Popen(...,stdin=open(os.devnull,"r")...) > > And it looks like svn is writting the credentials > > prompt on stderr. > > ...which, as you can see from the code I posted, is piped to STDOUT, > which is then PIPE'd through to the calling python so that > communicate()'s return value will contain the output. > > As I explained, I can't reproduce this by replacing svn with a simple > python script that writes to stderr. So, what is svn doing? Many programs prompt for auth credentials on the controlling tty instead of standard input/output. I believe SSH also does this, which suggests that it's considered more secure. No idea why, but I trust the authors of SSH to know their stuff in this regard. Cheers, Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details From wolfgang at rohdewald.de Thu Aug 5 08:23:08 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Thu, 5 Aug 2010 14:23:08 +0200 Subject: subprocess escaping POpen?! In-Reply-To: <4C5A9F37.80708@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> Message-ID: <201008051423.08319.wolfgang@rohdewald.de> On Donnerstag 05 August 2010, Chris Withers wrote: > But why only the request for auth credentials? for security reasons I suppose - make sure a human enters the password -- Wolfgang From __peter__ at web.de Thu Aug 5 08:27:44 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Aug 2010 14:27:44 +0200 Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: Chris Withers wrote: > Peter Otten wrote: >>>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) >> 'en_US.UTF8' >>>>> print locale.currency(13535, grouping=True) >> $13,535.00 > > Okay, so if I'm writing a wsgi app, and I want to format depending on > the choices of the currently logged in users, what would you recommend? > > I can't do setlocale, since that would affect all users, and in a > mult-threaded environment that would be bad. > > Does that mean the whole locale package is useless to all web-app Blame it on the C guys ;) I've seen http://babel.edgewall.org/wiki/Documentation/intro.html http://babel.edgewall.org/wiki/ApiDocs/babel.numbers http://babel.edgewall.org/wiki/BabelFaq#WhatalternativesexistforPythonprojects mentioned here but not yet tried it myself. Peter From solipsis at pitrou.net Thu Aug 5 08:34:37 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 5 Aug 2010 14:34:37 +0200 Subject: PyInt_FromLong gives segfault on small numbers (<257) References: <5db89057-3281-495a-80e4-2e76d7235da6@d17g2000yqb.googlegroups.com> Message-ID: <20100805143437.1af3a184@pitrou.net> On Thu, 5 Aug 2010 05:04:36 -0700 (PDT) Marcos Prieto wrote: > Hi, > > I'm trying to call python (python 2.6) functions from C++ using MS VC+ > + 6.0 and any calls to PyInt_FromLong with numbers below 257 give me > exceptions, no problems with bigger numbers > > PyObject *pValue; > > pValue = PyInt_FromLong(1L); (or pValue = PyInt_FromLong(1); Have you called Py_Initialize() before? From chris at simplistix.co.uk Thu Aug 5 08:47:10 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 13:47:10 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <201008051423.08319.wolfgang@rohdewald.de> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> Message-ID: <4C5AB2CE.7040903@simplistix.co.uk> Wolfgang Rohdewald wrote: > On Donnerstag 05 August 2010, Chris Withers wrote: >> But why only the request for auth credentials? > > for security reasons I suppose - make sure a human enters > the password Well yes, but what if you actually want to script it? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From smallpox911 at gmail.com Thu Aug 5 08:50:53 2010 From: smallpox911 at gmail.com (small Pox) Date: Thu, 5 Aug 2010 05:50:53 -0700 (PDT) Subject: *** Project for New American Python, Scheme, Emacs, Unix Century - TUTORIAL VIDEOS *** Message-ID: http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1 http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related http://www.youtube.com/watch?v=eVJxzJAU0nE From jonathan.fine1 at googlemail.com Thu Aug 5 09:07:32 2010 From: jonathan.fine1 at googlemail.com (jfine) Date: Thu, 5 Aug 2010 06:07:32 -0700 (PDT) Subject: A new syntax for writing tests References: Message-ID: On 5 Aug, 10:17, Jean-Michel Pichavant wrote: > Jonathan Fine wrote: > > Hi > > > I just discovered today anewsyntaxfor writing tests. ?The basic > > idea is to write a function that contains some statements, and run it > > via a decorator. ?I wonder if anyone had seen this pattern before, and > > how you feel about it. ?For myself, I quite like it. > > > Let's suppose we want to test this trivial (of course) class. > > ? ? class Adder(object): > > > ? ? ? ? def __init__(self): > > ? ? ? ? ? ? self.value = 0 > > > ? ? ? ? def plus(self, delta): > > ? ? ? ? ? ? self.value += delta > > > The test the class you need a runner. ?In this case it is quite simple. > > > ? ? def runner(script, expect): > > ? ? ? ? '''Create an adder, run script, expect value.''' > > > ? ? ? ? adder = Adder() > > ? ? ? ? script(adder) > > ? ? ? ? return adder.value > > > We can now create (and run if we wish) a test. ?To do this we write > > > ? ? @testit(runner, 4) > > ? ? def whatever(a): > > ? ? ? ? '''Two plus two is four.''' > > > ? ? ? ? a.plus(2) > > ? ? ? ? a.plus(2) > > > Depending on the exact value of the testit decorator (which in the end > > is up to you) we can store the test, or execute it immediately, or do > > something else. > > > The simplest implementation prints: > > ? ? OK: Two plus two is four. > > for this passing test, and > > ? ? Fail: Two plus four is five. > > ? ? ? expect 5 > > ? ? ? actual 6 > > for a test that fails. > > > Here is the testit decorator used to produce the above output: > > > ? ? def testit(runner, expect): > > ? ? ? ? '''Test statements decorator.''' > > > ? ? ? ? def next(script): > > ? ? ? ? ? ? actual = runner(script, expect) > > ? ? ? ? ? ? if actual == expect: > > ? ? ? ? ? ? ? ? print 'OK:', script.__doc__ > > ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? print 'Fail:', script.__doc__ > > ? ? ? ? ? ? ? ? print ' ?expect', expect > > ? ? ? ? ? ? ? ? print ' ?actual', actual > > > ? ? ? ? return next > > > You can pick this code, for at least the next 30 days, at > > ? ?http://dpaste.com/hold/225056/ > > > For me the key benefit is that writing the test is really easy. ? > > Here's a test I wrote earlier today. > > > @testit(runner, '''''') > > def whatever(tb): > > ? ? tb.start('a', {'att': 'value'}) > > ? ? tb.start('b') > > ? ? tb.end('b') > > ? ? tb.end('a') > > > If the test has a set-up and tear-down, this can be handled in the > > runner, as can the test script raising an expected or unexpected > > exception. > > Hi, > > "The unittest module provides a rich set of tools for constructing and > running tests. This section demonstrates that a small subset of the > tools suffice to meet the needs of most users." > > sourcehttp://docs.python.org/library/unittest.html > > As you can see, a much more featured test framework already exists. > > There's nothing wrong in anewtest framework, but it has to be better > than the existing one in some situations. Chalk and cheese. My concern is to make tests easy to write, and that is something that unittest is, in my view, not good at. It is, as you say, a *test framework*. I've not written a test framework. I've found what seems to be a new *syntax* for writing tests. Tests written in the new syntax can be run in the unittest (or any other) framework. -- Jonathan From gurudatta97 at gmail.com Thu Aug 5 09:12:48 2010 From: gurudatta97 at gmail.com (guru datta) Date: Thu, 5 Aug 2010 06:12:48 -0700 (PDT) Subject: ATTRACTIVE HOT PHOTOS&VIDEOS Message-ID: <4ca483a5-b928-4dab-9123-7e09bc26cbfb@l32g2000prn.googlegroups.com> AMISHAPATEL HOT BOOBS http://babes-devi.blogspot.com/2010/07/amishpatel-latest-photos.html ARCHANA UNSEENED EXPOSING PHOTOS http://babes-devi.blogspot.com/2010/07/archana-unseened-photos.html KATRINA KAIF HOT SEXY PHOTOS http://babes-devi.blogspot.com/2010/07/katrina-sexy-looking-photos.html THISHA HOT WET PHOTOS http://babes-devi.blogspot.com/2010/06/thrisha-hot-wet-photos.html SEXY CHARMI IN A BATHROOM http://babes-devi.blogspot.com/2010/06/charmi-in-bath.html KAJALAGARWAL IN A ROMANTIC FEEL http://babes-devi.blogspot.com/2010/06/kajal-hot-photos.html NAMITHA IN A BEACH http://babes-devi.blogspot.com/2010/06/nayagarala-namitha.html From invalid at invalid.invalid Thu Aug 5 09:32:26 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 5 Aug 2010 13:32:26 +0000 (UTC) Subject: subprocess escaping POpen?! References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> Message-ID: On 2010-08-05, Chris Withers wrote: > Wolfgang Rohdewald wrote: >> On Donnerstag 05 August 2010, Chris Withers wrote: >>> But why only the request for auth credentials? >> >> for security reasons I suppose - make sure a human enters >> the password > > Well yes, but what if you actually want to script it? Scripting passwords is considered a huge security hole, so people who care about security try to prevent it by doing things like reading passwords from /dev/tty instead of stdin. -- Grant Edwards grant.b.edwards Yow! I want my nose in at lights! gmail.com From jeanmichel at sequans.com Thu Aug 5 09:36:29 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 15:36:29 +0200 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AA75C.3080700@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <4C5AA2B8.3020806@sequans.com> <4C5AA75C.3080700@simplistix.co.uk> Message-ID: <4C5ABE5D.3040609@sequans.com> Chris Withers wrote: > Jean-Michel Pichavant wrote: >> You did not redirect stdin, so it is expected you can still read >> input from the console. > > Okay, so if I definitely wanted no input, what should I pass as the > stdin parameter to the POpen constructor? You do want an input don't you ? 'cause there is a password to enter. from subprocess doc page: "Note that if you want to send data to the process?s stdin, you need to create the Popen object with stdin=PIPE." > >> And it looks like svn is writting the credentials prompt on stderr. > > ...which, as you can see from the code I posted, is piped to STDOUT, > which is then PIPE'd through to the calling python so that > communicate()'s return value will contain the output. > > As I explained, I can't reproduce this by replacing svn with a simple > python script that writes to stderr. So, what is svn doing? You're right, then that means than svn is writing credentials neither on stdout nor stderr. > >> You may want to look at http://pysvn.tigris.org/docs/pysvn.html though. > > Yeah, we were using that, but found it excruciatingly painful due to > its dependency on a subversion source install due to its c extension. I can't argue with that. > > cheers, > > Chris > If you want to scriptly interract with svn or anything else, you may look at the pexpect module. JM From samwyse at gmail.com Thu Aug 5 09:44:30 2010 From: samwyse at gmail.com (samwyse) Date: Thu, 5 Aug 2010 06:44:30 -0700 (PDT) Subject: simple (I hope!) problem References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> <4c57b51c$0$28663$c3e8da3@news.astraweb.com> Message-ID: On Aug 5, 4:32?am, Jean-Michel Pichavant wrote: > samwyse wrote: > > On Aug 3, 1:20 am, Steven D'Aprano > T... at cybersource.com.au> wrote: > > >> On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote: > > >>> Fortunately, I don't need the functionality of the object, I just want > >>> something that won't generate an error when I use it. ?So, what is the > >>> quickest way to to create such an object (replacing the 'pass' in my > >>> first snippet). ?My solution is this: > > >>> ? ? class C: > >>> ? ? ? ? def filter(self, *args, **kwds): > >>> ? ? ? ? ? ? pass > >>> ? ? register = C() > > >>> but it seems like I should be able to do something "better", as measured > >>> by lines of code, faking more than just a 'filter' method, or both. ?Any > >>> ideas? ?Thanks! > > >> You want a variation on the Null Object design pattern. > > >> class NullWithMethods(object): > >> ? ? def __getattr__(self, name): > >> ? ? ? ? return self > >> ? ? def __call__(self, *args, **kwargs): > >> ? ? ? ? pass > > >> And in action: > > >>>>> c = NullWithMethods() > >>>>> c.spam("hello", "world") > >>>>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42) > > >> -- > >> Steven > > > JM emailed me a good solution, but yours is great! Thanks! > > The version I gave you overrides __getattribute__. To be honest, > overriding __getattr__ is a better solution.Just in case you don't know > the difference, __getattr__ is called only if the attribute is not found > while __getattribute__ is actually called to find the attribute. > > JM I have to apologize for not replying as soon as I got your email. It did everything I needed, so I implemented it in my code and went to town. Then, when I did finally return to the c.l.py, there was an solution that exceeded my needs by letting me chain together arbitrary lists of attributes. Now that I've slept on it, I've come up with a solution that I like even more: >>> class Placeholder(object): def __getattr__(self, name): return self def __getitem__(self, index): return self def __call__(self, *args, **kwargs): return self >>> x = Placeholder() >>> x('hello, world').y[42].z <__main__.Placeholder object at 0x01E46490> Yes, running it from the prompt looks ugly, but within a program the return value is silently discarded. From python.list at tim.thechases.com Thu Aug 5 09:46:28 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 05 Aug 2010 08:46:28 -0500 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xocdi56cp.fsf@ruckus.brouhaha.com> Message-ID: <4C5AC0B4.40604@tim.thechases.com> On 08/05/10 05:33, Lawrence D'Oliveiro wrote: > OK, I have a copy of K&R 2nd Ed on a shelf within reach here. Can you point > out some behaviour that C programmers might need to rely on, that is not > specified in that document? "need to" is considerably different from "might". Size of an int, assumptions that int=pointer, evaluation order of postfix increment/decrement... http://stackoverflow.com/questions/625333/how-to-limit-the-impact-of-implementation-dependent-language-features-in-c or http://tinyurl.com/263jayy if mailers between here & there break the URL) Just because facilities (macros, best-practices, etc) have been established for some of these things doesn't mean a programmer will reach for them if their code happens to work locally without them. Trust me...I've encountered PLENTY of such code in production before I left behind (for the most part) the world of C. -tkc From downaold at gmail.com Thu Aug 5 09:46:29 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 5 Aug 2010 15:46:29 +0200 Subject: abstract metaclass Message-ID: <1B034596-7B57-4950-8070-7685176A824E@gmail.com> Hi all, I'm trying to create a metaclass that keeps track of its objects, and implement this as a collections.MutableMapping. That is, something like this: class type2(type, MutableMapping): ... /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/abc.pyc in __new__(mcls, name, bases, namespace) 83 if getattr(value, "__isabstractmethod__", False)) 84 for base in bases: ---> 85 for name in getattr(base, "__abstractmethods__", set()): 86 value = getattr(cls, name, None) 87 if getattr(value, "__isabstractmethod__", False): TypeError: Error when calling the metaclass bases 'getset_descriptor' object is not iterable Anybody knows why? Every type is just an object, isn't it? Thanks in advance, cheers, Roald From kushal.kumaran at gmail.com Thu Aug 5 09:47:32 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 05 Aug 2010 19:17:32 +0530 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AB2CE.7040903@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> Message-ID: <1281016052.15056.5.camel@Nokia-N900> ----- Original message ----- > Wolfgang Rohdewald wrote: > > On Donnerstag 05 August 2010, Chris Withers wrote: > > > But why only the request for auth credentials? > > > > for security reasons I suppose - make sure a human enters > > the password > > Well yes, but what if you actually want to script it? > Then you use expect. See http://pexpect.sf.net for a python version. -- regards, kushal -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Thu Aug 5 09:52:24 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 15:52:24 +0200 Subject: A new syntax for writing tests In-Reply-To: References: Message-ID: <4C5AC218.4040803@sequans.com> jfine wrote: > On 5 Aug, 10:17, Jean-Michel Pichavant wrote: > >> Jonathan Fine wrote: >> >>> Hi >>> >>> I just discovered today anewsyntaxfor writing tests. The basic >>> idea is to write a function that contains some statements, and run it >>> via a decorator. I wonder if anyone had seen this pattern before, and >>> how you feel about it. For myself, I quite like it. >>> >>> Let's suppose we want to test this trivial (of course) class. >>> class Adder(object): >>> >>> def __init__(self): >>> self.value = 0 >>> >>> def plus(self, delta): >>> self.value += delta >>> >>> The test the class you need a runner. In this case it is quite simple. >>> >>> def runner(script, expect): >>> '''Create an adder, run script, expect value.''' >>> >>> adder = Adder() >>> script(adder) >>> return adder.value >>> >>> We can now create (and run if we wish) a test. To do this we write >>> >>> @testit(runner, 4) >>> def whatever(a): >>> '''Two plus two is four.''' >>> >>> a.plus(2) >>> a.plus(2) >>> >>> Depending on the exact value of the testit decorator (which in the end >>> is up to you) we can store the test, or execute it immediately, or do >>> something else. >>> >>> The simplest implementation prints: >>> OK: Two plus two is four. >>> for this passing test, and >>> Fail: Two plus four is five. >>> expect 5 >>> actual 6 >>> for a test that fails. >>> >>> Here is the testit decorator used to produce the above output: >>> >>> def testit(runner, expect): >>> '''Test statements decorator.''' >>> >>> def next(script): >>> actual = runner(script, expect) >>> if actual == expect: >>> print 'OK:', script.__doc__ >>> else: >>> print 'Fail:', script.__doc__ >>> print ' expect', expect >>> print ' actual', actual >>> >>> return next >>> >>> You can pick this code, for at least the next 30 days, at >>> http://dpaste.com/hold/225056/ >>> >>> For me the key benefit is that writing the test is really easy. >>> Here's a test I wrote earlier today. >>> >>> @testit(runner, '''''') >>> def whatever(tb): >>> tb.start('a', {'att': 'value'}) >>> tb.start('b') >>> tb.end('b') >>> tb.end('a') >>> >>> If the test has a set-up and tear-down, this can be handled in the >>> runner, as can the test script raising an expected or unexpected >>> exception. >>> >> Hi, >> >> "The unittest module provides a rich set of tools for constructing and >> running tests. This section demonstrates that a small subset of the >> tools suffice to meet the needs of most users." >> >> sourcehttp://docs.python.org/library/unittest.html >> >> As you can see, a much more featured test framework already exists. >> >> There's nothing wrong in anewtest framework, but it has to be better >> than the existing one in some situations. >> > > Chalk and cheese. > > My concern is to make tests easy to write, and that is something that > unittest is, in my view, not good at. It is, as you say, a *test > framework*. > > I've not written a test framework. I've found what seems to be a new > *syntax* for writing tests. Tests written in the new syntax can be > run in the unittest (or any other) framework. > > -- > Jonathan > > Well, I never used unittest, but the given example in the doc is pretty much simple. I'm still scratching my head. JM PS : I think your usage of 'syntax' is inapropriate. From jjposner at optimum.net Thu Aug 5 10:01:59 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 05 Aug 2010 10:01:59 -0400 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <4C5AC457.6010709@optimum.net> On 8/5/2010 12:33 AM, John Nagle wrote: > There's got to be a better way to do this: > > > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) > Here's a more elegant variant, using regexp lookahead: def thous_format(integer_string): """ add comma thousands separator(s) to an integer-valued string """ return re.sub(r'(\d{3})(?=\d)', r'\1,', integer_string[::-1])[::-1] I *thought* that I had found this on python-list on or about July 5, but I didn't find the thread after a search through the archives. -John From nanothermite911fbibustards at gmail.com Thu Aug 5 10:22:19 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Thu, 5 Aug 2010 07:22:19 -0700 (PDT) Subject: A portable LISP interpreter that includes all the major list-processing functions is described. A complete, annotated listing of the program's code, written in PASCAL, is included. References: <006adcc5-9b71-44d2-91b4-9a82e895aeb1@k19g2000yqc.googlegroups.com> <3616c873-bc13-4bb1-a7d9-fd3357f9f2b1@y32g2000prc.googlegroups.com> Message-ID: <95a6fab2-171f-4b69-a2b3-1494a5929eb1@w30g2000yqw.googlegroups.com> On Jul 24, 3:42?pm, Emmy Noether wrote: > On Jul 23, 9:27?pm, TheFlyingDutchman wrote: > > > > > On Jul 23, 12:06?pm, Emmy Noether wrote: > > > > Title ? PortableLISPinterpreter > > > Creator/Author ?Cox, L.A. Jr. ; Taylor, W.P. > > > Publication Date ? ? ? ?1978 May 31 > > > OSTI Identifier OSTI ID: 7017786 > > > Report Number(s) ? ? ? ?UCRL-52417 > > > DOE Contract Number ? ? W-7405-ENG-48 > > > Resource Type ? Technical Report > > > Research Org ? ?California Univ., Livermore (USA). Lawrence Livermore > > > Lab. > > > Subject 99 GENERAL AND MISCELLANEOUS//MATHEMATICS, COMPUTING, AND > > > INFORMATION SCIENCE; COMPUTER CODES; L CODES; COMPUTERS; PROGRAMMING; > > > PROGRAMMING LANGUAGES > > > Description/Abstract ? ?A portableLISPinterpreter that includes all the > > > major list-processing functions is described. A complete, annotated > > > listing of the program's code, written inPASCAL, is included. > > > Country of Publication ?United States > > > Language ? ? ? ?English > > > Format ?Medium: X; Size: Pages: 21 > > > Availability ? ?Dep. NTIS, PC A02/MF A01. > > > System Entry Date ? ? ? 2008 Feb 12 > > > Is this available online? If only in hardcopy form, do they lend it > > out? > > I am glad to share with everyone. However its useless without the > ability to compile and run. Also with text, its easy to read and > discuss the code which has a listing of 900 lines. > > I have already spent 4 hours scanning/processing to a stage where I > got a decent OCR which needs hand-verification of pages. I need 4 or 8 > volunteers depending on whether one want to do two pages each or 1 > page each. Its an hour of joyful work each for two pages. Explanation > are good quality. We will re-write to C, python etc. > > It must be edited in emacs in fundamental mode to overridepascalmode > indentation. Go topascalmode periodically to colorize to indicate > errors, and then revert before inserting anything. Stay close to the > original page. > > Email me to receive image and initial ocr and lots of fixes I did by > hand for more than 4hrs. Send only plain text message or it goes to > spam. > > Then we share with everyone here or put it on some site. > > E.N. http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1 http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related http://www.youtube.com/watch?v=eVJxzJAU0nE The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From chare at labr.net Thu Aug 5 10:26:14 2010 From: chare at labr.net (Chris Hare) Date: Thu, 05 Aug 2010 09:26:14 -0500 Subject: assigning variables from list data Message-ID: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> I have a database query result (see code below). In PHP, I would have said list(var1,var2,var) = $result and each element in the list would be assigned to each of the named variables. I have my data coming out of the database, and I can see it is a list. so my question is, instead of having to do the variable assignment as I have it here, is there a way more like PHP or am I stuck with it? import sqlite3 as sqlite try: print "connecting to disk db ..." conn = sqlite.connect("netcomm.db") except: print "oops" print "retrieving data" cursor = conn.cursor() cursor.execute('select * from net where NetNumber > 0') list = cursor.fetchone() print list print len(list) for item in list: print item netNumber = list[0] netType = list[1] netConditions = list[2] netStartLocal = list[3] NCS = list[4] NCS1 = list[5] RADAR = list[6] NetFreq = list[7] Repeater = list[8] Notes = list[9] From nanothermite911fbibustards at gmail.com Thu Aug 5 10:26:15 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Thu, 5 Aug 2010 07:26:15 -0700 (PDT) Subject: Fascinating interview by Richard Stallman on Russia TV References: <4db5e9a2-1d00-4b02-b988-17829a537aab@x27g2000yqb.googlegroups.com> <1f6bd9bb-f7c6-4d0c-9936-d51b881da156@s24g2000pri.googlegroups.com> <87iq4dmcsh.fsf@temporary-address.org.uk> <6MOdnZERJ9-Zd9_RnZ2dnUVZ7rSdnZ2d@bt.com> Message-ID: <4a0c24a8-1619-4ca9-93ea-ff6d8d9da1ec@c10g2000yqi.googlegroups.com> On Jul 18, 4:48?am, Richard Heathfield wrote: > Richard Heathfield > Email: -http://www. +rjh@ > "Usenet is a strange place" - dmr 29 July 1999 > Sig line vacant - apply within http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1 http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related http://www.youtube.com/watch?v=eVJxzJAU0nE The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From chris at simplistix.co.uk Thu Aug 5 10:38:27 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 15:38:27 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <1281016052.15056.5.camel@Nokia-N900> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> Message-ID: <4C5ACCE3.3080800@simplistix.co.uk> Kushal Kumaran wrote: > > ----- Original message ----- > > Wolfgang Rohdewald wrote: > > > On Donnerstag 05 August 2010, Chris Withers wrote: > > > > But why only the request for auth credentials? > > > > > > for security reasons I suppose - make sure a human enters > > > the password > > > > Well yes, but what if you actually want to script it? > > > > Then you use expect. > > See http://pexpect.sf.net for a python version. ...which doesn't work on Windows. Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From mail at timgolden.me.uk Thu Aug 5 10:48:53 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Aug 2010 15:48:53 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5ACCE3.3080800@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> Message-ID: <4C5ACF55.4090900@timgolden.me.uk> On 05/08/2010 15:38, Chris Withers wrote: > Kushal Kumaran wrote: >> >> ----- Original message ----- >> > Wolfgang Rohdewald wrote: >> > > On Donnerstag 05 August 2010, Chris Withers wrote: >> > > > But why only the request for auth credentials? >> > > >> > > for security reasons I suppose - make sure a human enters >> > > the password >> > >> > Well yes, but what if you actually want to script it? >> > >> >> Then you use expect. >> >> See http://pexpect.sf.net for a python version. > > ...which doesn't work on Windows. There is a winpexpect: http://pypi.python.org/pypi/winpexpect/1.3 TJG From chris at simplistix.co.uk Thu Aug 5 10:49:53 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 15:49:53 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5ACF55.4090900@timgolden.me.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> <4C5ACF55.4090900@timgolden.me.uk> Message-ID: <4C5ACF91.1050109@simplistix.co.uk> Tim Golden wrote: >>> See http://pexpect.sf.net for a python version. >> >> ...which doesn't work on Windows. > > There is a winpexpect: > > http://pypi.python.org/pypi/winpexpect/1.3 Are the two api-identical? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From benjamin.kaplan at case.edu Thu Aug 5 10:54:50 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 5 Aug 2010 07:54:50 -0700 Subject: assigning variables from list data In-Reply-To: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> References: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> Message-ID: On Thu, Aug 5, 2010 at 7:26 AM, Chris Hare wrote: > > I have a database query result (see code below). ?In PHP, I would have said > > list(var1,var2,var) = $result > > and each element in the list would be assigned to each of the named variables. ?I have my data coming out of the database, and I can see it is a list. ?so my question is, instead of having to do the variable assignment as I have it here, is there a way more like PHP or am I stuck with it? > > import sqlite3 as sqlite > > try: > ? ? ? ?print "connecting to disk db ..." > ? ? ? ?conn = sqlite.connect("netcomm.db") > except: > ? ? ? ?print "oops" > > print "retrieving data" > cursor = conn.cursor() > cursor.execute('select * from net where NetNumber > 0') > list = cursor.fetchone() > print list > print len(list) > for item in list: > ? ?print item > netNumber = list[0] > netType = list[1] > netConditions = list[2] > netStartLocal = list[3] > NCS = list[4] > NCS1 = list[5] > RADAR = list[6] > NetFreq = list[7] > Repeater = list[8] > Notes = list[9] > -- netNumber, netType, netConditions, netStartLocal, NCS, NCS1, RADAR, NetFreq, Repeater, Notes = list by the way, don't call the list "list". It will hide the built-in with the same name. > http://mail.python.org/mailman/listinfo/python-list > From mail at timgolden.me.uk Thu Aug 5 10:55:25 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Aug 2010 15:55:25 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5ACF91.1050109@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> <4C5ACF55.4090900@timgolden.me.uk> <4C5ACF91.1050109@simplistix.co.uk> Message-ID: <4C5AD0DD.4010809@timgolden.me.uk> On 05/08/2010 15:49, Chris Withers wrote: > Tim Golden wrote: >>>> See http://pexpect.sf.net for a python version. >>> >>> ...which doesn't work on Windows. >> >> There is a winpexpect: >> >> http://pypi.python.org/pypi/winpexpect/1.3 > > Are the two api-identical? From the bitbucket page: http://bitbucket.org/geertj/winpexpect/wiki/Home """ The API of winpexpect is identical to that of pexpect. The only difference is that you must use the class "winspawn" instead of "spawn" """ TJG From chris at simplistix.co.uk Thu Aug 5 10:56:20 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 15:56:20 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AD0DD.4010809@timgolden.me.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> <4C5ACF55.4090900@timgolden.me.uk> <4C5ACF91.1050109@simplistix.co.uk> <4C5AD0DD.4010809@timgolden.me.uk> Message-ID: <4C5AD114.1030004@simplistix.co.uk> Tim Golden wrote: > On 05/08/2010 15:49, Chris Withers wrote: >> Tim Golden wrote: >>>>> See http://pexpect.sf.net for a python version. >>>> >>>> ...which doesn't work on Windows. >>> >>> There is a winpexpect: >>> >>> http://pypi.python.org/pypi/winpexpect/1.3 >> >> Are the two api-identical? > > From the bitbucket page: > > http://bitbucket.org/geertj/winpexpect/wiki/Home > > """ > The API of winpexpect is identical to that of pexpect. > The only difference is that you must use the class "winspawn" > instead of "spawn" ...then why aren't they in the same fs&@ing package? ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From mail at timgolden.me.uk Thu Aug 5 10:56:51 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Aug 2010 15:56:51 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AD114.1030004@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> <4C5ACF55.4090900@timgolden.me.uk> <4C5ACF91.1050109@simplistix.co.uk> <4C5AD0DD.4010809@timgolden.me.uk> <4C5AD114.1030004@simplistix.co.uk> Message-ID: <4C5AD133.6010107@timgolden.me.uk> On 05/08/2010 15:56, Chris Withers wrote: > Tim Golden wrote: >> On 05/08/2010 15:49, Chris Withers wrote: >>> Tim Golden wrote: >>>>>> See http://pexpect.sf.net for a python version. >>>>> >>>>> ...which doesn't work on Windows. >>>> >>>> There is a winpexpect: >>>> >>>> http://pypi.python.org/pypi/winpexpect/1.3 >>> >>> Are the two api-identical? >> >> From the bitbucket page: >> >> http://bitbucket.org/geertj/winpexpect/wiki/Home >> >> """ >> The API of winpexpect is identical to that of pexpect. >> The only difference is that you must use the class "winspawn" >> instead of "spawn" > > ...then why aren't they in the same fs&@ing package? ;-) He does explain there that he hopes to have the changes merged upstream. Presumably it hasn't happened yet... TJG From python.list at tim.thechases.com Thu Aug 5 10:59:16 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 05 Aug 2010 09:59:16 -0500 Subject: assigning variables from list data In-Reply-To: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> References: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> Message-ID: <4C5AD1C4.6030900@tim.thechases.com> On 08/05/10 09:26, Chris Hare wrote: > I have a database query result (see code below). In PHP, I > would have said > > list(var1,var2,var) = $result > > and each element in the list would be assigned to each of the > named variables. I have my data coming out of the database, > and I can see it is a list. so my question is, instead of > having to do the variable assignment as I have it here, is > there a way more like PHP or am I stuck with it? > > cursor.execute('select * from net where NetNumber> 0') > list = cursor.fetchone() First off, I'd not mask the built-in "list", but you can use row = cursor.fetchone() if row: (netNumber, netType, netCond, netStLo, NCS, NCS1) = row else: print "No results" (just add in the right number of variables to which you want to assign to) -tkc From jonathan.fine1 at googlemail.com Thu Aug 5 11:06:03 2010 From: jonathan.fine1 at googlemail.com (jfine) Date: Thu, 5 Aug 2010 08:06:03 -0700 (PDT) Subject: A new syntax for writing tests References: Message-ID: <8ea4f012-d986-4936-af09-b3e08ee3d9f3@o19g2000yqb.googlegroups.com> On 5 Aug, 14:52, Jean-Michel Pichavant wrote: > jfine wrote: > > On 5 Aug, 10:17, Jean-Michel Pichavant wrote: > > >> Jonathan Fine wrote: > > >>> Hi > > >>> I just discovered today anewsyntaxfor writing tests. ?The basic > >>> idea is to write a function that contains some statements, and run it > >>> via a decorator. ?I wonder if anyone had seen this pattern before, and > >>> how you feel about it. ?For myself, I quite like it. > > >>> Let's suppose we want to test this trivial (of course) class. > >>> ? ? class Adder(object): > > >>> ? ? ? ? def __init__(self): > >>> ? ? ? ? ? ? self.value = 0 > > >>> ? ? ? ? def plus(self, delta): > >>> ? ? ? ? ? ? self.value += delta > > >>> The test the class you need a runner. ?In this case it is quite simple. > > >>> ? ? def runner(script, expect): > >>> ? ? ? ? '''Create an adder, run script, expect value.''' > > >>> ? ? ? ? adder = Adder() > >>> ? ? ? ? script(adder) > >>> ? ? ? ? return adder.value > > >>> We can now create (and run if we wish) a test. ?To do this we write > > >>> ? ? @testit(runner, 4) > >>> ? ? def whatever(a): > >>> ? ? ? ? '''Two plus two is four.''' > > >>> ? ? ? ? a.plus(2) > >>> ? ? ? ? a.plus(2) > > >>> Depending on the exact value of the testit decorator (which in the end > >>> is up to you) we can store the test, or execute it immediately, or do > >>> something else. > > >>> The simplest implementation prints: > >>> ? ? OK: Two plus two is four. > >>> for this passing test, and > >>> ? ? Fail: Two plus four is five. > >>> ? ? ? expect 5 > >>> ? ? ? actual 6 > >>> for a test that fails. > > >>> Here is the testit decorator used to produce the above output: > > >>> ? ? def testit(runner, expect): > >>> ? ? ? ? '''Test statements decorator.''' > > >>> ? ? ? ? def next(script): > >>> ? ? ? ? ? ? actual = runner(script, expect) > >>> ? ? ? ? ? ? if actual == expect: > >>> ? ? ? ? ? ? ? ? print 'OK:', script.__doc__ > >>> ? ? ? ? ? ? else: > >>> ? ? ? ? ? ? ? ? print 'Fail:', script.__doc__ > >>> ? ? ? ? ? ? ? ? print ' ?expect', expect > >>> ? ? ? ? ? ? ? ? print ' ?actual', actual > > >>> ? ? ? ? return next > > >>> You can pick this code, for at least the next 30 days, at > >>> ? ?http://dpaste.com/hold/225056/ > > >>> For me the key benefit is that writing the test is really easy. ? > >>> Here's a test I wrote earlier today. > > >>> @testit(runner, '''''') > >>> def whatever(tb): > >>> ? ? tb.start('a', {'att': 'value'}) > >>> ? ? tb.start('b') > >>> ? ? tb.end('b') > >>> ? ? tb.end('a') > > >>> If the test has a set-up and tear-down, this can be handled in the > >>> runner, as can the test script raising an expected or unexpected > >>> exception. > > >> Hi, > > >> "The unittest module provides a rich set of tools for constructing and > >> running tests. This section demonstrates that a small subset of the > >> tools suffice to meet the needs of most users." > > >> sourcehttp://docs.python.org/library/unittest.html > > >> As you can see, a much more featured test framework already exists. > > >> There's nothing wrong in anewtest framework, but it has to be better > >> than the existing one in some situations. > > > Chalk and cheese. > > > My concern is to make tests easy to write, and that is something that > > unittest is, in my view, not good at. ?It is, as you say, a *test > > framework*. > > > I've not written a test framework. ?I've found what seems to be anew > > *syntax* for writing tests. ?Tests written in thenewsyntaxcan be > > run in the unittest (or any other) framework. > > > -- > > Jonathan > > Well, I never used unittest, but the given example in the doc is pretty > much simple. > I'm still scratching my head. I think you'd understand better if you used unittest. For example, try coding my test (with say 10 distinct tests of a class more complicated than Adder) using unittest. I think you'll see the point when you get to number 5. Here, for reference, is my complete code for one test. See how it scales. http://dpaste.com/hold/225056/ (available for at least 30 days). -- Jonathan From pfinane at gmail.com Thu Aug 5 11:07:13 2010 From: pfinane at gmail.com (hrdublin) Date: Thu, 5 Aug 2010 08:07:13 -0700 (PDT) Subject: Are you Searching for a New IT or Telecoms Job? Message-ID: <664cd08f-1de3-4d33-bcd9-c4aacce14f8a@t20g2000yqa.googlegroups.com> Then start your Search here at JobPIMP JobPIMP is a Customised Search Engine that is crawling over 800+ Local and International Job Boards so you don't have to. JobPIMP is searching well known mainstream, niche, and less well known specialist job portals (your search results on one page). Click Link and Try JobPIMP Today http://www.directsource-network.com/jobpimphome.html It is 100% FREE!!! Or do a Google Search for "jobpimp" Find Us on Facebook http://www.facebook.com/DSN.ExpatJobs From none at none.com Thu Aug 5 11:15:48 2010 From: none at none.com (Brandon McCombs) Date: Thu, 05 Aug 2010 11:15:48 -0400 Subject: new to python - trouble calling a function from another function In-Reply-To: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> References: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> Message-ID: Jon Clements wrote: > On 5 Aug, 08:25, Brandon McCombs wrote: >> Hello, >> >> I'm building an elevator simulator for a class assignment. I recently >> ran into a roadblock and don't know how to fix it. For some reason, in >> my checkQueue function below, the call to self.goUp() is never executed. >> It is on the last line of code I pasted in. I can put print statements >> before and after the call and I have a print statement in goUp() itself. >> Only the print statements before and after the call are executed. The >> one inside goUp() is never executed because goUp() never seems to be >> executed. How can that be? I don't get any errors when the script >> executes. Surely this isn't some limitation I'm encountering? >> >> thanks >> >> sorry about the formatting >> >> --------------------------------------------- >> class Elevator(Process): >> def __init__(self,name): >> Process.__init__(self,name=name) >> self.numPassengers = 0 >> self.passengerList = [] >> self.passengerWaitQ = [] >> self.currentFloor = 1 >> self.idle = 1 >> self.newPassengers = 0 >> def goUp(self): >> print "here" >> bubbleSort(self.passengerList, len(self.passengerList)) >> self.currentFloor += 1 >> if len(self.passengerList) > 0: >> for p in self.passengerList: >> if self.currentFloor == p.destination: >> yield (p.destination - self.currenteFloor) * TRAVELTIME, self >> reactivate(p) >> p.inBuilding() >> else: >> self.goUp() >> >> def checkQueue(self): >> if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < >> MAXCAPACITY: >> if len(self.passengerWaitQ) < MAXCAPACITY: >> self.newPassengers = len(self.passengerWaitQ) >> else: >> self.newPassengers = MAXCAPACITY - len(self.passengerList) >> for i in range(0,self.newPassengers): >> self.passengerList.append(self.passengerWaitQ.pop()) >> self.goUp() > > Hi Brandon, > > Nice one at having a good crack at coding before posting! > > From your posted code, I'm struggling to see what's trying to be > taught to you for this class assignment. not relevant at this point > > As a note it'll be worth reading PEP 8 regarding naming conventions, > because it looks very Java-ish to me! ok but not relevant > > (I might be taking too much a real-world approach in the following, > but do with it as you will...) > > I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere. > Although what I'm thinking is that different Elevators will have > different capacities and different floors they service. An Elevator is > *not* going to know its number of passengers (the most it could do is > capacity based on weight restrictions) therefore it's not going to > know the number of new passengers on each floor either. okay but not relevant to the problem at hand > > A couple of things that'd be worthwhile: > > 1) Post the requirements for your assignment - what's it supposed to > output etc... that isn't relevant for determining at the python level why a function simply isn't being called > 2) Go find an elevator, take a pen and pad with you, and stand in it > for 30 mins or so, and see how the real thing deals with situations > and make notes. ie, does it queue requests, or decide to take the next > nearest floor, when does it stop and open etc...? > > hth > > Jon. > actually it doesn't help at all since you decided to focus on everything but my actual question of why a function call wasn't working but rather question the validity of the program itself From none at none.com Thu Aug 5 11:20:22 2010 From: none at none.com (Brandon McCombs) Date: Thu, 05 Aug 2010 11:20:22 -0400 Subject: new to python - trouble calling a function from another function In-Reply-To: <6pgqi7-unn.ln1@satorlaser.homedns.org> References: <6pgqi7-unn.ln1@satorlaser.homedns.org> Message-ID: Ulrich Eckhardt wrote: > Brandon McCombs wrote: >> I'm building an elevator simulator for a class assignment. I recently >> ran into a roadblock and don't know how to fix it. For some reason, in >> my checkQueue function below, the call to self.goUp() is never executed. > [...] >> sorry about the formatting > > While I can certainly forgive you the formatting (my problem is rather that > you didn't reduce the code to the smallest possible example so I missed a few lines, so sue me. ), Python wont. > Python is a language where whitespace is significant and can subtly change > the meaning of your code. > > Example: > >> for i in range(0,self.newPassengers): >> self.passengerList.append(self.passengerWaitQ.pop()) >> self.goUp() > > The formatting here is completely removed, but there are two conceivable > ways this could be formatted: already aware. I reformatted tabs to reduce the line wrap so it was easier for readers to read it. > > # variant 1 > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() > > #variant 2 > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() either one of those should still execute self.goUp(). I'm not getting anything though no matter where I place the function call. > > Someone already mentioned PEP 8 (search the web!). These PEPs could be > called the standards governing Python behaviour, and PEP 8 actually defines > several things concerning the formatting of sourcecode. Apply it unless you > have a good reason not to. > > > Further, you should run Python with "-t" as argument on the commandline. > This will give you warnings when it encounters inconsistent tab/spaces > usage. This can make a difference. Yeah I already tried that using 'tabnanny' I think it was called to diagnose one function that I decided to create and the -t option gave me false information. I determined that I had a tab in front of the function name (just like many others) however the actual fix was to put in spaces until it lined up with all the other 'def' lines. > > Example: > > #variant 3 > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() > > If your editor is set to four spaces per tab, this will look like variant 2, > with 8 spaces it will look like variant 1. I don't know (and don't care, > since PEP-8 mandates four spaces) which interpretation Python actually > uses. > > > Lastly, you can simplify your check_queue() function. First, determine the > number of free places inside the elevator. Then, you simply append that > many passengers from the waiting list to the passenger list: > > free = MAX_CAPACITY - len(self.passengers) > new_passengers = self.passenger_wait_queue[:free] > self.passenger_wait_queue = self.passenger_wait_queue[free:] > self.passengers += new_passengers > > This uses the fact that list indices are automatically truncated to a valid > range, so requesting the elements 0 to 10 from a 5-element list will only > yield those five elements, not raise an exception. It's up to you though > which version is clearer to you. I would perhaps bail out if "free == 0" > and then also not call go_up() lateron. > > so you made other recommendations but didn't address my original question unless I missed it somewhere. From eldiener at tropicsoft.invalid Thu Aug 5 11:31:08 2010 From: eldiener at tropicsoft.invalid (Edward Diener) Date: Thu, 05 Aug 2010 11:31:08 -0400 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 8/2/2010 5:42 PM, Mark Lawrence wrote: > On 02/08/2010 00:08, candide wrote: >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. >> >> Has it ever been planned to rewrite in C++ the historical implementation >> (of course in an object oriented design) ? > > I can't understand why any serious programmer mentions C++. As soon as I > read it, I have to rush either to the kitchen to find a bowl to throw up > in, or head for the toilet so I can talk to the great white telephone. It must be because we can not be as phenomenally intelligent as you evidently are from your comment. From tgrav at me.com Thu Aug 5 11:40:07 2010 From: tgrav at me.com (Tommy Grav) Date: Thu, 05 Aug 2010 11:40:07 -0400 Subject: new to python - trouble calling a function from another function In-Reply-To: References: <6pgqi7-unn.ln1@satorlaser.homedns.org> Message-ID: On Aug 5, 2010, at 11:20 AM, Brandon McCombs wrote: > so I missed a few lines, so sue me. The problem is that when you don't post a self contained example there is no proper way to answer your question, since the problem could be outside the part you posted. > already aware. I reformatted tabs to reduce the line wrap so it was easier for readers to read it. Never format code after you copy-paste it to your browser. This may change the behavior of your example making it impossible for people to help you. > either one of those should still execute self.goUp(). I'm not getting anything though no matter where I place the function call. Like someone said before. Try to create the smallest subset of your code that shows this behavior and copy-paste it to the list and people will try to help. Right now there is no clear answer from what you posted. Tommy From wherespythonmonks at gmail.com Thu Aug 5 11:42:06 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 5 Aug 2010 11:42:06 -0400 Subject: easy question on parsing python: "is not None" Message-ID: How does "x is not None" make any sense? "not x is None" does make sense. I can only surmise that in this context (preceding is) "not" is not a unary right-associative operator, therefore: x is not None === IS_NOTEQ(X, None) Beside "not in" which seems to work similarly, is there other syntactical sugar like this that I should be aware of? W From neilc at norwich.edu Thu Aug 5 11:42:48 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 5 Aug 2010 15:42:48 GMT Subject: new to python - trouble calling a function from another function References: Message-ID: <8c04foFkkuU1@mid.individual.net> On 2010-08-05, Brandon McCombs wrote: > class Elevator(Process): > def __init__(self,name): > Process.__init__(self,name=name) > self.numPassengers = 0 > self.passengerList = [] > self.passengerWaitQ = [] > self.currentFloor = 1 > self.idle = 1 > self.newPassengers = 0 > def goUp(self): > print "here" > bubbleSort(self.passengerList, len(self.passengerList)) > self.currentFloor += 1 > if len(self.passengerList) > 0: > for p in self.passengerList: > if self.currentFloor == p.destination: > yield (p.destination - self.currenteFloor) * TRAVELTIME, self > reactivate(p) > p.inBuilding() > else: > self.goUp() > > def checkQueue(self): > if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < > MAXCAPACITY: > if len(self.passengerWaitQ) < MAXCAPACITY: > self.newPassengers = len(self.passengerWaitQ) > else: > self.newPassengers = MAXCAPACITY - len(self.passengerList) > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() Does your program call checkQueue? -- Neil Cerutti From downaold at gmail.com Thu Aug 5 11:56:37 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 5 Aug 2010 17:56:37 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: > How does "x is not None" make any sense? "not x is None" does make > sense. > > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator, therefore: > > x is not None === IS_NOTEQ(X, None) > > Beside "not in" which seems to work similarly, is there other > syntactical sugar like this that I should be aware of? 'not None' first casts None to a bool, and then applies 'not', so 'x is not None' means 'x is True'. 'not x is None' is the same as 'not (x is None)' Cheers, Roald From jeanmichel at sequans.com Thu Aug 5 11:58:54 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 17:58:54 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: <4C5ADFBE.5090308@sequans.com> wheres pythonmonks wrote: > How does "x is not None" make any sense? "not x is None" does make sense. > > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator, therefore: > > x is not None === IS_NOTEQ(X, None) > > Beside "not in" which seems to work similarly, is there other > syntactical sugar like this that I should be aware of? > > W > x is not None === not (x is None). "is not" is an operator, not the combination of 2. JM From ben+python at benfinney.id.au Thu Aug 5 11:59:01 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 06 Aug 2010 01:59:01 +1000 Subject: easy question on parsing python: "is not None" References: Message-ID: <87sk2t1262.fsf@benfinney.id.au> wheres pythonmonks writes: > How does "x is not None" make any sense? In two ways: partly from the fact that Python syntax is preferentially designed to be reasonably readable to a native English reader; and partly because it makes for more obvious semantics. ?is not? is a single operator which makes operator precedence clear, and also ?x is not None? is gramatically good English. > "not x is None" does make sense. It unfortunately makes for awkward English, and it also makes for two separate operators and hence non-obvious operator precedence. > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator Rather than surmise, you can read the language reference which makes clear that ?is not? is one operator. -- \ ?I am amazed, O Wall, that you have not collapsed and fallen, | `\ since you must bear the tedious stupidities of so many | _o__) scrawlers.? ?anonymous graffiti, Pompeii, 79 CE | Ben Finney From wherespythonmonks at gmail.com Thu Aug 5 12:07:53 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 5 Aug 2010 12:07:53 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: Well, I am not convinced of the equivalence of not None and true: >>> not None True >>> 3 is True; False >>> 3 is not None True >>> P.S. Sorry for the top-post -- is there a way to not do top posts from gmail? I haven't used usenet since tin. On Thu, Aug 5, 2010 at 11:56 AM, Roald de Vries wrote: > On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: >> >> How does "x is not None" make any sense? ?"not x is None" does make sense. >> >> I can only surmise that in this context (preceding is) "not" is not a >> unary right-associative operator, therefore: >> >> x is not None === IS_NOTEQ(X, None) >> >> Beside "not in" which seems to work similarly, is there other >> syntactical sugar like this that I should be aware of? > > 'not None' first casts None to a bool, and then applies 'not', so 'x is not > None' means 'x is True'. > 'not x is None' is the same as 'not (x is None)' > > Cheers, Roald > -- > http://mail.python.org/mailman/listinfo/python-list > From carey.tilden at gmail.com Thu Aug 5 12:10:53 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Thu, 5 Aug 2010 09:10:53 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 8:42 AM, wheres pythonmonks wrote: > How does "x is not None" make any sense? ?"not x is None" does make sense. > > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator, therefore: > > x is not None === IS_NOTEQ(X, None) > > Beside "not in" which seems to work similarly, is there other > syntactical sugar like this that I should be aware of? In addition to all the other fine responses, you also might want to take a look at the python grammar [1]. The relevant line is: comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' Cheers, Carey [1] http://docs.python.org/reference/grammar.html From clp2 at rebertia.com Thu Aug 5 12:11:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 5 Aug 2010 09:11:59 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Thu, Aug 5, 2010 at 8:56 AM, Roald de Vries wrote: > On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: >> How does "x is not None" make any sense? ?"not x is None" does make sense. >> >> I can only surmise that in this context (preceding is) "not" is not a >> unary right-associative operator, therefore: >> >> x is not None === IS_NOTEQ(X, None) >> >> Beside "not in" which seems to work similarly, is there other >> syntactical sugar like this that I should be aware of? > > 'not None' first casts None to a bool, and then applies 'not', so 'x is not > None' means 'x is True'. Absolutely incorrect. Read the final paragraph of http://docs.python.org/reference/expressions.html#notin Cheers, Chris -- http://blog.rebertia.com From a.pfrengle at gmail.com Thu Aug 5 12:18:49 2010 From: a.pfrengle at gmail.com (Andreas Pfrengle) Date: Thu, 5 Aug 2010 09:18:49 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> <4C5A893C.6060807@sschwarzer.net> Message-ID: <7e8d94eb-7313-4f31-84b5-95874602697c@q22g2000yqm.googlegroups.com> Hello everyone, thanks for all the suggestions. I did effort to redesign parts of the data structure the last days, but not all (only those I could easily keep track of in my code). For the rest I add +1 before the presentation and comment it. Seems the easiest way now. Andreas From nikos.the.gr33k at gmail.com Thu Aug 5 12:31:18 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Thu, 5 Aug 2010 09:31:18 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format References: Message-ID: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> On 5 ???, 11:55, Dennis Lee Bieber wrote: > On Wed, 4 Aug 2010 16:40:45 -0700 (PDT), ????? > declaimed the following in > gmane.comp.python.general: > > > ? ? ? ? ? ? ? ? ? ?for entry in row: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ?entry = datetime.datetime.strftime( entry, '%d %b, %H:%M' ) #!!! > > this is wrong! > > ? ? ? ? ? ? ? ? ? ? ? ? ? ?print ( ''' ''' % entry ) > > > Apart from that i don't know how iam supposed to print it, because the > > date string is the 3rd string in every row of the dataset. > > ? ? ? ? As you state, it is the third item in each returned row... So why > are you trying to treat EVERY item in the row as a date? Because when i try to prin the 3 items liek that print row[0], row[1], row[2] it gives me an error, so i dont knwo how to tell it how to print the 3rd item differently. > > ? ? ? ? Since MySQLdb appears to return datetime objects (my quick test is > showing datetime.date for dates in a test database) you should be > probably be using > > ? ? ? ? formatted_entry = entry.strftime("%d... %M") I tried that myself yesterday but look it fails to the following message /home/webville/public_html/cgi-bin/index.py 63 64 for entry in row: 65 formatted_entry = entry.strftime('%d %b, %H:%M') 66 print ( ''' ''' % entry ) 67 formatted_entry undefined, entry = '178-124-186.dynamic.cyta.gr', entry.strftime undefined AttributeError: 'str' object has no attribute 'strftime' args = ("'str' object has no attribute 'strftime'",) From daniel.eliason at excite.com Thu Aug 5 12:31:30 2010 From: daniel.eliason at excite.com (fortunatus) Date: Thu, 5 Aug 2010 09:31:30 -0700 (PDT) Subject: A portable LISP interpreter that includes all the major list-processing functions is described. A complete, annotated listing of the program's code, written in PASCAL, is included. References: <006adcc5-9b71-44d2-91b4-9a82e895aeb1@k19g2000yqc.googlegroups.com> <3616c873-bc13-4bb1-a7d9-fd3357f9f2b1@y32g2000prc.googlegroups.com> Message-ID: On Jul 24, 6:42?pm, Emmy Noether wrote: > I have already spent 4 hours scanning/processing to a stage where I > got a decent OCR which needs hand-verification of pages. I need 4 or 8 > volunteers depending on whether one want to do two pages each or 1 > page each. Its an hour of joyful work each for two pages. Sheesh, if you just focussed on typing in, you could be done by now instead of fooling around with OCR and enlisting volunteers for something that amounts to the same beginner experiment that has been done 10,000 times: a fundamental Lisp interpreter. Don't get me wrong, it's a good experiment, but it really needn't require so much trouble... For that matter, why not write your own? Start by replicating McCarthy's group's initial interpreter... From clp2 at rebertia.com Thu Aug 5 12:32:47 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 5 Aug 2010 09:32:47 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 8:42 AM, wheres pythonmonks wrote: > How does "x is not None" make any sense? ?"not x is None" does make sense. > > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator, therefore: > > x is not None === IS_NOTEQ(X, None) > > Beside "not in" which seems to work similarly, is there other > syntactical sugar like this that I should be aware of? It's not quite the same type of sugar as that, but people sometimes forget that comparisons can be chained: if x < y <= z: Same as: if x < y and y <= z: # but y is only evaluated once Cheers, Chris From downaold at gmail.com Thu Aug 5 12:35:53 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 5 Aug 2010 18:35:53 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Aug 5, 2010, at 6:11 PM, Chris Rebert wrote: > On Thu, Aug 5, 2010 at 8:56 AM, Roald de Vries > wrote: >> On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: >>> How does "x is not None" make any sense? "not x is None" does >>> make sense. >>> >>> I can only surmise that in this context (preceding is) "not" is >>> not a >>> unary right-associative operator, therefore: >>> >>> x is not None === IS_NOTEQ(X, None) >>> >>> Beside "not in" which seems to work similarly, is there other >>> syntactical sugar like this that I should be aware of? >> >> 'not None' first casts None to a bool, and then applies 'not', so >> 'x is not >> None' means 'x is True'. > > Absolutely incorrect. Read the final paragraph of > http://docs.python.org/reference/expressions.html#notin Oops, sorry :$. From python at mrabarnett.plus.com Thu Aug 5 12:36:50 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 05 Aug 2010 17:36:50 +0100 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: <4C5AC457.6010709@optimum.net> References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <4C5AC457.6010709@optimum.net> Message-ID: <4C5AE8A2.1010902@mrabarnett.plus.com> John Posner wrote: > On 8/5/2010 12:33 AM, John Nagle wrote: >> There's got to be a better way to do this: >> >> >> def editmoney(n) : >> return((",".join(reduce(lambda lst, item : (lst + [item]) if >> item else lst, >> re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) >> > > Here's a more elegant variant, using regexp lookahead: > > def thous_format(integer_string): > """ > add comma thousands separator(s) to an integer-valued string > """ > return re.sub(r'(\d{3})(?=\d)', r'\1,', integer_string[::-1])[::-1] > > I *thought* that I had found this on python-list on or about July 5, but > I didn't find the thread after a search through the archives. > You don't need to reverse the string: def thous_format(integer_string): """ add comma thousands separator(s) to an integer-valued string """ return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string) From davea at ieee.org Thu Aug 5 13:03:41 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 05 Aug 2010 13:03:41 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <4C5AEEED.40409@ieee.org> Roald de Vries wrote: >
On Aug 5, > 2010, at 5:42 PM, wheres pythonmonks wrote: >> How does "x is not None" make any sense? "not x is None" does make >> sense. >> >> I can only surmise that in this context (preceding is) "not" is not a >> unary right-associative operator, therefore: >> >> x is not None === IS_NOTEQ(X, None) >> >> Beside "not in" which seems to work similarly, is there other >> syntactical sugar like this that I should be aware of? > > 'not None' first casts None to a bool, and then applies 'not', so 'x > is not None' means 'x is True'. > 'not x is None' is the same as 'not (x is None)' > > Cheers, Roald > Did you try it? Python 2.6.4 (r264:75706, Jan 22 2010, 16:41:54) [MSC v.1500 32 bit win32 Type "help", "copyright", "credits" or "license" for more informatio >>> 4 is not None True >>> True is not None True >>> False is not None True >>> None is not None False >>> Looks to me like x is not None is equivalent to not (x is None) (I get same results for 3.1) DaveA From ethan at stoneleaf.us Thu Aug 5 13:09:04 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 05 Aug 2010 10:09:04 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <4C5AF030.8000408@stoneleaf.us> Roald de Vries wrote: > On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: >> How does "x is not None" make any sense? "not x is None" does make >> sense. >> >> I can only surmise that in this context (preceding is) "not" is not a >> unary right-associative operator, therefore: >> >> x is not None === IS_NOTEQ(X, None) >> >> Beside "not in" which seems to work similarly, is there other >> syntactical sugar like this that I should be aware of? > > 'not None' first casts None to a bool, and then applies 'not', so 'x is > not None' means 'x is True'. This is not correct. 'is not' is a single operator, and in this case is checking that the object 'x' is not the same as the object 'None'. No boolean conversions are done -- False and True have nothing to do with this example. Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. --> x = 5 --> x is not None True --> x = True --> x is not None True --> x = ('this','is','a','tuple') --> x is not None True --> x = None --> x is not None False ~Ethan~ From landa.martin at gmail.com Thu Aug 5 13:50:21 2010 From: landa.martin at gmail.com (Martin Landa) Date: Thu, 5 Aug 2010 10:50:21 -0700 (PDT) Subject: ctypes: pointer to method Message-ID: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Hi, is it possible to pass pointer to a method using ctypes. Sample code: ... G_set_error_routine(byref(self._print_error)) ... def _print_error(self, msg, type): """!Redirect stderr""" self.log.write(msg) gives me G_set_error_routine(byref(self._print_error)) TypeError: byref() argument must be a ctypes instance, not 'instancemethod' C function G_set_error_routine is defined as void G_set_error_routine(int (*error_routine) (const char *, int)) Thanks in advance for any pointers. Martin From urban.dani at gmail.com Thu Aug 5 14:01:37 2010 From: urban.dani at gmail.com (Daniel Urban) Date: Thu, 5 Aug 2010 20:01:37 +0200 Subject: new to python - trouble calling a function from another function In-Reply-To: References: Message-ID: > I'm building an elevator simulator for a class assignment. I recently ran > into a roadblock and don't know how to fix it. For some reason, in my > checkQueue function below, the call to self.goUp() is never executed. It is > on the last line of code I pasted in. I can put print statements before and > after the call and I have a print statement in goUp() itself. ?Only the > print statements before and after the call are executed. The one inside > goUp() is never executed because goUp() never seems to be executed. How can > that be? I don't get any errors when the script executes. Surely this isn't > some limitation I'm encountering? I think the self.goUp() call is executed, the goUp function gets called, returns a generator object (because goUp is a generator function), then you don't use that generator object for anything. Daniel From no.email at nospam.invalid Thu Aug 5 14:10:04 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Thu, 05 Aug 2010 11:10:04 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xocdi56cp.fsf@ruckus.brouhaha.com> Message-ID: <7xmxt1kk1v.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > OK, I have a copy of K&R 2nd Ed on a shelf within reach here. Can you point > out some behaviour that C programmers might need to rely on, that is not > specified in that document? C has all kinds of undefined behavior. "Might need to rely on" is not relevant for this kind of issue. Ada's designers had the goal that that Ada programs should have NO undefined behavior. As a famous example of C's underspecification, the behavior of a[i++] = i; is undefined in C99. See: https://www.securecoding.cert.org/confluence/display/seccode/EXP30-C.+Do+not+depend+on+order+of+evaluation+between+sequence+points From andresen.nils at googlemail.com Thu Aug 5 14:26:52 2010 From: andresen.nils at googlemail.com (Nils) Date: Thu, 5 Aug 2010 11:26:52 -0700 (PDT) Subject: pre-uninstall script in bdist_wininst Message-ID: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> Hi. I am using a postinstall-script like this: setup( ... scripts=['scripts\install.py'], options = { ... "bdist_wininst" : { "install_script" : "install.py", ... }, } ) According to the docs in [1] this script is a) called after install (with the "-install" parameter) - this works fine for me... b) called before uninstall (with tho "-remove" parameter) - this however does not work. Can someone please point me to the direction on how to get a pre- uninstall script working? btw: With that I am trying to register a com-server on install and de- register on uninstall - so if other ideas are around I'd love to hear them, too... Nils From andresen.nils at googlemail.com Thu Aug 5 14:31:31 2010 From: andresen.nils at googlemail.com (Nils) Date: Thu, 5 Aug 2010 11:31:31 -0700 (PDT) Subject: pre-uninstall script in bdist_wininst References: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> Message-ID: On 5 Aug., 20:26, Nils wrote: > According to the docs in [1] [...] and with [1] I meant http://docs.python.org/distutils/builtdist.html#the-postinstallation-script Nils From jjposner at optimum.net Thu Aug 5 14:31:40 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 05 Aug 2010 14:31:40 -0400 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <4C5AC457.6010709@optimum.net> Message-ID: <4C5B038C.8000208@optimum.net> On 8/5/2010 12:36 PM, MRAB wrote: > You don't need to reverse the string: > > def thous_format(integer_string): > """ > add comma thousands separator(s) to an integer-valued string > """ > return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string) Nice! My first encounter with a look-behind! It appears that a slight simplification is possible: return re.sub(r"(?<=\d)(?=(\d\d\d)+$)", ",", integer_string) There no harm in putting \d\d\d into a group, though the group is never used. -John From jjposner at optimum.net Thu Aug 5 14:31:40 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 05 Aug 2010 14:31:40 -0400 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <4C5AC457.6010709@optimum.net> Message-ID: <4C5B038C.8000208@optimum.net> On 8/5/2010 12:36 PM, MRAB wrote: > You don't need to reverse the string: > > def thous_format(integer_string): > """ > add comma thousands separator(s) to an integer-valued string > """ > return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string) Nice! My first encounter with a look-behind! It appears that a slight simplification is possible: return re.sub(r"(?<=\d)(?=(\d\d\d)+$)", ",", integer_string) There no harm in putting \d\d\d into a group, though the group is never used. -John From nikos.the.gr33k at gmail.com Thu Aug 5 14:52:58 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Thu, 5 Aug 2010 11:52:58 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> Message-ID: <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> Hey i made it! :-) dataset = cursor.fetchall() for row in dataset: print ( '''
''' ) date = row[2].strftime( '%d %b, %H:%M' ) print ( ''' ''' % ( row[0], row[1], date ) ) Unfortunately had to ditch the 'for entry in row' line because couldn't iterate over the items of the row. Could you please shoe me how could i do the same thing with iteration?! Thanks! From python.list at tim.thechases.com Thu Aug 5 15:09:52 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 05 Aug 2010 14:09:52 -0500 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> Message-ID: <4C5B0C80.6080406@tim.thechases.com> On 08/05/10 13:52, ????? wrote: > dataset = cursor.fetchall() > > for row in dataset: > print ( ''' ''' ) > > date = row[2].strftime( '%d %b, %H:%M' ) > > print ( ''' ''' % > ( row[0], row[1], date ) ) > > Unfortunately had to ditch the 'for entry in row' line because > couldn't iterate over the items of the row. > > Could you please shoe me how could i do the same thing with > iteration?! Well, depending on whether "row" is a tuple or a list, you can do either row[2] = row[2].strftime(...) # if it's a list # the assignment will fail if it's a tuple or you can just iterate over a predefined list/tuple: for row in dataset: print ("") for item in (row[0], row[1], row[2].strftime(...)): print ("") for item in (host, hits, dt.strftime(...)): print ("" % item) print ("") Or perhaps even just print ("".join("" % item for item in (host, hits, dt.strftime(...)) ) Whichever you prefer. I think I'm partial to the 2nd-from-last version, especially as the list of fields may grow. -tkc From nobody at nowhere.com Thu Aug 5 15:19:42 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 05 Aug 2010 20:19:42 +0100 Subject: subprocess escaping POpen?! References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> Message-ID: On Thu, 05 Aug 2010 12:23:35 +0100, Chris Withers wrote: >>> ...then the output is indeed captured. So, what is svn doing >>> differently? How is it escaping its jail? >> >> maybe it does not read from stdin but directly from /dev/tty > > But why only the request for auth credentials? So that you can do e.g.: ssh remotehost command arg arg ... outfile From nobody at nowhere.com Thu Aug 5 15:32:25 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 05 Aug 2010 20:32:25 +0100 Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Message-ID: On Thu, 05 Aug 2010 10:50:21 -0700, Martin Landa wrote: > is it possible to pass pointer to a method using ctypes. I don't know about methods, but it works for functions. > Sample code: > > ... > G_set_error_routine(byref(self._print_error)) This won't work; you have to be more explicit, e.g.: errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int)) errfunc = errtype(print_error) G_set_error_routine(errfunc) NOTE: be sure to keep a reference to the wrapper, as ctypes doesn't hold references itself. IOW, you can't replace the above with: errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int)) G_set_error_routine(errtype(print_error)) If you do this, the wrapper is eligible for garbage collection as soon as G_set_error_routine() returns, and will probably have vanished by the time that G_fatal_error() gets called. For more information see: http://docs.python.org/library/ctypes.html#callback-functions From britt.snodgrass at gmail.com Thu Aug 5 16:35:01 2010 From: britt.snodgrass at gmail.com (Britt) Date: Thu, 5 Aug 2010 13:35:01 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On Aug 1, 9:34?pm, Albert Hopkins wrote: > On Mon, 2010-08-02 at 01:08 +0200, candide wrote: > > I would propose that in fact most programming languages are implemented > in C. ?Sun's (Oracle's) Java compiler and runtime are written in ANSI C. > The core of the Gnu Compiler Collection (which includes C++ and > Objective-C compilers) is written in C. The open-source GCC Ada compiler (GNAT) is written in Ada. The GPL'd compiler source code is available at http://libre.adacore.com/libre/ From nikos.the.gr33k at gmail.com Thu Aug 5 17:01:28 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Thu, 5 Aug 2010 14:01:28 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> Message-ID: >On 5 ???, 22:09, Tim Chase wrote: > On 08/05/10 13:52, ????? wrote: > > > dataset = cursor.fetchall() > > > for row in dataset: > > ? ? ?print ( ''' ?''' ) As i have it the returned 'dataset' is stored line per line to 'row'. So, 'dataset' in here is a 'list of tuples' right? and 'row' in here is a tuple form the above list of tuples right? Am i understanding this correctly?! > Well, depending on whether "row" is a tuple or a list, you can do > either It was a tuple. But it migth as well be a list too?!?! Could 'dataset' be a 'list of lists' as well? How one would know in which way the returned mysql data is saved in? > Though I think I'd make it a bit clearer by naming the fields: > > ? ?for host, hits, dt in dataset: > ? ? ?print ("") > ? ? ?for item in (host, hits, dt.strftime(...)): > ? ? ? ?print ("" % item) > ? ? ?print ("") Cool! I myself like this solution best over the all working other! very nice approach thank you very much! Is what i anted and couldn't write myself! But please tell me if in my example 'row' was a tuple, what kind of objects is 'host', 'hits', 'dt' here and how do they sore the data? Thanks again for the cool examples! From __peter__ at web.de Thu Aug 5 17:13:10 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Aug 2010 23:13:10 +0200 Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <4c5a7682$0$11096$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Thu, 05 Aug 2010 00:22:57 -0700, geremy condra wrote: > >>>>>> locale.setlocale(locale.LC_ALL, "") >>> 'de_DE.UTF-8' >>>>>> print locale.currency(13535, grouping=True) >>> 13.535,00 ? >>>>>> print locale.format("%d", 13535, grouping=True) >>> 13.535 >>> >>> Peter >> >> I had literally no idea this existed. Thanks. > > I knew it existed, but completely forgot about it. > > Thanks also Peter. You're welcome! From cs at zip.com.au Thu Aug 5 18:10:12 2010 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 6 Aug 2010 08:10:12 +1000 Subject: avoiding top posts in gmail [was easy question on parsing python: "is not None"] In-Reply-To: References: Message-ID: <20100805221012.GA30332@cskk.homeip.net> On 05Aug2010 12:07, wheres pythonmonks wrote: | P.S. Sorry for the top-post -- is there a way to not do top posts from | gmail? I haven't used usenet since tin. The standard way is with attitude: view having your cursor at the top not as forcing you to top post but as an opportunity to start pruning the quoted text to leave only the relevant bits. And as you prune, you stick your reply text below the relevant quoted text that remains, with a blank line between. I spent a few months in a strongly GMail workplace with technical people who produced nicely interleaved/pruned/bottom posted conversations this way all the time. Works well. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ To be or not to be? Not to be. - John Slater (Arnold Schwartzenegger), _Macbeth_ (_The_Last_Action_Hero_) From chare at labr.net Thu Aug 5 18:41:36 2010 From: chare at labr.net (Chris Hare) Date: Thu, 05 Aug 2010 17:41:36 -0500 Subject: defining, raising and catching exceptions Message-ID: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> I have a block of test code, where I am trying to raise and catch my own user defined exception class NetActiveError(RuntimeError): def __init__(self,error): self.args = error def a(): try: fh = open("me.txt", "r") except Exception as (errno, errText): print errText try: b() except NetActiveError as (errono, errText): print errno, errText def b(): print "def b" raise NetActiveError,"net already running" a() When I run it though, I get the following error: chare$ python z No such file or directory def b Traceback (most recent call last): File "z", line 20, in a() File "z", line 12, in a except NetActiveError as (errono, errText): ValueError: too many values to unpack What am I doing wrong here? From benjamin.kaplan at case.edu Thu Aug 5 18:44:07 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 5 Aug 2010 15:44:07 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Thu, Aug 5, 2010 at 9:07 AM, wheres pythonmonks wrote: > Well, I am not convinced of the equivalence of not None and true: > >>>> not None > True >>>> 3 is True; > False >>>> 3 is not None > True >>>> > > P.S. Sorry for the top-post -- is there a way to not do top posts from > gmail? ?I haven't used usenet since tin. > Scroll down in the email and press enter a few times. From benjamin.kaplan at case.edu Thu Aug 5 18:49:38 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 5 Aug 2010 15:49:38 -0700 Subject: defining, raising and catching exceptions In-Reply-To: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> Message-ID: What makes you think it has to do with user-defined exceptions? >>> try : ... raise Exception("hello") ... except Exception as (errno, errText) : ... print "whatever" ... Traceback (most recent call last): ValueError: need more than 1 values to unpack An Exception is an object, not a tuple of number and text. Raise an instance of the exception, not the class: raise NetActiveError("net already running") And then catch the exception object except NetActiveError as err: print err.args On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare wrote: > > I have a block of test code, where I am trying to raise and catch my own user defined exception > > class NetActiveError(RuntimeError): > ? ?def __init__(self,error): > ? ? ? ?self.args = error > > def a(): > ? ?try: > ? ? ? ?fh = open("me.txt", "r") > ? ?except Exception as (errno, errText): > ? ? ? ?print errText > ? ?try: > ? ? ? ?b() > ? ?except NetActiveError as (errono, errText): > ? ? ? ?print errno, errText > > def b(): > ? ?print "def b" > ? ?raise NetActiveError,"net already running" > > > a() > > > When I run it though, I get the following error: > > chare$ python z > No such file or directory > def b > Traceback (most recent call last): > ?File "z", line 20, in > ? ?a() > ?File "z", line 12, in a > ? ?except NetActiveError as (errono, errText): > ValueError: too many values to unpack > > > What am I doing wrong here? > > > -- > http://mail.python.org/mailman/listinfo/python-list > From nyamatongwe+thunder at gmail.com Thu Aug 5 18:59:28 2010 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 06 Aug 2010 08:59:28 +1000 Subject: Why is python not written in C++ ? In-Reply-To: <7xmxt1kk1v.fsf@ruckus.brouhaha.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xocdi56cp.fsf@ruckus.brouhaha.com> <7xmxt1kk1v.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > C has all kinds of undefined behavior. "Might need to rely on" is not > relevant for this kind of issue. Ada's designers had the goal that that > Ada programs should have NO undefined behavior. Ada achieves this by describing a long list of implementation defined behaviour (Annex M). http://oopweb.com/Ada/Documents/Ada95RM/Volume/m.htm > As a famous example of C's underspecification, the behavior of > > a[i++] = i; > > is undefined in C99. Ada does not define ordering in all cases either. For example the order of elaboration of library_items (essentially the order in which modules are run in the absence of explicit declarations) is defined for GNAT as """ first elaborating bodies as early as possible (i.e. in preference to specs where there is a choice), and second by evaluating the immediate with clauses of a unit to determine the probably best choice, and third by elaborating in alphabetical order of unit names where a choice still remains """ Other compilers use different orders. I just love that "probably". Neil From rhodri at wildebst.demon.co.uk Thu Aug 5 19:15:38 2010 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Fri, 06 Aug 2010 00:15:38 +0100 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks wrote: > Well, I am not convinced of the equivalence of not None and true: > >>>> not None > True >>>> 3 is True; > False >>>> 3 is not None > True >>>> You're not testing for equivalence there, you're testing for identity. "is" and "is not" test whether the two objects concerned are (or are not) the same object. Two objects can have the same value, but be different objects. The interpreter can fool you by caching and reusing objects which have the same value when it happens to know about it, in particular for small integers, but this is just a happy accident of the implementation and in no way guaranteed by the language. For example: >>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" True >>> a = "spam, eggs, chips and spam" >>> b = "spam, eggs, chips and spam" >>> a is b False >>> a == b True Also, remember that "is not" is a single operator, *not* the concatenation of "is" and "not". Your last test is probably not checking what you think it is :-) >>> 3 is (not None) False -- Rhodri James *-* Wildebeest Herder to the Masses From chare at labr.net Thu Aug 5 19:21:27 2010 From: chare at labr.net (Chris Hare) Date: Thu, 05 Aug 2010 18:21:27 -0500 Subject: defining, raising and catching exceptions In-Reply-To: References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> Message-ID: <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> okay - but why does the response come back like No such file or directory def b ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 'n', 'i', 'n', 'g') On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote: > What makes you think it has to do with user-defined exceptions? > >>>> try : > ... raise Exception("hello") > ... except Exception as (errno, errText) : > ... print "whatever" > ... > Traceback (most recent call last): > ValueError: need more than 1 values to unpack > > An Exception is an object, not a tuple of number and text. > > Raise an instance of the exception, not the class: > > raise NetActiveError("net already running") > > And then catch the exception object > > except NetActiveError as err: > print err.args > > On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare wrote: >> >> I have a block of test code, where I am trying to raise and catch my own user defined exception >> >> class NetActiveError(RuntimeError): >> def __init__(self,error): >> self.args = error >> >> def a(): >> try: >> fh = open("me.txt", "r") >> except Exception as (errno, errText): >> print errText >> try: >> b() >> except NetActiveError as (errono, errText): >> print errno, errText >> >> def b(): >> print "def b" >> raise NetActiveError,"net already running" >> >> >> a() >> >> >> When I run it though, I get the following error: >> >> chare$ python z >> No such file or directory >> def b >> Traceback (most recent call last): >> File "z", line 20, in >> a() >> File "z", line 12, in a >> except NetActiveError as (errono, errText): >> ValueError: too many values to unpack >> >> >> What am I doing wrong here? >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list From roy at panix.com Thu Aug 5 19:45:50 2010 From: roy at panix.com (Roy Smith) Date: Thu, 05 Aug 2010 19:45:50 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message , Roy Smith wrote: > > > C++, for all its flaws, had one powerful feature which made it very > > popular. It is a superset of C. > > Actually, it never was. Yes, there are a few corner cases where valid C syntax has different semantics in C and C++. But, they are very few. Calling C++ a superset of C is essentially correct. It is certainly correct from the level of a risk-averse development manager deciding if he or she is willing to use C++ for the first time. Fear of the unknown is a powerful deterrent. It's a lot easier to accept something like C++ because "it's just a superset of C, and we've been using C for years". I suspect the same effect contributed to Java's success as well. "Look, it's got curly braces and semicolons. It's just like C!" From python.list at tim.thechases.com Thu Aug 5 19:46:54 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 05 Aug 2010 18:46:54 -0500 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> Message-ID: <4C5B4D6E.1070501@tim.thechases.com> On 08/05/10 16:01, ????? wrote: >> On 5 ???, 22:09, Tim Chase wrote: >>> dataset = cursor.fetchall() >> >>> for row in dataset: >>> print ( ''' ''' ) > > So, 'dataset' in here is a 'list of tuples' right? and 'row' > in here is a tuple form the above list of tuples right? > > Am i understanding this correctly?! > > It was a tuple. But it migth as well be a list too?!?! > > Could 'dataset' be a 'list of lists' as well? Pretty much...it's either a list-of-tuples or a list-of-lists (I'm not sure if is part of the DB-API spec to mandate one or the other). For the most part, you can treat them as the same thing. However, tuples are immutable, so you can't say my_tuple[3] = some_value but with a list you can: my_list[3] = some_value > How one would know in which way the returned mysql data is saved in? Well, you can ask: print type(row) (I *suspect* it's a tuple) or you can just tell it what to be: for row in dataset: row = list(row) row[3] = row[3].strftime(...) for item in row: ... I don't usually have cause to write a value back into the data I'm reading from the DB, so it's never really mattered to me whether the DB gives me tuples or lists. >> Though I think I'd make it a bit clearer by naming the fields: >> >> for host, hits, dt in dataset: >> print ("") >> for item in (host, hits, dt.strftime(...)): >> print ("" % item) >> print ("") > > Cool! I myself like this solution best over the all working other! > very nice approach thank you very much! Is what i anted and couldn't > write myself! > > But please tell me if in my example 'row' was a tuple, what kind of > objects is 'host', 'hits', 'dt' here and how do they sore the data? Python supports "tuple assignment" which means that the following are about[*] the same: # variant A for row in dataset: host = row[0] hits = row[1] dt = row[2] # rest of your code here # variant B for row in dataset: host, hits, dt = row # rest of your code here # variant C for host, hits, dt in row: # rest of your code here The data-type of the individual values would be whatever comes back from the database as translated into Python (string, float/Decimal, boolean, datetime, etc). In your example, it's likely a string+integer+datetime as the 3 values. You can see why I prefer the elegance of just performing the assignment in the for-loop (variant C). Hope this helps, -tkc [*] "about" the same because in #1 and #2, you also have access to the whole row; whereas in #3, you don't have something called "row", but you could reassemble it if you needed: row = (host, hits, dt) From python at mrabarnett.plus.com Thu Aug 5 20:37:17 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 06 Aug 2010 01:37:17 +0100 Subject: defining, raising and catching exceptions In-Reply-To: <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> Message-ID: <4C5B593D.3090505@mrabarnett.plus.com> Chris Hare wrote: > okay - but why does the response come back like > > No such file or directory > def b > ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 'n', 'i', 'n', 'g') > The class Exception saves its arguments in the 'args' instance attribute, and when it prints the exception it prints those arguments: >>> e = Exception(1, 2, 3) >>> print e.args (1, 2, 3) >>> print e (1, 2, 3) >>> print repr(e) Exception(1, 2, 3) NetActiveError inherits from RuntimeError, and ultimately from Exception. NetActiveError sets the 'args' attribute to its single string argument, and when the exception is printed out it thinks it's the arguments: >>> e.args = "string" >>> print e ('s', 't', 'r', 'i', 'n', 'g') >>> print repr(e) Exception('s', 't', 'r', 'i', 'n', 'g') The correct way to create your own exceptions is to call the superclass's __init__ method: >>> class NetActiveError(RuntimeError): ... def __init__(self, error): ... RuntimeError.__init__(self, error) ... >>> e = NetActiveError("string") >>> print e string >>> print repr(e) NetActiveError('string',) > > On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote: > >> What makes you think it has to do with user-defined exceptions? >> >>>>> try : >> ... raise Exception("hello") >> ... except Exception as (errno, errText) : >> ... print "whatever" >> ... >> Traceback (most recent call last): >> ValueError: need more than 1 values to unpack >> >> An Exception is an object, not a tuple of number and text. >> >> Raise an instance of the exception, not the class: >> >> raise NetActiveError("net already running") >> >> And then catch the exception object >> >> except NetActiveError as err: >> print err.args >> >> On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare wrote: >>> I have a block of test code, where I am trying to raise and catch my own user defined exception >>> >>> class NetActiveError(RuntimeError): >>> def __init__(self,error): >>> self.args = error >>> >>> def a(): >>> try: >>> fh = open("me.txt", "r") >>> except Exception as (errno, errText): >>> print errText >>> try: >>> b() >>> except NetActiveError as (errono, errText): >>> print errno, errText >>> >>> def b(): >>> print "def b" >>> raise NetActiveError,"net already running" >>> >>> >>> a() >>> >>> >>> When I run it though, I get the following error: >>> >>> chare$ python z >>> No such file or directory >>> def b >>> Traceback (most recent call last): >>> File "z", line 20, in >>> a() >>> File "z", line 12, in a >>> except NetActiveError as (errono, errText): >>> ValueError: too many values to unpack >>> >>> >>> What am I doing wrong here? >>> From wolftracks at invalid.com Thu Aug 5 20:55:30 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 17:55:30 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem Message-ID: It's been awhile since I've used python, and I recall there is a way to find the version number from the IDLE command line prompt. dir, help, __version.__? I made the most minimal change to a program, and it works for me, but not my partner. He gets Traceback (most recent call last): File "C:\Documents and Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", line 40, in from scipy import stats as stats # scoreatpercentile File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, in from stats import * File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, in import scipy.special as special File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 22, in from numpy.testing import NumpyTest ImportError: cannot import name NumpyTest Here are the first few lines of code. import sys, os, glob import string from numpy import * from datetime import datetime, timedelta import time from scipy import stats as stats # scoreatpercentile I'm pretty sure he has the same version of Python, 2.5, but perhaps not the numpy or scipy modules. I need to find out his version numbers. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet From steve at REMOVE-THIS-cybersource.com.au Thu Aug 5 21:13:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 01:13:11 GMT Subject: [Tutor] Finding the version # of a module, and py module problem References: Message-ID: <4c5b61a7$0$28666$c3e8da3@news.astraweb.com> On Thu, 05 Aug 2010 17:55:30 -0700, W. eWatson wrote: > I'm pretty sure he has the same version of Python, 2.5, but perhaps not > the numpy or scipy modules. I need to find out his version numbers. It's only a convention, but the usual way is to check the __version__ attribute. It works for Numpy: >>> import numpy >>> numpy.__version__ '1.0.3' -- Steven From python at mrabarnett.plus.com Thu Aug 5 21:23:51 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 06 Aug 2010 02:23:51 +0100 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: <4C5B6427.6000001@mrabarnett.plus.com> W. eWatson wrote: > It's been awhile since I've used python, and I recall there is a way to > find the version number from the IDLE command line prompt. dir, help, > __version.__? > > I made the most minimal change to a program, and it works for me, but > not my partner. He gets > > Traceback (most recent call last): > File "C:\Documents and > Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", > line 40, in > from scipy import stats as stats # scoreatpercentile > File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, > in > from stats import * > File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, > in > import scipy.special as special > File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line > 22, in > from numpy.testing import NumpyTest > ImportError: cannot import name NumpyTest > > Here are the first few lines of code. > > import sys, os, glob > import string > from numpy import * > from datetime import datetime, timedelta > import time > from scipy import stats as stats # scoreatpercentile > > I'm pretty sure he has the same version of Python, 2.5, but perhaps not > the numpy or scipy modules. I need to find out his version numbers. > Try: import numpy help(numpy.version) BTW, on Python 2.6 I can see that there's "numpytest" but not "NumpyTest". From steve at REMOVE-THIS-cybersource.com.au Thu Aug 5 21:26:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 01:26:42 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: > P.S. Sorry for the top-post -- is there a way to not do top posts from > gmail? I haven't used usenet since tin. Er, surely you can just move the cursor before you start typing??? -- Steven From chare at labr.net Thu Aug 5 21:28:45 2010 From: chare at labr.net (Chris Hare) Date: Thu, 05 Aug 2010 20:28:45 -0500 Subject: defining, raising and catching exceptions In-Reply-To: <4C5B593D.3090505@mrabarnett.plus.com> References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> <4C5B593D.3090505@mrabarnett.plus.com> Message-ID: On Aug 5, 2010, at 7:37 PM, MRAB wrote: > Chris Hare wrote: >> okay - but why does the response come back like >> No such file or directory >> def b >> ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 'n', 'i', 'n', 'g') > The class Exception saves its arguments in the 'args' instance > attribute, and when it prints the exception it prints those arguments: > > > >>> e = Exception(1, 2, 3) > >>> print e.args > (1, 2, 3) > >>> print e > (1, 2, 3) > >>> print repr(e) > Exception(1, 2, 3) > > > NetActiveError inherits from RuntimeError, and ultimately from > Exception. > > NetActiveError sets the 'args' attribute to its single string argument, > and when the exception is printed out it thinks it's the arguments: > > > >>> e.args = "string" > >>> print e > ('s', 't', 'r', 'i', 'n', 'g') > >>> print repr(e) > Exception('s', 't', 'r', 'i', 'n', 'g') > > > The correct way to create your own exceptions is to call the > superclass's __init__ method: > > > >>> class NetActiveError(RuntimeError): > ... def __init__(self, error): > ... RuntimeError.__init__(self, error) > ... > >>> e = NetActiveError("string") > >>> print e > string > >>> print repr(e) > NetActiveError('string',) > > >> On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote: >>> What makes you think it has to do with user-defined exceptions? >>> >>>>>> try : >>> ... raise Exception("hello") >>> ... except Exception as (errno, errText) : >>> ... print "whatever" >>> ... >>> Traceback (most recent call last): >>> ValueError: need more than 1 values to unpack >>> >>> An Exception is an object, not a tuple of number and text. >>> >>> Raise an instance of the exception, not the class: >>> >>> raise NetActiveError("net already running") >>> >>> And then catch the exception object >>> >>> except NetActiveError as err: >>> print err.args >>> >>> On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare wrote: >>>> I have a block of test code, where I am trying to raise and catch my own user defined exception >>>> >>>> class NetActiveError(RuntimeError): >>>> def __init__(self,error): >>>> self.args = error >>>> >>>> def a(): >>>> try: >>>> fh = open("me.txt", "r") >>>> except Exception as (errno, errText): >>>> print errText >>>> try: >>>> b() >>>> except NetActiveError as (errono, errText): >>>> print errno, errText >>>> >>>> def b(): >>>> print "def b" >>>> raise NetActiveError,"net already running" >>>> >>>> >>>> a() >>>> >>>> >>>> When I run it though, I get the following error: >>>> >>>> chare$ python z >>>> No such file or directory >>>> def b >>>> Traceback (most recent call last): >>>> File "z", line 20, in >>>> a() >>>> File "z", line 12, in a >>>> except NetActiveError as (errono, errText): >>>> ValueError: too many values to unpack >>>> >>>> >>>> What am I doing wrong here? >>>> > > -- > http://mail.python.org/mailman/listinfo/python-list okay - thanks for the tutorial -- you explained what I couldn't find in the docs I looked at. I appreciate your help From steve at REMOVE-THIS-cybersource.com.au Thu Aug 5 21:38:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 01:38:42 GMT Subject: defining, raising and catching exceptions References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> Message-ID: <4c5b67a2$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 01:37:17 +0100, MRAB wrote: > The correct way to create your own exceptions is to call the > superclass's __init__ method: > > > >>> class NetActiveError(RuntimeError): > ... def __init__(self, error): > ... RuntimeError.__init__(self, error) As given, that's pointless since you're neither overriding (replacing) nor overloading the base class method. Since NetActiveError inherits ALL behaviour and state from RuntimeError, there's no need to overload anything at all, so the correct way to subclass is to simply give the subclass a name and (optionally) a docstring: class NetActiveError(RuntimeError): """Description of error goes here.""" The only change from the OP's code is that instead of defining a non- standard error attribute, it uses the standard message and args attributes: >>> e = NetActiveError('network already running') >>> e.message 'network already running' >>> e.args ('network already running',) -- Steven From wolftracks at invalid.com Thu Aug 5 21:40:02 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 18:40:02 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: <4c5b61a7$0$28666$c3e8da3@news.astraweb.com> References: <4c5b61a7$0$28666$c3e8da3@news.astraweb.com> Message-ID: On 8/5/2010 6:13 PM, Steven D'Aprano wrote: > On Thu, 05 Aug 2010 17:55:30 -0700, W. eWatson wrote: > >> I'm pretty sure he has the same version of Python, 2.5, but perhaps not >> the numpy or scipy modules. I need to find out his version numbers. > > It's only a convention, but the usual way is to check the __version__ > attribute. It works for Numpy: > >>>> import numpy >>>> numpy.__version__ > '1.0.3' > > > It is now written in my Py book. Thanks. From wolftracks at invalid.com Thu Aug 5 21:42:04 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 18:42:04 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On 8/5/2010 6:23 PM, MRAB wrote: > W. eWatson wrote: >> It's been awhile since I've used python, and I recall there is a way >> to find the version number from the IDLE command line prompt. dir, >> help, __version.__? >> >> I made the most minimal change to a program, and it works for me, but >> not my partner. He gets >> >> Traceback (most recent call last): >> File "C:\Documents and >> Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", >> line 40, in >> from scipy import stats as stats # scoreatpercentile >> File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, >> in >> from stats import * >> File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, >> in >> import scipy.special as special >> File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line >> 22, in >> from numpy.testing import NumpyTest >> ImportError: cannot import name NumpyTest >> >> Here are the first few lines of code. >> >> import sys, os, glob >> import string >> from numpy import * >> from datetime import datetime, timedelta >> import time >> from scipy import stats as stats # scoreatpercentile >> >> I'm pretty sure he has the same version of Python, 2.5, but perhaps >> not the numpy or scipy modules. I need to find out his version numbers. >> > Try: > > import numpy > help(numpy.version) > > BTW, on Python 2.6 I can see that there's "numpytest" but not > "NumpyTest". I have to stick with 2.5 for comparability with my partner. He's non-Python but was able to get Python 2.5 working. I think he somehow bumped ahead to a later version of numpy than I have. From philip at semanchuk.com Thu Aug 5 21:47:48 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 5 Aug 2010 21:47:48 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Aug 5, 2010, at 8:55 PM, W. eWatson wrote: > It's been awhile since I've used python, and I recall there is a way > to find the version number from the IDLE command line prompt. dir, > help, __version.__? Hi Wayne, FYI it's got nothing to do with IDLE, it's just a question of whether or not the module in question exposes any kind of a version attribute. There's no standard, unfortunately. The most popular convention seems to be via an attribute called __version__, but I've also seen __VERSION__, VERSION, and version. Here's some code that I wrote that you might find useful. It's from a setup.py and it checks a list of modules on which our project depends to see if (a) they're installed and (b) if the version installed is adequate. In the snippet below, dependencies is a list of custom classes that represent modules we need (e.g. numpy). # Try each module for dependency in dependencies: try: __import__(dependency.name) except ImportError: # Uh oh! dependency.installed = None else: # The module loaded OK. Get a handle to it and try to extract # version info. # Many Python modules follow the convention of providing their # version as a string in a __version__ attribute. module = sys.modules[dependency.name] # This is what I default to. dependency.installed = "[version unknown]" for attribute_name in ("__version__", "__VERSION__", "VERSION", "version"): if hasattr(module, attribute_name): dependency.installed = getattr(module, attribute_name) break Hope this helps a little, Philip From wolftracks at invalid.com Thu Aug 5 21:50:14 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 18:50:14 -0700 Subject: Python Portability--Not very portable? Message-ID: In my on-again-off-again experience with Python for 18 months, portability seems an issue. As an example, my inexperienced Python partner 30 miles away has gotten out of step somehow. I think by installing a different version of numpy than I use. I gave him a program we both use months ago, and he had no trouble. (We both use IDLE on 2.5). I made a one character change to it and sent him the new py file. He can't execute it. I doubt he has changed anything in the intervening period. A further example. Months ago I decided to see if I could compile a program to avoid such problems as above. I planned to satisfy that need, and see if I could distribute some simple programs to non-Python friends. I pretty well understand the idea,and got it working with a small program. It seemed like a lot of manual labor to do it. From skippy.hammond at gmail.com Thu Aug 5 22:02:50 2010 From: skippy.hammond at gmail.com (Mark Hammond) Date: Fri, 06 Aug 2010 12:02:50 +1000 Subject: pre-uninstall script in bdist_wininst In-Reply-To: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> References: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> Message-ID: <4C5B6D4A.3000702@gmail.com> On 6/08/2010 4:26 AM, Nils wrote: > Hi. > I am using a postinstall-script like this: > setup( > ... > scripts=['scripts\install.py'], > options = { > ... > "bdist_wininst" : { > "install_script" : "install.py", > ... > }, > } > ) > > According to the docs in [1] this script is > a) called after install (with the "-install" parameter) - this works > fine for me... > b) called before uninstall (with tho "-remove" parameter) - this > however does not work. According to a comment in pywin32's post-install script: elif arg == "-remove": # bdist_msi calls us before uninstall, so we can undo what we # previously did. Sadly, bdist_wininst calls us *after*, so # we can't do much at all. So it seems possible your script is failing due to an import error as your module has already been removed. Maybe a .msi would work better for you. > btw: With that I am trying to register a com-server on install and de- > register on uninstall - so if other ideas are around I'd love to hear > them, too... I'd suggest using py2exe to package the object and inno installer or similar to handle the install and uninstall parts. Mark From wuwei23 at gmail.com Thu Aug 5 22:42:28 2010 From: wuwei23 at gmail.com (alex23) Date: Thu, 5 Aug 2010 19:42:28 -0700 (PDT) Subject: Why is there no platform independent way of clearing a terminal? References: Message-ID: <6fdf65db-ab65-4891-9e3b-253896245326@h40g2000pro.googlegroups.com> Lawrence D'Oliveiro wrote: > You?ve got to be kidding. Look at the number of Windows-specific questions > this groups is already full of. Are you really unable to tell the difference between questions about Windows-related modules and snarky, off-topic sniping at Windows itself? From debatem1 at gmail.com Thu Aug 5 22:45:12 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 5 Aug 2010 19:45:12 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson wrote: > In my on-again-off-again experience with Python for 18 months, portability > seems an issue. > > As an example, my inexperienced Python partner 30 miles away has gotten out > of step somehow. I think by installing a different version of numpy than I > use. I gave him a program we both use months ago, and he had no trouble. (We > both use IDLE on 2.5). I made a one character change to it and sent him the > new py file. He can't execute it. I doubt he has changed anything in the > intervening period. Portability doesn't mean you can use different versions of your dependencies and be A-OK. It should be fairly obvious that if the behavior of your dependencies changes, your code needs to change to ensure that it demonstrates the same behavior. Portability also doesn't mean that any given one-character change is valid, so that may be your issue as well. > A further example. Months ago I decided to see if I could compile a program > to avoid such problems as above. I planned to satisfy that need, and see if > I could distribute some simple programs to non-Python friends. I pretty well > understand the idea,and got it working with a small program. It seemed like > a lot of manual labor to do it. What, why were you compiling a program? And why not just use distutils? Geremy Condra From wolftracks at invalid.com Thu Aug 5 23:28:40 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 20:28:40 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On 8/5/2010 7:45 PM, geremy condra wrote: > On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson wrote: >> In my on-again-off-again experience with Python for 18 months, portability >> seems an issue. >> >> As an example, my inexperienced Python partner 30 miles away has gotten out >> of step somehow. I think by installing a different version of numpy than I >> use. I gave him a program we both use months ago, and he had no trouble. (We >> both use IDLE on 2.5). I made a one character change to it and sent him the >> new py file. He can't execute it. I doubt he has changed anything in the >> intervening period. > > Portability doesn't mean you can use different versions of your > dependencies and be A-OK. It should be fairly obvious that if the > behavior of your dependencies changes, your code needs to change to > ensure that it demonstrates the same behavior. Portability also > doesn't mean that any given one-character change is valid, so that may > be your issue as well. > >> A further example. Months ago I decided to see if I could compile a program >> to avoid such problems as above. I planned to satisfy that need, and see if >> I could distribute some simple programs to non-Python friends. I pretty well >> understand the idea,and got it working with a small program. It seemed like >> a lot of manual labor to do it. > > What, why were you compiling a program? And why not just use distutils? > > Geremy Condra I checked the one char change on my system thoroughly. I looked around on some forums and NGs 4 months ago, and found no one even had a simple "compiled program" available to even demonstrate some simple example. I would think there are some small time and big time Python players who sell executable versions of their programs for profit? disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils might have been part of it. So how does one keep a non-Python user in lock step with my setup, so these problems don't arise? I don't even want to think about having him uninstall and re-install. :-) Although maybe he could do it without making matters worse. From debatem1 at gmail.com Thu Aug 5 23:50:57 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 5 Aug 2010 20:50:57 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 8:28 PM, W. eWatson wrote: > On 8/5/2010 7:45 PM, geremy condra wrote: >> >> On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson ?wrote: >>> >>> In my on-again-off-again experience with Python for 18 months, >>> portability >>> seems an issue. >>> >>> As an example, my inexperienced Python partner 30 miles away has gotten >>> out >>> of step somehow. I think by installing a different version of numpy than >>> I >>> use. I gave him a program we both use months ago, and he had no trouble. >>> (We >>> both use IDLE on 2.5). I made a one character change to it and sent him >>> the >>> new py file. He can't execute it. I doubt he has changed anything in the >>> intervening period. >> >> Portability doesn't mean you can use different versions of your >> dependencies and be A-OK. It should be fairly obvious that if the >> behavior of your dependencies changes, your code needs to change to >> ensure that it demonstrates the same behavior. Portability also >> doesn't mean that any given one-character change is valid, so that may >> be your issue as well. >> >>> A further example. Months ago I decided to see if I could compile a >>> program >>> to avoid such problems as above. I planned to satisfy that need, and see >>> if >>> I could distribute some simple programs to non-Python friends. I pretty >>> well >>> understand the idea,and got it working with a small program. It seemed >>> like >>> a lot of manual labor to do it. >> >> What, why were you compiling a program? And why not just use distutils? >> >> Geremy Condra > > I checked the one char change on my system thoroughly. I looked around on > some forums and NGs 4 months ago, and found no one even had a simple > "compiled program" available to even demonstrate some simple example. That would be because Python is an interpreted language. > I would think there are some small time and big time Python players who sell > executable versions of their programs for profit? Yes. What's your point? > disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils > might have been part of it. distutils. http://docs.python.org/library/distutils.html > So how does one keep a non-Python user in lock step with my setup, so these > problems don't arise? I don't even want to think about having him uninstall > and re-install. :-) Although maybe he could do it without making matters > worse. That's going to hinge on what your dependencies are. Geremy Condra From nagle at animats.com Fri Aug 6 01:13:26 2010 From: nagle at animats.com (John Nagle) Date: Thu, 05 Aug 2010 22:13:26 -0700 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: References: Message-ID: <4c5b99f6$0$1613$742ec2ed@news.sonic.net> On 8/4/2010 4:40 PM, ????? wrote: > cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page > = '%s' ORDER BY date DESC ''' % (page) ) Don't do string substitution ("%") on SQL statements. Let MySQLdb do it for you, with proper escaping: cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s ORDER BY date DESC''', (page,)) The difference is that if some external source can control "page", and they put in a value like 100 ; DELETE FROM visitors; SELECT * FROM visitors you just lost your data. John Nagle From navkirats at gmail.com Fri Aug 6 01:14:36 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 6 Aug 2010 10:44:36 +0530 Subject: Import python modules from sub-directories Message-ID: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> Hi guys, I am new to python and would like to import certain classes in sub-directories of the working directory. I was wondering how will I be able to achieve this? Regards, Nav From navkirats at gmail.com Fri Aug 6 01:41:51 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 6 Aug 2010 11:11:51 +0530 Subject: Import python modules from sub-directories In-Reply-To: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> References: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> Message-ID: <00C202DF-A4CB-44AA-8C1C-C3A422317830@gmail.com> On 06-Aug-2010, at 10:44 AM, Navkirat Singh wrote: > Hi guys, > > I am new to python and would like to import certain classes in sub-directories of the working directory. I was wondering how will I be able to achieve this? > > Regards, > Nav Thanks. I got it. I just put an empty __init__.py file in the subdirectories and it worked. From ralf at schoenian-online.de Fri Aug 6 02:05:33 2010 From: ralf at schoenian-online.de (Ralf Schoenian) Date: Fri, 06 Aug 2010 08:05:33 +0200 Subject: Import python modules from sub-directories In-Reply-To: References: Message-ID: <4c5ba0d1$0$7656$9b4e6d93@newsspool1.arcor-online.net> Navkirat Singh wrote: > Hi guys, > > I am new to python and would like to import certain classes in sub-directories of the working directory. I was wondering how will I be able to achieve this? > > Regards, > Nav Hi, put an empty file with the name __init__.py in your subdirectory. I call it sub1 here. Assuming your filename is importme.py and your classname is Test you can do the following imports: from sub1.importme import Test import sub1.importme You can find further explainations in the official tutorial http://docs.python.org/tutorial/modules.html Regards, Ralf From cournape at gmail.com Fri Aug 6 02:22:10 2010 From: cournape at gmail.com (David Cournapeau) Date: Fri, 6 Aug 2010 15:22:10 +0900 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On Fri, Aug 6, 2010 at 8:45 AM, Roy Smith wrote: > In article , > ?Lawrence D'Oliveiro wrote: > >> In message , Roy Smith wrote: >> >> > C++, for all its flaws, had one powerful feature which made it very >> > popular. ?It is a superset of C. >> >> Actually, it never was. > > Yes, there are a few corner cases where valid C syntax has different > semantics in C and C++. ?But, they are very few. ?Calling C++ a superset > of C is essentially correct. This is only true if you limit yourself to C89 (as python seems to do). If you start using C99 (and lot of people do, if only because they don't realize it because gcc is quite relax about it), then almost no non trivial C code is valid C++ in my experience. David From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 6 03:25:37 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Aug 2010 09:25:37 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: <4c5bb8ec$0$14667$426a74cc@news.free.fr> Roald de Vries a ?crit : > > 'not None' first casts None to a bool, and then applies 'not', so 'x is > not None' means 'x is True'. Obviously plain wrong : Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 42 is not None True >>> 42 is True False >>> Please check your facts before posting !-) From rdmoores at gmail.com Fri Aug 6 03:26:49 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 6 Aug 2010 00:26:49 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Thu, Aug 5, 2010 at 16:15, Rhodri James wrote: > On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks > wrote: > You're not testing for equivalence there, you're testing for identity. ?"is" > and "is not" test whether the two objects concerned are (or are not) the > same object. ?Two objects can have the same value, but be different objects. > ?The interpreter can fool you by caching and reusing objects which have the > same value when it happens to know about it, in particular for small > integers, but this is just a happy accident of the implementation and in no > way guaranteed by the language. ?For example: > >>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" > > True >>>> >>>> a = "spam, eggs, chips and spam" >>>> b = "spam, eggs, chips and spam" >>>> a is b > > False >>>> >>>> a == b > > True > I'm wondering if there isn't considerable predictability to that "happy accident". Note how 1 'word' is treated versus 2: >>> x = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>> y = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>> x is y True >>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>> x is y False >>> (Python 3.1 on Vista.) Dick Moores From ldo at geek-central.gen.new_zealand Fri Aug 6 03:38:43 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Aug 2010 19:38:43 +1200 Subject: subprocess escaping POpen?! References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> Message-ID: In message , Chris Withers wrote: > Wolfgang Rohdewald wrote: > >> On Donnerstag 05 August 2010, Chris Withers wrote: >> >>> But why only the request for auth credentials? >> >> for security reasons I suppose - make sure a human enters >> the password > > Well yes, but what if you actually want to script it? Set up a public/private key pair. From zhxia at njnet.edu.cn Fri Aug 6 03:43:11 2010 From: zhxia at njnet.edu.cn (=?gb2312?Q?=CF=C4=D5=F0?=) Date: Fri, 6 Aug 2010 15:43:11 +0800 (CST) Subject: =?gb2312?B?UmU6IEltcG9ydCBweXRob24gbW9kdWxlcyBmcm9tIHN1Yi1kaXJlY3Rvcmllcw==?= In-Reply-To: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> References: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> Message-ID: <55296.202.112.23.199.1281080591.squirrel@carnation.njnet.edu.cn> > Hi guys, > > I am new to python and would like to import certain classes in sub-directories of the > working directory. I was wondering how will I be able to achieve this? > > Regards, > Nav > -- > http://mail.python.org/mailman/listinfo/python-list > Please try "touch __init__.py" in sub-directories. From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 6 03:49:32 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Aug 2010 09:49:32 +0200 Subject: assigning variables from list data In-Reply-To: References: Message-ID: <4c5bbe87$0$9222$426a74cc@news.free.fr> Chris Hare a ?crit : > I have a database query result (see code below). In PHP, I would have said > > list(var1,var2,var) = $result Other already answered on the Python equivalent. But there's an IMHO better way, which is to use (if the DB-API connector provides it) a DictCursor, that yields dicts instead of tuples. > > import sqlite3 as sqlite > > try: > print "connecting to disk db ..." > conn = sqlite.connect("netcomm.db") > except: > print "oops" OT, but do yourself a favor and remove this try/except. Sorry to have to say but it's about the most stupidiest error handling scheme you could think of. Seriously. Ask yourself : what will happens if sqlite.connect raises AND you don't catch the exception ? Yes, the script will stop right here - which is what you want anyway - AND you will have an error message giving you informations about what went wrong, and a full traceback. IOW, you'll have as much helpful debugging infos as possible at this point. Now what will happen with your current code ? Instead of an informative error message, you have a "oops". Well, really helps. Then your script will go on, print "retrieving data", and you can bet your ass it'll crash on the next line - "cursor = conn.cursor()", that is - with a very less informative error message, and you'll wonder why. Also, be warned that SysExit and KeyboardInterrupt are also exceptions. The one you may NOT want to catch and dismiss. To make a long story short: 1/ only catch exceptions you can *and* want to handle 2/ never assume anything about what caused the exception 3/ not exception handling is better than a wrong exception handling. HTH From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 6 04:32:00 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Aug 2010 10:32:00 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <4c5bc87b$0$10004$426a34cc@news.free.fr> Richard D. Moores a ?crit : > On Thu, Aug 5, 2010 at 16:15, Rhodri James wrote: >> On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks >> wrote: > >> You're not testing for equivalence there, you're testing for identity. "is" >> and "is not" test whether the two objects concerned are (or are not) the >> same object. Two objects can have the same value, but be different objects. >> The interpreter can fool you by caching and reusing objects which have the >> same value when it happens to know about it, in particular for small >> integers, but this is just a happy accident of the implementation and in no >> way guaranteed by the language. For example: >> >>>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" >> True >>>>> a = "spam, eggs, chips and spam" >>>>> b = "spam, eggs, chips and spam" >>>>> a is b >> False >>>>> a == b >> True >> > > I'm wondering if there isn't considerable predictability to that > "happy accident". There is, indeed, but that's really implementation details. > Note how 1 'word' is treated versus 2: > >>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>> x is y > True >>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>> x is y > False CPython caches strings that happen to be valid Python identifiers. But once again, this is an implementation-specific optimization. From jldunn2000 at gmail.com Fri Aug 6 05:06:29 2010 From: jldunn2000 at gmail.com (loial) Date: Fri, 6 Aug 2010 02:06:29 -0700 (PDT) Subject: How to read large amounts of output via popen Message-ID: <9fe7d6b5-7bbd-4453-8cf3-99d6e1260325@i31g2000yqm.googlegroups.com> I need to read a large amount of data that is being returned in standard output by a shell script I am calling. (I think the script should really be writing to a file but I have no control over that) Currently I have the following code. It seeems to work, however I suspect this may not work with large amounts of standard output. What is the best way to read a large amount of data from standard output and write to a file? Here is my code. process=subprocess.Popen(['myscript', 'param1'], shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) cmdoutput=process.communicate() myfile = open('/home/john/myoutputfile','w') myfile.write(cmdoutput[0]) myfile.close() From nawabadeel at gmail.com Fri Aug 6 05:07:32 2010 From: nawabadeel at gmail.com (Muhammad Adeel) Date: Fri, 6 Aug 2010 02:07:32 -0700 (PDT) Subject: Byte Offsets of Tokens, Ngrams and Sentences? Message-ID: <4b6077cf-d921-4f25-99ac-b74e6bc66056@d17g2000yqb.googlegroups.com> Hi, Does any one know how to tokenize a string in python that returns the byte offsets and tokens? Moreover, the sentence splitter that returns the sentences and byte offsets? Finally n-grams returned with byte offsets. Input: This is a string. Output: This 0 is 5 a 8 string. 10 thanks From ldo at geek-central.gen.new_zealand Fri Aug 6 05:23:37 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Aug 2010 21:23:37 +1200 Subject: Python Portability References: Message-ID: In message , W. eWatson wrote: > I made a one character change to it and sent him the new py file. He can't > execute it. What exactly was the problem? From ldo at geek-central.gen.new_zealand Fri Aug 6 05:25:23 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Aug 2010 21:25:23 +1200 Subject: Python Script Cannot Write to Directory References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> <4c5a6d00$0$29614$426a34cc@news.free.fr> Message-ID: In message <4c5a6d00$0$29614$426a34cc at news.free.fr>, News123 wrote: > The original question lacks necessary information That seems to be very common in this newsgroup. From rdmoores at gmail.com Fri Aug 6 05:27:11 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 6 Aug 2010 02:27:11 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5bc87b$0$10004$426a34cc@news.free.fr> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On Fri, Aug 6, 2010 at 01:32, Bruno Desthuilliers wrote: > Richard D. Moores a ?crit : >> >> On Thu, Aug 5, 2010 at 16:15, Rhodri James >> wrote: >>> >>> On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks >>> wrote: >> >>> You're not testing for equivalence there, you're testing for identity. >>> ?"is" >>> and "is not" test whether the two objects concerned are (or are not) the >>> same object. ?Two objects can have the same value, but be different >>> objects. >>> ?The interpreter can fool you by caching and reusing objects which have >>> the >>> same value when it happens to know about it, in particular for small >>> integers, but this is just a happy accident of the implementation and in >>> no >>> way guaranteed by the language. ?For example: >>> >>>>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" >>> >>> True >>>>>> >>>>>> a = "spam, eggs, chips and spam" >>>>>> b = "spam, eggs, chips and spam" >>>>>> a is b >>> >>> False >>>>>> >>>>>> a == b >>> >>> True >>> >> >> I'm wondering if there isn't considerable predictability to that >> "happy accident". > > There is, indeed, but that's really implementation details. > >> Note how 1 'word' is treated versus 2: >> >>>>> x = >>>>> 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>>> y = >>>>> 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>>> x is y >> >> True >>>>> >>>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj >>>>> hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj >>>>> hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>>> x is y >> >> False > > > CPython caches strings that happen to be valid Python identifiers. But once > again, this is an implementation-specific optimization. So there would be a different implementation for each operating system? One for Windows, one for linux? Or one for Vista and one for XP? I'm just trying to clarify what is meant by "implementation". Thanks, Dick Moores From jeanmichel at sequans.com Fri Aug 6 05:42:39 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 06 Aug 2010 11:42:39 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4C5BD90F.6020000@sequans.com> Steven D'Aprano wrote: > On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: > > >> P.S. Sorry for the top-post -- is there a way to not do top posts from >> gmail? I haven't used usenet since tin. >> > > Er, surely you can just move the cursor before you start typing??? > > > > CTRL+END will bring the cursor at the end of the file (for most the the mail clients). JM From gagsl-py2 at yahoo.com.ar Fri Aug 6 05:49:33 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Aug 2010 06:49:33 -0300 Subject: Byte Offsets of Tokens, Ngrams and Sentences? References: <4b6077cf-d921-4f25-99ac-b74e6bc66056@d17g2000yqb.googlegroups.com> Message-ID: En Fri, 06 Aug 2010 06:07:32 -0300, Muhammad Adeel escribi?: > Does any one know how to tokenize a string in python that returns the > byte offsets and tokens? Moreover, the sentence splitter that returns > the sentences and byte offsets? Finally n-grams returned with byte > offsets. > > Input: > This is a string. > > Output: > This 0 > is 5 > a 8 > string. 10 Like this? py> import re py> s = "This is a string." py> for g in re.finditer("\S+", s): ... print g.group(), g.start() ... This 0 is 5 a 8 string. 10 -- Gabriel Genellina From jeanmichel at sequans.com Fri Aug 6 05:57:00 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 06 Aug 2010 11:57:00 +0200 Subject: Python Script Cannot Write to Directory In-Reply-To: References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> <4c5a6d00$0$29614$426a34cc@news.free.fr> Message-ID: <4C5BDC6C.4040703@sequans.com> Lawrence D'Oliveiro wrote: > In message <4c5a6d00$0$29614$426a34cc at news.free.fr>, News123 wrote: > > >> The original question lacks necessary information >> > > That seems to be very common in this newsgroup. > ... JM From downaold at gmail.com Fri Aug 6 06:01:23 2010 From: downaold at gmail.com (Roald de Vries) Date: Fri, 6 Aug 2010 12:01:23 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5bb8ec$0$14667$426a74cc@news.free.fr> References: <4c5bb8ec$0$14667$426a74cc@news.free.fr> Message-ID: <7783CEA7-C451-4DB5-8161-D2E6D3800D42@gmail.com> On Aug 6, 2010, at 9:25 AM, Bruno Desthuilliers wrote: > Roald de Vries a ?crit : >> 'not None' first casts None to a bool, and then applies 'not', so >> 'x is not None' means 'x is True'. > > Obviously plain wrong : > > Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 42 is not None > True > >>> 42 is True > False > >>> I know. I'm sorry. I'm embarrassed. I will check my facts better before posting in the future. And I'm sorry. Cheers, Roald From gagsl-py2 at yahoo.com.ar Fri Aug 6 06:02:07 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Aug 2010 07:02:07 -0300 Subject: How to read large amounts of output via popen References: <9fe7d6b5-7bbd-4453-8cf3-99d6e1260325@i31g2000yqm.googlegroups.com> Message-ID: En Fri, 06 Aug 2010 06:06:29 -0300, loial escribi?: > I need to read a large amount of data that is being returned in > standard output by a shell script I am calling. > > (I think the script should really be writing to a file but I have no > control over that) > > Currently I have the following code. It seeems to work, however I > suspect this may not work with large amounts of standard output. > > What is the best way to read a large amount of data from standard > output and write to a file? > > Here is my code. > > process=subprocess.Popen(['myscript', 'param1'], > shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > cmdoutput=process.communicate() > > myfile = open('/home/john/myoutputfile','w') > > myfile.write(cmdoutput[0]) > > myfile.close() If all you do with the process' output is to write it to the output file, you can avoid the intermediate step: myfile = open('/home/john/myoutputfile','w') myerror = open('/home/john/myerrorfile','w') process=subprocess.Popen(['myscript', 'param1'], shell=False,stdout=myfile,stderr=myerror) process.wait() (untested) -- Gabriel Genellina From nawabadeel at gmail.com Fri Aug 6 06:06:18 2010 From: nawabadeel at gmail.com (Muhammad Adeel) Date: Fri, 6 Aug 2010 03:06:18 -0700 (PDT) Subject: Byte Offsets of Tokens, Ngrams and Sentences? References: <4b6077cf-d921-4f25-99ac-b74e6bc66056@d17g2000yqb.googlegroups.com> Message-ID: <76ea31b5-4591-4183-aedc-0cf40a809b37@m1g2000yqo.googlegroups.com> On Aug 6, 10:49?am, "Gabriel Genellina" wrote: > En Fri, 06 Aug 2010 06:07:32 -0300, Muhammad Adeel ? > escribi?: > > > Does any one know how to tokenize a string in python that returns the > > byte offsets and tokens? Moreover, the sentence splitter that returns > > the sentences and byte offsets? Finally n-grams returned with byte > > offsets. > > > Input: > > This is a string. > > > Output: > > This ?0 > > is ? ? ?5 > > a ? ? ? 8 > > string. ? 10 > > Like this? > > py> import re > py> s = "This is a string." > py> for g in re.finditer("\S+", s): > ... ? print g.group(), g.start() > ... > This 0 > is 5 > a 8 > string. 10 > > -- > Gabriel Genellina Hi, Thanks. Can you please tell me how to do for n-grams and sentences as well? From gagsl-py2 at yahoo.com.ar Fri Aug 6 06:13:17 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Aug 2010 07:13:17 -0300 Subject: abstract metaclass References: <1B034596-7B57-4950-8070-7685176A824E@gmail.com> Message-ID: En Thu, 05 Aug 2010 10:46:29 -0300, Roald de Vries escribi?: > I'm trying to create a metaclass that keeps track of its objects, and > implement this as a collections.MutableMapping. That is, something like > this: > > > class type2(type, MutableMapping): > ... > > /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/abc.pyc in __new__(mcls, name, bases, namespace) > 83 if getattr(value, "__isabstractmethod__", > False)) > 84 for base in bases: > ---> 85 for name in getattr(base, "__abstractmethods__", > set()): > 86 value = getattr(cls, name, None) > 87 if getattr(value, "__isabstractmethod__", > False): > > TypeError: Error when calling the metaclass bases > 'getset_descriptor' object is not iterable > > > Anybody knows why? Every type is just an object, isn't it? This may be an oversight in ABCMeta implementation - please file a bug report at http://bugs.python.org/ -- Gabriel Genellina From zak.mc.kraken at libero.it Fri Aug 6 07:12:44 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Fri, 06 Aug 2010 13:12:44 +0200 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: Richard D. Moores wrote: > So there would be a different implementation for each operating > system? One for Windows, one for linux? Or one for Vista and one for > XP? I'm just trying to clarify what is meant by "implementation". there are dozillions of "implementation" of python: one for each release of CPython (2.0, 2.1.2, 2.6.1, 3.x.y...), multiplied for each OS multiplied for IronPython, Jython, Pypy... etc... (obviously the "implementation details" between, say, CPython 2.6.1 and 2.6.2 are really minor vs Pypy X.Y.Z and IronPython A.B.C) -- By ZeD From no.email at please.post Fri Aug 6 07:23:50 2010 From: no.email at please.post (kj) Date: Fri, 6 Aug 2010 11:23:50 +0000 (UTC) Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> Message-ID: In Nobody writes: >On Fri, 23 Jul 2010 10:42:26 +0000, Steven D'Aprano wrote: >> Don't write bare excepts, always catch the error you want and nothing >> else. >That advice would make more sense if it was possible to know which >exceptions could be raised. In practice, that isn't possible, as the >documentation seldom provides this information. Even for the built-in >classes, the documentation is weak in this regard; for less important >modules and third-party libraries, it's entirely absent. I don't get your point. Even when I *know* that a certain exception may happen, I don't necessarily catch it. I catch only those exceptions for which I can think of a suitable response that is *different* from just letting the program fail. (After all, my own code raises its own exceptions with the precise intention of making the program fail.) If an unexpected exception occurs, then by definition, I had no better response in mind for that situation than just letting the program fail, so I'm happy to let that happen. If, afterwards, I think of a different response for a previously uncaught exception, I'll modify the code accordingly. I find this approach far preferable to the alternative of knowing a long list of possible exceptions (some of which may never happen in actual practice), and think of ways to keep the program still alive no-matter-what. "No memory? No disk space? No problem! Just a flesh wound!" What's the point of that? (If I want the final error message to be something other than a bare stack trace, I may wrap the whole execution in a global/top-level try/catch block so that I can fashion a suitable error message right before calling exit, but that's just "softening the fall": the program still will go down.) From katcipis at inf.ufsc.br Fri Aug 6 07:37:59 2010 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Fri, 6 Aug 2010 08:37:59 -0300 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 12:28 AM, W. eWatson wrote: > On 8/5/2010 7:45 PM, geremy condra wrote: > >> On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson >> wrote: >> >>> In my on-again-off-again experience with Python for 18 months, >>> portability >>> >>> seems an issue. >>> >>> As an example, my inexperienced Python partner 30 miles away has gotten >>> out >>> of step somehow. I think by installing a different version of numpy than >>> I >>> use. I gave him a program we both use months ago, and he had no trouble. >>> (We >>> both use IDLE on 2.5). I made a one character change to it and sent him >>> the >>> new py file. He can't execute it. I doubt he has changed anything in the >>> intervening period. >>> >> >> Portability doesn't mean you can use different versions of your >> dependencies and be A-OK. It should be fairly obvious that if the >> behavior of your dependencies changes, your code needs to change to >> ensure that it demonstrates the same behavior. Portability also >> doesn't mean that any given one-character change is valid, so that may >> be your issue as well. >> >> A further example. Months ago I decided to see if I could compile a >>> program >>> to avoid such problems as above. I planned to satisfy that need, and see >>> if >>> I could distribute some simple programs to non-Python friends. I pretty >>> well >>> understand the idea,and got it working with a small program. It seemed >>> like >>> a lot of manual labor to do it. >>> >> >> What, why were you compiling a program? And why not just use distutils? >> >> Geremy Condra >> > > I checked the one char change on my system thoroughly. I looked around on > some forums and NGs 4 months ago, and found no one even had a simple > "compiled program" available to even demonstrate some simple example. > > I would think there are some small time and big time Python players who > sell executable versions of their programs for profit? > > disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils > might have been part of it. > And what was hard to do with Py2Exe? i used it on relatively complex college work using QT and the worse i had to do was include a "sip" option to make Py2Exe work with PyQT. But the setup.py script that generates the .exe (automatically) was ridiculously small and simple ( https://svn.inf.ufsc.br/katcipis/python/FormaisGUI/src/setup.py). For me compiling a python program into an .exe always was pretty easy (already made it at my work with a prototype, that one was quite complex, i just had some problem with the netifaces module). > > So how does one keep a non-Python user in lock step with my setup, so these > problems don't arise? I don't even want to think about having him uninstall > and re-install. :-) Although maybe he could do it without making matters > worse. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.getgnulinux.org/windows -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Fri Aug 6 07:39:06 2010 From: roy at panix.com (Roy Smith) Date: Fri, 06 Aug 2010 07:39:06 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In article , David Cournapeau wrote: > > Yes, there are a few corner cases where valid C syntax has different > > semantics in C and C++. ??But, they are very few. ??Calling C++ a superset > > of C is essentially correct. > > This is only true if you limit yourself to C89 (as python seems to > do). If you start using C99 (and lot of people do, if only because > they don't realize it because gcc is quite relax about it), then > almost no non trivial C code is valid C++ in my experience. I'm not following you. If anything, C99 makes C closer to C++. Can you give me some examples of valid C99 which is not also valid C++? From dangets at gmail.com Fri Aug 6 08:28:40 2010 From: dangets at gmail.com (DG) Date: Fri, 6 Aug 2010 05:28:40 -0700 (PDT) Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On Aug 6, 2:32?am, Bruno Desthuilliers wrote: > Richard D. Moores a ?crit : > > > > > On Thu, Aug 5, 2010 at 16:15, Rhodri James wrote: > >> On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks > >> wrote: > > >> You're not testing for equivalence there, you're testing for identity. ?"is" > >> and "is not" test whether the two objects concerned are (or are not) the > >> same object. ?Two objects can have the same value, but be different objects. > >> ?The interpreter can fool you by caching and reusing objects which have the > >> same value when it happens to know about it, in particular for small > >> integers, but this is just a happy accident of the implementation and in no > >> way guaranteed by the language. ?For example: > > >>>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" > >> True > >>>>> a = "spam, eggs, chips and spam" > >>>>> b = "spam, eggs, chips and spam" > >>>>> a is b > >> False > >>>>> a == b > >> True > > > I'm wondering if there isn't considerable predictability to that > > "happy accident". > > There is, indeed, but that's really implementation details. > > > Note how 1 'word' is treated versus 2: > > >>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' > >>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' > >>>> x is y > > True > >>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' > >>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' > >>>> x is y > > False > > CPython caches strings that happen to be valid Python identifiers. But > once again, this is an implementation-specific optimization. I've always thought of it as you don't compare strings with "is", you *should* use == The reasoning is that you don't know if that string instance is the only one in memory. I've heard as an implementation detail, since strings are immutable, that Python will only create one actual instance and just assign new references to it (your first x is y example), but to compare equality it just makes sense to use "==", not to ask if it is the same object in memory. Plus, I believe the "==" operator will check if the variables point to the same object. Using is/is not with None works well, because I believe there will always only be 1 None object. From nobody at nowhere.com Fri Aug 6 08:44:48 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 06 Aug 2010 13:44:48 +0100 Subject: How to read large amounts of output via popen References: <9fe7d6b5-7bbd-4453-8cf3-99d6e1260325@i31g2000yqm.googlegroups.com> Message-ID: On Fri, 06 Aug 2010 02:06:29 -0700, loial wrote: > I need to read a large amount of data that is being returned in > standard output by a shell script I am calling. > > (I think the script should really be writing to a file but I have no > control over that) If the script is writing to stdout, you get to decide whether its stdout is a pipe, file, tty, etc. > Currently I have the following code. It seeems to work, however I > suspect this may not work with large amounts of standard output. > process=subprocess.Popen(['myscript', 'param1'], > shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > cmdoutput=process.communicate() It's certainly not the best way to read large amounts of output. Unfortunately, better solutions get complicated when you need to read more than one of stdout and stderr, or if you also need to write to stdin. If you only need stdout, you can just read from process.stdout in a loop. You can leave stderr going to wherever the script's stderr goes (e.g. the terminal), or redirect it to a file. If you really do need both stdout and stderr, then you either need to enable non-blocking I/O, or use a separate thread for each stream, or redirect at least one of them to a file. FWIW, Popen.communicate() uses non-blocking I/O on Unix and separate threads on Windows (the standard library doesn't include a mechanism to enable non-blocking I/O on Windows). > What is the best way to read a large amount of data from standard > output and write to a file? For this case, the best way is to just redirect stdout to a file, rather than passing it through the script, i.e.: outfile = open('outputfile', 'w') process = subprocess.call(..., stdout = outfile) outfile.close() From landimatte at gmail.com Fri Aug 6 08:49:04 2010 From: landimatte at gmail.com (Matteo Landi) Date: Fri, 6 Aug 2010 14:49:04 +0200 Subject: pylint scores In-Reply-To: <4c554c01$0$6122$426a34cc@news.free.fr> References: <4C532577.8010906@free.fr> <4c554c01$0$6122$426a34cc@news.free.fr> Message-ID: On Sun, Aug 1, 2010 at 12:27 PM, News123 wrote: > Hi, > > > On 07/31/2010 11:04 AM, Matteo Landi wrote: >> What are the messages one should really care about while evaluating >> its code using pylint? It's easy to get 5 scored with a "lot of public >> methods" or bad named variables such as 'x' or 'y' .. Have you got any >> config file to share? > > > The most important ones are of course the errors. > Some of them might be false, but in our team we agreed, that no file is > allowed to report pylint errors. > This means > - just fixing errors (in most cases) > - rewriting code (in a few cases) > - masking errors with pylint directives in the source (some other few > errrors) > > > > > If you only want to see the errros, then just run > pylint -E filename.py > > Note: This is a rather new but very useful switch.. It doesn't exist > ? ?on Ubuntu 10.4's release pylint 0.19.0, but exists on pylint 0.21.1 > > > > Apart from that. You should discuss within your team, which > errors you'd like to have ignored and adapt the pylintrc. This > is a rather personal decision. > For one project we disiabled for example following warnings: > ## C0322 = "Operator not preceded by a space" > ## C0323 = "Operator not followed by a space" > ## C0324 = "Comma not followed by a space" > As we did not have time to rewrite all of the existing code, that > violated these rules. > We prefered to 'hide' these warnings in order to sett the more important > ones. > > On another new project however we did NOT comment therese rules > and decided, that all new code should follow these rules > > > We disabled some special global variables, which we'd like to have in > lower case > > const-rgx ==((specialvar)|(v_[a-z_][a-z0-9_]*)|([A-Z_][A-Z0-9_]*)|(__.*__))$ > > > you could also modify variables like > # Maximum number of attributes for a class (see R0902). > max-attributes=7 > > # Minimum number of public methods for a class (see R0903). > min-public-methods=2 > > # Maximum number of public methods for a class (see R0904). > max-public-methods=20 > > > For some graphics module functions for example we wanted to > be allowed to use variable names like x,y as they are > completely meaningful names for pixel coordinates. > > > so change the entry good-names > good-names=x,y,ex,Run,_ Thank you so much, these are very precious settings. > > > Hope, that this gave you some ideas > > > >> >> On Sat, Jul 31, 2010 at 2:48 AM, Dan Stromberg wrote: >>> >>> On Fri, Jul 30, 2010 at 12:18 PM, News123 wrote: >>>> >>>> On 07/30/2010 03:12 PM, wheres pythonmonks wrote: >>>>> I am starting to use pylint to look at my code and I see that it gives a >>>>> rating. >>>>> What values do experienced python programmers get on code not >>>>> targeting the benchmark? >>>>> >>>>> I wrote some code, tried to keep it under 80 characters per line, >>>>> reasonable variable names, and I got: >>>>> >>>>> 0.12 / 10. >>>>> >>>>> Is this a good score for one not targeting the benchmark? ?(pylint >>>>> running in default mode) >>>>> >>>> It's not a goodf core, but arrives easily if you never ran pylint before. >>>> With very little effort you should be able to be above 5 >>>> with a little more effort above 7 >>>> >>>> >>>>> Somewhat related: ?Is the backslash the only way to extend arguments >>>>> to statements over multiple lines? ?(e.g.) >>>> >>>> if you have an opening parenthesis, or bracked, then you don't need a >>>> backslash >>>> >>>> so instead of >>>> if longlonglonglonglonglonglonglongvar == \ >>>> ? ? ? ?otherlonglonglonglongvar: >>>> >>>> you could also write: >>>> >>>> if (longlonglonglonglonglonglonglongvar == >>>> ? ? ? ?otherlonglonglonglongvar): >>>> >>>> >>>> same works of course with asserts. >>>> >>>>> >>>>>>>> def f(x,y,z): return(x+y+z); >>>>> ... >>>>>>>> f(1,2, >>>>> ... 3) >>>>> 6 >>>>>>>> assert f(1,2,3)>0, >>>>> ? File "", line 1 >>>>> ? ? assert f(1,2,3)>0, >>>>> ? ? ? ? ? ? ? ? ? ? ?^ >>>>> SyntaxError: invalid syntax >>>>>>>> >>>>> >>>>> In the above, I could split the arguments to f (I guess b/c of the >>>>> parens) but not for assert. ?I could use a backslash, but I find this >>>>> ugly -- it that my only (best?) option? >>>>> >>>>> [I really like to assert my code to correctness and I like using the >>>>> second argument to assert, but this resulted in a lot of long lines >>>>> that I was unable to break except with an ugly backslash.] >>>>> >>>>> W >>>> >>> IMO, the important thing about pylint's scoring is that it's but one way of >>> many of producing good Python code. ?However, it's also one of the easier >>> ways of producing good python code. >>> I personally like to get my scores up near 10, by annotating in comments >>> about the few things that pylint flags that I can't just code around. ?This >>> requires jumping through some slightly silly hoops (EG the previously >>> mentioned "too few public methods", which my various container classes >>> always trip over), but going through this process is worthwhile for >>> highlighting the hoops pylint can detect that -aren't- so silly. >>> The one thing I like to leave unfixed is FIXME's - otherwise my preference >>> would be to go for a score of 10 for production code. >>> I also like to create a ./this-pylint script for my various projects, that >>> have global overrides - things like identifier rules, line length, and... ?I >>> don't get blanks instead of tabs. ?Blanks are fine if you don't understand >>> tabs (or think someone in the future who doesn't understand tabs will need >>> to work on your code), but tabs allow everyone to see code indented the way >>> -they- want to see it, not just the way the original author wanted to see >>> it. >>> This script (./this-pylint) will also save output from the test in a text >>> file, for make (or other dependency handling program) to use to avoid >>> re-pylint'ing unmodified code. ?It'll give an error typically, if pytlint >>> detects any errors other than FIXME's (excluding ones, as I mentioned >>> before, that have a comment disabling the warning, of course). >>> I'm more than a little sad that pylint doesn't seem to be moving to python 3 >>> in any big hurry. >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From navkirats at gmail.com Fri Aug 6 09:15:42 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 6 Aug 2010 18:45:42 +0530 Subject: Import python modules from sub-directories In-Reply-To: <55296.202.112.23.199.1281080591.squirrel@carnation.njnet.edu.cn> References: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> <55296.202.112.23.199.1281080591.squirrel@carnation.njnet.edu.cn> Message-ID: On 06-Aug-2010, at 1:13 PM, ?? wrote: > > >> Hi guys, >> >> I am new to python and would like to import certain classes in sub-directories of the >> working directory. I was wondering how will I be able to achieve this? >> >> Regards, >> Nav >> -- >> http://mail.python.org/mailman/listinfo/python-list > >> > > Please try "touch __init__.py" in sub-directories. > > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks, that worked : ) From sschwarzer at sschwarzer.net Fri Aug 6 09:37:04 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 06 Aug 2010 15:37:04 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <4C5C1000.3050102@sschwarzer.net> Hi DG, On 2010-08-06 14:28, DG wrote: > I've always thought of it as you don't compare strings with "is", you > *should* use == The reasoning is that you don't know if that string > instance is the only one in memory. I've heard as an implementation > detail, since strings are immutable, that Python will only create one > actual instance and just assign new references to it (your first x is > y example), but to compare equality it just makes sense to use "==", > not to ask if it is the same object in memory. Yes, you'd usually use == to compare strings. The use in the post presumably was to show the behavior when you use `is`; I guess it wasn't meant as an example for production code. :) I can imagine a case where you might want to compare a string with `is`: FORWARD = "forward" BACKWARD = "backward" ... def func(direction=FORWARD): if direction is FORWARD: ... elif direction is BACKWARD: ... else: ... in case you expect people to specifically use the constants you provided in the module. Here, the fact that FORWARD actually is the string "forward" might be considered an implementation detail. Using a string instead of an `object()` has the advantage that it makes usage in error messages easier. Actually, I've never seen such a use, as far as I remember. What do other people here think? Is the code above, which compares strings with `is`, bad style, and if yes, why? How would you write the code instead? > Plus, I believe the > "==" operator will check if the variables point to the same object. No, that's what `is` is for. > Using is/is not with None works well, because I believe there will > always only be 1 None object. Yes, and it avoids subtle bugs if someone overwrites `__eq__` in some class: >>> class AlwaysEqual(object): ... def __eq__(self, other): ... return True ... >>> always_equal = AlwaysEqual() >>> always_equal == None True >>> None == always_equal True >>> always_equal is None False Stefan From cournape at gmail.com Fri Aug 6 09:55:49 2010 From: cournape at gmail.com (David Cournapeau) Date: Fri, 6 Aug 2010 22:55:49 +0900 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On Fri, Aug 6, 2010 at 8:39 PM, Roy Smith wrote: > In article , > ?David Cournapeau wrote: > >> > Yes, there are a few corner cases where valid C syntax has different >> > semantics in C and C++. ?But, they are very few. ?Calling C++ a superset >> > of C is essentially correct. >> >> This is only true if you limit yourself to C89 (as python seems to >> do). If ?you start using C99 (and lot of people do, if only because >> they don't realize it because gcc is quite relax about it), then >> almost no non trivial C code is valid C++ in my experience. > > I'm not following you. ?If anything, C99 makes C closer to C++. ?Can you > give me some examples of valid C99 which is not also valid C++? variable size array, the meaning of inline, etc... In addition to int f(void) vs int f(), legality vs illegality of p = malloc(n);, type of enum, keyword incompatibility (new, delete, etc...) which are already there in C89. I have yet seen a project where you could build C code with a C++ compiler - the only ones I know are specifically designed that way and it is painful. David From aleksandar27 at BRISIOVOnet.hr Fri Aug 6 09:58:02 2010 From: aleksandar27 at BRISIOVOnet.hr (alejandro) Date: Fri, 6 Aug 2010 15:58:02 +0200 Subject: Need help from someone that have PIL installed Message-ID: Can please someone run this little script that should output characters like ????? in an image. If it does it correctly can you tell me what OS, python version & PIL version you have? Or better if someone can tell me why this is not working properly on my PC? (Win XP, PIL 1.1.6., Python 2.6...) I don't recive any error it's just that the characters outputed in the image are not characters... more like symbols... # encoding:utf-8 from PIL import Image import ImageDraw import ImageFont img = Image.new("RGBA",(250,40)) #----------------------------------- making the image transparent pixdata = img.load() for y in xrange(img.size[1]): for x in xrange(img.size[0]): if pixdata[x, y] == (255, 255, 255, 255): pixdata[x, y] = (255, 255, 255, 0) #--------------------------------- drawing text draw = ImageDraw.Draw(img) arial = ImageFont.truetype("arial.ttf",32) # needs path to font, my font was in the same folder as the script string = "proba test ?????" draw.text((20,8),string ,font=arial, fill="red") # write img.save("img2.png", "PNG") From rdmoores at gmail.com Fri Aug 6 10:20:38 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 6 Aug 2010 07:20:38 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 18:47, Philip Semanchuk wrote: > > it's just a question of whether or not > the module in question exposes any kind of a version attribute. There's no > standard, unfortunately. The most popular convention seems to be via an > attribute called __version__, but I've also seen __VERSION__, VERSION, and > version. > Here's one more way: >>> import gmpy >>> gmpy.__version__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__version__' >>> >>> gmpy.version() '1.12' >>> Dick Moores From __peter__ at web.de Fri Aug 6 10:26:52 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 16:26:52 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: alejandro wrote: > Can please someone run this little script that should output characters > like ????? in an image. > If it does it correctly can you tell me what OS, python version & PIL > version you have? > Or better if someone can tell me why this is not working properly on my > PC? (Win XP, PIL 1.1.6., Python 2.6...) > I don't recive any error it's just that the characters outputed in the > image are not characters... more like symbols... > > # encoding:utf-8 > > from PIL import Image > import ImageDraw > import ImageFont # the last tuple is the background color img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) > draw = ImageDraw.Draw(img) > arial = ImageFont.truetype("arial.ttf",32) # needs path to font, my font > was in the same folder as the script # I think that the PIL can cope with unicode, so add a u-prefix here: text = u"proba test ?????" draw.text((20,8), text ,font=arial, fill="red") > # write > img.save("img2.png", "PNG") Peter From jldunn2000 at gmail.com Fri Aug 6 10:32:57 2010 From: jldunn2000 at gmail.com (loial) Date: Fri, 6 Aug 2010 07:32:57 -0700 (PDT) Subject: How to read large amounts of output via popen References: <9fe7d6b5-7bbd-4453-8cf3-99d6e1260325@i31g2000yqm.googlegroups.com> Message-ID: Ok, thats great. Thanks for the very elegant solution(s) On 6 Aug, 13:44, Nobody wrote: > On Fri, 06 Aug 2010 02:06:29 -0700, loial wrote: > > I need to read a large amount of data that is being returned in > > standard output by a shell script I am calling. > > > (I think the script should really be writing to a file but I have no > > control over that) > > If the script is writing to stdout, you get to decide whether its stdout > is a pipe, file, tty, etc. > > > Currently I have the following code. It seeems to work, however I > > suspect this may not work with large amounts of standard output. > > process=subprocess.Popen(['myscript', 'param1'], > > shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > > cmdoutput=process.communicate() > > It's certainly not the best way to read large amounts of output. > Unfortunately, better solutions get complicated when you need to read more > than one of stdout and stderr, or if you also need to write to stdin. > > If you only need stdout, you can just read from process.stdout in a loop. > You can leave stderr going to wherever the script's stderr goes (e.g. the > terminal), or redirect it to a file. > > If you really do need both stdout and stderr, then you either need to > enable non-blocking I/O, or use a separate thread for each stream, or > redirect at least one of them to a file. > > FWIW, Popen.communicate() uses non-blocking I/O on Unix and separate > threads on Windows (the standard library doesn't include a mechanism to > enable non-blocking I/O on Windows). > > > What is the best way to read a large amount of data from standard > > output and write to a file? > > For this case, the best way is to just redirect stdout to a file, rather > than passing it through the script, i.e.: > > ? ? ? ? outfile = open('outputfile', 'w') > ? ? ? ? process = subprocess.call(..., stdout = outfile) > ? ? ? ? outfile.close() From aleksandar27 at BRISIOVOnet.hr Fri Aug 6 10:37:01 2010 From: aleksandar27 at BRISIOVOnet.hr (alejandro) Date: Fri, 6 Aug 2010 16:37:01 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: > # the last tuple is the background color > img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) Thank you for this.... > # I think that the PIL can cope with unicode, so add a u-prefix here: > text = u"proba test ?????" > draw.text((20,8), text ,font=arial, fill="red") Nope i gives: SyntaxError: (unicode error) 'utf8' codec can't decode byte 0x9e in position 0: unexpected code byte and without the encoding : SyntaxError: Non-ASCII character '\x9e' in file C:\Documents and Settings\Perc\My Documents\NetBeansProjects\venus_header\src\venus_header.py on line 16, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details From __peter__ at web.de Fri Aug 6 10:51:16 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 16:51:16 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: alejandro wrote: >> # the last tuple is the background color >> img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) > Thank you for this.... > >> # I think that the PIL can cope with unicode, so add a u-prefix here: >> text = u"proba test ?????" >> draw.text((20,8), text ,font=arial, fill="red") > > Nope i gives: > SyntaxError: (unicode error) 'utf8' codec can't decode byte 0x9e in > position 0: unexpected code byte > > and without the encoding : > SyntaxError: Non-ASCII character '\x9e' in file C:\Documents and > Settings\Perc\My > Documents\NetBeansProjects\venus_header\src\venus_header.py on line 16, > but no encoding declared; see http://www.python.org/peps/pep-0263.html for > details Make sure that # encoding:utf-8 is the first line of your script, details and fineprint here: http://www.python.org/dev/peps/pep-0263/ Peter From pruebauno at latinmail.com Fri Aug 6 10:51:22 2010 From: pruebauno at latinmail.com (nn) Date: Fri, 6 Aug 2010 07:51:22 -0700 (PDT) Subject: new to python - trouble calling a function from another function References: Message-ID: <3f1c8f38-931c-4da7-83d8-d2c2f14e6611@i24g2000yqa.googlegroups.com> On Aug 5, 2:01?pm, Daniel Urban wrote: > > I'm building an elevator simulator for a class assignment. I recently ran > > into a roadblock and don't know how to fix it. For some reason, in my > > checkQueue function below, the call to self.goUp() is never executed. It is > > on the last line of code I pasted in. I can put print statements before and > > after the call and I have a print statement in goUp() itself. ?Only the > > print statements before and after the call are executed. The one inside > > goUp() is never executed because goUp() never seems to be executed. How can > > that be? I don't get any errors when the script executes. Surely this isn't > > some limitation I'm encountering? > > I think the self.goUp() call is executed, the goUp function gets > called, returns a generator object (because goUp is a generator > function), then you don't use that generator object for anything. > > Daniel Brandon, this example might help you understand the problem: >>> def g(): print('p1') yield 2 print('p3') >>> g() >>> b=g() >>> next(b) p1 2 >>> next(b) p3 Traceback (most recent call last): File "", line 1, in next(b) StopIteration >>> From wolftracks at invalid.com Fri Aug 6 11:00:55 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 08:00:55 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: >> I would think there are some small time and big time Python players who sell >> executable versions of their programs for profit? > > Yes. What's your point? That someone must know how to distribute them without having the source code ripped off. > >> disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils >> might have been part of it. > > distutils. > > http://docs.python.org/library/distutils.html I don't see ;how distutils is going to solve this problem. Are you suggesting the program should be packaged? Why? I can just send it to him as py code. distutils looks like it's for library modules, e.g., functions like math. > >> So how does one keep a non-Python user in lock step with my setup, so these >> problems don't arise? I don't even want to think about having him uninstall >> and re-install. :-) Although maybe he could do it without making matters >> worse. > > That's going to hinge on what your dependencies are. > > Geremy Condra From philip at semanchuk.com Fri Aug 6 11:09:17 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Fri, 6 Aug 2010 11:09:17 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: <6DA63311-7A1B-4C80-B8C0-5F89CA217B03@semanchuk.com> On Aug 6, 2010, at 10:20 AM, Richard D. Moores wrote: > On Thu, Aug 5, 2010 at 18:47, Philip Semanchuk > wrote: >> >> it's just a question of whether or not >> the module in question exposes any kind of a version attribute. >> There's no >> standard, unfortunately. The most popular convention seems to be >> via an >> attribute called __version__, but I've also seen __VERSION__, >> VERSION, and >> version. >> > Here's one more way: >>>> import gmpy >>>> gmpy.__version__ > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '__version__' >>>> >>>> gmpy.version() > '1.12' That's the nice thing about standards -- there are so many to choose from! =) Thanks for pointing that out; I'll update my code. bye Philip From __peter__ at web.de Fri Aug 6 11:14:07 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 17:14:07 +0200 Subject: Python Portability--Not very portable? References: Message-ID: W. eWatson wrote: >>> I would think there are some small time and big time Python players who >>> sell executable versions of their programs for profit? >> >> Yes. What's your point? > That someone must know how to distribute them without having the source > code ripped off. Yes, but he won't tell for fear of getting ripped off of his knowledge. From aleksandar27 at BRISIOVOnet.hr Fri Aug 6 11:22:32 2010 From: aleksandar27 at BRISIOVOnet.hr (alejandro) Date: Fri, 6 Aug 2010 17:22:32 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: > > Make sure that > > # encoding:utf-8 > > is the first line of your script, details and fineprint here: > > http://www.python.org/dev/peps/pep-0263/ > > Peter Tryed that... What was the output of my script on your computer? From wolftracks at invalid.com Fri Aug 6 11:27:43 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 08:27:43 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: I can't respond to otten directly, since he uses gmane. Here's my response. W. eWatson wrote: >>> >>> I would think there are some small time and big time Python players who >>> >>> sell executable versions of their programs for profit? >> >> >> >> Yes. What's your point? > > That someone must know how to distribute them without having the source > > code ripped off. Ott wrote? Yes, but he won't tell for fear of getting ripped off of his knowledge. Who won't tell? Why would I send you the py code, for example, if I wanted to protect it because of its importance? I'd put it in exe form and send it and allow you to input data to produce the desired result of the program. From __peter__ at web.de Fri Aug 6 11:44:05 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 17:44:05 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: alejandro wrote: >> Make sure that >> >> # encoding:utf-8 >> >> is the first line of your script, details and fineprint here: >> >> http://www.python.org/dev/peps/pep-0263/ >> >> Peter > > Tryed that... What happened? > What was the output of my script on your computer? $ python -V Python 2.6.4 $ python -c "import Image; print Image.VERSION" 1.1.6 $ cat draw_text.py # encoding:utf-8 from PIL import Image import ImageDraw import ImageFont img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) draw = ImageDraw.Draw(img) FONT = "/usr/share/fonts/truetype/msttcorefonts/arial.ttf" arial = ImageFont.truetype(FONT, 32) text = u"proba test ?????" print repr(text) draw.text((20,8), text, font=arial, fill="red") img.save("tmp.png") $ python draw_text.py u'proba test \xbe\xe6\xe8\xf0\xb9' The image looks as expected. Peter From __peter__ at web.de Fri Aug 6 12:03:04 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 18:03:04 +0200 Subject: Python Portability--Not very portable? References: Message-ID: W. eWatson wrote: > I can't respond to otten directly, since he uses gmane. Here's my > response. > > W. eWatson wrote: > > >>> >>> I would think there are some small time and big time Python > players who > >>> >>> sell executable versions of their programs for profit? > >> >> > >> >> Yes. What's your point? > > > That someone must know how to distribute them without having the > > > source code ripped off. > Ott wrote? > Yes, but he won't tell for fear of getting ripped off of his knowledge. > > > Who won't tell? The the guy who knows how to distribute the source code without having it ripped off... Seriously, I try to make a joke once in a while, usually with devastating results. The idea you were meant to take away was that once you start thinking about a protection scheme there is always a next step until you reach the point where your software, say, is completely safe, but also completely unusable. Had Guido started the language in that mindset there would be no Python for you to worry about its ripp-off safety. > Why would I send you the py code, for example, if I > wanted to protect it because of its importance? Because if you think again you may find that it's not as important as you think? > I'd put it in exe form > and send it and allow you to input data to produce the desired result of > the program. There is no analog in python, and if you cannot concentrate on your honest customers the only option that offers reasonable "safety" would be to turn your application into web service. Peter From aahz at pythoncraft.com Fri Aug 6 12:10:24 2010 From: aahz at pythoncraft.com (Aahz) Date: 6 Aug 2010 09:10:24 -0700 Subject: Checking that 2 pdf are identical (md5 a solution?) References: <58d8ce50-35b1-4a0a-8588-ed7c19a7d349@w30g2000yqw.googlegroups.com> Message-ID: In article , rlevesque wrote: > >Given your expertise I will not be able to 'repay' you by helping on >Python problems but if you ever need help with SPSS related problems I >will be pleased to provide the assistance you need. Generally speaking, the community philosophy is "pay forward" -- help someone else who needs it (either here or somewhere else). When everyone helps other people, it all evens out. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From nawabadeel at gmail.com Fri Aug 6 12:14:00 2010 From: nawabadeel at gmail.com (Muhammad Adeel) Date: Fri, 6 Aug 2010 09:14:00 -0700 (PDT) Subject: Smith-Waterman Algorithm in Python Message-ID: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> Hi, Does any one about any implementation of classical Smith Waterman local alignment algorithm and it's variants for aligning natural language text? thanks From fetchinson at googlemail.com Fri Aug 6 12:54:14 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 6 Aug 2010 18:54:14 +0200 Subject: Smith-Waterman Algorithm in Python In-Reply-To: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> Message-ID: > Does any one about any implementation of classical Smith Waterman > local alignment algorithm and it's variants for aligning natural > language text? Please see http://tinyurl.com/2wy43fh Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From thomas at jollans.com Fri Aug 6 12:55:46 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 06 Aug 2010 18:55:46 +0200 Subject: Need help from someone that have PIL installed In-Reply-To: References: Message-ID: <4C5C3E92.9090008@jollans.com> On 08/06/2010 04:37 PM, alejandro wrote: > >> # the last tuple is the background color >> img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) > Thank you for this.... > >> # I think that the PIL can cope with unicode, so add a u-prefix here: >> text = u"proba test ?????" >> draw.text((20,8), text ,font=arial, fill="red") > > Nope i gives: > SyntaxError: (unicode error) 'utf8' codec can't decode byte 0x9e in position > 0: unexpected code byte Is the file, which you claim is UTF-8 encoded, actually UTF-8 encoded? If you're not sure, explicitly tell your text editor to save the file as UTF-8, and then try again. > > and without the encoding : > SyntaxError: Non-ASCII character '\x9e' in file C:\Documents and > Settings\Perc\My Documents\NetBeansProjects\venus_header\src\venus_header.py > on line 16, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details > > > From ppearson at nowhere.invalid Fri Aug 6 13:20:30 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 6 Aug 2010 17:20:30 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> Message-ID: <8c2uiuFg9bU1@mid.individual.net> On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: [snip] > I can imagine a case where you might want to compare a > string with `is`: > > FORWARD = "forward" > BACKWARD = "backward" > > ... > > def func(direction=FORWARD): > if direction is FORWARD: > ... > elif direction is BACKWARD: > ... > else: > ... > > in case you expect people to specifically use the constants > you provided in the module. Here, the fact that FORWARD > actually is the string "forward" might be considered an > implementation detail. Using a string instead of an > `object()` has the advantage that it makes usage in error > messages easier. > > Actually, I've never seen such a use, as far as I remember. > What do other people here think? Is the code above, which > compares strings with `is`, bad style, and if yes, why? How > would you write the code instead? Hey, that's a cute example, but . . . what a trap! Is it possible to document the use-the-object-not-the-string requirement loudly enough that people won't get caught? -- To email me, substitute nowhere->spamcop, invalid->net. From debatem1 at gmail.com Fri Aug 6 13:31:16 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 10:31:16 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 8:00 AM, W. eWatson wrote: > >>> I would think there are some small time and big time Python players who >>> sell >>> executable versions of their programs for profit? >> >> Yes. What's your point? > > That someone must know how to distribute them without having the source code > ripped off. I've never seen a code obfuscation scheme I thought did the job the whole way, including compiling C, and Python bytecode is significantly easier to turn back into something resembling the original source (YMMV, I suppose). Also, if you don't know about common tools like distutils, the odds are pretty good that it isn't your code itself that is valuable to you- you're probably more interested in protecting your idea about what the code should do. At least for now, that's outside of the scope of technical solutions- discuss it with a lawyer, not a programmer. >> >>> disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and >>> disutils >>> might have been part of it. >> >> distutils. >> >> http://docs.python.org/library/distutils.html > > I don't see ;how distutils is going to solve this problem. Are you > suggesting the program should be packaged? Why? I can just send it to him as > py code. distutils looks like it's for library modules, e.g., functions like > math. ...no. Distutils is handy because you could just bundle your dependencies and hand them an easy-to-install package, which would be a quick way to get everybody on the same page. Of course, depending on the licenses those dependencies are under you might want to do even more talking to a lawyer than I've previously suggested before you go about trying to sell that bundle- I'm sure you wouldn't want to 'rip off' great free projects like python and numpy. Geremy Condra From wolftracks at invalid.com Fri Aug 6 13:35:38 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 10:35:38 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On 8/6/2010 9:03 AM, Peter Otten wrote: ... > > Seriously, I try to make a joke once in a while, usually with devastating > results. The idea you were meant to take away was that once you start > thinking about a protection scheme there is always a next step until you > reach the point where your software, say, is completely safe, but also > completely unusable. Had Guido started the language in that mindset there > would be no Python for you to worry about its ripp-off safety. > >> Why would I send you the py code, for example, if I >> wanted to protect it because of its importance? > > Because if you think again you may find that it's not as important as you > think? > >> I'd put it in exe form >> and send it and allow you to input data to produce the desired result of >> the program. > > There is no analog in python, and if you cannot concentrate on your honest > customers the only option that offers reasonable "safety" would be to turn > your application into web service. > > Peter So you think Python is part of open software in terms of distributing a "product"? So I should stick to C, where one can distribute programs w/o revealing code details, and having a customer compile the code? It's been awhile since I've used Linux or Unix, but I think there's a lot of commercial code out there dependent upon it, and the users do not have to compile anything. From prakash.stack at gmail.com Fri Aug 6 13:44:35 2010 From: prakash.stack at gmail.com (prakash jp) Date: Fri, 6 Aug 2010 23:14:35 +0530 Subject: python interview quuestions Message-ID: Hi all, I would like to aquint myself with Python Interview questions . I am a Python Scripter, so if u could orient the pointers in the same direction it would be very handy Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Fri Aug 6 13:47:48 2010 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 06 Aug 2010 10:47:48 -0700 Subject: python interview quuestions In-Reply-To: References: Message-ID: <4C5C4AC4.6070005@islandtraining.com> On 08/06/2010 10:44 AM, prakash jp wrote: > Hi all, > I would like to aquint myself with Python Interview questions . I am a > Python Scripter, so if u could orient the pointers in the same > direction it would be very handy > Regards Huh??? From wolftracks at invalid.com Fri Aug 6 13:54:04 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 10:54:04 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On 8/5/2010 6:47 PM, Philip Semanchuk wrote: > > On Aug 5, 2010, at 8:55 PM, W. eWatson wrote: > >> It's been awhile since I've used python, and I recall there is a way >> to find the version number from the IDLE command line prompt. dir, >> help, __version.__? > > Hi Wayne, > FYI it's got nothing to do with IDLE, it's just a question of whether or > not the module in question exposes any kind of a version attribute. > There's no standard, unfortunately. The most popular convention seems to > be via an attribute called __version__, but I've also seen __VERSION__, > VERSION, and version. > > Here's some code that I wrote that you might find useful. It's from a > setup.py and it checks a list of modules on which our project depends to > see if (a) they're installed and (b) if the version installed is > adequate. In the snippet below, dependencies is a list of custom classes > that represent modules we need (e.g. numpy). > > > # Try each module > for dependency in dependencies: > try: > __import__(dependency.name) > except ImportError: > # Uh oh! > dependency.installed = None > else: > # The module loaded OK. Get a handle to it and try to extract > # version info. > # Many Python modules follow the convention of providing their > # version as a string in a __version__ attribute. > module = sys.modules[dependency.name] > > # This is what I default to. > dependency.installed = "[version unknown]" > > for attribute_name in ("__version__", "__VERSION__", "VERSION", > "version"): > if hasattr(module, attribute_name): > dependency.installed = getattr(module, attribute_name) > break > > Hope this helps a little, > Philip > Thanks. I'll look into it. From wolftracks at invalid.com Fri Aug 6 13:58:24 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 10:58:24 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On 8/6/2010 10:31 AM, geremy condra wrote: > On Fri, Aug 6, 2010 at 8:00 AM, W. eWatson wrote: >> >>>> I would think there are some small time and big time Python players who >>>> sell >>>> executable versions of their programs for profit? >>> >>> Yes. What's your point? >> >> That someone must know how to distribute them without having the source code >> ripped off. > > I've never seen a code obfuscation scheme I thought did the job the > whole way, including compiling C, and Python bytecode is significantly > easier to turn back into something resembling the original source > (YMMV, I suppose). Also, if you don't know about common tools like > distutils, the odds are pretty good that it isn't your code itself > that is valuable to you- you're probably more interested in protecting > your idea about what the code should do. At least for now, that's > outside of the scope of technical solutions- discuss it with a lawyer, > not a programmer. > >>> >>>> disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and >>>> disutils >>>> might have been part of it. >>> >>> distutils. >>> >>> http://docs.python.org/library/distutils.html >> >> I don't see ;how distutils is going to solve this problem. Are you >> suggesting the program should be packaged? Why? I can just send it to him as >> py code. distutils looks like it's for library modules, e.g., functions like >> math. > > ...no. Distutils is handy because you could just bundle your > dependencies and hand them an easy-to-install package, which would be > a quick way to get everybody on the same page. Of course, depending on > the licenses those dependencies are under you might want to do even > more talking to a lawyer than I've previously suggested before you go > about trying to sell that bundle- I'm sure you wouldn't want to 'rip > off' great free projects like python and numpy. > > Geremy Condra Yes, code reversal programs have been around for many, many decades. Try one on MS Word or Adobe Acrobat. :-) Is there a complete illustration of using disutils? Our only dependencies are on Python Org material. We use no commercial or licensed code. From __peter__ at web.de Fri Aug 6 14:05:17 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 20:05:17 +0200 Subject: Python Portability--Not very portable? References: Message-ID: W. eWatson wrote: > So you think Python is part of open software in terms of distributing a > "product"? So I should stick to C, where one can distribute programs w/o > revealing code details, and having a customer compile the code? It's No, I'm trying to make you reconsider what you're going to protect rather than how. Aren't your customers more interested in using your software rather than tinker with it? From tjreedy at udel.edu Fri Aug 6 14:20:45 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 06 Aug 2010 14:20:45 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On 8/6/2010 5:27 AM, Richard D. Moores wrote: > So there would be a different implementation for each operating > system? One for Windows, one for linux? Or one for Vista and one for > XP? I'm just trying to clarify what is meant by "implementation". Different version of CPython (that string caching bit has changed in the past) and CPython versus Jython, PyPy, IronPython, Cython, etc. -- Terry Jan Reedy From cmpython at gmail.com Fri Aug 6 14:22:28 2010 From: cmpython at gmail.com (CM) Date: Fri, 6 Aug 2010 11:22:28 -0700 (PDT) Subject: Python Portability--Not very portable? References: Message-ID: On Aug 5, 9:50?pm, "W. eWatson" wrote: > In my on-again-off-again experience with Python for 18 months, > portability seems an issue. > > As an example, my inexperienced Python partner 30 miles away has gotten > out of step somehow. I think by installing a different version of numpy > than I use. I gave him a program we both use months ago, and he had no > trouble. (We both use IDLE on 2.5). I made a one character change to it > and sent him the new py file. He can't execute it. I doubt he has > changed anything in the intervening period. I'm curious: what was the one character change? And does your original program still work for him? Why did he install a different version of numpy if things were working for him? By the way, posting "x doesn't work" on a forum never gets you any help, because clairvoyance is not real :D. Posting actual error messages sample code does. > A further example. Months ago I decided to see if I could compile a > program to avoid such problems as above. I planned to satisfy that need, > and see if I could distribute some simple programs to non-Python > friends. I pretty well understand the idea,and got it working with a > small program. It seemed like a lot of manual labor to do it. As someone mentioned, you don't "compile" anything in Python. You can make a .exe file, though, using, as you know, py2exe. I find using GUI2Exe (which requires you have wxPython) to make things much easier and then if you want to be even fancier, use InnoSetup to make an installer. Once you get a working script in py2exe/GUI2Exe, it is usually a snap to make a new version of your .exe after changing your code a bit. As far as then updating your .exe files with your non-Python friends, you should search this newsgroup for Esky, which seems like a very nice idea for doing this very thing. Che From cmpython at gmail.com Fri Aug 6 14:24:57 2010 From: cmpython at gmail.com (CM) Date: Fri, 6 Aug 2010 11:24:57 -0700 (PDT) Subject: Python Portability--Not very portable? References: Message-ID: <9bf7870e-d0c8-492a-bcba-bfa018ffc159@x21g2000yqa.googlegroups.com> > As an example, my inexperienced Python partner 30 miles away has gotten > out of step somehow. I think by installing a different version of numpy > than I use. I gave him a program we both use months ago, and he had no > trouble. (We both use IDLE on 2.5). I made a one character change to it > and sent him the new py file. He can't execute it. I doubt he has > changed anything in the intervening period. I'm curious: what was the one character change? And does your original program still work for him? Why did he install a different version of numpy if things were working for him? By the way, posting "x doesn't work" on a forum never gets you any help, because clairvoyance is not real :D. Posting actual error messages sample code does. > A further example. Months ago I decided to see if I could compile a > program to avoid such problems as above. I planned to satisfy that need, > and see if I could distribute some simple programs to non-Python > friends. I pretty well understand the idea,and got it working with a > small program. It seemed like a lot of manual labor to do it. As someone mentioned, you don't "compile" anything in Python. You can make a .exe file, though, using, as you know, py2exe. I find using GUI2Exe (which requires you have wxPython) to make things much easier and then if you want to be even fancier, use InnoSetup to make an installer. Once you get a working script in py2exe/GUI2Exe, it is usually a snap to make a new version of your .exe after changing your code a bit. As far as then updating your .exe files with your non-Python friends, you should search this newsgroup for Esky, which seems like a very nice idea for doing this very thing. Che From prologic at shortcircuit.net.au Fri Aug 6 14:30:53 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 04:30:53 +1000 Subject: Perl -> Python unpack Message-ID: Hey all, Quick question for you Python enthusiasts that also happen to know Perl quite well... What does a* or A* translate to in Python when unpacking binary data with struct.unpack(...) ? cheers James -- -- James Mills -- -- "Problems are solved by method" From python.list at tim.thechases.com Fri Aug 6 14:32:08 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 06 Aug 2010 13:32:08 -0500 Subject: python interview quuestions In-Reply-To: References: Message-ID: <4C5C5528.5060608@tim.thechases.com> > I would like to aquint myself with Python Interview questions This came up a while ago: http://www.mail-archive.com/python-list at python.org/msg168961.html Most of that thread is still relevant (perhaps throw in some py3l questions too) -tkc From sschwarzer at sschwarzer.net Fri Aug 6 14:36:26 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 06 Aug 2010 20:36:26 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <8c2uiuFg9bU1@mid.individual.net> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> Message-ID: <4C5C562A.90702@sschwarzer.net> Hello Peter, On 2010-08-06 19:20, Peter Pearson wrote: > On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: > [snip] >> I can imagine a case where you might want to compare a >> string with `is`: >> >> FORWARD = "forward" >> BACKWARD = "backward" >> >> ... >> >> def func(direction=FORWARD): >> if direction is FORWARD: >> ... >> elif direction is BACKWARD: >> ... >> else: >> ... >> [...] > Hey, that's a cute example, Thanks! > but . . . what a trap! Is it > possible to document the use-the-object-not-the-string requirement > loudly enough that people won't get caught? That's a good question, actually that's the nagging problem I also have with the approach. In production code I might write # Use _these_ objects to indicate directions, not string # constants with the same value. FORWARD = "forward" BACKWARD = "backward" However, that won't help if people import the module and see the strings under "global data" and so assume they're "just strings". Moreover, if you have to write such a comment for every use of the idiom the conciseness of the approach vanishes. Another view at the matter would be to let clients of the module find out their mistake by unit tests. But of course that's somewhat doubtful as the intention should be to write robust instead of bug-inviting code. I wonder if there's a way to have both the "cuteness" of the string constants _and_ more robustness. Stefan From prologic at shortcircuit.net.au Fri Aug 6 14:45:11 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 04:45:11 +1000 Subject: python interview quuestions In-Reply-To: <4C5C5528.5060608@tim.thechases.com> References: <4C5C5528.5060608@tim.thechases.com> Message-ID: On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >> I would like to aquint myself with Python Interview questions > > This came up a while ago: > > http://www.mail-archive.com/python-list at python.org/msg168961.html > > Most of that thread is still relevant (perhaps throw in some py3l questions > too) A common thing you can do in interviews is ask your interviewee to write (in Python) a solution to the "FizzBuzz" problem. Any good competent Python programmer should be able to do this in 5-10mins (5 if you're good). cheers james -- -- James Mills -- -- "Problems are solved by method" From debatem1 at gmail.com Fri Aug 6 14:50:10 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 11:50:10 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 10:58 AM, W. eWatson wrote: > Is there a complete illustration of using disutils? Our only dependencies > are on Python Org material. We use no commercial or licensed code. http://tinyurl.com/3yhwjfj Geremy Condra From chris at simplistix.co.uk Fri Aug 6 15:06:00 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 06 Aug 2010 20:06:00 +0100 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: <9b4bd0c2-8912-4a60-9a12-b7b8586aba84@i4g2000prf.googlegroups.com> References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <9b4bd0c2-8912-4a60-9a12-b7b8586aba84@i4g2000prf.googlegroups.com> Message-ID: <4C5C5D18.3090101@simplistix.co.uk> DarkBlue wrote: > On Aug 5, 7:06 pm, Chris Withers wrote: >> Peter Otten wrote: >>>>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) >>> 'en_US.UTF8' >>>>>> print locale.currency(13535, grouping=True) >>> $13,535.00 >> Okay, so if I'm writing a wsgi app, and I want to format depending on >> the choices of the currently logged in users, what would you recommend? >> >> I can't do setlocale, since that would affect all users, and in a >> mult-threaded environment that would be bad. >> >> Does that mean the whole locale package is useless to all web-app builders? >> >> Chris > > from re import * > > class editmoney(float): > def __init__(self,mymoney): What does this have to do with my question about locales in multi-threaded environments? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From python.list at tim.thechases.com Fri Aug 6 15:11:54 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 06 Aug 2010 14:11:54 -0500 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <4C5C5E7A.5050203@tim.thechases.com> On 08/06/10 13:45, James Mills wrote: > On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >>> I would like to aquint myself with Python Interview questions >> >> This came up a while ago: >> >> http://www.mail-archive.com/python-list at python.org/msg168961.html >> >> Most of that thread is still relevant (perhaps throw in some py3l questions >> too) > > A common thing you can do in interviews is ask > your interviewee to write (in Python) a solution > to the "FizzBuzz" problem. Any good competent > Python programmer should be able to do this > in 5-10mins (5 if you're good). Another common thing you can do on a newsgroup is mention the "FizzBuzz" problem. Any good competent newsgroup will produce a multitude of proposed solutions, the majority of which will be wrong. ;-) -tkc From wolftracks at invalid.com Fri Aug 6 15:14:53 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 12:14:53 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: I must be missing something. I tried this. (Windows, IDLE, Python 2.5) # Try each module import sys import numpy import scipy import string dependencies = "numyp", "scipy" for dependency in dependencies: try: __import__(dependency.name) except ImportError: # Uh oh! dependency.installed = None else: # The module loaded OK. Get a handle to it and try to extract # version info. # Many Python modules follow the convention of providing their # version as a string in a __version__ attribute. module = sys.modules[dependency.name] # This is what I default to. dependency.installed = "[version unknown]" for attribute_name in ("__version__", "__VERSION__", "VERSION", "version"): if hasattr(module, attribute_name): dependency.installed = getattr(module, attribute_name) break The result was this. Traceback (most recent call last): File "C:/Users/Wayne/Sandia_Meteors/Trajectory_Estimation/dependency_code", line 10, in __import__(dependency.name) AttributeError: 'str' object has no attribute 'name' From prologic at shortcircuit.net.au Fri Aug 6 15:19:16 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 05:19:16 +1000 Subject: python interview quuestions In-Reply-To: <4C5C5E7A.5050203@tim.thechases.com> References: <4C5C5528.5060608@tim.thechases.com> <4C5C5E7A.5050203@tim.thechases.com> Message-ID: On Sat, Aug 7, 2010 at 5:11 AM, Tim Chase wrote: > Another common thing you can do on a newsgroup is mention the "FizzBuzz" > problem. ?Any good competent newsgroup will produce a multitude of proposed > solutions, the majority of which will be wrong. ;-) That's actually a very good point! Someone should post this very problem to this newsgroups/list and see how many active python programmers here actually "get it right" :) *evil grin* --james -- -- James Mills -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Fri Aug 6 15:28:39 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 6 Aug 2010 12:28:39 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 12:14 PM, W. eWatson wrote: > I must be missing something. I tried this. (Windows, IDLE, Python 2.5) > # Try each module > import sys > import numpy > import scipy > import string > > dependencies = "numyp", "scipy" > for dependency in dependencies: > ? ?try: > ? ? ? ?__import__(dependency.name) > ? ?except ImportError: > ? ? ? ?# Uh oh! > ? ? ? ?dependency.installed = None > ? ?else: > ? ? ? ?# The module loaded OK. Get a handle to it and try to extract > ? ? ? ?# version info. > ? ? ? ?# Many Python modules follow the convention of providing their > ? ? ? ?# version as a string in a __version__ attribute. > ? ? ? ?module = sys.modules[dependency.name] > > ? ? ? ?# This is what I default to. > ? ? ? ?dependency.installed = "[version unknown]" > > ? ? ? ?for attribute_name in ("__version__", "__VERSION__", "VERSION", > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "version"): > ? ? ? ? ? ?if hasattr(module, attribute_name): > ? ? ? ? ? ? ? ?dependency.installed = getattr(module, attribute_name) > ? ? ? ? ? ? ? ?break > > The result was this. > Traceback (most recent call last): > ?File "C:/Users/Wayne/Sandia_Meteors/Trajectory_Estimation/dependency_code", > line 10, in > ? ?__import__(dependency.name) > AttributeError: 'str' object has no attribute 'name' > -- Try reading the code, not just copying and pasting. dependencies isn't supposed to be a list of strings. It's a list of objects (at least) a name and an installed attribute. > http://mail.python.org/mailman/listinfo/python-list > From tgrav at mac.com Fri Aug 6 15:31:36 2010 From: tgrav at mac.com (Tommy Grav) Date: Fri, 06 Aug 2010 15:31:36 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Aug 6, 2010, at 3:14 PM, W. eWatson wrote: > I must be missing something. I tried this. (Windows, IDLE, Python 2.5) > # Try each module > import sys > import numpy > import scipy > import string > > dependencies = "numyp", "scipy" > for dependency in dependencies: > try: > __import__(dependency.name) > except ImportError: > # Uh oh! > dependency.installed = None > else: > # The module loaded OK. Get a handle to it and try to extract > # version info. > # Many Python modules follow the convention of providing their > # version as a string in a __version__ attribute. > module = sys.modules[dependency.name] > > # This is what I default to. > dependency.installed = "[version unknown]" > > for attribute_name in ("__version__", "__VERSION__", "VERSION", > "version"): > if hasattr(module, attribute_name): > dependency.installed = getattr(module, attribute_name) > break > > The result was this. > Traceback (most recent call last): > File "C:/Users/Wayne/Sandia_Meteors/Trajectory_Estimation/dependency_code", line 10, in > __import__(dependency.name) > AttributeError: 'str' object has no attribute 'name' > -- > http://mail.python.org/mailman/listinfo/python-list dependencies = "numpy", "scipy" is a tuple of two strings, when you do your for loop you first get "numpy" (a string) and it does not have a .name attribute. Tommy From ethan at stoneleaf.us Fri Aug 6 15:34:24 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 06 Aug 2010 12:34:24 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: <4C5C562A.90702@sschwarzer.net> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <4C5C562A.90702@sschwarzer.net> Message-ID: <4C5C63C0.9060508@stoneleaf.us> Stefan Schwarzer wrote: > Hello Peter, > > On 2010-08-06 19:20, Peter Pearson wrote: >> On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: >> [snip] >>> I can imagine a case where you might want to compare a >>> string with `is`: >>> >>> FORWARD = "forward" >>> BACKWARD = "backward" >>> >>> ... >>> >>> def func(direction=FORWARD): >>> if direction is FORWARD: >>> ... >>> elif direction is BACKWARD: >>> ... >>> else: >>> ... >>> [...] > >> Hey, that's a cute example, > > Thanks! > >> but . . . what a trap! Is it >> possible to document the use-the-object-not-the-string requirement >> loudly enough that people won't get caught? > > That's a good question, actually that's the nagging problem > I also have with the approach. > > In production code I might write > > # Use _these_ objects to indicate directions, not string > # constants with the same value. > FORWARD = "forward" > BACKWARD = "backward" > > However, that won't help if people import the module and see > the strings under "global data" and so assume they're "just > strings". Moreover, if you have to write such a comment for > every use of the idiom the conciseness of the approach > vanishes. > > Another view at the matter would be to let clients of the > module find out their mistake by unit tests. But of course > that's somewhat doubtful as the intention should be to write > robust instead of bug-inviting code. > > I wonder if there's a way to have both the "cuteness" of the > string constants _and_ more robustness. > > Stefan Instead of using 'is' use '=='. Maybe not as cute, but definitely more robust! ~Ethan~ From albert at spenarnc.xs4all.nl Fri Aug 6 15:41:28 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 06 Aug 2010 19:41:28 GMT Subject: Easy questions from a python beginner References: <4c495b50$0$28634$c3e8da3@news.astraweb.com> Message-ID: In article <4c495b50$0$28634$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Thu, 22 Jul 2010 21:23:05 -0700, Stephen Hansen wrote: > >> On 7/22/10 7:47 PM, wheres pythonmonks wrote: >[...] >>> The truth is that I don't intend to use these approaches in anything >>> serious. However, I've been known to do some metaprogramming from time >>> to time. >> >> Depending on how you define "metaprogramming", Python is pretty >> notoriously ill-suited towards the task (more, its basically considered >> a feature it doesn't let you go there) -- or, it allows you to do vast >> amounts of stuff with its few dark magic hooks. I've never had a >> satisfying definition of metaprogramming that more then 50% of any group >> agree with, so I'm not sure which you're looking for. :) > >I disagree strongly at your characterisation that Python is notorious for >being ill-suited towards metaprogramming. I'd say the complete opposite >-- what is considered dark and scary metaprogramming tasks in other >languages is considered too ordinary to even mention in Python. > >If you have a class that defines a single member (or attribute in Python >terminology) "spam", and you want to add a second "ham" to a specific >instance, such a thing is either deep, dark metaprogramming in some >languages, if not outright impossible. In Python it is not even >noteworthy: > >instance.ham = "something" # *yawns* > >Recently there was a thread started by some Java or C++ refugee who was >distressed about attribute access in Python, because it made >metaprogramming frighteningly easy: > >http://mail.python.org/pipermail/python-list/2010-June/1248029.html > >My response at the time was: Python makes metaprogramming *easy*: > >http://mail.python.org/pipermail/python-list/2010-June/1248053.html > >I can't imagine how he would have reacted if we had showed him how easy >it is to monkey-patch built-in functions... > >[...] >> But! What it doesn't let you do is get clever with syntax and write a >> sort of "simplified" or domain specific language to achieve certain >> sorts of repetitive tasks quickly. You always end up writing normal >> Python that looks like all other Python. > >Exactly... 90% of the time that you think you want a DSL, Python beat you >to it. > >It is true that other languages (like Lisp, or Forth) allow you to write >your own syntax. That's incredibly powerful, but it also has serious >costs. If you can define your own syntax, that means every piece of code >you look at is potentially a different language. The answer is, of course, discipline. I'm a Forth programmer and I morf Forth into an assembler. Now some sources become assembler sources and one should be very adamant about it. I've written a Perl interpreter for those sources, and a Python interpreter would be even easier. If I'm doing Python, I don't miss macro possibilities, but sometimes my code gets repetitive. If I ever get bored by repetition, there is m4. m4 < aap.pym > aap.py python aap.py (See my site below for Forth assemblers, and non-trivial m4 usage.) >-- >Steven Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From jjposner at optimum.net Fri Aug 6 16:07:42 2010 From: jjposner at optimum.net (John Posner) Date: Fri, 06 Aug 2010 16:07:42 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C5C6B8E.1070300@optimum.net> On 8/2/2010 11:00 PM, John Posner wrote: > On 7/31/2010 1:31 PM, John Posner wrote: >> >> Caveat -- there's another description of defaultdict here: >> >> http://docs.python.org/library/collections.html#collections.defaultdict >> >> ... and it's bogus. This other description claims that __missing__ is a >> method of defaultdict, not of dict. > > Following is a possible replacement for the bogus description. Comments > welcome. I intend to submit a Python doc bug, and I'd like to have a > clean alternative to propose. After some off-list discussion with Ethan Furman (many thanks!), the Python Doc bug is submitted: #9536 at bugs.python.org. -John From landa.martin at gmail.com Fri Aug 6 16:10:42 2010 From: landa.martin at gmail.com (Martin Landa) Date: Fri, 6 Aug 2010 13:10:42 -0700 (PDT) Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Message-ID: <8e7cd90c-1053-44e0-b0ce-ea95e2025a2c@d17g2000yqb.googlegroups.com> Hi, On Aug 5, 9:32?pm, Nobody wrote: > I don't know about methods, but it works for functions. > > > Sample code: > > > ? ? ... > > ? ? G_set_error_routine(byref(self._print_error)) > > This won't work; you have to be more explicit, e.g.: > > ? ? ? ? errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int)) > ? ? ? ? errfunc = errtype(print_error) > ? ? ? ? G_set_error_routine(errfunc) the C function is defined as G_set_error_routine = _libs['grass_gis. 7.0.svn'].G_set_error_routine G_set_error_routine.restype = None G_set_error_routine.argtypes = [CFUNCTYPE(UNCHECKED(c_int), String, c_int)] I defined in Python function print_error() def print_error(self, msg, type): print msg, type and errtype = CFUNCTYPE(UNCHECKED(c_int), String, c_int) errfunc = errtype(print_error) G_set_error_routine(errfunc) unfortunately the application crashes when print_error() is called from C library static void vfprint_error(int type, const char *template, va_list ap) { char buffer[2000]; /* G_asprintf does not work */ vsprintf(buffer, template, ap); G_debug(5, "print_error(): msg = \"%s\" type = %d", buffer, type); print_error(buffer, type); } Any idea how to solve it. Thanks, Martin From landa.martin at gmail.com Fri Aug 6 16:18:37 2010 From: landa.martin at gmail.com (Martin Landa) Date: Fri, 6 Aug 2010 13:18:37 -0700 (PDT) Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> <8e7cd90c-1053-44e0-b0ce-ea95e2025a2c@d17g2000yqb.googlegroups.com> Message-ID: <98c10bcc-40f9-4a2a-a187-1f1997aab7d4@z10g2000yqb.googlegroups.com> Hi, On Aug 6, 10:10?pm, Martin Landa wrote: > Any idea how to solve it. Thanks, Martin I overlooked note """ Make sure you keep references to CFUNCTYPE objects as long as they are used from C code. ctypes doesn?t, and if you don?t, they may be garbage collected, crashing your program when a callback is made. """ If I defined errtype and errfunc as global variable everything works. Thanks again for your help. Martin From debatem1 at gmail.com Fri Aug 6 16:28:53 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 13:28:53 -0700 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: On Fri, Aug 6, 2010 at 11:45 AM, James Mills wrote: > On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >>> I would like to aquint myself with Python Interview questions >> >> This came up a while ago: >> >> http://www.mail-archive.com/python-list at python.org/msg168961.html >> >> Most of that thread is still relevant (perhaps throw in some py3l questions >> too) > > A common thing you can do in interviews is ask > your interviewee to write (in Python) a solution > to the "FizzBuzz" problem. Any good competent > Python programmer should be able to do this > in 5-10mins (5 if you're good). > > cheers > james If I had to wait 5 minutes while a candidate tried to solve this problem I would not hire them. One minute, fine- maybe you're just a little rusty or nervous, or the rare person who has to back away from real-world programming concerns to deal with a trivial problem like this. If English isn't your native tongue I might double or even triple that. Otherwise, no way- I'm going to spend more time hanging over your head than you'll save me. Geremy Condra From prologic at shortcircuit.net.au Fri Aug 6 16:37:05 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 06:37:05 +1000 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: On Sat, Aug 7, 2010 at 6:28 AM, geremy condra wrote: > If I had to wait 5 minutes while a candidate tried to solve this > problem I would not hire them. Yes you do raise a valid point. It should really only take you a mere few seconds or so to write a solution to this. More over, it can be done in just a single line of Python. 7 if you're not very familiar with Python. cheers James -- -- James Mills -- -- "Problems are solved by method" From joncle at googlemail.com Fri Aug 6 17:10:35 2010 From: joncle at googlemail.com (Jon Clements) Date: Fri, 6 Aug 2010 14:10:35 -0700 (PDT) Subject: new to python - trouble calling a function from another function References: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> Message-ID: On 5 Aug, 16:15, Brandon McCombs wrote: > Jon Clements wrote: > > On 5 Aug, 08:25, Brandon McCombs wrote: > >> Hello, > > >> I'm building an elevator simulator for a class assignment. I recently > >> ran into a roadblock and don't know how to fix it. For some reason, in > >> my checkQueue function below, the call to self.goUp() is never executed. > >> It is on the last line of code I pasted in. I can put print statements > >> before and after the call and I have a print statement in goUp() itself. > >> ? Only the print statements before and after the call are executed. The > >> one inside goUp() is never executed because goUp() never seems to be > >> executed. How can that be? I don't get any errors when the script > >> executes. Surely this isn't some limitation I'm encountering? > > >> thanks > > >> sorry about the formatting > > >> --------------------------------------------- > >> class Elevator(Process): > >> def __init__(self,name): > >> ? ? ? ? Process.__init__(self,name=name) > >> ? ? ? ? self.numPassengers = 0 > >> ? ? ? ? self.passengerList = [] > >> ? ? ? ? self.passengerWaitQ = [] > >> ? ? ? ? self.currentFloor = 1 > >> ? ? ? ? self.idle = 1 > >> ? ? ? ? self.newPassengers = 0 > >> def goUp(self): > >> ? ? ? ? print "here" > >> ? ? ? ? bubbleSort(self.passengerList, len(self.passengerList)) > >> ? ? ? ? self.currentFloor += 1 > >> ? ? ? ? if len(self.passengerList) > 0: > >> ? ? ? ? ? ?for p in self.passengerList: > >> ? ? ? ? ? ? ? if self.currentFloor == p.destination: > >> ? ? ? ? ? ? ? ? yield (p.destination - self.currenteFloor) * TRAVELTIME, self > >> ? ? ? ? ? ? ? ? reactivate(p) > >> ? ? ? ? ? ? ? ? p.inBuilding() > >> ? ? ? ? ? ? ? else: > >> ? ? ? ? ? ? ? ? self.goUp() > > >> def checkQueue(self): > >> ? ? ? ? if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < > >> MAXCAPACITY: > >> ? ? ? ? if len(self.passengerWaitQ) < MAXCAPACITY: > >> ? ? ? ? ? ? self.newPassengers = len(self.passengerWaitQ) > >> ? ? ? ? else: > >> ? ? ? ? ? ? ?self.newPassengers = MAXCAPACITY - len(self.passengerList) > >> ? ? ? ? for i in range(0,self.newPassengers): > >> ? ? ? ? ? self.passengerList.append(self.passengerWaitQ.pop()) > >> ? ? ? ? self.goUp() > > > Hi Brandon, > > > Nice one at having a good crack at coding before posting! > > > From your posted code, I'm struggling to see what's trying to be > > taught to you for this class assignment. > > not relevant at this point > > > > > As a note it'll be worth reading PEP 8 regarding naming conventions, > > because it looks very Java-ish to me! > > ok but not relevant > > > > > (I might be taking too much a real-world approach in the following, > > but do with it as you will...) > > > I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere. > > Although what I'm thinking is that different Elevators will have > > different capacities and different floors they service. An Elevator is > > *not* going to know its number of passengers (the most it could do is > > capacity based on weight restrictions) therefore it's not going to > > know the number of new passengers on each floor either. > > okay but not relevant to the problem at hand > > > > > A couple of things that'd be worthwhile: > > > 1) Post the requirements for your assignment - what's it supposed to > > output etc... > > that isn't relevant for determining at the python level why a function > simply isn't being called > > > 2) Go find an elevator, take a pen and pad with you, and stand in it > > for 30 mins or so, and see how the real thing deals with situations > > and make notes. ie, does it queue requests, or decide to take the next > > nearest floor, when does it stop and open etc...? > > > hth > > > Jon. > > actually it doesn't help at all since you decided to focus on everything > but my actual question of why a function call wasn't working but rather > question the validity of the program itself Heard of something called 'sentences' that start with a capital letter that end with (mostly) a full stop? Anyway, what I suggested was that your design is massively flawed. You ask a group, that's friendly to newbies for help, and you receive advice... then "bitch" about it. Indeed, the intention was to make you re-think the whole program -- then you'd have learnt more. Focusing on one thing when it's the wrong design anyway is a *bad thing*. Remember, you've posted to a list that have members that have done 30+ years of programming in a professional role. Just my 2c, Jon. From luke.leighton at gmail.com Fri Aug 6 17:32:31 2010 From: luke.leighton at gmail.com (Luke Kenneth Casson Leighton) Date: Fri, 6 Aug 2010 22:32:31 +0100 Subject: HL7 v3 (XML) importer Message-ID: an HL7 v2 importer was written by john paulett, and it has been enhanced to support some of the HL7 v3 standard, which is XML-based. no dependencies are required: xml.sax is used so as to reduce the dependencies to purely python. additionally, as HL7 has versions/revisions, published data specifications were pulled from mirthcorp.com and transformed into python, automatically. HL7v3 revisions 2.1, 2.2, 2.3, 2.31, 2.4 and 2.5 are supported. there is still work to be carried out: MSH, PID, NTE, ORC, ORB and OBX are the presently supported segmentss, with a hard-coded assumption about the data hierarchy instead of using the same MessageFormat specifications that mirthcorp.com have written. this is likely to be corrected soon, but the project for which the code is being updated only requires "lab data imports", so support for other MessageFormats is not a high priority. in case anyone is interested, this hl7 library is to be used in gnumed, to be able to import laboratory data reports into the gnumed database. code is at: http://github.com/lkcl/hl7 i realise that this code is pretty specialist, but if you're looking around for free software libraries or applications that support HL7, http://mirthcorp.com is pretty much it, and mirth is pretty heavy-duty and forces a dependency of java and javascript for scripting, which may be of concern to some. hence, this smaller library is being created, in python. l. From debatem1 at gmail.com Fri Aug 6 17:47:10 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 14:47:10 -0700 Subject: new to python - trouble calling a function from another function In-Reply-To: References: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> Message-ID: On Thu, Aug 5, 2010 at 8:15 AM, Brandon McCombs wrote: > Jon Clements wrote: >> >> On 5 Aug, 08:25, Brandon McCombs wrote: >>> >>> Hello, >>> >>> I'm building an elevator simulator for a class assignment. I recently >>> ran into a roadblock and don't know how to fix it. For some reason, in >>> my checkQueue function below, the call to self.goUp() is never executed. >>> It is on the last line of code I pasted in. I can put print statements >>> before and after the call and I have a print statement in goUp() itself. >>> ?Only the print statements before and after the call are executed. The >>> one inside goUp() is never executed because goUp() never seems to be >>> executed. How can that be? I don't get any errors when the script >>> executes. Surely this isn't some limitation I'm encountering? >>> >>> thanks >>> >>> sorry about the formatting >>> >>> --------------------------------------------- >>> class Elevator(Process): >>> def __init__(self,name): >>> ? ? ? ?Process.__init__(self,name=name) >>> ? ? ? ?self.numPassengers = 0 >>> ? ? ? ?self.passengerList = [] >>> ? ? ? ?self.passengerWaitQ = [] >>> ? ? ? ?self.currentFloor = 1 >>> ? ? ? ?self.idle = 1 >>> ? ? ? ?self.newPassengers = 0 >>> def goUp(self): >>> ? ? ? ?print "here" >>> ? ? ? ?bubbleSort(self.passengerList, len(self.passengerList)) >>> ? ? ? ?self.currentFloor += 1 >>> ? ? ? ?if len(self.passengerList) > 0: >>> ? ? ? ? ? for p in self.passengerList: >>> ? ? ? ? ? ? ?if self.currentFloor == p.destination: >>> ? ? ? ? ? ? ? ?yield (p.destination - self.currenteFloor) * TRAVELTIME, >>> self >>> ? ? ? ? ? ? ? ?reactivate(p) >>> ? ? ? ? ? ? ? ?p.inBuilding() >>> ? ? ? ? ? ? ?else: >>> ? ? ? ? ? ? ? ?self.goUp() >>> >>> def checkQueue(self): >>> ? ? ? ?if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < >>> MAXCAPACITY: >>> ? ? ? ?if len(self.passengerWaitQ) < MAXCAPACITY: >>> ? ? ? ? ? ?self.newPassengers = len(self.passengerWaitQ) >>> ? ? ? ?else: >>> ? ? ? ? ? ? self.newPassengers = MAXCAPACITY - len(self.passengerList) >>> ? ? ? ?for i in range(0,self.newPassengers): >>> ? ? ? ? ?self.passengerList.append(self.passengerWaitQ.pop()) >>> ? ? ? ?self.goUp() >> >> Hi Brandon, >> >> Nice one at having a good crack at coding before posting! >> >> From your posted code, I'm struggling to see what's trying to be >> taught to you for this class assignment. > > not relevant at this point > >> >> As a note it'll be worth reading PEP 8 regarding naming conventions, >> because it looks very Java-ish to me! > > ok but not relevant > >> >> (I might be taking too much a real-world approach in the following, >> but do with it as you will...) >> >> I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere. >> Although what I'm thinking is that different Elevators will have >> different capacities and different floors they service. An Elevator is >> *not* going to know its number of passengers (the most it could do is >> capacity based on weight restrictions) therefore it's not going to >> know the number of new passengers on each floor either. > > okay but not relevant to the problem at hand > >> >> A couple of things that'd be worthwhile: >> >> 1) Post the requirements for your assignment - what's it supposed to >> output etc... > > that isn't relevant for determining at the python level why a function > simply isn't being called > >> 2) Go find an elevator, take a pen and pad with you, and stand in it >> for 30 mins or so, and see how the real thing deals with situations >> and make notes. ie, does it queue requests, or decide to take the next >> nearest floor, when does it stop and open etc...? >> >> hth >> >> Jon. >> > > actually it doesn't help at all since you decided to focus on everything but > my actual question of why a function call wasn't working but rather question > the validity of the program itself This is too bad. You looked like you were all set to be the poster child for how to ask a good question here, and now you've blown it. Geremy Condra From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:13:50 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:13:50 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> Message-ID: <4c5c891d$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 17:20:30 +0000, Peter Pearson wrote: > On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: [snip] >> I can imagine a case where you might want to compare a string with >> `is`: >> >> FORWARD = "forward" >> BACKWARD = "backward" [...] >> Actually, I've never seen such a use, as far as I remember. What do >> other people here think? Is the code above, which compares strings with >> `is`, bad style, and if yes, why? How would you write the code instead? > > Hey, that's a cute example, but . . . what a trap! Is it possible to > document the use-the-object-not-the-string requirement loudly enough > that people won't get caught? Nope. People don't read documentation :) That's why I prefer to test for human-readable constants using equality, so if the caller prefers to call func(x, "forward") instead of func(x, FORWARD) it will still work. Or I use FOWARD = object() BACKWARDS = object() and force them to use my constants. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:23:05 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:23:05 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <4c5c8b49$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 05:28:40 -0700, DG wrote: > I've always thought of it as you don't compare strings with "is", you > *should* use == The reasoning is that you don't know if that string > instance is the only one in memory. This is excellent advice. I won't say that there is "never" a use-case for testing strings for identity, but I can't think of one that isn't contrived and artificial. > I've heard as an implementation > detail, since strings are immutable, that Python will only create one > actual instance and just assign new references to it (your first x is y > example), but to compare equality it just makes sense to use "==", not > to ask if it is the same object in memory. Plus, I believe the "==" > operator will check if the variables point to the same object. Yes, that is an optimization that CPython performs. Other implementations may do different, but the optimization is so obvious and so cheap that I would be shocked if any of the major implementations fail to do so. > Using is/is not with None works well, because I believe there will > always only be 1 None object. Yes, that is correct, but there's also a semantic difference. Generally, when testing for None, you actually want None and not some look-alike that merely tests equal to None. You want to "accept no substitutes", and so an identity test is necessary. -- Steven From wolfram.hinderer at googlemail.com Fri Aug 6 18:24:21 2010 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Fri, 6 Aug 2010 15:24:21 -0700 (PDT) Subject: default behavior References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> Message-ID: On 6 Aug., 22:07, John Posner wrote: > On 8/2/2010 11:00 PM, John Posner wrote: > > > On 7/31/2010 1:31 PM, John Posner wrote: > > >> Caveat -- there's another description of defaultdict here: > > >>http://docs.python.org/library/collections.html#collections.defaultdict > > >> ... and it's bogus. This other description claims that __missing__ is a > >> method of defaultdict, not of dict. > > > Following is a possible replacement for the bogus description. Comments > > welcome. I intend to submit a Python doc bug, and I'd like to have a > > clean alternative to propose. > > After some off-list discussion with Ethan Furman (many thanks!), the > Python Doc bug is submitted: #9536 at bugs.python.org. > > -John This is probably nitpicking, but the patch calls __missing__ a special method. However, unlike special methods, it is not invoked by "special syntax" but by the dict's __getitem__ method. (len() invokes __len__ on any object - you can't do something similar with __missing__.) __missing__ is also not listed as a special method on http://docs.python.org/py3k/reference/datamodel.html#special-method-names However, "normal" special method lookup seems to be used. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:26:59 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:26:59 GMT Subject: Python Portability--Not very portable? References: Message-ID: <4c5c8c33$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 08:00:55 -0700, W. eWatson wrote: >>> I would think there are some small time and big time Python players >>> who sell executable versions of their programs for profit? >> >> Yes. What's your point? > That someone must know how to distribute them without having the source > code ripped off. That's what copyright law is for. If you think that distributing object code (instead of source code) is going to deter a serious hacker, you're deluded. Besides, I don't mean to be rude, but what makes you think anyone would care about stealing your code? If you think people are interested in stealing your code, you're almost certainly wrong. The world is full of coders who think their two-bit text editor or re-implementation of PacMan is the most precious, precious software in existence. The vast majority of them are wrong. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:28:52 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:28:52 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> Message-ID: <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: >> Plus, I believe the >> "==" operator will check if the variables point to the same object. > > No, that's what `is` is for. Actually, yes, equality is implemented with a short-cut that checks for identity first. That makes something like: s = "abc"*1000*1000*10 s == s nice and quick, as Python can immediately recognise that a string is always equal to itself without having to walk the entire string comparing each character with itself. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:29:28 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:29:28 GMT Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> Message-ID: <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 11:23:50 +0000, kj wrote: > I don't get your point. Even when I *know* that a certain exception may > happen, I don't necessarily catch it. I catch only those exceptions for > which I can think of a suitable response that is *different* from just > letting the program fail. (After all, my own code raises its own > exceptions with the precise intention of making the program fail.) If > an unexpected exception occurs, then by definition, I had no better > response in mind for that situation than just letting the program fail, > so I'm happy to let that happen. If, afterwards, I think of a different > response for a previously uncaught exception, I'll modify the code > accordingly. > > I find this approach far preferable to the alternative of knowing a long > list of possible exceptions (some of which may never happen in actual > practice), and think of ways to keep the program still alive > no-matter-what. "No memory? No disk space? No problem! Just a flesh > wound!" What's the point of that? /me cheers wildly! Well said! -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:31:45 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:31:45 GMT Subject: Python Portability--Not very portable? References: Message-ID: <4c5c8d51$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 10:35:38 -0700, W. eWatson wrote: > So you think Python is part of open software in terms of distributing a > "product"? Python itself *is* open source software. It doesn't *require* you to write open source software. > So I should stick to C, where one can distribute programs w/o > revealing code details No you can't. That's the point that you are missing. When you ship a compiled exe, you are still shipping code, and anyone serious about "ripping off" your ideas will not find that even the tiniest barrier to doing so. Microsoft never ship their code to Windows, and yet virus and malware authors regularly and rapidly analyse it well enough to not only work out what it does and how it does it, but to discover vulnerabilities that even Microsoft don't know about. If MS can't protect their code, what makes you think your .exe file is going to any better protected? -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:32:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:32:11 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4c5c8d6b$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 11:42:39 +0200, Jean-Michel Pichavant wrote: > Steven D'Aprano wrote: >> On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: >> >>> P.S. Sorry for the top-post -- is there a way to not do top posts from >>> gmail? I haven't used usenet since tin. >>> >> Er, surely you can just move the cursor before you start typing??? >> > CTRL+END will bring the cursor at the end of the file (for most the the > mail clients). Bottom-posting is just as annoying as top-posting, except for very short posts like this. Posting in-line, where you trim the excess quoting to leave enough to give context, is most recommended. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:46:17 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:46:17 GMT Subject: Python Portability--Not very portable? References: Message-ID: <4c5c90b8$0$28666$c3e8da3@news.astraweb.com> On Thu, 05 Aug 2010 18:50:14 -0700, W. eWatson wrote: > As an example, my inexperienced Python partner 30 miles away has gotten > out of step somehow. I think by installing a different version of numpy > than I use. I gave him a program we both use months ago, and he had no > trouble. (We both use IDLE on 2.5). I made a one character change to it > and sent him the new py file. He can't execute it. I doubt he has > changed anything in the intervening period. What does that mean? It crashes? It raises an exception? He double-clicks on it and nothing happens? What error does he get? What was the one character change? Have you tested it and are you sure it works, or are you just assuming it works? What OS are you using? How did you send it to him? Can he open the file in a text editor, and what does he see? > A further example. Months ago I decided to see if I could compile a > program to avoid such problems as above. I planned to satisfy that need, > and see if I could distribute some simple programs to non-Python > friends. I pretty well understand the idea,and got it working with a > small program. It seemed like a lot of manual labor to do it. I'm sorry, I don't fully understand what you think this is going to accomplish. A program compiled to object code is going to be dependent on the hardware platform, the operating system, and any libraries that may or may not be installed. Most likely the *exact* version of the libraries. Do the words "DLL Hell" mean anything to you? How is that an advantage of Python's source-code distribution? -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:47:36 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:47:36 GMT Subject: Python Portability--Not very portable? References: Message-ID: <4c5c9107$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 10:58:24 -0700, W. eWatson wrote: > Is there a complete illustration of using disutils? Our only > dependencies are on Python Org material. We use no commercial or > licensed code. Oh my, the sheer ignorance that sentence reveals. Python and the standard library *is* licensed. I mean, good grief, when you start up Python's interpreter, it even says: Type "help", "copyright", "credits" or "license" for more information. Similarly any C compiler you use will also be licensed. If it's not, you have no right to use it! (Unless you can find a public domain compiler, which I doubt exists, and even if one does, I doubt it will be very good.) -- Steven From jjposner at optimum.net Fri Aug 6 19:29:22 2010 From: jjposner at optimum.net (John Posner) Date: Fri, 06 Aug 2010 19:29:22 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C5C9AD2.6010308@optimum.net> On 8/6/2010 6:24 PM, Wolfram Hinderer wrote: > > This is probably nitpicking, but the patch calls __missing__ a special > method. However, unlike special methods, it is not invoked by "special > syntax" but by the dict's __getitem__ method. (len() invokes __len__ > on any object - you can't do something similar with __missing__.) > > __missing__ is also not listed as a special method on > http://docs.python.org/py3k/reference/datamodel.html#special-method-names > > However, "normal" special method lookup seems to be used. Fair enough. Please add your comment to #9536 at bugs.python.org. Tx, John From ritchy_gato at hotmail.com Fri Aug 6 19:47:58 2010 From: ritchy_gato at hotmail.com (Ritchy lelis) Date: Fri, 6 Aug 2010 16:47:58 -0700 (PDT) Subject: How to implement a pipeline...??? Please help Message-ID: <5242b005-31b6-4a9c-afd9-6fbb82e28db7@l14g2000yql.googlegroups.com> Hi guys In the development of my ADC project i have a new new challenge. First i need to implement a 10 Bit pipelineADC that will be the basis to later implement any kind of pipeline arquitecture (i mean, with 10 Bit, 16 Bit or any other configuration i want) i wish to... What's a 10 Bit pipiline ADC? This link with a draw will help have a perfect view of what is it: http://t3.gstatic.com/images?q=tbn:ANd9GcQK_Pwz3ssk1yoDDFwGjJ5FWAwcqr1mV9EwdndlHCEvOMdTOa4&t=1&usg=__-TsH7dnNdJm4GZTuWCxjvajZhfk= To have a 10 Bit pipiline ADC we need 9 stages, where 8 of them are a 1.5 bit configuration and the last one have a 2 Bit configuration. How it works? When we inject a input voltage (at the first block), it will be computed in the first 1.5 Bit stage and when finished the compute it will generate a output voltage who served of input voltage for the second 1.5 Bit stage which in his turn generate also a output voltage who served of input voltage in the third stage ... and successively continuing until the ninth stage. The ninth stage it's a 2 Bit stage and it will receive the last output voltage from the eighth stage and in his turn it will compute a final output signal. I already implemented the 1.5 Bit/stage and the 2 Bit/stage functions with good results (i already watch their plot's and they are cool to me) but my Pipeline function try don't seems that good. After the 2 Bit compute i expect a output signal like the drawing on the link below but more stretched. http://t3.gstatic.com/images?q=tbn:ANd9GcQGQYDW0iLCSXfMMurIksWsgklsvtj26IBtQRacFtY7ifu9RQA&t=1&usg=__-yHJFMatnCPcf9jWQv3kaxM0brE= Instead of have a lot of steps one after the another, it will have something like a single step only. Why? That it's because when we have a pipeline with a lot of stage's the final output voltage until the 2 Bit stage it's very "dense" and long and that nearly saturating the last block ( the 2 Bit stage). Next i will leave the code that I have done so far for my Pipeline function: ------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------- from flash1b5 import flash1b5 from flash1b5 import * from flash2b import flash2b from flash2b import * import matplotlib.pyplot as plt import numpy as np from pylab import * if __name__ == "__main__": Inc = raw_input("Valor do Incrimento = ") Vref = np.linspace(1,1, Inc) Vi = np.linspace(-1,1, Inc) Cs = np.linspace(3e-12, 3e-12, Inc) Cf = np.linspace(3e-12, 3e-12, Inc) f1 = flash1b5(Vi, Vref, Cs, Cf) Vin1 = f1[0] Vt1 = f1[1] Vd1 = f1[2] f2b = flash2b(Vt1, Vref) Vin2 = f2b[0] Vd2 = f2b[1] hold(True) fig2 = figure(1,figsize=(8,5)) ax2 = fig2.add_subplot(111, autoscale_on=False, xlim=(-1,1), ylim=(-0.5,2.5)) ax2.plot(Vin2, Vd2, lw=2, color='blue') grid (True); xlabel('V_ent');ylabel('Vout_Digital') plt.show() ------------------------------------------------------------------------------------------------------------------------------------------------------------------- The 1.5 Bit function: import numpy as np from pylab import * def flash1b5(Vi, Vref, Cs, Cf): Vin = np.zeros(Vi.shape, dtype=np.float) Vt = np.zeros(Vi.shape, dtype=np.float) Vd = np.zeros(Vi.shape, dtype=np.float) if any(Vi > Vref/4): mask1 = (Vi > Vref/4) np.putmask(Vin, mask1, Vi) Vs= (1+Cs/Cf)*Vin - (Cs/Cf)*Vref np.putmask(Vd, mask1, [2]) np.putmask(Vt, mask1, Vs) ## if any(-Vref/4 <= Vi) and any( Vi<= Vref/4): mask2 = (-Vref/4 <= Vi) & (Vi <= Vref/4) np.putmask(Vin, mask2, Vi) Vs = (1+(Cs/Cf))*Vin np.putmask(Vd, mask2, [1]) np.putmask(Vt, mask2, Vs) ## if any(Vi < -Vref/4): mask3 = (Vi < -Vref/4) np.putmask(Vin, mask3, Vi) Vs= (1+Cs/Cf)*Vin + (Cs/Cf)*Vref np.putmask(Vd, mask3, [0]) np.putmask(Vt, mask3, Vs) ## out = [Vin, Vt, Vd] return out ------------------------------------------------------------------------------------------------------------------------------------------------------------------- The 2 Bit function: import numpy as np from pylab import * def flash2b(Vi, Vref): Vin = np.zeros(Vi.shape, dtype=np.float) Vt = np.zeros(Vi.shape, dtype=np.float) Vd = np.zeros(Vi.shape, dtype=np.float) if any(Vi > Vref/2): mask1 = (Vi > Vref/2) np.putmask(Vin, mask1, Vi) np.putmask(Vd, mask1, [3]) if any(Vi > 0) and any(Vref/2 >= Vi): mask2 = (Vref/2 >= Vi) & (Vi > 0) np.putmask(Vin, mask2, Vi) np.putmask(Vd, mask2, [2]) if any(Vi <= 0) and any(-Vref/2 < Vi): mask3 = (-Vref/2 < Vi) & (Vi <= 0) np.putmask(Vin, mask3, Vi) np.putmask(Vd, mask3, [1]) if any(Vi <= -Vref/2): mask4 = (Vi < -Vref/2) np.putmask(Vin, mask4, Vi) np.putmask(Vd, mask4, [0]) S_Out = [Vin, Vd] return S_Out --------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------- Guys i'm asking if it's possible for a generic function for a pipeline, all the suggestions ideas are welcome. Also if you have a specific solution for my problem I will be grateful for it here. Thanks for reading my post. Cheers From nyamatongwe+thunder at gmail.com Fri Aug 6 20:05:09 2010 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 07 Aug 2010 10:05:09 +1000 Subject: Microsoft lessening commitment to IronPython and IronRuby Message-ID: There is a blog post from Jimmy Schementi who previously worked at Microsoft on IronRuby about the state of dynamic language work there. http://blog.jimmy.schementi.com/2010/08/start-spreading-news-future-of-jimmy.html Neil From dchichkov at gmail.com Fri Aug 6 20:45:31 2010 From: dchichkov at gmail.com (dmtr) Date: Fri, 6 Aug 2010 17:45:31 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? Message-ID: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> I'm running into some performance / memory bottlenecks on large lists. Is there any easy way to minimize/optimize memory usage? Simple str() and unicode objects() [Python 2.6.4/Linux/x86]: >>> sys.getsizeof('') 24 bytes >>> sys.getsizeof('0') 25 bytes >>> sys.getsizeof(u'') 28 bytes >>> sys.getsizeof(u'0') 32 bytes Lists of str() and unicode() objects (see ref. code below): >>> [str(i) for i in xrange(0, 10000000)] 370 Mb (37 bytes/item) >>> [unicode(i) for i in xrange(0, 10000000)] 613 Mb (63 bytes/item) Well... 63 bytes per item for very short unicode strings... Is there any way to do better than that? Perhaps some compact unicode objects? -- Regards, Dmitry ---- import os, time, re start = time.time() l = [unicode(i) for i in xrange(0, 10000000)] dt = time.time() - start vm = re.findall("(VmPeak.*|VmSize.*)", open('/proc/%d/status' % os.getpid()).read()) print "%d keys, %s, %f seconds, %f keys per second" % (len(l), vm, dt, len(l) / dt) From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 21:02:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 01:02:01 GMT Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: <4c5cb088$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 17:45:31 -0700, dmtr wrote: > I'm running into some performance / memory bottlenecks on large lists. > Is there any easy way to minimize/optimize memory usage? Yes, lots of ways. For example, do you *need* large lists? Often a better design is to use generators and iterators to lazily generate data when you need it, rather than creating a large list all at once. An optimization that sometimes may help is to intern strings, so that there's only a single copy of common strings rather than multiple copies of the same one. Can you compress the data and use that? Without knowing what you are trying to do, and why, it's really difficult to advise a better way to do it (other than vague suggestions like "use generators instead of lists"). Very often, it is cheaper and faster to just put more memory in the machine than to try optimizing memory use. Memory is cheap, your time and effort is not. [...] > Well... 63 bytes per item for very short unicode strings... Is there > any way to do better than that? Perhaps some compact unicode objects? If you think that unicode objects are going to be *smaller* than byte strings, I think you're badly informed about the nature of unicode. Python is not a low-level language, and it trades off memory compactness for ease of use. Python strings are high-level rich objects, not merely a contiguous series of bytes. If all else fails, you might have to use something like the array module, or even implement your own data type in C. But as a general rule, as I mentioned above, the best way to minimize the memory used by a large list is to not use a large list. I can't emphasise that enough -- look into generators and iterators, and lazily handle your data whenever possible. -- Steven From thomas at jollans.com Fri Aug 6 21:08:55 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 03:08:55 +0200 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: <4C5CB227.4070402@jollans.com> On 08/07/2010 02:45 AM, dmtr wrote: > I'm running into some performance / memory bottlenecks on large lists. > Is there any easy way to minimize/optimize memory usage? > > Simple str() and unicode objects() [Python 2.6.4/Linux/x86]: >>>> sys.getsizeof('') 24 bytes >>>> sys.getsizeof('0') 25 bytes >>>> sys.getsizeof(u'') 28 bytes >>>> sys.getsizeof(u'0') 32 bytes > > Lists of str() and unicode() objects (see ref. code below): >>>> [str(i) for i in xrange(0, 10000000)] 370 Mb (37 bytes/item) >>>> [unicode(i) for i in xrange(0, 10000000)] 613 Mb (63 bytes/item) > > Well... 63 bytes per item for very short unicode strings... Is there > any way to do better than that? Perhaps some compact unicode objects? There is a certain price you pay for having full-feature Python objects. What are you trying to accomplish anyway? Maybe the array module can be of some help. Or numpy? > > -- Regards, Dmitry > > ---- > import os, time, re > start = time.time() > l = [unicode(i) for i in xrange(0, 10000000)] > dt = time.time() - start > vm = re.findall("(VmPeak.*|VmSize.*)", open('/proc/%d/status' % > os.getpid()).read()) > print "%d keys, %s, %f seconds, %f keys per second" % (len(l), vm, dt, > len(l) / dt) From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 21:25:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 01:25:01 GMT Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <4c5cb5ec$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 06:37:05 +1000, James Mills wrote: > On Sat, Aug 7, 2010 at 6:28 AM, geremy condra > wrote: >> If I had to wait 5 minutes while a candidate tried to solve this >> problem I would not hire them. > > Yes you do raise a valid point. It should really only take you a mere > few seconds or so to write a solution to this. Yes, but the point is to come up with a solution that is *correct*, not merely a solution. *wink* Just the mere typing time will be "a few seconds or so", so you're leaving zero time for actual thought, let alone running the code at least once to test it. Personally, I'd rather see how a potential hire *tests* his code than how he writes it. Writing code is easy. Testing code is harder. Testing it properly is harder still -- it's amazing how many people forget that it's not just necessary to test the function on data that *works*, but also on data that fails as well (unless, of course, you're happy with function behaviour that is unspecified in the face of errors). I also want to see when the coder thinks she's done. If I say "Write a function that does fizzbuzz", does she assume I want *just* the function, or does she ask questions like "Do you want documentation and tests? What sort of tests?". Does she assume that because the fizzbuzz function is small it doesn't need documentation or testing? The Fizzbuzz algorithm itself is the simple part. If I'm hiring a coder, I care more about their attitude to documentation and testing than their ability to code up a tiny algorithm in five seconds time. I want to see if they are a careful coder, or a cowboy. > More over, it can be done in just a single line of Python. > > 7 if you're not very familiar with Python. Or if you value readability over conserving newlines. Some months ago I wrote a version of FizzBuzz. By the time I read the description of the problem, re-read it to make sure I understood it and looking for any hidden traps ("seems too simple to me, what have I missed?"), wrote a first draft, tested it, fixed a silly typo, and then tested it again, it took about 3-5 minutes. I don't believe I have anything to be ashamed about that, especially not when I look at the number of comments by people who claimed the exercise was so trivial that they did it in ten seconds, AND GOT IT WRONG. Then I added error checking, tests and documentation, and the whole exercise took about 20 minutes. That was probably overkill, but I was bored :) (At least I didn't turn it into a class.) -- Steven From greg.ewing at canterbury.ac.nz Fri Aug 6 21:36:30 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 07 Aug 2010 13:36:30 +1200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <4C5C562A.90702@sschwarzer.net> Message-ID: <8c3r45FsveU1@mid.individual.net> Ethan Furman wrote: > Instead of using 'is' use '=='. Maybe not as cute, but definitely more > robust! It's also just as efficient if you use strings that resemble identifiers, because they will be interned, so the comparison will end up just doing an indentity test anyway. -- Greg From dchichkov at gmail.com Fri Aug 6 21:39:27 2010 From: dchichkov at gmail.com (dmtr) Date: Fri, 6 Aug 2010 18:39:27 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Steven, thank you for answering. See my comments inline. Perhaps I should have formulated my question a bit differently: Are there any *compact* high performance containers for unicode()/str() objects in Python? By *compact* I don't mean compression. Just optimized for memory usage, rather than performance. What I'm really looking for is a dict() that maps short unicode strings into tuples with integers. But just having a *compact* list container for unicode strings would help a lot (because I could add a __dict__ and go from it). > Yes, lots of ways. For example, do you *need* large lists? Often a better > design is to use generators and iterators to lazily generate data when > you need it, rather than creating a large list all at once. Yes. I do need to be able to process large data sets. No, there is no way I can use an iterator or lazily generate data when I need it. > An optimization that sometimes may help is to intern strings, so that > there's only a single copy of common strings rather than multiple copies > of the same one. Unfortunately strings are unique (think usernames on facebook or wikipedia). And I can't afford storing them in db/memcached/redis/ etc... Too slow. > Can you compress the data and use that? Without knowing what you are > trying to do, and why, it's really difficult to advise a better way to do > it (other than vague suggestions like "use generators instead of lists"). Yes. I've tried. But I was unable to find a good, unobtrusive way to do that. Every attempt either adds some unnecessary pesky code, or slow, or something like that. See more at: http://bugs.python.org/issue9520 > Very often, it is cheaper and faster to just put more memory in the > machine than to try optimizing memory use. Memory is cheap, your time and > effort is not. Well... I'd really prefer to use say 16 bytes for 10 chars strings and fit data into 8Gb Rather than paying extra $1k for 32Gb. > > Well... ?63 bytes per item for very short unicode strings... Is there > > any way to do better than that? Perhaps some compact unicode objects? > > If you think that unicode objects are going to be *smaller* than byte > strings, I think you're badly informed about the nature of unicode. I don't think that that unicode objects are going to be *smaller*! But AFAIK internally CPython uses UTF-8? No? And 63 bytes per item seems a bit excessive. My question was - is there any way to do better than that.... > Python is not a low-level language, and it trades off memory compactness > for ease of use. Python strings are high-level rich objects, not merely a > contiguous series of bytes. If all else fails, you might have to use > something like the array module, or even implement your own data type in > C. Are there any *compact* high performance containers (with dict, list interface) in Python? -- Regards, Dmitry From greg.ewing at canterbury.ac.nz Fri Aug 6 21:41:03 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 07 Aug 2010 13:41:03 +1200 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5c8b49$0$28666$c3e8da3@news.astraweb.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4c5c8b49$0$28666$c3e8da3@news.astraweb.com> Message-ID: <8c3rcoF2tpU1@mid.individual.net> Steven D'Aprano wrote: > Generally, > when testing for None, you actually want None and not some look-alike > that merely tests equal to None. That's true, although I can't think of a use case for an object that compares equal to None but isn't -- except for obfuscated code competition entries and making obscure points in usenet discussions. :-) -- Greg From dchichkov at gmail.com Fri Aug 6 21:56:55 2010 From: dchichkov at gmail.com (dmtr) Date: Fri, 6 Aug 2010 18:56:55 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: > > Well... ?63 bytes per item for very short unicode strings... Is there > > any way to do better than that? Perhaps some compact unicode objects? > > There is a certain price you pay for having full-feature Python objects. Are there any *compact* Python objects? Optimized for compactness? > What are you trying to accomplish anyway? Maybe the array module can be > of some help. Or numpy? Ultimately a dict that can store ~20,000,000 entries: (u'short string' : (int, int, int, int, int, int, int)). -- Regards, Dmitry From clp2 at rebertia.com Fri Aug 6 22:03:46 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 6 Aug 2010 19:03:46 -0700 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Message-ID: On Fri, Aug 6, 2010 at 6:39 PM, dmtr wrote: >> > Well... ?63 bytes per item for very short unicode strings... Is there >> > any way to do better than that? Perhaps some compact unicode objects? >> >> If you think that unicode objects are going to be *smaller* than byte >> strings, I think you're badly informed about the nature of unicode. > > I don't think that that unicode objects are going to be *smaller*! > But AFAIK internally CPython uses UTF-8? Nope. unicode objects internally use UCS-2 or UCS-4, depending on how CPython was ./configure-d; the former is the default. See PEP 261. Cheers, Chris -- http://blog.rebertia.com From roy at panix.com Fri Aug 6 22:04:10 2010 From: roy at panix.com (Roy Smith) Date: Fri, 06 Aug 2010 22:04:10 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <4c5cb5ec$0$28666$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Personally, I'd rather see how a potential hire *tests* his code than how > he writes it. Writing code is easy. Testing code is harder. Testing it > properly is harder still -- it's amazing how many people forget that it's > not just necessary to test the function on data that *works*, but also on > data that fails as well (unless, of course, you're happy with function > behaviour that is unspecified in the face of errors). > > I also want to see when the coder thinks she's done. Perhaps I'm reading more into your choice of words than you intended, but I'm curious what you envision a "coder" does. I think of "coder" and a rather low-level job. Somebody who just writes code. I'm generally looking for somebody who is more of a software engineer. Somebody who is not just writing some code, but who is building a product. That means, as you suggest, that it's documented, tested, robust, maintainable, portable, all that good stuff. > If I say "Write a function that does fizzbuzz", does she assume I > want *just* the function, or does she ask questions like "Do you want > documentation and tests? What sort of tests?". I think this depends on the situation. For writing code at a whiteboard while i watched, I'd expect the candidate to concentrate just on the code itself. If it was an assigment, as in, "Write a program to do X, and mail it to me by tomorrow", I'd expect a much more complete treatment. From ldo at geek-central.gen.new_zealand Fri Aug 6 22:05:16 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 07 Aug 2010 14:05:16 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In message , David Cournapeau wrote: > I have yet seen a project where you could build C code with a C++ > compiler - the only ones I know are specifically designed that way and > it is painful. I seem to recall a FAQ entry, might have been on kernelnewbies.org, asking why the Linux kernel wasn?t written in C++. The answer explained that at one time there was an experiment to make the kernel compilable with a C++ compiler, without actually using any C++ features. The result: they lost about 10% in speed. That was enough to put the kernel developers off taking the experiment any further. From lists at cheimes.de Fri Aug 6 22:07:13 2010 From: lists at cheimes.de (Christian Heimes) Date: Sat, 07 Aug 2010 04:07:13 +0200 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: > I'm running into some performance / memory bottlenecks on large lists. > Is there any easy way to minimize/optimize memory usage? > > Simple str() and unicode objects() [Python 2.6.4/Linux/x86]: >>>> sys.getsizeof('') 24 bytes >>>> sys.getsizeof('0') 25 bytes >>>> sys.getsizeof(u'') 28 bytes >>>> sys.getsizeof(u'0') 32 bytes A Python str object contains much more than just the raw string. On a 32bit system it contains: * a pointer to its type (ptr with 4 bytes) * a reference counter (ssize_t, 4 bytes) * the length of the string (ssize_t, 4 bytes) * the cached hash of the string (long, 8 bytes) * interning state (int, 4 bytes) * a null terminated char array for its data. Christian From philip at semanchuk.com Fri Aug 6 22:18:13 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Fri, 6 Aug 2010 22:18:13 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Aug 6, 2010, at 3:14 PM, W. eWatson wrote: > I must be missing something. I tried this. (Windows, IDLE, Python 2.5) Yes, as Benjamin Kaplan pointed out and as I said in the email where I posted this code snippet, "dependencies is a list of custom classes that represent modules we need (e.g. numpy)." The code I posted was not meant to be a complete working example. It's part of a larger piece of code that I didn't have time to cook down to a simpler, self- sufficient whole. Also, in your list you've got "numyp" instead of "numpy". Also, at the top of your code you have "import numpy" and "import scipy" which defeats the purpose of this code. Try this (untested): import sys dependencies = ("numpy", "scipy", "some_other_module") for dependency in dependencies: try: __import__(dependency) except ImportError: # Uh oh! print "%s is not installed" % dependency else: # The module loaded OK. Get a handle to it and try to extract # version info. # Many Python modules follow the convention of providing their # version as a string in a __version__ attribute. module = sys.modules[dependency] for attribute_name in ("__version__", "__VERSION__", "VERSION", "version"): if hasattr(module, attribute_name): version = getattr(module, attribute_name) print "module %s has version %s" % (dependency, version) break bye Philip > # Try each module > import sys > import numpy > import scipy > import string > > dependencies = "numyp", "scipy" > for dependency in dependencies: > try: > __import__(dependency.name) > except ImportError: > # Uh oh! > dependency.installed = None > else: > # The module loaded OK. Get a handle to it and try to extract > # version info. > # Many Python modules follow the convention of providing their > # version as a string in a __version__ attribute. > module = sys.modules[dependency.name] > > # This is what I default to. > dependency.installed = "[version unknown]" > > for attribute_name in ("__version__", "__VERSION__", "VERSION", > "version"): > if hasattr(module, attribute_name): > dependency.installed = getattr(module, attribute_name) > break > > The result was this. > Traceback (most recent call last): > File "C:/Users/Wayne/Sandia_Meteors/Trajectory_Estimation/ > dependency_code", line 10, in > __import__(dependency.name) > AttributeError: 'str' object has no attribute 'name' > -- > http://mail.python.org/mailman/listinfo/python-list From nyamatongwe+thunder at gmail.com Fri Aug 6 22:18:35 2010 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 07 Aug 2010 12:18:35 +1000 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Message-ID: dmtr: > What I'm really looking for is a dict() that maps short unicode > strings into tuples with integers. But just having a *compact* list > container for unicode strings would help a lot (because I could add a > __dict__ and go from it). Add them all into one string or array and use indexes into that string. Neil From debatem1 at gmail.com Fri Aug 6 22:26:52 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 19:26:52 -0700 Subject: python interview quuestions In-Reply-To: <4c5cb5ec$0$28666$c3e8da3@news.astraweb.com> References: <4C5C5528.5060608@tim.thechases.com> <4c5cb5ec$0$28666$c3e8da3@news.astraweb.com> Message-ID: On Fri, Aug 6, 2010 at 6:25 PM, Steven D'Aprano wrote: > On Sat, 07 Aug 2010 06:37:05 +1000, James Mills wrote: > >> On Sat, Aug 7, 2010 at 6:28 AM, geremy condra >> wrote: >>> If I had to wait 5 minutes while a candidate tried to solve this >>> problem I would not hire them. >> >> Yes you do raise a valid point. It should really only take you a mere >> few seconds or so to write a solution to this. > > Yes, but the point is to come up with a solution that is *correct*, not > merely a solution. *wink* > > Just the mere typing time will be "a few seconds or so", so you're > leaving zero time for actual thought, let alone running the code at least > once to test it. I wouldn't let them have access to an interpreter for this either. The goal is to see if they can put out something that looks reasonably close to a solution; if so, they're probably trainable. Otherwise, GTFO. > Personally, I'd rather see how a potential hire *tests* his code than how > he writes it. Writing code is easy. Testing code is harder. Testing it > properly is harder still -- it's amazing how many people forget that it's > not just necessary to test the function on data that *works*, but also on > data that fails as well (unless, of course, you're happy with function > behaviour that is unspecified in the face of errors). Absolutely. A great problem for this is the ACM programming challenge pig latin translator- it contains a logic error that makes a certain case ambiguous. Hire the ones that spot the problem before they touch the keyboard on the spot, and put the ones that test for it at the top of the heap. > I also want to see when the coder thinks she's done. If I say "Write a > function that does fizzbuzz", does she assume I want *just* the function, > or does she ask questions like "Do you want documentation and tests? What > sort of tests?". Does she assume that because the fizzbuzz function is > small it doesn't need documentation or testing? The Fizzbuzz algorithm > itself is the simple part. If I'm hiring a coder, I care more about their > attitude to documentation and testing than their ability to code up a > tiny algorithm in five seconds time. I want to see if they are a careful > coder, or a cowboy. I have things I'd rather do than sit around and watch a candidate write tests. If I wanted them to write tests, I'd send them the problem before the interview and have them sell me on their way of solving it during the interview. > >> More over, it can be done in just a single line of Python. >> >> 7 if you're not very familiar with Python. > > Or if you value readability over conserving newlines. I was thinking the same thing. > Some months ago I wrote a version of FizzBuzz. By the time I read the > description of the problem, re-read it to make sure I understood it and > looking for any hidden traps ("seems too simple to me, what have I > missed?"), wrote a first draft, tested it, fixed a silly typo, and then > tested it again, it took about 3-5 minutes. I don't believe I have > anything to be ashamed about that, especially not when I look at the > number of comments by people who claimed the exercise was so trivial that > they did it in ten seconds, AND GOT IT WRONG. Given the expectation of interpreter-ready code rather than just logically correct and close enough, 3 minutes isn't insane. 5 minutes is still pretty out there, though. Of course, getting it wrong doesn't win anybody points. > Then I added error checking, tests and documentation, and the whole > exercise took about 20 minutes. That was probably overkill, but I was > bored :) Just maybe ;) Geremy Condra From python.list at tim.thechases.com Fri Aug 6 22:31:30 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 06 Aug 2010 21:31:30 -0500 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <4C5CC582.5080005@tim.thechases.com> On 08/06/10 15:37, James Mills wrote: > On Sat, Aug 7, 2010 at 6:28 AM, geremy condra wrote: >> If I had to wait 5 minutes while a candidate tried to solve this >> problem I would not hire them. > > Yes you do raise a valid point. It should really only take > you a mere few seconds or so to write a solution to this. > > More over, it can be done in just a single line of Python. > > 7 if you're not very familiar with Python. While it *can* be done in one line, I'm not sure it's the most legible solution. Though I must say I like this one-line python version: for i in range(1, 101): print ((i%3==0 and 'fizz' or '') + (i%5==0 and 'buzz' or '')) or i (adjust "3" and "5" for your local flavor of fizzbuzz) I'm not sure I'd hire a candidate that proposed this as a solution in earnest, but I'd have fun chatting with them :) -tkc From hunguponcontent at gmail.com Fri Aug 6 23:05:56 2010 From: hunguponcontent at gmail.com (Default User) Date: Fri, 6 Aug 2010 22:05:56 -0500 Subject: Python "why" questions Message-ID: >From "the emperor's new clothes" department: 1) Why do Python lists start with element [0], instead of element [1]? "Common sense" would seem to suggest that lists should start with [1]. 2) In Python 3, why is print a function only, so that: print "Hello, World" is not okay, but it must be print("Hello, World") instead? (Yeah, I know: picky, picky . . . ) 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but 8 * 3.57 displays as 28.56 (rounded off to 2 decimal places)? And yet, in Python 2.6, 8 * 3.57 displays as 28.559999999999999? And we wonder why kids don't want to learn to program. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryan at rfk.id.au Fri Aug 6 23:36:03 2010 From: ryan at rfk.id.au (Ryan Kelly) Date: Sat, 07 Aug 2010 13:36:03 +1000 Subject: Python "why" questions In-Reply-To: References: Message-ID: <1281152163.2089.6.camel@durian> On Fri, 2010-08-06 at 22:05 -0500, Default User wrote: > >From "the emperor's new clothes" department: > > 1) Why do Python lists start with element [0], instead of element > [1]? "Common sense" would seem to suggest that lists should start > with [1]. "Common sense" is wrong. There are many compelling advantages to numbering from zero instead of one: http://lambda-the-ultimate.org/node/1950 > 2) In Python 3, why is print a function only, so that: print "Hello, > World" is not okay, but it must be print("Hello, World") instead? > (Yeah, I know: picky, picky . . . ) The real question is, why was print so special in Python 2 that is can be called without parentheses? The answer was "no reason" and it was fixed in Python 3 to be consistent with the rest of the language. > 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but > 8 * 3.57 displays as 28.56 (rounded off to 2 decimal places)? And > yet, in Python 2.6, 8 * 3.57 displays as 28.559999999999999? Because the code for displaying floats was improved in python 3. You can follow the fascinating discussion on issue 7117: http://bugs.python.org/issue7117 I can't defend the rounding issues of floating point numbers in general - it's just "one of those things" that you have to deal with. But show me a language where floats don't have this problem. > And we wonder why kids don't want to learn to program. Yeah, obscure language warts, that must be the reason. Note to self: DNFTT... Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details From chare at labr.net Fri Aug 6 23:37:26 2010 From: chare at labr.net (Chris Hare) Date: Fri, 06 Aug 2010 22:37:26 -0500 Subject: sched() function questions Message-ID: <172F5EAB-7A0B-4FB9-AF53-4899B19027C5@labr.net> I am currently using threading.timer to execute an event in my big chunk of code. This is causing a problem with sqlite, so I am trying to figure out the sched function import sched import time def timerfunc(): print "hello", time.time() return(time.time()) def delay(period): time.sleep(period) def some(): s.enterabs(900,1, timerfunc, () ) s.run() s = sched.scheduler(timerfunc, delay) print time.time() some() x = 0 while 1: print x x = x + 1 time.sleep(60) print str(s.queue()) What I am trying to do is mimic the Timer function, where my code will continue to function while my scheduled function executes in 15 minutes or 900 seconds. This doesn't do it though. Any help? From zak.mc.kraken at libero.it Fri Aug 6 23:46:23 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Sat, 07 Aug 2010 05:46:23 +0200 Subject: Python "why" questions References: Message-ID: Default User wrote: >>From "the emperor's new clothes" department: > > 1) Why do Python lists start with element [0], instead of element [1]? > "Common sense" would seem to suggest that lists should start with [1]. http://userweb.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html > 2) In Python 3, why is print a function only, so that: print "Hello, > World" > is not okay, but it must be print("Hello, World") instead? (Yeah, I know: > picky, picky . . . ) "There should be one-- and preferably only one --obvious way to do it." > 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but 8 * > 3.57 displays as 28.56 (rounded off to 2 decimal places)? And yet, in > Python 2.6, 8 * 3.57 displays as 28.559999999999999? http://mail.python.org/pipermail/python-dev/2009-October/092958.html and replies -- By ZeD From ben+python at benfinney.id.au Sat Aug 7 00:28:19 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 07 Aug 2010 14:28:19 +1000 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> Message-ID: <87k4o311y4.fsf@benfinney.id.au> Steven D'Aprano writes: > On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: > > > P.S. Sorry for the top-post -- is there a way to not do top posts > > from gmail? I haven't used usenet since tin. > > Er, surely you can just move the cursor before you start typing??? I like to think that the cursor is placed at the top by default so that is easy: just travel down through the quoted material, removing it if not relevant and inserting one's responses where needed. -- \ ?Two hands working can do more than a thousand clasped in | `\ prayer.? ?Anonymous | _o__) | Ben Finney From pavlovevidence at gmail.com Sat Aug 7 00:55:26 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 6 Aug 2010 21:55:26 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: On Aug 6, 6:56?pm, dmtr wrote: > > > Well... ?63 bytes per item for very short unicode strings... Is there > > > any way to do better than that? Perhaps some compact unicode objects? > > > There is a certain price you pay for having full-feature Python objects. > > Are there any *compact* Python objects? Optimized for compactness? Yes, but probably not in the way that'd be useful to you. Look at the array module, and also consider the third-party numpy library. They store compact arrays of numeric types (mostly) but they have character type storage as well. That probably won't help you, though, since you have variable-length strings. I don't know of any third-party types that can do what you want, but there might be some. Search PyPI. > > What are you trying to accomplish anyway? Maybe the array module can be > > of some help. Or numpy? > > Ultimately a dict that can store ~20,000,000 entries: (u'short > string' : (int, int, int, int, int, int, int)). My recommendation would be to use sqlite3. Only if you know for sure that it's too slow--meaning that you've actually tried it and it was too slow, and nothing else--then should you bother with a For that I'd probably go with a binary tree rather than a hash. So you have a huge numpy character array that stores all 20 million short strings end-to-end (in lexical order, so that you can look up the strings with a binary search), then you have an numpy integer array that stores the indices into this string where the word boundaries are, and then an Nx7 numpy integer array storing the int return vslues. That's three compact arrays. Carl Banks From clp2 at rebertia.com Sat Aug 7 01:33:55 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 6 Aug 2010 22:33:55 -0700 Subject: Python "why" questions In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 8:05 PM, Default User wrote: > >From "the emperor's new clothes" department: > > 1)? Why do Python lists start with element [0], instead of element [1]? > "Common sense" would seem to suggest that lists should start with [1]. (In addition to the other good answers already given) Well, "tradition" (originating from C) suggests otherwise. *Very* few languages use 1-based indexing: http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(array)#Array_system_cross-reference_list > 2)? In Python 3, why is print a function only, so that: print "Hello, World" > is not okay, but it must be print("Hello, World") instead?? (Yeah, I know: > picky, picky . . . ) One less special case to learn; makes the language more regular and easier to learn. It also lets one write: f = lambda x: print(x) Which is not possible if print is a statement. Cheers, Chris -- http://blog.rebertia.com From torriem at gmail.com Sat Aug 7 01:56:04 2010 From: torriem at gmail.com (Michael Torrie) Date: Fri, 06 Aug 2010 23:56:04 -0600 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: <4C5CF574.20702@gmail.com> On 08/06/2010 07:56 PM, dmtr wrote: > Ultimately a dict that can store ~20,000,000 entries: (u'short > string' : (int, int, int, int, int, int, int)). I think you really need a real database engine. With the proper indexes, MySQL could be very fast storing and retrieving this information for you. And it will use your RAM to cache as it sees fit. Don't try to reinvent the wheel here. From torriem at gmail.com Sat Aug 7 02:10:05 2010 From: torriem at gmail.com (Michael Torrie) Date: Sat, 07 Aug 2010 00:10:05 -0600 Subject: new to python - trouble calling a function from another function In-Reply-To: References: Message-ID: <4C5CF8BD.6040609@gmail.com> On 08/05/2010 01:25 AM, Brandon McCombs wrote: > How can that be? I don't get any errors when the script > executes. Surely this isn't some limitation I'm encountering? > > > yield (p.destination - self.currenteFloor) * TRAVELTIME, self ^^^^^^^^^ To be succinct, goUp() is apparently a generator function. "yield" means the function needs to be iterated over; calling it just sets up the generator and returns a generator object. So yeah your goUp() call will appear (and actually does) do nothing at all. From dchichkov at gmail.com Sat Aug 7 02:27:46 2010 From: dchichkov at gmail.com (dmtr) Date: Fri, 6 Aug 2010 23:27:46 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: On Aug 6, 10:56?pm, Michael Torrie wrote: > On 08/06/2010 07:56 PM, dmtr wrote: > > > Ultimately a dict that can store ~20,000,000 entries: (u'short > > string' : (int, int, int, int, int, int, int)). > > I think you really need a real database engine. ?With the proper > indexes, MySQL could be very fast storing and retrieving this > information for you. ?And it will use your RAM to cache as it sees fit. > ?Don't try to reinvent the wheel here. No, I've tried. DB solutions are not even close in terms of the speed. Processing would take weeks :( Memcached or REDIS sort of work, but they are still a bit on the slow side, to be a pleasure to work with. The standard dict() container is *a lot* faster. It is also hassle free (accepting unicode keys/etc). I just wish there was a bit more compact dict container, optimized for large dataset and memory, not for speed. And with the default dict() I'm also running into some kind of nonlinear performance degradation, apparently after 10,000,000-13,000,000 keys. But I can't recreate this with a solid test case (see http://bugs.python.org/issue9520 ) :( -- Dmitry From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sat Aug 7 02:36:29 2010 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sat, 7 Aug 2010 06:36:29 +0000 (UTC) Subject: Is there any way to minimize str()/unicode() objects memory usage ?[Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Message-ID: dmtr wrote: > > What I'm really looking for is a dict() that maps short unicode > strings into tuples with integers. But just having a *compact* list > container for unicode strings would help a lot (because I could add a > __dict__ and go from it). > At this point, I'd suggest to use one of the dbm modules, and pack the integers with struct.pack into a short string(s). Depending on your usage pattern, there are marked performance differences between dbhash, gdbm, and dbm implementations, so perhaps it would pay off to invest sometime in benchmarking. If your data are write-once, then cdb has excellent performance (but a different API). The file will be usually cached in RAM, so no need to worry about I/O bottlenecks... and if small enough, you can always put it into a ramdisk. If your strings are long enough, you can improve memory usage with a use of zlib.compress (dumb and unoptimal way of using compression, but easy and present in the std library) - but always verify if the compressed strings are _shorter_ than originals. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From prologic at shortcircuit.net.au Sat Aug 7 02:43:39 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 16:43:39 +1000 Subject: Perl -> Python unpack In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 4:30 AM, James Mills wrote: > What does a* or A* translate to in Python when unpacking > binary data with struct.unpack(...) ? Fine I"ll answer my own question. Python _does not_ support implicit size in struct formatting rules. sizes are explicit meaning that you must "compute" the size you require. a* or A* would translate to 10s for example where you want a string with a size of 10. cheers James -- -- James Mills -- -- "Problems are solved by method" From macgyver at cyta.gr Sat Aug 7 02:45:28 2010 From: macgyver at cyta.gr (=?ISO-8859-7?Q?=CD=E9=EA=FC=EB=E1=EF=F2_=CA=EF=FD=F1=E1=F2?=) Date: Sat, 07 Aug 2010 09:45:28 +0300 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: <4C5B4D6E.1070501@tim.thechases.com> References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> <4C5B4D6E.1070501@tim.thechases.com> Message-ID: <4C5D0108.2090401@cyta.gr> ???? 6/8/2010 2:46 ??, ?/? Tim Chase ??????: > # variant B > for row in dataset: > host, hits, dt = row > # rest of your code here So, row is a tuple comprising of 3 fields, and host, hist, dt are variables assigned each one of row's tuple values by breaking it to it's elements. But what kind of objects is host, hits, dt that containes the row's tuple data themselves? tuples or lists and why? > # variant C > for host, hits, dt in row: > # rest of your code here > host, hits, data each and every one of them hold a piece of the row's tuple values. But what happens in here? 'for host, hits, dt in dataset:' Here we don't have the row tuple. So what tthose variabels store, and in what datatype they strore info in and what is the difference between this and 'for host, hits, dt in row:' What datatypes are these vars here and what data each one hold? > The data-type of the individual values would be whatever comes back > from the database as translated into Python (string, float/Decimal, > boolean, datetime, etc). In your example, it's likely a > string+integer+datetime as the 3 values. You can see why I prefer the > elegance of just performing the assignment in the for-loop (variant C). > If the fieds datatypes returned form the database are for exmaple page varchar(50) , hits inteeger[11], date datetime then the when python grabs those results fields it would translate them to 'page as string' , (hits as int) , 'date as string' respectively? Whcih emans it translated those fileds returned to the most appropriate-most close to prototype stored in database' datatypes automatically? > > [*] "about" the same because in #1 and #2, you also have access to the > whole row; whereas in #3, you don't have something called "row", but > you could reassemble it if you needed: > > row = (host, hits, dt Would that be a row or a tuple when joined? Again, thanks for ALL your preciosu help you provide me! From __peter__ at web.de Sat Aug 7 02:50:35 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Aug 2010 08:50:35 +0200 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: dmtr wrote: >> > Well... 63 bytes per item for very short unicode strings... Is there >> > any way to do better than that? Perhaps some compact unicode objects? >> >> There is a certain price you pay for having full-feature Python objects. > > Are there any *compact* Python objects? Optimized for compactness? > >> What are you trying to accomplish anyway? Maybe the array module can be >> of some help. Or numpy? > > Ultimately a dict that can store ~20,000,000 entries: (u'short > string' : (int, int, int, int, int, int, int)). I don't know to what extent it still applys but switching off cyclic garbage collection with import gc gc.disable() while building large datastructures used to speed up things significantly. That's what I would try first with your real data. Encoding your unicode strings as UTF-8 could save some memory. When your integers fit into two bytes, say, you can use an array.array() instead of the tuple. Peter From sschwarzer at sschwarzer.net Sat Aug 7 03:04:06 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 07 Aug 2010 09:04:06 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4C5D0566.8090801@sschwarzer.net> Hi Steven, On 2010-08-07 00:28, Steven D'Aprano wrote: > On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: >>> Plus, I believe the >>> "==" operator will check if the variables point to the same object. >> >> No, that's what `is` is for. > > Actually, yes, equality is implemented with a short-cut that checks for > identity first. That makes something like: > [...] Oops, I didn't realize that the OP had mentioned the identity check as an optimization in case the objects are the same. I thought he was confusing the operator with `is`. > s = "abc"*1000*1000*10 > s == s > > nice and quick, as Python can immediately recognise that a string is > always equal to itself without having to walk the entire string comparing > each character with itself. Yes, that definitely makes sense. I guess I would have implemented it this way as well. :) Stefan From nikos.the.gr33k at gmail.com Sat Aug 7 03:09:59 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 00:09:59 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format References: <4c5b99f6$0$1613$742ec2ed@news.sonic.net> Message-ID: <04b47c50-8d69-43e5-bdff-12d5526ddc17@s9g2000yqd.googlegroups.com> On 6 ???, 08:13, John Nagle wrote: > On 8/4/2010 4:40 PM, ????? wrote: > > > ? ? ? ? ? ?cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page > > = '%s' ORDER BY date DESC ''' % (page) ) > > Don't do string substitution ("%") on SQL statements. ?Let MySQLdb do it > for you, with proper escaping: > > ? ? cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s > ? ? ? ? ORDER BY date DESC''', (page,)) Thanks i didn't know. But you also do use '%s' here as well. Just without the quotes? Why? How is this valid? And also what's the comma after the (page,) ? What does the comam do? > > The difference is that if some external source can control "page", and > they put in a value like > > ? ? ? ? 100 ; DELETE FROM visitors; SELECT * FROM visitors > > you just lost your data. Thanks iam trying to test this because its very interesting and when i try: http://webville.gr/index.html?show=log&page="index.html ; DELETE FROM visitors; SELECT * FROM visitors" cgitb gives me an error 53 except MySQLdb.Error: 54 print ( "Error %d: %s" % (e.args[0], e.args[1]) ) 55 else: 56 #display dataset e undefined NameError: name 'e' is not defined args = ("name 'e' is not defined",) How can i try it successfully? Have to ssay here that i use mod_rewrite in my remote web server and every incoming html request gets treated by counter.py with this rule RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^/?(.+\.html) /cgi-bin/counter.py?page=$1 [L,PT,QSA] Also for the program exectuion to reach the: cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) statement i expect the user to: # ================================================================================================================= # if extra string is attached to the URL is 'log' then show excplicit page log and exit # ================================================================================================================= if form.getvalue('show') == 'log': Please help me reproduce what you suggest. I beleive its called MySQL injection and i very like want to see this in action! :-) From greg.ewing at canterbury.ac.nz Sat Aug 7 03:28:56 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 07 Aug 2010 19:28:56 +1200 Subject: Unicode error In-Reply-To: <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> Message-ID: <8c4fouF1bdU1@mid.individual.net> Steven D'Aprano wrote: > "No memory? No disk space? No problem! Just a flesh > wound!" What's the point of that? +1 QOTW From dchichkov at gmail.com Sat Aug 7 03:30:35 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 7 Aug 2010 00:30:35 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: On Aug 6, 11:50?pm, Peter Otten <__pete... at web.de> wrote: > I don't know to what extent it still applys but switching off cyclic garbage > collection with > > import gc > gc.disable() Haven't tried it on the real dataset. On the synthetic test it (and sys.setcheckinterval(100000)) gave ~2% speedup and no change in memory usage. Not significant. I'll try it on the real dataset though. > while building large datastructures used to speed up things significantly. > That's what I would try first with your real data. > > Encoding your unicode strings as UTF-8 could save some memory. Yes... In fact that's what I'm trying now... .encode('utf-8') definitely creates some clutter in the code, but I guess I can subclass dict... And it does saves memory! A lot of it. Seems to be a bit faster too.... > When your integers fit into two bytes, say, you can use an array.array() > instead of the tuple. Excellent idea. Thanks! And it seems to work too, at least for the test code. Here are some benchmarks (x86 desktop): Unicode key / tuple: >>> for i in xrange(0, 1000000): d[unicode(i)] = (i, i+1, i+2, i+3, i+4, i+5, i+6) 1000000 keys, ['VmPeak:\t 224704 kB', 'VmSize:\t 224704 kB'], 4.079240 seconds, 245143.698209 keys per second >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) 1000000 keys, ['VmPeak:\t 201440 kB', 'VmSize:\t 201440 kB'], 4.985136 seconds, 200596.331486 keys per second >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = (i, i+1, i+2, i+3, i+4, i+5, i+6) 1000000 keys, ['VmPeak:\t 125652 kB', 'VmSize:\t 125652 kB'], 3.572301 seconds, 279931.625282 keys per second Almost halved the memory usage. And faster too. Nice. -- Dmitry From greg.ewing at canterbury.ac.nz Sat Aug 7 03:33:44 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 07 Aug 2010 19:33:44 +1200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: <8c4g22F5ljU1@mid.individual.net> Lawrence D'Oliveiro wrote: > at one > time there was an experiment to make the kernel compilable with a C++ > compiler, without actually using any C++ features. The result: they lost > about 10% in speed. That was enough to put the kernel developers off taking > the experiment any further. FWIW, certain parts of the Darwin kernel are written in a carefully-selected subset of C++. So Apple evidently think that it makes sense to use some C++ in a Unix kernel under some circumstances. -- Greg From dchichkov at gmail.com Sat Aug 7 03:33:54 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 7 Aug 2010 00:33:54 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: Correction. I've copy-pasted it wrong! array.array('i', (i, i+1, i+2, i +3, i+4, i+5, i+6)) was the best. >>> for i in xrange(0, 1000000): d[unicode(i)] = (i, i+1, i+2, i+3, i+4, i+5, i+6) 1000000 keys, ['VmPeak:\t 224704 kB', 'VmSize:\t 224704 kB'], 4.079240 seconds, 245143.698209 keys per second >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = (i, i+1, i+2, i+3, i+4, i+5, i+6) 1000000 keys, ['VmPeak:\t 201440 kB', 'VmSize:\t 201440 kB'], 4.985136 seconds, 200596.331486 keys per second >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) 1000000 keys, ['VmPeak:\t 125652 kB', 'VmSize:\t 125652 kB'], 3.572301 seconds, 279931.625282 keys per second -- Dmitry From gagsl-py2 at yahoo.com.ar Sat Aug 7 03:44:19 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 07 Aug 2010 04:44:19 -0300 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> <4C5D0566.8090801@sschwarzer.net> Message-ID: En Sat, 07 Aug 2010 04:04:06 -0300, Stefan Schwarzer escribi?: > On 2010-08-07 00:28, Steven D'Aprano wrote: >> Actually, yes, equality is implemented with a short-cut that checks for >> identity first. That makes something like: >> [...] > > Oops, I didn't realize that the OP had mentioned the > identity check as an optimization in case the objects are > the same. I thought he was confusing the operator with `is`. > >> s = "abc"*1000*1000*10 >> s == s >> >> nice and quick, as Python can immediately recognise that a string is >> always equal to itself without having to walk the entire string >> comparing >> each character with itself. > > Yes, that definitely makes sense. I guess I would have > implemented it this way as well. :) For strings and other internal types this optimization certainly makes sense. For user-defined types it gets in the way and prevents defining an object such x==x is False (like NANs). -- Gabriel Genellina From __peter__ at web.de Sat Aug 7 04:16:47 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Aug 2010 10:16:47 +0200 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: dmtr wrote: > On Aug 6, 11:50 pm, Peter Otten <__pete... at web.de> wrote: >> I don't know to what extent it still applys but switching off cyclic >> garbage collection with >> >> import gc >> gc.disable() > > > Haven't tried it on the real dataset. On the synthetic test it (and > sys.setcheckinterval(100000)) gave ~2% speedup and no change in memory > usage. Not significant. I'll try it on the real dataset though. > > >> while building large datastructures used to speed up things >> significantly. That's what I would try first with your real data. >> >> Encoding your unicode strings as UTF-8 could save some memory. > > Yes... In fact that's what I'm trying now... .encode('utf-8') > definitely creates some clutter in the code, but I guess I can > subclass dict... And it does saves memory! A lot of it. Seems to be a > bit faster too.... > >> When your integers fit into two bytes, say, you can use an array.array() >> instead of the tuple. > > Excellent idea. Thanks! And it seems to work too, at least for the > test code. Here are some benchmarks (x86 desktop): > > Unicode key / tuple: >>>> for i in xrange(0, 1000000): d[unicode(i)] = (i, i+1, i+2, i+3, i+4, >>>> i+5, i+6) > 1000000 keys, ['VmPeak:\t 224704 kB', 'VmSize:\t 224704 kB'], > 4.079240 seconds, 245143.698209 keys per second > >>>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = >>>> array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) > 1000000 keys, ['VmPeak:\t 201440 kB', 'VmSize:\t 201440 kB'], > 4.985136 seconds, 200596.331486 keys per second > >>>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = (i, i+1, >>>> i+2, i+3, i+4, i+5, i+6) > 1000000 keys, ['VmPeak:\t 125652 kB', 'VmSize:\t 125652 kB'], > 3.572301 seconds, 279931.625282 keys per second > > Almost halved the memory usage. And faster too. Nice. > def benchmark_dict(d, N): > start = time.time() > > for i in xrange(N): > length = lengths[random.randint(0, 255)] > word = ''.join([ letters[random.randint(0, 255)] for i in xrange(length) ]) > d[word] += 1 > > dt = time.time() - start > vm = re.findall("(VmPeak.*|VmSize.*)", open('/proc/%d/status' % os.getpid()).read()) > print "%d keys (%d unique), %s, %f seconds, %f keys per second" % (N, len(d), vm, dt, N / dt) > Looking at your benchmark, random.choice(letters) has probably less overhead than letters[random.randint(...)]. You might even try to inline it as letters[int(random.random())*256)] Peter From dchichkov at gmail.com Sat Aug 7 04:32:45 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 7 Aug 2010 01:32:45 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: > Looking at your benchmark, random.choice(letters) has probably less overhead > than letters[random.randint(...)]. You might even try to inline it as Right... random.choice()... I'm a bit new to python, always something to learn. But anyway in that benchmark (from http://bugs.python.org/issue9520 ) the code that generate 'words' takes 90% of the time. And I'm really looking at deltas between different methods, not the absolute value. I was also using different code to get benchmarks for my previous message... Here's the code: #!/usr/bin/python # -*- coding: utf-8 -*- import os, time, re, array start = time.time() d = dict() for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) dt = time.time() - start vm = re.findall("(VmPeak.*|VmSize.*)", open('/proc/%d/status' % os.getpid()).read()) print "%d keys, %s, %f seconds, %f keys per second" % (len(d), vm, dt, len(d) / dt) From dchichkov at gmail.com Sat Aug 7 04:45:45 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 7 Aug 2010 01:45:45 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: I guess with the actual dataset I'll be able to improve the memory usage a bit, with BioPython::trie. That would probably be enough optimization to continue working with some comfort. On this test code BioPython::trie gives a bit of improvement in terms of memory. Not much though... >>> d = dict() >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) 1000000 keys, ['VmPeak:\t 125656 kB', 'VmSize:\t 125656 kB'], 3.525858 seconds, 283618.896034 keys per second >>> from Bio import trie >>> d = trie.trie() >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) 1000000 keys, ['VmPeak:\t 108932 kB', 'VmSize:\t 108932 kB'], 4.142797 seconds, 241382.814950 keys per second From aleksandar27 at BRISIOVOnet.hr Sat Aug 7 05:09:01 2010 From: aleksandar27 at BRISIOVOnet.hr (alejandro) Date: Sat, 7 Aug 2010 11:09:01 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: > > Is the file, which you claim is UTF-8 encoded, actually UTF-8 encoded? > If you're not sure, explicitly tell your text editor to save the file as > UTF-8, and then try again. I feel like an idiot... haven't used Python for some time... my editor was set for utf-8 on PHP projects and other... but somehow i forgot to set for py files too... thanks both of you! From nawabadeel at gmail.com Sat Aug 7 05:32:27 2010 From: nawabadeel at gmail.com (Sohail) Date: Sat, 7 Aug 2010 02:32:27 -0700 (PDT) Subject: Python library for Sequence Matching/Comparison Message-ID: Hi, Is there any sequence matching library in (apart from difflib) to compare sequences of natural text? thanks From r3831110n at gmail.com Sat Aug 7 05:53:04 2010 From: r3831110n at gmail.com (Rebel Lion) Date: Sat, 7 Aug 2010 02:53:04 -0700 (PDT) Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: On Aug 5, 12:33?pm, John Nagle wrote: > There's got to be a better way to do this: > > def editmoney(n) : > ? ? ?return((",".join(reduce(lambda lst, item : (lst + [item]) if > ? ? ? ? ?item else lst, > ? ? ? ? ?re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) > > ?>>> editmoney(0) > '0' > ?>>> editmoney(13535) > '13,535' > ?>>> editmoney(-14535) > '-14,535' > ?>>> editmoney(123456) > '123,456' > ?>>> editmoney(1234567890) > '1,234,567,890' > ?>>> editmoney(-1234) > '-1,234' > > The basic idea here is that we want to split the string of digits > into groups of 3 digits, aligned at the right. ?Because regular > expressions are right to left, we have to reverse the string to > do that, then reverse again at the end. ?s[::-1} reverses an > interable. > > "split" with a capturing group introduces empty strings into the > list. ?Hence the "reduce" and lambda to get rid of them. > > Any better ideas? > > (Yes, I know there's a built-in feature for this scheduled for > Python 2.7.) > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle In [1]: '{:,}'.format(-12345678) Out[1]: '-12,345,678' From downaold at gmail.com Sat Aug 7 06:03:05 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 12:03:05 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <1CED8AC9-25D8-44C4-A20D-DE6B3570ECAB@gmail.com> On Aug 7, 2010, at 5:46 AM, Vito 'ZeD' De Tullio wrote: > Default User wrote: > >>> From "the emperor's new clothes" department: >> >> 1) Why do Python lists start with element [0], instead of element >> [1]? >> "Common sense" would seem to suggest that lists should start with >> [1]. > > http://userweb.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html I think the reason why is just historical; C uses zero-based indices. In C, an array index is an offset with respect to the pointer that the array variable actually is, so 0 makes sense (my_array[0] == *my_array). I'm not convinceed (yet) by Dijkstra's reasoning. *Maybe* if you want to describe a range with two References: Message-ID: On Sat, Aug 7, 2010 at 12:32, Sohail wrote: > Hi, > > Is there any sequence matching library in (apart from difflib) to > compare sequences of natural text? > > thanks > -- > http://mail.python.org/mailman/listinfo/python-list > Are you aware of NLTK? It has a lot of sub-libraries for almost anything you might need with processing natural text. Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: From sschwarzer at sschwarzer.net Sat Aug 7 06:41:12 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 07 Aug 2010 12:41:12 +0200 Subject: default behavior In-Reply-To: <4c539ce4$0$11091$c3e8da3@news.astraweb.com> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4c539ce4$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C5D3848.6070708@sschwarzer.net> On 2010-07-31 05:47, Steven D'Aprano wrote: > On Fri, 30 Jul 2010 08:34:52 -0400, wheres pythonmonks wrote: > It does re-use the same underlying data. > > >>> from collections import defaultdict as dd > >>> x = dd(list) > >>> x[1].append(1) > >>> x > defaultdict(, {1: [1]}) > >>> y = dict(x) > >>> x[1].append(42) > >>> y > {1: [1, 42]} One thing to keep in mind: dict(some_defaultdict) doesn't store a reference to the defaultdict; instead it makes a shallow copy, so key/value pairs added _after_ the "cast" aren't included in the new dict: >>> y[2] = 17 >>> y {1: [1, 42], 2: 17} >>> x defaultdict(, {1: [1, 42]}) Stefan From landa.martin at gmail.com Sat Aug 7 06:46:57 2010 From: landa.martin at gmail.com (Martin Landa) Date: Sat, 7 Aug 2010 03:46:57 -0700 (PDT) Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Message-ID: Hi, On Aug 5, 9:32?pm, Nobody wrote: > ? ? ? ? errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int)) > ? ? ? ? errfunc = errtype(print_error) > ? ? ? ? G_set_error_routine(errfunc) the problem occurs when restype is not None, but c_int. E.g. if hasattr(_libs['grass_gis'], 'G_set_error_routine'): G_set_error_routine = _libs['grass_gis'].G_set_error_routine G_set_error_routine.restype = c_int G_set_error_routine.argtypes = [CFUNCTYPE(UNCHECKED(c_int), String, c_int)] errtype = CFUNCTYPE(UNCHECKED(c_int), String, c_int) errfunc = errtype(print_error) or errtype = CFUNCTYPE(c_int, String, c_int) errfunc = errtype(print_error) ends up with error G_set_error_routine(errfunc) TypeError: in method 'G_set_error_routine', argument 1 of type 'int (*) (char const *,int)' The first argument of CFUNCTYPE defines result type (restype), AFAIU that should work. Thanks in advance again, Martin From shambhu.1980 at gmail.com Sat Aug 7 07:10:45 2010 From: shambhu.1980 at gmail.com (Shambhu Sharma) Date: Sat, 7 Aug 2010 16:40:45 +0530 Subject: os.unlink on Windows Message-ID: Hi, I am new to Python. I was trying to use os.unlink function in windows. But i am getting error: OSError: [Errno 2] No such file or directory: 'C:\\SHAMBHU\\tmp\\text_delete.txt' Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But os.unlink is adding extra backslash with pathname. I tried with Python2.5 and Python3.1 but got same error. Please suggest how to remove this error. -- If linux doesn't have a solution, then u have a wrong problem. Shambhu Kumar Sharma 91-98864 91913 -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Sat Aug 7 07:16:01 2010 From: chare at labr.net (Chris Hare) Date: Sat, 07 Aug 2010 06:16:01 -0500 Subject: sched() function questions In-Reply-To: References: <172F5EAB-7A0B-4FB9-AF53-4899B19027C5@labr.net> Message-ID: <55105A92-0B0D-4C67-8639-7CD8D0DA06C6@labr.net> On Aug 7, 2010, at 1:30 AM, Dennis Lee Bieber wrote: > On Fri, 06 Aug 2010 22:37:26 -0500, Chris Hare > declaimed the following in gmane.comp.python.general: > > >> print str(s.queue()) >> > I don't find a queue method defined for scheduler objects in the > documentation for my version of Python (2.5) > >> What I am trying to do is mimic the Timer function, where my code will continue to function while my scheduled function executes in 15 minutes or 900 seconds. This doesn't do it though. Any help? > > And what IS it doing? On my system, I'd expect the program to fail > when trying to print whatever that queue() method is supposed to return. > > However, here is the key item you seem to have missed -- from the > documentation: > > -=-=-=-=- > run( ) > > Run all scheduled events. This function will wait (using the delayfunc > function passed to the constructor) for the next event, then execute it > and so on until there are no more scheduled events. > -=-=-=-=- > > As soon as you call s.run() the entire PROGRAM goes into a wait > state until the first of the queued events time expires. AND won't > return until ALL events have happened. > > To have scheduled events happen asynchronously you will have to > instantiate a THREAD which runs the scheduler... Of course, for your > simple example, who needs the scheduler -- a simple sleep() in the > thread will do what you attempted... The scheduler is useful when you > want to queue a whole bunch of timed events and have them run in order > at the set times... maybe even have events add more events to the > system. > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-listThanks Dennis. I guess I will have to figure out how to resolve the sqlite error From thomas at jollans.com Sat Aug 7 07:46:13 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 13:46:13 +0200 Subject: os.unlink on Windows In-Reply-To: References: Message-ID: <4C5D4785.7030401@jollans.com> On 08/07/2010 01:10 PM, Shambhu Sharma wrote: > Hi, > > I am new to Python. I was trying to use os.unlink function in > windows. But i am getting error: > OSError: [Errno 2] No such file or directory: > 'C:\\SHAMBHU\\tmp\\text_delete.txt' > > Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But > os.unlink is adding extra backslash with pathname. No, it isn't. What you're seeing is simply the repr() of the path name string. >>> p = r'C:\SHAMBHU\tmp\text_delete.txt' >>> p 'C:\\SHAMBHU\\tmp\\text_delete.txt' >>> print(p) C:\SHAMBHU\tmp\text_delete.txt >>> I think the file you're trying to delete probably doesn't exist. Why don't you double-check that. > I tried with > Python2.5 and Python3.1 but got same error. > Please suggest how to remove this error. > > -- > If linux doesn't have a solution, then u have a wrong problem. > > Shambhu Kumar Sharma > 91-98864 91913 > From news1234 at free.fr Sat Aug 7 07:48:32 2010 From: news1234 at free.fr (News123) Date: Sat, 07 Aug 2010 13:48:32 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4c5d4810$0$1426$426a74cc@news.free.fr> On 08/07/2010 05:36 AM, Ryan Kelly wrote: > On Fri, 2010-08-06 at 22:05 -0500, Default User wrote: >> >From "the emperor's new clothes" department: >> >> 1) Why do Python lists start with element [0], instead of element >> [1]? "Common sense" would seem to suggest that lists should start >> with [1]. > > "Common sense" is wrong. There are many compelling advantages to > numbering from zero instead of one: > > http://lambda-the-ultimate.org/node/1950 It makes sense in assembly language and even in many byte code languages. It makes sense if you look at the internal representation of unsigned numbers (which might become an index) For a complete beginner common sense dictates differently and there might be confusion why the second element in a list has index 1. However I seriously doubt, that this is a real problem. You learn things like this on the first day of learning a programming language. > >> 2) In Python 3, why is print a function only, so that: print "Hello, >> World" is not okay, but it must be print("Hello, World") instead? >> (Yeah, I know: picky, picky . . . ) > > The real question is, why was print so special in Python 2 that is can > be called without parentheses? The answer was "no reason" and it was > fixed in Python 3 to be consistent with the rest of the language. > >> 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but >> 8 * 3.57 displays as 28.56 (rounded off to 2 decimal places)? And >> yet, in Python 2.6, 8 * 3.57 displays as 28.559999999999999? > > Because the code for displaying floats was improved in python 3. You > can follow the fascinating discussion on issue 7117: > > http://bugs.python.org/issue7117 > > I can't defend the rounding issues of floating point numbers in general > - it's just "one of those things" that you have to deal with. But show > me a language where floats don't have this problem. > >> And we wonder why kids don't want to learn to program. > I did not see the original post, but this statement sounds rather trollish to me. It might just be, that you can do so many things on a computer without having to program. Watching youtube or browsing the web, chatting about favourite PC games, the amount of SW, that you can download for almost every task make it much less attractive to write own programs. When my parents had their first computer there were very little games and PC's weren't connected to the net. so if I wanted to play with the computer I had mostly the choice between the games called: - basic - pascal - word star - super calc Syntax details are barely a reason to frighten children. children start very often with typing in small programs without understanding them, lookin at the results and changing what they believe to understand. Non native english speakers can write programs, before they even knew what the english words 'if' 'else' 'while' 'list' mean. They don't care. They learn that if 'starts' a condition and that 'else' is the beginning of the section to be executed if the condition is not true. > Yeah, obscure language warts, that must be the reason. > > Note to self: DNFTT... > > > Ryan > From __peter__ at web.de Sat Aug 7 07:53:58 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Aug 2010 13:53:58 +0200 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> Message-ID: Tim Chase wrote: > On 08/06/10 15:37, James Mills wrote: >> On Sat, Aug 7, 2010 at 6:28 AM, geremy condra wrote: >>> If I had to wait 5 minutes while a candidate tried to solve this >>> problem I would not hire them. >> >> Yes you do raise a valid point. It should really only take >> you a mere few seconds or so to write a solution to this. >> >> More over, it can be done in just a single line of Python. >> >> 7 if you're not very familiar with Python. > > While it *can* be done in one line, I'm not sure it's the most > legible solution. Though I must say I like this one-line python > version: > > for i in range(1, 101): print ((i%3==0 and 'fizz' or '') + > (i%5==0 and 'buzz' or '')) or i > > (adjust "3" and "5" for your local flavor of fizzbuzz) > > I'm not sure I'd hire a candidate that proposed this as a > solution in earnest, but I'd have fun chatting with them :) You mean you'd go for the candidate who took the conservative approach and got it right: print 1 print 2 print 'Fizz' print 4 print 'Buzz' print 'Fizz' print 7 print 8 print 'Fizz' print 'Buzz' print 11 print 'Fizz' print 13 print 14 print 'FizzBuzz' print 16 print 17 print 'Fizz' print 19 print 'Buzz' print 'Fizz' print 22 print 23 print 'Fizz' print 'Buzz' print 26 print 'Fizz' print 28 print 29 print 'FizzBuzz' print 31 print 32 print 'Fizz' print 34 print 'Buzz' print 'Fizz' print 37 print 38 print 'Fizz' print 'Buzz' print 41 print 42 print 43 print 44 print 'FizzBuzz' print 46 print 47 print 'Fizz' print 49 print 'Buzz' print 'Fizz' print 52 print 53 print 'Fizz' print 'Buzz' print 56 print 'Fizz' print 58 print 59 print 'FizzBuzz' print 61 print 62 print 'Fizz' print 64 print 'Buzz' print 'Fizz' print 67 print 68 print 'Fizz' print 'Buzz' print 71 print 'Fizz' print 73 print 74 print 'FizzBuzz' print 76 print 77 print 'Fizz' print 79 print 'Buzz' print 'Fizz' print 82 print 83 print 'Fizz' print 'Buzz' print 86 print 'Fizz' print 88 print 89 print 'FizzBuzz' print 91 print 92 print 'Fizz' print 94 print 'Buzz' print 'Fizz' print 97 print 98 print 'Fizz' print 'Buzz' Well, almost right, but one error per 100 lines at the first try is near- genius anyway... Peter From steve at REMOVE-THIS-cybersource.com.au Sat Aug 7 08:00:25 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 12:00:25 GMT Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> <8c4fouF1bdU1@mid.individual.net> Message-ID: <4c5d4ad9$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 19:28:56 +1200, Gregory Ewing wrote: > Steven D'Aprano wrote: >> "No memory? No disk space? No problem! Just a flesh wound!" What's >> the point of that? > > +1 QOTW While I'm always happy to be nominated for QOTW, in this case I didn't say it, and the nomination should go to KJ. -- Steven From thomas at jollans.com Sat Aug 7 08:00:59 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 14:00:59 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4C5D4AFB.90204@jollans.com> On 08/07/2010 05:05 AM, Default User wrote: >>From "the emperor's new clothes" department: > > 1) Why do Python lists start with element [0], instead of element [1]? > "Common sense" would seem to suggest that lists should start with [1]. As others have pointed out, there is a nice argument to be made for zero-based indices. However, the killer reason is: "it's what everybody else does." As it stands, the only perceived problem with zero-based indices is that it's one of the many tiny confusions that new programmers face. On the other hand, it's the way nearly every other popular programming language does it, and therefore, it's the way almost every programmer likes to think about sequences. Also, it has the nice property that, for an infinite sequence, every integer makes sense as an index (in Python). > > 2) In Python 3, why is print a function only, so that: print "Hello, > World" is not okay, but it must be print("Hello, World") instead? > (Yeah, I know: picky, picky . . . ) > > 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but 8 > * 3.57 displays as 28.56 (rounded off to 2 decimal places)? And yet, in > Python 2.6, 8 * 3.57 displays as 28.559999999999999? 0:pts/3:~% python3.1 Python 3.1.2 (release31-maint, Jul 8 2010, 09:18:08) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 28.56 28.56 >>> 0:pts/3:~% python2.6 Python 2.6.6rc1+ (r266rc1:83691, Aug 5 2010, 17:07:04) [GCC 4.4.5 20100728 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 28.56 28.559999999999999 >>> 0:pts/3:~% same number - why use more digits if you can avoid it? Python 3 is smart enough to avoid it. > > And we wonder why kids don't want to learn to program. Don't kids want to learn to program? Many don't, a fair bunch do. It's the same for any other art. Also, the only people that realize this kind of "issue" are those that have already learned programming. From gnusiva at gmail.com Sat Aug 7 08:04:43 2010 From: gnusiva at gmail.com (siva moorthy) Date: Sat, 7 Aug 2010 15:04:43 +0300 Subject: Need Translation library Message-ID: hi all, i wish to code for translation in python i want to parse a python program itself and make some keyword changes (replacement) tell me any library to parse python source code and another library to change some words phonetically to other language thanks in advance Siva -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 7 08:05:02 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 12:05:02 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> <87k4o311y4.fsf@benfinney.id.au> Message-ID: <4c5d4bed$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 14:28:19 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: >> >> > P.S. Sorry for the top-post -- is there a way to not do top posts >> > from gmail? I haven't used usenet since tin. >> >> Er, surely you can just move the cursor before you start typing??? > > I like to think that the cursor is placed at the top by default so that > is > easy: just travel down through the quoted material, removing it if not > relevant and inserting one's responses where needed. Yes, but apparently millions of Internet users have keyboards where neither the cursor keys nor backspace/delete works. Being unable to interleave their reply with the quoted text, they end up quoting the entire week-long thread at the bottom of every email they send. I blame Manservant Neville. -- Steven From thomas at jollans.com Sat Aug 7 08:28:48 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 14:28:48 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> <4C5D0566.8090801@sschwarzer.net> Message-ID: <4C5D5180.6020200@jollans.com> On 08/07/2010 09:44 AM, Gabriel Genellina wrote: > En Sat, 07 Aug 2010 04:04:06 -0300, Stefan Schwarzer > escribi?: >> On 2010-08-07 00:28, Steven D'Aprano wrote: > >>> Actually, yes, equality is implemented with a short-cut > that checks for >>> identity first. That makes something like: >>> [...] >> >> Oops, I didn't realize that the OP had mentioned the >> identity check as an optimization in case the objects are >> the same. I thought he was confusing the operator with `is`. >> >>> s = "abc"*1000*1000*10 >>> s == s >>> >>> nice and quick, as Python can immediately recognise that a string is >>> always equal to itself without having to walk the entire string >>> comparing >>> each character with itself. >> >> Yes, that definitely makes sense. I guess I would have >> implemented it this way as well. :) > > For strings and other internal types this optimization certainly makes > sense. For user-defined types it gets in the way and prevents defining > an object such x==x is False (like NANs). > That's probably why this optimisation doesn't exist for user-defined types: Python 3.1.2 (release31-maint, Jul 8 2010, 09:18:08) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> class A: ... def __eq__(self, x): ... if self is x: return False ... else: return True ... >>> >>> A() == A() True >>> a = A() >>> a == a False >>> From hobson42 at gmaiil.com Sat Aug 7 08:34:06 2010 From: hobson42 at gmaiil.com (Ian) Date: Sat, 07 Aug 2010 13:34:06 +0100 Subject: Smith-Waterman Algorithm in Python In-Reply-To: References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> Message-ID: <4C5D52BE.302@gmaiil.com> On 06/08/2010 17:54, Daniel Fetchinson wrote: >> Does any one about any implementation of classical Smith Waterman >> local alignment algorithm and it's variants for aligning natural >> language text? >> > > Please see http://tinyurl.com/2wy43fh > > Every one of the first 20 entries is either the OP questions or your reply. Daniel - you are no help at all, and no funny. Ian From darcy at druid.net Sat Aug 7 08:54:28 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 7 Aug 2010 08:54:28 -0400 Subject: Python "why" questions In-Reply-To: <4c5d4810$0$1426$426a74cc@news.free.fr> References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <20100807085428.48664a76.darcy@druid.net> On Sat, 07 Aug 2010 13:48:32 +0200 News123 wrote: > It makes sense in assembly language and even in many byte code languages. > It makes sense if you look at the internal representation of unsigned > numbers (which might become an index) > > For a complete beginner common sense dictates differently and there > might be confusion why the second element in a list has index 1. Would said beginner also be surprised that a newborn baby is zero years old or would it be more natural to call them a one year old? Zero based counting is perfectly natural. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From __peter__ at web.de Sat Aug 7 08:58:14 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Aug 2010 14:58:14 +0200 Subject: Smith-Waterman Algorithm in Python References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> <4C5D52BE.302@gmaiil.com> Message-ID: Ian wrote: > On 06/08/2010 17:54, Daniel Fetchinson wrote: >>> Does any one about any implementation of classical Smith Waterman >>> local alignment algorithm and it's variants for aligning natural >>> language text? >>> >> >> Please see http://tinyurl.com/2wy43fh >> >> > Every one of the first 20 entries is either the OP questions or your > reply. > > Daniel - you are no help at all, and no funny. Maybe, but the OP would have had the advantage of not seeing these entries had he googled before asking. The first hit for Smith Waterman in Python is still http://narnia.cs.ttu.edu/drupal/node/104 and finding it and evaluating it before posting here should have been doable. Peter From downaold at gmail.com Sat Aug 7 09:37:23 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 15:37:23 +0200 Subject: Python "why" questions In-Reply-To: <20100807085428.48664a76.darcy@druid.net> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> Message-ID: <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> On Aug 7, 2010, at 2:54 PM, D'Arcy J.M. Cain wrote: > On Sat, 07 Aug 2010 13:48:32 +0200 > News123 wrote: >> It makes sense in assembly language and even in many byte code >> languages. >> It makes sense if you look at the internal representation of unsigned >> numbers (which might become an index) >> >> For a complete beginner common sense dictates differently and there >> might be confusion why the second element in a list has index 1. > > Would said beginner also be surprised that a newborn baby is zero > years > old or would it be more natural to call them a one year old? Zero > based counting is perfectly natural. A new born baby is in his/her first year. It's year 1 of his/her life. For this reason, also "the year 0" doesn't exist. From the fact that a baby can be half a year old, you derive that arrays should have floats as indices? From steve at REMOVE-THIS-cybersource.com.au Sat Aug 7 09:38:20 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 13:38:20 GMT Subject: Python "why" questions References: Message-ID: <4c5d61cc$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 14:00:59 +0200, Thomas Jollans wrote: > On 08/07/2010 05:05 AM, Default User wrote: >>>From "the emperor's new clothes" department: >> >> 1) Why do Python lists start with element [0], instead of element [1]? >> "Common sense" would seem to suggest that lists should start with [1]. > > As others have pointed out, there is a nice argument to be made for > zero-based indices. However, the killer reason is: "it's what everybody > else does." I'll have you know that there are still some Pascal programmers in the world, thank you. > As it stands, the only perceived problem with zero-based > indices is that it's one of the many tiny confusions that new > programmers face. On the other hand, it's the way nearly every other > popular programming language does it, and therefore, it's the way almost > every programmer likes to think about sequences. It didn't take me long to get used to thinking in zero-based indexes, but years later, I still find it hard to *talk* in zero-based indexes. It's bad enough saying that the first element in a list in the zeroth element, but that the second element is the first makes my head explode... > Also, it has the nice property that, for an infinite sequence, every > integer makes sense as an index (in Python). Er, what's the -1th element of an infinite sequence? -- Steven From darcy at druid.net Sat Aug 7 09:53:48 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 7 Aug 2010 09:53:48 -0400 Subject: Python "why" questions In-Reply-To: <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> Message-ID: <20100807095348.073cd803.darcy@druid.net> On Sat, 7 Aug 2010 15:37:23 +0200 Roald de Vries wrote: > > Would said beginner also be surprised that a newborn baby is zero > > years > > old or would it be more natural to call them a one year old? Zero > > based counting is perfectly natural. > > A new born baby is in his/her first year. It's year 1 of his/her life. > For this reason, also "the year 0" doesn't exist. From the fact that a > baby can be half a year old, you derive that arrays should have floats > as indices? No. You are giving me math and logic but the subject was common sense. Common usage counts ages as years with the second year called "one year old" so zero based counting is common. We don't tell Aunt Martha that little Jimmy is in his third year. We say that he is two years old and Aunt Martha, a non-programmer, understands exactly what we mean. Using one-based counting (first year, second year, etc.) would be the unnatural thing, would confuse Aunt Martha and make her spoil her apple pie and no one wants that. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From albert at spenarnc.xs4all.nl Sat Aug 7 09:54:28 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 07 Aug 2010 13:54:28 GMT Subject: Nice way to cast a homogeneous tuple References: <4c50eb46$0$28664$c3e8da3@news.astraweb.com> <1pm7i7-473.ln1@satorlaser.homedns.org> Message-ID: In article <1pm7i7-473.ln1 at satorlaser.homedns.org>, Ulrich Eckhardt wrote: >Steven D'Aprano wrote: >> Perhaps I have been misinformed, but my understanding of C type-casts is >> that (where possible), a cast like `int(var)` merely tells the compiler >> to temporarily disregard the type of var and treat it as if it were an >> int. In other words, it's a compiler instruction rather than a conversion >> function. > >You are misinformed. The result of a cast in C or C++ behaves as if a >temporary was created: > > int x = 0; > unsigned(x)--; // invalid, compiler error > >Now, where this distinction gets blurred is when you are casting pointers: > > (*(unsigned*)&x)--; > >or, in C++, references: > > reinterpret_cast(x)--; > >Technically, these are still invalid though, only that they give you >undefined behaviour at runtime instead of a compiler error, but those are >already very fine details of the according standards. There is just one conclusion that should remain from this. If you're ever going to program in in c or c++, casts are to be avoided like the plague. (And recently they have been thought over in C++ to be split in different names with the reinterpret_cast the most dangerous, but at least it is a big read flag.) I see an analogy with goto's in my experience. Once you understand how bad they are, you discover there is always a better solution. It is unfortunate that cast's in Python share the same name, but it is kind of unavoidable because it is about the proper CS name to use. >Uli Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From downaold at gmail.com Sat Aug 7 09:57:00 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 15:57:00 +0200 Subject: iterators and continuing after a StopIteration Message-ID: Hi all, I have a list that I'm iterating over, and during the iteration items are appended. Moreover, it is iterated over in two nested loops. If the inner loop comes to the end, I want the outer loop to append an item. Is there a way to do this? Because once an iterator has raised a StopIteration, it can not go to a next item anymore. Aside question: is there a rationale for the current behavior? To me it seems more natural to continue iteration after appending new items. I want to use it for a graph walk. nodes is a list of all nodes, edges is an on the fly constructed list of edges in the order of visiting, initial_nodes is a list of (root) nodes edges = [] edge_it = iter(edges) for node in initial_nodes: edges += node.leaving_edges try: while True: edge = edge_it.next() edges += edge.head.leaving_edges except StopIteration: pass Thanks in advance, cheers, Roald From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sat Aug 7 10:04:48 2010 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sat, 7 Aug 2010 14:04:48 +0000 (UTC) Subject: Is there any way to minimize str()/unicode() objects memory usage ?[Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: dmtr wrote: > I guess with the actual dataset I'll be able to improve the memory > usage a bit, with BioPython::trie. That would probably be enough > optimization to continue working with some comfort. On this test code > BioPython::trie gives a bit of improvement in terms of memory. Not > much though... > >>>> d = dict() >>>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) > Using struct.pack('7i',i, i+1, i+2, i+3, i+4, i+5, i+6) instead of array.array gives 20% improvement in time with (not surprisingly) the same memory usage. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From downaold at gmail.com Sat Aug 7 10:05:07 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 16:05:07 +0200 Subject: Python "why" questions In-Reply-To: <20100807095348.073cd803.darcy@druid.net> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <20100807095348.073cd803.darcy@druid.net> Message-ID: On Aug 7, 2010, at 3:53 PM, D'Arcy J.M. Cain wrote: > On Sat, 7 Aug 2010 15:37:23 +0200 > Roald de Vries wrote: >>> Would said beginner also be surprised that a newborn baby is zero >>> years >>> old or would it be more natural to call them a one year old? Zero >>> based counting is perfectly natural. >> >> A new born baby is in his/her first year. It's year 1 of his/her >> life. >> For this reason, also "the year 0" doesn't exist. From the fact >> that a >> baby can be half a year old, you derive that arrays should have >> floats >> as indices? > > No. You are giving me math and logic but the subject was common > sense. Common usage counts ages as years with the second year called > "one year old" so zero based counting is common. We don't tell Aunt > Martha that little Jimmy is in his third year. We say that he is two > years old and Aunt Martha, a non-programmer, understands exactly what > we mean. Using one-based counting (first year, second year, etc.) > would be the unnatural thing, would confuse Aunt Martha and make her > spoil her apple pie and no one wants that. My point is that "0" in "Jimmy is 0" doesn't play the same role as in "item 0 of a sequence". From steve at REMOVE-THIS-cybersource.com.au Sat Aug 7 10:10:29 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 14:10:29 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <4c5d6955$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 08:54:28 -0400, D'Arcy J.M. Cain wrote: > On Sat, 07 Aug 2010 13:48:32 +0200 > News123 wrote: >> It makes sense in assembly language and even in many byte code >> languages. It makes sense if you look at the internal representation of >> unsigned numbers (which might become an index) >> >> For a complete beginner common sense dictates differently and there >> might be confusion why the second element in a list has index 1. > > Would said beginner also be surprised that a newborn baby is zero years > old or would it be more natural to call them a one year old? Zero based > counting is perfectly natural. There's nothing natural about saying that a baby is zero years old. A newborn baby is "a newborn baby", then it's "one day old", "two days old", ... "one month old", "two months old", ... "one year old". In any case, we're discussing *ordinals*, not cardinal numbers. The ordinals in common English are first, second, third, ... but in computing frequently zeroth, first, second, third, ... There is a reason why mathematicians describe the integers 1, 2, 3, ... as the "Natural Numbers". It took thousands of years of human civilization before people accepted that zero was a number. In fact, for the ancient Greeks, one wasn't a number either. We still reserve the term "a number of X" to refer to more than one X, and would feel cheated if somebody offered us a number of gifts and then gave us only a single one. "Number" refers to a plurality, and one is singular. According to Euclid, one was the monad, the indivisible unit from which the numbers were formed. As late as 1537, the German mathematician Jacob Kobel wrote "1 is no number, but it is a generatrix, beginning and foundation for all other numbers". In short, there's nothing natural about counting numbers at all, let alone whether we should start at 0 or 1. P.S. I don't know if I should be gratified or disappointed that nobody has yet quoted Stan Kelly-Bootle: "Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." -- Steven From thomas at jollans.com Sat Aug 7 10:29:16 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 16:29:16 +0200 Subject: Python "why" questions In-Reply-To: <4c5d61cc$0$28666$c3e8da3@news.astraweb.com> References: <4c5d61cc$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4C5D6DBC.7050508@jollans.com> On 08/07/2010 03:38 PM, Steven D'Aprano wrote: > On Sat, 07 Aug 2010 14:00:59 +0200, Thomas Jollans wrote: > >> On 08/07/2010 05:05 AM, Default User wrote: >>> >From "the emperor's new clothes" department: >>> >>> 1) Why do Python lists start with element [0], instead of element [1]? >>> "Common sense" would seem to suggest that lists should start with [1]. >> >> As others have pointed out, there is a nice argument to be made for >> zero-based indices. However, the killer reason is: "it's what everybody >> else does." > > I'll have you know that there are still some Pascal programmers in the > world, thank you. > > > >> As it stands, the only perceived problem with zero-based >> indices is that it's one of the many tiny confusions that new >> programmers face. On the other hand, it's the way nearly every other >> popular programming language does it, and therefore, it's the way almost >> every programmer likes to think about sequences. > > It didn't take me long to get used to thinking in zero-based indexes, but > years later, I still find it hard to *talk* in zero-based indexes. It's > bad enough saying that the first element in a list in the zeroth element, > but that the second element is the first makes my head explode... zeroth oneth twoth ;-) (element no. one is a better way of pronouncing it.) > > >> Also, it has the nice property that, for an infinite sequence, every >> integer makes sense as an index (in Python). > > Er, what's the -1th element of an infinite sequence? well, it's the first from the other end. The infinite bit is in between, thank you very much. ;-) From no.email at please.post Sat Aug 7 10:37:24 2010 From: no.email at please.post (kj) Date: Sat, 7 Aug 2010 14:37:24 +0000 (UTC) Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> <8c4fouF1bdU1@mid.individual.net> <4c5d4ad9$0$28666$c3e8da3@news.astraweb.com> Message-ID: In <4c5d4ad9$0$28666$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >On Sat, 07 Aug 2010 19:28:56 +1200, Gregory Ewing wrote: >> Steven D'Aprano wrote: >>> "No memory? No disk space? No problem! Just a flesh wound!" What's >>> the point of that? >> >> +1 QOTW >While I'm always happy to be nominated for QOTW, in this case I didn't >say it, and the nomination should go to KJ. (The ol' "insert Monty Python reference" move: it never fails...) From nobody at nowhere.com Sat Aug 7 10:41:56 2010 From: nobody at nowhere.com (Nobody) Date: Sat, 07 Aug 2010 15:41:56 +0100 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Message-ID: On Fri, 06 Aug 2010 18:39:27 -0700, dmtr wrote: > Steven, thank you for answering. See my comments inline. Perhaps I > should have formulated my question a bit differently: Are there any > *compact* high performance containers for unicode()/str() objects in > Python? By *compact* I don't mean compression. Just optimized for > memory usage, rather than performance. > > What I'm really looking for is a dict() that maps short unicode > strings into tuples with integers. Use UTF-8 encoded strings (str/bytes) as keys rather than unicode objects. From nobody at nowhere.com Sat Aug 7 10:48:17 2010 From: nobody at nowhere.com (Nobody) Date: Sat, 07 Aug 2010 15:48:17 +0100 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> Message-ID: On Sat, 07 Aug 2010 09:53:48 -0400, D'Arcy J.M. Cain wrote: >> A new born baby is in his/her first year. It's year 1 of his/her life. >> For this reason, also "the year 0" doesn't exist. From the fact that a >> baby can be half a year old, you derive that arrays should have floats >> as indices? > > No. You are giving me math and logic but the subject was common > sense. Common usage counts ages as years with the second year called > "one year old" so zero based counting is common. We don't tell Aunt > Martha that little Jimmy is in his third year. Apparently, the Japanese used to (before they started adopting western conventions). I.e. ages were given as "in his tenth year" (meaning nine years old). From albert at spenarnc.xs4all.nl Sat Aug 7 10:48:29 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 07 Aug 2010 14:48:29 GMT Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Roy Smith wrote: >In article <4c55fe82$0$9111$426a34cc at news.free.fr>, > candide wrote: > >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. > >One thing that comes to mind is that it's much easier to distribute C >libraries than C++ libraries. > >If I compile a main program with one C compiler and you compile a >dynamically loaded library with another C compiler on the same box, the >odds are pretty good they'll interoperate without any problems. > >Not at all so with C++ compilers. The linkage is *way* more >complicated. Not just how the two compilers do name mangling, but how >they handle exceptions, RVO, and a zillion other details. Pretty much >the only way to make it work is to compile everything with exactly the >same compiler. That would make it pretty close to impossible for people >to take a Python core distribution and add their own extension modules >to it. We had a similar discussion on comp.lang.forth. The bottom line is that to implement a programming language you want to use a simpler programming language, not a more complicated one. Then there is a secondary requirement, that language must allow sufficient access to low level features to allow decent performance. A third aspect is that Linux/Unices as well as Windows assume OS interaction in terms of c-libraries. Any intermediary is inconvenient at least. Or in one catch phrase: " To implement a programming language you need a high level assembler like C." (We went on whether Forth would be a suitable high level assembler for Haskell. It would beat C++ -- not C -- for implementing Python, that much I'm sure.) Undoubtedly C is the right choice to implement Python. Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From albert at spenarnc.xs4all.nl Sat Aug 7 11:13:00 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 07 Aug 2010 15:13:00 GMT Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Roy Smith wrote: >In article , > Lawrence D'Oliveiro wrote: > >> In message , Roy Smith wrote: >> >> > C++, for all its flaws, had one powerful feature which made it very >> > popular. It is a superset of C. >> >> Actually, it never was. > >Yes, there are a few corner cases where valid C syntax has different >semantics in C and C++. But, they are very few. Calling C++ a superset >of C is essentially correct. One aspect of C++ is that all standard functions of C are called in the same way. A large part of programs consists of stringing API calls together. Those require little work to upgrade to C++. So from a practical point of view this is very much true. > >It is certainly correct from the level of a risk-averse development >manager deciding if he or she is willing to use C++ for the first time. >Fear of the unknown is a powerful deterrent. It's a lot easier to >accept something like C++ because "it's just a superset of C, and we've >been using C for years". Even if it is overhyped, the C++ compiler vendors certainly tried to make it happen. > >I suspect the same effect contributed to Java's success as well. "Look, >it's got curly braces and semicolons. It's just like C!" Of course! Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From nobody at nowhere.com Sat Aug 7 11:24:09 2010 From: nobody at nowhere.com (Nobody) Date: Sat, 07 Aug 2010 16:24:09 +0100 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: On Sat, 07 Aug 2010 13:48:32 +0200, News123 wrote: >> "Common sense" is wrong. There are many compelling advantages to >> numbering from zero instead of one: >> >> http://lambda-the-ultimate.org/node/1950 > > It makes sense in assembly language and even in many byte code languages. > It makes sense if you look at the internal representation of unsigned > numbers (which might become an index) It also makes sense mathematically. E.g. for an MxN array stored as a 1-dimensional array, the element a[j][i] is at index j * N + i with zero-based indices but: (j-1) * N + (i-1) + 1 = j * N + i - N with one-based indices. IOW, if a language uses one-based indices, it will inevitably end up converting to and from zero-based indices under the hood, and may end up forcing the user to do likewise if they need to do their own array manipulation. From downaold at gmail.com Sat Aug 7 11:38:37 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 17:38:37 +0200 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <48C30F62-B3AE-4F59-A9F3-E9DE54C39CCE@gmail.com> On Aug 7, 2010, at 5:24 PM, Nobody wrote: > On Sat, 07 Aug 2010 13:48:32 +0200, News123 wrote: > >>> "Common sense" is wrong. There are many compelling advantages to >>> numbering from zero instead of one: >>> >>> http://lambda-the-ultimate.org/node/1950 >> >> It makes sense in assembly language and even in many byte code >> languages. >> It makes sense if you look at the internal representation of unsigned >> numbers (which might become an index) > > It also makes sense mathematically. E.g. for an MxN array stored as a > 1-dimensional array, the element a[j][i] is at index > > j * N + i Nice example! From pengyu.ut at gmail.com Sat Aug 7 11:48:47 2010 From: pengyu.ut at gmail.com (Peng Yu) Date: Sat, 7 Aug 2010 10:48:47 -0500 Subject: How to match patterns like XX YY XX YY? (regex) Message-ID: Hi, Suppose that I have strings like the following test(a b)a b test(xy uv)xy uv ... I want to change them to test(a)a test(b)b test(xy)xy test(uv)uv ... The problem is that I don't know how to capture pattern that repeat itself (like 'a' and 'xy' in the example). I could use 'test\((\w+) (\w+)\)(\w) (\w)', but it will capture something like 'test(a b)x y', which I don't want to. I'm wondering if there is way to capture recurring patterns. -- Regards, Peng From wolftracks at invalid.com Sat Aug 7 12:12:50 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 09:12:50 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On 8/6/2010 7:18 PM, Philip Semanchuk wrote: > > On Aug 6, 2010, at 3:14 PM, W. eWatson wrote: > >> I must be missing something. I tried this. (Windows, IDLE, Python 2.5) > > Yes, as Benjamin Kaplan pointed out and as I said in the email where I > posted this code snippet, "dependencies is a list of custom classes that > represent modules we need (e.g. numpy)." The code I posted was not meant > to be a complete working example. It's part of a larger piece of code > that I didn't have time to cook down to a simpler, self-sufficient whole. > > Also, in your list you've got "numyp" instead of "numpy". > > Also, at the top of your code you have "import numpy" and "import scipy" > which defeats the purpose of this code. > Good. It worked. Are there other attributes of a module that can help identify it further? Release date, ...? From alex at moreati.org.uk Sat Aug 7 12:15:26 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Sat, 7 Aug 2010 09:15:26 -0700 (PDT) Subject: How to match patterns like XX YY XX YY? (regex) References: Message-ID: <9af8026e-322c-4ca3-9afc-aafda85bfac3@j8g2000yqd.googlegroups.com> On Aug 7, 4:48?pm, Peng Yu wrote: > The problem is that I don't know how to capture pattern that repeat > itself (like 'a' and 'xy' in the example). I could use 'test\((\w+) > (\w+)\)(\w) (\w)', but it will capture something like 'test(a b)x y', > which I don't want to. > > I'm wondering if there is way to capture recurring patterns. Back references can deal with repetition. Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> re.match(r'test\((\w+) (\w+)\)\1 \2', 'test(xy uv)xy uv').groups() ('xy', 'uv') >>> re.match(r'test\((\w+) (\w+)\)\1 \2', 'test(a b)x y') >>> From zyzhu2000 at gmail.com Sat Aug 7 12:26:39 2010 From: zyzhu2000 at gmail.com (GZ) Date: Sat, 7 Aug 2010 09:26:39 -0700 (PDT) Subject: Sequential Object Store Message-ID: <6e21725a-e5c4-45be-81c4-5a9fd79df413@d8g2000yqf.googlegroups.com> Hi All, I need to store a large number of large objects to file and then access them sequentially. I am talking about a few thousands of objects and each with size of a few hundred kilobytes, and total file size a few gigabytes. I tried shelve, but it is not good at sequentially accessing the data. In essence, shelve.keys() takes forever. I am wondering if there is a module that can persist a stream of objects without having to load everything into memory. (For this reason, I think Pickle is out, too, because it needs everything to be in memory.) Thanks, GZ From albert at spenarnc.xs4all.nl Sat Aug 7 13:02:54 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 07 Aug 2010 17:02:54 GMT Subject: measuring a function time References: <831343.82061.qm@web50006.mail.re2.yahoo.com> <4c5178ae$0$11091$c3e8da3@news.astraweb.com> Message-ID: In article <4c5178ae$0$11091$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Thu, 29 Jul 2010 14:42:58 +0200, Matteo Landi wrote: > >> This should be enough >> >>>>>import time >>>>>tic = time.time() >>>>>function() >>>>>toc = time.time() >>>>>print toc - tic > >You're typing that in the interactive interpreter, which means the timer >is counting the seconds while you're typing subsequent commands. At the >very least, you need to put that code into a function. There is an alternative, for once the semicolon comes in handy: >>>from time import * >>> x=time(); function(); print time()-x 6.551980773430 > >The best way to time small code snippets and fast functions is with the >timeit module. > >-- >Steven Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From python.list at tim.thechases.com Sat Aug 7 13:12:04 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 07 Aug 2010 12:12:04 -0500 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: <4C5D0108.2090401@cyta.gr> References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> <4C5B4D6E.1070501@tim.thechases.com> <4C5D0108.2090401@cyta.gr> Message-ID: <4C5D93E4.9090605@tim.thechases.com> On 08/07/10 01:45, ???????? ?????? wrote: >> # variant B >> for row in dataset: >> host, hits, dt = row >> # rest of your code here > > So, row is a tuple comprising of 3 fields, and host, hist, dt > are variables assigned each one of row's tuple values by > breaking it to it's elements. > > But what kind of objects is host, hits, dt that containes the > row's tuple data themselves? tuples or lists and why? They contain the data of each respective element. E.g.: >>> dataset = [ ... (1, 'a', True), ... (2, 'b', False), ... ] >>> >>> for one, two, three in dataset: ... print 'one%s = %r' % (type(one), one) ... print 'two%s = %r' % (type(two), two) ... print 'three%s = %r' % (type(three), three) ... print '-' * 10 ... one = 1 two = 'a' three = True ---------- one = 2 two = 'b' three = False ---------- So likely in your case, "host" is a string, "hits" is an int, and "dt" is a datetime.datetime object. The three of them together are the row as represented as a tuple: >>> type( (host, hits, dt) ) which you can see in your own code by changing it temporarily to: for row in dataset: print type(row), len(row) >> # variant C >> for host, hits, dt in row: >> # rest of your code here >> > host, hits, data each and every one of them hold a piece of the row's > tuple values. > > But what happens in here? The same as Variant B, only it doesn't use the intermediate tuple "row". > 'for host, hits, dt in dataset:' > > Here we don't have the row tuple. So what tthose variabels store, and in > what datatype they strore info in and what is the difference between this > and > > 'for host, hits, dt in row:' The second one will fail because it would be the same as for tpl in row: host, hits, dt = tpl The 1st time through the loop, tpl=host; the 2nd time through the loop, tpl=hits; and the 3rd time through the loop, tpl=dt Attempting to do a tuple assignment (that 2nd line) will attempt to do something like host, hits, dt = "example.com" # 1st pass through the loop host, hits, dt = 42 # 2nd pass through the loop host, hits, dt = datetime(2010,7,5)# 3rd pass through the loop In most cases, it will fail on the first pass through the loop (except in the freak case your string value happens to have 3 characters: >>> host, hits, dt = "abc" #exactly 3 letters >>> host 'a' ) > If the fieds datatypes returned form the database are for exmaple page > varchar(50) , hits inteeger[11], date datetime then > the when python grabs those results fields it would translate them to > 'page as string' , (hits as int) , 'date as string' respectively? > Whcih emans it translated those fileds returned to the most > appropriate-most close to prototype stored in database' datatypes > automatically? Yes, except the internals (of the DB module...in this case mysql) are smart enough to translate the date into a datetime.datetime object, instead of a string. >> row = (host, hits, dt > > Would that be a row or a tuple when joined? A "row" is a conceptual thing -- one row of data from your query. It can be represented as either a tuple or a list (or any iteratable that represents "things in this row"). In this case (and I believe each row returned by a cursor.fetch*() call), it was tuple. I hope that helps...it would behoove you to experiment with tuple-assignments such as the example code above so that you understand what it's doing in each case. -tkc From nikos.the.gr33k at gmail.com Sat Aug 7 13:29:09 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 10:29:09 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex Message-ID: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Hello guys! Need your precious help again! In every html file i have in the very first line a page_id fro counetr countign purpsoes like in a format of a comment like this: and so on. every html file has its one page_id How can i grab that string representaion of a number from inside the .html file using regex and convert it to an integer value? # ============================== # open current html template and get the page ID number # ============================== f = open( '/home/webville/public_html/' + page ) #read first line of the file firstline = f.readline() page_id = re.match( '', firstline ) print ( page_id ) From nikos.the.gr33k at gmail.com Sat Aug 7 13:31:38 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 10:31:38 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: i also dont know what wrong with this line: host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] hostmatch = re.search('cyta', host) if cookie.has_key('visitor') != 'nikos' or hostmatch is None: # do stuff the 'stuff' never gets executed, while i ant them to be as long as i dont have regex match! From fetchinson at googlemail.com Sat Aug 7 13:43:11 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 7 Aug 2010 19:43:11 +0200 Subject: Smith-Waterman Algorithm in Python In-Reply-To: <4C5D52BE.302@gmaiil.com> References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> <4C5D52BE.302@gmaiil.com> Message-ID: >>> Does any one about any implementation of classical Smith Waterman >>> local alignment algorithm and it's variants for aligning natural >>> language text? >>> >> >> Please see http://tinyurl.com/2wy43fh >> >> > Every one of the first 20 entries is either the OP questions or your reply. And you think it was there before the OP sent his message? Oh wait, did you just invent a time machine? :) > Daniel - you are no help at all, and no funny. Actually, I'm damn funny! :) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From gelonida at gmail.com Sat Aug 7 13:53:55 2010 From: gelonida at gmail.com (Gelonida) Date: Sat, 07 Aug 2010 19:53:55 +0200 Subject: cscope like source code navigation for python code Message-ID: Hi, I'm using g?vim and its c-scope plugin for browsing C-code. What would be a good way of navigating larger python projects with vim? thanks for any suggestions From python at mrabarnett.plus.com Sat Aug 7 14:12:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 19:12:18 +0100 Subject: iterators and continuing after a StopIteration In-Reply-To: References: Message-ID: <4C5DA202.2020504@mrabarnett.plus.com> Roald de Vries wrote: > Hi all, > > > I have a list that I'm iterating over, and during the iteration items > are appended. Moreover, it is iterated over in two nested loops. If the > inner loop comes to the end, I want the outer loop to append an item. Is > there a way to do this? Because once an iterator has raised a > StopIteration, it can not go to a next item anymore. > > Aside question: is there a rationale for the current behavior? To me it > seems more natural to continue iteration after appending new items. > > > I want to use it for a graph walk. > > nodes is a list of all nodes, > edges is an on the fly constructed list of edges in the order of visiting, > initial_nodes is a list of (root) nodes > > edges = [] > edge_it = iter(edges) > for node in initial_nodes: > edges += node.leaving_edges > try: > while True: > edge = edge_it.next() > edges += edge.head.leaving_edges > except StopIteration: > pass > > > Thanks in advance, cheers, Roald You could add the new edges to another list: edges = [] pending_edges = [] for node in initial_nodes: pending_edges += node.leaving_edges while pending_edges: new_edges = [] for edge in pending_edges: new_edges += edge.head.leaving_edges edges += pending_edges pending_edges = new_edges or use indexing: edges = [] for node in initial_nodes: edges += node.leaving_edges index = 0 while index < len(edges): edges += edges[index].head.leaving_edges index += 1 From python at mrabarnett.plus.com Sat Aug 7 14:20:46 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 19:20:46 +0100 Subject: How to match patterns like XX YY XX YY? (regex) In-Reply-To: References: Message-ID: <4C5DA3FE.7000109@mrabarnett.plus.com> Peng Yu wrote: > Hi, > > Suppose that I have strings like the following > > test(a b)a b > test(xy uv)xy uv > ... > > I want to change them to > > test(a)a test(b)b > test(xy)xy test(uv)uv > ... > > > The problem is that I don't know how to capture pattern that repeat > itself (like 'a' and 'xy' in the example). I could use 'test\((\w+) > (\w+)\)(\w) (\w)', but it will capture something like 'test(a b)x y', > which I don't want to. > > I'm wondering if there is way to capture recurring patterns. > Use backreferences (it's in the documentation): pattern = re.compile(r'test\((\w+) (\w+)\)\1 \2') From python at mrabarnett.plus.com Sat Aug 7 14:24:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 19:24:52 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DA4F4.7080706@mrabarnett.plus.com> ????? wrote: > Hello guys! Need your precious help again! > > In every html file i have in the very first line a page_id fro counetr > countign purpsoes like in a format of a comment like this: > > > > > > and so on. every html file has its one page_id > > How can i grab that string representaion of a number from inside > the .html file using regex and convert it to an integer value? > > # ============================== > # open current html template and get the page ID number > # ============================== > > f = open( '/home/webville/public_html/' + page ) > > #read first line of the file > firstline = f.readline() > > page_id = re.match( '', firstline ) > print ( page_id ) Use group capture: found = re.match(r'', firstline).group(1) print(page_id) From python at mrabarnett.plus.com Sat Aug 7 14:27:58 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 19:27:58 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DA5AE.90307@mrabarnett.plus.com> ????? wrote: > i also dont know what wrong with this line: > > host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] > > hostmatch = re.search('cyta', host) > > if cookie.has_key('visitor') != 'nikos' or hostmatch is None: > # do stuff > > the 'stuff' never gets executed, while i ant them to be as long as i > dont have regex match! Try printing out repr(host). Does it contain "cyta"? From nikos.the.gr33k at gmail.com Sat Aug 7 14:48:02 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 11:48:02 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: On 7 ???, 21:27, MRAB wrote: > ????? wrote: > > i also dont know what wrong with this line: > > > host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] > > > hostmatch = re.search('cyta', host) > > > if cookie.has_key('visitor') != 'nikos' or hostmatch is None: > > ? ? ?# do stuff > > > the 'stuff' never gets executed, while i want them to be as long as i > > dont have regex match! > > Try printing out repr(host). Does it contain "cyta"? Yes it does contain it as print shown! is something wrong with this line in logic or syntax? if cookie.has_key('visitor') != 'nikos' or re.search('cyta', host) is None: # do database stuff From nikos.the.gr33k at gmail.com Sat Aug 7 14:51:46 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 11:51:46 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: On 7 ???, 21:24, MRAB wrote: > Use group capture: > > ? ? ?found = re.match(r'', firstline).group(1) > ? ? ?print(page_id) Worked like a charm! Thanks a lot! So match method here not only searched for the string representation of the number but also convert it to integer as well? r stand for retrieve the string here? and group? Wehn a regex searched a .txt file when is retrieving something for it always retrieve it as string right? or can get it as a number as well? From clp2 at rebertia.com Sat Aug 7 14:57:50 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 7 Aug 2010 11:57:50 -0700 Subject: Need Translation library In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 5:04 AM, siva moorthy wrote: > hi all, > i wish to code for translation in python > > i want to parse a python program itself and make some keyword changes > (replacement) > tell me any library to parse python source code Depending on you needs, one of: http://docs.python.org/library/tokenize.html http://docs.python.org/library/ast.html Cheers, Chris -- http://blog.rebertia.com From thomas at jollans.com Sat Aug 7 15:03:21 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 21:03:21 +0200 Subject: How to grab a number from inside a .html file using regex In-Reply-To: References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DADF9.9090806@jollans.com> On 08/07/2010 08:51 PM, ????? wrote: > On 7 ???, 21:24, MRAB wrote: > >> Use group capture: >> >> found = re.match(r'', firstline).group(1) >> print(page_id) > > Worked like a charm! Thanks a lot! > > So match method here not only searched for the string representation > of the number but also convert it to integer as well? > > r stand for retrieve the string here? r"xyz" is a raw string literal. That means that backslash escapes are turned off -- r'\n' == '\\n' > > and group? > > Wehn a regex searched a .txt file when is retrieving something for it > always retrieve it as string right? or can get it as a number as well? From python at mrabarnett.plus.com Sat Aug 7 15:07:49 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 20:07:49 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DAF05.1080008@mrabarnett.plus.com> ????? wrote: > On 7 ???, 21:27, MRAB wrote: >> ????? wrote: >>> i also dont know what wrong with this line: >>> host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] >>> hostmatch = re.search('cyta', host) >>> if cookie.has_key('visitor') != 'nikos' or hostmatch is None: >>> # do stuff >>> the 'stuff' never gets executed, while i want them to be as long as i >>> dont have regex match! >> Try printing out repr(host). Does it contain "cyta"? > > Yes it does contain it as print shown! > > is something wrong with this line in logic or syntax? > > if cookie.has_key('visitor') != 'nikos' or re.search('cyta', host) is > None: > # do database stuff > You said "i want them to be as long as i dont have regex match". re.search('cyta', host) will return None if there's no match, but you said "Yes it does contain it", so there _is_ a match, therefore: hostmatch is None is False. From nagle at animats.com Sat Aug 7 15:14:46 2010 From: nagle at animats.com (John Nagle) Date: Sat, 07 Aug 2010 12:14:46 -0700 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> On 8/7/2010 5:00 AM, Thomas Jollans wrote: > On 08/07/2010 05:05 AM, Default User wrote: >> > From "the emperor's new clothes" department: >> >> 1) Why do Python lists start with element [0], instead of element [1]? >> "Common sense" would seem to suggest that lists should start with [1]. > > As others have pointed out, there is a nice argument to be made for > zero-based indices. However, the killer reason is: "it's what everybody > else does." FORTRAN, MATLAB, and Octave all use 1-based subscripts. The languages which have real multidimensional arrays, rather than arrays of arrays, tend to use 1-based subscripts. That reflects standard practice in mathematics. John Nagle From wolftracks at invalid.com Sat Aug 7 15:17:57 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 12:17:57 -0700 Subject: Python Portability In-Reply-To: References: Message-ID: On 8/6/2010 2:23 AM, Lawrence D'Oliveiro wrote: > In message, W. eWatson wrote: > >> I made a one character change to it and sent him the new py file. He can't >> execute it. > > What exactly was the problem? > I put a minus sign in front of a variable. I had him use the shell to check his version numpy, which he just provided. version -- 1.4.0. As I think I mentioned above, he's probably not using the same numpy version that I use 1.2.0. Don't ask for an explanation of why I want him on 1.2.0. :-) I think that pretty much wraps up the problem. He needs to get back to 1.2.0. Presumably I have him somehow delete the numpy site-package, the numpy 1.2.0 package? Just drill his way dow from the .../lib/site_packages? Then install 1.2.0. He's missed the boat on that before by not following instructions. From python at mrabarnett.plus.com Sat Aug 7 15:17:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 20:17:59 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DB167.4000602@mrabarnett.plus.com> ????? wrote: > On 7 ???, 21:24, MRAB wrote: > >> Use group capture: >> >> found = re.match(r'', firstline).group(1) >> print(page_id) > > Worked like a charm! Thanks a lot! > > So match method here not only searched for the string representation > of the number but also convert it to integer as well? > > r stand for retrieve the string here? > > and group? > > Wehn a regex searched a .txt file when is retrieving something for it > always retrieve it as string right? or can get it as a number as well? The 'r' prefix makes it a 'raw string literal'. That means that the string literal won't treat backslashes as special. Before raw string literals were added to the Python language I would have needed to write: '' instead. (Actually, that's not strictly true in this case, because \d doesn't have a special meaning Python strings, but it's a good idea to use raw string literals habitually when writing regexes in order to reduce the chance of forgetting them when they _are_ necessary. Well, that's what I think, anyway. :-)) From nikos.the.gr33k at gmail.com Sat Aug 7 15:36:27 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 12:36:27 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> On 7 ???, 22:07, MRAB wrote: > re.search('cyta', host) will return None if there's no match, but you > said "Yes it does contain it", so there _is_ a match, therefore: > > ? ? ?hostmatch is None > > is False. The code block inside the if structure must be executes ONLY if the 'visitor' cookie is not set to the client's browser or the hostname address of the client doesn't contain in it the string 'cyta'. # ====================================== # do not increment the counter if a Cookie is set to the visitors browser already # ====================================== if cookie.has_key('visitor') != 'nikos' or re.search('cyta', host) is None: I still don't get it :) From nikos.the.gr33k at gmail.com Sat Aug 7 15:37:54 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 12:37:54 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <0b6075f3-2f44-44d8-844f-166ac90e42c7@m1g2000yqo.googlegroups.com> On 7 ???, 22:17, MRAB wrote: > ????? wrote: > > On 7 ???, 21:24, MRAB wrote: > > >> Use group capture: > > >> ? ? ?found = re.match(r'', firstline).group(1) > >> ? ? ?print(page_id) > > > Worked like a charm! Thanks a lot! > > > So match method here not only searched for the string representation > > of the number but also convert it to integer as well? > > > r stand for retrieve the string here? > > > and group? > > > Wehn a regex searched a .txt file when is retrieving something for it > > always retrieve it as string right? or can get it as a number as well? > > The 'r' prefix makes it a 'raw string literal'. That means that the > string literal won't treat backslashes as special. Before raw string > literals were added to the Python language I would have needed to write: > > ? ? ?'' > > instead. > > (Actually, that's not strictly true in this case, because \d doesn't > have a special meaning Python strings, but it's a good idea to use raw > string literals habitually when writing regexes in order to reduce the > chance of forgetting them when they _are_ necessary. Well, that's what I > think, anyway. :-)) Couln't agree more! As the saying goes, better safe than sorry! :-) From thomas at jollans.com Sat Aug 7 15:52:53 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 21:52:53 +0200 Subject: How to grab a number from inside a .html file using regex In-Reply-To: <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> Message-ID: <4C5DB995.4060502@jollans.com> On 08/07/2010 09:36 PM, ????? wrote: > cookie.has_key('visitor') != 'nikos' This is always True. has_key returns a bool, which is never equal to any string, even 'nikos'. From martin at v.loewis.de Sat Aug 7 16:00:39 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 07 Aug 2010 22:00:39 +0200 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: <4C5DBB67.6090700@v.loewis.de> > As an example, my inexperienced Python partner 30 miles away has gotten > out of step somehow. I think by installing a different version of numpy > than I use. I gave him a program we both use months ago, and he had no > trouble. (We both use IDLE on 2.5). I made a one character change to it > and sent him the new py file. He can't execute it. I doubt he has > changed anything in the intervening period. You'll find that many people will be very skeptical wrt. this story: this kind of thing really isn't supposed to happen, and it's difficult to believe that it failed just because of the one-character change. You already said that that the change was adding a minus sign somewhere. Can you now kindly also report what then the problem was that your partner encountered (specific error message would be appreciated). > A further example. Months ago I decided to see if I could compile a > program to avoid such problems as above. I planned to satisfy that need, > and see if I could distribute some simple programs to non-Python > friends. I pretty well understand the idea,and got it working with a > small program. It seemed like a lot of manual labor to do it. It's a lot of manual labor only the first time. When you package the next version of the same software, manual labor should be minimal. Regards, Martin From pavlovevidence at gmail.com Sat Aug 7 16:02:56 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 7 Aug 2010 13:02:56 -0700 (PDT) Subject: Nice way to cast a homogeneous tuple References: <4c50eb46$0$28664$c3e8da3@news.astraweb.com> <1pm7i7-473.ln1@satorlaser.homedns.org> Message-ID: <49f9d367-20fc-442f-b397-9d50ffb391f2@i4g2000prf.googlegroups.com> On Aug 7, 6:54?am, Albert van der Horst wrote: > In article <1pm7i7-473.... at satorlaser.homedns.org>, > Ulrich Eckhardt ? wrote: > > > > >Steven D'Aprano wrote: > >> Perhaps I have been misinformed, but my understanding of C type-casts is > >> that (where possible), a cast like `int(var)` merely tells the compiler > >> to temporarily disregard the type of var and treat it as if it were an > >> int. In other words, it's a compiler instruction rather than a conversion > >> function. > > >You are misinformed. The result of a cast in C or C++ behaves as if a > >temporary was created: > > > ?int x = 0; > > ?unsigned(x)--; // invalid, compiler error > > >Now, where this distinction gets blurred is when you are casting pointers: > > > ?(*(unsigned*)&x)--; > > >or, in C++, references: > > > ?reinterpret_cast(x)--; > > >Technically, these are still invalid though, only that they give you > >undefined behaviour at runtime instead of a compiler error, but those are > >already very fine details of the according standards. > > There is just one conclusion that should remain from this. > If you're ever going to program in in c or c++, casts are to be > avoided like the plague. You sound as if you don't usually program in C or C++, which suggests to me that you shouldn't be offering advice on how to program in these languages. I program in C all the time, and I can tell you you can't get very far in C or C++ without sometimes resorting to type-casts. (C ++ offers more help for class types, but there's not a lot you can do to avoid casts for converting between built-in types.) The CPython interpreter uses type casts all over the place, BTW. > (And recently they have been thought over in > C++ to be split in different names with the reinterpret_cast the most > dangerous, but at least it is a big read flag.) If by "recently" you mean "10 years ago", and by "thought over" you mean "standardized and implemented". > I see an analogy with goto's in my experience. Once you understand > how bad they are, you discover there is always a better solution. What better solution do you propose for this that doesn't use type- casting? int a, b; double ratio; ratio = (double)a/b; > It is unfortunate that cast's in Python share the same name, but > it is kind of unavoidable because it is about the proper CS name to use. Not really. Very few people call int(), float(), and company "type casts". They aren't type casts at all, they are constructors that sometimes have the same semantics as type casts in C. Carl Banks From python at mrabarnett.plus.com Sat Aug 7 16:07:01 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 21:07:01 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: <4C5DB995.4060502@jollans.com> References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> <4C5DB995.4060502@jollans.com> Message-ID: <4C5DBCE5.4050803@mrabarnett.plus.com> Thomas Jollans wrote: > On 08/07/2010 09:36 PM, ????? wrote: >> cookie.has_key('visitor') != 'nikos' > > This is always True. has_key returns a bool, which is never equal to any > string, even 'nikos'. I missed that bit! :-) Anyway, the OP said "the 'stuff' never gets executed". Kinda puzzling... From nikos.the.gr33k at gmail.com Sat Aug 7 16:29:54 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 13:29:54 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> Message-ID: <431664b9-f813-4523-b54d-b3697eb8bf24@y11g2000yqm.googlegroups.com> On 7 ???, 22:52, Thomas Jollans wrote: > On 08/07/2010 09:36 PM, ????? wrote: > > > cookie.has_key('visitor') != 'nikos' > > This is always True. has_key returns a bool, which is never equal to any > string, even 'nikos'. if cookie.has_key('visitor') or re.search('cyta', host) is None: adresses the problem :-) Thanks alot Thomas and MRAB for ALL your help! From torriem at gmail.com Sat Aug 7 17:01:37 2010 From: torriem at gmail.com (Michael Torrie) Date: Sat, 07 Aug 2010 15:01:37 -0600 Subject: Python Portability In-Reply-To: References: Message-ID: <4C5DC9B1.1040501@gmail.com> On 08/07/2010 01:17 PM, W. eWatson wrote: > Presumably I have him somehow delete the numpy site-package, the numpy > 1.2.0 package? Just drill his way dow from the .../lib/site_packages? > Then install 1.2.0. He's missed the boat on that before by not following > instructions. Wait. I'm confused. Aren't you distributing your python app as an executable, with the interpreter and all the libraries bundled? From martin at v.loewis.de Sat Aug 7 17:26:31 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 07 Aug 2010 23:26:31 +0200 Subject: Python Portability In-Reply-To: References: Message-ID: <4C5DCF87.4000800@v.loewis.de> Am 07.08.2010 23:01, schrieb Michael Torrie: > On 08/07/2010 01:17 PM, W. eWatson wrote: >> Presumably I have him somehow delete the numpy site-package, the numpy >> 1.2.0 package? Just drill his way dow from the .../lib/site_packages? >> Then install 1.2.0. He's missed the boat on that before by not following >> instructions. > > Wait. I'm confused. Aren't you distributing your python app as an > executable, with the interpreter and all the libraries bundled? No, he was really mentioning two distinct scenarios. In the one discussed above, the remote machine had all stuff manually installed, and somehow got the actual Python program copied into it. Regards, Martin From stefan_ml at behnel.de Sat Aug 7 17:58:20 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 07 Aug 2010 23:58:20 +0200 Subject: Problem with Elementtree and XMLSchem instance type In-Reply-To: <4C52D1F6.7020209@adm.umu.se> References: <4C52D1F6.7020209@adm.umu.se> Message-ID: Roland Hedberg, 30.07.2010 15:21: > I have the following XML snippet: > > xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > xmlns:fed="http://docs.oasis-open.org/wsfed/federation/200706" > xsi:type="fed:SecurityTokenServiceType"> > .... > > > This part after parsing with Elementtree gives me an Element instance > with the following properties: > >> tree.tag > {urn:oasis:names:tc:SAML:2.0:metadata}RoleDescriptor >> tree.keys() > ['{http://www.w3.org/2001/XMLSchema-instance}type'] >> tree['{http://www.w3.org/2001/XMLSchema-instance}type'] > fed:SecurityTokenServiceType > > And there is the problem, I've lost the coupling between the prefix > 'fed' and the namespace > "http://docs.oasis-open.org/wsfed/federation/200706". > > Is there any way I can get at the prefix<-> namespace mapping from an > Element instance ? > I've read the documentation I can find and there is nothing that tells > me how to get at the mapping. > > If I print the Element instance the prefix 'fed' is replace by 'ns0' or > something like that. > Definitely something that has no connection to the original 'fed'. Yes, ElementTree does that. There are two ways to work around this: recent ET versions support explicitly defining namespace-prefix mappings at a module global level (IIRC, starting with ET 1.3/Py2.7/Py3.2), so you can provide a fixed prefix if you know what's coming in. Failing that, you can switch to lxml.etree, which keeps namespace prefixes as seen in the parsed document. Stefan From aahz at pythoncraft.com Sat Aug 7 17:58:56 2010 From: aahz at pythoncraft.com (Aahz) Date: 7 Aug 2010 14:58:56 -0700 Subject: distutils question - building universal modules on OS X? References: Message-ID: In article , Louis Theran wrote: > >Is there a standard recipe for getting distutils to built universal .so >files for modules that have C/C++ source? You should check the archives of http://mail.python.org/mailman/listinfo/pythonmac-sig -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From rantingrick at gmail.com Sat Aug 7 18:02:14 2010 From: rantingrick at gmail.com (rantingrick) Date: Sat, 7 Aug 2010 15:02:14 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> Message-ID: <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> On Aug 7, 9:10?am, Steven D'Aprano wrote: > On Sat, 07 Aug 2010 08:54:28 -0400, D'Arcy J.M. Cain wrote: > > On Sat, 07 Aug 2010 13:48:32 +0200 > > News123 wrote: > >> It makes sense in assembly language and even in many byte code > >> languages. It makes sense if you look at the internal representation of > >> unsigned numbers (which might become an index) > > >> For a complete beginner common sense dictates differently and there > >> might be confusion why the second element in a list has index 1. > > > Would said beginner also be surprised that a newborn baby is zero years > > old or would it be more natural to call them a one year old? ?Zero based > > counting is perfectly natural. > > There's nothing natural about saying that a baby is zero years old. A > newborn baby is "a newborn baby", then it's "one day old", "two days > old", ... "one month old", "two months old", ... "one year old". Well not if you are referring to how people "say" things. But what people "say" and the facts of reality are some times two different things. Heck we even have a few folks in this group who overuse the expression "used to" quite frequently in place of the more correct term "previously" -- i won't give names. But if i did i would start at index zero! When any object is "born" (whether it be a life form, or a planet, or even a class instance) "it" will be zero years old until 1 year of time has passed has passed. If you want to properly describe age you could say a baby who was born five minutes ago is... - 0 millenniums - 0 centuries - 0 decades - 0 years - 0 months - 0 days - 0 hours - 5 minutes - 60*5 seconds - (60*5)*1000 millisecond - crikey i'm tired! Just because Aunt Martha is is too lazy to list out the details that has no effect on reality. YES a newborn is zero years old. YES, a newborn is zero months old, ...an so on. From no.email at nospam.invalid Sat Aug 7 18:37:04 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 07 Aug 2010 15:37:04 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <7xwrs2t5gv.fsf@ruckus.brouhaha.com> Albert van der Horst writes: > We had a similar discussion on comp.lang.forth. Heh, fancy meeting you here ;-) > The bottom line is that to implement a programming language > you want to use a simpler programming language, not a more > complicated one. Nah, gas is written in C, and nobody implements VHDL as logic gates. > (We went on whether Forth would be a suitable high level assembler > for Haskell. It would beat C++ -- not C -- for implementing Python, > that much I'm sure.) Haskell (or at least certain parts of it) should probably be implemented in Coq or Agda, which are even higher level than Haskell. > Undoubtedly C is the right choice to implement Python. Python has been experimentally implemented in Haskell: http://hackage.haskell.org/package/berp-0.0.2 but the most interesting implementation (not yet ready for production, but a serious ongoing project partly funded by the EU) is written in Python itself: http://codespeak.net/pypy/ From python at mrabarnett.plus.com Sat Aug 7 18:44:05 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 23:44:05 +0100 Subject: Python "why" questions In-Reply-To: <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: <4C5DE1B5.7070802@mrabarnett.plus.com> rantingrick wrote: > On Aug 7, 9:10 am, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 07 Aug 2010 08:54:28 -0400, D'Arcy J.M. Cain wrote: >>> On Sat, 07 Aug 2010 13:48:32 +0200 >>> News123 wrote: >>>> It makes sense in assembly language and even in many byte code >>>> languages. It makes sense if you look at the internal representation of >>>> unsigned numbers (which might become an index) >>>> For a complete beginner common sense dictates differently and there >>>> might be confusion why the second element in a list has index 1. >>> Would said beginner also be surprised that a newborn baby is zero years >>> old or would it be more natural to call them a one year old? Zero based >>> counting is perfectly natural. >> There's nothing natural about saying that a baby is zero years old. A >> newborn baby is "a newborn baby", then it's "one day old", "two days >> old", ... "one month old", "two months old", ... "one year old". > > Well not if you are referring to how people "say" things. But what > people "say" and the facts of reality are some times two different > things. Heck we even have a few folks in this group who overuse the > expression "used to" quite frequently in place of the more correct > term "previously" -- i won't give names. But if i did i would start at > index zero! > There's nothing wrong with "used to", but "more correct"? It either _is_ correct or _isn't_ correct. And it's "I", not "i". :-) > When any object is "born" (whether it be a life form, or a planet, or > even a class instance) "it" will be zero years old until 1 year of > time has passed has passed. If you want to properly describe age you > could say a baby who was born five minutes ago is... > > - 0 millenniums millennia > - 0 centuries > - 0 decades > - 0 years > - 0 months > - 0 days > - 0 hours > - 5 minutes > - 60*5 seconds > - (60*5)*1000 millisecond > - crikey i'm tired! > > Just because Aunt Martha is is too lazy to list out the details that > has no effect on reality. YES a newborn is zero years old. YES, a > newborn is zero months old, ...an so on. From hexamorph at gmx.net Sat Aug 7 19:06:34 2010 From: hexamorph at gmx.net (Hexamorph) Date: Sun, 08 Aug 2010 01:06:34 +0200 Subject: Python "why" questions In-Reply-To: <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: <4C5DE6FA.1090701@gmx.net> rantingrick wrote: > Well not if you are referring to how people "say" things. But what > people "say" and the facts of reality are some times two different > things. Heck we even have a few folks in this group who overuse the > expression "used to" quite frequently in place of the more correct > term "previously" -- i won't give names. Rick, do you know *ANY* other language other than English? Not everybody understands English on an Oxford level (and I doubt you do). You're just a loud-mouthing (probably incorrect English) idiot. (Spare your comments about personal attacks, you're not so stupid to not know why you regularly receive such comments) Lurking for long enough to know your style. Looking at your Unicode rant, combined with some other comments and your general "I am right and you are wrong because you disagree with me." style, I came to the conclusion, that you are either a faschist or the perfect role model for an imperialistic, foreign culture destroying, self-praising, arrogant, ignorant moron. > When any object is "born" (whether it be a life form, or a planet, or > even a class instance) "it" will be zero years old until 1 year of > time has passed has passed. A year is not the smallest index. A year is 365 days is 8760 hours is 525600 is 31536000 minutes, and so on and so on and so on... That's *totally* different from array[0], array[1], etc. There is *NO* array[0.5]. Going down to the smalled possible time scale (quantum physics level ), what is the the correct index for "my baby is *just* born, hence it's X quantum leap old." where x might be 0 or 1. Yes, I know that this is nonsense (since such a discrete quantum leap doesn't even exists) but so is the whole discussion. Something starts at 0, others at 1. You only have to add/sub 1 depending on the situation. Mind-boggling, I must say! And really, even brand-new programmer will face *A LOT* harder problems than this. Programming is not stamp collecting! Programming requires a half working brain, and those who don't have that, should sort their stamps while watching some "Next top model" stuff on TV. "Make everything as simple as possible, but not simpler." - Einstein From ben+python at benfinney.id.au Sat Aug 7 19:16:26 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Aug 2010 09:16:26 +1000 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> Message-ID: <878w4i10ad.fsf@benfinney.id.au> Peter Pearson writes: > Hey, that's a cute example, but . . . what a trap! Is it possible to > document the use-the-object-not-the-string requirement loudly enough > that people won't get caught? Don't use strings for such values. The data isn't going to be used, so there's no sense using a semantically rich data type like a string. Instead, use an ?object? instance; then, the only way to get a binding that will compare equal is to use the very object itself. FORWARD = object() BACKWARD = object() -- \ ?Never do anything against conscience even if the state demands | `\ it.? ?Albert Einstein | _o__) | Ben Finney From debatem1 at gmail.com Sat Aug 7 19:24:32 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 7 Aug 2010 16:24:32 -0700 Subject: Python "why" questions In-Reply-To: <4C5DE6FA.1090701@gmx.net> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> <4C5DE6FA.1090701@gmx.net> Message-ID: On Sat, Aug 7, 2010 at 4:06 PM, Hexamorph wrote: > rantingrick wrote: > >> Well not if you are referring to how people "say" things. But what >> people "say" and the facts of reality are some times two different >> things. Heck we even have a few folks in this group who overuse the >> expression "used to" quite frequently in place of the more correct >> term "previously" -- i won't give names. > > > > Rick, do you know *ANY* other language other than English? Not everybody > understands English on an Oxford level (and I doubt you do). You're just a > loud-mouthing (probably incorrect English) idiot. (Spare your comments about > personal attacks, you're not so stupid to not know why you regularly receive > such comments) > > Lurking for long enough to know your style. Looking at your Unicode rant, > combined with some other comments and your general "I am right and you are > wrong because you disagree with me." style, I came to the conclusion, that > you are either a faschist or the perfect role model for an imperialistic, > foreign culture destroying, self-praising, arrogant, ignorant moron. Rick? Is that you? Geremy Condra From wolftracks at invalid.com Sat Aug 7 19:24:52 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 16:24:52 -0700 Subject: Python Portability In-Reply-To: References: Message-ID: On 8/7/2010 2:01 PM, Michael Torrie wrote: > On 08/07/2010 01:17 PM, W. eWatson wrote: >> Presumably I have him somehow delete the numpy site-package, the numpy >> 1.2.0 package? Just drill his way dow from the .../lib/site_packages? >> Then install 1.2.0. He's missed the boat on that before by not following >> instructions. > > Wait. I'm confused. Aren't you distributing your python app as an > executable, with the interpreter and all the libraries bundled? Not at all. There is no exe. The py source program is all that goes out. It is expected that the recipients have the same versions of modules, numpy, etc, and IDLE. All under Windows. There's not a single person (of about 50) that gets person who is likely to have changed the Python environment. None of them know Python. When the sponsor decides to change the app we all use, then we update Python and modules as required. User's execute the programs with IDLE, or a double click of the py file. From ben+python at benfinney.id.au Sat Aug 7 19:34:22 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Aug 2010 09:34:22 +1000 Subject: Python "why" questions References: <4c5d61cc$0$28666$c3e8da3@news.astraweb.com> Message-ID: <874of60zgh.fsf@benfinney.id.au> Steven D'Aprano writes: > It didn't take me long to get used to thinking in zero-based indexes, > but years later, I still find it hard to *talk* in zero-based indexes. > It's bad enough saying that the first element in a list in the zeroth > element, but that the second element is the first makes my head > explode... Don't say those things, then. In addition to making your head explode, they're not true. There is no ?zeroth element? in a sequence. The first element in a sequence is addressed by index 0. The second element in a sequence is addressed by index 1. The last element in a sequence is addressed by index -1. In other words, it's never true (in Python) that index N addresses the Nth element of the sequence; so that's not a useful equivalence to maintain. Hope that helps. -- \ ?The trouble with eating Italian food is that five or six days | `\ later you're hungry again.? ?George Miller | _o__) | Ben Finney From wolftracks at invalid.com Sat Aug 7 19:36:48 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 16:36:48 -0700 Subject: Python Portability In-Reply-To: <4C5DCF87.4000800@v.loewis.de> References: <4C5DCF87.4000800@v.loewis.de> Message-ID: On 8/7/2010 2:26 PM, Martin v. Loewis wrote: > Am 07.08.2010 23:01, schrieb Michael Torrie: >> On 08/07/2010 01:17 PM, W. eWatson wrote: >>> Presumably I have him somehow delete the numpy site-package, the numpy >>> 1.2.0 package? Just drill his way dow from the .../lib/site_packages? >>> Then install 1.2.0. He's missed the boat on that before by not following >>> instructions. >> >> Wait. I'm confused. Aren't you distributing your python app as an >> executable, with the interpreter and all the libraries bundled? > > No, he was really mentioning two distinct scenarios. In the one > discussed above, the remote machine had all stuff manually installed, > and somehow got the actual Python program copied into it. > > Regards, > Martin To add to the msg I just sent to M. Torrie. We are given the msi programs for Python, PIL,matplotlib, and numpy. The question of how to uninstall and re-install a different version remains. The answer is? From ben+python at benfinney.id.au Sat Aug 7 19:39:18 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Aug 2010 09:39:18 +1000 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> Message-ID: <87zkwyyoux.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > No. You are giving me math and logic but the subject was common > sense. Common sense is often unhelpful, and in such cases the best way to teach something is to plainly contradict that common sense. Common sense, for example, would have the Earth as a flat surface with the Sun and Moon as roughly-identically-sized objects orbiting the Earth. Is it better to pander to that common sense, or to vigorously reject it in order to teach something more useful? -- \ ?Courage is not the absence of fear, but the decision that | `\ something else is more important than fear.? ?Ambrose Redmoon | _o__) | Ben Finney From usernet at ilthio.net Sat Aug 7 19:42:31 2010 From: usernet at ilthio.net (Tim Harig) Date: Sat, 7 Aug 2010 23:42:31 +0000 (UTC) Subject: cscope like source code navigation for python code References: Message-ID: On 2010-08-07, Gelonida wrote: > I'm using g?vim and its c-scope plugin for browsing C-code. > What would be a good way of navigating larger python projects with vim? ctags: http://ctags.sourceforge.net/ From ben+python at benfinney.id.au Sat Aug 7 19:43:39 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Aug 2010 09:43:39 +1000 Subject: Python Portability--Not very portable? References: Message-ID: <87vd7myono.fsf@benfinney.id.au> "W. eWatson" writes: > Yes, code reversal programs have been around for many, many decades. > Try one on MS Word or Adobe Acrobat. :-) Interesting examples. What ?important stuff? from those programs has not been ?ripped off?, to use your terms? Is there anything remaining in those programs which others would find sufficiently valuable that has *not* been ?ripped off?? -- \ ?If you make people think they're thinking, they'll love you; | `\ but if you really make them think, they'll hate you.? ?Donald | _o__) Robert Perry Marquis | Ben Finney From martin at v.loewis.de Sat Aug 7 19:45:46 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 08 Aug 2010 01:45:46 +0200 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> Message-ID: <4C5DF02A.6010200@v.loewis.de> > To add to the msg I just sent to M. Torrie. We are given the msi > programs for Python, PIL,matplotlib, and numpy. The question of how to > uninstall and re-install a different version remains. I'd claim that this is not the real question. The real question is, instead: "What specific error did you get when adding a single minus sign to the program?" Please try answering that question also. > The answer is? I'm not sure I understand the question. What do you mean by "given"? Perhaps "already downloaded locally"? If so, the obvious answer is "Go to Add-Remove-Programs. Uninstall. Then double-click the MSI files." If that is not a good answer: why not? If you want that automated: write a batch file, invoking "msiexec" as necessary. Regards, Martin From alex at moreati.org.uk Sat Aug 7 19:54:03 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Sat, 7 Aug 2010 16:54:03 -0700 (PDT) Subject: Sequential Object Store References: <6e21725a-e5c4-45be-81c4-5a9fd79df413@d8g2000yqf.googlegroups.com> Message-ID: On Aug 7, 5:26?pm, GZ wrote: > I am wondering if there is a module that can persist a stream of > objects without having to load everything into memory. (For this > reason, I think Pickle is out, too, because it needs everything to be > in memory.) >From the pickle docs it looks like you could do something like: try: import cPickle as pickle except ImportError import pickle file_obj = open('whatever', 'wb') p = pickle.Pickler(file_obj) for x in stream_of_objects: p.dump(x) p.memo.clear() del p file_obj.close() then later file_obj = open('whatever', 'rb') p = pickle.Unpickler(file_obj) while True: try: x = p.load() do_something_with(x) except EOFError: break Your loading loop could be wrapped in a generator function, so only one object should be held in memory at once. From nikos.the.gr33k at gmail.com Sat Aug 7 20:20:24 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 17:20:24 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex Message-ID: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Hello dear Pythoneers, I have over 500 .php web pages in various subfolders under 'data' folder that i have to rename to .html and and ditch the '' tages from within and also insert a very first line of where id must be an identification unique number of every page for counter tracking purposes. ONly pure html code must be left. I before find otu Python used php and now iam switching to templates + python solution so i ahve to change each and every page. I don't know how to handle such a big data replacing problem and cannot play with fire because those 500 pages are my cleints pages and data of those filesjust cannot be messes up. Can you provide to me a script please that is able of performing an automatic way of such a page content replacing? Thanks a million! From rantingrick at gmail.com Sat Aug 7 20:40:33 2010 From: rantingrick at gmail.com (rantingrick) Date: Sat, 7 Aug 2010 17:40:33 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> On Aug 7, 7:20?pm, ????? wrote: > Hello dear Pythoneers, I prefer Pythonista, but anywho.. > I have over 500 .php web pages in various subfolders under 'data' > folder that i have to rename to .html import os os.rename(old, new) > and and ditch the '' tages from within path = 'some/valid/path' f = open(path, 'r') data = f.read() f.close() data.replace('', '') > and also insert a very first line of > where id must be an identification unique number of every page for > counter tracking purposes. comment = ""%(idnum) data.insert(idx, comment) > ONly pure html code must be left. Well then don't F up! However judging from the amount of typos in this post i would suggest you do some major testing! > I don't know how to handle such a big data replacing problem and > cannot play with fire because those 500 pages are my cleints pages and > data of those files just cannot be messes up. Better do some serous testing first, or (if you have enough disc space ) create copies instead! > Can you provide to me a script please that is able of performing an > automatic way of such a page content replacing? This is very basic stuff and the fine manual is free you know. But how much are you willing to pay? From wolftracks at invalid.com Sat Aug 7 21:10:34 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 18:10:34 -0700 Subject: Python Portability In-Reply-To: <4C5DF02A.6010200@v.loewis.de> References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On 8/7/2010 4:45 PM, Martin v. Loewis wrote: >> To add to the msg I just sent to M. Torrie. We are given the msi >> programs for Python, PIL,matplotlib, and numpy. The question of how to >> uninstall and re-install a different version remains. > > I'd claim that this is not the real question. The real question is, > instead: "What specific error did you get when adding a single minus > sign to the program?" > > Please try answering that question also. > >> The answer is? > > I'm not sure I understand the question. What do you mean by "given"? > Perhaps "already downloaded locally"? > > If so, the obvious answer is "Go to Add-Remove-Programs. Uninstall. > Then double-click the MSI files." If that is not a good answer: > why not? > > If you want that automated: write a batch file, invoking "msiexec" > as necessary. > > Regards, > Martin > > Given. We either download them from various specified sites or newbies get a CD when they receive hardware that is used by the sponsor's programs. Add-Remove would be a very good answer, except for one thing. Understand that I'm in Win7 so CP takes on a different form. On Control Panel Add-Remove, I can find exactly two Python files: Python 2.5, and python-Numpy-1.2.0. No scipy anything. Well, this is interesting. I just noticed Martin v. Loewis on the Python 2.5 entry. That's you, right? msiexec. Don't need it automated now, but it might be worthwhile, at some future point. I think I posted the errors my partner got above. Let me look. Yes, here's the copy. He gets Traceback (most recent call last): File "C:\Documents and Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", line 40, in from scipy import stats as stats # scoreatpercentile File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, in from stats import * File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, in import scipy.special as special File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 22, in from numpy.testing import NumpyTest ImportError: cannot import name NumpyTest Here are the first few lines of code. import sys, os, glob import string from numpy import * from datetime import datetime, timedelta import time from scipy import stats as stats # scoreatpercentile From cmpython at gmail.com Sat Aug 7 21:26:51 2010 From: cmpython at gmail.com (CM) Date: Sat, 7 Aug 2010 18:26:51 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> Message-ID: <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> > Apparently, the Japanese used to (before they started adopting western > conventions). I.e. ages were given as "in his tenth year" (meaning nine > years old). Koreans still do this. The day a child is born it is "one". Even odder to me, the next birthday is not on the next anniversary of the birth, but on the following New Year's Day. So a kid who is born on Dec 26th, will be "two" as of New Year's Day the week following his/ her birth. (They also are aware of the "western" version of their ages if needed). . From python at mrabarnett.plus.com Sat Aug 7 21:42:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Aug 2010 02:42:07 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> Message-ID: <4C5E0B6F.9000403@mrabarnett.plus.com> rantingrick wrote: > On Aug 7, 7:20 pm, ????? wrote: >> Hello dear Pythoneers, > > I prefer Pythonista, but anywho.. > >> I have over 500 .php web pages in various subfolders under 'data' >> folder that i have to rename to .html > > import os > os.rename(old, new) > >> and and ditch the '' tages from within > > path = 'some/valid/path' > f = open(path, 'r') > data = f.read() > f.close() > data.replace(' data.replace('?>', '') > That should be: data = data.replace('', '') >> and also insert a very first line of >> where id must be an identification unique number of every page for >> counter tracking purposes. > > comment = ""%(idnum) > data.insert(idx, comment) > Strings don't have an 'insert' method! >> ONly pure html code must be left. > > Well then don't F up! However judging from the amount of typos in this > post i would suggest you do some major testing! > >> I don't know how to handle such a big data replacing problem and >> cannot play with fire because those 500 pages are my cleints pages and >> data of those files just cannot be messes up. > > Better do some serous testing first, or (if you have enough disc > space ) create copies instead! > >> Can you provide to me a script please that is able of performing an >> automatic way of such a page content replacing? > > This is very basic stuff and the fine manual is free you know. But how > much are you willing to pay? From ian.g.kelly at gmail.com Sat Aug 7 22:08:05 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 7 Aug 2010 20:08:05 -0600 Subject: Python "why" questions In-Reply-To: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: On Sat, Aug 7, 2010 at 1:14 PM, John Nagle wrote: > ? FORTRAN, MATLAB, and Octave all use 1-based subscripts. > > ? The languages which have real multidimensional arrays, rather > than arrays of arrays, tend to use 1-based subscripts. ?That > reflects standard practice in mathematics. I propose that this has less to do with the fact that those languages have "real" multidimensional arrays, and more to do with the fact that those languages are designed for doing mathematics. C, Oberon, and others also have "real" multidimensional arrays, and use 0-based subscripts. Standard practice in mathematics is not necessarily best practice in programming. Cheers, Ian From nikos.the.gr33k at gmail.com Sat Aug 7 22:26:31 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 19:26:31 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> Message-ID: # rename ALL php files to html in every subfolder of the folder 'data' os.rename('*.php', '*.html') # how to tell python to rename ALL php files to html to ALL subfolder under 'data' ? # current path of the file to be processed path = './data' # this must be somehow in a loop i feel that read every file of every subfolder # open an html file for reading f = open(path, 'rw') # read the contents of the whole file data = f.read() # replace all php tags with empty string data = data.replace('', '') # write replaced data to file data = f.write() # insert an increasing unique integer number at the very first line of every html file processing comment = ""%(idnum) # how will the number change here an increased by one file after file? f = f.close() Please help i'm new to python an apart from syntx its a logic problem as well and needs experience. From roy at panix.com Sat Aug 7 22:35:59 2010 From: roy at panix.com (Roy Smith) Date: Sat, 07 Aug 2010 22:35:59 -0400 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> Message-ID: In article <7f3c505c-4002-427e-a969-6d735307e0f6 at z10g2000yqb.googlegroups.com>, CM wrote: > > Apparently, the Japanese used to (before they started adopting western > > conventions). I.e. ages were given as "in his tenth year" (meaning nine > > years old). With apologies to Paul Simon... One man's ceil() is another man's floor() From steveo at syslang.net Sat Aug 7 22:42:25 2010 From: steveo at syslang.net (Steven W. Orr) Date: Sat, 07 Aug 2010 22:42:25 -0400 Subject: I need a starter ptr writing python embedded in html. Message-ID: <4C5E1991.9020401@syslang.net> I'm ok in python but I haven't done too much with web pages. I have a web page that is hand written in html that has about 1000 entries in a table and I want to convert the table from entries like this to SomePythonCall('Some Date String', 'SomeTag', 'localSubdir', "http://www.example.com/remote/path/something.html", 'Click', 'Some Comment') Can someone tell me what I should look at to do this? Is mod_python where I should start or are there things that are better? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From jstrickler at gmail.com Sat Aug 7 22:42:31 2010 From: jstrickler at gmail.com (John S) Date: Sat, 7 Aug 2010 19:42:31 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <989608bf-56fd-4f96-988e-9f3e6daa8680@d8g2000yqf.googlegroups.com> On Aug 7, 8:20?pm, ????? wrote: > Hello dear Pythoneers, > > I have over 500 .php web pages in various subfolders under 'data' > folder that i have to rename to .html and and ditch the '' > tages from within and also insert a very first line of > where id must be an identification unique number of every page for > counter tracking purposes. ONly pure html code must be left. > > I before find otu Python used php and now iam switching to templates + > python solution so i ahve to change each and every page. > > I don't know how to handle such a big data replacing problem and > cannot play with fire because those 500 pages are my cleints pages and > data of those filesjust cannot be messes up. > > Can you provide to me a script please that is able of performing an > automatic way of such a page content replacing? > > Thanks a million! If the 500 web pages are PHP only in the sense that there is only one pair of tags in each file, surrounding the entire content, then what you ask for is doable. from os.path import join import os id = 1 # id number for currdir,files,dirs in os.walk('data'): for f in files: if f.endswith('php'): source_file_name = join(currdir,f) # get abs path to filename source_file = open(source_file_name) source_contents = source_file.read() # read contents of PHP file source_file.close() # replace tags source_contents = source_contents.replace('<%','') source_contents = source_contents.replace('%>','') # add ID source_contents = ( '' % id ) + source_contents id += 1 # create new file with .html extension source_file_name = source_file_name.replace('.php','.html') dest_file = open(source_file_name,'w') dest_file.write(source_contents) # write contents dest_file.close() Note: error checking left out for clarity. On the other hand, if your 500 web pages contain embedded PHP variables or logic, you have a big job ahead. Django templates and PHP are two different languages for embedding data and logic in web pages. Converting a project from PHP to Django involves more than renaming the template files and deleting "'; } ?> In Django, you would typically put this logic in a Django *view* (which btw is not what is called a 'view' in MVC term), which is the code that prepares data for the template. The logic would not live with the HTML. The template uses "template variables" that the view has associated with a Python variable or function. You might create a template variable (created via a Context object) named 'browser' that contains a value that identifies the browser. Thus, your Python template (HTML file) might look like this: {% if browser == 'IE' %}You are using Internet Explorer{% endif %} PHP tends to combine the presentation with the business logic, or in MVC terms, combines the view with the controller. Django separates them out, which many people find to be a better way. The person who writes the HTML doesn't have to speak Python, but only know the names of template variables and a little bit of template logic. In PHP, the HTML code and all the business logic lives in the same files. Even here, it would probably make sense to calculate the browser ID in the header of the HTML file, then access it via a variable in the body. If you have 500 static web pages that are part of the same application, but that do not contain any logic, your application might need to be redesigned. Also, you are doing your changes on a COPY of the application on a non- public server, aren't you? If not, then you really are playing with fire. HTH, John From rantingrick at gmail.com Sat Aug 7 22:46:18 2010 From: rantingrick at gmail.com (rantingrick) Date: Sat, 7 Aug 2010 19:46:18 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> Message-ID: <1ea6fd9a-d83b-4b45-b5e9-9b5673b9e5f4@e15g2000yqo.googlegroups.com> On Aug 7, 8:42?pm, MRAB wrote: > That should be: > > ? ?data = data.replace(' ? ?data = data.replace('?>', '') Yes, Thanks MRAB. I did forget that important detail. > Strings don't have an 'insert' method! *facepalm*! I really must stop Usenet-ing whilst consuming large volumes of alcoholic beverages. From jstrickler at gmail.com Sat Aug 7 22:56:05 2010 From: jstrickler at gmail.com (John S) Date: Sat, 7 Aug 2010 19:56:05 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <989608bf-56fd-4f96-988e-9f3e6daa8680@d8g2000yqf.googlegroups.com> Message-ID: <355b90cc-bbf5-41bc-9021-e796bf2a1f2c@5g2000yqz.googlegroups.com> Even though I just replied above, in reading over the OP's message, I think the OP might be asking: "How can I use RE string replacement to find PHP tags and convert them to Django template tags?" Instead of saying source_contents = source_contents.replace(...) say this instead: import re def replace_php_tags(m): ''' PHP tag replacer This function is called for each PHP tag. It gets a Match object as its parameter, so you can get the contents of the old tag, and should return the new (Django) tag. ''' # m is the match object from the current match php_guts = m.group(1) # the contents of the PHP tag # now put the replacement logic here # and return whatever should go in place of the PHP tag, # which could be '{{ python_template_var }}' # or '{% template logic ... %} # or some combination source_contents = re.sub('',replace_php_tags,source_contents) From nikos.the.gr33k at gmail.com Sat Aug 7 23:11:01 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 20:11:01 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <989608bf-56fd-4f96-988e-9f3e6daa8680@d8g2000yqf.googlegroups.com> Message-ID: <2a14900c-f2e5-49e0-b260-5129e4c851f6@14g2000yqa.googlegroups.com> On 8 ???, 05:42, John S wrote: > If the 500 web pages are PHP only in the sense that there is only one > pair of tags in each file, surrounding the entire content, then > what you ask for is doable. First of all, thank you very much John for your BIG effort to help me(i'm still readign your posts)! I have to tell you here that those php files contain several instances of php opening and closing tags(like 3 each php file). The rest is pure html data. That happened because those files were in the beginning html only files that later needed conversion to php due to some dynamic code that had to be used to address some issues. Please tell me that the code you provided can be adjusted to several instances as well! From nikos.the.gr33k at gmail.com Sat Aug 7 23:35:03 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 20:35:03 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <989608bf-56fd-4f96-988e-9f3e6daa8680@d8g2000yqf.googlegroups.com> <355b90cc-bbf5-41bc-9021-e796bf2a1f2c@5g2000yqz.googlegroups.com> Message-ID: <921898ca-f8d1-472b-b47e-626a1b6afb59@l14g2000yql.googlegroups.com> On 8 ???, 05:56, John S wrote: >"How can I use RE string replacement to find PHP tags and convert them >to Django template tags?" No, not at all John, at least not yet! I have only 1 week that i'm learnign python(changing from php & perl) so i'm very fresh at this beautifull and straighforwrd language. When i have a good understnading of Python then i will proceed to Django templates. Until then my Python templates would be only 'simple html files' that the only thign they contain apart form the html data would be the special string formatting identifies '%s' :-) From miki.tebeka at gmail.com Sat Aug 7 23:57:50 2010 From: miki.tebeka at gmail.com (Miki) Date: Sat, 7 Aug 2010 20:57:50 -0700 (PDT) Subject: I need a starter ptr writing python embedded in html. References: Message-ID: <3cc2a461-19f0-4aaf-9305-dde36fa2656c@v6g2000prd.googlegroups.com> On Aug 7, 7:42?pm, "Steven W. Orr" wrote: > I'm ok in python but I haven't done too much with web pages. I have a web page > that is hand written in html that has about 1000 entries in a table and I want > to convert the table from entries like this > > ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? > > to > > ? ?SomePythonCall('Some Date String', > ? ? ? ? ? ? ? ? 'SomeTag', > ? ? ? ? ? ? ? ? 'localSubdir', > ? ? ? ? ? ? ? ? "http://www.example.com/remote/path/something.html", > ? ? ? ? ? ? ? ? 'Click', > ? ? ? ? ? ? ? ? 'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? Have a look at http://www.crummy.com/software/BeautifulSoup/. All the best, -- Miki http://mikitebeka.com The only difference between children and adults is the price of the toys From pavlovevidence at gmail.com Sun Aug 8 00:34:00 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 7 Aug 2010 21:34:00 -0700 (PDT) Subject: Nice way to cast a homogeneous tuple References: <4c50eb46$0$28664$c3e8da3@news.astraweb.com> <1pm7i7-473.ln1@satorlaser.homedns.org> <49f9d367-20fc-442f-b397-9d50ffb391f2@i4g2000prf.googlegroups.com> Message-ID: <6473a005-3753-4628-850d-be49cdf6bd2d@h17g2000pri.googlegroups.com> On Aug 7, 8:18?pm, Dennis Lee Bieber wrote: > On Sat, 7 Aug 2010 13:02:56 -0700 (PDT), Carl Banks > declaimed the following in > gmane.comp.python.general: > > > > > Not really. ?Very few people call int(), float(), and company "type > > casts". ?They aren't type casts at all, they are constructors that > > sometimes have the same semantics as type casts in C. > > ? ? ? ? Given the different syntax, I never see them as "type casts"... They > look like functions that take an argument (or more than one: > int("FE", 16) ) and convert it into a value of the type named... > > ? ? ? ? C, OTOH, I'm never sure if a conversion (the bit pattern of the > result is different from the bit pattern of the source) or an > equivalencing (the bit pattern of the result is the same as the bit > pattern of the source, but the /interpretation/ of those bits is > different) is taking place. C's type casts are always a conversion. There are no exceptions I'm aware of. The only way to reinterpret bits in C is to take a reference, cast the pointer, and then derefernece again. (C++ has a reinterpret_cast for that.) *(int*)&x Casting an integer to a pointer retains the same bits because a pointer's "value" is considered to be the same as the unsigned integer with the same bit pattern. Pointer-to-pointer casts in C++ don't always retain the same bits, BTW. Carl Banks From eknath.iyer at gmail.com Sun Aug 8 02:49:01 2010 From: eknath.iyer at gmail.com (Eknath Venkataramani) Date: Sun, 8 Aug 2010 12:19:01 +0530 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <4C5E1991.9020401@syslang.net> References: <4C5E1991.9020401@syslang.net> Message-ID: BeautifulSoup On Sun, Aug 8, 2010 at 8:12 AM, Steven W. Orr wrote: > I'm ok in python but I haven't done too much with web pages. I have a web > page > that is hand written in html that has about 1000 entries in a table and I > want > to convert the table from entries like this > > > > > > > > > > to > > SomePythonCall('Some Date String', > 'SomeTag', > 'localSubdir', > "http://www.example.com/remote/path/something.html", > 'Click', > 'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? > > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things have > .0. > happened but none stranger than this. Does your driver's license say Organ > ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are all- > 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Eknath Venkataramani -------------- next part -------------- An HTML attachment was scrubbed... URL: From sschwarzer at sschwarzer.net Sun Aug 8 03:46:40 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 08 Aug 2010 09:46:40 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <878w4i10ad.fsf@benfinney.id.au> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <878w4i10ad.fsf@benfinney.id.au> Message-ID: <4C5E60E0.3050603@sschwarzer.net> Hi Ben, On 2010-08-08 01:16, Ben Finney wrote: > Don't use strings for such values. The data isn't going to be used, so > there's no sense using a semantically rich data type like a string. > > Instead, use an ?object? instance; then, the only way to get a binding > that will compare equal is to use the very object itself. > > FORWARD = object() > BACKWARD = object() Yes, that's the obvious approach. :-) I had used strings in the example with the reasoning that they could be readily used in messages (from my post: "Using a string instead of an `object()` has the advantage that it makes usage in error messages easier."). For the record, another approach I've seen is something like FORWARD, BACKWARD, UNKNOWN = range(3) This has the same problem as when using strings for the constants but looking at the module contents it's a bit more obvious that these are just "magic numbers", so presumably the constant names should be used instead. Stefan From blur959 at hotmail.com Sun Aug 8 04:02:36 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 01:02:36 -0700 (PDT) Subject: Renaming of files in OS directory Message-ID: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Hi, all, I am writing a program that renames files inside OS directories the user provides. I am at the early stage of writing it and I encountered some problems. Below is my code. There is an error i received when i run this code. The error is, WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect. Hope you guys could help. import os, glob def fileDirectory(): #Asks the user for a file root directory fileroot = raw_input("Please input the file root directory \n\n") print fileroot #Returns a list with all the files inside the file root directory os.listdir(fileroot) fileDirectory() From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 04:09:35 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Aug 2010 08:09:35 GMT Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <4c5e663f$0$28655$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 17:20:24 -0700, ????? wrote: > I don't know how to handle such a big data replacing problem and cannot > play with fire because those 500 pages are my cleints pages and data of > those filesjust cannot be messes up. Take a backup copy of the files, and only edit the copies. Don't replace the originals until you know they're correct. -- Steven From landa.martin at gmail.com Sun Aug 8 04:14:38 2010 From: landa.martin at gmail.com (Martin Landa) Date: Sun, 8 Aug 2010 01:14:38 -0700 (PDT) Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Message-ID: <72b2e878-b61c-4f0e-92ca-14e5d54adf0f@v41g2000yqv.googlegroups.com> On Aug 7, 12:46?pm, Martin Landa wrote: > the problem occurs when restype is not None, but c_int. E.g. solved. Martin From clp2 at rebertia.com Sun Aug 8 04:15:51 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 8 Aug 2010 01:15:51 -0700 Subject: Renaming of files in OS directory In-Reply-To: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: > Hi, all, I am writing a program that renames files inside OS > directories the user provides. I am at the early stage of writing it > and I encountered some problems. > > Below is my code. There is an error i received when i run this code. > The error is, WindowsError: [Error 123] The filename, directory name, > or volume label syntax is incorrect. Well, what directory did you input? Apparently it wasn't a valid or extant one. Cheers, Chris -- http://blog.rebertia.com From nikos.the.gr33k at gmail.com Sun Aug 8 04:30:51 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 01:30:51 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> Message-ID: On 8 ???, 11:09, Steven D'Aprano wrote: > On Sat, 07 Aug 2010 17:20:24 -0700, ????? wrote: > > I don't know how to handle such a big data replacing problem and cannot > > play with fire because those 500 pages are my cleints pages and data of > > those filesjust cannot be messes up. > > Take a backup copy of the files, and only edit the copies. Don't replace > the originals until you know they're correct. > > -- > Steven Yes of course, but the code that John S provided need soem modification in order to be able to change various instances of php tags and not only one set. From blur959 at hotmail.com Sun Aug 8 04:35:54 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 01:35:54 -0700 (PDT) Subject: Renaming of files in OS directory References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: On Aug 8, 4:15?pm, Chris Rebert wrote: > On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: > > Hi, all, I am writing a program that renames files inside OS > > directories the user provides. I am at the early stage of writing it > > and I encountered some problems. > > > Below is my code. There is an error i received when i run this code. > > The error is, WindowsError: [Error 123] The filename, directory name, > > or volume label syntax is incorrect. > > Well, what directory did you input? Apparently it wasn't a valid or extant one. > > Cheers, > Chris > --http://blog.rebertia.com I input for e.g, "C:" it works, basically, if i input a hard code string inside os.listdir it works, but if i stored the string that the user keyed inside a variable and run os.listdir with the variable, there is that error. But inputing hard code string inside os.listdir isn't what I want when I am writing this program. From clp2 at rebertia.com Sun Aug 8 04:58:10 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 8 Aug 2010 01:58:10 -0700 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <4C5E1991.9020401@syslang.net> References: <4C5E1991.9020401@syslang.net> Message-ID: On Sat, Aug 7, 2010 at 7:42 PM, Steven W. Orr wrote: > I'm ok in python but I haven't done too much with web pages. I have a web page > that is hand written in html that has about 1000 entries in a table and I want > to convert the table from entries like this > > ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? > > to > > ? SomePythonCall('Some Date String', > ? ? ? ? ? ? ? ?'SomeTag', > ? ? ? ? ? ? ? ?'localSubdir', > ? ? ? ? ? ? ? ?"http://www.example.com/remote/path/something.html", > ? ? ? ? ? ? ? ?'Click', > ? ? ? ? ? ? ? ?'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? Certainly not mod_python; that project is dead. mod_wsgi is the suggested replacement. But both are relatively low-level solutions. Python has myriad web frameworks available for it; have a look at them. Cheers, Chris -- http://blog.rebertia.com From mark.dufour at gmail.com Sun Aug 8 05:01:32 2010 From: mark.dufour at gmail.com (Mark Dufour) Date: Sun, 8 Aug 2010 11:01:32 +0200 Subject: ANN: Shed Skin 0.5 Message-ID: Hi all, I have just released Shed Skin 0.5, an experimental (restricted) Python-to-C++ compiler. Please see my blog for more details about the release: http://shed-skin.blogspot.com/ Thanks, Mark Dufour. -- http://www.youtube.com/watch?v=E6LsfnBmdnk -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Sun Aug 8 05:21:56 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 02:21:56 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> Message-ID: <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> Script so far: #!/usr/bin/python import cgitb; cgitb.enable() import cgi, re, os print ( "Content-type: text/html; charset=UTF-8 \n" ) id = 0 # unique page_id for currdir, files, dirs in os.walk('data'): for f in files: if f.endswith('php'): # get abs path to filename src_f = join(currdir,f) # open php src file f = open(src_f, 'r') src_data = f.read() # read contents of PHP file f.close() print 'reading from %s' % src_f # replace tags src_data = src_data.replace('<%', '') src_data = src_data.replace('%>', '') print 'replacing php tags' # add ID src_data = ( '' % id ) + src_data id += 1 print 'adding unique page_id' # create new file with .html extension src_file = src_file.replace('.php', '.html') # open newly created html file for insertid data dest_f = open(src_f, 'w') dest_f.write(src_data) # write contents dest_f.close() print 'writing to %s' % dest_f Please help me adjust it, if need extra modification for more php tags replacing. From thomas at jollans.com Sun Aug 8 06:00:51 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 12:00:51 +0200 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: <4C5E8053.90901@jollans.com> On 08/08/2010 03:10 AM, W. eWatson wrote: > I think I posted the errors my partner got above. Let me look. Yes, > here's the copy. > He gets > > Traceback (most recent call last): > File "C:\Documents and > Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", > line 40, in > from scipy import stats as stats # scoreatpercentile > File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, > in > from stats import * > File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, > in > import scipy.special as special > File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line > 22, in > from numpy.testing import NumpyTest > ImportError: cannot import name NumpyTest > Is this error actually caused by the "one char change"? If you undo your "one char change", does the error disappear? > Here are the first few lines of code. > > import sys, os, glob > import string > from numpy import * > from datetime import datetime, timedelta > import time > from scipy import stats as stats # scoreatpercentile From thomas at jollans.com Sun Aug 8 06:05:10 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 12:05:10 +0200 Subject: Renaming of files in OS directory In-Reply-To: References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: <4C5E8156.4000001@jollans.com> On 08/08/2010 10:35 AM, blur959 wrote: > On Aug 8, 4:15 pm, Chris Rebert wrote: >> On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: >>> Hi, all, I am writing a program that renames files inside OS >>> directories the user provides. I am at the early stage of writing it >>> and I encountered some problems. >> >>> Below is my code. There is an error i received when i run this code. >>> The error is, WindowsError: [Error 123] The filename, directory name, >>> or volume label syntax is incorrect. >> >> Well, what directory did you input? Apparently it wasn't a valid or extant one. >> >> Cheers, >> Chris >> --http://blog.rebertia.com > > > I input for e.g, "C:" it works, basically, if i input a hard code > string inside os.listdir it works, but if i stored the string that the > user keyed inside a variable and run os.listdir with the variable, > there is that error. But inputing hard code string inside os.listdir > isn't what I want when I am writing this program. You didn't answert the question. What is the actual string you pass to os.listdir after you got it from the user? You could print repr(fileroot) to find out. My tentative guess is that maybe Windows doesn't like newlines in file names (I know UNIX allows them, but they're still usually a bad idea) and maybe you string ends with a newline. From thomas at jollans.com Sun Aug 8 06:09:00 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 12:09:00 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <1ea6fd9a-d83b-4b45-b5e9-9b5673b9e5f4@e15g2000yqo.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> <1ea6fd9a-d83b-4b45-b5e9-9b5673b9e5f4@e15g2000yqo.googlegroups.com> Message-ID: <4C5E823C.40105@jollans.com> On 08/08/2010 04:46 AM, rantingrick wrote: > *facepalm*! I really must stop Usenet-ing whilst consuming large > volumes of alcoholic beverages. THAT explains a lot. Cheers From thomas at jollans.com Sun Aug 8 06:13:10 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 12:13:10 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> Message-ID: <4C5E8336.6070000@jollans.com> On 08/08/2010 11:21 AM, ????? wrote: > Please help me adjust it, if need extra modification for more php tags > replacing. Have you tried it ? I haven't, but I see no immediate reason why it wouldn't work with multiple PHP blocks. > #!/usr/bin/python > > import cgitb; cgitb.enable() > import cgi, re, os > > print ( "Content-type: text/html; charset=UTF-8 \n" ) > > > id = 0 # unique page_id > > for currdir, files, dirs in os.walk('data'): > > for f in files: > > if f.endswith('php'): > > # get abs path to filename > src_f = join(currdir,f) > > # open php src file > f = open(src_f, 'r') > src_data = f.read() # read contents of PHP file > f.close() > print 'reading from %s' % src_f > > # replace tags > src_data = src_data.replace('<%', '') > src_data = src_data.replace('%>', '') Did you read the script before posting? ;-) Here, you remove ASP-style tags. Which is fine, PHP supports them if you configure it that way, but you probably didn't. Change this to the start and end tags you actually use, and, if you use multiple forms (such as print 'replacing php tags' > > # add ID > src_data = ( '' % id ) + src_data > id += 1 > print 'adding unique page_id' > > # create new file with .html extension > src_file = src_file.replace('.php', '.html') > > # open newly created html file for insertid data > dest_f = open(src_f, 'w') > dest_f.write(src_data) # write contents > dest_f.close() > print 'writing to %s' % dest_f > From blur959 at hotmail.com Sun Aug 8 06:23:28 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 03:23:28 -0700 (PDT) Subject: Renaming of files in OS directory References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: On Aug 8, 6:05?pm, Thomas Jollans wrote: > On 08/08/2010 10:35 AM, blur959 wrote: > > > > > On Aug 8, 4:15 pm, Chris Rebert wrote: > >> On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: > >>> Hi, all, I am writing a program that renames files inside OS > >>> directories the user provides. I am at the early stage of writing it > >>> and I encountered some problems. > > >>> Below is my code. There is an error i received when i run this code. > >>> The error is, WindowsError: [Error 123] The filename, directory name, > >>> or volume label syntax is incorrect. > > >> Well, what directory did you input? Apparently it wasn't a valid or extant one. > > >> Cheers, > >> Chris > >> --http://blog.rebertia.com > > > I input for e.g, "C:" it works, basically, if i input a hard code > > string inside os.listdir it works, but if i stored the string that the > > user keyed inside a variable and run os.listdir with the variable, > > there is that error. But inputing hard code string inside os.listdir > > isn't what I want when I am writing this program. > > You didn't answert the question. What is the actual string you pass to > os.listdir after you got it from the user? You could > ? ? print repr(fileroot) > to find out. > > My tentative guess is that maybe Windows doesn't like newlines in file > names (I know UNIX allows them, but they're still usually a bad idea) > and maybe you string ends with a newline. I do not get what you mean. The string i passed in is stored inside the variable fileroot. In the case I tested, i inputed the string "C: \" inside the raw_input and stored it inside fileroot, I tried printing repr(fileroot) and it gave me "C:\" as the result and when i tried running os.listdir(fileroot) i got the error. The string i passed to os.listdir is the string i keyed inside fileroot under the raw_input? From ldo at geek-central.gen.new_zealand Sun Aug 8 06:44:56 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Aug 2010 22:44:56 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> <8c4g22F5ljU1@mid.individual.net> Message-ID: In message <8c4g22F5ljU1 at mid.individual.net>, Gregory Ewing wrote: > FWIW, certain parts of the Darwin kernel are written in a > carefully-selected subset of C++. So Apple evidently think > that it makes sense to use some C++ in a Unix kernel under > some circumstances. I wonder if that explains Apple?s well-known multitasking problems. :) From ldo at geek-central.gen.new_zealand Sun Aug 8 06:45:51 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Aug 2010 22:45:51 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In message , Albert van der Horst wrote: > The bottom line is that to implement a programming language > you want to use a simpler programming language, not a more > complicated one. That would rule out ever using a language to implement itself. From gelonida at gmail.com Sun Aug 8 06:47:51 2010 From: gelonida at gmail.com (Gelonida) Date: Sun, 08 Aug 2010 12:47:51 +0200 Subject: cscope like source code navigation for python code In-Reply-To: References: Message-ID: On 08/08/2010 01:42 AM, Tim Harig wrote: > On 2010-08-07, Gelonida wrote: >> I'm using g?vim and its c-scope plugin for browsing C-code. >> What would be a good way of navigating larger python projects with vim? > > ctags: > http://ctags.sourceforge.net/ Thanks Tim. This looks quite interesting. I prefereed vim/cscope for navigation, but guess after some learning with vim/ctags I should get along quite well. My biggest problem with is, that ctrl-] doesn't ask you to which tag to jump in case multiple options exist. From cournape at gmail.com Sun Aug 8 07:08:00 2010 From: cournape at gmail.com (David Cournapeau) Date: Sun, 8 Aug 2010 20:08:00 +0900 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On Sun, Aug 8, 2010 at 10:10 AM, W. eWatson wrote: > On 8/7/2010 4:45 PM, Martin v. Loewis wrote: >>> >>> To add to the msg I just sent to M. Torrie. We are given the msi >>> programs for Python, PIL,matplotlib, and numpy. The question of how to >>> uninstall and re-install a different version remains. >> >> I'd claim that this is not the real question. The real question is, >> instead: "What specific error did you get when adding a single minus >> sign to the program?" >> >> Please try answering that question also. >> >>> The answer is? >> >> I'm not sure I understand the question. What do you mean by "given"? >> Perhaps "already downloaded locally"? >> >> If so, the obvious answer is "Go to Add-Remove-Programs. Uninstall. >> Then double-click the MSI files." If that is not a good answer: >> why not? >> >> If you want that automated: write a batch file, invoking "msiexec" >> as necessary. >> >> Regards, >> Martin >> >> > Given. We either download them from various specified sites or newbies get a > CD when they receive hardware that is used by the sponsor's programs. > > Add-Remove would be a very good answer, except for one thing. Understand > that I'm in Win7 so CP takes on a different form. On Control Panel > Add-Remove, I can find exactly two Python files: Python 2.5, and > python-Numpy-1.2.0. No scipy anything. Well, this is interesting. I just > noticed Martin v. Loewis on the Python 2.5 entry. That's you, right? You are conflating so many issues at the same time, it is very difficult to follow what you are doing. Concerning the numpy error: you installed a version of scipy which requires a more recent version of numpy than the one you have. More concretely, NumpyTest has disappeared since 1.3.0. Unless you have a good reason not to, I strongly suggest to just use the last released versions of numpy and scipy (1.4.1 and 0.8.0 respectively). Note also that Enthought Python Distribution exists to exactly avoid those issues - they do the packaging hard word so that you don't have to. But none of this has anything to do with one character change or portability, cheers, David From thomas at jollans.com Sun Aug 8 07:27:15 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 13:27:15 +0200 Subject: cscope like source code navigation for python code In-Reply-To: References: Message-ID: <4C5E9493.6060101@jollans.com> On 08/07/2010 07:53 PM, Gelonida wrote: > Hi, > > I'm using g?vim and its c-scope plugin for browsing C-code. > > What would be a good way of navigating larger python projects with vim? > > > thanks for any suggestions > http://pypi.python.org/pypi/pycscope/0.2 Looks like an option From ldo at geek-central.gen.new_zealand Sun Aug 8 07:40:19 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Aug 2010 23:40:19 +1200 Subject: Microsoft lessening commitment to IronPython and IronRuby References: Message-ID: In message , Neil Hodgson wrote: > http://blog.jimmy.schementi.com/2010/08/start-spreading-news-future-of-jimmy.html Frankly I never understood the point of IronPython and IronRuby. They seemed like a desperate attempt to keep Dotnet relevant in the modern world of dynamic languages. Looks like it was a failure. Yawn. From shambhu.1980 at gmail.com Sun Aug 8 07:41:14 2010 From: shambhu.1980 at gmail.com (Shambhu) Date: Sun, 8 Aug 2010 04:41:14 -0700 (PDT) Subject: os.unlink on Windows References: Message-ID: Hi Thomas, I checked, file is present. Here is my sample script: import os filename = "C:\SHAMBHU\tmp\text_delete.txt" os.unlink(filename) File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\ \tmp\\text_delete.txt" is not (with extra backslash in path which is added by os.unlink). Regards. Shambhu. On Aug 7, 4:46?pm, Thomas Jollans wrote: > On 08/07/2010 01:10 PM, Shambhu Sharma wrote: > > > Hi, > > > ? ? ? ? I am new to Python. I was trying to use os.unlink function in > > windows. But i am getting error: > > OSError: [Errno 2] No such file or directory: > > 'C:\\SHAMBHU\\tmp\\text_delete.txt' > > > Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But > > os.unlink is adding extra backslash with pathname. > > No, it isn't. What you're seeing is simply the repr() of the path name > string. > > >>> p = r'C:\SHAMBHU\tmp\text_delete.txt' > >>> p > > 'C:\\SHAMBHU\\tmp\\text_delete.txt'>>> print(p) > > C:\SHAMBHU\tmp\text_delete.txt > > > > I think the file you're trying to delete probably doesn't exist. Why > don't you double-check that. > > > I tried with > > Python2.5 and Python3.1 but got same error. > > Please suggest how to remove this error. > > > -- > > If linux doesn't have a solution, then u have a wrong problem. > > > Shambhu Kumar Sharma > > 91-98864 91913 > > From nikos.the.gr33k at gmail.com Sun Aug 8 07:41:21 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 04:41:21 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> Message-ID: <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> On 8 ???, 13:13, Thomas Jollans wrote: > On 08/08/2010 11:21 AM, ????? wrote: > > > Please help me adjust it, if need extra modification for more php tags > > replacing. > > Have you tried it ? I haven't, but I see no immediate reason why it > wouldn't work with multiple PHP blocks. > > > > > > > #!/usr/bin/python > > > import cgitb; cgitb.enable() > > import cgi, re, os > > > print ( "Content-type: text/html; charset=UTF-8 \n" ) > > > id = 0 ?# unique page_id > > > for currdir, files, dirs in os.walk('data'): > > > ? ? for f in files: > > > ? ? ? ? if f.endswith('php'): > > > ? ? ? ? ? ? # get abs path to filename > > ? ? ? ? ? ? src_f = join(currdir,f) > > > ? ? ? ? ? ? # open php src file > > ? ? ? ? ? ? f = open(src_f, 'r') > > ? ? ? ? ? ? src_data = f.read() ? ? ? ? # read contents of PHP file > > ? ? ? ? ? ? f.close() > > ? ? ? ? ? ? print 'reading from %s' % src_f > > > ? ? ? ? ? ? # replace tags > > ? ? ? ? ? ? src_data = src_data.replace('<%', '') > > ? ? ? ? ? ? src_data = src_data.replace('%>', '') > > Did you read the script before posting? ;-) > Here, you remove ASP-style tags. Which is fine, PHP supports them if you > configure it that way, but you probably didn't. Change this to the start > and end tags you actually use, and, if you use multiple forms (such as > > > > > ? ? ? ? ? ? print 'replacing php tags' > > > ? ? ? ? ? ? # add ID > > ? ? ? ? ? ? src_data = ( '' % id ) + src_data > > ? ? ? ? ? ? id += 1 > > ? ? ? ? ? ? print 'adding unique page_id' > > > ? ? ? ? ? ? # create new file with .html extension > > ? ? ? ? ? ? src_file = src_file.replace('.php', '.html') > > > ? ? ? ? ? ? # open newly created html file for insertid data > > ? ? ? ? ? ? dest_f = open(src_f, 'w') > > ? ? ? ? ? ? dest_f.write(src_data) ? ? ?# write contents > > ? ? ? ? ? ? dest_f.close() > > ? ? ? ? ? ? print 'writing to %s' % dest_f Yes i have read the code very well and by mistake i wrote '<%>' instead of ' of every html file afetr removing the tags this line must be inserted(this holds the template variable) that 'counter.py' uses to produce data

??????? ??????????: %(counter)d

After making this modifications then i can trst the script to a COPY of the original data in my pc. *In my pc i run Windows 7 while remote web hosting setup uses Linux Servers. *That wont be a problem right? From thomas at jollans.com Sun Aug 8 07:45:35 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 13:45:35 +0200 Subject: Renaming of files in OS directory In-Reply-To: References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: <4C5E98DF.2000504@jollans.com> On 08/08/2010 12:23 PM, blur959 wrote: > On Aug 8, 6:05 pm, Thomas Jollans wrote: >> On 08/08/2010 10:35 AM, blur959 wrote: >> >> >> >>> On Aug 8, 4:15 pm, Chris Rebert wrote: >>>> On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: >>>>> Hi, all, I am writing a program that renames files inside OS >>>>> directories the user provides. I am at the early stage of writing it >>>>> and I encountered some problems. >> >>>>> Below is my code. There is an error i received when i run this code. >>>>> The error is, WindowsError: [Error 123] The filename, directory name, >>>>> or volume label syntax is incorrect. >> >>>> Well, what directory did you input? Apparently it wasn't a valid or extant one. >> >>>> Cheers, >>>> Chris >>>> --http://blog.rebertia.com >> >>> I input for e.g, "C:" it works, basically, if i input a hard code >>> string inside os.listdir it works, but if i stored the string that the >>> user keyed inside a variable and run os.listdir with the variable, >>> there is that error. But inputing hard code string inside os.listdir >>> isn't what I want when I am writing this program. >> >> You didn't answert the question. What is the actual string you pass to >> os.listdir after you got it from the user? You could >> print repr(fileroot) >> to find out. >> >> My tentative guess is that maybe Windows doesn't like newlines in file >> names (I know UNIX allows them, but they're still usually a bad idea) >> and maybe you string ends with a newline. > > > > I do not get what you mean. The string i passed in is stored inside > the variable fileroot. In the case I tested, i inputed the string "C: > \" inside the raw_input and stored it inside fileroot, I tried > printing repr(fileroot) and it gave me "C:\" as the result and when i > tried running os.listdir(fileroot) i got the error. The string i > passed to os.listdir is the string i keyed inside fileroot under the > raw_input? You are passing a string to os.listdir. (you call that string fileroot). There is probably something wrong with that string. In principle, it doesn't matter where you got the string from - with raw_input() or by hard-coding the string. repr(fileroot) is almost certainly not "C:\" -- that is not a valid string literal. What did you enter exactly? -- Thomas From usernet at ilthio.net Sun Aug 8 08:15:29 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 12:15:29 +0000 (UTC) Subject: cscope like source code navigation for python code References: Message-ID: On 2010-08-08, Gelonida wrote: > On 08/08/2010 01:42 AM, Tim Harig wrote: >> On 2010-08-07, Gelonida wrote: >>> I'm using g?vim and its c-scope plugin for browsing C-code. >>> What would be a good way of navigating larger python projects with vim? >> >> ctags: >> http://ctags.sourceforge.net/ > > I prefereed vim/cscope for navigation, but guess after some learning > with vim/ctags I should get along quite well. It takes a little getting used to because it isn't as intuative as cscope's visual navigation; but, it is quite efficient once you have internalized it. It also has a portability advantage. ctags works with all versions of vi so you are not just limited to vim. Excuberant ctags works with most langauges that you are likely to be working in and many tools are available that produce ctags files for other languages. > My biggest problem with is, that ctrl-] doesn't ask you to which tag to > jump in case multiple options exist. It usually jumps to the most relavant tag. If necessary, you can specify exactly which tag you need with ":tag". From thomas at jollans.com Sun Aug 8 08:17:26 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 14:17:26 +0200 Subject: os.unlink on Windows In-Reply-To: References: Message-ID: <4C5EA056.1080602@jollans.com> On 08/08/2010 01:41 PM, Shambhu wrote: > Hi Thomas, > > I checked, file is present. Here is my sample script: > import os > filename = "C:\SHAMBHU\tmp\text_delete.txt" > os.unlink(filename) > > File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\ > \tmp\\text_delete.txt" is not (with extra backslash in path which is > added by os.unlink). os.unlink isn't adding anything. The extra backslashes you're seeing are being added when DISPLAYING the file name string. That's because Python uses backslashes to escape special characters in strings. >>> print("C:\\SHAMBHU\\tmp\\text_delete.txt") C:\SHAMBHU\tmp\text_delete.txt >>> print("C:\SHAMBHU\tmp\text_delete.txt") C:\SHAMBHU mp ext_delete.txt >>> '\t' is the TAB character. What is the error message, exactly, when you run the above script? Since you didn't escape the backslashes properly, I expect it refers to 'C:\\SHAMBHU\tmp\text_delet.txt' -- The first backslash is still a backslash -- it gets doubled when printed as a string (but NOT when passed to the OS by unlink), but the second and third ones were used to create TAB characters. Probably. Either always double backslashes in paths, or use raw string literals (r"C:\SHAMBHU\tmp\text_delete.txt" -- keeps the \s) (or use forward slashes in paths...) > > Regards. > Shambhu. > > > > On Aug 7, 4:46 pm, Thomas Jollans wrote: >> On 08/07/2010 01:10 PM, Shambhu Sharma wrote: >> >>> Hi, >> >>> I am new to Python. I was trying to use os.unlink function in >>> windows. But i am getting error: >>> OSError: [Errno 2] No such file or directory: >>> 'C:\\SHAMBHU\\tmp\\text_delete.txt' >> >>> Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But >>> os.unlink is adding extra backslash with pathname. >> >> No, it isn't. What you're seeing is simply the repr() of the path name >> string. >> >>>>> p = r'C:\SHAMBHU\tmp\text_delete.txt' >>>>> p >> >> 'C:\\SHAMBHU\\tmp\\text_delete.txt'>>> print(p) >> >> C:\SHAMBHU\tmp\text_delete.txt >> >> >> > >> I think the file you're trying to delete probably doesn't exist. Why >> don't you double-check that. >> >>> I tried with >>> Python2.5 and Python3.1 but got same error. >>> Please suggest how to remove this error. >> >>> -- >>> If linux doesn't have a solution, then u have a wrong problem. >> >>> Shambhu Kumar Sharma >>> 91-98864 91913 >> >> > From blur959 at hotmail.com Sun Aug 8 08:35:52 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 05:35:52 -0700 (PDT) Subject: Renaming of files in OS directory References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: <509a751d-6c82-4129-b3de-85aab9f69ef1@v6g2000prd.googlegroups.com> On Aug 8, 7:45?pm, Thomas Jollans wrote: > On 08/08/2010 12:23 PM, blur959 wrote: > > > > > On Aug 8, 6:05 pm, Thomas Jollans wrote: > >> On 08/08/2010 10:35 AM, blur959 wrote: > > >>> On Aug 8, 4:15 pm, Chris Rebert wrote: > >>>> On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: > >>>>> Hi, all, I am writing a program that renames files inside OS > >>>>> directories the user provides. I am at the early stage of writing it > >>>>> and I encountered some problems. > > >>>>> Below is my code. There is an error i received when i run this code. > >>>>> The error is, WindowsError: [Error 123] The filename, directory name, > >>>>> or volume label syntax is incorrect. > > >>>> Well, what directory did you input? Apparently it wasn't a valid or extant one. > > >>>> Cheers, > >>>> Chris > >>>> --http://blog.rebertia.com > > >>> I input for e.g, "C:" it works, basically, if i input a hard code > >>> string inside os.listdir it works, but if i stored the string that the > >>> user keyed inside a variable and run os.listdir with the variable, > >>> there is that error. But inputing hard code string inside os.listdir > >>> isn't what I want when I am writing this program. > > >> You didn't answert the question. What is the actual string you pass to > >> os.listdir after you got it from the user? You could > >> ? ? print repr(fileroot) > >> to find out. > > >> My tentative guess is that maybe Windows doesn't like newlines in file > >> names (I know UNIX allows them, but they're still usually a bad idea) > >> and maybe you string ends with a newline. > > > I do not get what you mean. The string i passed in is stored inside > > the variable fileroot. In the case I tested, i inputed the string "C: > > \" inside the raw_input and stored it inside fileroot, I tried > > printing repr(fileroot) and it gave me "C:\" as the result and when i > > tried running os.listdir(fileroot) i got the error. The string i > > passed to os.listdir is the string i keyed inside fileroot under the > > raw_input? > > You are passing a string to os.listdir. (you call that string fileroot). > There is probably something wrong with that string. In principle, it > doesn't matter where you got the string from - with raw_input() or by > hard-coding the string. > > repr(fileroot) is almost certainly not "C:\" -- that is not a valid > string literal. > > What did you enter exactly? > > -- Thomas Sorry, This is my first time using the os commands in python, Ok, firstly, I entered "C:\" inside raw_input and stored it inside fileroot. When i print repr(fileroot), my result was '"C:\\"' . And when I run os.listdir with fileroot, I got that error. I typed my os.listdir code like this: os.listdir(fileroot) I attached my code for reference, thanks again! import os, glob def fileDirectory(): # Ask user for file directory input fileroot = raw_input("Input") print repr(fileroot) #Returns a list with all the files inside the file root directory( The error occurs here ) os.listdir(fileroot) fileDirectory() From thomas at jollans.com Sun Aug 8 08:40:05 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 14:40:05 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> Message-ID: <4C5EA5A5.90107@jollans.com> On 08/08/2010 01:41 PM, ????? wrote: > I was so dizzy and confused yesterday that i forgot to metnion that > not only i need removal of php openign and closing tags but whaevers > data lurks inside those tags as well ebcause now with the 'counter.py' > script i wrote the html fiels would open ftm there and substitute the > tempalte variabels like %(counter)d I could just hand you a solution, but I'll be a bit of a bastard and just give you some hints. You could use regular expressions. If you know regular expressions, it's relatively trivial - but I doubt you know regexp. You could also repeatedly find the next occurrence of first a start tag, then an end tag, using either str.find or str.split, and build up a version of the file without PHP yourself. > Also before the > > > > > of every html file afetr removing the tags this line must be > inserted(this holds the template variable) that 'counter.py' uses to > produce data > >

??????? ??????????: %(counter)d >

This problem is truly trivial. I know you can do it yourself, or at least give it a good shot, and ask again when you hit a serious roadblock. If I may comment on your HTML: you forgot to close your
and tags. Close them! Also, both (CENTER and FONT) have been deprecated since HTML 4.0 -- you should consider using CSS for these tasks instead. Also, this line does not look like a heading, so H4 is hardly fitting. > > After making this modifications then i can trst the script to a COPY > of the original data in my pc. It would be nice if you re-read your posts before sending and tried to iron out some of more careless spelling mistakes. Maybe you are doing your best to post in good English -- it isn't bad and I realize this is neither your native language nor alphabet, in which case I apologize. The fact of the matter is: I originally interpreter "trst" as "trust", which made no sense whatsoever. > > *In my pc i run Windows 7 while remote web hosting setup uses Linux > Servers. > *That wont be a problem right? Nah. From wolftracks at invalid.com Sun Aug 8 09:03:48 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 08 Aug 2010 06:03:48 -0700 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On 8/8/2010 4:08 AM, David Cournapeau wrote: ... >> python-Numpy-1.2.0. No scipy anything. Well, this is interesting. I just >> noticed Martin v. Loewis on the Python 2.5 entry. That's you, right? > > You are conflating so many issues at the same time, it is very > difficult to follow what you are doing. > > Concerning the numpy error: you installed a version of scipy which > requires a more recent version of numpy than the one you have. More > concretely, NumpyTest has disappeared since 1.3.0. Unless you have a > good reason not to, I strongly suggest to just use the last released > versions of numpy and scipy (1.4.1 and 0.8.0 respectively). > > Note also that Enthought Python Distribution exists to exactly avoid > those issues - they do the packaging hard word so that you don't have > to. > > But none of this has anything to do with one character change or portability, > > cheers, > > David Believe me I had no intent of expanding this thread beyond looking for a straight and simple insight to Python distribution (portability, whatever) and how to get my partner squared away. The general issue seems to drifted off on its own accord. I find generally that once I've had to post five times on a topic, and haven't gotten a satisfactory answer, I'm not going to get one. Yes, you are quite correct about numpy, but for reasons which I have no plans to explain, I want my partner on the same version of numpy as myself. I now have the answer I need, and I do not care one more wit about a one character change. I'm done here. From thomas at jollans.com Sun Aug 8 09:13:25 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 15:13:25 +0200 Subject: Renaming of files in OS directory In-Reply-To: <509a751d-6c82-4129-b3de-85aab9f69ef1@v6g2000prd.googlegroups.com> References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> <509a751d-6c82-4129-b3de-85aab9f69ef1@v6g2000prd.googlegroups.com> Message-ID: <4C5EAD75.8000805@jollans.com> On 08/08/2010 02:35 PM, blur959 wrote: > Sorry, This is my first time using the os commands in python, Ok, > firstly, I entered "C:\" inside raw_input and stored it inside > fileroot. When i print repr(fileroot), my result was '"C:\\"' . And > when I run os.listdir with fileroot, I got that error. I typed my > os.listdir code like this: os.listdir(fileroot) > > I attached my code for reference, thanks again! Okay, maybe you've already understood the problem now, but in case you haven't: '"C:\\"' is no valid file name. The quotes ("") are part of what you're passing to the OS here, which you don't want. Just enter the file name without quotes. (or, if you really want quoting for some reason, you could manually strip the quotes, or use the shlex module. > > > import os, glob > > def fileDirectory(): > # Ask user for file directory input > fileroot = raw_input("Input") > print repr(fileroot) > > > #Returns a list with all the files inside the file root > directory( The error occurs here ) > os.listdir(fileroot) > > > fileDirectory() From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 09:29:43 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Aug 2010 13:29:43 GMT Subject: os.unlink on Windows References: Message-ID: <4c5eb146$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 04:41:14 -0700, Shambhu wrote: > Hi Thomas, > > I checked, file is present. Here is my sample script: > import os > filename = "C:\SHAMBHU\tmp\text_delete.txt" Did you intend to provide a filename with two TAB characters in it? c colon backslash s h a m b u TAB m p TAB e x t underscore d e l e t e dot t x t > File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\ > \tmp\\text_delete.txt" is not (with extra backslash in path which is > added by os.unlink). os.unlink does add any extra backslashes. You are misinterpreting what you are seeing. -- Steven From costin.gament at gmail.com Sun Aug 8 09:32:19 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 16:32:19 +0300 Subject: Class initialization Message-ID: Hi there. I'm kind of a beginner with Python (and programming in general). My problem is with initializing a class. Let's say I've defined it like this: class foo: a = 0 b = 0 and later I'm trying to initialize two different classes like this: c1 = foo() c2 = foo() The problem I have is that c1 and c2 tend to point to the same instance, like a weird c-like pointer. Please tell me, what am I doing wrong? Thank you, From gslindstrom at gmail.com Sun Aug 8 09:40:48 2010 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sun, 8 Aug 2010 08:40:48 -0500 Subject: # of Months between two dates Message-ID: I work for a company that processes claims for the health care industry (Novasys Health, recently purchased by Centene Corp). My current assignment has me writing a routine to compute insurance premiums. One of the requirements is to determine how many months a policy has been in effect. The datetime module will give me the number of days but, with months having different lengths, that does not do me much good. I've looked in the calendar library but didn't see anything there, either. I've written a function to return the months between date1 and date2 but I'd like to know if anyone is aware of anything in the standard library to do the same? For bonus points, does anyone know if postgres can do the same (we use a lot of date/time funcitons in postgres, already, but didn't see this problem addressed). On a side note; since I'm dealing with money (USD), I decided to use the decimal module for all computations. It's not a big difference -- unless you've seen the movie "Office Space" :-) -- but it sure is nice. Especially being able to easily round values to the nearest cent. You just have to love the standard library. Thanks for your help, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From blur959 at hotmail.com Sun Aug 8 09:43:52 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 06:43:52 -0700 (PDT) Subject: Renaming of files in OS directory References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> <509a751d-6c82-4129-b3de-85aab9f69ef1@v6g2000prd.googlegroups.com> Message-ID: <2126c6f2-762b-47e6-b50e-6cb2c956c68d@l25g2000prn.googlegroups.com> On Aug 8, 9:13?pm, Thomas Jollans wrote: > On 08/08/2010 02:35 PM, blur959 wrote: > > > Sorry, This is my first time using the os commands in python, Ok, > > firstly, I entered "C:\" inside raw_input and stored it inside > > fileroot. When i print repr(fileroot), my result was '"C:\\"' . And > > when I run os.listdir with fileroot, I got that error. I typed my > > os.listdir code like this: os.listdir(fileroot) > > > I attached my code for reference, thanks again! > > Okay, maybe you've already understood the problem now, but in case you > haven't: > '"C:\\"' is no valid file name. The quotes ("") are part of what you're > passing to the OS here, which you don't want. Just enter the file name > without quotes. (or, if you really want quoting for some reason, you > could manually strip the quotes, or use the shlex module. > > > > > import os, glob > > > def fileDirectory(): > > ? ? # Ask user for file directory input > > ? ? fileroot = raw_input("Input") > > ? ? print repr(fileroot) > > > ? ? #Returns a list with all the files inside the file root > > directory( The error occurs here ) > > ? ? os.listdir(fileroot) > > > fileDirectory() > > okay i got it already thanks alot man! Appreciate it! From gelonida at gmail.com Sun Aug 8 09:49:26 2010 From: gelonida at gmail.com (Gelonida) Date: Sun, 08 Aug 2010 15:49:26 +0200 Subject: cscope like source code navigation for python code In-Reply-To: <4C5E9493.6060101@jollans.com> References: <4C5E9493.6060101@jollans.com> Message-ID: Hi Thomas, On 08/08/2010 01:27 PM, Thomas Jollans wrote: > On 08/07/2010 07:53 PM, Gelonida wrote: >> Hi, >> >> I'm using g?vim and its c-scope plugin for browsing C-code. >> >> What would be a good way of navigating larger python projects with vim? >> >> >> thanks for any suggestions >> > > > http://pypi.python.org/pypi/pycscope/0.2 > > Looks like an option Yes it looks like an option. Unfortunately it is from 2006 and reported (and aborted) on a syntax error of one of my files. My file is running and passes pylint / pychecker. So I'm afraid, that the code might be outdated. I'll investigte perhaps a little more. From downaold at gmail.com Sun Aug 8 09:59:56 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 8 Aug 2010 15:59:56 +0200 Subject: Class initialization In-Reply-To: References: Message-ID: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> On Aug 8, 2010, at 3:32 PM, Costin Gament wrote: > Hi there. > I'm kind of a beginner with Python (and programming in general). My > problem is with initializing a class. Let's say I've defined it like > this: > > class foo: > a = 0 > b = 0 > > and later I'm trying to initialize two different classes like this: > c1 = foo() > c2 = foo() > > The problem I have is that c1 and c2 tend to point to the same > instance, like a weird c-like pointer. Please tell me, what am I doing > wrong? Your problem probably is that a and b are class variables; c1 and c2 are different objects (in your terminology: they point to different instances). See http://docs.python.org/tutorial/classes.html#class-objects for more info. Cheers, Roald From nikos.the.gr33k at gmail.com Sun Aug 8 10:06:20 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 07:06:20 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> Message-ID: <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> On 8 ???, 15:40, Thomas Jollans wrote: > On 08/08/2010 01:41 PM, ????? wrote: > > > I was so dizzy and confused yesterday that i forgot to metnion that > > not only i need removal of php openign and closing tags but whaevers > > data lurks inside those tags as well ebcause now with the 'counter.py' > > script i wrote the html fiels would open ftm there and substitute the > > tempalte variabels like %(counter)d > > I could just hand you a solution, but I'll be a bit of a bastard and > just give you some hints. > > You could use regular expressions. If you know regular expressions, it's > relatively trivial - but I doubt you know regexp. Here is the code with some try-and-fail modification i made, still non- working based on your hints: ========================================================== id = 0 # unique page_id for currdir, files, dirs in os.walk('varsa'): for f in files: if f.endswith('php'): # get abs path to filename src_f = join(currdir, f) # open php src file print 'reading from %s' % src_f f = open(src_f, 'r') src_data = f.read() # read contents of PHP file f.close() # replace tags print 'replacing php tags and contents within' src_data = src_data.replace(r'', '') # the dot matches any character i hope! no matter how many of them?!? # add ID print 'adding unique page_id' src_data = ( '' % id ) + src_data id += 1 # add template variables print 'adding counter template variable' src_data = src_data + '''

??????? ??????????: %(counter)d

''' # i can think of this but the above line must be above NOT after but how to right that?!? # rename old php file to new with .html extension src_file = src_file.replace('.php', '.html') # open newly created html file for inserting data print 'writing to %s' % dest_f dest_f = open(src_f, 'w') dest_f.write(src_data) # write contents dest_f.close() This is the best i can do. Sorry for any typos i might made. Please shed some LIGHT! From costin.gament at gmail.com Sun Aug 8 10:14:08 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 17:14:08 +0300 Subject: Class initialization In-Reply-To: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: Thank you for your answer, but it seems I didn't make myself clear. Take the code: class foo: a = 0 b = 0 c1 = foo() c1.a = 5 c2 = foo() print c2.a 5 Somehow, when I try to acces the 'a' variable in c2 it has the same value as the 'a' variable in c1. Am I missing something? On Sun, Aug 8, 2010 at 4:59 PM, Roald de Vries wrote: > > Your problem probably is that a and b are class variables; c1 and c2 are > different objects (in your terminology: they point to different instances). > > See http://docs.python.org/tutorial/classes.html#class-objects for more > info. > > Cheers, Roald > > -- > http://mail.python.org/mailman/listinfo/python-list > From steveo at syslang.net Sun Aug 8 10:21:45 2010 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 08 Aug 2010 10:21:45 -0400 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <3cc2a461-19f0-4aaf-9305-dde36fa2656c@v6g2000prd.googlegroups.com> References: <3cc2a461-19f0-4aaf-9305-dde36fa2656c@v6g2000prd.googlegroups.com> Message-ID: <4C5EBD79.80607@syslang.net> On 08/07/10 23:57, quoth Miki: > On Aug 7, 7:42 pm, "Steven W. Orr" wrote: >> I'm ok in python but I haven't done too much with web pages. I have a web page >> that is hand written in html that has about 1000 entries in a table and I want >> to convert the table from entries like this >> >>
>> >> >> >> >> >> >> >> to >> >> SomePythonCall('Some Date String', >> 'SomeTag', >> 'localSubdir', >> "http://www.example.com/remote/path/something.html", >> 'Click', >> 'Some Comment') >> >> Can someone tell me what I should look at to do this? Is mod_python where I >> should start or are there things that are better? > Have a look at http://www.crummy.com/software/BeautifulSoup/. Thanks. But what I'm not seeing is any example of how to make this allowed to generate the html at run time. I think I want to embed my python code into an html file. Beautiful soup seems to allow me to create a preprocessor which I could use through a Makefile to generate the html. I have the feeling I'm missing something. Or do I use this in conjunction with wsgi? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From downaold at gmail.com Sun Aug 8 10:38:34 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 8 Aug 2010 16:38:34 +0200 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: <446A31BC-2992-416D-B7B9-A846CB7AC09A@gmail.com> On Aug 8, 2010, at 4:14 PM, Costin Gament wrote: > Thank you for your answer, but it seems I didn't make myself clear. You could have been clearer in your first post, yeah. > Take the code: > class foo: > a = 0 > b = 0 > c1 = foo() > c1.a = 5 > c2 = foo() > print c2.a > 5 > > Somehow, when I try to acces the 'a' variable in c2 it has the same > value as the 'a' variable in c1. Am I missing something? I can't reproduce this. Which version are you using? > On Sun, Aug 8, 2010 at 4:59 PM, Roald de Vries > wrote: >> >> Your problem probably is that a and b are class variables; And class variables are not instance variables. >> c1 and c2 are >> different objects (in your terminology: they point to different >> instances). I still suspect that this is the problem. In Python, classes are objects (instances of another class) too. In your class, you assign 0 to the variables foo.a and foo.b. >> See http://docs.python.org/tutorial/classes.html#class-objects for >> more >> info. So: > class foo: > a = 0 creates a class variable foo.a and set it to 0 > b = 0 creates a class variable foo.b and set it to 0 > c1 = foo() creates a new foo that can be referenced as c1 > c1.a = 5 creates an instance variable c1.a and set it to 5 > c2 = foo() creates a new foo that can be referenced as c2 > print c2.a there is no instance variable c2.a, so the class variable foo.a is referenced > 5 I get 0 here. Cheers, Roald From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 10:49:27 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Aug 2010 14:49:27 GMT Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: <4c5ec3f7$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 17:14:08 +0300, Costin Gament wrote: > Thank you for your answer, but it seems I didn't make myself clear. Take > the code: > class foo: > a = 0 > b = 0 > c1 = foo() > c1.a = 5 > c2 = foo() > print c2.a > 5 Incorrect. >>> class foo: ... a = 0 ... b = 0 ... >>> c1 = foo() >>> c1.a = 5 >>> c2 = foo() >>> print c2.a 0 -- Steven From costin.gament at gmail.com Sun Aug 8 10:57:38 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 17:57:38 +0300 Subject: Class initialization In-Reply-To: <4c5ec3f7$0$28663$c3e8da3@news.astraweb.com> References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> <4c5ec3f7$0$28663$c3e8da3@news.astraweb.com> Message-ID: Apparently, the code I've given here does, in fact, work. Still, I am encountering a similar problem in a much larger class (it is in a separate module, if that is any help). Also, the variable I am having trouble with is itself another class. I don't think it's appropriate to paste so much code in here, so if anybody has some knowledge about similar problems... On Sun, Aug 8, 2010 at 5:49 PM, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 17:14:08 +0300, Costin Gament wrote: > >> Thank you for your answer, but it seems I didn't make myself clear. Take >> the code: >> class foo: >> ? a = 0 >> ? b = 0 >> c1 = foo() >> c1.a = 5 >> c2 = foo() >> print c2.a >> 5 > > Incorrect. > >>>> class foo: > ... ? a = 0 > ... ? b = 0 > ... >>>> c1 = foo() >>>> c1.a = 5 >>>> c2 = foo() >>>> print c2.a > 0 > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > From thomas at jollans.com Sun Aug 8 10:59:34 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 16:59:34 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <4C5EC656.9070105@jollans.com> On 08/08/2010 04:06 PM, ????? wrote: > On 8 ???, 15:40, Thomas Jollans wrote: >> On 08/08/2010 01:41 PM, ????? wrote: >> >>> I was so dizzy and confused yesterday that i forgot to metnion that >>> not only i need removal of php openign and closing tags but whaevers >>> data lurks inside those tags as well ebcause now with the 'counter.py' >>> script i wrote the html fiels would open ftm there and substitute the >>> tempalte variabels like %(counter)d >> >> I could just hand you a solution, but I'll be a bit of a bastard and >> just give you some hints. >> >> You could use regular expressions. If you know regular expressions, it's >> relatively trivial - but I doubt you know regexp. > > Here is the code with some try-and-fail modification i made, still non- > working based on your hints: > ========================================================== > > id = 0 # unique page_id > > for currdir, files, dirs in os.walk('varsa'): > > for f in files: > > if f.endswith('php'): > > # get abs path to filename > src_f = join(currdir, f) > > # open php src file > print 'reading from %s' % src_f > f = open(src_f, 'r') > src_data = f.read() # read contents of PHP file > f.close() > > # replace tags > print 'replacing php tags and contents within' > src_data = src_data.replace(r'', '') # > the dot matches any character i hope! no matter how many of them?!? Two problems here: str.replace doesn't use regular expressions. You'll have to use the re module to use regexps. (the re.sub function to be precise) '.' matches a single character. Any character, but only one. '.*' matches as many characters as possible. This is not what you want, since it will match everything between the *first* . You want non-greedy matching. '.*?' is the same thing, without the greed. > > # add ID > print 'adding unique page_id' > src_data = ( '' % id ) + src_data > id += 1 > > # add template variables > print 'adding counter template variable' > src_data = src_data + '''

??????? > ??????????: %(counter)d

''' > # i can think of this but the above line must be above body> NOT after but how to right that?!? You will have to find the tag before inserting the string. str.find should help -- or you could use str.replace and replace the tag with you counter line, plus a new . > > # rename old php file to new with .html extension > src_file = src_file.replace('.php', '.html') > > # open newly created html file for inserting data > print 'writing to %s' % dest_f > dest_f = open(src_f, 'w') > dest_f.write(src_data) # write contents > dest_f.close() > > This is the best i can do. No it's not. You're just giving up too soon. From usernet at ilthio.net Sun Aug 8 11:01:53 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 15:01:53 +0000 (UTC) Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On 2010-08-08, Costin Gament wrote: > Thank you for your answer, but it seems I didn't make myself clear. > Take the code: > class foo: > a = 0 > b = 0 > c1 = foo() > c1.a = 5 > c2 = foo() > print c2.a > 5 > > Somehow, when I try to acces the 'a' variable in c2 it has the same > value as the 'a' variable in c1. Am I missing something? Others have told you that at a and b belong to the class object rather then to the instance objects. Perhaps this will demonstrate the difference: >>> class foo(): ... def __init__(self): ... self.a = 0 ... self.b = 0 ... >>> c1 = foo() >>> c1.a = 5 >>> c2 = foo() >>> print c2.a 0 >>> From albert at spenarnc.xs4all.nl Sun Aug 8 11:12:16 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 08 Aug 2010 15:12:16 GMT Subject: easy question on parsing python: "is not None" References: <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> Message-ID: In article <8c2uiuFg9bU1 at mid.individual.net>, Peter Pearson wrote: >On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: >[snip] >> I can imagine a case where you might want to compare a >> string with `is`: >> >> FORWARD = "forward" >> BACKWARD = "backward" >> >> ... >> >> def func(direction=FORWARD): >> if direction is FORWARD: >> ... >> elif direction is BACKWARD: >> ... >> else: >> ... >> >> in case you expect people to specifically use the constants >> you provided in the module. Here, the fact that FORWARD >> actually is the string "forward" might be considered an >> implementation detail. Using a string instead of an >> `object()` has the advantage that it makes usage in error >> messages easier. >> >> Actually, I've never seen such a use, as far as I remember. >> What do other people here think? Is the code above, which >> compares strings with `is`, bad style, and if yes, why? How >> would you write the code instead? > >Hey, that's a cute example, but . . . what a trap! Is it >possible to document the use-the-object-not-the-string requirement >loudly enough that people won't get caught? king = "This is just a string for denoting a chess object, \ if a field contains (a reference to) king, it means the piece \ is standing on that field" Even a fresh convert from the Java language would not insert the string instead of the name of the object. (In practive you want black kings and white kings to be different objects, probably.) > >-- >To email me, substitute nowhere->spamcop, invalid->net. -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From jhjaggars at gmail.com Sun Aug 8 11:13:00 2010 From: jhjaggars at gmail.com (Jesse Jaggars) Date: Sun, 8 Aug 2010 10:13:00 -0500 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On Sun, Aug 8, 2010 at 10:01 AM, Tim Harig wrote: > On 2010-08-08, Costin Gament wrote: >> Thank you for your answer, but it seems I didn't make myself clear. >> Take the code: >> class foo: >> ? a = 0 >> ? b = 0 >> c1 = foo() >> c1.a = 5 >> c2 = foo() >> print c2.a >> 5 >> >> Somehow, when I try to acces the 'a' variable in c2 it has the same >> value as the 'a' variable in c1. Am I missing something? > > Others have told you that at a and b belong to the class object rather then > to the instance objects. ?Perhaps this will demonstrate the difference: > >>>> class foo(): > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.a = 0 > ... ? ? ? ? ? ? self.b = 0 > ... >>>> c1 = foo() >>>> c1.a = 5 >>>> c2 = foo() >>>> print c2.a > 0 >>>> > -- > http://mail.python.org/mailman/listinfo/python-list > Is it possible that you are using a mutable class object? A common gotcha is to do something like this: >>> class foo(object): ... x = [] ... >>> a = foo() >>> b = foo() >>> a.x.append(123) >>> b.x [123] And expect b.x to be an empty list. From costin.gament at gmail.com Sun Aug 8 11:14:06 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 18:14:06 +0300 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: So you're saying I should just use __init__? Will that get me out of my predicament? No, I don't quite understand the difference between my exemple and using __init__, but I will read the docs about it. On Sun, Aug 8, 2010 at 6:01 PM, Tim Harig wrote: > > Others have told you that at a and b belong to the class object rather then > to the instance objects. ?Perhaps this will demonstrate the difference: > >>>> class foo(): > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.a = 0 > ... ? ? ? ? ? ? self.b = 0 > ... >>>> c1 = foo() >>>> c1.a = 5 >>>> c2 = foo() >>>> print c2.a > 0 >>>> From costin.gament at gmail.com Sun Aug 8 11:16:20 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 18:16:20 +0300 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: That looks just like my code. What's the problem? On Sun, Aug 8, 2010 at 6:13 PM, Jesse Jaggars wrote: > > Is it possible that you are using a mutable class object? A common > gotcha is to do something like this: > >>>> class foo(object): > ... ? x = [] > ... >>>> a = foo() >>>> b = foo() >>>> a.x.append(123) >>>> b.x > [123] > > And expect b.x to be an empty list. From knny.myer at gmail.com Sun Aug 8 11:28:06 2010 From: knny.myer at gmail.com (Kenny Meyer) Date: Sun, 8 Aug 2010 11:28:06 -0400 Subject: cscope like source code navigation for python code In-Reply-To: References: <4C5E9493.6060101@jollans.com> Message-ID: <20100808152806.GD10814@5732Z> Gelonida (gelonida at gmail.com) wrote: > Hi Thomas, > > On 08/08/2010 01:27 PM, Thomas Jollans wrote: > > On 08/07/2010 07:53 PM, Gelonida wrote: > >> Hi, > >> > >> I'm using g?vim and its c-scope plugin for browsing C-code. > >> > >> What would be a good way of navigating larger python projects with vim? > >> > >> > >> thanks for any suggestions > >> > > > > > > http://pypi.python.org/pypi/pycscope/0.2 > > > > Looks like an option > > Yes it looks like an option. > Unfortunately it is from 2006 and reported (and aborted) on a syntax > error of one of my files. > > My file is running and passes pylint / pychecker. > > So I'm afraid, that the code might be outdated. > I'll investigte perhaps a little more. I wonder if you have seen the new version: http://pypi.python.org/pypi/pycscope/0.3 -- Onward and upwards, .O. Kenny Meyer ..O :wq OOO -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: Digital signature URL: From usernet at ilthio.net Sun Aug 8 11:28:32 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 15:28:32 +0000 (UTC) Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On 2010-08-08, Costin Gament wrote: > So you're saying I should just use __init__? Will that get me out of > my predicament? > No, I don't quite understand the difference between my exemple and > using __init__, but I will read the docs about it. It is not so much using __init__() that makes the difference as it what scope the variables are assigned to. If you define them as you where, then the variables are associated with the class object itself. If the variable is a mutable type, and you change it in one instance, it actually changes it in the class object which means it also changes for all of the instances. I used the constructor because it gives me a reference to the newly created instance object "self". I then assign the variables to self, which assignes them to the newly created instance object. Then each instance has its own separate a and b variables that will not change when the variables are changed inside of another instance object. From costin.gament at gmail.com Sun Aug 8 11:45:53 2010 From: costin.gament at gmail.com (=?UTF-8?Q?Costin_Gamen=C8=9B?=) Date: Sun, 8 Aug 2010 18:45:53 +0300 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: Thanks a lot. I'll try give it a go and see if it helps. On Sun, Aug 8, 2010 at 6:28 PM, Tim Harig wrote: > It is not so much using __init__() that makes the difference as it what > scope the variables are assigned to. ?If you define them as you where, then > the variables are associated with the class object itself. ?If the variable > is a mutable type, and you change it in one instance, it actually changes > it in the class object which means it also changes for all of the > instances. > > I used the constructor because it gives me a reference to the newly created > instance object "self". ?I then assign the variables to self, which > assignes them to the newly created instance object. ?Then each instance has > its own separate a and b variables that will not change when the variables > are changed inside of another instance object. From usernet at ilthio.net Sun Aug 8 11:49:32 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 15:49:32 +0000 (UTC) Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On 2010-08-08, Tim Harig wrote: > On 2010-08-08, Costin Gament wrote: >> So you're saying I should just use __init__? Will that get me out of >> my predicament? >> No, I don't quite understand the difference between my exemple and >> using __init__, but I will read the docs about it. > > It is not so much using __init__() that makes the difference as it what > scope the variables are assigned to. If you define them as you where, then > the variables are associated with the class object itself. If the variable > is a mutable type, and you change it in one instance, it actually changes > it in the class object which means it also changes for all of the > instances. > > I used the constructor because it gives me a reference to the newly created > instance object "self". I then assign the variables to self, which > assignes them to the newly created instance object. Then each instance has > its own separate a and b variables that will not change when the variables > are changed inside of another instance object. Maybe I can make that a little clearer yet. When you define a class in python you actually create a class object. This object is basically used as a template to create instance objects. When you define a variable attached to the class object that is mutable, the instance objects receive the exact same reference that was given to the instance object. Since it is mutable, any changes made using that reference will affect all of the instances that also point to that reference. You wouldn't have seen this effect using your simplified examle because number are immutable objects. When you change the value for one of the instance objects, it receives a new reference, rather then making the change in place. The other instances do not reflect this change because their variables still point back to the original reference given to the class. From steve at holdenweb.com Sun Aug 8 11:51:58 2010 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Aug 2010 11:51:58 -0400 Subject: DjangoCon 2010 Message-ID: <4C5ED29E.90403@holdenweb.com> This is a reminder that DjangoCon US 2010 is now under a month away! The third such conference, DjangoCon returns this year to the green Doubletree Hotel in Portland, OR from September 7-9, with a three day sprint hosted by Urban Airship from September 10-12. The program schedule is at http://djangocon.us/schedule/ and you can register at http://djangocon.us/tickets/ The conference price for hotel accommodation is guaranteed only until August 13, so if you plan to attend you should register straight away. -- Steve Holden +1 571 484 6266 +1 800 494 3119 DjangoCon US September 7-9, 2010 http://djangocon.us/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ From usernet at ilthio.net Sun Aug 8 11:55:09 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 15:55:09 +0000 (UTC) Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On 2010-08-08, Tim Harig wrote: > On 2010-08-08, Tim Harig wrote: >> On 2010-08-08, Costin Gament wrote: >>> So you're saying I should just use __init__? Will that get me out of >>> my predicament? >>> No, I don't quite understand the difference between my exemple and >>> using __init__, but I will read the docs about it. >> >> It is not so much using __init__() that makes the difference as it what >> scope the variables are assigned to. If you define them as you where, then >> the variables are associated with the class object itself. If the variable >> is a mutable type, and you change it in one instance, it actually changes >> it in the class object which means it also changes for all of the >> instances. >> >> I used the constructor because it gives me a reference to the newly created >> instance object "self". I then assign the variables to self, which >> assignes them to the newly created instance object. Then each instance has >> its own separate a and b variables that will not change when the variables >> are changed inside of another instance object. > > Maybe I can make that a little clearer yet. When you define a class in > python you actually create a class object. This object is basically used > as a template to create instance objects. When you define a variable > attached to the class object that is mutable, the instance objects receive > the exact same reference that was given to the instance object. Since it > is mutable, any changes made using that reference will affect all of the > instances that also point to that reference. You wouldn't have seen this > effect using your simplified examle because number are immutable objects. > When you change the value for one of the instance objects, it receives a > new reference, rather then making the change in place. The other instances > do not reflect this change because their variables still point back to the > original reference given to the class. And to complete that thought, when you assign variables directly to the instance, as I did using the constructor's reference to self, each instance receives a brand new reference that is not shared among any of the other instances. From wolftracks at invalid.com Sun Aug 8 12:16:22 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 08 Aug 2010 09:16:22 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? Message-ID: See Subject. I use matplotlib, scipy, numpy and possibly one other module. If I go to the control panel, I only see numpy listed. Why? I use a search and find only numpy and Python itself. How can matplotlib and scipy be uninstalled? From aahz at pythoncraft.com Sun Aug 8 12:24:39 2010 From: aahz at pythoncraft.com (Aahz) Date: 8 Aug 2010 09:24:39 -0700 Subject: suitable py2app. References: <744e466d-40c8-4a20-97cc-c8973aa369a9@c38g2000vba.googlegroups.com> Message-ID: In article <744e466d-40c8-4a20-97cc-c8973aa369a9 at c38g2000vba.googlegroups.com>, ata.jaf wrote: > >I'm looking for a suitable tutorial for "py2app". I googled it but >couldn't find anything. Can you help me please? What did you google for? "py2app tutorial" finds lots of hits. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From breamoreboy at yahoo.co.uk Sun Aug 8 12:51:31 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 08 Aug 2010 17:51:31 +0100 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On 08/08/2010 17:16, W. eWatson wrote: > See Subject. I use matplotlib, scipy, numpy and possibly one other > module. If I go to the control panel, I only see numpy listed. Why? I > use a search and find only numpy and Python itself. How can matplotlib > and scipy be uninstalled? Have you heard of google? Mark Lawrence. From benjamin.kaplan at case.edu Sun Aug 8 12:57:59 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 8 Aug 2010 09:57:59 -0700 Subject: Class initialization In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 6:32 AM, Costin Gament wrote: > > Hi there. > I'm kind of a beginner with Python (and programming in general). My > problem is with initializing a class. Let's say I've defined it like > this: > > class foo: > ? a = 0 > ? b = 0 > > and later I'm trying to initialize two different classes like this: > c1 = foo() > c2 = foo() > > The problem I have is that c1 and c2 tend to point to the same > instance, like a weird c-like pointer. Please tell me, what am I doing > wrong? > > Thank you, Python is not C++ or Java. Don't expect it to behave like them. In Python, everything you declare in the class namespace is in the *class* namespace. Since functions are objects too, this works out rather nicely for the most part. Where it doesn't work is when you use mutable variables. Here's the example you wanted to give: class Foo(object): a = [] b= [] Unlike Java or C++, classes are objects too. That leads to one of the neat tricks you can do with Python. The code above is exactly the same thing as this Foo = type("Foo",object, {}) #that dictionary will become Foo's list of attributes Foo.a = [] Foo.b = [] Now, when you call f1 = Foo(), it creates a new object. But here's what happens when you call f1.a.append(1) : * First, Python will look in the attributes of f1 for a. But f1 doesn't have an attribute "a". * So it starts looking up the classes in the inheritance tree. It looks at Foo and finds that Foo does have an attribute "a", so it grabs that. * Then, it looks up the attribute "append" on the a attribute (which is a list), and calls that with the arguments Foo.a and 1. * When f2 = Foo() goes looking for a, it finds the exact same object- Foo.a. It doesn't have its own copy, If you want an object to have its own copy of the variable, you have to create the new copy when the object is created, not when the class is created. That's why you'll see this in most Python programs : class Foo(object) : def __init__(self) : #self is the new object that was just created. #now here we'll assign the attributes on the new object, instead of the class. self.a = [] self.b = [] From torriem at gmail.com Sun Aug 8 13:00:53 2010 From: torriem at gmail.com (Michael Torrie) Date: Sun, 08 Aug 2010 11:00:53 -0600 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: <4C5EE2C5.6050506@gmail.com> On 08/08/2010 10:16 AM, W. eWatson wrote: > See Subject. I use matplotlib, scipy, numpy and possibly one other > module. If I go to the control panel, I only see numpy listed. Why? I > use a search and find only numpy and Python itself. How can matplotlib > and scipy be uninstalled? The best way is probably to find the folders in site-packages that contain these modules and simply delete them. They will be self-contained in folders, so it should be a pretty clean delete. Or you could try just installing the versions you want on top of the existing versions. This should work, even for a downgrade. From drobinow at gmail.com Sun Aug 8 13:21:55 2010 From: drobinow at gmail.com (David Robinow) Date: Sun, 8 Aug 2010 13:21:55 -0400 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence wrote: > On 08/08/2010 17:16, W. eWatson wrote: >> >> See Subject. I use matplotlib, scipy, numpy and possibly one other >> module. If I go to the control panel, I only see numpy listed. Why? I >> use a search and find only numpy and Python itself. How can matplotlib >> and scipy be uninstalled? > > Have you heard of google? google is not relevant to this issue. This group is the correct forum. I'm not sure what the answer to the OP's problem is. If you no longer wish to use these modules I suggest doing nothing. No harm will result. If you want to upgrade just install the new version. If that doesn't work, file a bug report. From hunguponcontent at gmail.com Sun Aug 8 13:24:34 2010 From: hunguponcontent at gmail.com (Default User) Date: Sun, 8 Aug 2010 12:24:34 -0500 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> Message-ID: Not to prolong a good "food fight", but IIRC, many years ago in QBasic, one could choose OPTION BASE 0 or OPTION BASE 1 to make arrays start with element [0] or element [1], respectively. Could such a feature be added to Python without significantly bloating the interpreter? Then, if starting with [0] "works for you", nothing really changes. And if starting with [1] "works for you", then you are not made to feel like a second-class citizen, and about as welcome as a dimwit at the Mensa meeting. Isn't Python supposed to be simple and accessible, and therefore fun? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstrickler at gmail.com Sun Aug 8 13:29:16 2010 From: jstrickler at gmail.com (John S) Date: Sun, 8 Aug 2010 10:29:16 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <2b1da9fc-5c13-4301-8d0d-322eeac715ee@d17g2000yqb.googlegroups.com> On Aug 8, 10:59?am, Thomas Jollans wrote: > On 08/08/2010 04:06 PM, ????? wrote: > > > > > > > On 8 ???, 15:40, Thomas Jollans wrote: > >> On 08/08/2010 01:41 PM, ????? wrote: > > >>> I was so dizzy and confused yesterday that i forgot to metnion that > >>> not only i need removal of php openign and closing tags but whaevers > >>> data lurks inside those tags as well ebcause now with the 'counter.py' > >>> script i wrote the html fiels would open ftm there and substitute the > >>> tempalte variabels like %(counter)d > > >> I could just hand you a solution, but I'll be a bit of a bastard and > >> just give you some hints. > > >> You could use regular expressions. If you know regular expressions, it's > >> relatively trivial - but I doubt you know regexp. > > > Here is the code with some try-and-fail modification i made, still non- > > working based on your hints: > > ========================================================== > > > id = 0 ?# unique page_id > > > for currdir, files, dirs in os.walk('varsa'): > > > ? ? for f in files: > > > ? ? ? ? if f.endswith('php'): > > > ? ? ? ? ? ? # get abs path to filename > > ? ? ? ? ? ? src_f = join(currdir, f) > > > ? ? ? ? ? ? # open php src file > > ? ? ? ? ? ? print 'reading from %s' % src_f > > ? ? ? ? ? ? f = open(src_f, 'r') > > ? ? ? ? ? ? src_data = f.read() ? ? ? ? # read contents of PHP file > > ? ? ? ? ? ? f.close() > > > ? ? ? ? ? ? # replace tags > > ? ? ? ? ? ? print 'replacing php tags and contents within' > > ? ? ? ? ? ? src_data = src_data.replace(r'', '') ? ? ? ? ? ? # > > the dot matches any character i hope! no matter how many of them?!? > > Two problems here: > > str.replace doesn't use regular expressions. You'll have to use the re > module to use regexps. (the re.sub function to be precise) > > '.' ?matches a single character. Any character, but only one. > '.*' matches as many characters as possible. This is not what you want, > since it will match everything between the *first* . > You want non-greedy matching. > > '.*?' is the same thing, without the greed. > > > > > ? ? ? ? ? ? # add ID > > ? ? ? ? ? ? print 'adding unique page_id' > > ? ? ? ? ? ? src_data = ( '' % id ) + src_data > > ? ? ? ? ? ? id += 1 > > > ? ? ? ? ? ? # add template variables > > ? ? ? ? ? ? print 'adding counter template variable' > > ? ? ? ? ? ? src_data = src_data + '''

??????? > > ??????????: %(counter)d

''' > > ? ? ? ? ? ? # i can think of this but the above line must be above > body> NOT after but how to right that?!? > > You will have to find the tag before inserting the string. > str.find should help -- or you could use str.replace and replace the > tag with you counter line, plus a new . > > > > > ? ? ? ? ? ? # rename old php file to new with .html extension > > ? ? ? ? ? ? src_file = src_file.replace('.php', '.html') > > > ? ? ? ? ? ? # open newly created html file for inserting data > > ? ? ? ? ? ? print 'writing to %s' % dest_f > > ? ? ? ? ? ? dest_f = open(src_f, 'w') > > ? ? ? ? ? ? dest_f.write(src_data) ? ? ?# write contents > > ? ? ? ? ? ? dest_f.close() > > > This is the best i can do. > > No it's not. You're just giving up too soon. When replacing text in an HTML document with re.sub, you want to use the re.S (singleline) option; otherwise your pattern won't match when the opening tag is on one line and the closing is on another. From joel.goldstick at columbuswebmakers.com Sun Aug 8 13:31:21 2010 From: joel.goldstick at columbuswebmakers.com (Joel Goldstick) Date: Sun, 08 Aug 2010 13:31:21 -0400 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <4C5EE9E9.10906@columbuswebmakers.com> ? wrote: > Hello dear Pythoneers, > > I have over 500 .php web pages in various subfolders under 'data' > folder that i have to rename to .html and and ditch the '' > tages from within and also insert a very first line of > where id must be an identification unique number of every page for > counter tracking purposes. ONly pure html code must be left. > > I before find otu Python used php and now iam switching to templates + > python solution so i ahve to change each and every page. > > I don't know how to handle such a big data replacing problem and > cannot play with fire because those 500 pages are my cleints pages and > data of those filesjust cannot be messes up. > > Can you provide to me a script please that is able of performing an > automatic way of such a page content replacing? > > Thanks a million! This is quite a vague description of the file contents. But, for a completely different approach, how about using a browser and doing view source, then saving the html that was generated. This will contain no php code, but it will contain the results of whatever the php was doing. If you don't have time to do this manually, look into wget or curl, which will do the job in a program environment. The discussion so far has dealt with stripping php, and leaving the html. But the html must have embeded in it. Or, there could be long fragments of html which are constructed by php and then echo'ed. Joel Goldstick From thomas at jollybox.de Sun Aug 8 13:33:34 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 8 Aug 2010 19:33:34 +0200 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <4C5E1991.9020401@syslang.net> References: <4C5E1991.9020401@syslang.net> Message-ID: <201008081933.34614.thomas@jollybox.de> On Sunday 08 August 2010 04:42:25 Steven W. Orr wrote: > I'm ok in python but I haven't done too much with web pages. I have a web > page that is hand written in html that has about 1000 entries in a table > and I want to convert the table from entries like this > >
> > > > > > > > to > > SomePythonCall('Some Date String', > 'SomeTag', > 'localSubdir', > "http://www.example.com/remote/path/something.html", > 'Click', > 'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? I'm a bit confused about what you're actually asking. If you have a long, HTML file you want to convert to something else (like Python code...), then BeautifulSoup will help you do that - you can use it to parse the original file, and thus make it easier to do the conversion. If your question was "how do I use Python to create web sites": You don't embed Python in HTML. I doubt anybody does this seriously -- Python (with indentation-based scoping) is less well-suited for this than PHP or Ruby, and it's better to keep logic and presentation separate anyway. "The" standard for using Python on the web is WSGI -- it's a very simple, low- level interface between Python and the web server. There are a number of higher-level web frameworks that you might want to look at if your project is sufficiently complex. [1] -- Thomas [1] http://wiki.python.org/moin/WebFrameworks From joel.goldstick at columbuswebmakers.com Sun Aug 8 13:36:28 2010 From: joel.goldstick at columbuswebmakers.com (Joel Goldstick) Date: Sun, 08 Aug 2010 13:36:28 -0400 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <4C5E1991.9020401@syslang.net> References: <4C5E1991.9020401@syslang.net> Message-ID: <4C5EEB1C.7050607@columbuswebmakers.com> Steven W. Orr wrote: > I'm ok in python but I haven't done too much with web pages. I have a web page > that is hand written in html that has about 1000 entries in a table and I want > to convert the table from entries like this > > > > > > > > > > to > > SomePythonCall('Some Date String', > 'SomeTag', > 'localSubdir', > "http://www.example.com/remote/path/something.html", > 'Click', > 'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? > > TIA > > Quickest way to get where you are going is django or another (perhaps smaller) framework. Since you say you are good with python, you could get your website done in a weekend Joel Goldstick From benjamin.kaplan at case.edu Sun Aug 8 13:51:10 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 8 Aug 2010 10:51:10 -0700 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> Message-ID: On Sun, Aug 8, 2010 at 10:24 AM, Default User wrote: > Not to prolong a good "food fight", but IIRC, many years ago in QBasic, > one could choose > > OPTION BASE 0 > > or > > OPTION BASE 1 > > to make arrays start with element [0] or element [1], respectively.? Could > such a feature be added to Python without significantly bloating the > interpreter? > > Then, if starting with [0] "works for you", nothing really changes.? And if > starting with [1] "works for you", then you are not made to feel like a > second-class citizen, and about as welcome as a dimwit at the Mensa > meeting. > > Isn't Python supposed to be simple and accessible, and therefore fun? > Python is also about being readable and consistent. It's going to get really confusing if half the files use 1-based lists and the other half use 0-based. Is it really that hard to get used to indices running from 0 to length-1? Also, good luck getting through life without running into C, C++, C#, Visual Basic, F#, Java, Ruby, Perl, Lisp, or OCaml code. Along with all the languages that use 0-based arrays. From nagle at animats.com Sun Aug 8 13:55:02 2010 From: nagle at animats.com (John Nagle) Date: Sun, 08 Aug 2010 10:55:02 -0700 Subject: urllib "quote" problem Message-ID: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> This warning appeared from urllib.quote: "/usr/local/lib/python2.6/urllib.py:1222: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal res = map(safe_map.__getitem__, s) " Here's urllib.quote from Python 2.6: ==== def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," Each of these characters is reserved in some component of a URL, but not necessarily in all of them. By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode '/'. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters. """ cachekey = (safe, always_safe) try: safe_map = _safemaps[cachekey] except KeyError: safe += always_safe safe_map = {} for i in range(256): c = chr(i) safe_map[c] = (c in safe) and c or ('%%%02X' % i) _safemaps[cachekey] = safe_map res = map(safe_map.__getitem__, s) #### WARNING REPORTED HERE return ''.join(res) ===== I don't, unfortunately, know what went into this call to produce the message; probably a URL in Unicode. This looks like code that will do the wrong thing in Python 2.6 for characters in the range 128-255. Those are illegal in type "str", but this code is constructing such values with "chr". John Nagle From benjamin.kaplan at case.edu Sun Aug 8 13:56:04 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 8 Aug 2010 10:56:04 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 10:21 AM, David Robinow wrote: > On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence wrote: >> On 08/08/2010 17:16, W. eWatson wrote: >>> >>> See Subject. I use matplotlib, scipy, numpy and possibly one other >>> module. If I go to the control panel, I only see numpy listed. Why? I >>> use a search and find only numpy and Python itself. How can matplotlib >>> and scipy be uninstalled? >> >> Have you heard of google? > google is not relevant to this issue. This group is the correct forum. > I'm not sure what the answer to the OP's problem is. If you no longer > wish to use these modules I suggest doing nothing. No harm will > result. Since this is specifically a matplotlib and scipy question, the most relevant forums would be the matplotlib and scipy mailing lists. The maintainers of those projects are probably on those lists, and they'll be able to answer this question better than we can since they know what the installers do in the first place. https://lists.sourceforge.net/lists/listinfo/matplotlib-users http://mail.scipy.org/mailman/listinfo/scipy-user From python at mrabarnett.plus.com Sun Aug 8 14:05:19 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Aug 2010 19:05:19 +0100 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> Message-ID: <4C5EF1DF.3090007@mrabarnett.plus.com> Default User wrote: > Not to prolong a good "food fight", but IIRC, many years ago in QBasic, > one could choose > > OPTION BASE 0 > > or > > OPTION BASE 1 > > to make arrays start with element [0] or element [1], respectively. > Could such a feature be added to Python without significantly bloating > the interpreter? > > Then, if starting with [0] "works for you", nothing really changes. And > if starting with [1] "works for you", then you are not made to feel like > a second-class citizen, and about as welcome as a dimwit at the Mensa > meeting. > If you changed the base then you'd break the standard library, unless everyone altered their code to compensate. It's all part of learning a programming language. Some have 0-based indexing, others have 1-based indexing; some have mutable strings, others have immutable strings, still others don't have 'proper' strings. Just learn to adapt. From python at mrabarnett.plus.com Sun Aug 8 14:16:51 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Aug 2010 19:16:51 +0100 Subject: # of Months between two dates In-Reply-To: References: Message-ID: <4C5EF493.2070508@mrabarnett.plus.com> Greg Lindstrom wrote: > I work for a company that processes claims for the health care industry > (Novasys Health, recently purchased by Centene Corp). My current > assignment has me writing a routine to compute insurance premiums. One > of the requirements is to determine how many months a policy has been in > effect. The datetime module will give me the number of days but, with > months having different lengths, that does not do me much good. I've > looked in the calendar library but didn't see anything there, either. > > I've written a function to return the months between date1 and date2 but > I'd like to know if anyone is aware of anything in the standard library > to do the same? For bonus points, does anyone know if postgres can do > the same (we use a lot of date/time funcitons in postgres, already, but > didn't see this problem addressed). > [snip] A simple expression is: diff = (current_year - start_year) * 12 + (current_month - start_month) According to this, if a policy started on 31 July 2010, then on 1 August 2010 it has been in effect for 1 month. Is this reasonable? It depends! It's probably better to write the function yourself according to what makes sense in your use-case, and document its behaviour clearly. From joel.goldstick at columbuswebmakers.com Sun Aug 8 14:24:50 2010 From: joel.goldstick at columbuswebmakers.com (Joel Goldstick) Date: Sun, 08 Aug 2010 14:24:50 -0400 Subject: # of Months between two dates In-Reply-To: References: Message-ID: <4C5EF672.8010508@columbuswebmakers.com> Greg Lindstrom wrote: > I work for a company that processes claims for the health care industry > (Novasys Health, recently purchased by Centene Corp). My current assignment > has me writing a routine to compute insurance premiums. One of the > requirements is to determine how many months a policy has been in effect. > The datetime module will give me the number of days but, with months having > different lengths, that does not do me much good. I've looked in the > calendar library but didn't see anything there, either. > > I've written a function to return the months between date1 and date2 but I'd > like to know if anyone is aware of anything in the standard library to do > the same? For bonus points, does anyone know if postgres can do the same > (we use a lot of date/time funcitons in postgres, already, but didn't see > this problem addressed). > > On a side note; since I'm dealing with money (USD), I decided to use the > decimal module for all computations. It's not a big difference -- unless > you've seen the movie "Office Space" :-) -- but it sure is nice. Especially > being able to easily round values to the nearest cent. You just have to > love the standard library. > > Thanks for your help, > --greg > > y_diff = present year - start date year m_diff = present month - start date month + (12 * y_diff) From thomas at jollans.com Sun Aug 8 14:47:16 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 20:47:16 +0200 Subject: Python "why" questions In-Reply-To: References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: <4C5EFBB4.9060300@jollans.com> On 2010-08-08 05:18, Dennis Lee Bieber wrote: > Was it this thread where I commented that many early BASICs would > allocate an eleven element array on > > DIM A(10) VB.net does this -- to cater for the classic VB programmer who is used to being able to index the number in brackets, and the .net framework, which uses 0-based indexing (as everything else would look silly in C#, or, especially, in C++/CLI. From costin.gament at gmail.com Sun Aug 8 15:25:15 2010 From: costin.gament at gmail.com (=?UTF-8?Q?Costin_Gamen=C8=9B?=) Date: Sun, 8 Aug 2010 22:25:15 +0300 Subject: Class initialization In-Reply-To: References: Message-ID: Thank you all for your answers and your patience. As soon as I can, I'll update my code and read up on the subject. If I still can't get it working, I'll bother you again. From martin at v.loewis.de Sun Aug 8 15:29:44 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 08 Aug 2010 21:29:44 +0200 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: > Add-Remove would be a very good answer, except for one thing. Understand > that I'm in Win7 so CP takes on a different form. On Control Panel > Add-Remove, I can find exactly two Python files: Python 2.5, and > python-Numpy-1.2.0. No scipy anything. Well, it should be there. Perhaps it was installed by a different user, and will only show up when that user goes into CP? Do you recall what procedure you have used for installation? > Well, this is interesting. I just > noticed Martin v. Loewis on the Python 2.5 entry. That's you, right? Correct. I keep building the installers, but was asked to put Python Software Foundation into the creator field of the MSI file. > I think I posted the errors my partner got above. Let me look. Yes, > here's the copy. > He gets > > Traceback (most recent call last): > File "C:\Documents and > Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", > line 40, in > from scipy import stats as stats # scoreatpercentile > File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, > in > from stats import * > File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, > in > import scipy.special as special > File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line > 22, in > from numpy.testing import NumpyTest > ImportError: cannot import name NumpyTest There is no way this can be attributed to an addition of a single character. In your partner's version of numpy.testing, there is no name NumpyTest. That sounds alright - in my version of numpy, there is no numpy.testing.NumpyTest, either. However, the line in special\__init__.py, on my system, reads from numpy.testing import Tester So it looks like that the scipy version and the numpy version don't match. Regards, Martin From andresen.nils at googlemail.com Sun Aug 8 15:49:22 2010 From: andresen.nils at googlemail.com (Nils) Date: Sun, 8 Aug 2010 12:49:22 -0700 (PDT) Subject: pre-uninstall script in bdist_wininst References: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> Message-ID: <0dd74e88-9043-44bd-910e-1374f3d5de70@v41g2000yqv.googlegroups.com> On 6 Aug., 04:02, Mark Hammond wrote: > According to a comment in pywin32's post-install script: > > ? ? ? ? ?elif arg == "-remove": > ? ? ? ? ? ? ?# bdist_msi calls us before uninstall, so we can undo what we > ? ? ? ? ? ? ?# previously did. ?Sadly, bdist_wininst calls us *after*, so > ? ? ? ? ? ? ?# we can't do much at all. > Sadly, I can not confirm this. I wrote the simplest install-script (dump call-parameters to a txt-file) and tested with 2.6 and 2.7 On bdist_wininst my install_script was called on install with parameter "-install" On bdist_wininst my install_script was called on install without parameters My script was never (ever) called on uninstall... > I'd suggest using py2exe to package the object and inno installer or > similar to handle the install and uninstall parts. Yes, I'll try that, thanks. From tjreedy at udel.edu Sun Aug 8 16:49:40 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 08 Aug 2010 16:49:40 -0400 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: On 8/7/2010 7:53 AM, Peter Otten wrote: > > You mean you'd go for the candidate who took the conservative approach and > got it right: > > print 1 > print 2 > print 'Fizz' > print 4 > print 'Buzz' > print 'Fizz' > print 7 > print 8 > print 'Fizz' > print 'Buzz' Way too verbose. How about print("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n etc. -- Terry Jan Reedy From tjreedy at udel.edu Sun Aug 8 17:04:35 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 08 Aug 2010 17:04:35 -0400 Subject: Smith-Waterman Algorithm in Python In-Reply-To: References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> <4C5D52BE.302@gmaiil.com> Message-ID: On 8/7/2010 1:43 PM, Daniel Fetchinson wrote: >> Every one of the first 20 entries is either the OP questions or your reply. > > And you think it was there before the OP sent his message? > Oh wait, did you just invent a time machine? :) > >> Daniel - you are no help at all, and no funny. > > Actually, I'm damn funny! :) I have noticed before that people who post without searching first end up polluting subsequent searches. Google obviously boosts the rank of recent pages. That is because when people search for something like "Lindsey Lohan", they most likely want the latest news rather than a definitive biography page. -- Terry Jan Reedy From jrmy.lnrd at gmail.com Sun Aug 8 18:20:17 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Sun, 8 Aug 2010 15:20:17 -0700 (PDT) Subject: Regular expression issue Message-ID: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> I am trying to learn regular expressions in python3 and have an issue with one of the examples I'm working with. The code is: #! /usr/bin/env python3 import re search_string = "[^aeiou]y$" print() in_string = 'vacancy' if re.search(search_string, in_string) != None: print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) else: print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) print() in_string = 'boy' if re.search(search_string, in_string) != None: print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) else: print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) print() in_string = 'day' if re.search(search_string, in_string) != None: print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) else: print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) print() in_string = 'pita' if re.search(search_string, in_string) != None: print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) else: print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) print() The output that I am getting is: ay, ey, iy, oy and uy are not at the end of vacancy. ay, ey, iy, oy or uy were found at the end of boy. ay, ey, iy, oy or uy were found at the end of day. ay, ey, iy, oy or uy were found at the end of pita. The last line of the output is the opposite of what I expected to see, and I'm having trouble figuring out what the issue is. Any help would be greatly appreciated. From thomas at jollybox.de Sun Aug 8 18:27:11 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 9 Aug 2010 00:27:11 +0200 Subject: Perl -> Python unpack In-Reply-To: References: Message-ID: <201008090027.12375.thomas@jollybox.de> On Friday 06 August 2010, it occurred to James Mills to exclaim: > Quick question for you Python enthusiasts that also > happen to know Perl quite well... Few and far between ... From thomas at jollybox.de Sun Aug 8 18:32:55 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 9 Aug 2010 00:32:55 +0200 Subject: Regular expression issue In-Reply-To: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <201008090032.55996.thomas@jollybox.de> On Monday 09 August 2010, it occurred to genxtech to exclaim: > I am trying to learn regular expressions in python3 and have an issue > with one of the examples I'm working with. > The code is: > > #! /usr/bin/env python3 > > import re > > search_string = "[^aeiou]y$" To translate this expression to English: a character that is not a, e, i, o, or u, followed by the character 'y', at the end of the line. "vacancy" matches. It ends with "c" (not one of aeiou), followed by "y" "pita" does not match: it does not end with "y". > print() > > in_string = 'vacancy' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of > {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of > {0}.".format(in_string)) > print() > > in_string = 'boy' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of > {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of > {0}.".format(in_string)) > print() > > in_string = 'day' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of > {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of > {0}.".format(in_string)) > print() > > in_string = 'pita' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of > {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of > {0}.".format(in_string)) > print() > > The output that I am getting is: > ay, ey, iy, oy and uy are not at the end of vacancy. > ay, ey, iy, oy or uy were found at the end of boy. > ay, ey, iy, oy or uy were found at the end of day. > ay, ey, iy, oy or uy were found at the end of pita. > > The last line of the output is the opposite of what I expected to see, > and I'm having trouble figuring out what the issue is. Any help would > be greatly appreciated. From python at mrabarnett.plus.com Sun Aug 8 18:50:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Aug 2010 23:50:52 +0100 Subject: Regular expression issue In-Reply-To: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <4C5F34CC.7020709@mrabarnett.plus.com> genxtech wrote: > I am trying to learn regular expressions in python3 and have an issue > with one of the examples I'm working with. > The code is: > > #! /usr/bin/env python3 > > import re > > search_string = "[^aeiou]y$" You can think of this as: a non-vowel followed by a 'y', then the end of the string. > print() > > in_string = 'vacancy' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) Matches because 'c' is a non-vowel, 'y' matches, and then the end of the string. > print() > > in_string = 'boy' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) Doesn't match because 'o' is a vowel, not a non-vowel. > print() > > in_string = 'day' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) Doesn't match because 'a' is a vowel, not a non-vowel. > print() > > in_string = 'pita' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) Doesn't match because 't' is a non-vowel but 'a' doesn't match 'y'. > print() > > The output that I am getting is: > ay, ey, iy, oy and uy are not at the end of vacancy. > ay, ey, iy, oy or uy were found at the end of boy. > ay, ey, iy, oy or uy were found at the end of day. > ay, ey, iy, oy or uy were found at the end of pita. > > The last line of the output is the opposite of what I expected to see, > and I'm having trouble figuring out what the issue is. Any help would > be greatly appreciated. From clp2 at rebertia.com Sun Aug 8 18:55:03 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 8 Aug 2010 15:55:03 -0700 Subject: Regular expression issue In-Reply-To: <201008090032.55996.thomas@jollybox.de> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> <201008090032.55996.thomas@jollybox.de> Message-ID: On Sun, Aug 8, 2010 at 3:32 PM, Thomas Jollans wrote: > On Monday 09 August 2010, it occurred to genxtech to exclaim: >> I am trying to learn regular expressions in python3 and have an issue >> with one of the examples I'm working with. >> The code is: >> >> #! /usr/bin/env python3 >> >> import re >> >> search_string = "[^aeiou]y$" > > To translate this expression to English: > > a character that is not a, e, i, o, or u, followed by the character 'y', at > the end of the line. > > "vacancy" matches. It ends with "c" (not one of aeiou), followed by "y" > > "pita" does not match: it does not end with "y". Or in other words, the regex will not match when: - the string ends in "ay", "ey", "iy", "oy", or "uy" - the string doesn't end in "y" - the string is less than 2 characters long So, the program has a logic error in its assumptions. A non-match *doesn't* imply that a string ends in one of the aforementioned pairs; the other possibilities have been overlooked. May I suggest instead using the much more straightforward `search_string = "[aeiou]y$"` and then swapping your conditions around? The double-negative sort of style the program is currently using is (as you've just experienced) harder to reason about and thus more error-prone. Cheers, Chris -- http://blog.rebertia.com From wolftracks at invalid.com Sun Aug 8 19:15:45 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 08 Aug 2010 16:15:45 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On 8/8/2010 10:56 AM, Benjamin Kaplan wrote: > On Sun, Aug 8, 2010 at 10:21 AM, David Robinow wrote: >> On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence wrote: >>> On 08/08/2010 17:16, W. eWatson wrote: >>>> >>>> See Subject. I use matplotlib, scipy, numpy and possibly one other >>>> module. If I go to the control panel, I only see numpy listed. Why? I >>>> use a search and find only numpy and Python itself. How can matplotlib >>>> and scipy be uninstalled? >>> >>> Have you heard of google? >> google is not relevant to this issue. This group is the correct forum. >> I'm not sure what the answer to the OP's problem is. If you no longer >> wish to use these modules I suggest doing nothing. No harm will >> result. > > Since this is specifically a matplotlib and scipy question, the most > relevant forums would be the matplotlib and scipy mailing lists. The > maintainers of those projects are probably on those lists, and they'll > be able to answer this question better than we can since they know > what the installers do in the first place. > > https://lists.sourceforge.net/lists/listinfo/matplotlib-users > http://mail.scipy.org/mailman/listinfo/scipy-user Well, you have a good point, and I will do that. However, I'm surprised there doesn't seem to be some uniformity on this subject. Yes, removing them directly is an option, but I prefer to find out why the discrepancy? BTW, I really do not plan to remove them now. The anomaly does deserve an answer. To suggest Google as above, makes no sense to me. This is the place to ask, as another poster stated. From benjamin.kaplan at case.edu Sun Aug 8 19:34:37 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 8 Aug 2010 16:34:37 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 4:15 PM, W. eWatson wrote: > On 8/8/2010 10:56 AM, Benjamin Kaplan wrote: >> >> On Sun, Aug 8, 2010 at 10:21 AM, David Robinow ?wrote: >>> >>> On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence >>> ?wrote: >>>> >>>> On 08/08/2010 17:16, W. eWatson wrote: >>>>> >>>>> See Subject. I use matplotlib, scipy, numpy and possibly one other >>>>> module. If I go to the control panel, I only see numpy listed. Why? I >>>>> use a search and find only numpy and Python itself. How can matplotlib >>>>> and scipy be uninstalled? >>>> >>>> Have you heard of google? >>> >>> google is not relevant to this issue. This group is the correct forum. >>> I'm not sure what the answer to the OP's problem is. If you no longer >>> wish to use these modules I suggest doing nothing. No harm will >>> result. >> >> Since this is specifically a matplotlib and scipy question, the most >> relevant forums would be the matplotlib and scipy mailing lists. The >> maintainers of those projects are probably on those lists, and they'll >> be able to answer this question better than we can since they know >> what the installers do in the first place. >> >> https://lists.sourceforge.net/lists/listinfo/matplotlib-users >> http://mail.scipy.org/mailman/listinfo/scipy-user > > Well, you have a good point, and I will do that. However, I'm surprised > there doesn't seem to be some uniformity on this subject. > > Yes, removing them directly is an option, but I prefer to find out why the > discrepancy? BTW, I really do not plan to remove them now. The anomaly does > deserve an answer. > There's a discrepancy because package management on Python is completely broken. Distutils and Setuptools (and it's new fork, Distribute) are inadequate- they act as installers, but don't provide a way to uninstall the program. There are attempts to fix this, such as pip and Activestate's PyPM, but they aren't used as widely as the older methods. > To suggest Google as above, makes no sense to me. This is the place to ask, > as another poster stated. > -- > http://mail.python.org/mailman/listinfo/python-list > From python.list at tim.thechases.com Sun Aug 8 19:34:46 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 08 Aug 2010 18:34:46 -0500 Subject: Regular expression issue In-Reply-To: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <4C5F3F16.3070600@tim.thechases.com> On 08/08/10 17:20, genxtech wrote: > if re.search(search_string, in_string) != None: While the other responses have addressed some of the big issues, it's also good to use if thing_to_test is None: or if thing_to_test is not None: instead of "== None" or "!= None". -tkc From mwilson at the-wire.com Sun Aug 8 19:47:18 2010 From: mwilson at the-wire.com (Mel) Date: Sun, 08 Aug 2010 19:47:18 -0400 Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: Costin Gament wrote: > So you're saying I should just use __init__? Will that get me out of > my predicament? > No, I don't quite understand the difference between my exemple and > using __init__, but I will read the docs about it. Here's the thing about class variables: Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class AClass (object): ... var = 5 ... >>> a = AClass() >>> b = AClass() >>> a.var, b.var (5, 5) >>> AClass.var = 7 >>> a.var, b.var (7, 7) >>> a.var = 9 >>> a.var, b.var (9, 7) >>> a.var is AClass.var False >>> b.var is AClass.var True When `var` is defined as a variable in AClass, it belongs to AClass. But all the instances of AClass are allowed to access it as though it's their own -- it's a sensible way for Python to manage attribute lookup. Assigning to AClass.var changes the value as seen by all the instances. Assigning to a.var creates a new variable in instance a's namespace, and from then on that becomes the value that will be found by looking up a.var . The `is` test shows that this is true. Mel. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 20:17:32 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 00:17:32 GMT Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: <4c5f491c$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 19:47:18 -0400, Mel wrote: > Costin Gament wrote: > >> So you're saying I should just use __init__? Will that get me out of my >> predicament? >> No, I don't quite understand the difference between my exemple and >> using __init__, but I will read the docs about it. > > Here's the thing about class variables: [snip example] No, that's actually the thing about class *attributes*. This is Python, not Java or whatever language you're used to that uses such bizarrely inconsistent terminology. A variable holding an int is an int variable. A variable holding a string is a string variable. A variable holding a float is a float variable. And a variable holding a class is a class variable. Given a class: class MyClass: attribute = None MyClass is a perfectly normal variable, like any other variable you create in Python. You can reassign to it, you can pass it to functions, it has an object bound to it. In other words, it's a class variable in the same way that n = 2 creates an int variable. (Although of course because Python has dynamic typing, n is only an int until it gets rebound to something which isn't an int. Likewise MyClass is only a class until it gets rebound to something else.) That's why Python has builtin functions getattr, setattr and hasattr rather than getvar, setvar and hasvar. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 20:26:23 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 00:26:23 GMT Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? References: Message-ID: <4c5f4b2f$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 13:21:55 -0400, David Robinow wrote: > On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence > wrote: >> On 08/08/2010 17:16, W. eWatson wrote: >>> >>> See Subject. I use matplotlib, scipy, numpy and possibly one other >>> module. If I go to the control panel, I only see numpy listed. Why? I >>> use a search and find only numpy and Python itself. How can matplotlib >>> and scipy be uninstalled? >> >> Have you heard of google? > google is not relevant to this issue. This group is the correct forum. I would have thought that people who hang around dedicated forums for matplotlib and scipy would probably have more knowledge about the workings of the matplotlib and scipy installers than generic Python programmers, most of whom have never touched or used matplotlib or scipy. > I'm not sure what the answer to the OP's problem is. Oh the irony. -- Steven From peter.milliken at gmail.com Sun Aug 8 20:28:59 2010 From: peter.milliken at gmail.com (Peter) Date: Sun, 8 Aug 2010 17:28:59 -0700 (PDT) Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> On Aug 9, 6:49?am, Terry Reedy wrote: > On 8/7/2010 7:53 AM, Peter Otten wrote: > > > > > You mean you'd go for the candidate who took the conservative approach and > > got it right: > > > print 1 > > print 2 > > print 'Fizz' > > print 4 > > print 'Buzz' > > print 'Fizz' > > print 7 > > print 8 > > print 'Fizz' > > print 'Buzz' > > Way too verbose. How about > print("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n > etc. > > -- > Terry Jan Reedy And to hell with the code being maintainable afterwards? :-) Personally I would FIRE somebody who produced code like this. Assuming I was a manager or in a position to hire (I used to be in a previous life), then I would be looking for somebody who was capable of writing good, solid and MAINTAINABLE code (love those subjective words? :-)). Realistically, if the application is anything other than trivial then it will most likely have somebody poking around in it at some stage who isn't the brightest spark in the firmament. Anybody who produces nice, readable and straight forward code in my books gets the tick of approval. No offence intended, but anybody who tried to prove how "bright" they are by producing the least number of (unmaintainable) lines of code would not get past the first interview - unless they were prepared to sign a contract that guaranteed they would be available to maintain the application for its entire lifecycle. Generally (in my experience) people who write code like this don't hang around long - certainly not long enough to maintain their monstrosity! Peter From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 20:39:31 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 00:39:31 GMT Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> Message-ID: <4c5f4e42$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 17:28:59 -0700, Peter wrote: > On Aug 9, 6:49?am, Terry Reedy wrote: >> On 8/7/2010 7:53 AM, Peter Otten wrote: >> >> > You mean you'd go for the candidate who took the conservative >> > approach and got it right: >> >> > print 1 >> > print 2 >> > print 'Fizz' >> > print 4 >> > print 'Buzz' >> > print 'Fizz' >> > print 7 >> > print 8 >> > print 'Fizz' >> > print 'Buzz' >> >> Way too verbose. How about >> print("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n etc. >> >> -- >> Terry Jan Reedy > > And to hell with the code being maintainable afterwards? :-) I'm pretty sure both Peter Otten and Terry Reedy were being sarcastic and/ or ironic. -- Steven From rantingrick at gmail.com Sun Aug 8 20:43:03 2010 From: rantingrick at gmail.com (rantingrick) Date: Sun, 8 Aug 2010 17:43:03 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! Message-ID: Hello folks, You all know i been forced to use Ruby and i am not happy about that. But i thought i would share more compelling evidence of the moronicity of the Ruby language syntax from the perspective of regexp's. I recently built myself a nice little Ruby script editor because i hate everything else out there. Whist writing the Colorizer i realized (again) just how beautifully elegant Python is and how crufty and asinine Ruby is. Anyhow my point is that by looking at the regexp's you can clearly see that parsing Ruby syntax is BF and Python syntax is elegant! Here are a few examples: Note i used look back assertions for clarity. -------------------- Modules -------------------- Python does not have a module syntax (an thank Guido for that!) because we have a much better system of using the file as a module and not introducing more cruft into our scripts. Anyway if Python *did* have a module syntax it would look better than this crap! Python: N/A Ruby: r'(?<=module )(::)?(\w+(::)?)*' -------------------- Classes -------------------- Python and Ruby class definitions are almost the same except for the module cruft getting in the way again. Python: r'(?<=class )\w+' Ruby: r'(?<=class )(::)?(\w+(::)?)*' --------------------- Defs --------------------- HaHa, you're going to poop yourself when you see this! No introduction needed :-D. Python: r'(?<=def )\w+' Ruby: r'(?<=def )(self\.)?((\w+::\w+)|(\w+\.\w+)|(\w+))([?|!])?' --------------------- Strings --------------------- Single line strings are exactly the same in both languages except in Ruby double quoted strings are backslash interpreted and single quote strings are basically raw. Except Ruby introduces more cruft (as usual) in the form of what i call "lazy man" stings.... >>> a = %w{ one two three} ["one", "two", "three"] >>> s = %{one two three} one two three >>> repat = %r{one two three} /one two three/ ... only good for hand coding! ---------------------- Multi Line Strings ---------------------- Ha. Ruby does not really have multi line strings. Ruby has what they call a "Here Doc". Besides picking the most boneheaded name for such an object they also introduced and even more boneheaded syntax. To define a "Here Doc" (god i hate that name!) you start with double greater than ">>" and immediately follow with an identifier token of you choice (it can be anything your dirty little mind can come up with. >>HEREDOC this is the body of a here doc. Why the hell did they not just use triple quotes like Python did. Now i will need to remember some token to know where' i stopped HEREDOC As you can see it is another example of tacked on functionality that was not carefully considered before hand. Anyway here are the regexp's... Python: r'""".*?"""' Python: r"'''.*?'''" Ruby: r'<<(\w+).*?(\1)' -------------------------- Comments -------------------------- Ruby and Python single line comments are the same. Use the hash char. However Ruby introduces multi line comment blocks delimited by the tokens "=begin" and "=end". Python: r"#.*" Ruby: r"=begin.*?=end" Ruby: r"#.*" ------------------------- Conculsion ------------------------- I just want to take this opportunity to thank Mr. Van Rossum and the Python dev team for creating a truly revolutionary 21st century language that no other language can hold a candle to. Without Python we would be force to use these "other" monstrosities" on a daily basis -- and i just don't think i could bear it! Keep up the good work! From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 20:51:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 00:51:42 GMT Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? References: Message-ID: <4c5f511d$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 16:15:45 -0700, W. eWatson wrote: > To suggest Google as above, makes no sense to me. This is the place to > ask, as another poster stated. He may have stated it, but the evidence suggests he's wrong. You're asking a question about the details of the installers used specifically by scipy and matplotlib. Most people here have no idea about that, hence the lack of useful answers. The best likelihood of finding a solution is to go to a specialist forum, not a generic one. In any case, suggesting Google is *always* relevant. You gave us no reason at all to think that you had made any effort to solve the problem yourself before asking for us to volunteer our time. That's rude. Did you google for "uninstall scipy" before asking for help? Did you make any effort to read the Scipy manual first? Did you make any effort *at all*? If you had -- and for all we know, you might have spent days trying to solve this, or 3 seconds, or anything in between -- you didn't say so. Suggesting that you do some googling is absolutely relevant. Perhaps it's about time that we point you at this: http://catb.org/esr/faqs/smart-questions.html I don't agree with everything the author says, but the basic position is about right. -- Steven From roy at panix.com Sun Aug 8 21:01:46 2010 From: roy at panix.com (Roy Smith) Date: Sun, 08 Aug 2010 21:01:46 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> Message-ID: In article <388041a0-4bc5-4f65-bae3-d516fb90f57f at l25g2000prn.googlegroups.com>, Peter wrote: > Realistically, if the application is anything other than trivial then > it will most likely have somebody poking around in it at some stage > who isn't the brightest spark in the firmament. Anybody who produces > nice, readable and straight forward code in my books gets the tick of > approval. What he said. The first test of good code is that you can understand what you wrote six months after you wrote it. The second test is that you can explain it to some junior programmer a couple of cubes away from you, two or three years after you wrote it. The ultimate test is that some poor schmuck, long after you've moved on to another project (or company), can figure out what the heck you wrote, ten years later. And, oh, yeah, the junior programmer who you explained it to in the previous paragraph, may be 9 or 12 time zones away from the team who is currently maintaining your code, if he's around at all. From python at mrabarnett.plus.com Sun Aug 8 21:14:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 02:14:18 +0100 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: References: Message-ID: <4C5F566A.2000704@mrabarnett.plus.com> rantingrick wrote: > Hello folks, > [snip] > --------------------- > Strings > --------------------- > Single line strings are exactly the same in both languages except in > Ruby double quoted strings are backslash interpreted and single quote > strings are basically raw. Except Ruby introduces more cruft (as > usual) in the form of what i call "lazy man" stings.... > >>>> a = %w{ one two three} > ["one", "two", "three"] >>>> s = %{one two three} > one two three >>>> repat = %r{one two three} > /one two three/ > > ... only good for hand coding! > From Perl. > ---------------------- > Multi Line Strings > ---------------------- > Ha. Ruby does not really have multi line strings. Ruby has what they > call a "Here Doc". Besides picking the most boneheaded name for such > an object they also introduced and even more boneheaded syntax. To > define a "Here Doc" (god i hate that name!) you start with double > greater than ">>" and immediately follow with an identifier token of > you choice (it can be anything your dirty little mind can come up > with. > >>> HEREDOC > this is the body > of a > here doc. Why the > hell did they not just > use triple quotes like Python did. > Now i will need to remember some token to know where' > i stopped > HEREDOC > > As you can see it is another example of tacked on functionality that > was not carefully considered before hand. Anyway here are the > regexp's... > > Python: r'""".*?"""' > Python: r"'''.*?'''" > Ruby: r'<<(\w+).*?(\1)' > Also from Perl. I don't know what the point of your post was. We already know that we prefer Python; that's why we're here! :-) And anyway, being nasty about other languages feels unPythonic to me... From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 21:15:00 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 01:15:00 GMT Subject: Python -Vs- Ruby: A regexp match to the death! References: Message-ID: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 17:43:03 -0700, rantingrick wrote: > Ha. Ruby does not really have multi line strings. Except, of course, it does, as you go on to show. > Ruby has what they > call a "Here Doc". Besides picking the most boneheaded name for such an > object It's standard terminology that has been around for a long time in many different languages. http://en.wikipedia.org/wiki/Here_document > they also introduced and even more boneheaded syntax. To define a > "Here Doc" (god i hate that name!) you start with double greater than > ">>" and immediately follow with an identifier token of you choice (it > can be anything your dirty little mind can come up with. > >>>HEREDOC > this is the body > of a > here doc. Why the > hell did they not just > use triple quotes like Python did. > Now i will need to remember some token to know where' i stopped > HEREDOC Incorrect. [steve at sylar ~]$ irb irb(main):001:0> s = >>END SyntaxError: compile error (irb):1: syntax error s = >>END ^ from (irb):1 irb(main):002:0> s = <<-END irb(main):003:0" Multi-line text irb(main):004:0" goes here irb(main):005:0" END => "Multi-line text\ngoes here\n" irb(main):006:0> puts s Multi-line text goes here => nil irb(main):007:0> > As you can see it is another example of tacked on functionality that was > not carefully considered before hand. I disagree. It's an old and venerable technique, and very useful on the rare occasion that you have lots of quotation marks in a string. Whether those rare occasions are common enough to require specialist syntax is another question. In Python, the idea is that two heredocs (''' and """) is enough for anybody. That makes it difficult to write a string literal like, e.g.: Python strings have four delimiters: (1) single quote ' (2) double quote " (3) single-quote here-doc ''' (4) double-quote here-doc """ plus equivalent raw-strings of each kind. Trying writing that as a single literal in Python without escapes. There are work-arounds, of course, like using implicit concatenation, but they're ugly. In Ruby they decided to be more general, so you can define whatever heredoc you need to quote whatever literal string you need. That's not bone-headed. -- Steven From wuwei23 at gmail.com Sun Aug 8 21:32:50 2010 From: wuwei23 at gmail.com (alex23) Date: Sun, 8 Aug 2010 18:32:50 -0700 (PDT) Subject: Python Portability References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: <7cfbef6a-916c-4215-937a-2e724ab6c534@z30g2000prg.googlegroups.com> "W. eWatson" wrote: > I now have the answer I need, and I do not care one more wit > about a one character change. > > I'm done here. That's a fantastic response to give to people who were actually willing to sacrifice their time to help you with your problems. I'm always stunned at those who come here in ignorance somehow "knowing" what the correct answer they wanted is, even when it runs counter to responses from far more experienced people. Good luck continuing to get help here with that attitude. From ranjithtenz at gmail.com Sun Aug 8 22:16:11 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Mon, 9 Aug 2010 07:46:11 +0530 Subject: Need a mentor Message-ID: Hi all, I`m doing a python based project, I need a mentor who can guide me and help me to complete the project. the idea is fully based upon application programming. What I want is just suggest me how to implement so that I write the code and send it back to you. And there you can check the codes and find the better solution or giving me some other ideas so that we can optimize the code and bring a better solution. I`m glad to work on python if anyone interested in this please kindly let me know it. Awaiting for your reply. -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter.milliken at gmail.com Sun Aug 8 22:16:17 2010 From: peter.milliken at gmail.com (Peter) Date: Sun, 8 Aug 2010 19:16:17 -0700 (PDT) Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> <4c5f4e42$0$28663$c3e8da3@news.astraweb.com> Message-ID: On Aug 9, 10:39?am, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 17:28:59 -0700, Peter wrote: > > On Aug 9, 6:49?am, Terry Reedy wrote: > >> On 8/7/2010 7:53 AM, Peter Otten wrote: > > >> > You mean you'd go for the candidate who took the conservative > >> > approach and got it right: > > >> > print 1 > >> > print 2 > >> > print 'Fizz' > >> > print 4 > >> > print 'Buzz' > >> > print 'Fizz' > >> > print 7 > >> > print 8 > >> > print 'Fizz' > >> > print 'Buzz' > > >> Way too verbose. How about > >> print("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n etc. > > >> -- > >> Terry Jan Reedy > > > And to hell with the code being maintainable afterwards? :-) > > I'm pretty sure both Peter Otten and Terry Reedy were being sarcastic and/ > or ironic. > > -- > Steven I'm sure you're right - and I repeat that I meant no offense. My comments were intended in the spirit of what to do or do not do in an interview for (any) programming job. Peter and Terry just offered some good examples of what you don't want to do (IMO) :-) So, I apologise if anybody has taken my comments as a slur on Peter and/or Terry's posts - they were not intended as such. Peter From georgeolivergo at gmail.com Sun Aug 8 22:46:08 2010 From: georgeolivergo at gmail.com (George Oliver) Date: Sun, 8 Aug 2010 19:46:08 -0700 (PDT) Subject: requirements in writing an email/rss/usenet client? Message-ID: hi, I'd like to know what to consider when writing an email/rss/usenet client. Apologies for such a broad question, but I've never attempted a project of this scope and I'm currently feeling out the requirements. My target is something like a gui-based mutt (I use a Windows OS btw), with influences from programs like Alpine (http://www.washington.edu/ alpine/) and Sup (http://sup.rubyforge.org/). I currently use Thunderbird + Muttator, which is a nice setup; but, it has some clunky parts, and I thought it might be simpler in the end to start fresh than try to engage with what seems to be the massive-ness of Thunderbird (of course, I may be disabused of this notion at some point ;) ). So far I've looked at the email and related modules in the standard lib, found some related links from the list [1], and read a little about the relevant protocols involved. I'd appreciate hearing about any other examples, references, or experiences of people who've written similar programs or related libraries. thanks, George [1] Including references to: * http://sourceforge.net/projects/usablemail/ * http://proquest.safaribooksonline.com/0596000855/python2-CHP-11-SECT-4 * http://wiki.laptop.org/go/Email * the pyne client * http://chandler.osafoundation.org/ From sushma.konanki at gmail.com Mon Aug 9 00:25:29 2010 From: sushma.konanki at gmail.com (sushma) Date: Sun, 8 Aug 2010 21:25:29 -0700 (PDT) Subject: urgent requirement Message-ID: <19ff72d0-8e2a-4ad5-9b7f-bca2b6466541@z34g2000pro.googlegroups.com> We have an urgent requirement for people who are having experience in python. If you are interested for this position forward your updated resume to the sushmak at millenniumsoft.com with the details mention below; current ctc: expected ctc: notice period: regards, sushma. www.millenniumsoft.com From wolftracks at invalid.com Mon Aug 9 00:54:42 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 08 Aug 2010 21:54:42 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: <4c5f511d$0$28663$c3e8da3@news.astraweb.com> References: <4c5f511d$0$28663$c3e8da3@news.astraweb.com> Message-ID: On 8/8/2010 5:51 PM, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 16:15:45 -0700, W. eWatson wrote: > >> To suggest Google as above, makes no sense to me. This is the place to >> ask, as another poster stated. > > He may have stated it, but the evidence suggests he's wrong. You're > asking a question about the details of the installers used specifically > by scipy and matplotlib. Most people here have no idea about that, hence > the lack of useful answers. The best likelihood of finding a solution is > to go to a specialist forum, not a generic one. > > In any case, suggesting Google is *always* relevant. You gave us no > reason at all to think that you had made any effort to solve the problem > yourself before asking for us to volunteer our time. That's rude. Did you > google for "uninstall scipy" before asking for help? Did you make any > effort to read the Scipy manual first? Did you make any effort *at all*? > If you had -- and for all we know, you might have spent days trying to > solve this, or 3 seconds, or anything in between -- you didn't say so. > > Suggesting that you do some googling is absolutely relevant. > > Perhaps it's about time that we point you at this: > > http://catb.org/esr/faqs/smart-questions.html > > I don't agree with everything the author says, but the basic position is > about right. > > > For the last few hours, I've been on the scipy and numpy mail list, per a suggestion. No one seems to really understand uninstall there. I think Ben Caplan may have it right. You and I need go no further with this. We disagree--again. From shambhu.1980 at gmail.com Mon Aug 9 00:57:30 2010 From: shambhu.1980 at gmail.com (Shambhu) Date: Sun, 8 Aug 2010 21:57:30 -0700 (PDT) Subject: os.unlink on Windows References: <4c5eb146$0$28663$c3e8da3@news.astraweb.com> Message-ID: Hi Thomas, Steven, Thanks for explanation. It is working now after using double backslash in pathname. I was misinterpreting the display output and thinking that it was being added by 'os' module. Regards, Shambhu. T On Aug 8, 6:29?pm, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 04:41:14 -0700, Shambhu wrote: > > Hi Thomas, > > > ? ? ? ? ? ?I checked, file is present. Here is my sample script: > > import os > > filename = "C:\SHAMBHU\tmp\text_delete.txt" > > Did you intend to provide a filename with two TAB characters in it? > > c colon backslash s h a m b u TAB m p TAB e x t underscore d e l e t e > dot t x t > > > File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\ > > \tmp\\text_delete.txt" is not (with extra backslash in path which is > > added by os.unlink). > > os.unlink does add any extra backslashes. You are misinterpreting what > you are seeing. > > -- > Steven From tjreedy at udel.edu Mon Aug 9 01:11:59 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 01:11:59 -0400 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> <4c5f4e42$0$28663$c3e8da3@news.astraweb.com> Message-ID: On 8/8/2010 10:16 PM, Peter wrote: >> I'm pretty sure both Peter Otten and Terry Reedy were being sarcastic and/ >> or ironic. About the most I ever am ;=)! > I'm sure you're right - and I repeat that I meant no offense. > > My comments were intended in the spirit of what to do or do not do in > an interview for (any) programming job. Peter and Terry just offered > some good examples of what you don't want to do (IMO) :-) > > So, I apologise if anybody has taken my comments as a slur on Peter > and/or Terry's posts - they were not intended as such. I was not sure if you were taking me seriously or not, but rather than be insulted, I am delighted that I gave you an opportunity to both get something off your chest and say something worthwhile. When I was hired in part to maintain and extend someone else's work, it was in pretty good shape and the outgoing person, with more experience than me, gave me a quick head's about about it. But I realize that many others have been less fortunate, but of course cannot throw a fit in their new place of employment, as appropriate as it might seem. -- Terry Jan Reedy From nagle at animats.com Mon Aug 9 01:50:56 2010 From: nagle at animats.com (John Nagle) Date: Sun, 08 Aug 2010 22:50:56 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: <4c5f9748$0$1657$742ec2ed@news.sonic.net> On 8/8/2010 9:51 AM, Mark Lawrence wrote: > On 08/08/2010 17:16, W. eWatson wrote: >> See Subject. I use matplotlib, scipy, numpy and possibly one other >> module. If I go to the control panel, I only see numpy listed. Why? I >> use a search and find only numpy and Python itself. How can matplotlib >> and scipy be uninstalled? > > Have you heard of google? > > Mark Lawrence. It's a legitimate question. It might be framed as "why does Python package management not play well with the platform's package management system?" Which is a reasonable enough question. On Windows, some packages play well with Add/Remove programs, and some don't. On Linux, some packages play well with Yum, and some don't. The basic answer is that nobody is in charge. There's nobody even trying to herd the third-party modules. Unlike CPAN, which has standards for Perl packages and some level of quality control, PyPi is just a link farm. John Nagle From martin at v.loewis.de Mon Aug 9 01:59:06 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 09 Aug 2010 07:59:06 +0200 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: <4C5F992A.4040606@v.loewis.de> > There's a discrepancy because package management on Python is > completely broken. Distutils and Setuptools (and it's new fork, > Distribute) are inadequate- they act as installers, but don't provide > a way to uninstall the program. That's not true. If you use the bdist_wininst, bdist_msi, or bdist_rpm distutils commands, you get packages which support uninstallations very well. Regards, Martin From martin at v.loewis.de Mon Aug 9 02:01:06 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 09 Aug 2010 08:01:06 +0200 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: <4c5f9748$0$1657$742ec2ed@news.sonic.net> References: <4c5f9748$0$1657$742ec2ed@news.sonic.net> Message-ID: <4C5F99A2.9070309@v.loewis.de> > The basic answer is that nobody is in charge. There's nobody > even trying to herd the third-party modules. Unlike CPAN, which > has standards for Perl packages and some level of quality > control, PyPi is just a link farm. Do the standards of CPAN also include uninstallation? To my knowledge, they don't: so how does it help to have standards, wrt. to the OP's question? Regards, Martin From cjgohlke at gmail.com Mon Aug 9 02:30:46 2010 From: cjgohlke at gmail.com (Christoph Gohlke) Date: Sun, 8 Aug 2010 23:30:46 -0700 (PDT) Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? References: <4c5f511d$0$28663$c3e8da3@news.astraweb.com> Message-ID: <8135936c-9b50-4c04-afb7-46a564b24e62@b4g2000pra.googlegroups.com> On Aug 8, 9:54?pm, "W. eWatson" wrote: > On 8/8/2010 5:51 PM, Steven D'Aprano wrote: > > > On Sun, 08 Aug 2010 16:15:45 -0700, W. eWatson wrote: > > >> To suggest Google as above, makes no sense to me. This is the place to > >> ask, as another poster stated. > > > He may have stated it, but the evidence suggests he's wrong. You're > > asking a question about the details of the installers used specifically > > by scipy andmatplotlib. Most people here have no idea about that, hence > > the lack of useful answers. The best likelihood of finding a solution is > > to go to a specialist forum, not a generic one. > > > In any case, suggesting Google is *always* relevant. You gave us no > > reason at all to think that you had made any effort to solve the problem > > yourself before asking for us to volunteer our time. That's rude. Did you > > google for "uninstall scipy" before asking for help? Did you make any > > effort to read the Scipy manual first? Did you make any effort *at all*? > > If you had -- and for all we know, you might have spent days trying to > > solve this, or 3 seconds, or anything in between -- you didn't say so. > > > Suggesting that you do some googling is absolutely relevant. > > > Perhaps it's about time that we point you at this: > > >http://catb.org/esr/faqs/smart-questions.html > > > Idon'tagree with everything the author says, but the basic position is > > about right. > > For the last few hours, I've been on the scipy and numpy mail list, per > a suggestion. No one seems to really understand uninstall there. Well. Your question has been answered on Numpy-discussion in February and again today on SciPy-users. > I think > Ben Caplan may have it right. You and I need go no further with this. We > disagree--again. From ranjithtenz at gmail.com Mon Aug 9 02:31:26 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Mon, 9 Aug 2010 12:01:26 +0530 Subject: Need mentor Message-ID: Hi all, I have described the theme of my project here, When the script is runned a configuring window has to be displayed where the user has to configure for there desired Web Browser, Audio Player, Video Player, Text Editor (Each Specified in separate SS Tab). Here the script should retrieve all installed Web Browser, Audio Player, Video Player and Text Editor and categorized and displayed in their corresponding tab`s. Here the user has to choose and set their preferred Web Browser, Video Player, Audio Player, Text Editor and update the configure file. note 1: configuring window should run automatically only first if the user wants to reconfigure the file again they should run configuring module alone note 2: This script is to start it on every login and stay running on background until i shut download the machine. For an example, this is complete real time behavior of the script. Let us consider I`m the user I downloaded the script and runned it, It should check for a configuring file if there is no configure file is created means it should automatically create a new configure file and displays a configuring window in that window I will be offered by whatever the web browsers, audio player, video player, text editor installed on my machine will has to be shown to me in their corresponding tab`s I have to set my desired web browser if I choose chrome has my prefered web browser and whenever I press the key "w" on desktop screen the chrome browser should be opened, I have to set my desired Audio player if I choose exaile has my preferred audio player and whenever I press the key "a" on desktop screen the Exaile audio player should be opened,I have to set my desired video player if I choose vlc has my prefered video player and whenever I press the key "v" on desktop screen the vlc player should be opened, I have to set my desired text editor if I choose gedit has my prefered text editor and whenever I press the key "t" on desktop screen the Gedit text editor should be opened, this just like creating hotkeys and all these configured details should be updated when I click on apply and exits the configuring windows and runs the script at the desktop background while i`m in desktop when i just hit "w" chrome browser should opened -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Mon Aug 9 02:31:57 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 23:31:57 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> On 8 ???, 17:59, Thomas Jollans wrote: > Two problems here: > > str.replace doesn't use regular expressions. You'll have to use the re > module to use regexps. (the re.sub function to be precise) > > '.' ?matches a single character. Any character, but only one. > '.*' matches as many characters as possible. This is not what you want, > since it will match everything between the *first* . > You want non-greedy matching. > > '.*?' is the same thing, without the greed. Thanks you, So i guess this needs to be written as: src_data = re.sub( '', '', src_data ) Tha 'r' special char doesn't need to be inserter before the regex here due to regex ain't containing backslashes. > You will have to find the tag before inserting the string. > str.find should help -- or you could use str.replace and replace the > tag with you counter line, plus a new . Ah yes! Damn why din't i think of it.... str.replace should do the trick. I was stuck trying to figure regexes. So, i guess that should work: src_data = src_data.replace('', '

??????? ??????????: %(counter)d

' ) > No it's not. You're just giving up too soon. Yes youa re right, your hints keep me going and thank you for that. From israelu at elbit.co.il Mon Aug 9 02:50:06 2010 From: israelu at elbit.co.il (iu2) Date: Sun, 8 Aug 2010 23:50:06 -0700 (PDT) Subject: xmlrpc and processes Message-ID: <3ec02745-4982-4f9e-955f-b771cdd64e19@d8g2000yqf.googlegroups.com> Hi, I have a SimpleXMLRPCServer running on one PC. I need several ServerProxy-s talking to it, each one running on a different PC. That is, I run on each PC a client application, that talks to the one server using xml-rpc. Is the xml-rpc designed to work like this? If not, is there something I can do to still be able to work with xml-rpc in this architucture? Thank you very much From pavlovevidence at gmail.com Mon Aug 9 02:53:41 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 8 Aug 2010 23:53:41 -0700 (PDT) Subject: urgent requirement References: <19ff72d0-8e2a-4ad5-9b7f-bca2b6466541@z34g2000pro.googlegroups.com> Message-ID: <156761d4-4c6d-4583-904e-15f720365177@u4g2000prn.googlegroups.com> On Aug 8, 9:25?pm, sushma wrote: > ? We have an urgent requirement for people who are having experience > in python. ?If you are interested for this position forward your > updated resume to the sush... at millenniumsoft.com with the details > mention below; > > current ctc: > expected ctc: > notice period: #1: You should post this on the Python jobs board. http://www.python.org/community/jobs/ #2: I know the economy's bad but not everyone is going to apply to every job posting they see. You should include a least a little information about the job. Carl Banks From ldo at geek-central.gen.new_zealand Mon Aug 9 02:57:51 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Aug 2010 18:57:51 +1200 Subject: Python Portability References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: In message , W. eWatson wrote: > Believe me I had no intent of expanding this thread beyond looking for a > straight and simple insight to Python distribution (portability, > whatever) and how to get my partner squared away. The general issue > seems to drifted off on its own accord. ?Drifted off? bullshit. A whole lot of responders have wasted a whole lot of time trying to get to the bottom of your ?one-character change?, and now you try to pretend it wasn?t the issue at all. From nikos.the.gr33k at gmail.com Mon Aug 9 03:07:22 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 00:07:22 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: Now the code looks as follows: ============================= #!/usr/bin/python import re, os, sys id = 0 # unique page_id for currdir, files, dirs in os.walk('test'): for f in files: if f.endswith('php'): # get abs path to filename src_f = join(currdir, f) # open php src file print ( 'reading from %s' % src_f ) f = open(src_f, 'r') src_data = f.read() # read contents of PHP file f.close() # replace tags print ( 'replacing php tags and contents within' ) src_data = re.sub( '', '', src_data ) # add ID print ( 'adding unique page_id' ) src_data = ( '' % id ) + src_data id += 1 # add template variables print ( 'adding counter template variable' ) src_data = src_data.replace('', '

??????? ??????????: %(counter)d ' ) # rename old php file to new with .html extension src_file = src_file.replace('.php', '.html') # open newly created html file for inserting data print ( 'writing to %s' % dest_f ) dest_f = open(src_f, 'w') dest_f.write(src_data) # write contents dest_f.close() I just tried to test it. I created a folder names 'test' in me 'd:\' drive. Then i have put to .php files inside form the original to test if it would work ok for those too files before acting in the whole copy and after in the original project. so i opened a 'cli' form my Win7 and tried D:\>convert.py D:\> Itsjust printed an empty line and nothign else. Why didn't even try to open the folder and fiels within? Syntactically it doesnt ghive me an error! Somehting with os.walk() methos perhaps? From debatem1 at gmail.com Mon Aug 9 03:12:37 2010 From: debatem1 at gmail.com (geremy condra) Date: Mon, 9 Aug 2010 00:12:37 -0700 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On Sun, Aug 8, 2010 at 11:57 PM, Lawrence D'Oliveiro wrote: > In message , W. eWatson wrote: > >> Believe me I had no intent of expanding this thread beyond looking for a >> straight and simple insight to Python distribution (portability, >> whatever) and how to get my partner squared away. The general issue >> seems to drifted off on its own accord. > > ?Drifted off? bullshit. A whole lot of responders have wasted a whole lot of > time trying to get to the bottom of your ?one-character change?, and now you > try to pretend it wasn?t the issue at all. To be fair, it wasn't, little though he knew it. Geremy Condra From rantingrick at gmail.com Mon Aug 9 03:29:19 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 9 Aug 2010 00:29:19 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> Message-ID: <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> On Aug 8, 8:15?pm, Steven D'Aprano wrote: > In Ruby they decided to be more general, so you can define whatever > heredoc you need to quote whatever literal string you need. That's not > bone-headed. Devils Advocate! PS: Man you're irb main was so full of cobweb i could barley see the code... haa... haaaa... hachew!. ;-) From __peter__ at web.de Mon Aug 9 03:38:34 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 09:38:34 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: ????? wrote: > Now the code looks as follows: > for currdir, files, dirs in os.walk('test'): > > for f in files: > > if f.endswith('php'): > > # get abs path to filename > src_f = join(currdir, f) > I just tried to test it. I created a folder names 'test' in me 'd:\' > drive. > Then i have put to .php files inside form the original to test if it > would work ok for those too files before acting in the whole copy and > after in the original project. > > so i opened a 'cli' form my Win7 and tried > > D:\>convert.py > > D:\> > > Itsjust printed an empty line and nothign else. Why didn't even try to > open the folder and fiels within? > Syntactically it doesnt ghive me an error! > Somehting with os.walk() methos perhaps? If there is a folder D:\test and it does contain some PHP files (double- check!) the extension could be upper-case. Try if f.lower().endswith("php"): ... or php_files = fnmatch.filter(files, "*.php") for f in php_files: ... Peter From rantingrick at gmail.com Mon Aug 9 03:56:14 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 9 Aug 2010 00:56:14 -0700 (PDT) Subject: Python Portability References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On Aug 8, 8:03?am, "W. eWatson" wrote: > I'm done here. Well thats just great, now how will we ever know what the one char change was. Hmm. >>> a = 'somestring' >>> -a Traceback (most recent call last): File "", line 1, in -a TypeError: bad operand type for unary -: 'str' Go figure! From ldo at geek-central.gen.new_zealand Mon Aug 9 04:08:30 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Aug 2010 20:08:30 +1200 Subject: os.unlink on Windows References: <4c5eb146$0$28663$c3e8da3@news.astraweb.com> Message-ID: In message , Shambhu wrote: > It is working now after using double backslash in pathname. Might be simpler to use slashes. From steve at REMOVE-THIS-cybersource.com.au Mon Aug 9 04:21:51 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 08:21:51 GMT Subject: Python -Vs- Ruby: A regexp match to the death! References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> Message-ID: <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> On Mon, 09 Aug 2010 00:29:19 -0700, rantingrick wrote: > On Aug 8, 8:15?pm, Steven D'Aprano cybersource.com.au> wrote: > >> In Ruby they decided to be more general, so you can define whatever >> heredoc you need to quote whatever literal string you need. That's not >> bone-headed. > > Devils Advocate! > > PS: Man you're irb main was so full of cobweb i could barley see the > code... haa... haaaa... hachew!. ;-) irb's default prompt is a bit too verbose for my tastes, but Python allows you to customise its prompt too. You'll often see people here posting copy/pastes with a customised prompt, so obviously some people like that sort of thing. Me, my biggest gripe with the interactive interpreter is that using >>> as a prompt clashes with > as the standard quoting character in email and news, but Guido has refused to even consider changing it. And that it's quite finicky about blank lines between methods and inside functions. Makes it hard to paste code directly into the interpreter. And that pasting doesn't strip out any leading prompts. It needs a good doctest mode. -- Steven From nikos.the.gr33k at gmail.com Mon Aug 9 04:22:04 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 01:22:04 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> On 9 ???, 10:38, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > Now the code looks as follows: > > for currdir, files, dirs in os.walk('test'): > > > ? ? ? ? for f in files: > > > ? ? ? ? ? ? ? ? if f.endswith('php'): > > > ? ? ? ? ? ? ? ? ? ? ? ? # get abs path to filename > > ? ? ? ? ? ? ? ? ? ? ? ? src_f = join(currdir, f) > > I just tried to test it. I created a folder names 'test' in me 'd:\' > > drive. > > Then i have put to .php files inside form the original to test if it > > would work ok for those too files before acting in the whole copy and > > after in the original project. > > > so i opened a 'cli' form my Win7 and tried > > > D:\>convert.py > > > D:\> > > > Itsjust printed an empty line and nothign else. Why didn't even try to > > open the folder and fiels within? > > Syntactically it doesnt ghive me an error! > > Somehting with os.walk() methos perhaps? > > If there is a folder D:\test and it does contain some PHP files (double- > check!) the extension could be upper-case. Try > > if f.lower().endswith("php"): ... > > or > > php_files = fnmatch.filter(files, "*.php") > for f in php_files: ... > > Peter The extension is in in lower case. folder is there, php files is there, i dont know why it doesnt't want to go into the d:\test to find them. Thast one problem. The other one is: i made the code simpler by specifying the filename my self. ========================= # get abs path to filename src_f = 'd:\\test\\index.php' # open php src file print ( 'reading from %s' % src_f ) f = open(src_f, 'r') src_data = f.read() # read contents of PHP file f.close() ========================= but although ti nwo finds the fiel i egt this error in 'cli': D:\>aconvert.py reading from d:\test\index.php Traceback (most recent call last): File "D:\aconvert.py", line 16, in src_data = f.read() # read contents of PHP file File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position 321: char acter maps to Somethign with the damn encodings again!! From __peter__ at web.de Mon Aug 9 04:45:37 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 10:45:37 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> Message-ID: ????? wrote: > On 9 ???, 10:38, Peter Otten <__pete... at web.de> wrote: >> ????? wrote: >> > Now the code looks as follows: >> > for currdir, files, dirs in os.walk('test'): >> >> > for f in files: >> >> > if f.endswith('php'): >> >> > # get abs path to filename >> > src_f = join(currdir, f) >> > I just tried to test it. I created a folder names 'test' in me 'd:\' >> > drive. >> > Then i have put to .php files inside form the original to test if it >> > would work ok for those too files before acting in the whole copy and >> > after in the original project. >> >> > so i opened a 'cli' form my Win7 and tried >> >> > D:\>convert.py >> >> > D:\> >> >> > Itsjust printed an empty line and nothign else. Why didn't even try to >> > open the folder and fiels within? >> > Syntactically it doesnt ghive me an error! >> > Somehting with os.walk() methos perhaps? >> >> If there is a folder D:\test and it does contain some PHP files (double- >> check!) the extension could be upper-case. Try >> >> if f.lower().endswith("php"): ... >> >> or >> >> php_files = fnmatch.filter(files, "*.php") >> for f in php_files: ... >> >> Peter > > The extension is in in lower case. folder is there, php files is > there, i dont know why it doesnt't want to go into the d:\test to find > them. > > Thast one problem. > > The other one is: > > i made the code simpler by specifying the filename my self. > > ========================= > # get abs path to filename > src_f = 'd:\\test\\index.php' > > # open php src file > print ( 'reading from %s' % src_f ) > f = open(src_f, 'r') > src_data = f.read() # read contents of PHP file > f.close() > ========================= > > but although ti nwo finds the fiel i egt this error in 'cli': > > D:\>aconvert.py > reading from d:\test\index.php > Traceback (most recent call last): > File "D:\aconvert.py", line 16, in > src_data = f.read() # read contents of PHP file > File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode > return codecs.charmap_decode(input,self.errors,decoding_table)[0] > UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position > 321: char > acter maps to > > Somethign with the damn encodings again!! Hmm, at one point in this thread you switched from Python 2.x to Python 3.2. There are a lot of subtle and not so subtle differences between 2.x and 3.x, and I recommend that you stick to one while you are still in newbie mode. If you want to continue to use 3.x I recommend that you at least use the stable 3.1 version. Now one change from Python 2 to 3 is that open(filename, "r") gives you a beast that is unicode-aware and assumes that the file is encoded in utf-8 unless you tell it otherwise with open(..., encoding=whatever). So what is the charset used for your index.php? Peter From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 9 05:04:40 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Aug 2010 11:04:40 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <8c3r45FsveU1@mid.individual.net> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <4C5C562A.90702@sschwarzer.net> <8c3r45FsveU1@mid.individual.net> Message-ID: <4c5fc4a7$0$23059$426a74cc@news.free.fr> Gregory Ewing a ?crit : > Ethan Furman wrote: > >> Instead of using 'is' use '=='. Maybe not as cute, but definitely >> more robust! > > It's also just as efficient if you use strings that > resemble identifiers, because they will be interned, Remember : this IS an implementation detail. From fetchinson at googlemail.com Mon Aug 9 05:24:31 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 9 Aug 2010 11:24:31 +0200 Subject: Smith-Waterman Algorithm in Python In-Reply-To: References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> <4C5D52BE.302@gmaiil.com> Message-ID: >>> Every one of the first 20 entries is either the OP questions or your >>> reply. >> >> And you think it was there before the OP sent his message? >> Oh wait, did you just invent a time machine? :) >> >>> Daniel - you are no help at all, and no funny. >> >> Actually, I'm damn funny! :) > > I have noticed before that people who post without searching first end > up polluting subsequent searches. Google obviously boosts the > rank of recent pages. This is one of the three major reasons stackoverflow and friends were developed. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From aimeixu at amazon.com Mon Aug 9 05:33:52 2010 From: aimeixu at amazon.com (aimeixu) Date: Mon, 9 Aug 2010 17:33:52 +0800 Subject: how to change a string into dictionary Message-ID: <4C5FCB80.7010701@amazon.com> Hi, I am newbie for python ,Here is my question: a = "{'a':'1','b':'2'}" how to change a into a dictionary ,says, a = {'a':'1','b':'2'} Thanks a lot .Really need help. From blur959 at hotmail.com Mon Aug 9 05:44:11 2010 From: blur959 at hotmail.com (blur959) Date: Mon, 9 Aug 2010 02:44:11 -0700 (PDT) Subject: simple renaming files program Message-ID: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Hi, all, I am working on a simple program that renames files based on the directory the user gives, the names the user searched and the names the user want to replace. However, I encounter some problems. When I try running the script, when it gets to the os.rename part, there will be an error. The error is : n = os.rename(file, file.replace(s, r)) WindowsError: [Error 2] The system cannot find the file specified I attached my code below, hope you guys can help me, Thanks! import os directory = raw_input("input file directory") s = raw_input("search for name") r = raw_input("replace name") for file in os.listdir(directory): n = os.rename(file, file.replace(s, r)) print n From nikos.the.gr33k at gmail.com Mon Aug 9 05:46:26 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 02:46:26 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> Message-ID: <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> On 9 ???, 11:45, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > On 9 ???, 10:38, Peter Otten <__pete... at web.de> wrote: > >> ????? wrote: > >> > Now the code looks as follows: > >> > for currdir, files, dirs in os.walk('test'): > > >> > for f in files: > > >> > if f.endswith('php'): > > >> > # get abs path to filename > >> > src_f = join(currdir, f) > >> > I just tried to test it. I created a folder names 'test' in me 'd:\' > >> > drive. > >> > Then i have put to .php files inside form the original to test if it > >> > would work ok for those too files before acting in the whole copy and > >> > after in the original project. > > >> > so i opened a 'cli' form my Win7 and tried > > >> > D:\>convert.py > > >> > D:\> > > >> > Itsjust printed an empty line and nothign else. Why didn't even try to > >> > open the folder and fiels within? > >> > Syntactically it doesnt ghive me an error! > >> > Somehting with os.walk() methos perhaps? > > >> If there is a folder D:\test and it does contain some PHP files (double- > >> check!) the extension could be upper-case. Try > > >> if f.lower().endswith("php"): ... > > >> or > > >> php_files = fnmatch.filter(files, "*.php") > >> for f in php_files: ... > > >> Peter > > > The extension is in in lower case. folder is there, php files is > > there, i dont know why it doesnt't want to go into the d:\test to find > > them. > > > Thast one problem. > > > The other one is: > > > i made the code simpler by specifying the filename my self. > > > ========================= > > # get abs path to filename > > src_f = 'd:\\test\\index.php' > > > # open php src file > > print ( 'reading from %s' % src_f ) > > f = open(src_f, 'r') > > src_data = f.read() ? ? ? ? ? ? ? ?# read contents of PHP file > > f.close() > > ========================= > > > but ?although ti nwo finds the fiel i egt this error in 'cli': > > > D:\>aconvert.py > > reading from d:\test\index.php > > Traceback (most recent call last): > > ? File "D:\aconvert.py", line 16, in > > ? ? src_data = f.read() ? ? ? ? # read contents of PHP file > > ? File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode > > ? ? return codecs.charmap_decode(input,self.errors,decoding_table)[0] > > UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position > > 321: char > > acter maps to > > > Somethign with the damn encodings again!! > > Hmm, at one point in this thread you switched from Python 2.x to Python 3.2. > There are a lot of subtle and not so subtle differences between 2.x and 3.x, > and I recommend that you stick to one while you are still in newbie mode. > > If you want to continue to use 3.x I recommend that you at least use the > stable 3.1 version. > > Now one change from Python 2 to 3 is that open(filename, "r") gives you a > beast that is unicode-aware and assumes that the file is encoded in utf-8 > unless you tell it otherwise with open(..., encoding=whatever). So what is > the charset used for your index.php? > > Peter Yes yesterday i switched to Python 3.2 Peter. When i open index.php within Notapad++ it says its in utf-8 without BOM and it contains inside exepect form english chars , greek cjhars as well fro printing. The file was made by my client in dreamweaver. So since its utf-8 what the problem of opening it? From anand.shashwat at gmail.com Mon Aug 9 05:53:38 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 9 Aug 2010 15:23:38 +0530 Subject: how to change a string into dictionary In-Reply-To: <4C5FCB80.7010701@amazon.com> References: <4C5FCB80.7010701@amazon.com> Message-ID: On Mon, Aug 9, 2010 at 3:03 PM, aimeixu wrote: > Hi, > I am newbie for python ,Here is my question: > a = "{'a':'1','b':'2'}" > how to change a into a dictionary ,says, a = {'a':'1','b':'2'} > Thanks a lot .Really need help. > Parse the string and re-create the dictionary. >>> s = "{'a':'1','b':'2'}" >>> ds = {} >>> for i in s.strip('{}').split(','): ... key, val = i.split(':') ... ds[key.strip("'")] = val.strip("'") ... >>> ds {'a': '1', 'b': '2'} >>> type(ds) > -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Aug 9 06:01:37 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 9 Aug 2010 03:01:37 -0700 Subject: simple renaming files program In-Reply-To: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: On Mon, Aug 9, 2010 at 2:44 AM, blur959 wrote: > Hi, all, I am working on a simple program that renames files based on > the directory the user gives, the names the user searched and the > names the user want to replace. However, I encounter some problems. > When I try running the script, when it gets to the os.rename part, > there will be an error. The error is : > ?n = os.rename(file, file.replace(s, r)) > WindowsError: [Error 2] The system cannot find the file specified > > I attached my code below, hope you guys can help me, Thanks! > > import os > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for file in os.listdir(directory): > ? ?n = os.rename(file, file.replace(s, r)) > ? ?print n os.rename() takes paths that are absolute (or possibly relative to the cwd), not paths that are relative to some arbitrary directory (as returned by os.listdir()). Also, never name a variable "file"; it shadows the name of the built-in type. Hence (untested): from os import listdir, rename from os.path import isdir, join directory = raw_input("input file directory") s = raw_input("search for name") r = raw_input("replace name") for filename in listdir(directory): path = join(directory, filename) #paste the directory name on if isdir(path): continue #skip subdirectories (they're not files) newname = filename.replace(s, r) newpath = join(directory, newname) n = rename(path, newpath) print n Cheers, Chris -- http://blog.rebertia.com From anand.shashwat at gmail.com Mon Aug 9 06:01:37 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 9 Aug 2010 15:31:37 +0530 Subject: simple renaming files program In-Reply-To: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: On Mon, Aug 9, 2010 at 3:14 PM, blur959 wrote: > Hi, all, I am working on a simple program that renames files based on > the directory the user gives, the names the user searched and the > names the user want to replace. However, I encounter some problems. > When I try running the script, when it gets to the os.rename part, > there will be an error. The error is : > n = os.rename(file, file.replace(s, r)) > WindowsError: [Error 2] The system cannot find the file specified > This is because the file does not exist. > > I attached my code below, hope you guys can help me, Thanks! > > import os > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for file in os.listdir(directory): > n = os.rename(file, file.replace(s, r)) > print n > Tried this on my system, works. >>> [shutil.move(i, r) for i in os.listdir(directory) if i==s] -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From eckhardt at satorlaser.com Mon Aug 9 06:04:45 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 09 Aug 2010 12:04:45 +0200 Subject: how to change a string into dictionary References: Message-ID: aimeixu wrote: > a = "{'a':'1','b':'2'}" > how to change a into a dictionary ,says, a = {'a':'1','b':'2'} You could evaluate it as regular Python code, using "exec": res = {} exec("a={'a':'1'}", res) print res['a'] However, if this is input from a file or the user, be aware that this opens loopholes for executing _any_ code, so you should only exec code from sources you can trust. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From __peter__ at web.de Mon Aug 9 06:06:31 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:06:31 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> Message-ID: ????? wrote: > On 9 ???, 11:45, Peter Otten <__pete... at web.de> wrote: >> ????? wrote: >> > On 9 ???, 10:38, Peter Otten <__pete... at web.de> wrote: >> >> ????? wrote: >> >> > Now the code looks as follows: >> >> > for currdir, files, dirs in os.walk('test'): >> >> >> > for f in files: >> >> >> > if f.endswith('php'): >> >> >> > # get abs path to filename >> >> > src_f = join(currdir, f) >> >> > I just tried to test it. I created a folder names 'test' in me 'd:\' >> >> > drive. >> >> > Then i have put to .php files inside form the original to test if it >> >> > would work ok for those too files before acting in the whole copy >> >> > and after in the original project. >> >> >> > so i opened a 'cli' form my Win7 and tried >> >> >> > D:\>convert.py >> >> >> > D:\> >> >> >> > Itsjust printed an empty line and nothign else. Why didn't even try >> >> > to open the folder and fiels within? >> >> > Syntactically it doesnt ghive me an error! >> >> > Somehting with os.walk() methos perhaps? >> >> >> If there is a folder D:\test and it does contain some PHP files >> >> (double- check!) the extension could be upper-case. Try >> >> >> if f.lower().endswith("php"): ... >> >> >> or >> >> >> php_files = fnmatch.filter(files, "*.php") >> >> for f in php_files: ... >> >> >> Peter >> >> > The extension is in in lower case. folder is there, php files is >> > there, i dont know why it doesnt't want to go into the d:\test to find >> > them. >> >> > Thast one problem. >> >> > The other one is: >> >> > i made the code simpler by specifying the filename my self. >> >> > ========================= >> > # get abs path to filename >> > src_f = 'd:\\test\\index.php' >> >> > # open php src file >> > print ( 'reading from %s' % src_f ) >> > f = open(src_f, 'r') >> > src_data = f.read() # read contents of PHP file >> > f.close() >> > ========================= >> >> > but although ti nwo finds the fiel i egt this error in 'cli': >> >> > D:\>aconvert.py >> > reading from d:\test\index.php >> > Traceback (most recent call last): >> > File "D:\aconvert.py", line 16, in >> > src_data = f.read() # read contents of PHP file >> > File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode >> > return codecs.charmap_decode(input,self.errors,decoding_table)[0] >> > UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position >> > 321: char >> > acter maps to >> >> > Somethign with the damn encodings again!! >> >> Hmm, at one point in this thread you switched from Python 2.x to Python >> 3.2. There are a lot of subtle and not so subtle differences between 2.x >> and 3.x, and I recommend that you stick to one while you are still in >> newbie mode. >> >> If you want to continue to use 3.x I recommend that you at least use the >> stable 3.1 version. >> >> Now one change from Python 2 to 3 is that open(filename, "r") gives you a >> beast that is unicode-aware and assumes that the file is encoded in utf-8 >> unless you tell it otherwise with open(..., encoding=whatever). So what >> is the charset used for your index.php? >> >> Peter > > > Yes yesterday i switched to Python 3.2 Peter. > > When i open index.php within Notapad++ it says its in utf-8 without > BOM and it contains inside exepect form english chars , greek cjhars > as well fro printing. > > The file was made by my client in dreamweaver. > > So since its utf-8 what the problem of opening it? Python says it's not, and I tend to believe it. You can open the file with open(..., errors="replace") but you will lose data (which is already garbled, anyway). Again: in the unlikely case that Python is causing your problem -- you do understand what an alpha version is? Peter From eckhardt at satorlaser.com Mon Aug 9 06:11:06 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 09 Aug 2010 12:11:06 +0200 Subject: simple renaming files program References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: blur959 wrote: > Hi, all, I am working on a simple program that renames files based on > the directory the user gives, the names the user searched and the > names the user want to replace. However, I encounter some problems. > When I try running the script, when it gets to the os.rename part, > there will be an error. The error is : > n = os.rename(file, file.replace(s, r)) > WindowsError: [Error 2] The system cannot find the file specified I see that you are using os.listdir(), so the files should be present, but still, I would consider checking that when I encounter this error. > I attached my code below, hope you guys can help me, Thanks! > > import os > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for file in os.listdir(directory): > n = os.rename(file, file.replace(s, r)) > print n Looks good so far, but what are the values in s, r, file and the result of file.replace(s, r) for the case that fails? Also, as a side note, help(os.rename) doesn't document any returnvalue to store in n, but that doesn't seem to be the problem. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From clp2 at rebertia.com Mon Aug 9 06:13:01 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 9 Aug 2010 03:13:01 -0700 Subject: how to change a string into dictionary In-Reply-To: References: <4C5FCB80.7010701@amazon.com> Message-ID: On Mon, Aug 9, 2010 at 2:53 AM, Shashwat Anand wrote: > On Mon, Aug 9, 2010 at 3:03 PM, aimeixu wrote: >> Hi, >> I am newbie for python ,Here is my question: >> a = "{'a':'1','b':'2'}" >> how to change a into a dictionary ,says, a = {'a':'1','b':'2'} >> Thanks a lot .Really need help. > > Parse the string and re-create the dictionary. >>>> s =?"{'a':'1','b':'2'}" >>>> ds = {} >>>> for i in s.strip('{}').split(','): > ... ? ? key, val = i.split(':') > ... ? ? ds[key.strip("'")] = val.strip("'") Just for the record, that'll break if the dictionary entries have embedded commas or colons. eval() will handle such cases correctly and probably* run faster, but is obviously insecure. If you have control of both ends of the serialization process, you might consider using the `json` or `pickle` std lib modules instead. Cheers, Chris -- *Do a benchmark obviously. http://blog.rebertia.com From __peter__ at web.de Mon Aug 9 06:19:19 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:19:19 +0200 Subject: simple renaming files program References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: Chris Rebert wrote: > Hence (untested): > from os import listdir, rename > from os.path import isdir, join > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for filename in listdir(directory): > path = join(directory, filename) #paste the directory name on > if isdir(path): continue #skip subdirectories (they're not files) > newname = filename.replace(s, r) > newpath = join(directory, newname) > n = rename(path, newpath) > print n Warning: I don't remember how Windows handles this, but unix will happily perform os.rename("alpha/alpha.txt", "beta/beta.txt") and overwrite beta/beta.txt with alpha/alpha.txt. I'd rather modify the filename before joining it with the directory. newname = filename.replace(s, r) if newname != filename: path = os.path.join(directory, filename) newpath = os.path.join(directory, newname) os.rename(path, newpath) If you don't you run the risk of operating in unexpected directories. Peter From dmitrey.kroshko at scipy.org Mon Aug 9 06:26:04 2010 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 9 Aug 2010 03:26:04 -0700 (PDT) Subject: Create child class of Python dict with modified values Message-ID: <9f567611-6031-45fa-94d6-af85ebf1f655@p7g2000yqa.googlegroups.com> hi all, suppose I have defined a child class of Python dict, currently it constructor looks like that: def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) #(+some more insufficient code) Constructor should be capable of calling with either any way Python dict is constructed or with a Python dict instance to be derived from; calculations speed is important. So it works well for now, but I want __init__ to set modified values, like this: values_of_the_dict = [some_func(elem) for elem in self.values()] How this could be done? Thank you in advance, Dmitrey. From targetsmart at gmail.com Mon Aug 9 06:29:38 2010 From: targetsmart at gmail.com (targetsmart) Date: Mon, 9 Aug 2010 03:29:38 -0700 (PDT) Subject: dumping generator Message-ID: Right now if I want to dump the contents of a generator object I use , a snip from a bigger block of code.. try: while gen: print gen.next() except StopIteration: print "Done" else: raise is there a much simpler way ? like for printing list we do list = range(10) print list would print [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] From nikos.the.gr33k at gmail.com Mon Aug 9 06:34:30 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 03:34:30 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> Message-ID: <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> On 9 ???, 13:06, Peter Otten <__pete... at web.de> wrote: > > So since its utf-8 what the problem of opening it? > > Python says it's not, and I tend to believe it. You are right! I tried to do the same exact openign via IDLE enviroment and i goth the encoding of the file from there! >>> open("d:\\test\\index.php" ,'r') <_io.TextIOWrapper name='d:\\test\\index.php' encoding='cp1253'> Thats why in the error in my previous post it said File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode it tried to use the cp1253 encoding. But now sicne Python as we see can undestand the nature of the encoding what causing it not to open the file? From __peter__ at web.de Mon Aug 9 06:38:52 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:38:52 +0200 Subject: Create child class of Python dict with modified values References: <9f567611-6031-45fa-94d6-af85ebf1f655@p7g2000yqa.googlegroups.com> Message-ID: dmitrey wrote: > hi all, > suppose I have defined a child class of Python dict, currently it > constructor looks like that: > def __init__(self, *args, **kwargs): > dict.__init__(self, *args, **kwargs) > #(+some more insufficient code) > > Constructor should be capable of calling with either any way Python > dict is constructed or with a Python dict instance to be derived from; > calculations speed is important. > > So it works well for now, but I want __init__ to set modified values, > like this: > values_of_the_dict = [some_func(elem) for elem in self.values()] > > How this could be done? >>> class D(dict): ... def __init__(self, *args, **kw): ... if args: ... args = ((k, v.upper()) for k, v in args[0]), ... if kw: ... for k in kw: kw[k] = 10*kw[k] ... dict.__init__(self, *args, **kw) ... >>> D(["ab", "cd"], e="f") {'a': 'B', 'c': 'D', 'e': 'ffffffffff'} Replace v.upper() and 10*kw[k] with the appropriate some_func() calls. Personally I would apply the function before passing the data to the dict subclass. Peter From __peter__ at web.de Mon Aug 9 06:40:47 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:40:47 +0200 Subject: dumping generator References: Message-ID: targetsmart wrote: > Right now if I want to dump the contents of a generator object I use , > a snip from a bigger block of code.. > > try: > while gen: print gen.next() > except StopIteration: > print "Done" > else: > raise > > is there a much simpler way ? Indeed there is: for item in gen: print item print "Done" Peter From dmitrey.kroshko at scipy.org Mon Aug 9 06:44:36 2010 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 9 Aug 2010 03:44:36 -0700 (PDT) Subject: Create child class of Python dict with modified values References: <9f567611-6031-45fa-94d6-af85ebf1f655@p7g2000yqa.googlegroups.com> Message-ID: <7a7c0b96-ffae-48a5-a6f2-5999c56f5fad@t20g2000yqa.googlegroups.com> On Aug 9, 1:38?pm, Peter Otten <__pete... at web.de> wrote: > dmitrey wrote: > > hi all, > > suppose I have defined a child class of Python dict, currently it > > constructor looks like that: > > ? ? def __init__(self, *args, **kwargs): > > ? ? ? ? dict.__init__(self, *args, **kwargs) > > ? ? ? ? #(+some more insufficient code) > > > Constructor should be capable of calling with either any way Python > > dict is constructed or with a Python dict instance to be derived from; > > calculations speed is important. > > > So it works well for now, but I want __init__ to set modified values, > > like this: > > values_of_the_dict = [some_func(elem) for elem in self.values()] > > > How this could be done? > >>> class D(dict): > > ... ? ? def __init__(self, *args, **kw): > ... ? ? ? ? ? ? if args: > ... ? ? ? ? ? ? ? ? ? ? args = ((k, v.upper()) for k, v in args[0]), > ... ? ? ? ? ? ? if kw: > ... ? ? ? ? ? ? ? ? ? ? for k in kw: kw[k] = 10*kw[k] > ... ? ? ? ? ? ? dict.__init__(self, *args, **kw) > ...>>> D(["ab", "cd"], e="f") > > {'a': 'B', 'c': 'D', 'e': 'ffffffffff'} > > Replace v.upper() and 10*kw[k] with the appropriate some_func() calls. OK, thank you. > Personally I would apply the function before passing the data to the dict > subclass. It's impossible for the situation in hand. D. From eckhardt at satorlaser.com Mon Aug 9 06:44:38 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 09 Aug 2010 12:44:38 +0200 Subject: dumping generator References: Message-ID: targetsmart wrote: > Right now if I want to dump the contents of a generator object I use , > a snip from a bigger block of code.. > > try: > while gen: print gen.next() > except StopIteration: > print "Done" > else: > raise > > is there a much simpler way ? Why not something like this: for i in gen: print i > like for printing list we do > list = range(10) > print list > would print > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] You could coerce the thing into a list: gen = xrange(10) print list(gen) :) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From __peter__ at web.de Mon Aug 9 06:47:22 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:47:22 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> Message-ID: ????? wrote: > On 9 ???, 13:06, Peter Otten <__pete... at web.de> wrote: > >> > So since its utf-8 what the problem of opening it? >> >> Python says it's not, and I tend to believe it. > > You are right! > > I tried to do the same exact openign via IDLE enviroment and i goth > the encoding of the file from there! > >>>> open("d:\\test\\index.php" ,'r') > <_io.TextIOWrapper name='d:\\test\\index.php' encoding='cp1253'> > > Thats why in the error in my previous post it said > File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode > it tried to use the cp1253 encoding. > > But now sicne Python as we see can undestand the nature of the > encoding what causing it not to open the file? It doesn't. You have to tell. *If* the file uses cp1253 you can open it with open(..., encoding="cp1253") Note that if the file is not in cp1253 python will still happily open it as long as it doesn't contain the following bytes: >>> for i in range(256): ... try: chr(i).decode("cp1253") and None ... except: print i ... 129 136 138 140 141 142 143 144 152 154 156 157 158 159 170 210 255 Peter From blur959 at hotmail.com Mon Aug 9 06:48:37 2010 From: blur959 at hotmail.com (blur959) Date: Mon, 9 Aug 2010 03:48:37 -0700 (PDT) Subject: simple renaming files program References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: On Aug 9, 6:01?pm, Chris Rebert wrote: > On Mon, Aug 9, 2010 at 2:44 AM, blur959 wrote: > > Hi, all, I am working on a simple program that renames files based on > > the directory the user gives, the names the user searched and the > > names the user want to replace. However, I encounter some problems. > > When I try running the script, when it gets to the os.rename part, > > there will be an error. The error is : > > ?n = os.rename(file, file.replace(s, r)) > > WindowsError: [Error 2] The system cannot find the file specified > > > I attached my code below, hope you guys can help me, Thanks! > > > import os > > directory = raw_input("input file directory") > > s = raw_input("search for name") > > r = raw_input("replace name") > > > for file in os.listdir(directory): > > ? ?n = os.rename(file, file.replace(s, r)) > > ? ?print n > > os.rename() takes paths that are absolute (or possibly relative to the > cwd), not paths that are relative to some arbitrary directory (as > returned by os.listdir()). > Also, never name a variable "file"; it shadows the name of the built-in type. > > Hence (untested): > from os import listdir, rename > from os.path import isdir, join > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for filename in listdir(directory): > ? ? path = join(directory, filename) #paste the directory name on > ? ? if isdir(path): continue #skip subdirectories (they're not files) > ? ? newname = filename.replace(s, r) > ? ? newpath = join(directory, newname) > ? ? n = rename(path, newpath) > ? ? print n > > Cheers, > Chris > --http://blog.rebertia.com Thanks, they worked! From not_my_email at sadf.com Mon Aug 9 07:12:45 2010 From: not_my_email at sadf.com (Vedran) Date: Mon, 9 Aug 2010 11:12:45 +0000 (UTC) Subject: Decorators without function Message-ID: Hello! Is it possible to apply a decorator on a block of code, without defining a function that decorator is applied to. I have to generate a lot of similar graphs. For that reason I use plot_decorator to perform usual figure setup(outfile, legend, x_label, y_label and so on), and pylab.plot commands to do the actual plotting. Current solution: @plot_decorator(fig_params1) def plt(): pylab.plot(..first graph data...) pylab.plot(..second graph data..) plt() Is it possible to apply decorator only to the body of plt (several pylab.plot commands) without actually defining this function, because I use it only once, right after the definition? From __peter__ at web.de Mon Aug 9 07:37:14 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 13:37:14 +0200 Subject: Decorators without function References: Message-ID: Vedran wrote: > Hello! > > Is it possible to apply a decorator on a block of code, without defining > a function that decorator is applied to. You can only decorate functions or classes. > I have to generate a lot of similar graphs. For that reason I use > plot_decorator to perform usual figure setup(outfile, legend, x_label, > y_label and so on), and pylab.plot commands to do the actual plotting. > > Current solution: > > @plot_decorator(fig_params1) > def plt(): > pylab.plot(..first graph data...) > pylab.plot(..second graph data..) > plt() > > Is it possible to apply decorator only to the body of plt (several > pylab.plot commands) without actually defining this function, because I > use it only once, right after the definition? I have a hunch that a contextmanager is a better match for your requirements, see http://docs.python.org/library/contextlib.html#contextlib.contextmanager Peter From saeed.gnu at gmail.com Mon Aug 9 07:41:23 2010 From: saeed.gnu at gmail.com (saeed.gnu) Date: Mon, 9 Aug 2010 04:41:23 -0700 (PDT) Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: "x is y" means "id(y) == id(y)" "x is not y" means "id(x) != id(x)" "x is not None" means "id(x) != id(None)" "x is not None" is a really silly statement!! because id(None) and id of any constant object is not predictable! I don't know whay people use "is" instead of "==". you should write "if x!=None" instead of "x is not None" From sschwarzer at sschwarzer.net Mon Aug 9 07:42:12 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 09 Aug 2010 13:42:12 +0200 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> Message-ID: <4C5FE994.1040103@sschwarzer.net> Hi Steven, On 2010-08-09 10:21, Steven D'Aprano wrote: > And that it's quite finicky about blank lines between methods and inside > functions. Makes it hard to paste code directly into the interpreter. > > And that pasting doesn't strip out any leading prompts. It needs a good > doctest mode. ipython [1] should help here: IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: %paste? Type: Magic function Base Class: String Form: > Namespace: IPython internal File: /usr/lib/pymodules/python2.6/IPython/Magic.py Definition: %paste(self, parameter_s='') Docstring: Allows you to paste & execute a pre-formatted code block from clipboard. The text is pulled directly from the clipboard without user intervention. The block is dedented prior to execution to enable execution of method definitions. '>' and '+' characters at the beginning of a line are ignored, to allow pasting directly from e-mails, diff files and doctests (the '...' continuation prompt is also stripped). The executed block is also assigned to variable named 'pasted_block' for later editing with '%edit pasted_block'. You can also pass a variable name as an argument, e.g. '%paste foo'. This assigns the pasted block to variable 'foo' as string, without dedenting or executing it (preceding >>> and + is still stripped) '%paste -r' re-executes the block previously entered by cpaste. IPython statements (magics, shell escapes) are not supported (yet). See also -------- cpaste: manually paste code into terminal until you mark its end. Unfortunatey, when I enter In [2]: %paste at the prompt it gives me (before I pasted anything) In [2]: %paste ------------------------------------------------------------ File "", line 1 http://pypi.python.org/pypi/ipython/0.10 ^ SyntaxError: invalid syntax So far, I couldn't find anything on the net on this. [1] http://pypi.python.org/pypi/ipython Stefan From alex.lavoro.propio at gmail.com Mon Aug 9 08:10:19 2010 From: alex.lavoro.propio at gmail.com (Alex Barna) Date: Mon, 9 Aug 2010 05:10:19 -0700 (PDT) Subject: GUI automation tool (windows) Message-ID: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> I know that this question has been asked for several times, but it surprises that there is no tool under very active development and the community activities are very low (mailing list posts). All the tools listed in: http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#GUITestingTools Comparing with AutoIt (www.autoitscript.com), it has tens to hundreds of posts everyday. AutoIt uses a proprietary BASIC -like language, and to be honest, I don't like it and I prefer a Pythonic solution. pywinauto seems to be the best choice but the community has been very low also. The same happens in pyguiunit, pyAA, WATSUP, all development seem to be ceased. So what happens to this field (Windows GUI automation) ? From saeed.gnu at gmail.com Mon Aug 9 08:11:11 2010 From: saeed.gnu at gmail.com (saeed.gnu) Date: Mon, 9 Aug 2010 05:11:11 -0700 (PDT) Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On Aug 9, 3:41?pm, "saeed.gnu" wrote: > "x is y" ? ? ? ? ?means ? "id(y) == id(y)" > "x is not y" ? ? ?means ? "id(x) != id(x)" > "x is not None" ? means ? "id(x) != id(None)" > > "x is not None" ?is a really silly statement!! because id(None) and id > of any constant object is not predictable! I don't know whay people > use "is" instead of "==". you should write "if x!=None" instead of "x > is not None" Although small objects are unique in the memory (with a unique id) and using "is" works ok, but that's not logical to compare id's when we actually want to compare values! From saeed.gnu at gmail.com Mon Aug 9 09:00:03 2010 From: saeed.gnu at gmail.com (saeed.gnu) Date: Mon, 9 Aug 2010 06:00:03 -0700 (PDT) Subject: Python "why" questions References: Message-ID: <2165a843-888d-40de-8033-e871c7699d5f@x25g2000yqj.googlegroups.com> > > 1) ?Why do Python lists start with element [0], instead of element > > [1]? ?"Common sense" would seem to suggest that lists should start > > with [1]. ? Because Zero is the neutral element of addition operation. And indexes (and all adresses in computing) involve with addition much more than multiplication! That's too clear i think and that's silly to use One as first index of arrays/lists in a programming language! From jrmy.lnrd at gmail.com Mon Aug 9 09:18:35 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Mon, 9 Aug 2010 06:18:35 -0700 (PDT) Subject: Regular expression issue References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> On Aug 8, 7:34?pm, Tim Chase wrote: > On 08/08/10 17:20, genxtech wrote: > > > if re.search(search_string, in_string) != None: > > While the other responses have addressed some of the big issues, > it's also good to use > > ? ?if thing_to_test is None: > > or > > ? ?if thing_to_test is not None: > > instead of "== None" or "!= None". > > -tkc I would like to thank all of you for your responses. I understand what the regular expression means, and am aware of the double negative nature of the test. I guess what I am really getting at is why the last test returns a value of None, and even when using the syntax suggested in this quoted solution, the code for the last test is doing the opposite of the previous 2 tests that also returned a value of None. I hope this makes sense and clarifies what I am trying to ask. Thanks From jrmy.lnrd at gmail.com Mon Aug 9 09:18:35 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Mon, 9 Aug 2010 06:18:35 -0700 (PDT) Subject: Regular expression issue References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> On Aug 8, 7:34?pm, Tim Chase wrote: > On 08/08/10 17:20, genxtech wrote: > > > if re.search(search_string, in_string) != None: > > While the other responses have addressed some of the big issues, > it's also good to use > > ? ?if thing_to_test is None: > > or > > ? ?if thing_to_test is not None: > > instead of "== None" or "!= None". > > -tkc I would like to thank all of you for your responses. I understand what the regular expression means, and am aware of the double negative nature of the test. I guess what I am really getting at is why the last test returns a value of None, and even when using the syntax suggested in this quoted solution, the code for the last test is doing the opposite of the previous 2 tests that also returned a value of None. I hope this makes sense and clarifies what I am trying to ask. Thanks From mrmakent at cox.net Mon Aug 9 09:19:23 2010 From: mrmakent at cox.net (Mike Kent) Date: Mon, 9 Aug 2010 06:19:23 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: Message-ID: <8fa1a70c-c40b-40fd-8dc7-2cb155fbc8b1@l6g2000yqb.googlegroups.com> On Aug 8, 8:43?pm, rantingrick wrote: > Hello folks, > > You all know i been forced to use Ruby and i am not happy about that. ***Blablabla cut long rant*** Xah, this is really you, isn't it. Come on, confess. From frank at chagford.com Mon Aug 9 09:19:30 2010 From: frank at chagford.com (Frank Millman) Date: Mon, 9 Aug 2010 15:19:30 +0200 Subject: Circular imports (again) Message-ID: Hi all I know the problems related to circular imports, and I know some of the techniques to get around them. However, I find that I bump my head into them from time to time, which means, I guess, that I have not fully understood how to organise my code so that I avoid them in the first place. It has just happened again. I have organised my code into three modules, each representing a fairly cohesive functional area of the overall application. However, there really are times when Module A wants to invoke something from Module B, ditto for B and C, and ditto for C and A. I can think of two workarounds. One is to place the import statement inside the function that actually requires it. It is therefore not executed when the module itself is imported, thereby avoiding the problem. It works, but breaks the convention that all imports should be declared at the top of the program. A second solution is to avoid invoking the other modules directly, but rather use global Queue.Queues to pass requests from one module to another. Again, it works, but adds complication, especially if the 'invoker' needs to get a return value. So I think my main question is, is this a symptom of a flaw in my approach, or is this something that all programmers bump into from time to time? If the former, I can expand on my current requirement if anyone would like to suggest a better approach. If the latter, is either of the above solutions preferred, or are there other techniques to get around the problem. Any suggestions will be appreciated. Thanks Frank Millman From f3d27b at gmail.com Mon Aug 9 09:38:28 2010 From: f3d27b at gmail.com (Wang Lei) Date: Mon, 9 Aug 2010 21:38:28 +0800 Subject: HELP! build python error with message: "unable to load the file system codec" Message-ID: Hi, developers! I get python3k from the svn repository. The revision is 83889. When building it, i encounter this error. -------------------- gcc -pthread -Xlinker -export-dynamic -o python Modules/python.o libpython3.2.a -lpthread -ldl -lutil -lm XXX lineno: 1098, opcode: 32 Unable to get the locale encoding: fallback to utf-8 Fatal Python error: Py_Initialize: unable to load the file system codec LookupError: no codec search functions registered: can't find encoding /bin/sh: line 1: 14357 Aborted CC='gcc -pthread' LDSHARED='gcc -pthread -shared' LDFLAGS=' ' OPT='-DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes' ./python -E ../python-svn-14/setup.py build make: *** [sharedmods] Error 134 -------------------- What does that mean? Could anyone help? In case you want to check out the output. It is attached. -- Regards, Lei From eckhardt at satorlaser.com Mon Aug 9 09:39:08 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 09 Aug 2010 15:39:08 +0200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? The fact that Python is OOP doesn't mean that the implementation of it has to be written using an OOP language. Other than that, I'm actually surprised that nobody mentioned that Python actually _is_ written in C++. Yes, it's restricted to a subset thereof that is compatible to C, but you could also claim that it was written in a subset of C compatible to C++. :) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From python at mrabarnett.plus.com Mon Aug 9 09:52:42 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 14:52:42 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> Message-ID: <4C60082A.2060206@mrabarnett.plus.com> ????? wrote: > On 8 ???, 17:59, Thomas Jollans wrote: > >> Two problems here: >> >> str.replace doesn't use regular expressions. You'll have to use the re >> module to use regexps. (the re.sub function to be precise) >> >> '.' matches a single character. Any character, but only one. >> '.*' matches as many characters as possible. This is not what you want, >> since it will match everything between the *first* . >> You want non-greedy matching. >> >> '.*?' is the same thing, without the greed. > > Thanks you, > > So i guess this needs to be written as: > > src_data = re.sub( '', '', src_data ) > In a regex '?' is a special character, so if you want a literal '?' you need to escape it. Therefore: src_data = re.sub(r'<\?(.*?)\?>', '', src_data) > Tha 'r' special char doesn't need to be inserter before the regex here > due to regex ain't containing backslashes. > >> You will have to find the tag before inserting the string. >> str.find should help -- or you could use str.replace and replace the >> tag with you counter line, plus a new . > > Ah yes! Damn why din't i think of it.... str.replace should do the > trick. I was stuck trying to figure regexes. > > So, i guess that should work: > > src_data = src_data.replace('', '

color=green> ??????? ??????????: %(counter)d

' ) > >> No it's not. You're just giving up too soon. > > Yes youa re right, your hints keep me going and thank you for that. From davea at ieee.org Mon Aug 9 10:07:36 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 10:07:36 -0400 Subject: simple renaming files program In-Reply-To: References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: <4C600BA8.8070500@ieee.org> blur959 wrote: > On Aug 9, 6:01 pm, Chris Rebert wrote: > >> >> os.rename() takes paths that are absolute (or possibly relative to the >> cwd), not paths that are relative to some arbitrary directory (as >> returned by os.listdir()). >> Also, never name a variable "file"; it shadows the name of the built-in type. >> >> Hence (untested): >> from os import listdir, rename >> from os.path import isdir, join >> directory =aw_input("input file directory") >> s =aw_input("search for name") >> r =aw_input("replace name") >> >> for filename in listdir(directory): >> path = join(directory, filename) #paste the directory name on >> if isdir(path): continue #skip subdirectories (they're not files) >> newname = filename.replace(s, r) >> newpath = join(directory, newname) >> n = rename(path, newpath) >> print n >> >> Cheers, >> Chris >> --http://blog.rebertia.com >> > > Thanks, they worked! > > A refinement: use os.path.join(), rather than just join(). It's smarter about adding the right kind of slash between the nodes, if needed. Currently, if you leave off the trailing slash (from "directory"), you'll end up with the files being one level up, and the individual files having a string prepended. DaveA From python at mrabarnett.plus.com Mon Aug 9 10:14:16 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 15:14:16 +0100 Subject: Regular expression issue In-Reply-To: <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> Message-ID: <4C600D38.6070903@mrabarnett.plus.com> genxtech wrote: > On Aug 8, 7:34 pm, Tim Chase wrote: >> On 08/08/10 17:20, genxtech wrote: >> >>> if re.search(search_string, in_string) != None: >> While the other responses have addressed some of the big issues, >> it's also good to use >> >> if thing_to_test is None: >> >> or >> >> if thing_to_test is not None: >> >> instead of "== None" or "!= None". >> >> -tkc > > I would like to thank all of you for your responses. I understand > what the regular expression means, and am aware of the double negative > nature of the test. I guess what I am really getting at is why the > last test returns a value of None, and even when using the syntax > suggested in this quoted solution, the code for the last test is doing > the opposite of the previous 2 tests that also returned a value of > None. I hope this makes sense and clarifies what I am trying to ask. > It returns None because it doesn't match. Why doesn't it match? Because the regex wants the last character to be a 'y', but it isn't, it's a 'a'. From nikos.the.gr33k at gmail.com Mon Aug 9 10:17:51 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 07:17:51 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> Message-ID: On 9 ???, 13:47, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > On 9 ???, 13:06, Peter Otten <__pete... at web.de> wrote: > > >> > So since its utf-8 what the problem of opening it? > > >> Python says it's not, and I tend to believe it. > > > You are right! > > > I tried to do the same exact openign via IDLE enviroment and i goth > > the encoding of the file from there! > > >>>> open("d:\\test\\index.php" ,'r') > > <_io.TextIOWrapper name='d:\\test\\index.php' encoding='cp1253'> > > > Thats why in the error in my previous post it said > > File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode > > it tried to use the cp1253 encoding. > > > But now sicne Python as we see can undestand the nature of the > > encoding what causing it not to open the file? > > It doesn't. You have to tell. Why it doesn't? The idle response designates that it knows that file encoding is in "cp1253" which means it can identify it. *If* the file uses cp1253 you can open it with > > open(..., encoding="cp1253") > > Note that if the file is not in cp1253 python will still happily open it as > long as it doesn't contain the following bytes: > > >>> for i in range(256): > > ... ? ? try: chr(i).decode("cp1253") and None > ... ? ? except: print i > ... > 129 > 136 > 138 > 140 > 141 > 142 > 143 > 144 > 152 > 154 > 156 > 157 > 158 > 159 > 170 > 210 > 255 > > Peter I'm afraid it does because whn i tried: f = open(src_f, 'r', encoding="cp1253" ) i got the same error again.....what are those characters?Dont they belong too tot he same weird 'cp1253' encoding? Why compiler cant open them? From python at mrabarnett.plus.com Mon Aug 9 10:18:49 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 15:18:49 +0100 Subject: simple renaming files program In-Reply-To: <4C600BA8.8070500@ieee.org> References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> <4C600BA8.8070500@ieee.org> Message-ID: <4C600E49.3070907@mrabarnett.plus.com> Dave Angel wrote: > blur959 wrote: >> On Aug 9, 6:01 pm, Chris Rebert wrote: >> >>> >>> os.rename() takes paths that are absolute (or possibly relative to the >>> cwd), not paths that are relative to some arbitrary directory (as >>> returned by os.listdir()). >>> Also, never name a variable "file"; it shadows the name of the >>> built-in type. >>> >>> Hence (untested): >>> from os import listdir, rename >>> from os.path import isdir, join >>> directory =aw_input("input file directory") >>> s =aw_input("search for name") >>> r =aw_input("replace name") >>> >>> for filename in listdir(directory): >>> path = join(directory, filename) #paste the directory name on >>> if isdir(path): continue #skip subdirectories (they're not files) >>> newname = filename.replace(s, r) >>> newpath = join(directory, newname) >>> n = rename(path, newpath) >>> print n >>> >>> Cheers, >>> Chris >>> --http://blog.rebertia.com >>> >> >> Thanks, they worked! >> >> > A refinement: use os.path.join(), rather than just join(). It's > smarter about adding the right kind of slash between the nodes, if > needed. Currently, if you leave off the trailing slash (from > "directory"), you'll end up with the files being one level up, and the > individual files having a string prepended. > Have a look at the imports, Dave. :-) From nikos.the.gr33k at gmail.com Mon Aug 9 10:21:07 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 07:21:07 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> Message-ID: <1d07b6f8-6ccf-4472-a666-637a295ce1cd@z10g2000yqb.googlegroups.com> On 9 ???, 16:52, MRAB wrote: > ????? wrote: > > On 8 ???, 17:59, Thomas Jollans wrote: > > >> Two problems here: > > >> str.replace doesn't use regular expressions. You'll have to use the re > >> module to use regexps. (the re.sub function to be precise) > > >> '.' ?matches a single character. Any character, but only one. > >> '.*' matches as many characters as possible. This is not what you want, > >> since it will match everything between the *first* . > >> You want non-greedy matching. > > >> '.*?' is the same thing, without the greed. > > > Thanks you, > > > So i guess this needs to be written as: > > > src_data = re.sub( '', '', src_data ) > > In a regex '?' is a special character, so if you want a literal '?' you > need to escape it. Therefore: > > ? ? ?src_data = re.sub(r'<\?(.*?)\?>', '', src_data) i see, or perhaps even this: ? ?src_data = re.sub(r'', '', src_data) maybe it works here as well. From davea at ieee.org Mon Aug 9 10:21:38 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 10:21:38 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <4C600EF2.9060107@ieee.org> saeed.gnu wrote: > On Aug 9, 3:41 pm, "saeed.gnu" wrote: > >> "x is y" means "id(y) =id(y)" >> "x is not y" means "id(x) !=d(x)" >> "x is not None" means "id(x) !=d(None)" >> >> "x is not None" is a really silly statement!! because id(None) and id >> of any constant object is not predictable! I don't know whay people >> use "is" instead of "=. you should write "if x!=None" instead of "x >> is not None" >> > > Although small objects are unique in the memory (with a unique id) and > using "is" works ok, but that's not logical to compare id's when we > actually want to compare values! > > None is a single object; there is only one such object by language definition. So 'is' is the perfect operator if you want to check whether a particular object is that one or not. All other objects, of any possible type, will have a different ID than None. And talking about comparing values is nonsense anyway, since None has no value. It's only purpose is to indicate that some operation had no value, or no return statement, or ... Using '==' will not necessarily give the same result, and I can't think of ANY case where I'd prefer the former. If you disagree, give a concrete example. DaveA DaveA From blur959 at hotmail.com Mon Aug 9 10:24:36 2010 From: blur959 at hotmail.com (blur959) Date: Mon, 9 Aug 2010 07:24:36 -0700 (PDT) Subject: Creating a custom UI inside Maya with python Message-ID: Hi, all, I wonder if my post is relevant here, but i will still post it anyway. I am working on creating a custom UI inside Maya and I encountered some problems. Firstly, I am trying to create a textfield button that creates a locator-shaped curve based on the coordinates the user keyed into the text field. However I got no idea how to go about doing it properly. I hope you guys could give me some help. Thanks. I attached my code below. My code isn't working though. I have this error, which says button2 is not defined. I got no clue on how else to debug. import maya.cmds as cmds def createMyLayout(): window = cmds.window(widthHeight=(1000, 600), title="test", resizeToFitChildren=1) cmds.rowLayout("button1, button2, button3", numberOfColumns=5) cmds.columnLayout(adjustableColumn=True, columnAlign="center", rowSpacing=10) button2 = cmds.textFieldButtonGrp(label="LocatorCurve", text="Please key in your coordinates", changeCommand=edit_curve, buttonLabel="Execute", buttonCommand=locator_curve) cmds.setParent(menu=True) cmds.showWindow(window) def locator_curve(*args): # Coordinates of the locator-shaped curve. crv = cmds.curve(degree=1, point=[(1, 0, 0), (-1, 0, 0), (0, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 0), (0, 0, 1), (0, 0, -1), (0, 0, 0)]) return crv def edit_curve(*args): parts = button2.split(",") print parts x = parts[0] y = parts[1] z = parts[2] createMyLayout() From davea at ieee.org Mon Aug 9 10:40:06 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 10:40:06 -0400 Subject: simple renaming files program In-Reply-To: <4C600E49.3070907@mrabarnett.plus.com> References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> <4C600BA8.8070500@ieee.org> <4C600E49.3070907@mrabarnett.plus.com> Message-ID: <4C601346.4080804@ieee.org> MRAB wrote: > >>>> from os.path import isdir, join >>>> > > Have a look at the imports, Dave. :-) > Oops. I should have noticed that it was a function call, not a method. And there's no built-in called join(). I just usually avoid using this kind of alias, unless performance requires. thanks for keeping me honest. DaveA From nobody at nowhere.com Mon Aug 9 10:56:09 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 09 Aug 2010 15:56:09 +0100 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On Mon, 09 Aug 2010 04:41:23 -0700, saeed.gnu wrote: > "x is not None" is a really silly statement!! because id(None) and id > of any constant object is not predictable! I don't know whay people > use "is" instead of "==". you should write "if x!=None" instead of "x > is not None" No, you should use the identity check. If you use ==, the operand may have an __eq__ or __cmp__ method which considers the object equal to None. From pruebauno at latinmail.com Mon Aug 9 11:01:22 2010 From: pruebauno at latinmail.com (nn) Date: Mon, 9 Aug 2010 08:01:22 -0700 (PDT) Subject: Regular expression issue References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> Message-ID: On Aug 9, 9:18?am, genxtech wrote: > On Aug 8, 7:34?pm, Tim Chase wrote: > > > > > On 08/08/10 17:20, genxtech wrote: > > > > if re.search(search_string, in_string) != None: > > > While the other responses have addressed some of the big issues, > > it's also good to use > > > ? ?if thing_to_test is None: > > > or > > > ? ?if thing_to_test is not None: > > > instead of "== None" or "!= None". > > > -tkc > > I would like to thank all of you for your responses. ?I understand > what the regular expression means, and am aware of the double negative > nature of the test. ?I guess what I am really getting at is why the > last test returns a value of None, and even when using the syntax > suggested in this quoted solution, the code for the last test is doing > the opposite of the previous 2 tests that also returned a value of > None. ?I hope this makes sense and clarifies what I am trying to ask. > Thanks First: You understand the regular expression and the double negative but not both of them together, otherwise you would not be asking here. The suggestion of refactoring the code is that down the road you or somebody else doing maintenance will have to read it again. Good books avoid confusing grammar, likewise, good programs avoid confusing logic. Second: the root of your problem is the mistaken believe that P=>Q implies (not P)=>(not Q); This is not so. Let me give an example: if you say "if it rains" then "the ground is wet" that does not imply "if it doesn't rain" then "the ground is not wet". You could be watering the plants for instance. Saying "if the word finishes with a consonant and an y" then "ay, ey, iy, oy and uy are not at the end of the word" does not imply that "if the word does not finish with a consonant and an y" then "ay, ey, iy, oy or uy were found at the end of the word". The word could end in x for instance. I hope I didn't make it more confusing, otherwise other people will probably chime in to make it clear to you. From python at mrabarnett.plus.com Mon Aug 9 11:10:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 16:10:26 +0100 Subject: Creating a custom UI inside Maya with python In-Reply-To: References: Message-ID: <4C601A62.2020505@mrabarnett.plus.com> blur959 wrote: > Hi, all, I wonder if my post is relevant here, but i will still post > it anyway. I am working on creating a custom UI inside Maya and I > encountered some problems. Firstly, I am trying to create a textfield > button that creates a locator-shaped curve based on the coordinates > the user keyed into the text field. However I got no idea how to go > about doing it properly. I hope you guys could give me some help. > Thanks. I attached my code below. My code isn't working though. I have > this error, which says button2 is not defined. I got no clue on how > else to debug. > > import maya.cmds as cmds > > def createMyLayout(): [snip] > button2 = cmds.textFieldButtonGrp(label="LocatorCurve", > text="Please key in your > coordinates", > changeCommand=edit_curve, > buttonLabel="Execute", > buttonCommand=locator_curve) > [snip] When you assign to a name in a function the target is by default local to that function, so 'button2' is local to 'createMyLayout'. Add the line: global button2 to the function to make it visible to the rest of the module/file. From python at mrabarnett.plus.com Mon Aug 9 11:15:03 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 16:15:03 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <1d07b6f8-6ccf-4472-a666-637a295ce1cd@z10g2000yqb.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> <1d07b6f8-6ccf-4472-a666-637a295ce1cd@z10g2000yqb.googlegroups.com> Message-ID: <4C601B77.9080502@mrabarnett.plus.com> ????? wrote: > On 9 ???, 16:52, MRAB wrote: >> ????? wrote: >>> On 8 ???, 17:59, Thomas Jollans wrote: >>>> Two problems here: >>>> str.replace doesn't use regular expressions. You'll have to use the re >>>> module to use regexps. (the re.sub function to be precise) >>>> '.' matches a single character. Any character, but only one. >>>> '.*' matches as many characters as possible. This is not what you want, >>>> since it will match everything between the *first* . >>>> You want non-greedy matching. >>>> '.*?' is the same thing, without the greed. >>> Thanks you, >>> So i guess this needs to be written as: >>> src_data = re.sub( '', '', src_data ) >> In a regex '?' is a special character, so if you want a literal '?' you >> need to escape it. Therefore: >> >> src_data = re.sub(r'<\?(.*?)\?>', '', src_data) > > i see, or perhaps even this: > > src_data = re.sub(r'', '', src_data) > > maybe it works here as well. No. That regex means that it should match: # '>' From invalid at invalid.invalid Mon Aug 9 11:16:29 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 9 Aug 2010 15:16:29 +0000 (UTC) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: On 2010-08-07, Hexamorph wrote: > Lurking for long enough to know your style. Looking at your Unicode > rant, combined with some other comments and your general "I am right > and you are wrong because you disagree with me." style, I came to > the conclusion, that you are either a faschist or the perfect role > model for an imperialistic, foreign culture destroying, > self-praising, arrogant, ignorant moron. IOW, the "Ugly American". I assure you that we here in the US are aware of the problem and do try to keep them from annoying the rest of the world by providing them with an abundance of junk food, bad television, worse movies, and a variety of sporting events tailored to their tastes. Unfortunately the advent of cheap air-travel in the latter half of the 20th century has allowed small groups of them to escape and wander about various parts of the world (mainly Europe) in search of KFCs while complaining about the toilets, the food, the money, the weather, the roads, the cars, and so on. They are easily identified by their cloathing and their believe that everybody understands English if you speak it loudly and slowly while accompanying it with exaggerated, mostly-random hand gestures. Just avoid them if possible. Don't worry, the less contact they have with "furriners" the happier they are (which makes one wonder why they leave their home territories -- reasearch on that topic is ongoing). Unfortunately, if you work in the hospitality industries there's not much you can do other than grit your teeth, cross you fingers, and hope you'll end up with a batch that over-tips. -- Grant Edwards grant.b.edwards Yow! Youth of today! at Join me in a mass rally gmail.com for traditional mental attitudes! From johan at notused.invalid Mon Aug 9 11:19:17 2010 From: johan at notused.invalid (Johan) Date: Mon, 9 Aug 2010 17:19:17 +0200 Subject: Using dicts and lists as default arguments of functions Message-ID: <20100809171917.346bc849@reken.ne31.nl> Dear all, Considering this test program: def tst(a={}): print 1, a a['1'] = 1 print 2, a del a def tstb(a=[]): print 1, a a.append(1) print 2, a del a tst() tst() tstb() tstb() With output: tnjx at tnjx:~/tst> python tt.py 1 {} 2 {'1': 1} 1 {'1': 1} 2 {'1': 1} 1 [] 2 [1] 1 [1] 2 [1, 1] Would there be a way to ensure that the results does not depend on the previous call of the function. The desired output is: 1 {} 2 {'1': 1} 1 {} 2 {'1': 1} 1 [] 2 [1] 1 [] 2 [1] I know that tst({}) and tstb([]) will work, but is there any way to still use tst(), tstb()? Thanks in advance, Best regards, Johan From mwilson at the-wire.com Mon Aug 9 11:31:21 2010 From: mwilson at the-wire.com (Mel) Date: Mon, 09 Aug 2010 11:31:21 -0400 Subject: Using dicts and lists as default arguments of functions References: <20100809171917.346bc849@reken.ne31.nl> Message-ID: Johan wrote: > Dear all, > > Considering this test program: > > def tst(a={}): > print 1, a > a['1'] = 1 > print 2, a > del a The idiom to use is def tst (a=None): if a is None: a = {} # ... and so on. This means that every call to tst with unspecified a creates its own empty dict. Ditto for lists. Mel. From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 9 11:34:23 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Aug 2010 17:34:23 +0200 Subject: Using dicts and lists as default arguments of functions In-Reply-To: <20100809171917.346bc849@reken.ne31.nl> References: <20100809171917.346bc849@reken.ne31.nl> Message-ID: <4c601ffd$0$2755$426a74cc@news.free.fr> Johan a ?crit : > Dear all, > > Considering this test program: > > def tst(a={}): Stop here, we already know what will follow !-) And yes, it's one of Python's most (in)famous gotchas : default arguments values are computed only once, at function definition time (that is, when the def statement is executed). The correct way to write a function with mutable default arguments is: def func(arg=None): if arg is None: arg = [] # then proceed HTH From python at mrabarnett.plus.com Mon Aug 9 11:35:50 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 16:35:50 +0100 Subject: Using dicts and lists as default arguments of functions In-Reply-To: <20100809171917.346bc849@reken.ne31.nl> References: <20100809171917.346bc849@reken.ne31.nl> Message-ID: <4C602056.3080203@mrabarnett.plus.com> Johan wrote: > Dear all, > > Considering this test program: > > def tst(a={}): > print 1, a > a['1'] = 1 > print 2, a > del a > > def tstb(a=[]): > print 1, a > a.append(1) > print 2, a > del a > [snip] Do this instead: def tst(a=None): if a is None: a = {} print 1, a a['1'] = 1 print 2, a def tstb(a=None): if a is None: a = [] print 1, a a.append(1) print 2, a It's all explained here: http://effbot.org/zone/default-values.htm From iamforufriends at gmail.com Mon Aug 9 11:40:41 2010 From: iamforufriends at gmail.com (SAKEERA) Date: Mon, 9 Aug 2010 08:40:41 -0700 (PDT) Subject: EARN FROM HOME...EAZY... TRY THIS.#### Message-ID: <5e8886df-2337-41be-918a-cf7e8bb8bbdf@p22g2000pre.googlegroups.com> EARN FROM HOME...EAZY... TRY THIS.#### http://www.hymarkets.com/servlet/track?campaignID=70120000000AS5B&a_aid=d629b730 EARN FROM HOME...EAZY... TRY THIS.#### http://www.hymarkets.com/servlet/track?campaignID=70120000000AS5B&a_aid=d629b730 EARN FROM HOME...EAZY... TRY THIS.#### http://www.hymarkets.com/servlet/track?campaignID=70120000000AS5B&a_aid=d629b730 From michael at stroeder.com Mon Aug 9 11:43:00 2010 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 09 Aug 2010 17:43:00 +0200 Subject: ANN: python-ldap-2.3.12 Message-ID: Find a new release of python-ldap: http://pypi.python.org/pypi/python-ldap/2.3.12 python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). Project's web site: http://www.python-ldap.org/ Ciao, Michael. -- Michael Str?der E-Mail: michael at stroeder.com http://www.stroeder.com ---------------------------------------------------------------- Released 2.3.12 2010-08-05 Changes since 2.3.11: Lib/ * Removed tabs from various modules to make things work with python -tt. * Quick fix to ldif.is_dn() to let multi-valued RDNs pass as valid. Is too liberal in some corner-cases though... * Fix to ldif.is_dn() to allow dashes in attribute type (see SF#3020292) * ldap.open() now outputs a deprecation warning * module-wide locking is now limited to calling _ldap.initialize(). Still ldap.functions._ldap_function_call() is used to wrap all calls for writing debug log. Modules/ * New LDAP options available in OpenLDAP 2.4.18+ supported in LDAPObject.get/set_option(): ldap.OPT_X_KEEPALIVE_IDLE, ldap.OPT_X_KEEPALIVE_PROBES, ldap.OPT_X_KEEPALIVE_INTERVAL, ldap.OPT_X_TLS_CRLCHECK, ldap.OPT_X_TLS_CRLFILE Doc/ * Various small updates/improvements From nikos.the.gr33k at gmail.com Mon Aug 9 11:58:37 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 08:58:37 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> Message-ID: <905e8888-6664-4cae-8e57-27a1679a518a@y11g2000yqm.googlegroups.com> Please tell me that no matter what weird charhs has inside ic an still open thosie fiels and make the neccessary replacements. From python.koda at gmail.com Mon Aug 9 12:08:00 2010 From: python.koda at gmail.com (Alban Nona) Date: Mon, 9 Aug 2010 12:08:00 -0400 Subject: Subprocess Problem (Wait and while) Message-ID: Hi, I have some problem with my actual code. In fact, the script is done to work within nuke from the foundry which is a compositing software. Homever, I have some code difficulties as I quite new in the area. Here the deal: Im using subprocess command to copy some files into local directory, like this: cmd = ['xcopy', '/E', '/I', '/Q', '/Y', '%s' % _folder.replace('/', '\\'), '%s' % _temp.replace('/', '\\')] subprocess.Popen(cmd, shell=True) Its copying quite well. I have no problem with that. But, after the copy I would like to continue my code, but ONLY if the copy is done. If Im using a WAIT, its freezing the main program (nuke) until the copy in done. I want to avoid that. I also try "call" but same thing. Its freezing... I though about something like: while subprocess not finished: Do nothing else: Continue Program Like this its checking if the files is copying and do nothing until its done. I also tough: while os.listdir(src) != os.listdir(dst): Do nothing Else: Continue program But Im not sure its quite good solution. Someone can help me with this one please ? Thank you ! :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From darynr at gmail.com Mon Aug 9 12:11:37 2010 From: darynr at gmail.com (daryn) Date: Mon, 9 Aug 2010 09:11:37 -0700 (PDT) Subject: iter Message-ID: I'm just playing around with the iter function and I realize that I can use the iterator returned by it long after the original object has any name bound to it. Example: >>>a=[1,2,3,4] >>>b=iter(a) >>>b.next() 1 >>>a[1]=99 >>>a[3]=101 >>>del a >>>b.next() 99 >>>b.next() 3 >>>b.next() 101 it seems as if the original object is never being garbage collected even though there is no name bound to it. Does the name bound to the iterator object count as a reference to the original object for garbage collection purposes? Is there some way to retrieve/manipulate the original object via the iterator? Just trying to understand how this all works. -thanks for any help you can give daryn From __peter__ at web.de Mon Aug 9 12:21:39 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 18:21:39 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> <905e8888-6664-4cae-8e57-27a1679a518a@y11g2000yqm.googlegroups.com> Message-ID: ????? wrote: > Please tell me that no matter what weird charhs has inside ic an still > open thosie fiels and make the neccessary replacements. Go back to 2.6 for the moment and defer learning about unicode until you're done with the conversion job. From tjreedy at udel.edu Mon Aug 9 12:28:17 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 12:28:17 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On 8/9/2010 7:41 AM, saeed.gnu wrote: > "x is y" means "id(y) == id(y)" > "x is not y" means "id(x) != id(x)" > "x is not None" means "id(x) != id(None)" > > "x is not None" is a really silly statement!! Wrong. It is exactly right when that is what one means and is the STANDARD IDIOM. > because id(None) and id > of any constant object is not predictable! This is silly. The id of None and of any other object are predictably different. > I don't know whay people use "is" instead of "==". Because it is the right thing to do! > you should write "if x!=None" instead of "x is not None" Wrong. It is trivial to make a class whose objects compare == to None. -- Terry Jan Reedy From __peter__ at web.de Mon Aug 9 12:31:07 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 18:31:07 +0200 Subject: iter References: Message-ID: daryn wrote: > I'm just playing around with the iter function and I realize that I > can use the iterator returned by it long after the original object has > any name bound to it. Example: > >>>>a=[1,2,3,4] >>>>b=iter(a) >>>>b.next() > 1 >>>>a[1]=99 >>>>a[3]=101 >>>>del a >>>>b.next() > 99 >>>>b.next() > 3 >>>>b.next() > 101 > > it seems as if the original object is never being garbage collected > even though there is no name bound to it. Does the name bound to the > iterator object count as a reference to the original object for > garbage collection purposes? The listiterator object internally holds a reference to the list, but doesn't make it available to Python code. > Is there some way to retrieve/manipulate > the original object via the iterator? Not without dirty tricks (ctypes). > Just trying to understand how this all works. If you can read C look here: http://svn.python.org/view/python/branches/py3k/Objects/listobject.c?revision=81032&view=markup Peter From icanbob at gmail.com Mon Aug 9 12:49:57 2010 From: icanbob at gmail.com (bobicanprogram) Date: Mon, 9 Aug 2010 09:49:57 -0700 (PDT) Subject: xmlrpc and processes References: <3ec02745-4982-4f9e-955f-b771cdd64e19@d8g2000yqf.googlegroups.com> Message-ID: <83fa4bfc-2032-4486-b0f8-aa75d8c299b7@i13g2000yqd.googlegroups.com> On Aug 9, 2:50 am, iu2 wrote: > Hi, > > I have a SimpleXMLRPCServer running on one PC. > I need several ServerProxy-s talking to it, each one running on a > different PC. That is, I run on each PC a client application, that > talks to the one server using xml-rpc. > > Is the xml-rpc designed to work like this? If not, is there something > I can do to still be able to work with xml-rpc in this architucture? > > Thank you very much I don't have any direct experience with SimplXMLRPC, but depending on what you are actually trying to accomplish this technique might also work: http://www.icanprogram.com/06py/lesson1/lesson1.html Since SIMPL messaging is lower down on the stack than XML you could probably use SIMPL messages to carry XML structured content from client to server. bob From aahz at pythoncraft.com Mon Aug 9 12:52:20 2010 From: aahz at pythoncraft.com (Aahz) Date: 9 Aug 2010 09:52:20 -0700 Subject: Python parsing XML file problem with SAX References: Message-ID: In article , Stefan Behnel wrote: > >First of all: don't use SAX. Use ElementTree's iterparse() function. That >will shrink you code down to a simple loop in a few lines. Unless I'm missing something, that only helps if the final tree fits into memory. What do you suggest other than SAX if your XML file may be hundreds of megabytes? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From martin.hellwig at dcuktec.org Mon Aug 9 13:03:29 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 09 Aug 2010 18:03:29 +0100 Subject: xmlrpc and processes In-Reply-To: <3ec02745-4982-4f9e-955f-b771cdd64e19@d8g2000yqf.googlegroups.com> References: <3ec02745-4982-4f9e-955f-b771cdd64e19@d8g2000yqf.googlegroups.com> Message-ID: On 08/09/10 07:50, iu2 wrote: > Hi, > > I have a SimpleXMLRPCServer running on one PC. > I need several ServerProxy-s talking to it, each one running on a > different PC. That is, I run on each PC a client application, that > talks to the one server using xml-rpc. > > Is the xml-rpc designed to work like this? If not, is there something > I can do to still be able to work with xml-rpc in this architucture? > > Thank you very much Yeah should be no problem, you might get some ideas from reading this 'wrapper': http://code.google.com/p/dcuktec/source/browse/source/wrapped_xmlrpc_server/rpc.py -- mph From urban.dani at gmail.com Mon Aug 9 13:06:24 2010 From: urban.dani at gmail.com (Daniel Urban) Date: Mon, 9 Aug 2010 19:06:24 +0200 Subject: how to change a string into dictionary In-Reply-To: <4C5FCB80.7010701@amazon.com> References: <4C5FCB80.7010701@amazon.com> Message-ID: > a = "{'a':'1','b':'2'}" > how to change a into a dictionary ,says, a = {'a':'1','b':'2'} See also the ast.literal_eval function: http://docs.python.org/py3k/library/ast.html#ast.literal_eval Daniel From tjreedy at udel.edu Mon Aug 9 13:11:56 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 13:11:56 -0400 Subject: iter In-Reply-To: References: Message-ID: On 8/9/2010 12:11 PM, daryn wrote: > I'm just playing around with the iter function and I realize that I > can use the iterator returned by it long after the original object has > any name bound to it. Example: > >>>> a=[1,2,3,4] >>>> b=iter(a) >>>> b.next() > 1 >>>> a[1]=99 Changing a list while iterating through it is possible, sometimes useful, but error prone, especially with insert or delete. Changing a dict while iterating through it is prohibited since the iteration order depends on the exact internal structure. That in turn depends on the history of additions and deletions. >>>> a[3]=101 >>>> del a >>>> b.next() > 99 >>>> b.next() > 3 >>>> b.next() > 101 > > it seems as if the original object is never being garbage collected > even though there is no name bound to it. The fact that CPython currently deletes some things immediately is a current implementation detail, subject to change. > Does the name bound to the > iterator object count as a reference to the original object for > garbage collection purposes? Not quite. The iterator obviously has to have an internal reference, which amount to the almost the same thing. However, if you put the iterator in a list and deleted the name binding, both the iterator and list are still kept around. > Is there some way to retrieve/manipulate > the original object via the iterator? If you do dir(b), you will only see the standard __xx__ methods, most of which are inherited. Iterators can be written to expose an underlying object, if there is one, but some do not have one and this is not part of the simple iterator protocol. Hence builtin iterators for builtins do not do so. If one actually needed such lookup, this wrapper should work. class myiter(): def __init__(self, ob): self.ob = ob self.__itnext__ = iter(ob).__next__ def __iter__(self): return self def __next__(self): return self.__itnext__() it = myiter([1,2,3]) print (it.ob, list(it)) # [1, 2, 3] [1, 2, 3] > Just trying to understand how this all works. Keep experimenting. Python makes is so easy, especially with an edit window such as with IDLE and a Run command. I initially tried not defining myiter.__next__ and instead wrote: self.__next__ = iter(ob).__next__ but that does not work because special __xx__ methods are typically looked up on the class, not the instance. I know that but was not completely sure about this case. -- Terry Jan Reedy From tjreedy at udel.edu Mon Aug 9 13:15:24 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 13:15:24 -0400 Subject: Need mentor In-Reply-To: References: Message-ID: On 8/9/2010 2:31 AM, Ranjith Kumar wrote: > I have described the theme of my project here, Is this a class assignment or paid work? -- Terry Jan Reedy From tjreedy at udel.edu Mon Aug 9 13:24:11 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 13:24:11 -0400 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: On 8/9/2010 11:16 AM, Grant Edwards wrote: > IOW, the "Ugly American". [snip hate rant] Stereotypically bashing "Americans" is as ugly and obnoxious as bashing any other ethnic group. I have traveled the world and Americans are no worse, but are pretty much the same mix of good and bad. It is certainly off-topic and inappropriate for this group. -- Terry Jan Reedy From stefan_ml at behnel.de Mon Aug 9 13:31:20 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 09 Aug 2010 19:31:20 +0200 Subject: Python parsing XML file problem with SAX In-Reply-To: References: Message-ID: Aahz, 09.08.2010 18:52: > In article, > Stefan Behnel wrote: >> >> First of all: don't use SAX. Use ElementTree's iterparse() function. That >> will shrink you code down to a simple loop in a few lines. > > Unless I'm missing something, that only helps if the final tree fits into > memory. What do you suggest other than SAX if your XML file may be > hundreds of megabytes? Well, what about using ElementTree's iterparse() function in that case? That's what it's good at, and its cElementTree version is extremely fast. Stefan From ethan at stoneleaf.us Mon Aug 9 13:33:15 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 09 Aug 2010 10:33:15 -0700 Subject: Circular imports (again) In-Reply-To: References: Message-ID: <4C603BDB.4010103@stoneleaf.us> Frank Millman wrote: > Hi all > > I know the problems related to circular imports... > > It has just happened again. I have organised my code into three modules, > each representing a fairly cohesive functional area of the overall > application. However, there really are times when Module A wants to > invoke something from Module B, ditto for B and C, and ditto for C and A. I believe the issue arises when you have top-level code (module global code, or unindented code for the visual) that is calling the other module. If you keep your references to the other module in functions, you should be able to have your imports at module level. The below works fine. a.py ----- import b def spam(): b.eggs() def foo(): print "my circular-import-fu is strong!" # to amuse myself only!) ----- b.py ----- import a def eggs(): print 'sunnyside?' def ham(): a.foo() ----- If you put an in b.py, then you get: Traceback (most recent call last): File "", line 1, in File "a.py", line 1, in import b File "b.py", line 3, in a.spam() AttributeError: 'module' object has no attribute 'spam' Hope this helps. ~Ethan~ From nikos.the.gr33k at gmail.com Mon Aug 9 13:40:35 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 10:40:35 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> <905e8888-6664-4cae-8e57-27a1679a518a@y11g2000yqm.googlegroups.com> Message-ID: On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > Please tell me that no matter what weird charhs has inside ic an still > > open thosie fiels and make the neccessary replacements. > > Go back to 2.6 for the moment and defer learning about unicode until you're > done with the conversion job. You are correct again! 3.2 caused the problem, i switched to 2.7 and now i donyt have that problem anymore. File is openign okey! it ALMOST convert correctly! # replace tags print ( 'replacing php tags and contents within' ) src_data = re.sub( '<\?(.*?)\?>', '', src_data ) it only convert the first instance of php tages and not the rest? But why? From thomas at jollybox.de Mon Aug 9 14:05:42 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 9 Aug 2010 20:05:42 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <201008092005.43602.thomas@jollybox.de> On Monday 09 August 2010, it occurred to ????? to exclaim: > On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > > ????? wrote: > > > Please tell me that no matter what weird charhs has inside ic an still > > > open thosie fiels and make the neccessary replacements. > > > > Go back to 2.6 for the moment and defer learning about unicode until > > you're done with the conversion job. > > You are correct again! 3.2 caused the problem, i switched to 2.7 and > now i donyt have that problem anymore. File is openign okey! > > it ALMOST convert correctly! > > # replace tags > print ( 'replacing php tags and contents within' ) > src_data = re.sub( '<\?(.*?)\?>', '', src_data ) > > it only convert the first instance of php tages and not the rest? > But why? http://docs.python.org/library/re.html#re.S You probably need to pass the re.DOTALL flag. From invalid at invalid.invalid Mon Aug 9 14:07:56 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 9 Aug 2010 18:07:56 +0000 (UTC) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: On 2010-08-09, Terry Reedy wrote: > On 8/9/2010 11:16 AM, Grant Edwards wrote: > >> IOW, the "Ugly American". > [snip hate rant] > > Stereotypically bashing "Americans" I wasn't bashing "Americans". I was making light of a certain type of American tourist commonly denoted by the phrase "ugly american". > is as ugly and obnoxious as bashing any other ethnic group. I have > traveled the world and Americans are no worse, but are pretty much > the same mix of good and bad. I've travelled the world as well, and I think that Americans do indeed make worse "tourists" than most others. I've seen a lot of European and Asian tourists in the US, and I've never seen from them the types of behavior for which the "Ugly American" tourists is famous. I've never been confronted here in the US by a Japanese tourist who thought that if he spoke Japanese to a store clerk loudly and slowing the clerk would understand. I've never seen European tourists trying to avoid eating "American" food or complaining about the electrical outlets. > It is certainly off-topic and inappropriate for this group. To that I'll confess. -- Grant Edwards grant.b.edwards Yow! I feel ... JUGULAR ... at gmail.com From pavlovevidence at gmail.com Mon Aug 9 14:08:16 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 9 Aug 2010 11:08:16 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> On Aug 9, 6:39?am, Ulrich Eckhardt wrote: > candide wrote: > > Python is an object oriented langage (OOL). The Python main > > implementation is written in pure and "old" C90. Is it for historical > > reasons? > > The fact that Python is OOP doesn't mean that the implementation of it has > to be written using an OOP language. > > Other than that, I'm actually surprised that nobody mentioned that Python > actually _is_ written in C++. Yes, it's restricted to a subset thereof that > is compatible to C, but you could also claim that it was written in a > subset of C compatible to C++. > > :) I highly doubt the Python source would build with a C++ compiler. C++ is "'mostly' 'backwards' compatible" with C insofar as you can pretty easily write C code that is also legal (and semantically equivalent) C++. But if you don't actively try to write code that is compatible with both languages, chances are the C code will invoke one of those "'minor' 'backwards' incompatibilies", the most common one being failure to cast a pointer. Carl Banks From lists at cheimes.de Mon Aug 9 14:27:20 2010 From: lists at cheimes.de (Christian Heimes) Date: Mon, 09 Aug 2010 20:27:20 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> Message-ID: > I highly doubt the Python source would build with a C++ compiler. > > C++ is "'mostly' 'backwards' compatible" with C insofar as you can > pretty easily write C code that is also legal (and semantically > equivalent) C++. But if you don't actively try to write code that is > compatible with both languages, chances are the C code will invoke one > of those "'minor' 'backwards' incompatibilies", the most common one > being failure to cast a pointer. Indeed: g++ -pthread -c -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -I. -IInclude -I./Include -DPy_BUILD_CORE -o Parser/parsetok.o Parser/parsetok.c Parser/parsetok.c: In function 'node* parsetok(tok_state*, grammar*, int, perrdetail*, int*)': Parser/parsetok.c:251: error: invalid conversion from 'void*' to 'char*' make: *** [Parser/parsetok.o] Error 1 Beside from several invalid conversions Python could most probably be compiled with a g++ compiler. I once worked on a patch to fix the conversion issues but Martin argued against it. There isn't really a point in cluttering the source with type casts. Christian From carey.tilden at gmail.com Mon Aug 9 14:27:40 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Mon, 9 Aug 2010 11:27:40 -0700 Subject: Need mentor In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 11:31 PM, Ranjith Kumar wrote: > I have?described?the theme of my project here, It appears all you did was describe your project. Did you ask a question or seek any specific guidance? Did I miss something? Carey From pavlovevidence at gmail.com Mon Aug 9 14:51:47 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 9 Aug 2010 11:51:47 -0700 (PDT) Subject: Circular imports (again) References: Message-ID: <1969caaa-f119-47e6-83d4-c57767bd8ea4@e15g2000yqo.googlegroups.com> On Aug 9, 6:19?am, "Frank Millman" wrote: > It has just happened again. I have organised my code into three modules, > each representing a fairly cohesive functional area of the overall > application. However, there really are times when Module A wants to invoke > something from Module B, ditto for B and C, and ditto for C and A. There's a dozen reasons why circular imports can go wrong. Can you describe the problem you're having getting them to work? If there's a traceback when you try to do it, cut-and-paste the traceback and relevant code here. If it's running, but you are not getting the behavior you expect, tell us what you expected to happen and what actually did. [snip] > So I think my main question is, is this a symptom of a flaw in my approach, > or is this something that all programmers bump into from time to time? I consider the need to resort to circular imports a red flag, not a manifest error. You say you are organizing the modules "functionally". I find that when I do that, I will occasionally get circular references, so I can believe you. I also find that in most such cases, reorganizing the modules according to "dependencies", so as to remove the circular import, makes it more confusing. Sometimes organizing by function makes more sense than organizing by dependency, and it's better to live with circular imports than to use a less- sensical organization. Carl Banks From bartc at freeuk.com Mon Aug 9 15:12:16 2010 From: bartc at freeuk.com (Bartc) Date: Mon, 9 Aug 2010 20:12:16 +0100 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: "D'Arcy J.M. Cain" wrote in message news:mailman.1735.1281185722.1673.python-list at python.org... > On Sat, 07 Aug 2010 13:48:32 +0200 > News123 wrote: >> It makes sense in assembly language and even in many byte code languages. >> It makes sense if you look at the internal representation of unsigned >> numbers (which might become an index) >> >> For a complete beginner common sense dictates differently and there >> might be confusion why the second element in a list has index 1. > > Would said beginner also be surprised that a newborn baby is zero years > old or would it be more natural to call them a one year old? Zero > based counting is perfectly natural. Depends whether you are counting (discrete) things, or measuring them (over a continuous range). You would start counting at 1, but start measuring from 0. -- Bartc From iamforufriends at gmail.com Mon Aug 9 15:14:44 2010 From: iamforufriends at gmail.com (SAKEERA) Date: Mon, 9 Aug 2010 12:14:44 -0700 (PDT) Subject: EARN FROM HOME... ITS REAL.... Message-ID: EARN FROM HOME... ITS REAL.... http://www.kamaraja.com/howitworks.htm?aff=naagaarjuna .......AND...... http://www.hyaffiliates.com?pid=d629b730 EARN FROM HOME... ITS REAL.... http://www.kamaraja.com/howitworks.htm?aff=naagaarjuna .......AND...... http://www.hyaffiliates.com?pid=d629b730 From nikos.the.gr33k at gmail.com Mon Aug 9 15:27:56 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 12:27:56 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <2b1da9fc-5c13-4301-8d0d-322eeac715ee@d17g2000yqb.googlegroups.com> Message-ID: On 8 ???, 20:29, John S wrote: > When replacing text in an HTML document with re.sub, you want to use > the re.S (singleline) option; otherwise your pattern won't match when > the opening tag is on one line and the closing is on another. Thats exactly the problem iam facing now with this statement. src_data = re.sub( '<\?(.*?)\?>', '', src_data ) you mean i have to switch it like this? src_data = re.S ( '<\?(.*?)\?>', '', src_data ) ? From rtw at rtw.me.uk Mon Aug 9 15:30:36 2010 From: rtw at rtw.me.uk (Rob Williscroft) Date: Mon, 9 Aug 2010 19:30:36 +0000 (UTC) Subject: dumping generator References: Message-ID: targetsmart wrote in news:cd83533b-f51e-4955-96c5-f8a10185bef1 @i18g2000pro.googlegroups.com in gmane.comp.python.general: > Right now if I want to dump the contents of a generator object I use , > a snip from a bigger block of code.. > > try: > while gen: print gen.next() > except StopIteration: > print "Done" > else: > raise > > is there a much simpler way ? print list( gen ) > > like for printing list we do > list = range(10) > print list > would print > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Rob. From zyzhu2000 at gmail.com Mon Aug 9 15:39:29 2010 From: zyzhu2000 at gmail.com (GZ) Date: Mon, 9 Aug 2010 12:39:29 -0700 (PDT) Subject: Sequential Object Store References: <6e21725a-e5c4-45be-81c4-5a9fd79df413@d8g2000yqf.googlegroups.com> Message-ID: <440b3d66-8936-4a02-89f9-86cb7f262969@d17g2000yqb.googlegroups.com> Hi Alex, On Aug 7, 6:54?pm, Alex Willmer wrote: > On Aug 7, 5:26?pm, GZ wrote: > > > I am wondering if there is a module that can persist a stream of > > objects without having to load everything into memory. (For this > > reason, I think Pickle is out, too, because it needs everything to be > > in memory.) > > From the pickle docs it looks like you could do something like: > > try: > ? ? import cPickle as pickle > except ImportError > ? ? import pickle > > file_obj = open('whatever', 'wb') > p = pickle.Pickler(file_obj) > > for x in stream_of_objects: > ? ? p.dump(x) > ? ? p.memo.clear() > > del p > file_obj.close() > > then later > > file_obj = open('whatever', 'rb') > p = pickle.Unpickler(file_obj) > > while True: > ? ? try: > ? ? ? ? x = p.load() > ? ? ? ? do_something_with(x) > ? ? except EOFError: > ? ? ? ? break > > Your loading loop could be wrapped in a generator function, so only > one object should be held in memory at once. This totally works! Thanks! From nikos.the.gr33k at gmail.com Mon Aug 9 15:53:21 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 12:53:21 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> On 9 ???, 21:05, Thomas Jollans wrote: > On Monday 09 August 2010, it occurred to ????? to exclaim: > > > > > > > On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > > > ????? wrote: > > > > Please tell me that no matter what weird charhs has inside ic an still > > > > open thosie fiels and make the neccessary replacements. > > > > Go back to 2.6 for the moment and defer learning about unicode until > > > you're done with the conversion job. > > > You are correct again! 3.2 caused the problem, i switched to 2.7 and > > now i donyt have that problem anymore. File is openign okey! > > > it ALMOST convert correctly! > > > # replace tags > > print ( 'replacing php tags and contents within' ) > > src_data = re.sub( '<\?(.*?)\?>', '', src_data ) > > > it only convert the first instance of php tages and not the rest? > > But why? > > http://docs.python.org/library/re.html#re.S > > You probably need to pass the re.DOTALL flag. src_data = re.sub( '<\?(.*?)\?>', '', src_data, re.DOTALL ) like this? From clp2 at rebertia.com Mon Aug 9 15:55:26 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 9 Aug 2010 12:55:26 -0700 Subject: simple renaming files program In-Reply-To: References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: On Mon, Aug 9, 2010 at 3:19 AM, Peter Otten <__peter__ at web.de> wrote: > Chris Rebert wrote: > >> Hence (untested): >> from os import listdir, rename >> from os.path import isdir, join >> directory = raw_input("input file directory") >> s = raw_input("search for name") >> r = raw_input("replace name") >> >> for filename in listdir(directory): >> ? ? path = join(directory, filename) #paste the directory name on >> ? ? if isdir(path): continue #skip subdirectories (they're not files) >> ? ? newname = filename.replace(s, r) >> ? ? newpath = join(directory, newname) >> ? ? n = rename(path, newpath) >> ? ? print n > > Warning: I don't remember how Windows handles this, but unix will happily > perform os.rename("alpha/alpha.txt", "beta/beta.txt") and overwrite > beta/beta.txt with alpha/alpha.txt. > > I'd rather modify the filename before joining it with the directory. Er, unless I'm really missing something, that's what my code already does. Perhaps you misread it? The replace() clearly happens before the 2nd join(). I took special care to account for and avoid the potential problem you're talking about. Cheers, Chris -- http://blog.rebertia.com From nikos.the.gr33k at gmail.com Mon Aug 9 16:05:14 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 13:05:14 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> On 9 ???, 10:07, ????? wrote: > Now the code looks as follows: > > ============================= > #!/usr/bin/python > > import re, os, sys > > id = 0 ?# unique page_id > > for currdir, files, dirs in os.walk('test'): > > ? ? ? ? for f in files: > > ? ? ? ? ? ? ? ? if f.endswith('php'): > > ? ? ? ? ? ? ? ? ? ? ? ? # get abs path to filename > ? ? ? ? ? ? ? ? ? ? ? ? src_f = join(currdir, f) > > ? ? ? ? ? ? ? ? ? ? ? ? # open php src file > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'reading from %s' % src_f ) > ? ? ? ? ? ? ? ? ? ? ? ? f = open(src_f, 'r') > ? ? ? ? ? ? ? ? ? ? ? ? src_data = f.read() ? ? ? ? ? ? # read contents of PHP file > ? ? ? ? ? ? ? ? ? ? ? ? f.close() > > ? ? ? ? ? ? ? ? ? ? ? ? # replace tags > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'replacing php tags and contents within' ) > ? ? ? ? ? ? ? ? ? ? ? ? src_data = re.sub( '', '', src_data ) > > ? ? ? ? ? ? ? ? ? ? ? ? # add ID > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'adding unique page_id' ) > ? ? ? ? ? ? ? ? ? ? ? ? src_data = ( '' % id ) + src_data > ? ? ? ? ? ? ? ? ? ? ? ? id += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? # add template variables > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'adding counter template variable' ) > ? ? ? ? ? ? ? ? ? ? ? ? src_data = src_data.replace('', '

color=green> ??????? ??????????: %(counter)d ' ) > > ? ? ? ? ? ? ? ? ? ? ? ? # rename old php file to new with .html extension > ? ? ? ? ? ? ? ? ? ? ? ? src_file = src_file.replace('.php', '.html') > > ? ? ? ? ? ? ? ? ? ? ? ? # open newly created html file for inserting data > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'writing to %s' % dest_f ) > ? ? ? ? ? ? ? ? ? ? ? ? dest_f = open(src_f, 'w') > ? ? ? ? ? ? ? ? ? ? ? ? dest_f.write(src_data) ? ? ? ? ?# write contents > ? ? ? ? ? ? ? ? ? ? ? ? dest_f.close() > > I just tried to test it. I created a folder names 'test' in me 'd:\' > drive. > Then i have put to .php files inside form the original to test if it > would work ok for those too files before acting in the whole copy and > after in the original project. > > so i opened a 'cli' form my Win7 and tried > > D:\>convert.py > > D:\> > > Itsjust printed an empty line and nothign else. Why didn't even try to > open the folder and fiels within? > Syntactically it doesnt ghive me an error! > Somehting with os.walk() methos perhaps? Can you help in this too please? Now iam able to just convrt a single file 'd:\test\index.php' But these needs to be done for ALL the php files in every subfolder. > for currdir, files, dirs in os.walk('test'): > > ? ? ? ? for f in files: > > ? ? ? ? ? ? ? ? if f.endswith('php'): Should the above lines enter folders and find php files in each folder so to be edited? From __peter__ at web.de Mon Aug 9 16:06:50 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 22:06:50 +0200 Subject: simple renaming files program References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: Chris Rebert wrote: > On Mon, Aug 9, 2010 at 3:19 AM, Peter Otten <__peter__ at web.de> wrote: >> Warning: I don't remember how Windows handles this, but unix will happily >> perform os.rename("alpha/alpha.txt", "beta/beta.txt") and overwrite >> beta/beta.txt with alpha/alpha.txt. >> >> I'd rather modify the filename before joining it with the directory. > > Er, unless I'm really missing something, that's what my code already > does. Perhaps you misread it? The replace() clearly happens before the > 2nd join(). I took special care to account for and avoid the potential > problem you're talking about. You're right. Sorry for the confusion. Peter From torriem at gmail.com Mon Aug 9 16:06:51 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 09 Aug 2010 14:06:51 -0600 Subject: Circular imports (again) In-Reply-To: <1969caaa-f119-47e6-83d4-c57767bd8ea4@e15g2000yqo.googlegroups.com> References: <1969caaa-f119-47e6-83d4-c57767bd8ea4@e15g2000yqo.googlegroups.com> Message-ID: <4C605FDB.60208@gmail.com> On Aug 9, 6:19 am, "Frank Millman" wrote: > It has just happened again. I have organised my code into three modules, > each representing a fairly cohesive functional area of the overall > application. However, there really are times when Module A wants to invoke > something from Module B, ditto for B and C, and ditto for C and A. There are a number of ways to avoid circular imports, in order of my own preference: 1. Make common stuff a new module. So if A needs something from B, and vice versa, you must factor out the stuff and stick it in its own module. The fact that you have circular dependencies means that although things are cohesive, they are way too closely coupled. 2. Instead of having A refer directly to something in B (which would cause a circular dependency, have the caller pass in as a parameter to the function in A, whatever is needed from B. This could be just a variable, complex object, or even a function or method. Take advantage of the fact that everything in Python is a first-class object. 3. Take advantage of Python's dynamicism. Write an initializer function in A that allows you to tell it about B and C. In other words, you can pass B and C to some method in A and have it bind B and C to local attributes in A. Then you can call B and C's methods just fine from A since everything is looked up as it is called. From gagsl-py2 at yahoo.com.ar Mon Aug 9 16:14:26 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Aug 2010 17:14:26 -0300 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: En Mon, 09 Aug 2010 08:41:23 -0300, saeed.gnu escribi?: > "x is y" means "id(y) == id(y)" > "x is not y" means "id(x) != id(x)" No; consider this: py> id([])==id([]) True py> [] is [] False Comparing id's is the same as using the is operator only if you can guarantee that both operands are alive at the same time. -- Gabriel Genellina From python at mrabarnett.plus.com Mon Aug 9 16:17:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 21:17:25 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> Message-ID: <4C606255.9000201@mrabarnett.plus.com> ????? wrote: > On 9 ???, 21:05, Thomas Jollans wrote: >> On Monday 09 August 2010, it occurred to ????? to exclaim: >> >>> On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: >>>> ????? wrote: >>>>> Please tell me that no matter what weird charhs has inside ic an still >>>>> open thosie fiels and make the neccessary replacements. >>>> Go back to 2.6 for the moment and defer learning about unicode until >>>> you're done with the conversion job. >>> You are correct again! 3.2 caused the problem, i switched to 2.7 and >>> now i donyt have that problem anymore. File is openign okey! >>> it ALMOST convert correctly! >>> # replace tags >>> print ( 'replacing php tags and contents within' ) >>> src_data = re.sub( '<\?(.*?)\?>', '', src_data ) >>> it only convert the first instance of php tages and not the rest? >>> But why? >> http://docs.python.org/library/re.html#re.S >> >> You probably need to pass the re.DOTALL flag. > > src_data = re.sub( '<\?(.*?)\?>', '', src_data, re.DOTALL ) > > like this? re.sub doesn't accept a flags argument. You can put the flag inside the regex itself like this: src_data = re.sub(r'(?s)<\?(.*?)\?>', '', src_data) (Note that the abbreviation for re.DOTALL is re.S and the inline flag is '(?s)'. This is for historical reasons! :-)) From robert.kern at gmail.com Mon Aug 9 16:23:11 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 09 Aug 2010 15:23:11 -0500 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: <4C5FE994.1040103@sschwarzer.net> References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> <4C5FE994.1040103@sschwarzer.net> Message-ID: On 2010-08-09 06:42 , Stefan Schwarzer wrote: > Hi Steven, > > On 2010-08-09 10:21, Steven D'Aprano wrote: >> And that it's quite finicky about blank lines between methods and inside >> functions. Makes it hard to paste code directly into the interpreter. >> >> And that pasting doesn't strip out any leading prompts. It needs a good >> doctest mode. > > ipython [1] should help here: > > IPython 0.10 -- An enhanced Interactive Python. > ? -> Introduction and overview of IPython's features. > %quickref -> Quick reference. > help -> Python's own help system. > object? -> Details about 'object'. ?object also works, ?? prints more. > In [1]: %paste? > Type: Magic function > Base Class: > String Form:> > Namespace: IPython internal > File: /usr/lib/pymodules/python2.6/IPython/Magic.py > Definition: %paste(self, parameter_s='') > Docstring: > Allows you to paste& execute a pre-formatted code block from clipboard. > > The text is pulled directly from the clipboard without user > intervention. > > The block is dedented prior to execution to enable execution of method > definitions. '>' and '+' characters at the beginning of a line are > ignored, to allow pasting directly from e-mails, diff files and > doctests (the '...' continuation prompt is also stripped). The > executed block is also assigned to variable named 'pasted_block' for > later editing with '%edit pasted_block'. > > You can also pass a variable name as an argument, e.g. '%paste foo'. > This assigns the pasted block to variable 'foo' as string, without > dedenting or executing it (preceding>>> and + is still stripped) > > '%paste -r' re-executes the block previously entered by cpaste. > > IPython statements (magics, shell escapes) are not supported (yet). > > See also > -------- > cpaste: manually paste code into terminal until you mark its end. > > Unfortunatey, when I enter > > In [2]: %paste > > at the prompt it gives me (before I pasted anything) > > In [2]: %paste > ------------------------------------------------------------ > File "", line 1 > http://pypi.python.org/pypi/ipython/0.10 > ^ > SyntaxError: invalid syntax Yes, that's because you had that URL in your clipboard, not Python code. What were you expecting to happen? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From python at mrabarnett.plus.com Mon Aug 9 16:28:11 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 21:28:11 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> Message-ID: <4C6064DB.3090801@mrabarnett.plus.com> ????? wrote: > On 9 ???, 10:07, ????? wrote: >> Now the code looks as follows: >> >> ============================= >> #!/usr/bin/python >> >> import re, os, sys >> >> id = 0 # unique page_id >> >> for currdir, files, dirs in os.walk('test'): >> >> for f in files: >> >> if f.endswith('php'): >> [snip] >> >> I just tried to test it. I created a folder names 'test' in me 'd:\' >> drive. >> Then i have put to .php files inside form the original to test if it >> would work ok for those too files before acting in the whole copy and >> after in the original project. >> >> so i opened a 'cli' form my Win7 and tried >> >> D:\>convert.py >> >> D:\> >> >> Itsjust printed an empty line and nothign else. Why didn't even try to >> open the folder and fiels within? >> Syntactically it doesnt ghive me an error! >> Somehting with os.walk() methos perhaps? > > Can you help in this too please? > > Now iam able to just convrt a single file 'd:\test\index.php' > > But these needs to be done for ALL the php files in every subfolder. > >> for currdir, files, dirs in os.walk('test'): >> >> for f in files: >> >> if f.endswith('php'): > > Should the above lines enter folders and find php files in each folder > so to be edited? I'd start by commenting-out the lines which change the files and then add some more print statements to see which files it's finding. That might give a clue. Only when it's fixed and finding the correct files would I remove the additional print statements and then restore the commented lines. From nikos.the.gr33k at gmail.com Mon Aug 9 16:30:42 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 13:30:42 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> Message-ID: <40382ef4-b443-4d5b-86f3-fd2490185ca9@z10g2000yqb.googlegroups.com> On 9 ???, 23:17, MRAB wrote: > ????? wrote: > > On 9 ???, 21:05, Thomas Jollans wrote: > >> On Monday 09 August 2010, it occurred to ????? to exclaim: > > >>> On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > >>>> ????? wrote: > >>>>> Please tell me that no matter what weird charhs has inside ic an still > >>>>> open thosie fiels and make the neccessary replacements. > >>>> Go back to 2.6 for the moment and defer learning about unicode until > >>>> you're done with the conversion job. > >>> You are correct again! 3.2 caused the problem, i switched to 2.7 and > >>> now i donyt have that problem anymore. File is openign okey! > >>> it ALMOST convert correctly! > >>> # replace tags > >>> print ( 'replacing php tags and contents within' ) > >>> src_data = re.sub( '<\?(.*?)\?>', '', src_data ) > >>> it only convert the first instance of php tages and not the rest? > >>> But why? > >>http://docs.python.org/library/re.html#re.S > > >> You probably need to pass the re.DOTALL flag. > > > ?src_data = re.sub( '<\?(.*?)\?>', '', src_data, re.DOTALL ) > > > like this? > > re.sub doesn't accept a flags argument. You can put the flag inside the > regex itself like this: > > ? ? ?src_data = re.sub(r'(?s)<\?(.*?)\?>', '', src_data) > > (Note that the abbreviation for re.DOTALL is re.S and the inline flag is > '(?s)'. This is for historical reasons! :-)) This is for the '.' to match any character including '\n' too right? so no matter if the php start tag and the end tag is in different lines still to be matched, correct? We nned the 'raw' string as well? why? The regex doens't cotnain backslashes. From bartc at freeuk.com Mon Aug 9 16:36:01 2010 From: bartc at freeuk.com (Bartc) Date: Mon, 9 Aug 2010 21:36:01 +0100 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: "Nobody" wrote in message news:pan.2010.08.07.15.23.59.515000 at nowhere.com... > On Sat, 07 Aug 2010 13:48:32 +0200, News123 wrote: > >>> "Common sense" is wrong. There are many compelling advantages to >>> numbering from zero instead of one: >>> >>> http://lambda-the-ultimate.org/node/1950 >> >> It makes sense in assembly language and even in many byte code languages. >> It makes sense if you look at the internal representation of unsigned >> numbers (which might become an index) > > It also makes sense mathematically. E.g. for an MxN array stored as a > 1-dimensional array, the element a[j][i] is at index > > j * N + i > > with zero-based indices but: > > (j-1) * N + (i-1) + 1 > = j * N + i - N > > with one-based indices. In other words, an extra offset to be added, in an expression already using a multiply and add, and which likely also needs an extra multiply and add to get the byte address of the element. (And often, the a[j][i] expression will be in a loop, which can be compiled to a pointer that just steps from one element to the next using a single add.) The indices i and j might anyway be user data which happens to be 1-based. And if the context is Python, I doubt whether the choice of 0-based over a 1-based makes that much difference in execution speed. (I've implemented languages that allow both 0 and 1-based indexing (and N-based for that matter). Both are useful. But my interpreted languages tend to use 1-based default indexing as it seems more natural and 'obvious') > > IOW, if a language uses one-based indices, it will inevitably end up > converting to and from zero-based indices under the hood, Sometimes. At the very low level (static, fixed array), the cost is absorbed into the address calculation. At a higher level, the cost is less significant, or there might be tricks to avoid the extra addition. > and may end up > forcing the user to do likewise if they need to do their own array > manipulation. Lots of things require this sort of calculation, eg. how many pages are needed to print 267 lines of text at 60 lines per page? These counts are 1-based so it's (L-1)/P+1 (integer divide), or 5 pages. If we switch to 0-based counting, it's just L/P ('266' lines require '4' pages), but who's going to explain that to the user? -- Bartc From nikos.the.gr33k at gmail.com Mon Aug 9 17:05:53 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 14:05:53 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> Message-ID: <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> On 9 ???, 23:28, MRAB wrote: > ????? wrote: > > On 9 ???, 10:07, ????? wrote: > >> Now the code looks as follows: > > >> ============================= > >> #!/usr/bin/python > > >> import re, os, sys > > >> id = 0 ?# unique page_id > > >> for currdir, files, dirs in os.walk('test'): > > >> ? ? ? ? for f in files: > > >> ? ? ? ? ? ? ? ? if f.endswith('php'): > > [snip] > > >> I just tried to test it. I created a folder names 'test' in me 'd:\' > >> drive. > >> Then i have put to .php files inside form the original to test if it > >> would work ok for those too files before acting in the whole copy and > >> after in the original project. > > >> so i opened a 'cli' form my Win7 and tried > > >> D:\>convert.py > > >> D:\> > > >> Itsjust printed an empty line and nothign else. Why didn't even try to > >> open the folder and fiels within? > >> Syntactically it doesnt ghive me an error! > >> Somehting with os.walk() methos perhaps? > > > Can you help in this too please? > > > Now iam able to just convrt a single file 'd:\test\index.php' > > > But these needs to be done for ALL the php files in every subfolder. > > >> for currdir, files, dirs in os.walk('test'): > > >> ? ? ? ? for f in files: > > >> ? ? ? ? ? ? ? ? if f.endswith('php'): > > > Should the above lines enter folders and find php files in each folder > > so to be edited? > > I'd start by commenting-out the lines which change the files and then > add some more print statements to see which files it's finding. That > might give a clue. Only when it's fixed and finding the correct files > would I remove the additional print statements and then restore the > commented lines. I did that, but it doesnt even get to the 'test' folder to search for the files! From torriem at gmail.com Mon Aug 9 17:13:04 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 09 Aug 2010 15:13:04 -0600 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <4C606F60.1010004@gmail.com> On 08/09/2010 06:11 AM, saeed.gnu wrote: > On Aug 9, 3:41 pm, "saeed.gnu" wrote: >> "x is y" means "id(y) == id(y)" >> "x is not y" means "id(x) != id(x)" >> "x is not None" means "id(x) != id(None)" >> >> "x is not None" is a really silly statement!! because id(None) and id >> of any constant object is not predictable! I don't know whay people >> use "is" instead of "==". you should write "if x!=None" instead of "x >> is not None" > > Although small objects are unique in the memory (with a unique id) and > using "is" works ok, but that's not logical to compare id's when we > actually want to compare values! Sounds like you're confusing Python's namespace with variables. When I say: a = None I'm binding the None object to the a name. Thus a *is* None. While in theory "None" does have a value, doing "a is None" is much more explicit and clearer than "a == None" although perhaps the result is the same. In any event "a is None" is actually logical because that's what I'm normally interested in. Whether or not a is None. I don't really care about the value of None. From nikos.the.gr33k at gmail.com Mon Aug 9 17:15:30 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 14:15:30 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> Message-ID: <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> D:\>convert.py File "D:\convert.py", line 34 SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line 34, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details D:\> What does it refering too? what character cannot be identified? Line 34 is: src_data = src_data.replace( '', '

??????? ??????????: %(counter)d ' ) Also, for currdir, files, dirs in os.walk('test'): for f in files: if f.lower().endswith("php"): in the above lines should i state os.walk('test') or os.walk('d:\test') ? From sschwarzer at sschwarzer.net Mon Aug 9 17:43:08 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 09 Aug 2010 23:43:08 +0200 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> <4C5FE994.1040103@sschwarzer.net> Message-ID: <4C60766C.30401@sschwarzer.net> Hi Robert, On 2010-08-09 22:23, Robert Kern wrote: > On 2010-08-09 06:42 , Stefan Schwarzer wrote: >> Unfortunatey, when I enter >> >> In [2]: %paste >> >> at the prompt it gives me (before I pasted anything) >> >> In [2]: %paste >> ------------------------------------------------------------ >> File "", line 1 >> http://pypi.python.org/pypi/ipython/0.10 >> ^ >> SyntaxError: invalid syntax > > Yes, that's because you had that URL in your clipboard, not Python code. What > were you expecting to happen? I got that traceback as soon as I typed in "%paste" and pressed enter, without pasting anything in the terminal. I had assumed it works like :paste in Vim, activating a kind of "paste mode" where everything pasted into the terminal is modified as the help text suggests. Ok, I just noticed I should have actually _read_ the help text, not just scanned it. ;-) Sorry for the confusion. Stefan From sschwarzer at sschwarzer.net Mon Aug 9 17:47:14 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 09 Aug 2010 23:47:14 +0200 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: <4C60766C.30401@sschwarzer.net> References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> <4C5FE994.1040103@sschwarzer.net> <4C60766C.30401@sschwarzer.net> Message-ID: <4C607762.2080506@sschwarzer.net> On 2010-08-09 23:43, Stefan Schwarzer wrote: > I got that traceback as soon as I typed in "%paste" and > pressed enter, without pasting anything in the terminal. > I had assumed it works like :paste in Vim, activating a I meant ":set paste" of course. Stefan From tinnews at isbd.co.uk Mon Aug 9 17:52:39 2010 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Mon, 9 Aug 2010 22:52:39 +0100 Subject: mailbox.mbox not locking mbox properly Message-ID: <7u96j7-l8i.ln1@chris.zbmc.eu> I'm using the python mailbox class in a script that processes incoming mail and delivers it to various mbox format mailboxes. It appears that, although I am calling the lock method on the destination before writing to the mbox and calling unlock afterwards the locking isn't working correctly. I am reading the mail with mutt, if I deliver the mail direct using Postfix (i.e. bypassing my python script) mutt works perfectly and shows new mail arriving in the mailbox as expected with an 'N' flag beside it. If I deliver the mail with my python script I get an error from mutt saying "Mailbox was externally modified. Flags may be wrong.", or if I'm reading the mbox via NFS I get all sorts of strange errors (though again it works perfectly if Postfix writes to the mbox). So it seems that python's mailbox class locking isn't playing nicely with mutt's mailbox locking whereas postfix's locking does work correctly. Has anyone seen this problem before, and/or do I need to anything more than the following for the locking to work correctly:- # # # set up the mb for adding the new message, will create if it doesn't exist # dest = mailbox.mbox(mbName, factory=None) dest.lock() dest.add(m) # add the new message dest.flush() dest.unlock() Any help/comments most welcome -- Chris Green From python at mrabarnett.plus.com Mon Aug 9 18:32:53 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 23:32:53 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <40382ef4-b443-4d5b-86f3-fd2490185ca9@z10g2000yqb.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> <40382ef4-b443-4d5b-86f3-fd2490185ca9@z10g2000yqb.googlegroups.com> Message-ID: <4C608215.3080007@mrabarnett.plus.com> ????? wrote: > On 9 ???, 23:17, MRAB wrote: >> ????? wrote: >>> On 9 ???, 21:05, Thomas Jollans wrote: >>>> On Monday 09 August 2010, it occurred to ????? to exclaim: >>>>> On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: >>>>>> ????? wrote: >>>>>>> Please tell me that no matter what weird charhs has inside ic an still >>>>>>> open thosie fiels and make the neccessary replacements. >>>>>> Go back to 2.6 for the moment and defer learning about unicode until >>>>>> you're done with the conversion job. >>>>> You are correct again! 3.2 caused the problem, i switched to 2.7 and >>>>> now i donyt have that problem anymore. File is openign okey! >>>>> it ALMOST convert correctly! >>>>> # replace tags >>>>> print ( 'replacing php tags and contents within' ) >>>>> src_data = re.sub( '<\?(.*?)\?>', '', src_data ) >>>>> it only convert the first instance of php tages and not the rest? >>>>> But why? >>>> http://docs.python.org/library/re.html#re.S >>>> You probably need to pass the re.DOTALL flag. >>> src_data = re.sub( '<\?(.*?)\?>', '', src_data, re.DOTALL ) >>> like this? >> re.sub doesn't accept a flags argument. You can put the flag inside the >> regex itself like this: >> >> src_data = re.sub(r'(?s)<\?(.*?)\?>', '', src_data) >> >> (Note that the abbreviation for re.DOTALL is re.S and the inline flag is >> '(?s)'. This is for historical reasons! :-)) > > This is for the '.' to match any character including '\n' too right? > so no matter if the php start tag and the end tag is in different > lines still to be matched, correct? > > We nned the 'raw' string as well? why? The regex doens't cotnain > backslashes. Yes it does; two of them! From jrmy.lnrd at gmail.com Mon Aug 9 18:34:36 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Mon, 9 Aug 2010 15:34:36 -0700 (PDT) Subject: Regular expression issue References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> Message-ID: <913a63f9-d8bd-40f1-b7b7-7d7b7fa480c6@c10g2000yqi.googlegroups.com> I have it now. Had to beat my head over it a couple times. Thanks everybody. From miki.tebeka at gmail.com Mon Aug 9 18:37:21 2010 From: miki.tebeka at gmail.com (Miki) Date: Mon, 9 Aug 2010 15:37:21 -0700 (PDT) Subject: I need a starter ptr writing python embedded in html. References: <3cc2a461-19f0-4aaf-9305-dde36fa2656c@v6g2000prd.googlegroups.com> Message-ID: <278a2eec-68d7-4ff9-81f1-623183988aff@i4g2000prf.googlegroups.com> > >> I'm ok in python but I haven't done too much with web pages. I have a web page > >> that is hand written in html that has about 1000 entries in a table and I want > >> to convert the table from entries like this > > >> ? ?

> >> ? ? ? > >> ? ? ? > >> ? ? ? > >> ? ? ? > >> ? ? ? > >> ? ? > > >> to > > >> ? ?SomePythonCall('Some Date String', > >> ? ? ? ? ? ? ? ? 'SomeTag', > >> ? ? ? ? ? ? ? ? 'localSubdir', > >> ? ? ? ? ? ? ? ? "http://www.example.com/remote/path/something.html", > >> ? ? ? ? ? ? ? ? 'Click', > >> ? ? ? ? ? ? ? ? 'Some Comment') > > >> Can someone tell me what I should look at to do this? Is mod_python where I > >> should start or are there things that are better? > > Have a look athttp://www.crummy.com/software/BeautifulSoup/. > > Thanks. But what I'm not seeing is any example of how to make this allowed to > generate the html at run time. Oh, I misunderstood you. You probably want one of the templating systems out there, such as Mako, Jinja2, Cheetah, ... Maybe http://cherrypy.org/wiki/intro/1 will be of help. All the best, -- Miki From python at mrabarnett.plus.com Mon Aug 9 18:43:17 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 23:43:17 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> Message-ID: <4C608485.1080703@mrabarnett.plus.com> ????? wrote: > D:\>convert.py > File "D:\convert.py", line 34 > SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line > 34, but no > encoding declared; see http://www.python.org/peps/pep-0263.html for > details > > D:\> > > What does it refering too? what character cannot be identified? > > Line 34 is: > > src_data = src_data.replace( '', '

color=green> ??????? ??????????: %(counter)d ' ) > Didn't you say that you're using Python 2.7 now? The default file encoding will be ASCII, but your file isn't ASCII, it contains Greek letters. Add the encoding line: # -*- coding: utf-8 -*- and check that the file is saved as UTF-8. > Also, > > for currdir, files, dirs in os.walk('test'): > > for f in files: > > if f.lower().endswith("php"): > > in the above lines > > should i state os.walk('test') or os.walk('d:\test') ? The path 'test' is relative to the current working directory. Is that D:\ for your script? If not, then it won't find the (correct) folder. It might be better to use an absolute path instead. You could use either: r'd:\test' (note that I've made it a raw string because it contains a backslash which I want treated as a literal backslash) or: 'd:/test' (Windows should accept a slash as well as of a backslash.) From aahz at pythoncraft.com Mon Aug 9 19:20:33 2010 From: aahz at pythoncraft.com (Aahz) Date: 9 Aug 2010 16:20:33 -0700 Subject: Python parsing XML file problem with SAX References: Message-ID: In article , Stefan Behnel wrote: >Aahz, 09.08.2010 18:52: >> In article, >> Stefan Behnel wrote: >>> >>> First of all: don't use SAX. Use ElementTree's iterparse() function. That >>> will shrink you code down to a simple loop in a few lines. >> >> Unless I'm missing something, that only helps if the final tree fits into >> memory. What do you suggest other than SAX if your XML file may be >> hundreds of megabytes? > >Well, what about using ElementTree's iterparse() function in that case? >That's what it's good at, and its cElementTree version is extremely fast. The docs say, "Parses an XML section into an element tree incrementally". Sure sounds like it retains the entire parsed tree in RAM. Not good. Again, how do you parse an XML file larger than your available memory using something other than SAX? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From atyazdi at ucdavis.edu Mon Aug 9 19:27:14 2010 From: atyazdi at ucdavis.edu (Anahita Yazdi) Date: Mon, 9 Aug 2010 16:27:14 -0700 Subject: Image histogram Message-ID: Hi, I was just wondering how would I be able to get some extra help regarding editing an image's histogram using python's module? I have modified a histogram of an image however I dont know how to apply the new histogram to the image and basically reload the image based on its new modified histogram instead of its own histogram? In the other words how should I make changes on an image's histogram in a way that the image recognizes the new histogram and gets changed? I need to somehow introduce a LUT for the image and use ".point(table)" function to reload the image however I am not sure how to make the right LUT from a modified histogram! Thanks for the help in advance, Anahita -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Mon Aug 9 19:39:44 2010 From: lists at cheimes.de (Christian Heimes) Date: Tue, 10 Aug 2010 01:39:44 +0200 Subject: Python parsing XML file problem with SAX In-Reply-To: References: Message-ID: Am 10.08.2010 01:20, schrieb Aahz: > The docs say, "Parses an XML section into an element tree incrementally". > Sure sounds like it retains the entire parsed tree in RAM. Not good. > Again, how do you parse an XML file larger than your available memory > using something other than SAX? The document at http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ explains it one way. The iterparser approach is ingenious but it doesn't work for every XML format. Let's say you have a 10 GB XML file with one million tags. An iterparser doesn't load the entire document. Instead it iterates over the file and yields (for example) one million ElementTrees for each tag and its children. You can get the nice API of ElementTree with the memory efficiency of a SAX parser if you obey "Listing 4". Christian From gherron at islandtraining.com Mon Aug 9 19:56:38 2010 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 09 Aug 2010 16:56:38 -0700 Subject: Image histogram In-Reply-To: References: Message-ID: <4C6095B6.4000509@islandtraining.com> On 08/09/2010 04:27 PM, Anahita Yazdi wrote: > Hi, > I was just wondering how would I be able to get some extra help > regarding editing an image's histogram using python's module? I have > modified a histogram of an image however I dont know how to apply the > new histogram to the image and basically reload the image based on its > new modified histogram instead of its own histogram? In the other > words how should I make changes on an image's histogram in a way that > the image recognizes the new histogram and gets changed? I need to > somehow introduce a LUT for the image and use ".point(table)" function > to reload the image however I am not sure how to make the right LUT > from a modified histogram! > Thanks for the help in advance, > Anahita This is a Python newsgroup, not an image processing news group. If you are asking for an algorithm to modify an image -- then you are on the wrong list, and you'd be better off asking on some image processing news group. If, on the other hand, you have an image processing algorithm in mind, then tell us about the algorithm, and we'll discuss how to implement it in Python. Gary Herron From no.email at nospam.invalid Mon Aug 9 20:02:26 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 09 Aug 2010 17:02:26 -0700 Subject: Image histogram References: Message-ID: <7x1va7ibcd.fsf@ruckus.brouhaha.com> Gary Herron writes: > This is a Python newsgroup, not an image processing news group. > If you are asking for an algorithm to modify an image.... I saw it as a question of how to do something using PIL. Seems ok to me. From ranjithtenz at gmail.com Mon Aug 9 20:44:36 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Tue, 10 Aug 2010 06:14:36 +0530 Subject: Python-list Digest, Vol 83, Issue 103 In-Reply-To: References: Message-ID: Hi Terry, > ---------- Forwarded message ---------- > From: Terry Reedy > To: python-list at python.org > Date: Mon, 09 Aug 2010 13:15:24 -0400 > Subject: Re: Need mentor > On 8/9/2010 2:31 AM, Ranjith Kumar wrote: > >> I have described the theme of my project here, >> > > Is this a class assignment or paid work? > I want to gain some scripting knowledge, so I asked my College senior student how to improvise the scripting knowledge he suggested me to start a new project and he himself gave me this idea. Its not paid work I just want to learn something. What i want my mentor to do is by suggesting me how to improve the coding standards and adding up some other features. Thanks for ur concerned Terry reedy. Awaiting for ur reply. -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Mon Aug 9 20:48:54 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 10 Aug 2010 12:48:54 +1200 Subject: Decorators without function In-Reply-To: References: Message-ID: <8cblevF28iU1@mid.individual.net> Vedran wrote: > @plot_decorator(fig_params1) > def plt(): > pylab.plot(..first graph data...) > pylab.plot(..second graph data..) > plt() You could do something like def call(f): f() @call @plot_decorator(fig_params1) def plt(): pylab.plot(..first graph data...) pylab.plot(..second graph data..) -- Greg From ranjithtenz at gmail.com Mon Aug 9 21:04:36 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Tue, 10 Aug 2010 06:34:36 +0530 Subject: Need mentor Message-ID: Hi Carey, ---------- Forwarded message ---------- From: Carey Tilden To: python-list at python.org Date: Mon, 9 Aug 2010 11:27:40 -0700 Subject: Re: Need mentor On Sun, Aug 8, 2010 at 11:31 PM, Ranjith Kumar wrote: > I have described the theme of my project here, >>It appears all you did was describe your project. Did you ask a question or seek any specific guidance? Did I miss something? I just seeking for guidance so i could come up with better result like adding new features and improve the coding style. Thats all why I described my project completely so anyone could guide me. I have three questions, 1) When the user logins into system the script should automatically starts running and only terminates the script when the user shut down or log out the system. 2) How to make the script running at the background(on the desktop)? 3) How to get the installed web browser`s list from a system and print it? Thanks in advance -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Mon Aug 9 21:18:35 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 10 Aug 2010 11:18:35 +1000 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <87iq3jz2ms.fsf@benfinney.id.au> "saeed.gnu" writes: > "x is y" means "id(y) == id(y)" > "x is not y" means "id(x) != id(x)" > "x is not None" means "id(x) != id(None)" No, the meanings are different. The behaviour might, or might not, be the same. The operators are different *because* the meanings are different. > "x is not None" is a really silly statement!! because id(None) and id > of any constant object is not predictable! The value returned from ?id? is not predictable; but it doesn't need to be predictable. It merely needs to obey the invariant that the identity of any given object won't change during the object's lifetime. -- \ ?You've got the brain of a four-year-old boy, and I'll bet he | `\ was glad to get rid of it.? ?Groucho Marx | _o__) | Ben Finney From gherron at islandtraining.com Mon Aug 9 21:23:38 2010 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 09 Aug 2010 18:23:38 -0700 Subject: Image histogram In-Reply-To: <7x1va7ibcd.fsf@ruckus.brouhaha.com> References: <7x1va7ibcd.fsf@ruckus.brouhaha.com> Message-ID: <4C60AA1A.4070804@islandtraining.com> On 08/09/2010 05:02 PM, Paul Rubin wrote: > Gary Herron writes: > >> This is a Python newsgroup, not an image processing news group. >> If you are asking for an algorithm to modify an image.... >> > I saw it as a question of how to do something using PIL. Seems ok to me. > A quote from the OP: "however I dont know how to apply the new histogram to the image" PIL has no such operation. I have no knowledge of any such operation. And frankly, I'm having a hard time imagining what "apply a histogram to the image" even means. (For instance if the original histogram says there are 30 pixels with some value, and the new histogram says there should be 20 pixels with that value -- which 10 do I replace, and with what do I replace them?) We can help him use PIL to read, manipulate, and write an image. But the actual manipulation he is requesting is so far unspecified. So I'll repeat: If he is looking for an algorithm -- I haven't got one. If he has an algorithm -- tell us about it, and we'll discuss implementing it in Python. Gary Herron From wuwei23 at gmail.com Mon Aug 9 21:24:29 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 9 Aug 2010 18:24:29 -0700 (PDT) Subject: I need a starter ptr writing python embedded in html. References: Message-ID: <2cb7fa82-dea8-40ac-9091-1a4d88dfe8cd@z34g2000pro.googlegroups.com> "Steven W. Orr" wrote: > I'm ok in python but I haven't done too much with web pages. I have a web page > that is hand written in html that has about 1000 entries in a table and I want > to convert the table [into html] Is the data coming from somewhere like a file or db? If so, I'd just use something simple like this html generator: http://pypi.python.org/pypi/html It's a very clever use of context managers to handle element nesting :) If the data doesn't change very often, I'd just write a simple script that parses the data source and builds a html page to server statically. If it does, it's not much extra to convert that to a WSGI script that returns the html string rather than creating a static file. I use this approach to produce a browseable table from a folder full of files with fixed-pattern names. Hope this helps. From sturlamolden at yahoo.no Mon Aug 9 21:51:44 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 9 Aug 2010 18:51:44 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> Message-ID: <60227fab-90e6-45b6-96b2-4fec205f3619@g33g2000yqc.googlegroups.com> On 9 Aug, 10:21, Steven D'Aprano wrote: > And that it's quite finicky about blank lines between methods and inside > functions. Makes it hard to paste code directly into the interpreter. The combination of editor, debugger and interpreter is what I miss most from Matlab. In Matlab we can have a function or script open in an editor, and use it directly from the interpreter. No need to reimport or anything: edit and invoke. It is also possible to paste data directly from the clipboard into variables in the interpreter. ipython does not have that annoying >>> prompt. From robert.kern at gmail.com Mon Aug 9 21:59:10 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 09 Aug 2010 20:59:10 -0500 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: <4C60766C.30401@sschwarzer.net> References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> <4C5FE994.1040103@sschwarzer.net> <4C60766C.30401@sschwarzer.net> Message-ID: On 8/9/10 4:43 PM, Stefan Schwarzer wrote: > Hi Robert, > > On 2010-08-09 22:23, Robert Kern wrote: >> On 2010-08-09 06:42 , Stefan Schwarzer wrote: >>> Unfortunatey, when I enter >>> >>> In [2]: %paste >>> >>> at the prompt it gives me (before I pasted anything) >>> >>> In [2]: %paste >>> ------------------------------------------------------------ >>> File "", line 1 >>> http://pypi.python.org/pypi/ipython/0.10 >>> ^ >>> SyntaxError: invalid syntax >> >> Yes, that's because you had that URL in your clipboard, not Python code. What >> were you expecting to happen? > > I got that traceback as soon as I typed in "%paste" and > pressed enter, without pasting anything in the terminal. > I had assumed it works like :paste in Vim, activating a > kind of "paste mode" where everything pasted into the > terminal is modified as the help text suggests. %cpaste will do that. I implemented %paste because not all terminals will correctly paste arbitrary amounts of code correctly. Grabbing the text directly from the clipboard is less error-prone and removes redundant user interaction. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rene7705 at gmail.com Mon Aug 9 22:18:34 2010 From: rene7705 at gmail.com (Rene Veerman) Date: Tue, 10 Aug 2010 04:18:34 +0200 Subject: need a json representation of all members of any type of object, list or hashtable (php's var_dump) Message-ID: hi. for 2 open source components of mine that are used in debugging, i would like to capture the output generated by print for any variable. i'm new to python, so please excuse my noobishness. i don't know if objects can be json-ed as easy as lists and hash tables are by print. and i couldn't find how to capture the output generated by print into a string, so i can't use it with google appengine :( i'm in dire need of some expert advise here. -- --------------------------------- Greetings from Rene7705, My free open source webcomponents: ? http://code.google.com/u/rene7705/ ? http://mediabeez.ws/downloads (and demos) My music (i'm DJ firesnake) ? http://mediabeez.ws/music http://www.facebook.com/rene7705 --------------------------------- From benjamin.kaplan at case.edu Mon Aug 9 22:43:24 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 9 Aug 2010 19:43:24 -0700 Subject: need a json representation of all members of any type of object, list or hashtable (php's var_dump) In-Reply-To: References: Message-ID: On Mon, Aug 9, 2010 at 7:18 PM, Rene Veerman wrote: > hi. > > for 2 open source components of mine that are used in debugging, i > would like to capture the output generated by print for any variable. > i'm new to python, so please excuse my noobishness. > > i don't know if objects can be json-ed as easy as lists and hash > tables are by print. > and i couldn't find how to capture the output generated by print into > a string, so i can't use it with google appengine :( > > i'm in dire need of some expert advise here. > Use str() to turn stuff into strings. From python at mrabarnett.plus.com Mon Aug 9 22:49:47 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 10 Aug 2010 03:49:47 +0100 Subject: need a json representation of all members of any type of object, list or hashtable (php's var_dump) In-Reply-To: References: Message-ID: <4C60BE4B.3090902@mrabarnett.plus.com> Rene Veerman wrote: > hi. > > for 2 open source components of mine that are used in debugging, i > would like to capture the output generated by print for any variable. > i'm new to python, so please excuse my noobishness. > > i don't know if objects can be json-ed as easy as lists and hash > tables are by print. > and i couldn't find how to capture the output generated by print into > a string, so i can't use it with google appengine :( > > i'm in dire need of some expert advise here. > Lookup the 'StringIO' module (Python 2.x): from StringIO import StringIO import sys old_stdout = sys.stdout saved_output = StringIO() try: sys.stdout = saved_output print "Hello world!" finally: sys.stdout = old_stdout print saved_output.getvalue() From lepto.python at gmail.com Mon Aug 9 23:04:31 2010 From: lepto.python at gmail.com (oyster) Date: Tue, 10 Aug 2010 11:04:31 +0800 Subject: how to let shell.SendKeys use unicode on windows in python Message-ID: I want to use python to do some automatical operation on windows. the following is the code, which try to open a file with unicode characters in its filename in msword but I can't get it work correctly. Can anybody help me? if that is the shortcoming of WScript, is there any other way to do so in python? (I know there is something like autohotkey, but I am not willing to learn a new langauge ) thanks in advance import time import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate('winword') time.sleep(0.1) shell.SendKeys('%fo') # Alt+F, O time.sleep(0.1) path=r'c:\some unicode in file name.doc' shell.SendKeys(path) # fail on this line, no unicode appeared shell.SendKeys('{ENTER}') From wuwei23 at gmail.com Mon Aug 9 23:56:35 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 9 Aug 2010 20:56:35 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <35161a8e-d56a-4615-8ba8-a99a81da257a@q16g2000prf.googlegroups.com> Alex Barna wrote: > So what happens to this field (Windows GUI automation) ? Either someone cares enough to do something about it, or everyone just defaults to using AutoIT-like tools. Which Python implementation are you planning on contributing to? From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 00:12:10 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 04:12:10 GMT Subject: iter References: Message-ID: <4c60d19a$0$11121$c3e8da3@news.astraweb.com> On Mon, 09 Aug 2010 09:11:37 -0700, daryn wrote: > I'm just playing around with the iter function and I realize that I can > use the iterator returned by it long after the original object has any > name bound to it. Yes, the same as everything else in Python. Iterators aren't unique here. >>> a = [1,2,3] >>> b = [None, a, None] >>> id(a) == id(b[1]) # Same object, not a copy? True >>> del a >>> print b [None, [1, 2, 3], None] > it seems as if the original object is never being garbage collected even > though there is no name bound to it. Of course not. That would be a Bad Thing if Python garbage collected an object while other objects were still using it. Can you say "core dump"? > Does the name bound to the > iterator object count as a reference to the original object for garbage > collection purposes? No, but the iterator itself does. The technique is called *reference* counting, not "name counting". Each name is a reference, but not every reference is a name. > Is there some way to retrieve/manipulate the > original object via the iterator? Depends on the iterator. For the standard iterator created by iter(), I don't think so. But for a custom iterator type, there can be if you want: class MyIter(object): """Quick and dirty iterator.""" def __init__(self, data): self.data = data self.i = 0 def __iter__(self): return self def next(self): try: o = self.data[self.i] except IndexError: raise StopIteration self.i += 1 return o >>> it = MyIter([1,2,3,4]) >>> it.next() 1 >>> del it.data[1:3] >>> it.next() 4 -- Steven From navkirats at gmail.com Tue Aug 10 00:32:49 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Tue, 10 Aug 2010 10:02:49 +0530 Subject: favicon.ico problem Message-ID: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Hi guys, I am having this strange problem. I have programmed a very basic multiprocessing webserver using low level sockets. Each time the server receives a request it spawns a new process to handle the request. Now when through a web browser I type http://localhost:8001/ it automatically creates two processes: One process to server the '/' path and another one to serve the '/favicon.ico' path. I have not programmed it to serve the latter. Infact I dont even know where that name '/favicon.ico' comes from. Any insight into this weird behavior would be greatly appreciated. Regards, Nav From nad at acm.org Tue Aug 10 00:48:36 2010 From: nad at acm.org (Ned Deily) Date: Mon, 09 Aug 2010 21:48:36 -0700 Subject: favicon.ico problem References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Message-ID: In article <9F21F146-A43A-4108-962B-4DFA14E430E4 at gmail.com>, Navkirat Singh wrote: > I am having this strange problem. I have programmed a very basic > multiprocessing webserver using low level sockets. Each time the server > receives a request it spawns a new process to handle the request. Now when > through a web browser I type http://localhost:8001/ it automatically creates > two processes: One process to server the '/' path and another one to serve > the '/favicon.ico' path. I have not programmed it to serve the latter. Infact > I dont even know where that name '/favicon.ico' comes from. Any insight into > this weird behavior would be greatly appreciated. It's not the server's doing, it's the web browser requesting the favicon. See http://en.wikipedia.org/wiki/Favicon -- Ned Deily, nad at acm.org From John Tue Aug 10 00:53:10 2010 From: John (John) Date: Tue, 10 Aug 2010 00:53:10 -0400 Subject: File Manager in Tkinter Message-ID: As a learning exercise in Tkinter I htought about making a very simple and basic file manager for my own use. I tried searching google for any sample project and could not find anything. Not exactly sure how to start I tought I could ask here? I thought about making two listboxes one to list folders only the other files inside. I tried to make one listbox first but did not know how to list folders only. from Tkinter import * import os path = "D:\\" s = Scrollbar() L = Listbox() s.pack(side=RIGHT, fill=Y) L.pack(side=LEFT, fill=Y) s.config(command=L.yview) L.config(yscrollcommand=s.set) for filename in os.listdir(path): L.insert(END, filename) mainloop() Is there a way to list folders with images? Any suggestions or help how to proced would be appreciated. Thank you From chris.gonnerman at newcenturycomputers.net Tue Aug 10 00:56:15 2010 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 09 Aug 2010 23:56:15 -0500 Subject: [Python] favicon.ico problem In-Reply-To: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Message-ID: <4C60DBEF.505@newcenturycomputers.net> On 08/09/2010 11:32 PM, Navkirat Singh wrote: > I am having this strange problem. I have programmed a very basic multiprocessing webserver using low level sockets. Each time the server receives a request it spawns a new process to handle the request. Now when through a web browser I type http://localhost:8001/ it automatically creates two processes: One process to server the '/' path and another one to serve the '/favicon.ico' path. I have not programmed it to serve the latter. Infact I dont even know where that name '/favicon.ico' comes from. Any insight into this weird behavior would be greatly appreciated. > All modern browsers attempt to retrieve this file from any web server visited; it becomes the website's icon in any shortcut/deskcut, and appears on the address bar beside the URL. Short answer: You can safely ignore it. -- Chris. From clp2 at rebertia.com Tue Aug 10 01:07:09 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 9 Aug 2010 22:07:09 -0700 Subject: File Manager in Tkinter In-Reply-To: References: Message-ID: On Mon, Aug 9, 2010 at 9:53 PM, wrote: > As a learning exercise in Tkinter I htought about making a very simple > and basic file manager for my own use. I tried searching google for > any sample project and could not find anything. Not exactly ?sure how > to start I tought I could ask here? > > I thought about making two listboxes one to list folders only the > other files inside. I tried to make one listbox first but did not know > how to list folders only. os.path.isdir() tests a path for directory-ness. Check out the os.path std lib module generally: http://docs.python.org/library/os.path.html Cheers, Chris -- http://blog.rebertia.com From nikos.the.gr33k at gmail.com Tue Aug 10 01:11:44 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 22:11:44 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> Message-ID: <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> On 10 ???, 01:43, MRAB wrote: > ????? wrote: > > D:\>convert.py > > ? File "D:\convert.py", line 34 > > SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line > > 34, but no > > ?encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor > > details > > > D:\> > > > What does it refering too? what character cannot be identified? > > > Line 34 is: > > > src_data = src_data.replace( '', '

> color=green> ??????? ??????????: %(counter)d ' ) > > Didn't you say that you're using Python 2.7 now? The default file > encoding will be ASCII, but your file isn't ASCII, it contains Greek > letters. Add the encoding line: > > ? ? ?# -*- coding: utf-8 -*- > > and check that the file is saved as UTF-8. > > > Also, > > > for currdir, files, dirs in os.walk('test'): > > > ? ?for f in files: > > > ? ? ? ? ? ?if f.lower().endswith("php"): > > > in the above lines > > > should i state ?os.walk('test') or ?os.walk('d:\test') ? > > The path 'test' is relative to the current working directory. Is that > D:\ for your script? If not, then it won't find the (correct) folder. > > It might be better to use an absolute path instead. You could use > either: > > ? ? ?r'd:\test' > > (note that I've made it a raw string because it contains a backslash > which I want treated as a literal backslash) or: > > ? ? ?'d:/test' > > (Windows should accept a slash as well as of a backslash.) I will try it as soon as i make another change that i missed: The ID number of each php page was contained in the old php code within this string PageID = some_number So instead of create a new ID number for eaqch page i have to pull out this number to store to the beginnign to the file as comment line, because it has direct relationship with the mysql database as in tracking the number of each webpage and finding the counter of it. # Grab the PageID contained within the php code and store it in id variable id = re.search( 'PageID = ', src_data ) How to tell Python to Grab that number after 'PageID = ' string and to store it in var id that a later use in the program? also i made another changewould something like this work: =============================== # open same php file for storing modified data print ( 'writing to %s' % dest_f ) f = open(src_f, 'w') f.write(src_data) f.close() # rename edited .php file to .html extension dst_f = src_f.replace('.php', '.html') os.rename( src_f, dst_f ) =============================== Because instead of creating a new .html file and inserting the desired data of the old php thus having two files(old php, and new html) i decided to open the same php file for writing that data and then rename it to html. Would the above code work? From gradyknotts at gmail.com Tue Aug 10 01:17:03 2010 From: gradyknotts at gmail.com (Grady Knotts) Date: Tue, 10 Aug 2010 00:17:03 -0500 Subject: Using the print command in Python3 Message-ID: <516FACB9-3BBE-424E-B406-DDE5F5039292@gmail.com> In earlier versions of Python I can do: print 'A', print 'B' to print everything on the same line: 'A B' But I don't know how to do this with Python3 I've been trying things like: print('A',) print('B') and it prints two different lines. So, do I get two different print statements to output on the same line? From zhxia at njnet.edu.cn Tue Aug 10 01:27:39 2010 From: zhxia at njnet.edu.cn (Xia, Zhen) Date: Tue, 10 Aug 2010 13:27:39 +0800 Subject: favicon.ico problem In-Reply-To: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Message-ID: <20100810132739.e2e17b33.zhxia@njnet.edu.cn> On Tue, 10 Aug 2010 10:02:49 +0530 Navkirat Singh wrote: > Hi guys, > > I am having this strange problem. I have programmed a very basic multiprocessing webserver using low level sockets. Each time the server receives a request it spawns a new process to handle the request. Now when through a web browser I type http://localhost:8001/ it automatically creates two processes: One process to server the '/' path and another one to serve the '/favicon.ico' path. I have not programmed it to serve the latter. Infact I dont even know where that name '/favicon.ico' comes from. Any insight into this weird behavior would be greatly appreciated. > > Regards, > Nav > -- > http://mail.python.org/mailman/listinfo/python-list Your server just need to return an HTTP 404 response for this 'favicon.ico' request. -- Xia, Zhen From benjamin.kaplan at case.edu Tue Aug 10 01:34:54 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 9 Aug 2010 22:34:54 -0700 Subject: Using the print command in Python3 In-Reply-To: <516FACB9-3BBE-424E-B406-DDE5F5039292@gmail.com> References: <516FACB9-3BBE-424E-B406-DDE5F5039292@gmail.com> Message-ID: On Mon, Aug 9, 2010 at 10:17 PM, Grady Knotts wrote: > In earlier versions of Python I can do: > ? ? ? ?print 'A', > ? ? ? ?print 'B' > to print everything on the same line: 'A B' > > But I don't know how to do this with Python3 > I've been trying things like: > ? ? ? ?print('A',) > ? ? ? ?print('B') > and it prints two different lines. > > So, do I get two different print statements to output on the same line? > >>> help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. From navkirats at gmail.com Tue Aug 10 01:54:26 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Tue, 10 Aug 2010 11:24:26 +0530 Subject: favicon.ico problem In-Reply-To: <20100810132739.e2e17b33.zhxia@njnet.edu.cn> References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> <20100810132739.e2e17b33.zhxia@njnet.edu.cn> Message-ID: On 10-Aug-2010, at 10:57 AM, Xia, Zhen wrote: > On Tue, 10 Aug 2010 10:02:49 +0530 > Navkirat Singh wrote: > >> Hi guys, >> >> I am having this strange problem. I have programmed a very basic multiprocessing webserver using low level sockets. Each time the server receives a request it spawns a new process to handle the request. Now when through a web browser I type http://localhost:8001/ it automatically creates two processes: One process to server the '/' path and another one to serve the '/favicon.ico' path. I have not programmed it to serve the latter. Infact I dont even know where that name '/favicon.ico' comes from. Any insight into this weird behavior would be greatly appreciated. >> >> Regards, >> Nav >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Your server just need to return an HTTP 404 response for this 'favicon.ico' request. > > > -- > Xia, Zhen > -- > http://mail.python.org/mailman/listinfo/python-list Thanks guys ! That explains it ! Nav From navkirats at gmail.com Tue Aug 10 01:59:58 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Tue, 10 Aug 2010 11:29:58 +0530 Subject: Using the print command in Python3 In-Reply-To: References: <516FACB9-3BBE-424E-B406-DDE5F5039292@gmail.com> Message-ID: On 10-Aug-2010, at 11:04 AM, Benjamin Kaplan wrote: > On Mon, Aug 9, 2010 at 10:17 PM, Grady Knotts wrote: >> In earlier versions of Python I can do: >> print 'A', >> print 'B' >> to print everything on the same line: 'A B' >> >> But I don't know how to do this with Python3 >> I've been trying things like: >> print('A',) >> print('B') >> and it prints two different lines. >> >> So, do I get two different print statements to output on the same line? >> > > >>>> help(print) > Help on built-in function print in module builtins: > > print(...) > print(value, ..., sep=' ', end='\n', file=sys.stdout) > > Prints the values to a stream, or to sys.stdout by default. > Optional keyword arguments: > file: a file-like object (stream); defaults to the current sys.stdout. > sep: string inserted between values, default a space. > end: string appended after the last value, default a newline. > -- > http://mail.python.org/mailman/listinfo/python-list One method of doing this: Use the join method of the string: print( "".join( [ 'A' , ' B' ] ) This will give you : 'AB' I have used extra spaces just for clarity. Hope this helps ! Nav From timr at probo.com Tue Aug 10 02:19:21 2010 From: timr at probo.com (Tim Roberts) Date: Mon, 09 Aug 2010 23:19:21 -0700 Subject: Microsoft lessening commitment to IronPython and IronRuby References: Message-ID: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Lawrence D'Oliveiro wrote: > >Frankly I never understood the point of IronPython and IronRuby. They seemed >like a desperate attempt to keep Dotnet relevant in the modern world of >dynamic languages. Looks like it was a failure. Yawn. I'm not sure that's really fair. The .NET Common Language Runtime is a vast and very useful class library, including two complete GUI systems. The thought was that IronPython and IronRuby would let people who were comfortable in those languages tap into the CLR. In the end, it seemed to me that writing an IronPython program was mostly an exercise of writing it in C# and then translating. .NET is just too "tuned" for C# and VB. Although IronPython was a good fit, it was just not a great fit. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From timr at probo.com Tue Aug 10 02:28:16 2010 From: timr at probo.com (Tim Roberts) Date: Mon, 09 Aug 2010 23:28:16 -0700 Subject: mailbox.mbox not locking mbox properly References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: tinnews at isbd.co.uk wrote: > >I'm using the python mailbox class in a script that processes incoming >mail and delivers it to various mbox format mailboxes. It appears >that, although I am calling the lock method on the destination before >writing to the mbox and calling unlock afterwards the locking isn't >working correctly. >... >So it seems that python's mailbox class locking isn't playing nicely >with mutt's mailbox locking whereas postfix's locking does work >correctly. Correct. The "dest.flush()" method creates a temporary file, copies the entire modified mailbox into it, removed the original file, and renames the temp file into place. The Postfix MDA, like most MDAs, just opens the existing file and appends the new data to it. >Has anyone seen this problem before, and/or do I need to anything more >than the following for the locking to work correctly:- It's not the locking. It's the flush mechanism. The mbox class doesn't know that the ONLY thing you did was an append. You might have modified other messages in the middle. If you want to do an append, you'll need to write your own subclass of mbox. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From stefan_ml at behnel.de Tue Aug 10 02:35:15 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 10 Aug 2010 08:35:15 +0200 Subject: Python parsing XML file problem with SAX In-Reply-To: References: Message-ID: Christian Heimes, 10.08.2010 01:39: > Am 10.08.2010 01:20, schrieb Aahz: >> The docs say, "Parses an XML section into an element tree incrementally". >> Sure sounds like it retains the entire parsed tree in RAM. Not good. >> Again, how do you parse an XML file larger than your available memory >> using something other than SAX? > > The document at > http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ explains it > one way. > > The iterparser approach is ingenious but it doesn't work for every XML > format. Let's say you have a 10 GB XML file with one million > tags. An iterparser doesn't load the entire document. Instead it > iterates over the file and yields (for example) one million ElementTrees > for each tag and its children. You can get the nice API of > ElementTree with the memory efficiency of a SAX parser if you obey > "Listing 4". In the very common case that you are interested in all children of the root element, it's even enough to intercept on the specific tag name (lxml.etree has an option for that, but an 'if' block will do just fine in ET) and just ".clear()" the child element at the end of the loop body. That results in very fast and simple code, but will leave the tags in the tree while only removing their content and attributes. Usually works well enough for several ten thousand elements, especially when using cElementTree. As usual, a bit of benchmarking will uncover the right way to do it in your case. That's also a huge advantage over SAX: iterparse code is much easier to tune into a streamlined loop body when you need it. Stefan From ldo at geek-central.gen.new_zealand Tue Aug 10 02:42:35 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 10 Aug 2010 18:42:35 +1200 Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Message-ID: In message <7fr16650meigqgmj8rh0n3a66q9r4j4eva at 4ax.com>, Tim Roberts wrote: > The .NET Common Language Runtime is a vast and very useful class library, > including two complete GUI systems. Used only by corporate code-cutter drones. Go on, name one creative thing which was ever done in Dotnet. From stefan_ml at behnel.de Tue Aug 10 03:02:18 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 10 Aug 2010 09:02:18 +0200 Subject: Microsoft lessening commitment to IronPython and IronRuby In-Reply-To: References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Message-ID: Lawrence D'Oliveiro, 10.08.2010 08:42: > In message<7fr16650meigqgmj8rh0n3a66q9r4j4eva at 4ax.com>, Tim Roberts wrote: > >> The .NET Common Language Runtime is a vast and very useful class library, >> including two complete GUI systems. > > Used only by corporate code-cutter drones. > > Go on, name one creative thing which was ever done in Dotnet. Erm, this is Microsoft. It's not about being creative, it's about selling stuff to users. Stefan From eckhardt at satorlaser.com Tue Aug 10 03:06:49 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 10 Aug 2010 09:06:49 +0200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> Message-ID: <9da7j7-pv2.ln1@satorlaser.homedns.org> Carl Banks wrote: > I highly doubt the Python source would build with a C++ compiler. As Christian showed, it doesn't. However, look around the sources a bit. There are lots of places where e.g. the returnvalue of malloc() (or, rather, the macro that resolves to something like it) is explicitly type-cast to the according pointer type. When asked on the developers' list, it was said that this was intended for compatibility with C++, e.g. in cases where people want to embed Python into their C++ projects. Of course, this contradicts Christian's statement that C++ compatibility wasn't considered useful enough. *shrug* Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 03:58:27 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 07:58:27 GMT Subject: Using the print command in Python3 References: Message-ID: <4c6106a3$0$28655$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 00:17:03 -0500, Grady Knotts wrote: > In earlier versions of Python I can do: > print 'A', > print 'B' > to print everything on the same line: 'A B' > > But I don't know how to do this with Python3 I've been trying things > like: > print('A',) > print('B') > and it prints two different lines. > > So, do I get two different print statements to output on the same line? print("Hello", end=' ') print("world") outputs: Hello world -- Steven From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 04:04:17 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 08:04:17 GMT Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Message-ID: <4c610801$0$28655$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 18:42:35 +1200, Lawrence D'Oliveiro wrote: > In message <7fr16650meigqgmj8rh0n3a66q9r4j4eva at 4ax.com>, Tim Roberts > wrote: > >> The .NET Common Language Runtime is a vast and very useful class >> library, including two complete GUI systems. > > Used only by corporate code-cutter drones. > > Go on, name one creative thing which was ever done in Dotnet. Not just Dotnet, but Python on Dotnet. http://www.python.org/about/success/resolver/ http://blog.jonudell.net/2007/09/27/first-look-at-resolver-an-ironpython-based-spreadsheet/ -- Steven From ldo at geek-central.gen.new_zealand Tue Aug 10 04:05:12 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 10 Aug 2010 20:05:12 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message <56a18e2b-4967-4a63-852e-1eb53bb6e561 at j8g2000yqd.googlegroups.com>, Alex Barna wrote: > So what happens to this field (Windows GUI automation) ? Can?t understand the point to it. ?GUI automation? is a contradiction in terms, because a GUI is designed for use by humans to do manual tasks, not ones that can be automated. Tasks that can be automated are most easily, flexibly, and above all reliably, done via command lines and other such scripting interfaces. From greg.ewing at canterbury.ac.nz Tue Aug 10 04:07:06 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 10 Aug 2010 20:07:06 +1200 Subject: Microsoft lessening commitment to IronPython and IronRuby In-Reply-To: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Message-ID: <8ccf4kF38mU1@mid.individual.net> Tim Roberts wrote: > I'm not sure that's really fair. The .NET Common Language Runtime is a > vast and very useful class library, including two complete GUI systems. The > thought was that IronPython and IronRuby would let people who were > comfortable in those languages tap into the CLR. Is there any way for a non-.NET program to access a .NET library? Or is it necessary to drink the entire bottle of .NET kool-aid? -- Greg From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 04:20:35 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 08:20:35 GMT Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> Message-ID: <4c610bd2$0$28655$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 20:07:06 +1200, Gregory Ewing wrote: > Tim Roberts wrote: > >> I'm not sure that's really fair. The .NET Common Language Runtime is a >> vast and very useful class library, including two complete GUI systems. >> The thought was that IronPython and IronRuby would let people who were >> comfortable in those languages tap into the CLR. > > Is there any way for a non-.NET program to access a .NET library? Or is > it necessary to drink the entire bottle of .NET kool-aid? http://www.mono-project.com/Main_Page -- Steven From stefan_ml at behnel.de Tue Aug 10 04:32:43 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 10 Aug 2010 10:32:43 +0200 Subject: Microsoft lessening commitment to IronPython and IronRuby In-Reply-To: <4c610801$0$28655$c3e8da3@news.astraweb.com> References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <4c610801$0$28655$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano, 10.08.2010 10:04: > On Tue, 10 Aug 2010 18:42:35 +1200, Lawrence D'Oliveiro wrote: >> Go on, name one creative thing which was ever done in Dotnet. > > Not just Dotnet, but Python on Dotnet. > > http://www.python.org/about/success/resolver/ At the very end of that article, I found this statement: "Resolver One is Windows only" This sounds like a major drawback to me. It might be an acceptable "early project priority" if the app is only targeting the desktop, but this system additionally claims to be a "web-accessible spreadsheet". If this is supposed to run on a server, it means that it will always suffer from the "headless click-here-to-continue" problem. It might not be too hard to port the app to Mono, but the rather explicit claim above doesn't make me feel very comfortable about that upgrade path... Stefan From eric.brunel at pragmadev.com Tue Aug 10 04:40:53 2010 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 10 Aug 2010 10:40:53 +0200 Subject: File Manager in Tkinter References: Message-ID: In article , John wrote: > As a learning exercise in Tkinter I htought about making a very simple > and basic file manager for my own use. I tried searching google for > any sample project and could not find anything. Not exactly sure how > to start I tought I could ask here? > > I thought about making two listboxes one to list folders only the > other files inside. I tried to make one listbox first but did not know > how to list folders only. You just have to filter them explicitely by using os.path.isdir on each file name. > from Tkinter import * > import os > path = "D:\\" > > > s = Scrollbar() > L = Listbox() > > s.pack(side=RIGHT, fill=Y) > L.pack(side=LEFT, fill=Y) > > s.config(command=L.yview) > L.config(yscrollcommand=s.set) > > for filename in os.listdir(path): Add here: if os.path.isdir(os.path.join(path, filename)): > L.insert(END, filename) > > mainloop() > > > > Is there a way to list folders with images? AFAIK, not with a Listbox. You can do it with a Canvas, but it's much more complicated than using a Listbox, so maybe you should try to make your Listbox-only version works first. > Any suggestions or help how to proced would be appreciated. > > Thank you Good luck! From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 04:49:21 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 08:49:21 GMT Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4c611291$0$28655$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 20:05:12 +1200, Lawrence D'Oliveiro wrote: > In message > <56a18e2b-4967-4a63-852e-1eb53bb6e561 at j8g2000yqd.googlegroups.com>, Alex > Barna wrote: > >> So what happens to this field (Windows GUI automation) ? > > Can?t understand the point to it. ?GUI automation? is a contradiction in > terms, because a GUI is designed for use by humans to do manual tasks, > not ones that can be automated. There have been plenty of systems for recording user actions and playing them back. They're very useful at times. http://en.wikipedia.org/wiki/Macro_recorder http://en.wikipedia.org/wiki/Macro_(computer_science) You might even have heard of one of them... Emacs. I hear that it's moderately popular among Linux users. http://www.linuxjournal.com/article/3769 > Tasks that can be automated are most easily, flexibly, and above all > reliably, done via command lines and other such scripting interfaces. That's a matter of opinion, and it clearly depends on the nature of the GUI and CLI, as well as what task you're trying to automate. -- Steven From tzuchien.chiu at gmail.com Tue Aug 10 04:52:54 2010 From: tzuchien.chiu at gmail.com (Chien) Date: Tue, 10 Aug 2010 01:52:54 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <35161a8e-d56a-4615-8ba8-a99a81da257a@q16g2000prf.googlegroups.com> Message-ID: <2eea0548-2d5f-48ed-b597-009df537bdb1@j8g2000yqd.googlegroups.com> On Aug 10, 5:56?am, alex23 wrote: > Alex Barna wrote: > > So what happens to this field (Windows GUI automation) ? > > Either someone cares enough to do something about it, or everyone just > defaults to using AutoIT-like tools. There were a lot of development but then all ceased, except pywinauto has a final release in April, but really low community activity. Does it mean AutoIt has much more advantages than Python tools (which I have not realized) ? > Which Python implementation are you planning on contributing to? I'd say pywinauto. It's more O-O than the other tools. Excerpt from its homepage (http://pywinauto.openqa.org/): Most other tools are not object oriented you end up writing stuff like: window = findwindow(title = "Untitled - Notepad", class = "Notepad") SendKeys(window, "%OF") # Format -> Font fontdialog = findwindow("title = "Font") buttonClick(fontdialog, "OK") I was hoping to create something more userfriendly (and pythonic): win = app.UntitledNotepad win.MenuSelect("Format->Font") app.Font.OK.Click() Alex Barna From tinnews at isbd.co.uk Tue Aug 10 05:01:11 2010 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Tue, 10 Aug 2010 10:01:11 +0100 Subject: mailbox.mbox not locking mbox properly References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: Tim Roberts wrote: > tinnews at isbd.co.uk wrote: > > > >I'm using the python mailbox class in a script that processes incoming > >mail and delivers it to various mbox format mailboxes. It appears > >that, although I am calling the lock method on the destination before > >writing to the mbox and calling unlock afterwards the locking isn't > >working correctly. > >... > >So it seems that python's mailbox class locking isn't playing nicely > >with mutt's mailbox locking whereas postfix's locking does work > >correctly. > > Correct. The "dest.flush()" method creates a temporary file, copies the > entire modified mailbox into it, removed the original file, and renames the > temp file into place. > Yes, I just took a look at the mailbox.py code and it does exactly that which of course screws up just about any normal MUA looking at the mbox. Grrrrrr! > The Postfix MDA, like most MDAs, just opens the existing file and appends > the new data to it. > > >Has anyone seen this problem before, and/or do I need to anything more > >than the following for the locking to work correctly:- > > It's not the locking. It's the flush mechanism. The mbox class doesn't > know that the ONLY thing you did was an append. You might have modified > other messages in the middle. If you want to do an append, you'll need to > write your own subclass of mbox. OK, thanks. In reality I can probably just use straightforward file reading and writing as the *only* thing I will ever be doing is to append a message to a mailbox file. I think there should be a big warning in the mailbox documentation to this effect as doing it the way that Python's mailbox class does it will break all sorts of things. There should maybe be a specific 'append' method. -- Chris Green From eckhardt at satorlaser.com Tue Aug 10 05:01:26 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 10 Aug 2010 11:01:26 +0200 Subject: delegate functions to member Message-ID: <64h7j7-r73.ln1@satorlaser.homedns.org> Hi! I have an extension module (a plugin written with Boost.Python) and around that a wrapper class that adapts a few things. Since the module is a plugin, there are multiple implementations of this. What I'm currently doing is this: plugin = __import__(plugin_name) class PluginWrapper(plugin.PluginClass): ... This means that the definition of class PluginWrapper actually depends on the previously loaded module. What I would like to do is to define the wrapper just once and instead pass the plugin module to the constructor: class PluginWrapper(object): ... plugin = __import__(plugin_name) instance = PluginWrapper(plugin) Now, I use the wrapper to make some function more friendly (e.g. default parameters, keyword-parameters, wrapping raw handles) but I want other functions from the baseclass to remain untouched. If I use a baseclass, this lookup is automatic. However, when I pass the instance to the constructor, I have to store it in a member, and then I have to add code for every function only to delegate it to that member. Is there an easy and generic way out of this? Thanks! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From chris at simplistix.co.uk Tue Aug 10 05:04:26 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 10 Aug 2010 10:04:26 +0100 Subject: MailingLogger 3.3.3 Released! Message-ID: <4C61161A.3020205@simplistix.co.uk> I'm pleased to announce a new release of Mailinglogger. Mailinglogger provides two handlers for the standard python logging framework that enable log entries to be emailed either as the entries are logged or as a summary at the end of the running process. The handlers have the following features: - customisable and dynamic subject lines for emails sent - emails sent with an X-Mailer header for easy filtering - flood protection to ensure the number of emails sent is not excessive - support for SMTP servers that require authentication - fully documented and tested The latest releases of ZConfig provides a great way to configure the python logging framework without having to resort to the appalling .ini-based configuration stuff: >>> from ZConfig import configureLoggers >>> configureLoggers(''' ... ... level INFO ... ... PATH STDOUT ... format %(levelname)s %(name)s %(message)s ... ... ... ''') This release and the previous release fix some problems with interpolating non-text objects into log messages and running the tests in non-GMT timezones. For more information, please see: http://www.simplistix.co.uk/software/python/mailinglogger or http://pypi.python.org/pypi/mailinglogger cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From mail at timgolden.me.uk Tue Aug 10 05:08:37 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 10 Aug 2010 10:08:37 +0100 Subject: Subprocess Problem (Wait and while) In-Reply-To: References: Message-ID: <4C611715.8080005@timgolden.me.uk> On 09/08/2010 17:08, Alban Nona wrote: > Hi, > > I have some problem with my actual code. > In fact, the script is done to work within nuke from the foundry which is a > compositing software. > Homever, I have some code difficulties as I quite new in the area. > > Here the deal: > Im using subprocess command to copy some files into local directory, like > this: > > cmd = ['xcopy', '/E', '/I', '/Q', '/Y', '%s' % _folder.replace('/', > '\\'), '%s' % _temp.replace('/', '\\')] > subprocess.Popen(cmd, shell=True) > > Its copying quite well. I have no problem with that. But, after the copy I > would like to continue my code, but ONLY if the copy is done. > If Im using a WAIT, its freezing the main program (nuke) until the copy in > done. I want to avoid that. I also try "call" but same thing. Its > freezing... > I though about something like: > > while subprocess not finished: > Do nothing > else: > Continue Program Have a look at the .poll method of subprocess.Popen > > Like this its checking if the files is copying and do nothing until its > done. I also tough: > > while os.listdir(src) != os.listdir(dst): > Do nothing > Else: > Continue program That's unlikely to work because Windows will create the directory entry first (and at the complete size) and will then fill it in as it copies. TJG From __peter__ at web.de Tue Aug 10 05:12:25 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 11:12:25 +0200 Subject: delegate functions to member References: <64h7j7-r73.ln1@satorlaser.homedns.org> Message-ID: Ulrich Eckhardt wrote: > Hi! > > I have an extension module (a plugin written with Boost.Python) and around > that a wrapper class that adapts a few things. Since the module is a > plugin, there are multiple implementations of this. What I'm currently > doing is this: > > plugin = __import__(plugin_name) > > class PluginWrapper(plugin.PluginClass): > ... > > This means that the definition of class PluginWrapper actually depends on > the previously loaded module. What I would like to do is to define the > wrapper just once and instead pass the plugin module to the constructor: > > class PluginWrapper(object): > ... > plugin = __import__(plugin_name) > instance = PluginWrapper(plugin) > > > Now, I use the wrapper to make some function more friendly (e.g. default > parameters, keyword-parameters, wrapping raw handles) but I want other > functions from the baseclass to remain untouched. If I use a baseclass, > this lookup is automatic. However, when I pass the instance to the > constructor, I have to store it in a member, and then I have to add code > for every function only to delegate it to that member. > > Is there an easy and generic way out of this? Use getattr() >>> class W(object): ... def __init__(self, wrapped): self._wrapped = wrapped ... def __getattr__(self, name): ... return getattr(self._wrapped, name) ... >>> class A(object): ... def hello(self): print "hello" ... >>> a = A() >>> w = W(a) >>> w.hello() hello However, with newsytle classes this doesn't work for __special__ methods >>> w.__str__() '<__main__.W object at 0x7f04ef2d4c50>' Peter From frank at chagford.com Tue Aug 10 05:13:06 2010 From: frank at chagford.com (Frank Millman) Date: Tue, 10 Aug 2010 11:13:06 +0200 Subject: Circular imports (again) References: Message-ID: "Frank Millman" wrote in message news:i3ov9e$dug$1 at dough.gmane.org... > Hi all > > I know the problems related to circular imports, and I know some of the > techniques to get around them. However, I find that I bump my head into > them from time to time, which means, I guess, that I have not fully > understood how to organise my code so that I avoid them in the first > place. > [...] > > So I think my main question is, is this a symptom of a flaw in my > approach, or is this something that all programmers bump into from time to > time? > Thanks for the replies. All good info, but it was Ethan that put me onto the right track. I omitted to mention one thing originally, as I did not think it important, but it turns out to be crucial. My code is organised into three 'packages', not 'modules'. To reproduce my situation, I did some tests with the following hierarchy - top/ a.py /bb __init__.py b.py /cc __init__.py c.py a.py ---- import bb.b import cc.c bb.b.foo() cc.c.foo() b.py ---- import cc.c def foo(): print 'in b.foo, call c.bar' cc.c.bar() def bar(): print ' bar in b' c.py ---- import bb.b def foo(): print 'in c.foo, call b.bar' bb.b.bar() def bar(): print ' bar in c' If I run 'a.py', I get the correct result - in b.foo, call c.bar bar in c in c.foo, call b.bar bar in b I changed 'a.py' - a.py ---- from bb import b from cc import c b.foo() c.foo() It still worked. Next I changed 'b.py' - b.py ---- from cc import c def foo(): print 'in b.foo, call c.bar' c.bar() def bar(): print ' bar in b' It still worked. Then I changed 'c.py' - c.py ---- from bb import b def foo(): print 'in b.foo, call c.bar' b.bar() def bar(): print ' bar in b' Now I get the following traceback - Traceback (most recent call last): File "F:\dd\a.py", line 1, in from bb import b File "F:\dd\bb\b.py", line 1, in from cc import c File "F:\dd\cc\c.py", line 1, in from bb import b ImportError: cannot import name b Now that I understand this, I can work around my problem by using fully-qualified module names. But it would be interesting to know the underlying reason for this behaviour. I am using python 2.6.2. Thanks for any insights. Frank From clp2 at rebertia.com Tue Aug 10 05:19:10 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 10 Aug 2010 02:19:10 -0700 Subject: delegate functions to member In-Reply-To: <64h7j7-r73.ln1@satorlaser.homedns.org> References: <64h7j7-r73.ln1@satorlaser.homedns.org> Message-ID: On Tue, Aug 10, 2010 at 2:01 AM, Ulrich Eckhardt wrote: > Hi! > > I have an extension module (a plugin written with Boost.Python) and around > that a wrapper class that adapts a few things. Since the module is a > plugin, there are multiple implementations of this. What I'm currently > doing is this: > > ?plugin = __import__(plugin_name) > > ?class PluginWrapper(plugin.PluginClass): > ? ? ... > > This means that the definition of class PluginWrapper actually depends on > the previously loaded module. What I would like to do is to define the > wrapper just once and instead pass the plugin module to the constructor: > > ?class PluginWrapper(object): > ? ?... > ?plugin = __import__(plugin_name) > ?instance = PluginWrapper(plugin) > > > Now, I use the wrapper to make some function more friendly (e.g. default > parameters, keyword-parameters, wrapping raw handles) but I want other > functions from the baseclass to remain untouched. If I use a baseclass, > this lookup is automatic. However, when I pass the instance to the > constructor, I have to store it in a member, and then I have to add code > for every function only to delegate it to that member. > > Is there an easy and generic way out of this? Create the subclass(es) dynamically: def wrap(plug_in): class PluginWrapper(plug_in.PluginClass): ... return PluginWrapper plugin = __import__(plugin_name) WrappedPlugin = wrap(plugin) Cheers, Chris -- http://blog.rebertia.com From jeanmichel at sequans.com Tue Aug 10 05:19:33 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 10 Aug 2010 11:19:33 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <878w4i10ad.fsf@benfinney.id.au> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <878w4i10ad.fsf@benfinney.id.au> Message-ID: <4C6119A5.1000301@sequans.com> Ben Finney wrote: > Peter Pearson writes: > > >> Hey, that's a cute example, but . . . what a trap! Is it possible to >> document the use-the-object-not-the-string requirement loudly enough >> that people won't get caught? >> > > Don't use strings for such values. The data isn't going to be used, so > there's no sense using a semantically rich data type like a string. > > Instead, use an ?object? instance; then, the only way to get a binding > that will compare equal is to use the very object itself. > > FORWARD = object() > BACKWARD = object() > > Strings may have their use, most of the time providing a string representation of the object, here is an example: FORWARD = object() print 'moving %s' % FORWARD > moving Another approach using strings: class Direction: FORWARD = 'forward' print "moving %s' % Direction.FORWARD > moving forward Note that Direction.FORWARD is Direction.FORWARD is safe and will return True. JM From chris at simplistix.co.uk Tue Aug 10 05:25:01 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 10 Aug 2010 10:25:01 +0100 Subject: Execute 1.2 Released! Message-ID: <4C611AED.7060500@simplistix.co.uk> I'm pleased to announce the first public release of Execute. This is a collection of common patterns for executing commands as sub processes. It supports executing a simple command that requires no input in a sub process and can return: - text sent to the standard error and output streams - the return code set by the command - both of the above as a tuple For more information, please see: http://www.simplistix.co.uk/software/python/execute cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From clp2 at rebertia.com Tue Aug 10 05:25:02 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 10 Aug 2010 02:25:02 -0700 Subject: mailbox.mbox not locking mbox properly In-Reply-To: References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: On Tue, Aug 10, 2010 at 2:01 AM, wrote: > Tim Roberts wrote: >> tinnews at isbd.co.uk wrote: >> > >> >I'm using the python mailbox class in a script that processes incoming >> >mail and delivers it to various mbox format mailboxes. ?It appears >> >that, although I am calling the lock method on the destination before >> >writing to the mbox and calling unlock afterwards the locking isn't >> >working correctly. >> >... >> >So it seems that python's mailbox class locking isn't playing nicely >> >with mutt's mailbox locking whereas postfix's locking does work >> >correctly. >> >> Correct. ?The "dest.flush()" method creates a temporary file, copies the >> entire modified mailbox into it, removed the original file, and renames the >> temp file into place. >> > Yes, I just took a look at the mailbox.py code and it does exactly > that which of course screws up just about any normal MUA looking at > the mbox. ?Grrrrrr! > > >> The Postfix MDA, like most MDAs, just opens the existing file and appends >> the new data to it. >> >> >Has anyone seen this problem before, and/or do I need to anything more >> >than the following for the locking to work correctly:- >> >> It's not the locking. ?It's the flush mechanism. ?The mbox class doesn't >> know that the ONLY thing you did was an append. ?You might have modified >> other messages in the middle. ?If you want to do an append, you'll need to >> write your own subclass of mbox. > > OK, thanks. ?In reality I can probably just use straightforward file > reading and writing as the *only* thing I will ever be doing is to > append a message to a mailbox file. > > I think there should be a big warning in the mailbox documentation to > this effect as doing it the way that Python's mailbox class does it > will break all sorts of things. ?There should maybe be a specific > 'append' method. File a documentation and/or library bug: http://bugs.python.org/ Cheers, Chris From chris at simplistix.co.uk Tue Aug 10 05:26:04 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 10 Aug 2010 10:26:04 +0100 Subject: Checker 1.3 Released! Message-ID: <4C611B2C.3040403@simplistix.co.uk> I'm pleased to announce a new release of Checker. This is a cross-platform, pluggable tool for comparing the configuration of a machine with a known configuration stored in text files in a source control system all written in Python. This release and the previous release fix ordering issues in file listings as well as generalise operating package listing to support RedHat-like systems in addition to Debian-like systems. For more information, please see: http://www.simplistix.co.uk/software/python/checker cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From alex.lavoro.propio at gmail.com Tue Aug 10 06:25:27 2010 From: alex.lavoro.propio at gmail.com (Alex Barna) Date: Tue, 10 Aug 2010 03:25:27 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On Aug 10, 10:05?am, Lawrence D'Oliveiro > Can?t understand the point to it. ?GUI automation? is a contradiction in > terms, because a GUI is designed for use by humans to do manual tasks, not > ones that can be automated. Automating GUI is for testing. From ldo at geek-central.gen.new_zealand Tue Aug 10 06:28:35 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 10 Aug 2010 22:28:35 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> Message-ID: In message , Christian Heimes wrote: > There isn't really a point in cluttering the source with type casts. Makes you wonder why they bothered using a typed language at all. From santiago.caracol at gmail.com Tue Aug 10 06:34:28 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Tue, 10 Aug 2010 03:34:28 -0700 (PDT) Subject: freeze function calls Message-ID: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> Hello, I want to write a web application that does this: (1) The user submits a query: --------------------------------- | What is the answer? | --------------------------------- (2) The web server gives the user N answers and a button saying "More answers": . answer 1 . answer 2 . answer 3 I am aware of several ways to do this: I could calculate all answers, but show only the first N of them. For certain kinds of calulations, I could use a kind of setoff argument. But I would like to do it in a more general and (hopefully) efficient way: I want the function or object that calculates the answers to be "frozen" at the point at which it has already calculated N answers. If the function gets a -signal within a reasonable period of time, it goes on producing more answers exactly at the point at which it got frozen. If no signal is sent, the function call is terminated automatically after M seconds. Note that, although the program to be written is a web application, this is not a question about web application specific things. My only difficulty is how to "freeze" function calls. Has anyone done something of this kind? Santiago From eckhardt at satorlaser.com Tue Aug 10 06:40:41 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 10 Aug 2010 12:40:41 +0200 Subject: delegate functions to member References: <64h7j7-r73.ln1@satorlaser.homedns.org> Message-ID: <9um7j7-ki3.ln1@satorlaser.homedns.org> Peter Otten wrote: > Use getattr() > >>>> class W(object): > ... def __init__(self, wrapped): self._wrapped = wrapped > ... def __getattr__(self, name): > ... return getattr(self._wrapped, name) > ... I thought there was something like this, thanks! :) When I read this, I thought "OK, now I only have check first if the attribute can be looked up in 'self' first", but even that isn't the case. I tried it and added another function to class W above, which I can call just as if it was defined in _wrapped, so obviously (?) the __getattr__ lookup isn't done there. So, short follow-up question: Why does this work? Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From nikos.the.gr33k at gmail.com Tue Aug 10 07:04:11 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Tue, 10 Aug 2010 04:04:11 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> Message-ID: <94951243-3c97-4fef-9f47-ba6dcdef032f@l14g2000yql.googlegroups.com> Please help me with these last changes before i try to perform an overall change. its almost done! From __peter__ at web.de Tue Aug 10 07:17:47 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 13:17:47 +0200 Subject: delegate functions to member References: <64h7j7-r73.ln1@satorlaser.homedns.org> <9um7j7-ki3.ln1@satorlaser.homedns.org> Message-ID: Ulrich Eckhardt wrote: > Peter Otten wrote: >> Use getattr() >> >>>>> class W(object): >> ... def __init__(self, wrapped): self._wrapped = wrapped >> ... def __getattr__(self, name): >> ... return getattr(self._wrapped, name) >> ... > > I thought there was something like this, thanks! :) > > When I read this, I thought "OK, now I only have check first if the > attribute can be looked up in 'self' first", but even that isn't the case. The getattr() call inside __getattr__() raises an AttributeError if it can't find an attribute called name in self._wrapped. This very thing you'd have to do if you wanted to signal that an attribute doesn't exist, like in >>> class A: ... def __getattr__(self, name): ... if name == "foo": return 42 ... raise AttributeError ... >>> a = A() >>> a.foo 42 >>> a.bar Traceback (most recent call last): File "", line 1, in File "", line 4, in __getattr__ AttributeError > I tried it and added another function to class W above, which I can call > just as if it was defined in _wrapped, so obviously (?) the __getattr__ > lookup isn't done there. > > So, short follow-up question: Why does this work? __getattr__() is a fallback that is only tried when the normal lookup fails. If you need to intercept every attribute lookup use __getattribute__() instead: >> class A(object): ... def __getattr__(self, name): ... print "__getattr__(%r)" % name ... return 42 ... def __getattribute__(self, name): ... print "__getattribute__(%r)" % name ... return super(A, self).__getattribute__(name) ... >>> a = A() >>> a.foo = "yadda" >>> a.foo __getattribute__('foo') 'yadda' >>> a.bar __getattribute__('bar') __getattr__('bar') 42 Peter From jeanmichel at sequans.com Tue Aug 10 07:51:17 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 10 Aug 2010 13:51:17 +0200 Subject: Python "why" questions In-Reply-To: <87zkwyyoux.fsf@benfinney.id.au> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <87zkwyyoux.fsf@benfinney.id.au> Message-ID: <4C613D35.4070604@sequans.com> Ben Finney wrote: > "D'Arcy J.M. Cain" writes: > > >> No. You are giving me math and logic but the subject was common >> sense. >> > > Common sense is often unhelpful, and in such cases the best way to teach > something is to plainly contradict that common sense. > > Common sense, for example, would have the Earth as a flat surface with > the Sun and Moon as roughly-identically-sized objects orbiting the > Earth. Is it better to pander to that common sense, or to vigorously > reject it in order to teach something more useful? > > I could'nt agree more. If it was not for my scolarship, I would gladly think that the earth is flat and the sun is moving around. It took thousands of years for *1* man to figure out that was wrong. So if there is one thing that common sense is not helpful, then that thing is finding the Truth. JM "Ignorance is the mother of all traditions" (V. Hugo) From msarro at gmail.com Tue Aug 10 07:57:40 2010 From: msarro at gmail.com (Matty Sarro) Date: Tue, 10 Aug 2010 07:57:40 -0400 Subject: Newbie question - calculating prime numbers Message-ID: Hey Everyone, I'm currently trying to work through MIT's opencourseware and am using python. The second assignment they offer is to determine the 1000th prime number. Below is the code I am using: #Assignment 1a #Determine the 1000th prime number candidate=3 #Already know that 2 is prime primeCount=1 while (primeCount<=1000): for i in range (2,candidate): if ((candidate%i)==0): print(candidate, " is not a prime") else: print(candidate, " is a prime!") primeCount+=1 candidate+=2 Now I'm not looking for a solution, but I'm hoping that someone can at least tell me where the error in my logic is. The outer loop keeps count and will keep iterating until the 1000th prime number has been found. The inner loop just attempts to divide the candidate number by each possible factor until it's reached, and then increases the candidate number value by two since even numbers above 2 aren't prime. The if statement inside the inner loop simply checks if there is a remainder when attempting to divide the candidate by the possible factor. If there isn't, its a factor and we can print "not a prime". If there is always a remainder, nothing is a factor and so the candidate is a prime. I figured it seemed simple enough, but I keep getting a massive output and almost nothing listed is a correct prime number. Please be gentle, its my first post and I haven't programmed in ages :) -Matty -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmnc at spray.se Tue Aug 10 07:58:55 2010 From: jmnc at spray.se (Jonas Nilsson) Date: Tue, 10 Aug 2010 13:58:55 +0200 Subject: Weird Python behaviour Message-ID: <28B77025-74CC-4642-8EB7-E83838FBAF2D@spray.se> Hello, Lets say that I want to feed an optional list to class constructor: class Family(): def __init__(self, fName, members = []): self.fName = fName self.members = members Now, lets add members to two different instances of Family: f1 = Family("Smith") f1.members.append("Bill") f2 = Family("Smithers") f2.members.append("Joe") Finally, lets look at the members in the Smithers family: print f2.members output: ['Bill', 'Joe'] Why on earth is the output ['Bill', 'Joe']!? Is there a simple solution that separates f1 and f2 without forcing me to write code for the special case when you don't feed members to the __init__()-function? /Jonas From __peter__ at web.de Tue Aug 10 08:10:36 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 14:10:36 +0200 Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> Message-ID: Santiago Caracol wrote: > Hello, > > I want to write a web application that does this: > > (1) The user submits a query: > > --------------------------------- > | What is the answer? | > --------------------------------- > > > (2) The web server gives the user N answers and a button saying "More > answers": > > . answer 1 > . answer 2 > . answer 3 > > > > I am aware of several ways to do this: I could calculate all > answers, but show only the first N of them. For certain kinds of > calulations, > I could use a kind of setoff argument. But I would like to do it in a > more general > and (hopefully) efficient way: > > I want the function or object that calculates the answers to be > "frozen" at the point at which it has already calculated N answers. If > the function gets a -signal within a reasonable period > of time, it goes on producing more answers exactly at the point at > which it got frozen. If no signal is sent, the function call is > terminated automatically after > M seconds. > > Note that, although the program to be written is a web application, > this is not a question about web application specific things. My only > difficulty is how to "freeze" function calls. > > Has anyone done something of this kind? Python offers an elegant mechanism to calculate values on demand: the generator function: >>> def calculate_answers(): ... for i in range(100): ... print "calculating answer #%d" % i ... yield i * i ... >>> from itertools import islice >>> gen = calculate_answers() This builds the generator but doesn't run the code inside. Now let's look at the first three "answers": >>> for answer in islice(gen, 3): ... print "the answer is", answer ... calculating answer #0 the answer is 0 calculating answer #1 the answer is 1 calculating answer #2 the answer is 4 If you repeat the last step you get the next three answers: >>> for answer in islice(gen, 3): ... print "the answer is", answer ... calculating answer #3 the answer is 9 calculating answer #4 the answer is 16 calculating answer #5 the answer is 25 Peter From __peter__ at web.de Tue Aug 10 08:18:02 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 14:18:02 +0200 Subject: Weird Python behaviour References: Message-ID: Jonas Nilsson wrote: > Lets say that I want to feed an optional list to class constructor: > > class Family(): > def __init__(self, fName, members = []): > Why on earth is the output ['Bill', 'Joe']!? Is there a simple > solution that separates f1 and f2 without forcing me to write code for > the special case when you don't feed members to the __init__()-function? Congrats; you just encountered a very popular new trap ;) The most recent explanation is only one day old: http://mail.python.org/pipermail/python-list/2010-August/1252316.html Peter From no.email at please.post Tue Aug 10 08:19:03 2010 From: no.email at please.post (kj) Date: Tue, 10 Aug 2010 12:19:03 +0000 (UTC) Subject: shelf-like list? Message-ID: I'm looking for a module that implements "persistent lists": objects that behave like lists except that all their elements are stored on disk. IOW, the equivalent of "shelves", but for lists rather than a dictionaries. Does anyone know of such a module? (I suppose that I could slap together a crude implementation of such a thing by wrapping a shelf with suitable methods to simulate the list interface. But I'd rather not roll my own if a tested implementation already exist.) TIA! ~K From eckhardt at satorlaser.com Tue Aug 10 08:20:22 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 10 Aug 2010 14:20:22 +0200 Subject: delegate functions to member References: <64h7j7-r73.ln1@satorlaser.homedns.org> <9um7j7-ki3.ln1@satorlaser.homedns.org> Message-ID: <6ps7j7-0s3.ln1@satorlaser.homedns.org> Peter Otten wrote: > Ulrich Eckhardt wrote: >> So, short follow-up question: Why does this work? > > __getattr__() is a fallback that is only tried when the normal lookup > fails. If you need to intercept every attribute lookup use > __getattribute__() instead: Thank you Peter, that was the missing piece to understand it! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From santiago.caracol at gmail.com Tue Aug 10 08:30:57 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Tue, 10 Aug 2010 05:30:57 -0700 (PDT) Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> Message-ID: <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> > Python offers an elegant mechanism to calculate values on demand: the > generator function: > > >>> def calculate_answers(): > > ... ? ? for i in range(100): > ... ? ? ? ? ? ? print "calculating answer #%d" % i > ... ? ? ? ? ? ? yield i * i > ... > Thanks for pointing this out. I was aware of the yield statement. My problem is this: (1) The user submits a query: --------------------------------- | What is the answer? | --------------------------------- (2) The web server gives the user N answers and a button saying "More answers": . answer 1 . answer 2 . answer 3 At this stage the function that writes html to the user has been called. The call must be terminated, or else, the user doesn't get any html. This means that the call of the answer-calculating function, whether it uses yield or not, is also terminated. This means, when the user presses the -button, the calculation has to start at the beginning. From __peter__ at web.de Tue Aug 10 08:48:39 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 14:48:39 +0200 Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> Message-ID: Santiago Caracol wrote: >> Python offers an elegant mechanism to calculate values on demand: the >> generator function: >> >> >>> def calculate_answers(): >> >> ... for i in range(100): >> ... print "calculating answer #%d" % i >> ... yield i * i >> ... >> > > Thanks for pointing this out. I was aware of the yield statement. > > My problem is this: > > (1) The user submits a query: > > --------------------------------- > | What is the answer? | > --------------------------------- > > > (2) The web server gives the user N answers and a button saying "More > answers": > > . answer 1 > . answer 2 > . answer 3 > > > > At this stage the function that writes html to the user has been > called. The call must be terminated, or else, the user doesn't get any > html. This means that the call of the answer-calculating function, > whether it uses yield or not, is also terminated. This means, when the > user presses the -button, the calculation has to start > at the beginning. Adapted from the wsgiref documentation at http://docs.python.org/library/wsgiref.html $ cat wsgi_demo.py from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server from itertools import count, islice def answers(): for i in count(): yield "Answer #%d\n" % i gen = answers() def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return islice(gen, 3) httpd = make_server('', 8000, simple_app) print "Serving on port 8000..." httpd.serve_forever() Run the above with $ python wsgi_demo.py Serving on port 8000... Now point your favourite browser to http://localhost:8000/ and hit refresh. Peter From davea at ieee.org Tue Aug 10 08:51:47 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 10 Aug 2010 08:51:47 -0400 Subject: Newbie question - calculating prime numbers In-Reply-To: References: Message-ID: <4C614B63.5070108@ieee.org> Matty Sarro wrote: > Hey Everyone, > I'm currently trying to work through MIT's opencourseware and am using > python. The second assignment they offer is to determine the 1000th prime > number. Below is the code I am using: > > #Assignment 1a > #Determine the 1000th prime number > candidate=3 > #Already know that 2 is prime > primeCount=1 > while (primeCount<=1000): > for i in range (2,candidate): > if ((candidate%i)==0): > print(candidate, " is not a prime") > else: > print(candidate, " is a prime!") > primeCount+=1 > candidate+=2 > > > > > Now I'm not looking for a solution, but I'm hoping that someone can at least > tell me where the error in my logic is. > The outer loop keeps count and will keep iterating until the 1000th prime > number has been found. > The inner loop just attempts to divide the candidate number by each possible > factor until it's reached, and then increases the candidate number value by > two since even numbers above 2 aren't prime. > The if statement inside the inner loop simply checks if there is a remainder > when attempting to divide the candidate by the possible factor. If there > isn't, its a factor and we can print "not a prime". If there is always a > remainder, nothing is a factor and so the candidate is a prime. > > I figured it seemed simple enough, but I keep getting a massive output and > almost nothing listed is a correct prime number. > > Please be gentle, its my first post and I haven't programmed in ages :) > -Matty > > Once you discover a particular value is not a prime, you need to get out of that for loop. Add a break after the appropriate print. Also, the print that says it IS a prime is misplaced. You only know that if you've gone all the way through the loop without ever hitting the break. That's a candidate for the 'else' clause of the for loop. There are other changes you could make for efficiency, but get it working correctly first. DaveA From msarro at gmail.com Tue Aug 10 08:55:09 2010 From: msarro at gmail.com (Matty Sarro) Date: Tue, 10 Aug 2010 08:55:09 -0400 Subject: Newbie question - calculating prime numbers In-Reply-To: <4C614B63.5070108@ieee.org> References: <4C614B63.5070108@ieee.org> Message-ID: Hey Dave, Thank you for the heads up. I actually bashed my head against the desk a few times and eventually I realized what I was doing wrong. Here's my final code (slightly optimized) that's verified and working. Out of curiousity, what other optimizations could I throw at it (without diving too deep too fast). #Assignment 1a #Determine the 1000th prime number candidate=1 #Already know that 2 is prime primeCount=1 while (primeCount<=1000): isPrime="true" i=2 halfCand=(candidate/2) while (isPrime=="true") and (i<=halfCand): if ((candidate%i)==0): isPrime="false" else: i+=1 if isPrime=="true": print(candidate, "is a prime.") primeCount+=1 #else: #print(candidate, " is not a prime.") candidate+=2 print("The 1000th prime number is ",(candidate-2)) On Tue, Aug 10, 2010 at 8:51 AM, Dave Angel wrote: > Matty Sarro wrote: > >> Hey Everyone, >> I'm currently trying to work through MIT's opencourseware and am using >> python. The second assignment they offer is to determine the 1000th prime >> number. Below is the code I am using: >> >> #Assignment 1a >> #Determine the 1000th prime number >> candidate=3 >> #Already know that 2 is prime >> primeCount=1 >> while (primeCount<=1000): >> for i in range (2,candidate): >> if ((candidate%i)==0): >> print(candidate, " is not a prime") >> else: >> print(candidate, " is a prime!") >> primeCount+=1 >> candidate+=2 >> >> >> >> >> Now I'm not looking for a solution, but I'm hoping that someone can at >> least >> tell me where the error in my logic is. >> The outer loop keeps count and will keep iterating until the 1000th prime >> number has been found. >> The inner loop just attempts to divide the candidate number by each >> possible >> factor until it's reached, and then increases the candidate number value >> by >> two since even numbers above 2 aren't prime. >> The if statement inside the inner loop simply checks if there is a >> remainder >> when attempting to divide the candidate by the possible factor. If there >> isn't, its a factor and we can print "not a prime". If there is always a >> remainder, nothing is a factor and so the candidate is a prime. >> >> I figured it seemed simple enough, but I keep getting a massive output and >> almost nothing listed is a correct prime number. >> >> Please be gentle, its my first post and I haven't programmed in ages :) >> -Matty >> >> >> > Once you discover a particular value is not a prime, you need to get out of > that for loop. Add a break after the appropriate print. > > Also, the print that says it IS a prime is misplaced. You only know that > if you've gone all the way through the loop without ever hitting the break. > That's a candidate for the 'else' clause of the for loop. > > There are other changes you could make for efficiency, but get it working > correctly first. > > DaveA > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Tue Aug 10 09:02:30 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 10 Aug 2010 23:02:30 +1000 Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> <4c610bd2$0$28655$c3e8da3@news.astraweb.com> Message-ID: <87aaouzkm1.fsf@benfinney.id.au> Steven D'Aprano writes: > On Tue, 10 Aug 2010 20:07:06 +1200, Gregory Ewing wrote: > > Is there any way for a non-.NET program to access a .NET library? Or > > is it necessary to drink the entire bottle of .NET kool-aid? > > http://www.mono-project.com/Main_Page Anyone thinking of using Mono needs to be aware of the dangers of software patents in general, and of .NET in paticular. The copyright license for Mono is under free software terms. But that gives no license at all for the patents. Novell, who have an exclusive deal for those patents, happily encourages use of Mono by third parties. The controversy has raged for a number of years. For more coverage than you have time for, see . The issue has polarised discussion, unfortunately, and there is a lot of name-calling and hyperbole on the record now. As the Mono site hints, the patent situation for .NET is *very* muddy. Microsoft hold patents covering much of .NET, but have made a (non-binding) ?Community Promise? that applies to *some* parts of .NET . -- \ ?It is seldom that liberty of any kind is lost all at once.? | `\ ?David Hume | _o__) | Ben Finney From hobson42 at gmaiil.com Tue Aug 10 09:14:27 2010 From: hobson42 at gmaiil.com (Ian) Date: Tue, 10 Aug 2010 14:14:27 +0100 Subject: Newbie question - calculating prime numbers In-Reply-To: References: Message-ID: <4C6150B3.7020709@gmaiil.com> On 10/08/2010 12:57, Matty Sarro wrote: > Hey Everyone, > I'm currently trying to work through MIT's opencourseware and am using > python. The second assignment they offer is to determine the 1000th > prime number. Below is the code I am using: > > #Assignment 1a > #Determine the 1000th prime number > candidate=3 > #Already know that 2 is prime > primeCount=1 > while (primeCount<=1000): > for i in range (2,candidate): > if ((candidate%i)==0): > print(candidate, " is not a prime") > else: > print(candidate, " is a prime!") > primeCount+=1 > candidate+=2 > > > > > Now I'm not looking for a solution, but I'm hoping that someone can at > least tell me where the error in my logic is. Hi Matty, Dave Angel has already given you some helpful stuff. I would only like to add that you need three states inside your loop a) Candidate is known to be prime b) Candidate is known to be not prime c) Candidate may or may not be prime and the code has to keep working on it. You are detecting the "is not prime" case correctly. The other two situations are confused. A candidate is only prime if it is not divisible by *any* number other than 1 or itself. Two hints for efficiency: If candidate has a factor, one of those factors MUST be <= square root of candidate - so you don't need to loop through so many. If x is prime, all multiples of x are not prime. See sieve of Eratosthenes. Regards Ian From __peter__ at web.de Tue Aug 10 09:18:31 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 15:18:31 +0200 Subject: Newbie question - calculating prime numbers References: <4C614B63.5070108@ieee.org> Message-ID: Matty Sarro wrote: > Hey Dave, > Thank you for the heads up. I actually bashed my head against the desk a > few times and eventually I realized what I was doing wrong. Here's my > final code (slightly optimized) that's verified and working. Out of > curiousity, what other optimizations could I throw at it (without diving > too deep too fast). > > #Assignment 1a > #Determine the 1000th prime number > candidate=1 > #Already know that 2 is prime > primeCount=1 > while (primeCount<=1000): > isPrime="true" > i=2 > halfCand=(candidate/2) > while (isPrime=="true") and (i<=halfCand): > if ((candidate%i)==0): > isPrime="false" > else: > i+=1 > if isPrime=="true": > print(candidate, "is a prime.") > primeCount+=1 > #else: > #print(candidate, " is not a prime.") > candidate+=2 > print("The 1000th prime number is ",(candidate-2)) Congrats! One obvious thing would be to replace the "true" and "false" strings with actual boolean values: isPrime = True ... while isPrime and i <= halfCand: ... etc. For a different perspective on the problem have a look at http://mail.python.org/pipermail/python-list/2009-November/1226626.html Peter From davea at ieee.org Tue Aug 10 09:50:18 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 10 Aug 2010 09:50:18 -0400 Subject: Newbie question - calculating prime numbers In-Reply-To: References: <4C614B63.5070108@ieee.org> Message-ID: <4C61591A.8050108@ieee.org> Matty Sarro wrote: > Hey Dave, > Thank you for the heads up. I actually bashed my head against the desk a few > times and eventually I realized what I was doing wrong. Here's my final code > (slightly optimized) that's verified and working. Out of curiousity, what > other optimizations could I throw at it (without diving too deep too fast). > > #Assignment 1a > #Determine the 1000th prime number > candidate=1 > #Already know that 2 is prime > primeCount=1 > while (primeCount<=1000): > isPrime="true" > i=2 > halfCand=(candidate/2) > while (isPrime=="true") and (i<=halfCand): > if ((candidate%i)==0): > isPrime="false" > else: > i+=1 > if isPrime=="true": > print(candidate, "is a prime.") > primeCount+=1 > #else: > #print(candidate, " is not a prime.") > candidate+=2 > print("The 1000th prime number is ",(candidate-2)) > > You top-posted, which messed up the message sequence. You should post your message AFTER whatever you're quoting. Your code starts by printing that 1 is prime, which it's not. And it doesn't print 2. Those two errors happen to cancel, so the 1000th prime is still right. But the initial value for candidate= should be 3, not 1. I didn't try to figure where the other error is, but somewhere your count is off by one. You've changed your code from using the built-in control flow to doing it by hand. That's almost never a good idea, and in this case it'll slow you down. Learn about the break statement to break out of a for loop or while loop. It saves doing multiple tests in the loop construct. Use True and False, not strings. Your halfCand could have been rootCand; you only need to check up to the square root of the candidate (see math.sqrt()). In fact, you only need to check those primes you've already built, up to the square root. For example, to tell if 23 is prime, you only need to divide by 2, 3 and 5. This would require that you build a list of results, appending to it whenever you find a new prime. It would mean that primeCount is not needed, as it's simply len(primeList). I don't know which of these ideas has already been covered in your class. But if you used all of these ideas, your code would be smaller and much faster. Currently, it spends more time in the print statements than in calculating, so I temporarily commented out the print of the first 999 primes. I coded up a quick version, and without the prints of individual primes, it sped up 1.3 secs to 0.03 secs. If I have both versions do the first 10,000 primes, the original takes 176 secs, while mine takes 0.5 DaveA From darcy at druid.net Tue Aug 10 09:51:34 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 10 Aug 2010 09:51:34 -0400 Subject: Python "why" questions In-Reply-To: <4C613D35.4070604@sequans.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <87zkwyyoux.fsf@benfinney.id.au> <4C613D35.4070604@sequans.com> Message-ID: <20100810095134.fa3a3e79.darcy@druid.net> On Tue, 10 Aug 2010 13:51:17 +0200 Jean-Michel Pichavant wrote: Pardon the response to the response. I missed Ben's message. > Ben Finney wrote: > > "D'Arcy J.M. Cain" writes: > >> No. You are giving me math and logic but the subject was common > >> sense. > > > > Common sense is often unhelpful, and in such cases the best way to teach > > something is to plainly contradict that common sense. I even agree with you. However, the OP was claiming that zero based counting contradicted common sense and that was what I was responding to. I would never use "common sense" to prove anything. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From santiago.caracol at gmail.com Tue Aug 10 09:56:56 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Tue, 10 Aug 2010 06:56:56 -0700 (PDT) Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> Message-ID: <34b16983-ac50-49a0-a612-0c35d9bf6c6f@l14g2000yql.googlegroups.com> > Run the above with > > $ python wsgi_demo.py > Serving on port 8000... > Thanks a lot for this code. The problem with it is that the whole application IS a generator function. That means that if I run the code at, say foo.org, then any user that visits the site will augment the answer number of the server running at foo.org. What I am trying to do is to process specific queries for different users. Each user is supposed to get his very own answers to his very own questions. And if a user doesn't hit the -button during a certain period of time, the generator or function call reponsible for answering his question is supposed to be killed or thrown-away or forgotten. If the user asks a new question (while the answers to the old question are still being displayed), then the generator or function call is also supposed to be forgotten and a new generator or function call -- one that matches the user's new question -- is supposed to be initiated. Santiago From herta.hy at gmail.com Tue Aug 10 10:02:06 2010 From: herta.hy at gmail.com (Herta) Date: Tue, 10 Aug 2010 07:02:06 -0700 (PDT) Subject: how to save a whole web page with something block Message-ID: <46c3cfc7-9339-4cd0-9ef9-4358730b706f@o7g2000prg.googlegroups.com> Hi everyone, I want to save a web page. I use urllib to parse the web page. But I find the saved file, where some content is missing. The missing part is block from the original web page, such as this part
...
.I don't know how to parse a whole page without something block in it. Could you help me figure it out? Thank you! This is my program url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp? Param=4502931&ProtId=1&ProtType=Receptor' f = urllib.urlretrieve(url,'test.html') From steveo at syslang.net Tue Aug 10 10:07:23 2010 From: steveo at syslang.net (Steven W. Orr) Date: Tue, 10 Aug 2010 10:07:23 -0400 Subject: How to capture all the environment variables from shell? In-Reply-To: References: <4C4E43D3.9070203@syslang.net> Message-ID: <4C615D1B.7060204@syslang.net> On 8/2/2010 4:33 AM, Thorsten Kampe wrote: > * Tim Chase (Mon, 26 Jul 2010 21:42:24 -0500) >> On 07/26/10 21:26, Steven W. Orr wrote: >>> Please! Never export anything from your .bashrc unless you >>> really know what you're doing. Almost all exports should be >>> done in your .bash_profile >> >> Could you elaborate on your reasoning why (or why-not)? I've >> found that my .bash_profile doesn't get evaluated when I crank up >> another terminal window, while my bashrc does. Thus I tend to >> put my exports in my ~/.bashrc so they actually take effect in my >> shell... > > ~/.bash_profile is only evaluated for login shells and ~/.bashrc only > for non-login shells. Thus it's recommended to keep ~/.bash_profile > empty (except a source statement for .bashrc) and put all your settings, > aliases, exports, etc. in .bashrc. > > Thorsten Sorry. Dead wrong. Please reread the above comment I wrote. If you set your environment variables in the .bashrc then you completely lose the ability of environment variables to be inherited by sub-shells. Again, envvars should be set in the .bash_profile, most everything else should be set in the .bashrc, and the .bashrc should be sourced into the .bash_profile to solve the problem that you thought you were solving. After that, and again, be aware that the .bashrc alone is executed for login shells *which are not interactive*. for example: ssh somemachine 'echo Hello' This command will *not* go through the .bash_profile but it will go through the .bashrc. This means that for cases like this, we want to check to see if the bash process is interactive or not inside the .bashrc and then do the right thing. =============== [[ -z "$PS1" ]] && setPATHHere =============== This is not needed for the above degenerate case, but it is needed if the command in question is kept in a directory that you normally find in a place that is part of your personal login PATH. E.G., If myprog lives in ~/bin then ssh somemachine myprog will fail unless you use the above construct. Hopefully, I'll only have to re-explain this another google times... -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net steve orr From benjamin.kaplan at case.edu Tue Aug 10 10:43:22 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 10 Aug 2010 07:43:22 -0700 Subject: Weird Python behaviour In-Reply-To: <28B77025-74CC-4642-8EB7-E83838FBAF2D@spray.se> References: <28B77025-74CC-4642-8EB7-E83838FBAF2D@spray.se> Message-ID: On Tue, Aug 10, 2010 at 4:58 AM, Jonas Nilsson wrote: > Hello, > > Lets say that I want to feed an optional list to class constructor: > > class Family(): > ? ? ? ?def __init__(self, fName, members = []): > ? ? ? ? ? ? ? ?self.fName = fName > ? ? ? ? ? ? ? ?self.members = members > > Now, lets add members to two different instances of Family: > > f1 = Family("Smith") > f1.members.append("Bill") > > f2 = Family("Smithers") > f2.members.append("Joe") > > Finally, lets look at the members in the Smithers family: > > print f2.members > output: ['Bill', 'Joe'] > > Why on earth is the output ['Bill', 'Joe']!? Is there a simple solution that > separates f1 and f2 without forcing me to write code for the special case > when you don't feed members to the __init__()-function? > > /Jonas In python, a function definition is an executable statement, not a declaration. Default args only get evaluated once- when the function is first created. You have to use a sentinel value and create the object inside the function if you want it to get executed every time. class Family(): def __init__(self, fName, members = None): if members is None : members = [] self.fName = fName self.members = members If None is a valid argument to this function, then make a dummy object and check identity (to make sure it's *that* object and not just something that evaluates equal). sentinel = object() def something_that_accepts_none(foo = sentinel) : if foo is sentinel : foo = {} # other stuff From John Tue Aug 10 10:58:39 2010 From: John (John) Date: Tue, 10 Aug 2010 10:58:39 -0400 Subject: File Manager in Tkinter References: Message-ID: On Tue, 10 Aug 2010 10:40:53 +0200, Eric Brunel wrote: >In article , John wrote: > >> As a learning exercise in Tkinter I htought about making a very simple >> and basic file manager for my own use. I tried searching google for >> any sample project and could not find anything. Not exactly sure how >> to start I tought I could ask here? >> >> I thought about making two listboxes one to list folders only the >> other files inside. I tried to make one listbox first but did not know >> how to list folders only. > >You just have to filter them explicitely by using os.path.isdir on each >file name. > >> from Tkinter import * >> import os >> path = "D:\\" >> >> >> s = Scrollbar() >> L = Listbox() >> >> s.pack(side=RIGHT, fill=Y) >> L.pack(side=LEFT, fill=Y) >> >> s.config(command=L.yview) >> L.config(yscrollcommand=s.set) >> >> for filename in os.listdir(path): > >Add here: > if os.path.isdir(os.path.join(path, filename)): >> L.insert(END, filename) >> >> mainloop() >> >> >> >> Is there a way to list folders with images? > >AFAIK, not with a Listbox. You can do it with a Canvas, but it's much >more complicated than using a Listbox, so maybe you should try to make >your Listbox-only version works first. > >> Any suggestions or help how to proced would be appreciated. >> >> Thank you > >Good luck! Thank you both for the suggestions. Have you ever tried to make one? From bieffe62 at gmail.com Tue Aug 10 11:01:07 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Tue, 10 Aug 2010 08:01:07 -0700 (PDT) Subject: Weird Python behaviour References: Message-ID: <4f9fc841-bd4f-471c-9e7c-dd91515fb5d2@a18g2000yqa.googlegroups.com> On 10 Ago, 13:58, Jonas Nilsson wrote: > Hello, > > Lets say that I want to feed an optional list to class constructor: > > class Family(): > ? ? ? ? def __init__(self, fName, members = []): > ? ? ? ? ? ? ? ? self.fName = fName > ? ? ? ? ? ? ? ? self.members = members > > Now, lets add members to two different instances of Family: > > f1 = Family("Smith") > f1.members.append("Bill") > > f2 = Family("Smithers") > f2.members.append("Joe") > > Finally, lets look at the members in the Smithers family: > > print f2.members > output: ['Bill', 'Joe'] > > Why on earth is the output ['Bill', 'Joe']!? Is there a simple ? > solution that separates f1 and f2 without forcing me to write code for ? > the special case when you don't feed members to the __init__()-function? > > /Jonas You stumbled in two python common pitfalls at once :-) One, the default arguments issue, was already pointed to you. The other one is that python variables are just names for objects. Assigning a variable never mean making a copy, it just means using another name for the same object. There used to be a very nice (also graphic) explanationor this somewhere on the web, but my googling skills failed me this time, so instead I'll show you the concept using your own code: >>> class Family: ... def __init__(self, fName, members = []): ... self.fname = fName ... self.members = members ... >>> mlist = ["Bill"] >>> f1 = Family("Smiths", mlist ) >>> mlist.append( "John" ) # attempt to not-so-clever reyse of the sme variable >>> f2 = Family("Smithers", mlist ) >>> f1.members ['Bill', 'John'] Now my example is a bit contrieved but I'm sure you got the idea : in your example is better to copy the list with self.members = members[:]. Better yet, you could make use of python arguments grouping feature : >>> class Family: ... def __init__(self, fName, *members ): ... self.members = list(members) # because members is a tuple ... self.fname = fName ... >>> f1 = Family("Smith") >>> f1.members.append("Bill") >>> f2 = Family("Smithers") >>> f2.members.append("Joe") >>> f2.members ['Joe'] >>> f1.members ['Bill'] This solves your "no initial member" special case and allows for an easier syntax for creating class instances (no brackets involved) >>> f3 = Family("Bochicchio", "Angelo", "Francesco", "Mario") >>> f3.members ['Angelo', 'Francesco', 'Mario'] >>> Ciao ---- FB From fetchinson at googlemail.com Tue Aug 10 11:04:09 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 10 Aug 2010 17:04:09 +0200 Subject: how to save a whole web page with something block In-Reply-To: <46c3cfc7-9339-4cd0-9ef9-4358730b706f@o7g2000prg.googlegroups.com> References: <46c3cfc7-9339-4cd0-9ef9-4358730b706f@o7g2000prg.googlegroups.com> Message-ID: > I want to save a web page. I use urllib to parse the web page. But I > find the saved file, where some content is missing. The missing part > is block from the original web page, such as this part
style="display: block;" id="GeneInts">...
.I don't know how to > parse a whole page without something block in it. Could you help me > figure it out? Thank you! > > > This is my program > > url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp? > Param=4502931&ProtId=1&ProtType=Receptor' > f = urllib.urlretrieve(url,'test.html') A web server may present different output depending on the client used. When you use your browser to look at the source and then use urllib's saved file you access the web server with different clients. I'm not saying this is your problem, but potentially it is. So you might want to make urllib appear as a browser by sending the appropriate headers. HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From python at mrabarnett.plus.com Tue Aug 10 11:12:02 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 10 Aug 2010 16:12:02 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> Message-ID: <4C616C42.6040506@mrabarnett.plus.com> ????? wrote: [snip] > > The ID number of each php page was contained in the old php code > within this string > > PageID = some_number > > So instead of create a new ID number for eaqch page i have to pull out > this number to store to the beginnign to the file as comment line, > because it has direct relationship with the mysql database as in > tracking the number of each webpage and finding the counter of it. > > # Grab the PageID contained within the php code and store it in id > variable > id = re.search( 'PageID = ', src_data ) > > How to tell Python to Grab that number after 'PageID = ' string and to > store it in var id that a later use in the program? > If the part of the file you're trying to match look like this: PageID = 12 then the regex should look like this: PageID = (\d+) and the code should look like this: page_id = re.search(r'PageID = (\d+)', src_data).group(1) The page_id will, of course, be a string. > also i made another changewould something like this work: > > =============================== > # open same php file for storing modified data > print ( 'writing to %s' % dest_f ) > f = open(src_f, 'w') > f.write(src_data) > f.close() > > # rename edited .php file to .html extension > dst_f = src_f.replace('.php', '.html') > os.rename( src_f, dst_f ) > =============================== > > Because instead of creating a new .html file and inserting the desired > data of the old php thus having two files(old php, and new html) i > decided to open the same php file for writing that data and then > rename it to html. > Would the above code work? Why wouldn't it? From nbuchholz at noao.edu Tue Aug 10 11:43:24 2010 From: nbuchholz at noao.edu (Nick Buchholz) Date: Tue, 10 Aug 2010 08:43:24 -0700 Subject: File Manager in Tkinter In-Reply-To: References: Message-ID: On Tue, 10 Aug 2010 10:58:39 -0400 John at mail.python.org wrote: >Thank you both for the suggestions. Have you ever tried to make one? >-- >http://mail.python.org/mailman/listinfo/python-list I don't know if my first reply went out so I'll repeat Here is a list box dialog written to allow selection of one of a specific type of file. It is a method in a larger gui object that controls hardware on a remote machine (called a PAN) and loads commands from files. def modeFiles(self): try: sysFile = self.chkConnected() except Disconnect,e: return (False, '') self.pan.ppxGetAVP( ('modeFdir', ) ) dir = self.pan.avps['modeFdir'].get() fileList = fetchModFiles(self.pan, dir=dir) flist = [] for file in fileList: idx = rfind(file, '/') flist.append(file[idx+1:]) dlg = Pmw.ComboBoxDialog(self.parent, title = 'Mode File Select', buttons=('Load', 'Cancel'), defaultbutton='Load', combobox_labelpos=N, label_text='Which Mode file to load', scrolledlist_items=flist, listbox_width=32) dlg.geometry('240x300+30+250') dlg.tkraise() result = dlg.activate(geometry='240x300+30+250') if result == 'Load': print "loading %s/%s "%(dir, dlg.get()) self.pan.ppxSetMode( (dlg.get(),) ) else: print "leaving" here is fetchModFilesz def fetchModFiles(pan=None, dir=None): """ A function to read mod files on remote pan in directory dir """ fileList = [] if pan is not None: if dir is None: rCmd = "/bin/echo $MONSOON_HOME" dir = commands.getoutput("ssh -X -l monsoon %s '%s'" % (pan.panName, rCmd) ) dir = dir+os.sep+'_'+pan.sysName lsCmd = "/bin/ls %s/*.mod"%(dir,) resp = commands.getoutput("ssh -X -l monsoon %s '%s'"% (pan.panName, lsCmd)) fileList = resp.split("\n") else: pass return fileList Someday I may have time to go back and clean these up and generalize them. But as the only software guy on a 3 man-year project due to complete in 9 months quick and dirty is the rule. Nick nbuchholz at noao.edu Day phone: (520) 318-8203 "Time is an illusion, Lunchtime doubly so" - Ford Prefect Time is an illusion perpetrated by the manufacturers of space. From __peter__ at web.de Tue Aug 10 11:46:02 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 17:46:02 +0200 Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> <34b16983-ac50-49a0-a612-0c35d9bf6c6f@l14g2000yql.googlegroups.com> Message-ID: Santiago Caracol wrote: >> Run the above with >> >> $ python wsgi_demo.py >> Serving on port 8000... >> > > Thanks a lot for this code. The problem with it is that the whole > application IS a generator function. That means that if I run the code > at, say foo.org, then any user that visits the site will augment the > answer number of the server running at foo.org. What I am trying to do > is to process specific queries for different users. Each user is > supposed to get his very own answers to his very own questions. And if > a user doesn't hit the -button during a certain period > of time, the generator or function call reponsible for answering his > question is supposed to be killed or thrown-away or forgotten. If the > user asks a new question (while the answers to the old question are > still being displayed), then the generator or function call is also > supposed to be forgotten and a new generator or function call -- one > that matches the user's new question -- is supposed to be initiated. Didn't you say you weren't interested in the web specific aspects? You may be able to do it by hand (the environ argument will probably include an IP that you can use to look up the generator in a dictionary) but I'd rather say you need a web framework that provides the session management. Cherrypy is a lightweight one, and after some try and way too much error I came up with # warning: newbie code import cherrypy from itertools import islice, count def answers(): for i in count(): yield "Answer #%d\n" % i class PythonRunner(object): def index(self): try: gen = cherrypy.session["gen"] except KeyError: cherrypy.session["gen"] = gen = answers() return "%s" % "".join(islice(gen, 3)) index.exposed = True if __name__ == '__main__': cherrypy.quickstart(PythonRunner(), config="cherry.conf") The contents of cherry.conf are: [global] server.socket_host = "127.0.0.1" server.socket_port = 8080 server.thread_pool = 10 [/] tools.sessions.on = True #tools.sessions.storage_type = "file" #tools.sessions.storage_path = "./sessions" tools.sessions.timeout = 60 See the result on http://localhost:8080/index I opened the page in Firefox and Konqueror, and the numbers were independent, so I'm pretty sure it works on a bigger scale, too. $ python -c 'import cherrypy; print cherrypy.__version__' 3.1.2 Note that storage_type = "file" is straight out for generators because they cannot be pickled. The workaround here would be a class like class Answers(object): def __init__(self): self.i = 0 def __iter__(self): return self def next(self): result = "Answer #%d\n" % self.i self.i += 1 return result Peter From sschwarzer at sschwarzer.net Tue Aug 10 11:57:21 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 10 Aug 2010 17:57:21 +0200 Subject: Weird Python behaviour In-Reply-To: <4f9fc841-bd4f-471c-9e7c-dd91515fb5d2@a18g2000yqa.googlegroups.com> References: <4f9fc841-bd4f-471c-9e7c-dd91515fb5d2@a18g2000yqa.googlegroups.com> Message-ID: <4C6176E1.7020504@sschwarzer.net> Hi, On 2010-08-10 17:01, Francesco Bochicchio wrote: > There used to be a very nice (also graphic) explanationor this > somewhere on the web, but my googling skills failed me this time, > so instead I'll show you the concept using your own code: Probably this isn't the page you're referring to, but I only recently gave a beginners' talk at EuroPython: http://sschwarzer.com/download/robust_python_programs_europython2010.pdf The topic of identity and assignments starts on slide 7, nice graphics start on slide 10. ;-) Stefan From jeff.hobbs at gmail.com Tue Aug 10 12:20:31 2010 From: jeff.hobbs at gmail.com (Jeff Hobbs) Date: Tue, 10 Aug 2010 09:20:31 -0700 (PDT) Subject: File Manager in Tkinter References: Message-ID: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> On Aug 9, 9:53?pm, John wrote: > As a learning exercise in Tkinter I htought about making a very simple > and basic file manager for my own use. I tried searching google for > any sample project and could not find anything. Not exactly ?sure how > to start I tought I could ask here? > > I thought about making two listboxes one to list folders only the > other files inside. I tried to make one listbox first but did not know > how to list folders only. Filter with os.path.isdir() > Is there a way to list folders with images? > Any suggestions or help how to proced would be appreciated. If you are using a Tkinter with Ttk (Tk 8.5), then use the treeview widget: http://docs.activestate.com/activepython/3.1/python/library/tkinter.ttk.html For more advanced needs, there is a Tk extension called tktreectrl that does some very cool views and has lots of controls: http://tktreectrl.sourceforge.net/ Jeff From torriem at gmail.com Tue Aug 10 12:29:23 2010 From: torriem at gmail.com (Michael Torrie) Date: Tue, 10 Aug 2010 10:29:23 -0600 Subject: Microsoft lessening commitment to IronPython and IronRuby In-Reply-To: <8ccf4kF38mU1@mid.individual.net> References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> Message-ID: <4C617E63.6020509@gmail.com> On 08/10/2010 02:07 AM, Gregory Ewing wrote: > Tim Roberts wrote: > >> I'm not sure that's really fair. The .NET Common Language Runtime is a >> vast and very useful class library, including two complete GUI systems. The >> thought was that IronPython and IronRuby would let people who were >> comfortable in those languages tap into the CLR. > > Is there any way for a non-.NET program to access a .NET library? > Or is it necessary to drink the entire bottle of .NET kool-aid? Well the only way for a non-.net program to access a .NET library is to either embed .NET or use some kind of bridge via RPC. So basically, the answer is "no." You pretty much have to embrace .NET or not use it. From John Tue Aug 10 12:43:12 2010 From: John (John) Date: Tue, 10 Aug 2010 12:43:12 -0400 Subject: File Manager in Tkinter References: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> Message-ID: <770366ta10gk98vgd5n2tapl7ag6skaeaj@4ax.com> On Tue, 10 Aug 2010 09:20:31 -0700 (PDT), Jeff Hobbs wrote: >On Aug 9, 9:53?pm, John wrote: >> As a learning exercise in Tkinter I htought about making a very simple >> and basic file manager for my own use. I tried searching google for >> any sample project and could not find anything. Not exactly ?sure how >> to start I tought I could ask here? >> >> I thought about making two listboxes one to list folders only the >> other files inside. I tried to make one listbox first but did not know >> how to list folders only. > >Filter with os.path.isdir() > >> Is there a way to list folders with images? >> Any suggestions or help how to proced would be appreciated. > >If you are using a Tkinter with Ttk (Tk 8.5), then use the treeview >widget: > >http://docs.activestate.com/activepython/3.1/python/library/tkinter.ttk.html > >For more advanced needs, there is a Tk extension called tktreectrl >that does some very cool views and has lots of controls: > >http://tktreectrl.sourceforge.net/ > >Jeff My python is version 2.6.5. Would you recomend I upgrade and if yes to which version? from tkinter import ttk Traceback (most recent call last): File "", line 1, in from tkinter import ttk ImportError: No module named tkinter From jmnc at spray.se Tue Aug 10 12:47:34 2010 From: jmnc at spray.se (Jonas Nilsson) Date: Tue, 10 Aug 2010 18:47:34 +0200 Subject: Weird Python behaviour Message-ID: On 10 Ago, 13:58, Jonas Nilsson wrote: .... > You stumbled in two python common pitfalls at once :-) > One, the default arguments issue, was already pointed to you. > > The other one is that python variables are just names for objects. > Assigning a variable never mean making a copy, it just means using > another name for the same object. > There used to be a very nice (also graphic) explanationor this > somewhere on the web, but my googling skills failed me this time, > so instead I'll show you the concept using your own code: > >>>> class Family: > ... def __init__(self, fName, members = []): > ... self.fname = fName > ... self.members = members > ... >>>> mlist = ["Bill"] >>>> f1 = Family("Smiths", mlist ) >>>> mlist.append( "John" ) # attempt to not-so-clever reyse of the >>>> sme variable >>>> f2 = Family("Smithers", mlist ) >>>> f1.members > ['Bill', 'John'] > > Now my example is a bit contrieved but I'm sure you got the idea : in > your example is better to copy the list with > self.members = members[:]. > > Better yet, you could make use of python arguments grouping feature : >>>> class Family: > ... def __init__(self, fName, *members ): > ... self.members = list(members) # because members is a > tuple > ... self.fname = fName > ... >>>> f1 = Family("Smith") >>>> f1.members.append("Bill") >>>> f2 = Family("Smithers") >>>> f2.members.append("Joe") >>>> f2.members > ['Joe'] >>>> f1.members > ['Bill'] > > This solves your "no initial member" special case and allows for an > easier syntax for creating class instances > (no brackets involved) > >>>> f3 = Family("Bochicchio", "Angelo", "Francesco", "Mario") >>>> f3.members > ['Angelo', 'Francesco', 'Mario'] >>>> > > > Ciao > ---- > FB Thanks everyone. I was a bit steamed about the problem as it was very unexpected. Because I couldn't figure out what key words to google on, I resorted to posting the problem here. /Jonas From esnow at verio.net Tue Aug 10 13:40:54 2010 From: esnow at verio.net (Eric Snow) Date: Tue, 10 Aug 2010 10:40:54 -0700 (PDT) Subject: type enforcement in _ssl.sslwrap Message-ID: <38664845-c34d-452e-a09c-3206383e90e3@s17g2000prh.googlegroups.com> ssl.SSLSocket.__init__ makes a call to _ssl.sslwrap (in the C module). That in turn makes a call to PyArg_ParseTuple, which casts the first arg of _ssl.sslwrap into a PySocketModule.Sock_Type object. My problem is that I am trying to pass in an object that implements the Socket interface, but does not inherit from _socket.socket, like you do with file-like objects. Is there a way to make this work, or is the PyArg_ParseTuple call going to stop me. Would I need to have _ssl.sslwrap do something differently with its args? -eric From nisha.sinah at gmail.com Tue Aug 10 13:56:36 2010 From: nisha.sinah at gmail.com (Jeannette) Date: Tue, 10 Aug 2010 10:56:36 -0700 (PDT) Subject: (Free Special Offer) Sweet & Sexy Homely Girls & Wives Want To Stay with You For a Nite Total Free Message-ID: <6d935b82-109b-4978-9392-bd9f4381bc37@q21g2000prm.googlegroups.com> http://photosfair1.blogspot.com/2010/04/miss-india-may2003-reena_1978.html http://photosfair1.blogspot.com/2010/04/dirty-wives_5225.html http://photosfair1.blogspot.com/2010/04/miss-april-2003esha_8032.html http://photosfair1.blogspot.com/2010/04/miss-august-2003khushbo_9889.html http://photosfair1.blogspot.com/2010/04/beautifull-english-house-wives_5073.html http://photosfair1.blogspot.com/2010/04/english-beautifull-real-house-wises_6871.html http://photosfair1.blogspot.com/2010/04/miss-india-nov2002aarna_1751.html http://photosfair1.blogspot.com/2010/04/english-aunties_9920.html http://photosfair1.blogspot.com/2010/04/lovely-sexy-wives_9058.html http://photosfair1.blogspot.com/2010/05/sexy-beauty_9772.html http://photosfair1.blogspot.com/2010/05/girls-stockings.html http://www.photosfair.com http://www.photosfair.com http://www.photosfair.com http://www.photosfair.com http://www.photosfair.com http://www.mysmsfair.com http://www.mysmsfair.com http://www.mysmsfair.com http://www.mysmsfair.com http://www.mysmsfair.com http://www.mysmsfair.com From bieffe62 at gmail.com Tue Aug 10 14:00:01 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Tue, 10 Aug 2010 11:00:01 -0700 (PDT) Subject: Weird Python behaviour References: <4f9fc841-bd4f-471c-9e7c-dd91515fb5d2@a18g2000yqa.googlegroups.com> <4C6176E1.7020504@sschwarzer.net> Message-ID: On 10 Ago, 17:57, Stefan Schwarzer wrote: > Hi, > > On 2010-08-10 17:01, Francesco Bochicchio wrote: > > > There used to be a very nice (also graphic) explanationor this > > somewhere on the web, but my googling skills failed me this time, > > so instead I'll show you the concept using your own code: > > Probably this isn't the page you're referring to, but I only > recently gave a beginners' talk at EuroPython: > > http://sschwarzer.com/download/robust_python_programs_europython2010.pdf > > The topic of identity and assignments starts on slide 7, > nice graphics start on slide 10. ;-) > > Stefan Also good :-) But I finally found the page I was referring to: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables Ciao --- FB From pavlovevidence at gmail.com Tue Aug 10 14:49:07 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 10 Aug 2010 11:49:07 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> Message-ID: On Aug 10, 12:06?am, Ulrich Eckhardt wrote: > Carl Banks wrote: > > I highly doubt the Python source would build with a C++ compiler. > > As Christian showed, it doesn't. However, look around the sources a bit. > There are lots of places where e.g. the returnvalue of malloc() (or, > rather, the macro that resolves to something like it) is explicitly > type-cast to the according pointer type. When asked on the developers' > list, it was said that this was intended for compatibility with C++, e.g. > in cases where people want to embed Python into their C++ projects. Of > course, this contradicts Christian's statement that C++ compatibility > wasn't considered useful enough. I question why it needs to be compatible with C++ to be able to embed Python in a C++ project. How many C++ compilers out there don't come bundled with a C compiler? Carl Banks From news1234 at free.fr Tue Aug 10 15:13:57 2010 From: news1234 at free.fr (News123) Date: Tue, 10 Aug 2010 21:13:57 +0200 Subject: GUI automation tool (windows) In-Reply-To: References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4c61a4f5$0$5804$426a34cc@news.free.fr> On 08/10/2010 12:25 PM, Alex Barna wrote: > On Aug 10, 10:05 am, Lawrence D'Oliveiro > Can?t understand the point > to it. ?GUI automation? is a contradiction in >> terms, because a GUI is designed for use by humans to do manual tasks, not >> ones that can be automated. > > Automating GUI is for testing. And sometimesfor working around SW, whch has no cli or other interface and should be automated From martin.hellwig at dcuktec.org Tue Aug 10 15:23:09 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 10 Aug 2010 20:23:09 +0100 Subject: GUI automation tool (windows) In-Reply-To: <4c61a4f5$0$5804$426a34cc@news.free.fr> References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c61a4f5$0$5804$426a34cc@news.free.fr> Message-ID: On 08/10/10 20:13, News123 wrote: > On 08/10/2010 12:25 PM, Alex Barna wrote: >> On Aug 10, 10:05 am, Lawrence D'Oliveiro> Can?t understand the point >> to it. ?GUI automation? is a contradiction in >>> terms, because a GUI is designed for use by humans to do manual tasks, not >>> ones that can be automated. >> >> Automating GUI is for testing. > And sometimesfor working around SW, whch has no cli or other interface > and should be automated > That and when you are forced using a gui and need to 'copy and paste' between two programs that have no native bridge except for the one that is between the keyboard and chair, then it is nice to know that there is a way of automating it. -- mph From james at agentultra.com Tue Aug 10 16:44:17 2010 From: james at agentultra.com (J Kenneth King) Date: Tue, 10 Aug 2010 16:44:17 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <877hjykxjy.fsf@agentultra.com> James Mills writes: > On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >>> I would like to aquint myself with Python Interview questions >> >> This came up a while ago: >> >> http://www.mail-archive.com/python-list at python.org/msg168961.html >> >> Most of that thread is still relevant (perhaps throw in some py3l questions >> too) > > A common thing you can do in interviews is ask > your interviewee to write (in Python) a solution > to the "FizzBuzz" problem. Any good competent > Python programmer should be able to do this > in 5-10mins (5 if you're good). > > cheers > james Fizzbuzz is annoying in interviews. I've never worked at a job where I was under a timer while a group of people sat across from me and scrutinized everything I was doing. I don't see how it can honestly tell you anything useful about the person you're interviewing either. Do you really think that what you assume about the interviewee based on characteristics you can infer from their solution to be really, honestly true? They might even completely bomb the solution and still be a brilliant programmer, but you'll never know that if you trust this simple "fizzbuzz" test. I've been in those interviews on both sides of the table. Neither side was a good experience. If a test is necessary, make it a take-home or demand source code if they have it. Read their code and judge for yourself the quality of their work. Any questions in an interview should be the usual "get to know you" type stuff. "What was the most difficult challenge you've faced on the job? How did you respond?" That sort of thing. From xahlee at gmail.com Tue Aug 10 17:03:01 2010 From: xahlee at gmail.com (Xah Lee) Date: Tue, 10 Aug 2010 14:03:01 -0700 (PDT) Subject: a article on does lang influence thought Message-ID: <1475a4b3-4abf-4fb9-8804-5c9fa99bc1cc@z30g2000prg.googlegroups.com> Great article. ?Lost in Translation? (2010-07-23), by By Lera Boroditsky. >From The Wall Street Journal. ?New cognitive research suggests that language profoundly influences the way people see the world; a different sense of blame in Japanese and Spanish? http://online.wsj.com/article/SB10001424052748703467304575383131592767868.html no surprise to lispers. though, standard caution apply here... do take the findings in the story lightly, as such non-scientific writing usually are full of vague notions, misleading, and sometimes outright incorrect. Also, for those of you dumb mono-USers... perhaps it's time to pick up another lang. lol and, time to learn lojban too! ? Xah's lojban page http://xahlee.org/lojban/lojban.html Xah ? http://xahlee.org/ ? From benjamin.kaplan at case.edu Tue Aug 10 17:11:12 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 10 Aug 2010 14:11:12 -0700 Subject: python interview quuestions In-Reply-To: <877hjykxjy.fsf@agentultra.com> References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> Message-ID: On Tue, Aug 10, 2010 at 1:44 PM, J Kenneth King wrote: > James Mills writes: > >> On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >>>> I would like to aquint myself with Python Interview questions >>> >>> This came up a while ago: >>> >>> http://www.mail-archive.com/python-list at python.org/msg168961.html >>> >>> Most of that thread is still relevant (perhaps throw in some py3l questions >>> too) >> >> A common thing you can do in interviews is ask >> your interviewee to write (in Python) a solution >> to the "FizzBuzz" problem. Any good competent >> Python programmer should be able to do this >> in 5-10mins (5 if you're good). >> >> cheers >> james > > Fizzbuzz is annoying in interviews. > > I've never worked at a job where I was under a timer while a group of > people sat across from me and scrutinized everything I was doing. > > I don't see how it can honestly tell you anything useful about the > person you're interviewing either. ?Do you really think that what you > assume about the interviewee based on characteristics you can infer from > their solution to be really, honestly true? ?They might even completely > bomb the solution and still be a brilliant programmer, but you'll never > know that if you trust this simple "fizzbuzz" test. > The interviews where I've been asked to write code, the interviewers had almost no interest in the code I actually wrote. They wanted me to think out loud, to see how I approached the problem. To make sure I did actually know how to program and not just copy/paste from a text book. > I've been in those interviews on both sides of the table. ?Neither side > was a good experience. > > If a test is necessary, make it a take-home or demand source code if > they have it. ?Read their code and judge for yourself the quality of > their work. > > Any questions in an interview should be the usual "get to know you" type > stuff. ?"What was the most difficult challenge you've faced on the job? > How did you respond?" ?That sort of thing. > -- Now those questions are completely useless for those of us still in school. Because almost nothing we've done so far really says anything about how we'll do on the job. When I get an interview like that, I usually end up with the same 2-3 responses to every single question, because those are the only experieces I've had outside of "well I had this tough homework assignment". From atyazdi at ucdavis.edu Tue Aug 10 17:35:07 2010 From: atyazdi at ucdavis.edu (Anahita Yazdi) Date: Tue, 10 Aug 2010 14:35:07 -0700 Subject: Image histogram In-Reply-To: References: Message-ID: Yes, my question is regarding PIL. And basically I need to reload an image given a new histogram. The new histogram has still the same amount of overall pixels however I have only switched a couple of picks. Another thing I have tried was using a function that could be given to the "point" module but problem with that was that I didnt want to apply the function to every single count in the histogram. I only need to change two or three picks there. Is this something that could be done with PIL modules at all? Thank you and sorry for the confusion, Anahita On Mon, Aug 9, 2010 at 4:27 PM, Anahita Yazdi wrote: > Hi, > I was just wondering how would I be able to get some extra help regarding > editing an image's histogram using python's module? I have modified a > histogram of an image however I dont know how to apply the new histogram to > the image and basically reload the image based on its new modified histogram > instead of its own histogram? In the other words how should I make changes > on an image's histogram in a way that the image recognizes the new histogram > and gets changed? I need to somehow introduce a LUT for the image and use > ".point(table)" function to reload the image however I am not sure how to > make the right LUT from a modified histogram! > Thanks for the help in advance, > Anahita > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff.hobbs at gmail.com Tue Aug 10 17:51:14 2010 From: jeff.hobbs at gmail.com (Jeff Hobbs) Date: Tue, 10 Aug 2010 14:51:14 -0700 (PDT) Subject: File Manager in Tkinter References: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> <770366ta10gk98vgd5n2tapl7ag6skaeaj@4ax.com> Message-ID: On Aug 10, 9:43?am, John wrote: > On Tue, 10 Aug 2010 09:20:31 -0700 (PDT), Jeff ?Hobbs > > > > wrote: > >On Aug 9, 9:53?pm, John wrote: > >> As a learning exercise in Tkinter I htought about making a very simple > >> and basic file manager for my own use. I tried searching google for > >> any sample project and could not find anything. Not exactly ?sure how > >> to start I tought I could ask here? > > >> I thought about making two listboxes one to list folders only the > >> other files inside. I tried to make one listbox first but did not know > >> how to list folders only. > > >Filter with os.path.isdir() > > >> Is there a way to list folders with images? > >> Any suggestions or help how to proced would be appreciated. > > >If you are using a Tkinter with Ttk (Tk 8.5), then use the treeview > >widget: > > >http://docs.activestate.com/activepython/3.1/python/library/tkinter.t... > > >For more advanced needs, there is a Tk extension called tktreectrl > >that does some very cool views and has lots of controls: > > >http://tktreectrl.sourceforge.net/ > > >Jeff > > My python is version 2.6.5. ?Would you recomend I upgrade and if yes > to which version? The version of python really isn't tightly coupled to the version of Tk, it is the configuration of how that python is built. ActivePython builds with Tk 8.5, so if you are using that, and it is < v3.1 (where ttk is in the core), then just do: pypm install pyttk which will install the wrapper you need for Ttk into v2.6 or 2.7 python. You need to make sure that you have Tk 8.5 (Tkinter.TkVersion >= 8.5) for ttk to work (though not technically true, the 8.4 tile version has subtle differences). The core python distro is still using the older Tk 8.4 in stock installers iiuc. Jeff From John Tue Aug 10 18:01:10 2010 From: John (John) Date: Tue, 10 Aug 2010 18:01:10 -0400 Subject: File Manager in Tkinter References: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> <770366ta10gk98vgd5n2tapl7ag6skaeaj@4ax.com> Message-ID: On Tue, 10 Aug 2010 14:51:14 -0700 (PDT), Jeff Hobbs wrote: >On Aug 10, 9:43?am, John wrote: >> On Tue, 10 Aug 2010 09:20:31 -0700 (PDT), Jeff ?Hobbs >> >> >> >> wrote: >> >On Aug 9, 9:53?pm, John wrote: >> >> As a learning exercise in Tkinter I htought about making a very simple >> >> and basic file manager for my own use. I tried searching google for >> >> any sample project and could not find anything. Not exactly ?sure how >> >> to start I tought I could ask here? >> >> >> I thought about making two listboxes one to list folders only the >> >> other files inside. I tried to make one listbox first but did not know >> >> how to list folders only. >> >> >Filter with os.path.isdir() >> >> >> Is there a way to list folders with images? >> >> Any suggestions or help how to proced would be appreciated. >> >> >If you are using a Tkinter with Ttk (Tk 8.5), then use the treeview >> >widget: >> >> >http://docs.activestate.com/activepython/3.1/python/library/tkinter.t... >> >> >For more advanced needs, there is a Tk extension called tktreectrl >> >that does some very cool views and has lots of controls: >> >> >http://tktreectrl.sourceforge.net/ >> >> >Jeff >> >> My python is version 2.6.5. ?Would you recomend I upgrade and if yes >> to which version? > >The version of python really isn't tightly coupled to the version of >Tk, it is the configuration of how that python is built. ActivePython >builds with Tk 8.5, so if you are using that, and it is < v3.1 (where >ttk is in the core), then just do: > pypm install pyttk >which will install the wrapper you need for Ttk into v2.6 or 2.7 >python. You need to make sure that you have Tk 8.5 (Tkinter.TkVersion >>= 8.5) for ttk to work (though not technically true, the 8.4 tile >version has subtle differences). The core python distro is still >using the older Tk 8.4 in stock installers iiuc. > >Jeff My version is from python.org can I upgrade my version to 8.5? tia for all the help much appreciated. From peter.milliken at gmail.com Tue Aug 10 18:51:31 2010 From: peter.milliken at gmail.com (Peter) Date: Tue, 10 Aug 2010 15:51:31 -0700 (PDT) Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> Message-ID: <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Agreed. Although anything that involves "take home" or reading of "their" code runs the risk of the candidate presenting somebody else's work... It was never a good experience being responsible for the hiring of somebody based on how well they sell themselves in an interview - some people are hopeless "sales people" and yet could be fantastic programmers! I mean lets face it, if you were good at selling would you still be a programmer? :-) I know who makes the most money! Of course there is the question of job satisfaction... I usually just tried to get a feel for their stated experience and ask some questions just to make sure they weren't presenting somebodies else's (fictitious even!) resume. You generally make the best decision based on a number of factors about each candidate and depend on the 3 or 6 month "trial" period to weed out any bad mistakes you may have made during selection! I remember one team I managed had an individual from overseas (I won't mention the country or anything) - and therefore background checks by HR were not really possible. The person made so many fundamental mistakes that I went to the project manager and asked to see the resume - there was no way in this world that they had ever done even 1/100th of what their resume stated! :-) Obviously the interviewers for that person where completely conned and missed the (what should have been) obvious signs that the resume and candidate did not match. This was one of the many reasons why I decided on a career change and went back to being a dumb and happy programmer! That was 14 years ago now and I haven't regretted the decision one single day of that time :-) Peter On Aug 11, 6:44?am, J Kenneth King wrote: > James Mills writes: > > On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: > >>> I would like to aquint myself with Python Interview questions > > >> This came up a while ago: > > >> http://www.mail-archive.com/python-l... at python.org/msg168961.html > > >> Most of that thread is still relevant (perhaps throw in some py3l questions > >> too) > > > A common thing you can do in interviews is ask > > your interviewee to write (in Python) a solution > > to the "FizzBuzz" problem. Any good competent > > Python programmer should be able to do this > > in 5-10mins (5 if you're good). > > > cheers > > james > > Fizzbuzz is annoying in interviews. > > I've never worked at a job where I was under a timer while a group of > people sat across from me and scrutinized everything I was doing. > > I don't see how it can honestly tell you anything useful about the > person you're interviewing either. ?Do you really think that what you > assume about the interviewee based on characteristics you can infer from > their solution to be really, honestly true? ?They might even completely > bomb the solution and still be a brilliant programmer, but you'll never > know that if you trust this simple "fizzbuzz" test. > > I've been in those interviews on both sides of the table. ?Neither side > was a good experience. > > If a test is necessary, make it a take-home or demand source code if > they have it. ?Read their code and judge for yourself the quality of > their work. > > Any questions in an interview should be the usual "get to know you" type > stuff. ?"What was the most difficult challenge you've faced on the job? > How did you respond?" ?That sort of thing. From martin at v.loewis.de Tue Aug 10 20:06:57 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 11 Aug 2010 02:06:57 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <9da7j7-pv2.ln1@satorlaser.homedns.org> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> Message-ID: <4C61E9A1.5090800@v.loewis.de> Am 10.08.2010 09:06, schrieb Ulrich Eckhardt: > Carl Banks wrote: >> I highly doubt the Python source would build with a C++ compiler. > > As Christian showed, it doesn't. However, look around the sources a bit. > There are lots of places where e.g. the returnvalue of malloc() (or, > rather, the macro that resolves to something like it) is explicitly > type-cast to the according pointer type. When asked on the developers' > list, it was said that this was intended for compatibility with C++, e.g. > in cases where people want to embed Python into their C++ projects. Of > course, this contradicts Christian's statement that C++ compatibility > wasn't considered useful enough. It doesn't contradict at all. In order to embed Python into a C++ application, it is sufficient if the Python header files can be compiled with a C++ compiler, and linking to the C function works properly - which is indeed the case. People integrate Python with C++ quite often, both for embedding it into C++, and for writing extension modules in C++. Regards, Martin From roy at panix.com Tue Aug 10 20:08:14 2010 From: roy at panix.com (Roy Smith) Date: Tue, 10 Aug 2010 20:08:14 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: In article <507f1970-9c15-4200-a90b-6ebc018c074b at a4g2000prm.googlegroups.com>, Peter wrote: > Agreed. Although anything that involves "take home" or reading of > "their" code runs the risk of the candidate presenting somebody else's > work... I expect a candidate to emphasize their positive qualities, perhaps even exaggerate a little. The point of a technical interview is to assess just how much of each :-) What I do NOT expect is outright prevarication. I go into the interview with the assumption that the candidate is, if nothing else, honest. In any case, if the candidate were to submit somebody else's work, it would come out pretty quickly as we discussed their code. I suppose one question I might ask would be, "Can you explain why, when I copy-paste one of your comments into a google search box, your entire program appears?" > I usually just tried to get a feel for their stated experience and ask > some questions just to make sure they weren't presenting somebodies > else's (fictitious even!) resume. Amazingly enough, that does happen. I once got two resumes in the same pile which were word-for-word identical, except for the name on the top. I've been around the block a few times, but I was still shocked. I'm not sure what was more shocking; that people could be that dishonest, or that they could be so clumsy and stupid about it. From candide at free.invalid Tue Aug 10 20:37:08 2010 From: candide at free.invalid (candide) Date: Wed, 11 Aug 2010 02:37:08 +0200 Subject: Splitting a sequence into pieces with identical elements Message-ID: <4c61f0c2$0$30068$426a34cc@news.free.fr> Suppose you have a sequence s , a string for say, for instance this one : spppammmmegggssss We want to split s into the following parts : ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] ie each part is a single repeated character word. What is the pythonic way to answer this question? A naive solution would be the following : # ------------------------------- z='spppammmmegggssss' zz=[] while z: k=1 while z[:k]==k*z[0]: k+=1 zz+=[z[:k-1]] z=z[k-1:] print zz # ------------------------------- but I guess this code is not very idiomatic :( From clp2 at rebertia.com Tue Aug 10 21:11:00 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 10 Aug 2010 18:11:00 -0700 Subject: Splitting a sequence into pieces with identical elements In-Reply-To: <4c61f0c2$0$30068$426a34cc@news.free.fr> References: <4c61f0c2$0$30068$426a34cc@news.free.fr> Message-ID: On Tue, Aug 10, 2010 at 5:37 PM, candide wrote: > Suppose you have a sequence s , a string ?for say, for instance this one : > > spppammmmegggssss > > We want to split s into the following parts : > > ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] > > ie each part is a single repeated character word. > > What is the pythonic way to answer this question? If you're doing an operation on an iterable, always leaf thru itertools first: http://docs.python.org/library/itertools.html from itertools import groupby def split_into_runs(seq): return ["".join(run) for letter, run in groupby(seq)] If itertools didn't exist: def split_into_runs(seq): if not seq: return [] iterator = iter(seq) letter = next(iterator) count = 1 words = [] for c in iterator: if c == letter: count += 1 else: word = letter * count words.append(word) letter = c count = 1 words.append(letter*count) return words Cheers, Chris -- http://blog.rebertia.com From python.list at tim.thechases.com Tue Aug 10 21:18:36 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 10 Aug 2010 20:18:36 -0500 Subject: Splitting a sequence into pieces with identical elements In-Reply-To: <4c61f0c2$0$30068$426a34cc@news.free.fr> References: <4c61f0c2$0$30068$426a34cc@news.free.fr> Message-ID: <4C61FA6C.4010907@tim.thechases.com> On 08/10/10 19:37, candide wrote: > Suppose you have a sequence s , a string for say, for instance this one : > > spppammmmegggssss > > We want to split s into the following parts : > > ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] > > ie each part is a single repeated character word. While I'm not sure it's idiomatic, the overabuse of regexps in Python certainly seems prevalent enough to be idiomatic ;-) As such, you can use: import re r = re.compile(r'((.)\1*)') #r = re.compile(r'((\w)\1*)') s = 'spppammmmegggssss' results = [m.group(0) for m in r.finditer(s)] Additionally, you have all the properties of the match-object (which includes the start/end) available too if you need). You don't specify what you want to have happen with non-letters (whitespace, punctuation, etc). The above just treats them like any other character, finding repeats. If you just want "word" characters, you can use the 2nd ("\w") version, or adjust accordingly. -tkc From python at mrabarnett.plus.com Tue Aug 10 21:30:49 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 02:30:49 +0100 Subject: Splitting a sequence into pieces with identical elements In-Reply-To: <4C61FA6C.4010907@tim.thechases.com> References: <4c61f0c2$0$30068$426a34cc@news.free.fr> <4C61FA6C.4010907@tim.thechases.com> Message-ID: <4C61FD49.9070704@mrabarnett.plus.com> Tim Chase wrote: > On 08/10/10 19:37, candide wrote: >> Suppose you have a sequence s , a string for say, for instance this >> one : >> >> spppammmmegggssss >> >> We want to split s into the following parts : >> >> ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] >> >> ie each part is a single repeated character word. > > While I'm not sure it's idiomatic, the overabuse of regexps in Python > certainly seems prevalent enough to be idiomatic ;-) > > As such, you can use: > > import re > r = re.compile(r'((.)\1*)') > #r = re.compile(r'((\w)\1*)') That should be \2, not \1. Alternatively: r = re.compile(r'(.)\1*') #r = re.compile(r'(\w)\1*') > s = 'spppammmmegggssss' > results = [m.group(0) for m in r.finditer(s)] > > Additionally, you have all the properties of the match-object (which > includes the start/end) available too if you need). > > You don't specify what you want to have happen with non-letters > (whitespace, punctuation, etc). The above just treats them like any > other character, finding repeats. If you just want "word" characters, > you can use the 2nd ("\w") version, or adjust accordingly. > From ritchy_gato at hotmail.com Tue Aug 10 22:01:41 2010 From: ritchy_gato at hotmail.com (Ritchy lelis) Date: Tue, 10 Aug 2010 19:01:41 -0700 (PDT) Subject: How to implement a pipeline...??? Please help References: <5242b005-31b6-4a9c-afd9-6fbb82e28db7@l14g2000yql.googlegroups.com> Message-ID: <08ce00ca-f58e-4ff4-a95e-54f7a4d5071f@w30g2000yqw.googlegroups.com> On 7 Ago, 07:30, Dennis Lee Bieber wrote: > On Fri, 6 Aug 2010 16:47:58 -0700 (PDT), Ritchy lelis > declaimed the following in > gmane.comp.python.general: > > > Guys i'm asking if it's possible for a generic function for a > > pipeline, all the suggestions ideas are welcome. > > ? ? ? ? I've not done metaclasses, so don't know if a metaclass would be of > use... Since it appears one would have to have something that generates > functions on the fly based upon inputs... > > ? ? ? ? I look at details on what you are trying to create and see a > series-parallel circuit architecture with clocked stages and delay lines > for the summing of the outputs. That is, when the clock ticks, every > stage in the unit does its processing and provides and output... On the > next tick, those outputs become inputs to the subsequent stage and the > process repeats > > > Also if you have a specific solution for my problem I will be grateful > > for it here. > > ? ? ? ? I'm still blinking at the thought of doing analog to digital > conversion in Python! I sure wouldn't hold out much hope of real-time > signal processing. There is a reason ADC and DAC are done in hardware, > even if the intermediate processing is with general purpose processors. > > ? ? ? ? I'm also not sure I understand the > > np.linspace(1,1, Inc)... > > ? ? ? ? Looking up documentation implies you are trying to create a vector > of "inc" length, evenly populated by values between 1 and 1... which > means a vector of all 1s... Might it not be faster to just > > ? ? ? ? v = [1] * inc > > and pass v to some numpy method for conversion from Python list to numpy > vector? > > (the -1 to 1 at least makes sense) > > ? ? ? ? Me? I'd probably create a class in which the __init__() takes a > value specifying the number of stages. It would than create suitable > lists to track values, some sort of counter (c), a Semaphore (s) > [initialized at 0 -- ie, already acquired/block], ?a thread for EACH > stage, and an Event (e) object > > ? ? ? ? Each stage thread, initialized with its position in the pipeline. > The threads perform an e.wait() call. They also, after the wait is > released, perform an e.clear() call. As their processing, they each grab > from the pipeline "input" list the current value for their position. > After processing they update their position in the "output" list(s), > they decrement the counter c (maybe put a lock around access to c). The > thread that decrements c to 0 is responsible for "releasing" the > semaphore. > > ? ? ? ? The main code of the class instance is responsible for a loop that > does: set up the "input" list based on current value of stage outputs, > initialize c to the count of stages (minus 1?), e.set() to signal all > stage threads to process the current conditions, s.acquire() to block > until the last processed thread (by c hitting 0) does s.release(). It > then collects the output lists, does whatever shifting is needed to > prepare for the next cycle... > > ? ? ? ? Actually, that "loop" may not be a loop so much as a method off the > class like > > ? ? ? ? digitalOutput = adcInstance.step(analogInput) > > which is, itself, in a loop. > > That is, something like... > > myADC = ADC(stages=10) > while True: > ? ? ? ? voltage = getNextAnalogInput() > ? ? ? ? digital = myADC.step(voltage) > ? ? ? ? outputDigitalValue() > > ? ? ? ? Obviously I've not taken the time to actually lay out all the > instance lists needed for inputs and outputs, nor the code of threads > (while one can create the first "stages-1" threads with a loop, the > final stage needs a discrete creation) > > ? ? ? ? When one finds that the threading solution is really slow (though > understandable in terms of the hardware circuit -- one thread per stage > makes the stages easy to code), THEN one might try to figure out how to > implement an iterative version... I suspect using numpy would be the > third optimization -- removing iteration by using parallel vector > operations. > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ Hi First of all i would like to thank you for your time and help. I appreciate your suggestions and they seems very good to me... The only problem it's that i'm newbie at python programming, but still interested to learn more and more... I already got a solution through harsh but it worked. at least I got the wave form i wanted. Next i'm going to let you'll my solution here. It's rudimentary but it work's. Seems very perceptible that's why i will not explain it right now but if in case of doubt I will: Pipeline Function: from flash1b5 import flash1b5 from flash1b5 import * from flash2b import flash2b from flash2b import * import matplotlib.pyplot as plt import numpy as np from pylab import * if __name__ == "__main__": Inc = raw_input("Valor do Incrimento = ") Vref = np.linspace(1,1, Inc) Vi = np.linspace(-1,1, Inc) # x = np.linspace(-1,1, Inc) # Vi = 1*sin(2*pi*(x-1/4)) Cs = np.linspace(3e-12, 3e-12, Inc) Cf = np.linspace(3e-12, 3e-12, Inc) f1 = flash1b5(Vi, Vref, Cs, Cf) Vin1 = f1[0] Vt1 = f1[1] Vd1 = f1[2]*256 f2 = flash1b5(Vt1, Vref, Cs, Cf) Vin2 = f2[0] Vt2 = f2[1] Vd2 = f2[2]*128 f3 = flash1b5(Vt2, Vref, Cs, Cf) Vin3 = f3[0] Vt3 = f3[1] Vd3 = f3[2]*64 f4 = flash1b5(Vt3, Vref, Cs, Cf) Vin4 = f4[0] Vt4 = f4[1] Vd4 = f4[2]*32 f5 = flash1b5(Vt4, Vref, Cs, Cf) Vin5 = f5[0] Vt5 = f5[1] Vd5 = f5[2]*16 f6 = flash1b5(Vt5, Vref, Cs, Cf) Vin6 = f6[0] Vt6 = f6[1] Vd6 = f6[2]*8 f7 = flash1b5(Vt6, Vref, Cs, Cf) Vin7 = f7[0] Vt7 = f7[1] Vd7 = f7[2]*4 f8 = flash1b5(Vt7, Vref, Cs, Cf) Vin8 = f8[0] Vt8 = f8[1] Vd8 = f8[2]*2 f2b = flash2b(Vt8, Vref) Vin2b = f2b[0] Vd2b = f2b[1]*1 Vd = Vd1+Vd2+Vd3+Vd4+Vd5+Vd6+Vd7+Vd8+Vd2b ## print 'Vin = ',Vin ## print 'Vt = ',Vt ## print 'Vd = ',Vd ## # fig1 = figure(1,figsize=(8,5)) # ax1 = fig1.add_subplot(211, autoscale_on=False, xlim=(-1,1), ylim=(-1,1)) # ax1.plot(Vin1, Vt4, lw=2, color='blue') # grid (True); title('FLASH 1.5 BIT',fontsize = 16);ylabel('Vout_Residuo') ## ## ax1.annotate('00', xy=(-0.5, 0.5)) ## ax1.annotate('01', xy=(0.0, 0.5)) ## ax1.annotate('11', xy=(0.5, 0.5)) # ## hold(True) # fig2 = figure(1,figsize=(8,5)) ax2 = fig2.add_subplot(111, autoscale_on=True) ax2.plot(Vin1, Vd, lw=2, color='red') grid (True); xlabel('Vin');ylabel('Vout_Digital') # ## ax2.annotate('00 --> 0', xy=(-0.5, 0.1)) ## ax2.annotate('01 --> 1', xy=(0.0, 1.1)) ## ax2.annotate('11 --> 2', xy=(0.5, 2.1)) ## # plt.show() -------------------------------------------------------------------------- About the answer i got for my last post: 1 - v = [1] * inc > > and pass v to some numpy method for conversion from Python list to numpy > vector? Yes i agree with you, but at the time i made it i found that function (Linspace) that could do what i was loking for and i didn't worry about search for a better solution. but even if wanted to, i'm new at the programming language and i don't know how to convert a list to a vector in numpy. but still open for tips/tricks that could help me. 2 - > Me? I'd probably create a class in which the __init__() takes a > value specifying the number of stages. It would than create suitable > lists to track values, some sort of counter (c), a Semaphore (s) > [initialized at 0 -- ie, already acquired/block], a thread for EACH > stage, and an Event (e) object > Each stage thread, initialized with its position in the pipeline. > The threads perform an e.wait() call. They also, after the wait is > released, perform an e.clear() call. As their processing, they each grab > from the pipeline "input" list the current value for their position. > After processing they update their position in the "output" list(s), > they decrement the counter c (maybe put a lock around access to c). The > thread that decrements c to 0 is responsible for "releasing" the > semaphore I did understand your algorithm/idea and that's what i want to implement here (you couldn't be more right). but i don't now how to implement the funcs e.wait() call and e.clear() call. they already exists? i have to create them? if I may, i would like to ask more help on this one please. I hope not to be bothering you :( From darkrho at gmail.com Tue Aug 10 22:27:32 2010 From: darkrho at gmail.com (Rolando Espinoza La Fuente) Date: Tue, 10 Aug 2010 22:27:32 -0400 Subject: python interview quuestions In-Reply-To: <4C5CC582.5080005@tim.thechases.com> References: <4C5C5528.5060608@tim.thechases.com> <4C5CC582.5080005@tim.thechases.com> Message-ID: On Fri, Aug 6, 2010 at 10:31 PM, Tim Chase wrote: [...] >> More over, it can be done in just a single line of Python. >> >> 7 if you're not very familiar with Python. > > While it *can* be done in one line, I'm not sure it's the most legible > solution. ?Though I must say I like this one-line python version: > > for i in range(1, 101): print ((i%3==0 and 'fizz' or '') + (i%5==0 and > 'buzz' or '')) or i > > (adjust "3" and "5" for your local flavor of fizzbuzz) > > I'm not sure I'd hire a candidate that proposed this as a solution in > earnest, but I'd have fun chatting with them :) I didn't believe it could take more than 5 minutes, but this took me ~10 minutes, though I'm familiar with python and I did the FizzBuzz one-liners before: http://gist.github.com/518370 Well.. I tried to use generators to make it "cool" but changed it for a test-friendly approach. I'll find hard to remember the one-liners in an interview and get it right. Rolando Espinoza La fuente www.insophia.com From python.list at tim.thechases.com Tue Aug 10 22:31:09 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 10 Aug 2010 21:31:09 -0500 Subject: Splitting a sequence into pieces with identical elements In-Reply-To: <4C61FD49.9070704@mrabarnett.plus.com> References: <4c61f0c2$0$30068$426a34cc@news.free.fr> <4C61FA6C.4010907@tim.thechases.com> <4C61FD49.9070704@mrabarnett.plus.com> Message-ID: <4C620B6D.90303@tim.thechases.com> On 08/10/10 20:30, MRAB wrote: > Tim Chase wrote: >> r = re.compile(r'((.)\1*)') >> #r = re.compile(r'((\w)\1*)') > > That should be \2, not \1. > > Alternatively: > > r = re.compile(r'(.)\1*') Doh, I had played with both and mis-transcribed the combination of them into one malfunctioning regexp. My original trouble with the 2nd one was that r.findall() (not .finditer) was only returning the first letter of each because that's what was matched. Wrapping it in the extra set of parens and using "\2" returned the actual data in sub-tuples: >>> s = 'spppammmmegggssss' >>> import re >>> r = re.compile(r'(.)\1*') >>> r.findall(s) # no repeated text, just the initial letter ['s', 'p', 'a', 'm', 'e', 'g', 's'] >>> [m.group(0) for m in r.finditer(s)] ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] >>> r = re.compile(r'((.)\2*)') >>> r.findall(s) [('s', 's'), ('ppp', 'p'), ('a', 'a'), ('mmmm', 'm'), ('e', 'e'), ('ggg', 'g'), ('ssss', 's')] >>> [m.group(0) for m in r.finditer(s)] ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] By then changing to .finditer() it made them both work the way I wanted. Thanks for catching my mistranscription. -tkc From ldo at geek-central.gen.new_zealand Tue Aug 10 22:57:27 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 14:57:27 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message , Alex Barna wrote: > On Aug 10, 10:05 am, Lawrence D'Oliveiro > >> Can?t understand the point to it. ?GUI automation? is a contradiction in >> terms, because a GUI is designed for use by humans to do manual tasks, >> not ones that can be automated. > > Automating GUI is for testing. But the most egregious GUI problems are going to be with humans being unable to figure out how to do something, am I right? How are you going to uncover those problems, except by testing with real people? Automated testing isn?t going to do it. From ldo at geek-central.gen.new_zealand Tue Aug 10 22:59:14 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 14:59:14 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c61a4f5$0$5804$426a34cc@news.free.fr> Message-ID: In message <4c61a4f5$0$5804$426a34cc at news.free.fr>, News123 wrote: > On 08/10/2010 12:25 PM, Alex Barna wrote: > >> On Aug 10, 10:05 am, Lawrence D'Oliveiro >> >>> Can?t understand the point to it. ?GUI automation? is a contradiction in >>> terms, because a GUI is designed for use by humans to do manual tasks, >>> not ones that can be automated. >> >> Automating GUI is for testing. > > And sometimesfor working around SW, whch has no cli or other interface > and should be automated Who would design software in such a brain-dead way? From invalid at invalid.invalid Tue Aug 10 23:06:49 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 03:06:49 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message >, Alex > Barna wrote: > >> On Aug 10, 10:05 am, Lawrence D'Oliveiro >> >>> Can???t understand the point to it. ???GUI automation??? is a contradiction in >>> terms, because a GUI is designed for use by humans to do manual tasks, >>> not ones that can be automated. >> >> Automating GUI is for testing. > > But the most egregious GUI problems are going to be with humans being > unable to figure out how to do something, am I right? How are you > going to uncover those problems, except by testing with real people? > Automated testing isn???t going to do it. Automated GUI testing isn't intended to uncover those sorts of problems in GUI design. Automated GUI intended to uncover problems in the underlying program functionality, and is used mainly for regression testing to insure that changes made to a program didn't cause any unintended changes in program behavior. Automated GUI testing often isn't even being used to test the program whos GUI is being automated. It's often used to test _other_ programs with which the GUI-automated-program interacts. -- Grant From invalid at invalid.invalid Tue Aug 10 23:08:18 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 03:08:18 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c61a4f5$0$5804$426a34cc@news.free.fr> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message <4c61a4f5$0$5804$426a34cc at news.free.fr>, News123 wrote: >> On 08/10/2010 12:25 PM, Alex Barna wrote: >>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>> >>>> Can???t understand the point to it. ???GUI automation??? is a >>>> contradiction in terms, because a GUI is designed for use by humans >>>> to do manual tasks, not ones that can be automated. >>> >>> Automating GUI is for testing. >> >> And sometimesfor working around SW, whch has no cli or other >> interface and should be automated > > Who would design software in such a brain-dead way? In my experience, almost everybody who designes apps for MS Windows. -- Grant From cs at zip.com.au Tue Aug 10 23:08:59 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 11 Aug 2010 13:08:59 +1000 Subject: How to capture all the environment variables from shell? In-Reply-To: <4C615D1B.7060204@syslang.net> References: <4C615D1B.7060204@syslang.net> Message-ID: <20100811030859.GA2279@cskk.homeip.net> On 10Aug2010 10:07, Steven W. Orr wrote: | On 8/2/2010 4:33 AM, Thorsten Kampe wrote: | > * Tim Chase (Mon, 26 Jul 2010 21:42:24 -0500) | >> On 07/26/10 21:26, Steven W. Orr wrote: | >>> Please! Never export anything from your .bashrc unless you | >>> really know what you're doing. Almost all exports should be | >>> done in your .bash_profile | >> | >> Could you elaborate on your reasoning why (or why-not)? I've | >> found that my .bash_profile doesn't get evaluated when I crank up | >> another terminal window, while my bashrc does. Thus I tend to | >> put my exports in my ~/.bashrc so they actually take effect in my | >> shell... | > | > ~/.bash_profile is only evaluated for login shells and ~/.bashrc only | > for non-login shells. Thus it's recommended to keep ~/.bash_profile | > empty (except a source statement for .bashrc) and put all your settings, | > aliases, exports, etc. in .bashrc. | | Sorry. Dead wrong. Please reread the above comment I wrote. If you set your | environment variables in the .bashrc then you completely lose the ability of | environment variables to be inherited by sub-shells. Again, envvars should be | set in the .bash_profile, most everything else should be set in the .bashrc, and | the .bashrc should be sourced into the .bash_profile to solve the problem that | you thought you were solving. | | After that, and again, be aware that the .bashrc alone is executed for login | shells *which are not interactive*. for example: | | ssh somemachine 'echo Hello' | | This command will *not* go through the .bash_profile but it will go through the | .bashrc. No, only interactive shells use the .bashrc. Still, you're quite right that envvars belong in the .bash_profile. .bashrc is for trivial setup stuff relevant only to interactive shells (for example history settings and interactive aliases). | This means that for cases like this, we want to check to see if the | bash process is interactive or not inside the .bashrc and then do the right thing. | | =============== | [[ -z "$PS1" ]] && setPATHHere | =============== This is Very Wrong. (RedHat do this test - it is bogus - if I set $PS1 in my profile it breaks badly.) Instead, test $-: case $- in *i*) echo INTERACTIVE ;; *) echo BATCH ;; esac | This is not needed for the above degenerate case, but it is needed if the | command in question is kept in a directory that you normally find in a place | that is part of your personal login PATH. E.G., If myprog lives in ~/bin then | | ssh somemachine myprog | | will fail unless you use the above construct. | | Hopefully, I'll only have to re-explain this another google times... "googol", surely? The reason .bashrc gets overused for envars, aside from ignorance and propagated bad habits, is that in a GUI desktop the setup sequence is often a bit backwards. A conventional terminal/console login means you get a login shell that sources your .{bash_}profile. And from there one would start a GUI and all the .profile stuff has been run Once, as it should be. But when the login itself is a GUI the various terminals get started _before_ the .profile stuff gets sourced, because the terminal is started by the desktop manager. Once common "fix" for this is to make all new terminals run login shells. Ugh, but it does work. But it they're not login shells, people stuff everything into their .bashrc because the .profile doesn't get sourced. And so the common awful setup you're bemoaning. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ For us, Zettai Zetsumei Toshi is an allegory for relations between the sexes, and it works especially well at this because we don't speak Japanese. She will say things, and we have no idea what the hell is going on, and then we'll select from a list of responses, but we have no idea which one is the right one, and then they're all wrong. It works on a lot of levels. - Tycho @ _Penny_Arcade_ From robert.kern at gmail.com Tue Aug 10 23:11:02 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 10 Aug 2010 22:11:02 -0500 Subject: GUI automation tool (windows) In-Reply-To: References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-10 21:57 , Lawrence D'Oliveiro wrote: > In message > , Alex > Barna wrote: > >> On Aug 10, 10:05 am, Lawrence D'Oliveiro >> >>> Can?t understand the point to it. ?GUI automation? is a contradiction in >>> terms, because a GUI is designed for use by humans to do manual tasks, >>> not ones that can be automated. >> >> Automating GUI is for testing. > > But the most egregious GUI problems are going to be with humans being unable > to figure out how to do something, am I right? Possibly, but it's not the *only* important problem. Automated GUI testing is usually a form of regression testing. You want to make sure that the behavior of parts of the GUI did not change when you made what should be unrelated modifications to the code. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Tue Aug 10 23:12:33 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 10 Aug 2010 22:12:33 -0500 Subject: GUI automation tool (windows) In-Reply-To: References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c61a4f5$0$5804$426a34cc@news.free.fr> Message-ID: On 2010-08-10 21:59 , Lawrence D'Oliveiro wrote: > In message<4c61a4f5$0$5804$426a34cc at news.free.fr>, News123 wrote: > >> On 08/10/2010 12:25 PM, Alex Barna wrote: >> >>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>> >>>> Can?t understand the point to it. ?GUI automation? is a contradiction in >>>> terms, because a GUI is designed for use by humans to do manual tasks, >>>> not ones that can be automated. >>> >>> Automating GUI is for testing. >> >> And sometimesfor working around SW, whch has no cli or other interface >> and should be automated > > Who would design software in such a brain-dead way? People who are not being paid for a CLI or other interface. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From cs at zip.com.au Tue Aug 10 23:16:01 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 11 Aug 2010 13:16:01 +1000 Subject: How to capture all the environment variables from shell? In-Reply-To: <20100811030859.GA2279@cskk.homeip.net> References: <20100811030859.GA2279@cskk.homeip.net> Message-ID: <20100811031601.GA4188@cskk.homeip.net> On 11Aug2010 13:08, I wrote: | On 10Aug2010 10:07, Steven W. Orr wrote: [...] | | After that, and again, be aware that the .bashrc alone is executed for login | | shells *which are not interactive*. for example: | | | | ssh somemachine 'echo Hello' | | | | This command will *not* go through the .bash_profile but it will go through the | | .bashrc. | | No, only interactive shells use the .bashrc. And then I read more closely and saw this in "man bash": Bash attempts to determine when it is being run by the remote shell daemon, usually rshd. If bash determines it is being run by rshd, it reads and executes commands from ~/.bashrc, if that file exists and is readable. It will not do this if invoked as sh. The --norc option may be used to inhibit this behavior, and the --rcfile option may be used to force another file to be read, but rshd does not generally invoke the shell with those options or allow them to be specified. Frankly, bash's startup behaviour is so corrupt (well, capricious anway) that I despair of it; I use zsh when possible. It also tries to be all things to all people, but is a bit saner. (And it doesn't hardwire ^W either!) Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ To be positive: To be mistaken at the top of one's voice. Ambrose Bierce (1842-1914), U.S. author. The Devil's Dictionary (1881-1906). From ben+python at benfinney.id.au Tue Aug 10 23:45:24 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 11 Aug 2010 13:45:24 +1000 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <87wrrxyfqj.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > Alex Barna wrote: > > > On Aug 10, 10:05 am, Lawrence D'Oliveiro > > > >> Can?t understand the point to it. ?GUI automation? is a > >> contradiction in terms, because a GUI is designed for use by humans > >> to do manual tasks, not ones that can be automated. > > > > Automating GUI is for testing. > > But the most egregious GUI problems are going to be with humans being > unable to figure out how to do something, am I right? You asked to understand the point of GUI automation. Alex responded with one (there may well be others) very good point of GUI automation: automated testing of the GUI's behaviour. What you raise here is not the point of GUI automation. Is you understanding of the point of GUI automation improved? -- \ ?I turned to speak to God/About the world's despair; But to | `\ make bad matters worse/I found God wasn't there.? ?Robert Frost | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Wed Aug 11 00:51:30 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 16:51:30 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message , Robert Kern wrote: > On 2010-08-10 21:57 , Lawrence D'Oliveiro wrote: > >> In message >> , Alex >> Barna wrote: >> >>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>> >>>> Can?t understand the point to it. ?GUI automation? is a contradiction >>>> in terms, because a GUI is designed for use by humans to do manual >>>> tasks, not ones that can be automated. >>> >>> Automating GUI is for testing. >> >> But the most egregious GUI problems are going to be with humans being >> unable to figure out how to do something, am I right? > > Possibly, but it's not the *only* important problem. Automated GUI testing > is usually a form of regression testing. You want to make sure that the > behavior of parts of the GUI did not change when you made what should be > unrelated modifications to the code. Again, that?s something that primarily affects real users, when they find some function is no longer in the place where they expect it to be. You have to test with real users to find out what they think of this sort of thing. From ldo at geek-central.gen.new_zealand Wed Aug 11 00:52:52 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 16:52:52 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message , Grant Edwards wrote: > Automated GUI intended to uncover problems in the underlying program > functionality ... That ?underlying? functionality has nothing to do with the GUI, then. Why not test it directly, rather than go through the GUI? > Automated GUI testing often isn't even being used to test the program > whos GUI is being automated. It's often used to test _other_ programs > with which the GUI-automated-program interacts. Again, this sounds like it has nothing to do with the GUI per se. From ben+python at benfinney.id.au Wed Aug 11 01:00:52 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 11 Aug 2010 15:00:52 +1000 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <87sk2lyc8r.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > In message , Grant Edwards wrote: > > > Automated GUI intended to uncover problems in the underlying program > > functionality ... > > That ?underlying? functionality has nothing to do with the GUI, then. Why > not test it directly, rather than go through the GUI? Because that behaviour can be different when tested in a way that doesn't involve using the actual program's interface. The GUI is part of the program's behaviour, remember, and just about any non-trivial GUI program will have quite complex behaviour specifically in its GUI. Is the concept of testing the actual program behaviour really foreign to you? If not, what part of this concept is causing you difficulty? -- \ ?Two paradoxes are better than one; they may even suggest a | `\ solution.? ?Edward Teller | _o__) | Ben Finney From magguru.anilkumar at gmail.com Wed Aug 11 01:01:03 2010 From: magguru.anilkumar at gmail.com (devi) Date: Tue, 10 Aug 2010 22:01:03 -0700 (PDT) Subject: GERMANY GIRLS SECRET SEX VIDEOS Message-ID: <7417e5b8-ed18-45cf-8508-6648e1749ce2@l25g2000prn.googlegroups.com> GERMANY GIRLS SECRET SEX VIDEOS At http://simpletoget.co.cc Due to high sex content, i have hidden the videos in an image.in that website on right side below search box click on image and watch videos in all angles. From invalid at invalid.invalid Wed Aug 11 02:09:21 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 06:09:21 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message , Robert > Kern wrote: > >> On 2010-08-10 21:57 , Lawrence D'Oliveiro wrote: >> >>> In message >>> , Alex >>> Barna wrote: >>> >>>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>>> >>>>> Can???t understand the point to it. ???GUI automation??? is a contradiction >>>>> in terms, because a GUI is designed for use by humans to do manual >>>>> tasks, not ones that can be automated. >>>> >>>> Automating GUI is for testing. >>> >>> But the most egregious GUI problems are going to be with humans being >>> unable to figure out how to do something, am I right? >> >> Possibly, but it's not the *only* important problem. Automated GUI testing >> is usually a form of regression testing. You want to make sure that the >> behavior of parts of the GUI did not change when you made what should be >> unrelated modifications to the code. > > Again, that???s something that primarily affects real users, when they find > some function is no longer in the place where they expect it to be. Automated testing can detect when some function is no longer where it used to be. > You have to test with real users to find out what they think of this > sort of thing. Again, nobody's talking about using automated testing to figure out what users think. We're talking about using automated testing to make sure that rev 3.5 acts the same what that rev 3.4 did when you push button X or select menu option Y. -- Grant From invalid at invalid.invalid Wed Aug 11 02:12:49 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 06:12:49 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> Automated GUI intended to uncover problems in the underlying program >> functionality ... > > That ???underlying??? functionality has nothing to do with the GUI, > then. Why not test it directly, rather than go through the GUI? Because in many programs _there_is_no_other_way_to_test_it_directly_. Yes, that sucks. In the real world most programs suck. You've still got to test them. >> Automated GUI testing often isn't even being used to test the program >> whos GUI is being automated. It's often used to test _other_ programs >> with which the GUI-automated-program interacts. > > Again, this sounds like it has nothing to do with the GUI per se. Exactly! That's what we've been trying to explain. Automating a GUI isn't done to test how well the GUI works for real users. It's done mainly for two purposes: 1) Regression testing to make sure that the GUI's behavior (good, bad, or indifferent) hasn't changed since the previous revision. 2) To test the functionality underlying the GUI. From tjreedy at udel.edu Wed Aug 11 02:24:11 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Aug 2010 02:24:11 -0400 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: On 8/10/2010 8:08 PM, Roy Smith wrote: > In any case, if the candidate were to submit somebody else's work, it > would come out pretty quickly as we discussed their code. I suppose one > question I might ask would be, "Can you explain why, when I copy-paste > one of your comments into a google search box, your entire program > appears?" Mostly likely because I wrote the original... would be my answer. -- Terry Jan Reedy From eckhardt at satorlaser.com Wed Aug 11 02:40:40 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 11 Aug 2010 08:40:40 +0200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> <4C61E9A1.5090800@v.loewis.de> Message-ID: <88t9j7-ri5.ln1@satorlaser.homedns.org> Martin v. Loewis wrote: > Am 10.08.2010 09:06, schrieb Ulrich Eckhardt: >> When asked on the developers' list, it was said that this was >> intended for compatibility with C++, e.g. in cases where people >> want to embed Python into their C++ projects. Of course, this >> contradicts Christian's statement that C++ compatibility >> wasn't considered useful enough. > > It doesn't contradict at all. In order to embed Python into a C++ > application, it is sufficient if the Python header files can be compiled > with a C++ compiler, and linking to the C function works > properly - which is indeed the case. That's true, maybe I don't remember the exact rationale. Especially if even someone like you, who is much deeper into Python development, doesn't, I'm wondering if I'm misremembering something.... Cheers! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From ldo at geek-central.gen.new_zealand Wed Aug 11 02:50:15 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 18:50:15 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message , Grant Edwards wrote: > ... nobody's talking about using automated testing to figure out > what users think. That?s the trouble. What?s the point of a GUI, then? From girish.cfc at gmail.com Wed Aug 11 03:09:58 2010 From: girish.cfc at gmail.com (Girish) Date: Wed, 11 Aug 2010 00:09:58 -0700 (PDT) Subject: Access lotus notes using Python 2.5.1 Message-ID: Hello All, I am trying to send email using Lotos notes. When I run following commands to establish a COM connection, Python crashes with a error saying "Runtime Error.....Pythonwin.exe abnormal termination". import win32com.client session = win32com.client.Dispatch('Lotus.NotesSession') Any help is appreciated. Thanks, Girish From rNOSPAMon at flownet.com Wed Aug 11 03:11:43 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 00:11:43 -0700 Subject: Line-by-line processing when stdin is not a tty Message-ID: When stdin is not a tty, Python seems to buffer all the input through EOF before processing any of it: [ron at mickey:~]$ cat | python print 123 print 456 123 456 Is there a way to get Python to process input line-by-line the way it does when stdin is a TTY even when stdin is not a TTY? Thanks, rg From eric.brunel at pragmadev.com Wed Aug 11 03:24:46 2010 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 11 Aug 2010 09:24:46 +0200 Subject: File Manager in Tkinter References: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> <770366ta10gk98vgd5n2tapl7ag6skaeaj@4ax.com> Message-ID: In article <770366ta10gk98vgd5n2tapl7ag6skaeaj at 4ax.com>, John wrote: > My python is version 2.6.5. Would you recomend I upgrade and if yes > to which version? > > > from tkinter import ttk > > Traceback (most recent call last): > File "", line 1, in > from tkinter import ttk > ImportError: No module named tkinter On Python 2.x, the module is called Tkinter with an uppercase T. It has been changed to tkinter with a lowercase t in Python 3.x for naming consistency reasons. From ben+python at benfinney.id.au Wed Aug 11 03:27:40 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 11 Aug 2010 17:27:40 +1000 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <87ocd9y5g3.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > In message , Grant Edwards wrote: > > > ... nobody's talking about using automated testing to figure out > > what users think. > > That?s the trouble. What?s the point of a GUI, then? I've no idea what you're asking any more. The above response seems like a total non-sequitur. But the above exchange convinces me that you're asking it in the wrong forum. This no longer has anything at all to do with Python in particular. -- \ ?Books and opinions, no matter from whom they came, if they are | `\ in opposition to human rights, are nothing but dead letters.? | _o__) ?Ernestine Rose | Ben Finney From santiago.caracol at gmail.com Wed Aug 11 04:16:37 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Wed, 11 Aug 2010 01:16:37 -0700 (PDT) Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> <34b16983-ac50-49a0-a612-0c35d9bf6c6f@l14g2000yql.googlegroups.com> Message-ID: <97e1c46b-c657-4016-afa4-c2867edd5722@5g2000yqz.googlegroups.com> Peter, thanks again for all this code. You helped me a lot. > Didn't you say you weren't interested in the web specific aspects? I thought that, although my problem had to do with client-server stuff, it wasn't really web-specific. But now I think that that was part of my problem. I failed to see that using sessions could be the solution. Santiago From usernet at ilthio.net Wed Aug 11 04:38:48 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 08:38:48 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, RG wrote: > When stdin is not a tty, Python seems to buffer all the input through > EOF before processing any of it: > > [ron at mickey:~]$ cat | python > print 123 > print 456 > 123 > 456 > > Is there a way to get Python to process input line-by-line the way it > does when stdin is a TTY even when stdin is not a TTY? It would be much better to know the overall purpose of what you are trying to achieve. There are may be better ways (ie, sockets) depending what you are trying to do. Knowing your target platform would also be helpful. For the python interpeter itself, you can can get interactive behavior by invoking it with the -i option. If you want to handle stdin a single line at a time from inside of your program, you can access it using sys.stdin.readline(). From cs at zip.com.au Wed Aug 11 05:42:30 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 11 Aug 2010 19:42:30 +1000 Subject: Line-by-line processing when stdin is not a tty In-Reply-To: References: Message-ID: <20100811094230.GA21181@cskk.homeip.net> On 11Aug2010 00:11, RG wrote: | When stdin is not a tty, Python seems to buffer all the input through | EOF before processing any of it: | | [ron at mickey:~]$ cat | python | print 123 | print 456 | 123 | 456 | | Is there a way to get Python to process input line-by-line the way it | does when stdin is a TTY even when stdin is not a TTY? What you're seeing here is not python's behaviour but cat's behaviour. Almost all programs do line buffering (flush buffer at newline) when the file is a terminal (character device) and block buffering (flush when a fixed size buffer, typically 8192 bytes or some larger power of 2) when the file is not a terminal. This is default behaviour for the stdio package. So "cat" is simply not feeding any data to python until it has a lot of it; there is nothing python can do about that. We would need to know more about your specific task to suggest workarounds. Usually you either need an option on the upstream program to tell it to line buffer explicitly or you need to play silly games with pseudo terminals to convince the upstream program it is attached to a terminal. The latter is both ugly and generally inadvisable because many programs that change their buffering when attached to a terminal also change other behaviour, such as issuing interactiove prompts etc. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ The type syntax for C is essentially unparsable. - Rob Pike From jeanmichel at sequans.com Wed Aug 11 05:47:46 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 11 Aug 2010 11:47:46 +0200 Subject: GUI automation tool (windows) In-Reply-To: References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4C6271C2.4030008@sequans.com> Grant Edwards wrote: > On 2010-08-11, Lawrence D'Oliveiro wrote: > >> In message >> , Alex >> Barna wrote: >> >> >>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>> >>> >>>> Can???t understand the point to it. ???GUI automation??? is a contradiction in >>>> terms, because a GUI is designed for use by humans to do manual tasks, >>>> not ones that can be automated. >>>> >>> Automating GUI is for testing. >>> >> But the most egregious GUI problems are going to be with humans being >> unable to figure out how to do something, am I right? How are you >> going to uncover those problems, except by testing with real people? >> Automated testing isn???t going to do it. >> > > Automated GUI testing isn't intended to uncover those sorts of > problems in GUI design. Automated GUI intended to uncover problems in > the underlying program functionality, and is used mainly for > regression testing to insure that changes made to a program didn't > cause any unintended changes in program behavior. > > Automated GUI testing often isn't even being used to test the program > whos GUI is being automated. It's often used to test _other_ programs > with which the GUI-automated-program interacts. > > Yep, as an example, I worked on a cardio medical system (X ray). In order to get to the market, such system must prove its robustness, part of the proof was about chaining thousands of patients without a crash nor X ray failure. This is where GUI automation comes in. The tool was simulating the interaction between a doctor and the system application GUI and was working 24/7. JM From nikos.the.gr33k at gmail.com Wed Aug 11 05:48:22 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Wed, 11 Aug 2010 02:48:22 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> Message-ID: <206e6cef-3760-49a7-bb8a-c5d1fe3a4091@i31g2000yqm.googlegroups.com> On 10 ???, 18:12, MRAB wrote: > ????? wrote: > > [snip] > > > > > > > The ID number of each php page was contained in the old php code > > within this string > > > PageID = some_number > > > So instead of create a new ID number for eaqch page i have to pull out > > this number to store to the beginnign to the file as comment line, > > because it has direct relationship with the mysql database as in > > tracking the number of each webpage and finding the counter of it. > > > # Grab the PageID contained within the php code and store it in id > > variable > > id = re.search( 'PageID = ', src_data ) > > > How to tell Python to Grab that number after 'PageID = ' string and to > > store it in var id that a later use in the program? > > If the part of the file you're trying to match look like this: > > ? ? ?PageID = 12 > > then the regex should look like this: > > ? ? ?PageID = (\d+) > > and the code should look like this: > > ? ? ?page_id = re.search(r'PageID = (\d+)', src_data).group(1) > > The page_id will, of course, be a string. > Thank you very much for helping me with the syntax. > > also i made another changewould something like this work: > > > =============================== > > # open same php file for storing modified data > > print ( 'writing to %s' % dest_f ) > > f = open(src_f, 'w') > > f.write(src_data) > > f.close() > > > # rename edited .php file to .html extension > > dst_f = src_f.replace('.php', '.html') > > os.rename( src_f, dst_f ) > > =============================== > > > Because instead of creating a new .html file and inserting the desired > > data of the old php thus having two files(old php, and new html) i > > decided to open the same php file for writing that data and then > > rename it to html. > > Would the above code work? > > Why wouldn't it? I though i was perhaps did something wrong with the code. ========================================= for currdir, files, dirs in os.walk('d:\\test'): # neither 'd:/test' tracks the folder for f in files: if f.lower().endswith("php"): print currdir, files, dirs, f ========================================= As you advised me in a previous post of yours i need to find out why the converting code although works for a single file doesn't for some reason enter folders and subfolders to grab files form there to convert. So as you said i should comment all other statements to find out the culprit in the above lines. Well those lines are supposed to print current working folder and files but when i run the above code it gives me nothing in response, not even 'f'. So does that mean that os.walk() method cannot enter the windows 7 folders? * One more thing is that instead of trying to run the above script form 'cli' wouldn't it better to run it as a cgi script and see the results in the browser instead with the addition fo this line? print ( "Content-type: text/html; charset=UTF-8 \n" ) Or for some reason this has to be run from the shell to both local(windows 7) and remote hosting (linux) servers? From wolfgang at rohdewald.de Wed Aug 11 06:01:25 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Wed, 11 Aug 2010 12:01:25 +0200 Subject: Line-by-line processing when stdin is not a tty In-Reply-To: <20100811094230.GA21181@cskk.homeip.net> References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: <201008111201.25689.wolfgang@rohdewald.de> On Mittwoch 11 August 2010, Cameron Simpson wrote: > Usually you either > need an option on the upstream program to tell it to line > buffer explicitly once cat had an option -u doing exactly that but nowadays -u seems to be ignored http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html -- Wolfgang From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 06:20:20 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 10:20:20 GMT Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4c627964$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 18:50:15 +1200, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> ... nobody's talking about using automated testing to figure out what >> users think. > > That?s the trouble. What?s the point of a GUI, then? Are you trolling, or do you really fail to understand that the concepts of *testing a GUI's functionality* and *asking users what sort of interface they want* are independent concepts? Let's put it this way... "Nobody is talking about using automated testing to find out what command line switches users want on their command line tools." "That's the trouble. What's the point of a CLI, then?" Do you see the difference now? -- Steven From usernet at ilthio.net Wed Aug 11 06:32:41 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 10:32:41 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: On 2010-08-11, Wolfgang Rohdewald wrote: > On Mittwoch 11 August 2010, Cameron Simpson wrote: >> Usually you either >> need an option on the upstream program to tell it to line >> buffer explicitly > > once cat had an option -u doing exactly that but nowadays > -u seems to be ignored > > http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html I have to wonder why cat knows or cares. Since we are referring to a single directional pipe, there is no fear of creating any kind of race condition. In general, I would expect that the shell opens the pipe (pipe()), fork()s, closes its own 0 or 1 descriptor as appropriate for each child, copies (dup()) one the file descriptors to the appropriate file descriptor for the child process, and exec()s to call the new process. Neither of the processes, in general, needs to know anything other the to write and read from their given descriptors. From python.list at tim.thechases.com Wed Aug 11 06:50:44 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 11 Aug 2010 05:50:44 -0500 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: <4C628084.7080509@tim.thechases.com> On 08/11/10 01:24, Terry Reedy wrote: > On 8/10/2010 8:08 PM, Roy Smith wrote: >> In any case, if the candidate were to submit somebody else's >> work, it would come out pretty quickly as we discussed their >> code. I suppose one question I might ask would be, "Can you >> explain why, when I copy-paste one of your comments into a >> google search box, your entire program appears?" > > Mostly likely because I wrote the original... > > would be my answer. Unfortunately there are candidates who would give your answer but then have trouble with "Then why are the Last-Modified HTTP headers showing a date several months before our interview?" It's as bad as the phone-interviews I've done where in the background I can hear the person on the other end typing my questions into a search box and reading off answers. On the bright side, those are short interviews... ;-) -tkc From chris at simplistix.co.uk Wed Aug 11 07:13:29 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 11 Aug 2010 12:13:29 +0100 Subject: regex to remove lines made of only whitespace Message-ID: <4C6285D9.8080000@simplistix.co.uk> Hi All, I'm looking for a regex (or other solution, as long as it's quick!) that could be used to strip out lines made up entirely of whitespace. eg: 'x\n \t \n\ny' -> 'x\ny' Does anyone have one handy? cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From andreas.tawn at ubisoft.com Wed Aug 11 07:21:10 2010 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 11 Aug 2010 13:21:10 +0200 Subject: regex to remove lines made of only whitespace In-Reply-To: <4C6285D9.8080000@simplistix.co.uk> References: <4C6285D9.8080000@simplistix.co.uk> Message-ID: <654D9D97DA51AD479973BC2D5578603C06C254BE12@PDC-MAIL-CMS01.ubisoft.org> > Hi All, > > I'm looking for a regex (or other solution, as long as it's quick!) > that > could be used to strip out lines made up entirely of whitespace. > > eg: > > 'x\n \t \n\ny' -> 'x\ny' > > Does anyone have one handy? > > cheers, > > Chris for line in lines: if not line.strip(): continue doStuff(line) cheers, Drea From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 07:27:49 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 11:27:49 GMT Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4c628934$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 06:12:49 +0000, Grant Edwards wrote: > Automating a GUI > isn't done to test how well the GUI works for real users. Or to put it another way... automated tests aren't useful for usability testing, regardless of whether one is testing a GUI app or a CLI app. > It's done mainly for two purposes: > > 1) Regression testing to make sure that the GUI's behavior (good, > bad, or indifferent) hasn't changed since the previous revision. > > 2) To test the functionality underlying the GUI. I would like to point out that automating GUIs isn't just done for testing purposes, but has other reasons as well. Probably the most common is for the same reason any automation is done, be it writing a script or building a robot: to reduce the amount of manual effort needed to do some repetitive or frequent task. Mouse and keyboard event recording software used to be one of the killer apps for power users back in the days of classic Apple Mac and early versions of Windows. I'm not entirely sure why they've faded away... it seems to have left an empty niche, for power users who aren't comfortable writing shell scripts, batch files or messing about with DBUS, but still want to automate repetitive tasks. Another common use is automating interactions with web sites via mechanize. -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 07:31:44 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 11:31:44 GMT Subject: regex to remove lines made of only whitespace References: Message-ID: <4c628a1f$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 12:13:29 +0100, Chris Withers wrote: > Hi All, > > I'm looking for a regex (or other solution, as long as it's quick!) that > could be used to strip out lines made up entirely of whitespace. def strip_blank_lines(lines): for line in lines: if not line.isspace(): yield line text = ''.join(strip_blank_lines(lines.split('\n'))) -- Steven From python.list at tim.thechases.com Wed Aug 11 07:33:15 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 11 Aug 2010 06:33:15 -0500 Subject: regex to remove lines made of only whitespace In-Reply-To: <654D9D97DA51AD479973BC2D5578603C06C254BE12@PDC-MAIL-CMS01.ubisoft.org> References: <4C6285D9.8080000@simplistix.co.uk> <654D9D97DA51AD479973BC2D5578603C06C254BE12@PDC-MAIL-CMS01.ubisoft.org> Message-ID: <4C628A7B.7060207@tim.thechases.com> On 08/11/10 06:21, Andreas Tawn wrote: >> I'm looking for a regex (or other solution, as long as it's quick!) >> that could be used to strip out lines made up entirely of whitespace. >> >> eg: >> >> 'x\n \t \n\ny' -> 'x\ny' > > for line in lines: > if not line.strip(): > continue > doStuff(line) Note that the OP's input and output were a single string. Perhaps something like >>> s = 'x\n \t \n\ny' >>> '\n'.join(line for line in s.splitlines() if line.strip()) 'x\ny' which, IMHO, has much greater clarity than any regexp with the added bonus of fewer regexp edge-cases (blanks at the beginning/middle/end of the text). -tkc From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 07:34:51 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 11:34:51 GMT Subject: type enforcement in _ssl.sslwrap References: <38664845-c34d-452e-a09c-3206383e90e3@s17g2000prh.googlegroups.com> Message-ID: <4c628adb$0$11101$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 10:40:54 -0700, Eric Snow wrote: > ssl.SSLSocket.__init__ makes a call to _ssl.sslwrap (in the C module). > That in turn makes a call to PyArg_ParseTuple, which casts the first arg > of _ssl.sslwrap into a PySocketModule.Sock_Type object. > > My problem is that I am trying to pass in an object that implements the > Socket interface, but does not inherit from _socket.socket, like you do > with file-like objects. Is there a way to make this work, or is the > PyArg_ParseTuple call going to stop me. I don't know. What happens when you try it? -- Steven From andreas.tawn at ubisoft.com Wed Aug 11 07:39:27 2010 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 11 Aug 2010 13:39:27 +0200 Subject: regex to remove lines made of only whitespace In-Reply-To: <4C628A7B.7060207@tim.thechases.com> References: <4C6285D9.8080000@simplistix.co.uk> <654D9D97DA51AD479973BC2D5578603C06C254BE12@PDC-MAIL-CMS01.ubisoft.org> <4C628A7B.7060207@tim.thechases.com> Message-ID: <654D9D97DA51AD479973BC2D5578603C06C254BE47@PDC-MAIL-CMS01.ubisoft.org> > On 08/11/10 06:21, Andreas Tawn wrote: > >> I'm looking for a regex (or other solution, as long as it's quick!) > >> that could be used to strip out lines made up entirely of > whitespace. > >> > >> eg: > >> > >> 'x\n \t \n\ny' -> 'x\ny' > > > > for line in lines: > > if not line.strip(): > > continue > > doStuff(line) > > Note that the OP's input and output were a single string. Ah, indeed. What do they say about the first part of assume? > Perhaps something like > >>> s = 'x\n \t \n\ny' > >>> '\n'.join(line for line in s.splitlines() if line.strip()) > 'x\ny' > > which, IMHO, has much greater clarity than any regexp with the > added bonus of fewer regexp edge-cases (blanks at the > beginning/middle/end of the text). > > -tkc This what I meant (no really) ;o). Cheers, Drea From enleverLesX_XXmcX at XmclavXeauX.com.invalid Wed Aug 11 07:44:22 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Wed, 11 Aug 2010 13:44:22 +0200 Subject: Access lotus notes using Python 2.5.1 References: Message-ID: <4c628d1b$0$5407$ba4acef3@reader.news.orange.fr> Hi! In several cases, Notes is not registred as COM server. Depending of installation. @-salutations -- MCi From sushma.konanki at gmail.com Wed Aug 11 08:09:01 2010 From: sushma.konanki at gmail.com (sushma) Date: Wed, 11 Aug 2010 05:09:01 -0700 (PDT) Subject: urgent requirement at Hyderabad Message-ID: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Hi, We are looking for Python Developers/programmers with 1+ years of experience. Send resume to sushmak at millenniumsoft.com Regards, Sushma. From stefan_ml at behnel.de Wed Aug 11 08:17:00 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 11 Aug 2010 14:17:00 +0200 Subject: urgent requirement at Hyderabad In-Reply-To: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Message-ID: In case anyone wondered: Hyderabad is likely referring to some place in Asia: http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29 Stefan From cs at zip.com.au Wed Aug 11 08:18:58 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 11 Aug 2010 22:18:58 +1000 Subject: Line-by-line processing when stdin is not a tty In-Reply-To: References: Message-ID: <20100811121858.GA5495@cskk.homeip.net> On 11Aug2010 10:32, Tim Harig wrote: | On 2010-08-11, Wolfgang Rohdewald wrote: | > On Mittwoch 11 August 2010, Cameron Simpson wrote: | >> Usually you either | >> need an option on the upstream program to tell it to line | >> buffer explicitly | > | > once cat had an option -u doing exactly that but nowadays | > -u seems to be ignored | > | > http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html | | I have to wonder why cat knows or cares. Since we are referring to | a single directional pipe, there is no fear of creating any kind of | race condition. In general, I would expect that the shell opens the | pipe (pipe()), fork()s, closes its own 0 or 1 descriptor as appropriate | for each child, copies (dup()) one the file descriptors to the | appropriate file descriptor for the child process, and exec()s to call | the new process. Neither of the processes, in general, needs to know | anything other the to write and read from their given descriptors. The buffering is a performance choice. Every write requires a context switch from userspace to kernel space, and availability of data in the pipe will wake up a downstream process blocked trying to read. It is far more efficient to do as few such copies as possible, so where interaction (as you point out) is one way it's usually better to write data in larger chunks. But when writing to a terminal, ostensibly for a human to read, line buffering is generally better (for exactly the issue the OP tripped over - humans expect stuff to happen as it occurs). -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ From benadictraj123 at gmail.com Wed Aug 11 08:23:46 2010 From: benadictraj123 at gmail.com (benadict raj) Date: Wed, 11 Aug 2010 05:23:46 -0700 (PDT) Subject: GET PAID FOR WORKING ONLINE $100 ON YOUR FIRST DAY Message-ID: GET PAID FOR WORKING ONLINE $100 ON YOUR FIRST DAY Just Re-launched! ClickMasterPro network Learn how to make money from your home using your website Just join this network and Learn the secrets of how to make 1000's of $$$$ by bringing visitors to your free link or website No investment free to join GREAT OFFER $1 PER REFERRAL if you bring 100 friends to this network you can earn $100 on your first day. I get paid through paypal or alertpay To join this network use the below link http://www.clickmasterpro.com/?rid=2662 Awesome earnings getpaid for your real effort form your home From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 08:34:09 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 12:34:09 GMT Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> Message-ID: <4c6298c1$0$11101$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 16:44:17 -0400, J Kenneth King wrote: > Fizzbuzz is annoying in interviews. It's not for the benefit of the interviewee, but for the interviewer. > I've never worked at a job where I was under a timer while a group of > people sat across from me and scrutinized everything I was doing. > > I don't see how it can honestly tell you anything useful about the > person you're interviewing either. Do you really think that what you > assume about the interviewee based on characteristics you can infer from > their solution to be really, honestly true? They might even completely > bomb the solution and still be a brilliant programmer, but you'll never > know that if you trust this simple "fizzbuzz" test. I think you've missed the point of the FizzBuzz test. Nobody should judge your skill as a programmer from whether you can write FizzBuzz in 3 minutes during an interview. The test is to weed out the people who aren't programmers at all, but think they can bluff their way into a programming job. Sounds ridiculous, but apparently there are vast hordes of people who can barely program "Hello World" applying for programming jobs. One figure bandied about -- how accurately, I don't know -- is 199 out of every 200 job applicants for programming jobs are barely capable of writing a line of code. http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html Fizz Buzz and similar tests aim to weed them out, *quickly*, so you can spend more time interviewing people who actually are programmers. I personally know somebody who got his start as a professional programmer through pure bluff. He had read up just enough about the language to be able to toss in the odd buzzword, his CV was a masterpiece of imagination, and he was applying for a job during the Y2K panic when companies would hire anyone who could spell COBOL correctly by the third attempt. The other reason for starting with something like the Fizz Buzz test is precisely to see how the interviewee will react. Do they ask for clarification if the question is underspecified? That tells you they're smart enough to *notice* when something is underspecified, and confident enough to raise the issue in an interview. That's 100 bonus points right there. Do they go to pieces? That tells you they don't perform well under pressure. Do they argue with you that the question is pointless? That tells you that they're very confident, and quite likely arrogant enough not to worry about offending a potential employer (and maybe even deservedly so). This means they are potentially difficult to deal with. That doesn't mean you don't hire them: some people are so good that they deserve to be prima donna. But if you're not looking for a prima donna, then it's better to find out early, so you don't waste either your time or the other guy's. > I've been in those interviews on both sides of the table. Neither side > was a good experience. > > If a test is necessary, make it a take-home or demand source code if > they have it. Read their code and judge for yourself the quality of > their work. Getting interviewees to do a take-home problem just means you hire the guy who is friends with a good programmer, rather than the good programmer. > Any questions in an interview should be the usual "get to know you" type > stuff. "What was the most difficult challenge you've faced on the job? > How did you respond?" That sort of thing. I *hate* those questions. For many people, the honest answer would be "Nothing I've ever done in my job has been even half as difficult as getting through the interview, because I'm bad at selling myself", but if you say that, it just sounds like you're trying to bullshit your way through the interview. -- Steven From usernet at ilthio.net Wed Aug 11 08:35:08 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 12:35:08 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, Cameron Simpson wrote: > On 11Aug2010 10:32, Tim Harig wrote: >| On 2010-08-11, Wolfgang Rohdewald wrote: >| > On Mittwoch 11 August 2010, Cameron Simpson wrote: >| >> Usually you either >| >> need an option on the upstream program to tell it to line >| >> buffer explicitly >| > >| > once cat had an option -u doing exactly that but nowadays >| > -u seems to be ignored >| > >| > http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html >| >| I have to wonder why cat knows or cares. Since we are referring to >| a single directional pipe, there is no fear of creating any kind of >| race condition. In general, I would expect that the shell opens the >| pipe (pipe()), fork()s, closes its own 0 or 1 descriptor as appropriate >| for each child, copies (dup()) one the file descriptors to the >| appropriate file descriptor for the child process, and exec()s to call >| the new process. Neither of the processes, in general, needs to know >| anything other the to write and read from their given descriptors. > > The buffering is a performance choice. Every write requires a context > switch from userspace to kernel space, and availability of data in the > pipe will wake up a downstream process blocked trying to read. > > It is far more efficient to do as few such copies as possible, so where > interaction (as you point out) is one way it's usually better to write > data in larger chunks. But when writing to a terminal, ostensibly for a > human to read, line buffering is generally better (for exactly the issue > the OP tripped over - humans expect stuff to happen as it occurs). Right, I don't question the optimization. I question whether the intelligence that performes that optimation should be placed within cat or whether it should be placed within the shell. It seems to me that the shell has a better idea of how the command is being used and can therefore make a better decision about whether or not buffering is appropriate. From usernet at ilthio.net Wed Aug 11 08:57:38 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 12:57:38 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c628934$0$11101$c3e8da3@news.astraweb.com> Message-ID: On 2010-08-11, Steven D'Aprano wrote: > Mouse and keyboard event recording software used to be one of the killer > apps for power users back in the days of classic Apple Mac and early > versions of Windows. I'm not entirely sure why they've faded away... it It faided away because automation based on on mouse clicks, and to a lesser extent key injection, is very fragile. GUIs are subject to changing in ways that are unpredictable and difficult to detect. Some GUI widget sets provide some programatic way to access the GUI items directly for testing and debugging purposes; but, that isn't always available in the final product. > Another common use is automating interactions with web sites via > mechanize. There are better ways of automating web site interactions. You can other generate the GETS and POSTS directly or you can use import the browsers through COM/XPCOM and manipulate the pages using the browser's DOM object. From roy at panix.com Wed Aug 11 09:04:09 2010 From: roy at panix.com (Roy Smith) Date: Wed, 11 Aug 2010 09:04:09 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <4c6298c1$0$11101$c3e8da3@news.astraweb.com> Message-ID: In article <4c6298c1$0$11101$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > Sounds ridiculous, but apparently there are vast hordes of people who can > barely program "Hello World" applying for programming jobs. One figure > bandied about -- how accurately, I don't know -- is 199 out of every 200 > job applicants for programming jobs are barely capable of writing a line > of code. By the same token, there are lots of people with advanced degrees in computer science who can't code their way out of a paper bag. One advantage of the take-home test is that you can prepare the test once and amortize the preparation cost over many applicants. It's a big investment of time to interview somebody. By the time I get up to investing an hour or so of my time on a phone screen, I'd like to weed out the obvious rejects as cheaply as possible. Even more interesting is to publish some problems on your web site and instruct applicants to submit a solution to one of them along with their resume. This makes the per-applicant cost to administer the exam essentially zero. It also has the nice side-effect of weeding out the resume spammers. To be honest, I've never done this, but I've seen companies that do. I may try it sometime. I still want to see the candidate write some code during the interview. This gives me a chance to feed them a problem incrementally and see where they take it. From ben+python at benfinney.id.au Wed Aug 11 09:35:18 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 11 Aug 2010 23:35:18 +1000 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: <877hjxxofd.fsf@benfinney.id.au> Tim Chase writes: > Unfortunately there are candidates who would give your answer but then > have trouble with "Then why are the Last-Modified HTTP headers showing > a date several months before our interview?" My response: ?Ha! That's a trick question; ?Last-Modified? is a field in the header, not a header itself?. That might lead to the ?why are you interested in leaving your current position? question rather precipitously, though. -- \ ?Courage is not the absence of fear, but the decision that | `\ something else is more important than fear.? ?Ambrose Redmoon | _o__) | Ben Finney From sturlamolden at yahoo.no Wed Aug 11 09:44:14 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 11 Aug 2010 06:44:14 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> <4C61E9A1.5090800@v.loewis.de> <88t9j7-ri5.ln1@satorlaser.homedns.org> Message-ID: <44d30ac7-931e-4eb0-9aed-f664c872d438@l20g2000yqm.googlegroups.com> On 11 Aug, 08:40, Ulrich Eckhardt wrote: > That's true, maybe I don't remember the exact rationale. Especially if even > someone like you, who is much deeper into Python development, doesn't, I'm > wondering if I'm misremembering something.... Header (definition) and source (implementation) is not the same. A C++ compiler can use Python's header files and link with Python's C API correctly. But it cannot compile Python's C source code. A C compiler is required to compile and build Python. From invalid at invalid.invalid Wed Aug 11 10:09:45 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 14:09:45 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> ... nobody's talking about using automated testing to figure out >> what users think. > > That???s the trouble. What???s the point of a GUI, then? OK, now you're just trolling. -- Grant Edwards grant.b.edwards Yow! I guess you guys got at BIG MUSCLES from doing too gmail.com much STUDYING! From invalid at invalid.invalid Wed Aug 11 10:13:09 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 14:13:09 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, Tim Harig wrote: > On 2010-08-11, RG wrote: >> When stdin is not a tty, Python seems to buffer all the input through >> EOF before processing any of it: >> >> [ron at mickey:~]$ cat | python >> print 123 >> print 456 >> 123 >> 456 >> >> Is there a way to get Python to process input line-by-line the way it >> does when stdin is a TTY even when stdin is not a TTY? > > It would be much better to know the overall purpose of what you are trying > to achieve. There are may be better ways (ie, sockets) depending what you > are trying to do. Knowing your target platform would also be helpful. > > For the python interpeter itself, you can can get interactive behavior by > invoking it with the -i option. If you're talking about unbuffered stdin/stdout, the option is -u. I don't really see how the -i option is relevent -- it causes the interpreter to go into interactive mode after running the script. > If you want to handle stdin a single line at a time from inside of your > program, you can access it using sys.stdin.readline(). That doesn't have any effect on stdin buffering. -- Grant Edwards grant.b.edwards Yow! ... I want to perform at cranial activities with gmail.com Tuesday Weld!! From __peter__ at web.de Wed Aug 11 10:49:03 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Aug 2010 16:49:03 +0200 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: Grant Edwards wrote: > On 2010-08-11, Tim Harig wrote: >> On 2010-08-11, RG wrote: >>> When stdin is not a tty, Python seems to buffer all the input through >>> EOF before processing any of it: >>> >>> [ron at mickey:~]$ cat | python >>> print 123 >>> print 456 >>> 123 >>> 456 >>> >>> Is there a way to get Python to process input line-by-line the way it >>> does when stdin is a TTY even when stdin is not a TTY? >> >> It would be much better to know the overall purpose of what you are >> trying >> to achieve. There are may be better ways (ie, sockets) depending what >> you >> are trying to do. Knowing your target platform would also be helpful. >> >> For the python interpeter itself, you can can get interactive behavior by >> invoking it with the -i option. > > If you're talking about unbuffered stdin/stdout, the option is -u. > > I don't really see how the -i option is relevent -- it causes the > interpreter to go into interactive mode after running the script. I'd say the following looks like what the OP was asking for: $ cat | python -i -c'import sys; sys.ps1=""' print sys.stdin.isatty() False print 1 1 print 2 2 (Whether it's useful is yet another question) >> If you want to handle stdin a single line at a time from inside of your >> program, you can access it using sys.stdin.readline(). > > That doesn't have any effect on stdin buffering. "for line in stream"-style file iteration uses an internal buffer that is not affected by the -u option; stream.readline() doesnt use this optimization. Peter From phd at phd.pp.ru Wed Aug 11 10:59:33 2010 From: phd at phd.pp.ru (Oleg Broytman) Date: Wed, 11 Aug 2010 18:59:33 +0400 Subject: SQLObject 0.13.0 Message-ID: <20100811145933.GB20946@phd.pp.ru> Hello! I'm pleased to announce version 0.13.0, the first stable release of branch 0.13 of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.13.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.12 --------------- Features & Interface -------------------- * SQLObject instances that don't have a per-instance connection can be pickled and unpickled. * Validators became stricter: StringCol and UnicodeCol now accept only str, unicode or an instance of a class that implements __unicode__ (but not __str__ because every object has a __str__ method); BoolCol accepts only bool or int or an instance of a class that implements __nonzero__; IntCol accepts int, long or an instance of a class that implements __int__ or __long__; FloatCol accepts float, int, long or an instance of a class that implements __float__, __int__ or __long__. * Added a connection class for rdbhost.com (commercial Postgres-over-Web service). Small Features -------------- * Added TimedeltaCol; currently it's only implemented on PostgreSQL as an INTERVAL type. * Do not pollute the base sqlmeta class to allow Style to set idName. In the case of inherited idName inherited value takes precedence; to allow Style to set idName reset inherited idName to None. * Better handling of circular dependencies in sqlobject-admin - do not include the class in the list of other classes. * Renamed db_encoding to dbEncoding in UnicodeStringValidator. * A new parameter 'sslmode' was added to PostgresConnection. * Removed SQLValidator - its attemptConvert was never called because in FormEncode it's named attempt_convert. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytman http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From invalid at invalid.invalid Wed Aug 11 11:01:12 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 15:01:12 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, Peter Otten <__peter__ at web.de> wrote: > Grant Edwards wrote: >>> If you want to handle stdin a single line at a time from inside of >>> your program, you can access it using sys.stdin.readline(). >> >> That doesn't have any effect on stdin buffering. > > "for line in stream"-style file iteration uses an internal buffer that is > not affected by the -u option; stream.readline() doesnt use this > optimization. You're right. Why didn't I know that? Using "for line in sys.stdin" does it's own buffering. In my tests using sys.stdin.readline() worked as the OP desired either with or without -u, either with or without cat. IOW, "cat" isn't buffering output on my system (or if it is, it's line-buffering). -- Grant Edwards grant.b.edwards Yow! I don't know WHY I at said that ... I think it gmail.com came from the FILLINGS in my rear molars ... From badouglas at gmail.com Wed Aug 11 11:08:21 2010 From: badouglas at gmail.com (bruce) Date: Wed, 11 Aug 2010 08:08:21 -0700 Subject: mysqldb - parameter issue Message-ID: hi... using python v2.6, using the mysqldb lib the test tbl looks like: DROP TABLE IF EXISTS `functionError_TBL`; CREATE TABLE `functionError_TBL` ( `parentFunction` varchar(100) NOT NULL default '', `currentFunction` varchar(100) NOT NULL default '', `parentFunctionID` int(10) NOT NULL default 0, `errorStatus` int(1) NOT NULL default 0, `clientServerUUID` varchar(100) NOT NULL default '', `processTime` timestamp NOT NULL default 0, `CollegeID` int(10) NOT NULL default 0, `CrawlID` varchar(200) NOT NULL default '', `CollegeName` varchar(200) NOT NULL default '', `CollegeAbbrv` varchar(200) NOT NULL default '', . . the test script looks like . . tlist= [(1, 1, 1281502771)] ins="insert into functionError_TBL " ins=ins+"(errorStatus, CollegeID, processTime)" ins=ins+" values " ins=ins+" (%s,%s, from_unixtime(%s))" db.executemany (ins, tlist) if the parameter is : (%s,%s, from_unixtime(%s))" it appears to work, data is inserted correctly... if the parameters are changed to (%s,from_unixtime(%s), %s)" along with the corresponding insert portion, and the test list, an error is generated.. this implies that something is going on with the use of the "from_unixtime" that i don't fully understand.. thoughts/pointers/comments... thanks thoughts on how to resolve this would be greatly appreciated. thanks From backgoodoo at gmail.com Wed Aug 11 11:09:50 2010 From: backgoodoo at gmail.com (Back9) Date: Wed, 11 Aug 2010 08:09:50 -0700 (PDT) Subject: How to swallow traceback message Message-ID: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Hi, I run my py app to display a file's contents, and it is normally very long. So I use it like below: python myapp.py input_file | more to see them step by step. But when I try to exit it, normally I use Ctrl+ C key to quit it. Problem is every time I do like it, it shows Traceback message and it makes my app not professional. How do I handle it gracefully. TIA From usernet at ilthio.net Wed Aug 11 11:19:03 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 15:19:03 +0000 (UTC) Subject: How to swallow traceback message References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: On 2010-08-11, Back9 wrote: > python myapp.py input_file | more > to see them step by step. > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > Problem is every time I do like it, it shows Traceback message and it > makes my app not professional. You have three options. 1. Exit more properly. 2. Catch and handle SIGINT yourself. 3. Wrap whatever section of your program is being interrupted in try/except to catch the KeyboardInterrupt exception when it is generated. From chris at simplistix.co.uk Wed Aug 11 11:21:20 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 11 Aug 2010 16:21:20 +0100 Subject: urgent requirement at Hyderabad In-Reply-To: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Message-ID: <4C62BFF0.4000504@simplistix.co.uk> sushma wrote: > We are looking for Python Developers/programmers with 1+ years of > experience. Send resume to sushmak at millenniumsoft.com So urgent you can't even be bothered to describe the job or post the advert in the correct place on the python job board. Good luck with that ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From eknath.iyer at gmail.com Wed Aug 11 11:24:36 2010 From: eknath.iyer at gmail.com (Eknath Venkataramani) Date: Wed, 11 Aug 2010 11:24:36 -0400 Subject: How to swallow traceback message In-Reply-To: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: See Exception Handling On Wed, Aug 11, 2010 at 11:09 AM, Back9 wrote: > Hi, > > I run my py app to display a file's contents, and it is normally very > long. > So I use it like below: > > python myapp.py input_file | more > to see them step by step. > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > Problem is every time I do like it, it shows Traceback message and it > makes my app not professional. > > How do I handle it gracefully. > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > -- Eknath Venkataramani -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Wed Aug 11 11:30:01 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 11 Aug 2010 17:30:01 +0200 Subject: How to swallow traceback message In-Reply-To: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: <4C62C1F9.40508@sequans.com> Back9 wrote: > Hi, > > I run my py app to display a file's contents, and it is normally very > long. > So I use it like below: > > python myapp.py input_file | more > to see them step by step. > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > Problem is every time I do like it, it shows Traceback message and it > makes my app not professional. > > How do I handle it gracefully. > > TIA > if __name__ == '__main__': try: main() except KeyboardInterrupt: print 'Hey ! this is a professional application' Cheers, JM From backgoodoo at gmail.com Wed Aug 11 11:32:19 2010 From: backgoodoo at gmail.com (Back9) Date: Wed, 11 Aug 2010 08:32:19 -0700 (PDT) Subject: How to swallow traceback message References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: On Aug 11, 11:19?am, Tim Harig wrote: > On 2010-08-11, Back9 wrote: > > > python myapp.py input_file | more > > to see them step by step. > > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > > Problem is every time I do like it, it shows Traceback message and it > > makes my app not professional. > > You have three options. > > ? ? ? ? 1. Exit more properly. > > ? ? ? ? 2. Catch and handle SIGINT yourself. > > ? ? ? ? 3. Wrap whatever section of your program is being interrupted in > ? ? ? ? ? ? ? ? try/except to catch the KeyboardInterrupt exception when it > ? ? ? ? ? ? ? ? is generated. I should have mentioned that I already use try/except KeyboardInterrupt statement. But it does not seem to work as I expected. TIA From torriem at gmail.com Wed Aug 11 12:02:14 2010 From: torriem at gmail.com (Michael Torrie) Date: Wed, 11 Aug 2010 10:02:14 -0600 Subject: How to swallow traceback message In-Reply-To: References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: <4C62C986.5030900@gmail.com> On 08/11/2010 09:32 AM, Back9 wrote: > I should have mentioned that I already use try/except > KeyboardInterrupt statement. > But it does not seem to work as I expected. If you want anyone to help further, you will need to say a) what you are expecting it to do and b) what it is actually doing. From chris at simplistix.co.uk Wed Aug 11 12:04:12 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 11 Aug 2010 17:04:12 +0100 Subject: regex to remove lines made of only whitespace In-Reply-To: <4c628a1f$0$11101$c3e8da3@news.astraweb.com> References: <4c628a1f$0$11101$c3e8da3@news.astraweb.com> Message-ID: <4C62C9FC.3010307@simplistix.co.uk> Steven D'Aprano wrote: > def strip_blank_lines(lines): > for line in lines: > if not line.isspace(): > yield line > > text = ''.join(strip_blank_lines(lines.split('\n'))) The final version I have is: def strip_blank_lines(text): result = [] for line in text.split('\n'): if line and not line.isspace(): result.append(line) return '\n'.join(result) Any improvements would be very welcome! Chris From fuglyducky at gmail.com Wed Aug 11 12:07:16 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Wed, 11 Aug 2010 09:07:16 -0700 (PDT) Subject: Confused: Newbie Function Calls Message-ID: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> I am a complete newbie to Python (and programming in general) and I have no idea what I'm missing. Below is a script that I am trying to work with and I cannot get it to work. When I call the final print function, nothing prints. However, if I print within the individual functions, I get the appropriate printout. Am I missing something??? Thanks in advance!!!! ################################################ # Global variable sample_string = "" def gen_header(sample_string): HEADER = """ mymultilinestringhere """ sample_string += HEADER return sample_string def gen_nia(sample_string): NIA = """ anothermultilinestringhere """ sample_string += NIA return sample_string gen_header(sample_string) gen_nia(sample_string) print(sample_string) From esnow at verio.net Wed Aug 11 12:12:06 2010 From: esnow at verio.net (Eric Snow) Date: Wed, 11 Aug 2010 09:12:06 -0700 (PDT) Subject: type enforcement in _ssl.sslwrap References: <38664845-c34d-452e-a09c-3206383e90e3@s17g2000prh.googlegroups.com> <4c628adb$0$11101$c3e8da3@news.astraweb.com> Message-ID: On Aug 11, 5:34?am, Steven D'Aprano wrote: > On Tue, 10 Aug 2010 10:40:54 -0700, Eric Snow wrote: > > ssl.SSLSocket.__init__ makes a call to _ssl.sslwrap (in the C module). > > That in turn makes a call to PyArg_ParseTuple, which casts the first arg > > of _ssl.sslwrap into a PySocketModule.Sock_Type object. > > > My problem is that I am trying to pass in an object that implements the > > Socket interface, but does not inherit from _socket.socket, like you do > > with file-like objects. ?Is there a way to make this work, or is the > > PyArg_ParseTuple call going to stop me. > > I don't know. What happens when you try it? > > -- > Steven When I pass my socket object in to ssl.wrap_socket I get the following exception: Traceback (most recent call last): File "", line 1, in ... File "/usr/local/lib/python2.7/ssl.py", line 342, in wrap_socket ciphers=ciphers) File "/usr/local/lib/python2.7/ssl.py", line 119, in __init__ ciphers) TypeError: must be _socket.socket, not ClientSocket I looked at what is going on there and found the call to _ssl.sslwrap. I tracked it down in the C source and found the call to PyArg_ParseTuple. -eric From suranap at gmail.com Wed Aug 11 12:21:34 2010 From: suranap at gmail.com (Pinku Surana) Date: Wed, 11 Aug 2010 09:21:34 -0700 (PDT) Subject: Is ElementTree development still active? Message-ID: <8b9ee78d-746e-4bb3-aef7-932ad2028650@x21g2000yqa.googlegroups.com> I checked the svn repo at effbot.org, but it appears to have no updates since 2007. Has development moved elsewhere? Thanks. From torriem at gmail.com Wed Aug 11 12:30:59 2010 From: torriem at gmail.com (Michael Torrie) Date: Wed, 11 Aug 2010 10:30:59 -0600 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: <4C62D043.9030200@gmail.com> On 08/11/2010 10:07 AM, fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! Yes. You are passing sample_string into the functions, but not doing anything with the return value. > def gen_header(sample_string): ^^^^^^^^^^^^^^^ The sample_string name is rebound to the parameter now, completely hiding the global variable, if that's really what you wanted. > def gen_nia(sample_string): ^^^^^^^^^^^^^^^^^^^ Again. > NIA = """ > anothermultilinestringhere > """ > > sample_string += NIA > return sample_string > > > gen_header(sample_string) > gen_nia(sample_string) Try this: sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) You could drop the arguments to your functions and use the "global" keyword to get access to sample_string from within the functions, but normally that's a bad idea. From the_mineo at web.de Wed Aug 11 12:31:39 2010 From: the_mineo at web.de (Wieland Hoffmann) Date: Wed, 11 Aug 2010 18:31:39 +0200 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: On 11.08.2010 18:07, fuglyducky wrote: > Am I missing something??? Thanks in advance!!!! Assign the returned value of your functions to something (like sample_string) and it will work: > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > HEADER = """ > mymultilinestringhere > """ > > sample_string += HEADER > return sample_string > > def gen_nia(sample_string): > NIA = """ > anothermultilinestringhere > """ > > sample_string += NIA > return sample_string > > > sample_string = gen_header(sample_string) > sample_string = gen_nia(sample_string) > > print(sample_string) From suranap at gmail.com Wed Aug 11 12:31:50 2010 From: suranap at gmail.com (Pinku Surana) Date: Wed, 11 Aug 2010 09:31:50 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> On Aug 11, 12:07?pm, fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! > > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > ? ? HEADER = """ > ? ? mymultilinestringhere > ? ? """ > > ? ? sample_string += HEADER > ? ? return sample_string > > def gen_nia(sample_string): > ? ? NIA = """ > ? ? anothermultilinestringhere > ? ? """ > > ? ? sample_string += NIA > ? ? return sample_string > > gen_header(sample_string) > gen_nia(sample_string) > > print(sample_string) There are 2 problems with your program. (1) If you want to use a global variable in a function, you have to add the line "global sample_string" to the beginning of that function. (2) Once you do (1), you will get an error because you've got sample_string as a global and a function parameter. Which one do you want to use in the function? You should change the name of the parameter to "sample" to solve that confusion. Here's the result, which works for me: sample_string = "" def gen_header(sample): global sample_string HEADER = """ mymultilinestringhere """ sample_string = sample + HEADER return sample_string def gen_nia(sample): global sample_string NIA = """ anothermultilinestringhere """ sample_string = sample + NIA return sample_string gen_header(sample_string) gen_nia(sample_string) print(sample_string) From robert.kern at gmail.com Wed Aug 11 12:33:56 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Aug 2010 11:33:56 -0500 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: On 8/11/10 11:07 AM, fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! > > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > HEADER = """ > mymultilinestringhere > """ > > sample_string += HEADER > return sample_string By default, all assignments inside of a function are local to the function. Even augmented assignments like +=. Python strings are immutable, so sample_string += HEADER works exactly like sample_string = sample_string + HEADER The string referred to by the global name sample_string is never modified and the global name is never reassigned. http://docs.python.org/py3k/tutorial/classes.html#python-scopes-and-namespaces > gen_header(sample_string) > gen_nia(sample_string) > > print(sample_string) You probably want something like the following: sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) print(sample_string) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ericwoodworth at gmail.com Wed Aug 11 12:39:19 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 09:39:19 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: This will work: ------------------------------------------------------------------------ sample_string="" def gen_header(sample_string=""): HEADER = """ mymultilinestringhere """ sample_string+= HEADER return sample_string def gen_nia(sample_string=""): NIA = """ anothermultilinestringhere """ sample_string += NIA return sample_string sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) print(sample_string) ------------------------------------------------------------------------ and this will work ------------------------------------------------------------------------ sample_string="" def gen_header(OtherString): global sample_string HEADER = """ mymultilinestringhere """ sample_string+= HEADER def gen_nia(OtherString): global sample_string NIA = """ anothermultilinestringhere """ sample_string += NIA gen_header(sample_string) gen_nia(sample_string) print(sample_string) ------------------------------------------------------------------------ The first one is the better of the 2 in this example but the second one will show you how to use global variables if you really need to use them So your problem was that you thought you were working on a global variable in your functions when you were not. Since the your def lines contained sample_string that make it a local variable. So when you were doing your += statements you were working on a local variable and not a global variable. You were returning the value of the local variable but you didn't have anything in the main body of your script catching that value. So simply changing these 2 lines: sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) made the global sample_string variable store the values of the return data. If you want to use global variables then you just have to do 2 things. First you have to make sure you don't have any local variables it the function with the same name. So I change the name to OtherString in the def line. Then you need a global statement at the start of your function (global sample_string) that tells python that you really do want to use that global variable. Global variables can cause you no end of heartache so python forces you to explicitly state that you want to use them. Hope that helps. From fuglyducky at gmail.com Wed Aug 11 12:39:58 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Wed, 11 Aug 2010 09:39:58 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> Message-ID: On Aug 11, 9:31?am, Pinku Surana wrote: > On Aug 11, 12:07?pm, fuglyducky wrote: > > > > > I am a complete newbie to Python (and programming in general) and I > > have no idea what I'm missing. Below is a script that I am trying to > > work with and I cannot get it to work. When I call the final print > > function, nothing prints. However, if I print within the individual > > functions, I get the appropriate printout. > > > Am I missing something??? Thanks in advance!!!! > > > ################################################ > > # Global variable > > sample_string = "" > > > def gen_header(sample_string): > > ? ? HEADER = """ > > ? ? mymultilinestringhere > > ? ? """ > > > ? ? sample_string += HEADER > > ? ? return sample_string > > > def gen_nia(sample_string): > > ? ? NIA = """ > > ? ? anothermultilinestringhere > > ? ? """ > > > ? ? sample_string += NIA > > ? ? return sample_string > > > gen_header(sample_string) > > gen_nia(sample_string) > > > print(sample_string) > > There are 2 problems with your program. > > (1) If you want to use a global variable in a function, you have to > add the line "global sample_string" to the beginning of that > function. > > (2) Once you do (1), you will get an error because you've got > sample_string as a global and a function parameter. Which one do you > want to use in the function? You should change the name of the > parameter to "sample" to solve that confusion. > > Here's the result, which works for me: > > sample_string = "" > def gen_header(sample): > ? ? global sample_string > ? ? HEADER = """ > ? ? mymultilinestringhere > ? ? """ > ? ? sample_string = sample + HEADER > ? ? return sample_string > def gen_nia(sample): > ? ? global sample_string > ? ? NIA = """ > ? ? anothermultilinestringhere > ? ? """ > ? ? sample_string = sample + NIA > ? ? return sample_string > gen_header(sample_string) > gen_nia(sample_string) > print(sample_string) Thanks! That did the trick. I am a bit confused though. I tried to follow a sample in a book (which works) where I didn't have to 1) pass the global variable as a parameter into the function, 2) did not have to define the global variable within the function. I apologize if this is a super stupid question but if it is global, why do I have to pass it into the function? Shouldn't the global variable be accessible from anywhere??? From jeanmichel at sequans.com Wed Aug 11 12:47:05 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 11 Aug 2010 18:47:05 +0200 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: <4C62D409.6010402@sequans.com> fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! > > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > HEADER = """ > mymultilinestringhere > """ > > sample_string += HEADER > return sample_string > > def gen_nia(sample_string): > NIA = """ > anothermultilinestringhere > """ > > sample_string += NIA > return sample_string > > > gen_header(sample_string) > gen_nia(sample_string) > > print(sample_string) > sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) print sample_string That should work. I guess you made an error thinking that sample_string += HEADER would change the value of the given parameter. It does not. The value is changed only for sample_string within the function This is the case for any immutable object (strings are immutable) in Python. Example: class AMutable(object): def __init__(self): self.description = 'I am X' myString = 'I am a immutable string' # an immutable object myMutable = AMutable() # a mutable object def bar(myMutable): myMutable.description = 'I am Y' # change the attribute description of the object def foo(aString): aString = 'fooooooooo' # will have no effect outside the function print 'before calling bar: ', myMutable.description bar(myMutable) print 'after calling bar: ', myMutable.description print 'before calling foo: ', myString foo(myString) print 'after calling foo: ', myString > before calling bar: I am X after calling bar: I am Y before calling foo: I am a immutable string after calling foo: I am a immutable string cheers, JM From ericwoodworth at gmail.com Wed Aug 11 12:55:56 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 09:55:56 -0700 (PDT) Subject: Queue cleanup Message-ID: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Hi I'm writing a multithreaded app that relies on Queues to move data between the threads. I'm trying to write my objects in a general way so that I can reuse them in the future so I need to write them in such a way that I don't know how many producer and how many consumer threads I might need. I also might have different consumer threads do different tasks (for example one might write to a log and one might write to SQL) so that again means I can't plan for a set ratio of consumers to producers. So it's unknown. So this means that instead of having 1 Queue that all the producers put to and that all the consumers get from I actually have 1 Queue per producer thread that the main body sends to the correct type of consumer thread. So I could get something like this where 3 producer threads write to 3 different Queues all of which get read by 1 consumer thread: P1 P2 P3 \ | / \ | / C1 So producers 1, 2, and 3 all write to individual Queues and consumer 1 had a list of those Queues and reads them all. The problem I'm having is that those producer threads can come and go pretty quickly and when they die I can cleanup the thread with join() but I'm still left with the Queue. So I could get something like this: P1 P3 \ | / \ | / C1 So here the P2 thread has ended and gone away but I still have his Queue lingering. So on a thread I can use is_alive() to check status and use join() to clean up but I don't see any analogous functionality for Queues. How do I kill them? I thought about putting a suicide message on the Queue and then C1 would read it and set the variable to None but i'm not sure setting the variable to None actually makes the Queue go away. It could just end up sitting in memory unreferenced - and that's not good. Additionally, I could have any number of consumer threads reading that Queue so once the first one get the suicide note the other consumer threads never would. I figure there has to be an elegant way for managing my Queues but so far I can't find it. Any suggestions would be appreciated and thanks in advance for any help. ps Python rocks. From ericwoodworth at gmail.com Wed Aug 11 12:58:17 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 09:58:17 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> Message-ID: <7d32ea1f-c415-4f66-b391-77c57caa5f1a@j5g2000vbg.googlegroups.com> On Aug 11, 12:39?pm, fuglyducky wrote: > On Aug 11, 9:31?am, Pinku Surana wrote: > > > > > > > On Aug 11, 12:07?pm, fuglyducky wrote: > > > > I am a complete newbie to Python (and programming in general) and I > > > have no idea what I'm missing. Below is a script that I am trying to > > > work with and I cannot get it to work. When I call the final print > > > function, nothing prints. However, if I print within the individual > > > functions, I get the appropriate printout. > > > > Am I missing something??? Thanks in advance!!!! > > > > ################################################ > > > # Global variable > > > sample_string = "" > > > > def gen_header(sample_string): > > > ? ? HEADER = """ > > > ? ? mymultilinestringhere > > > ? ? """ > > > > ? ? sample_string += HEADER > > > ? ? return sample_string > > > > def gen_nia(sample_string): > > > ? ? NIA = """ > > > ? ? anothermultilinestringhere > > > ? ? """ > > > > ? ? sample_string += NIA > > > ? ? return sample_string > > > > gen_header(sample_string) > > > gen_nia(sample_string) > > > > print(sample_string) > > > There are 2 problems with your program. > > > (1) If you want to use a global variable in a function, you have to > > add the line "global sample_string" to the beginning of that > > function. > > > (2) Once you do (1), you will get an error because you've got > > sample_string as a global and a function parameter. Which one do you > > want to use in the function? You should change the name of the > > parameter to "sample" to solve that confusion. > > > Here's the result, which works for me: > > > sample_string = "" > > def gen_header(sample): > > ? ? global sample_string > > ? ? HEADER = """ > > ? ? mymultilinestringhere > > ? ? """ > > ? ? sample_string = sample + HEADER > > ? ? return sample_string > > def gen_nia(sample): > > ? ? global sample_string > > ? ? NIA = """ > > ? ? anothermultilinestringhere > > ? ? """ > > ? ? sample_string = sample + NIA > > ? ? return sample_string > > gen_header(sample_string) > > gen_nia(sample_string) > > print(sample_string) > > Thanks! That did the trick. > > I am a bit confused though. I tried to follow a sample in a book > (which works) where I didn't have to 1) pass the global variable as a > parameter into the function, 2) did not have to define the global > variable within the function. I apologize if this is a super stupid > question but if it is global, why do I have to pass it into the > function? Shouldn't the global variable be accessible from anywhere??? If it's a global then you don't have to pass it to the function but you do have to have the line that says: global sample_string Now if you think the example in the book didn't do that and it still worked then if you post that sample I'm sure somebody can tell you why it worked. The book example might be doing something different. From rNOSPAMon at flownet.com Wed Aug 11 12:59:55 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 09:59:55 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , Cameron Simpson wrote: > On 11Aug2010 00:11, RG wrote: > | When stdin is not a tty, Python seems to buffer all the input through > | EOF before processing any of it: > | > | [ron at mickey:~]$ cat | python > | print 123 > | print 456 > | 123 > | 456 > | > | Is there a way to get Python to process input line-by-line the way it > | does when stdin is a TTY even when stdin is not a TTY? > > What you're seeing here is not python's behaviour but cat's behaviour. > > Almost all programs do line buffering (flush buffer at newline) when the > file is a terminal (character device) and block buffering (flush when a > fixed size buffer, typically 8192 bytes or some larger power of 2) when > the file is not a terminal. This is default behaviour for the stdio > package. > > So "cat" is simply not feeding any data to python until it has a lot of > it; I don't think that's right: [ron at mickey:~]$ cat | cat 123 123 321 321 Cat seems to flush its buffer after every newline. Also: [ron at mickey:~]$ cat -u | python print 123 print 456 123 456 > We would need to know > more about your specific task to suggest workarounds. I'm writing a system in a different language but want to use a Python library. I know of lots of ways to do this (embed a Python interpreter, fire up a python server) but by far the easiest to implement is to have the main program spawn a Python interpreter and interact with it through its stdin/stdout. In my code I explicitly force the output stream that is being piped to Python's stdin to be flushed so I know it's not a buffering problem on the input side. rg From ericwoodworth at gmail.com Wed Aug 11 13:01:09 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 10:01:09 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <6f6c0aa0-fc6f-47d4-bbf3-2ebe04f97cba@v23g2000vbi.googlegroups.com> On Aug 11, 12:55?pm, EW wrote: > Hi > > I'm writing a multithreaded app that relies on Queues to move data > between the threads. ?I'm trying to write my objects in a general way > so that I can reuse them in the future so I need to write them in such > a way that I don't know how many producer and how many consumer > threads I might need. ?I also might have different consumer threads do > different tasks (for example one might write to a log and one might > write to SQL) so that again means I can't plan for a set ratio of > consumers to producers. ?So it's unknown. > > So this means that instead of having 1 Queue that all the producers > put to and that all the consumers get from I actually have 1 Queue per > producer thread ?that the main body sends to the correct type of > consumer thread. ?So I could get something like this where 3 producer > threads write to 3 different Queues all of which get read by 1 > consumer thread: > > P1 ? ?P2 ? P3 > ? ? ?\ ? ?| ? / > ? ? ? ?\ ?| ?/ > ? ? ? ? C1 > > So producers 1, 2, and 3 all write to individual Queues and consumer 1 > had a list of those Queues and reads them all. ?The problem I'm having > is that those producer threads can come and go pretty quickly and when > they die I can cleanup the thread with join() but I'm still left with > the Queue. ?So I could get something like this: > > P1 ? ? ? ? P3 > ? ? ?\ ? ?| ? / > ? ? ? ?\ ?| ?/ > ? ? ? ? C1 > > So here the P2 thread has ended and gone away but I still have his > Queue lingering. > > So on a thread I can use is_alive() to check status and use join() to > clean up but I don't see any analogous functionality for Queues. ?How > do I kill them? ?I thought about putting a suicide message on the > Queue and then C1 would read it and set the variable to None but i'm > not sure setting the variable to None actually makes the Queue go > away. ?It could just end up sitting in memory unreferenced - and > that's not good. ?Additionally, I could have any number of consumer > threads reading that Queue so once the first one get the suicide note > the other consumer threads never would. > > I figure there has to be an elegant way for managing my Queues but so > far I can't find it. ?Any suggestions would be appreciated and thanks > in advance for any help. > > ps Python rocks. Whoo..the formatting got torn up! My terrible diagrams are even more terrible! Oh well, I think you'll catch my meaning :) From rNOSPAMon at flownet.com Wed Aug 11 13:02:24 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 10:02:24 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > Grant Edwards wrote: > > > On 2010-08-11, Tim Harig wrote: > >> On 2010-08-11, RG wrote: > >>> When stdin is not a tty, Python seems to buffer all the input through > >>> EOF before processing any of it: > >>> > >>> [ron at mickey:~]$ cat | python > >>> print 123 > >>> print 456 > >>> 123 > >>> 456 > >>> > >>> Is there a way to get Python to process input line-by-line the way it > >>> does when stdin is a TTY even when stdin is not a TTY? > >> > >> It would be much better to know the overall purpose of what you are > >> trying > >> to achieve. There are may be better ways (ie, sockets) depending what > >> you > >> are trying to do. Knowing your target platform would also be helpful. > >> > >> For the python interpeter itself, you can can get interactive behavior by > >> invoking it with the -i option. > > > > If you're talking about unbuffered stdin/stdout, the option is -u. > > > > I don't really see how the -i option is relevent -- it causes the > > interpreter to go into interactive mode after running the script. > > I'd say the following looks like what the OP was asking for: > > $ cat | python -i -c'import sys; sys.ps1=""' > print sys.stdin.isatty() > False > print 1 > 1 > print 2 > 2 That is indeed the behavior I'm looking for. > (Whether it's useful is yet another question) It's useful to me :-) I'm trying to access a python library from a program written in another language for which an equivalent library is not available. The easiest way to do that is to spawn a Python interpreter and interact with it through stdin/stdout. Thanks! rg From davea at ieee.org Wed Aug 11 13:08:44 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 11 Aug 2010 13:08:44 -0400 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: <4C62D91C.9020509@ieee.org> fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! > > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > HEADER = """ > mymultilinestringhere > """ > > sample_string += HEADER > return sample_string > > def gen_nia(sample_string): > NIA = """ > anothermultilinestringhere > """ > > sample_string += NIA > return sample_string > > > gen_header(sample_string) > gen_nia(sample_string) > > print(sample_string) > > It'd be best if you used different names for global scope than you do inside your functions. It won't change how this case works, but at least it'd be clearer what's happening. And sometimes you can get an unintended side effect when you use the same name for two different variables. In function gen_header(), you take an argument, and return a modified version of it. But the call to it never uses the return value. If you want to make any changes to the global value, you'd do something like this: sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) print(sample_string) HTH DaveA From no.email at nospam.invalid Wed Aug 11 13:18:24 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 10:18:24 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <7x39ulysnz.fsf@ruckus.brouhaha.com> EW writes: > I also might have different consumer threads do > different tasks (for example one might write to a log and one might > write to SQL) so that again means I can't plan for a set ratio of > consumers to producers.... So it's unknown. > > So this means that instead of having 1 Queue that all the producers > put to and that all the consumers get from I actually have 1 Queue per > producer thread That doesn't sound appropriate. Queues can have many readers and many writers. So use one queue per task (logging, SQL, etc), regardless of the number of producer or consumer threads. Any producer with an SQL request sends it to the SQL queue, which can have many listeners. The different SQL consumer threads listen to the SQL queue and pick up requests and handle them. From ericwoodworth at gmail.com Wed Aug 11 13:26:42 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 10:26:42 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> Message-ID: On Aug 11, 1:18?pm, Paul Rubin wrote: > EW writes: > > I also might have different consumer threads do > > different tasks (for example one might write to a log and one might > > write to SQL) so that again means I can't plan for a set ratio of > > consumers to producers.... ?So it's unknown. > > > So this means that instead of having 1 Queue that all the producers > > put to and that all the consumers get from I actually have 1 Queue per > > producer thread > > That doesn't sound appropriate. ?Queues can have many readers and many > writers. ?So use one queue per task (logging, SQL, etc), regardless of > the number of producer or consumer threads. ?Any producer with an SQL > request sends it to the SQL queue, which can have many listeners. ?The > different SQL consumer threads listen to the SQL queue and pick up > requests and handle them. I thought about doing it that way and I could do it that way but it still seems like there should be a way to clean up Queues on my own. If I did it this way then I guess I'd be relying on garbage collection when the script ended to clean up the Queues for me. What if I want to clean up my own Queues? Regardless of the specifics of my current design, I'm just generally curious how people manage cleanup of their Queues when they don't want them any more. From badouglas at gmail.com Wed Aug 11 13:29:29 2010 From: badouglas at gmail.com (bruce) Date: Wed, 11 Aug 2010 10:29:29 -0700 Subject: mysqldb - parameter issue In-Reply-To: References: Message-ID: hey dennis... umm.. given that i'm building the ins var/string to insert into the execute... i can't just place the triple quotes around it.. are you saying that the execute should have quotes placed around it within the execute so it would be something like execute("\""+sel""\""... or are you saying that within python i can just extend the line for the "sel" on multiple lines.. as to the err. i'm getting a " >>> Warning: Data truncated for column it appears that if i place the >>from_unixtime(%s) << at the end of the paramaters, then everything works.. but if i place it within the "%s" block.. the error is generated. I'm assuming there's some way to wrap the from_unixtime(%s) so it could be used as %s,%s,%s, from_unixtime(%s), %s, %s,... in checking the docs/spec.. i didn't see anything that discussed this... thanks > ins = """insert into functionError_TBL > (errorStatus, CollegeID, processTime) > values (%s, %s, from_unixtime(%s) )""" > On Wed, Aug 11, 2010 at 9:53 AM, Dennis Lee Bieber wrote: > On Wed, 11 Aug 2010 08:08:21 -0700, bruce > declaimed the following in gmane.comp.python.general: > > >> ? tlist= [(1, 1, 1281502771)] >> >> ? ins="insert into functionError_TBL " >> ? ins=ins+"(errorStatus, CollegeID, processTime)" >> ? ins=ins+" values " >> ? ins=ins+" ?(%s,%s, ?from_unixtime(%s))" > > ? ? ? ?Without examining the rest of the problem, the above sequence can be > cleaned up by using triple quotes... > > ? ? ? ?ins = """insert into functionError_TBL > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(errorStatus, CollegeID, processTime) > ? ? ? ? ? ? ? ? ? ? ? ?values (%s, %s, from_unixtime(%s) )""" > >> >> along with the corresponding insert portion, and the test list, an >> error is generated.. >> > ? ? ? ?What error? You've failed to post the most important part... EXACTLY > what the system reports... > -- > ? ? ? ?Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ?wlfraed at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Wed Aug 11 13:35:59 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Aug 2010 13:35:59 -0400 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: Rather than patch your code, I think you should see a better approach. from textwrap import dedent # removes common whitespace prefix lines = [] def add_header(ss): "Add header to sequence of string lines" ss.append(dedent("""\ # No initial blank line my multi-line string here """)) def add_more(ss): "Add more to sequence of string lines" ss.append(dedent(""" # Start with blank line another multi-line string here """)) add_header(lines) add_more(lines) print(''.join(lines)) # prints -------------------------------- my multi-line string here another multi-line string here -------------------------------- PS. Only use 'gen' for naming generator functions when you get to them. -- Terry Jan Reedy From tjreedy at udel.edu Wed Aug 11 13:44:14 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Aug 2010 13:44:14 -0400 Subject: Is ElementTree development still active? In-Reply-To: <8b9ee78d-746e-4bb3-aef7-932ad2028650@x21g2000yqa.googlegroups.com> References: <8b9ee78d-746e-4bb3-aef7-932ad2028650@x21g2000yqa.googlegroups.com> Message-ID: On 8/11/2010 12:21 PM, Pinku Surana wrote: > I checked the svn repo at effbot.org, but it appears to have no > updates since 2007. Has development moved elsewhere? It is now in the stdlib (19.11) as xml.etree.ElementTree http://svn.python.org/view/python/branches/py3k/Modules/_elementtree.c?revision=83949&view=markup last revised 12 min ago. -- Terry Jan Reedy From python at mrabarnett.plus.com Wed Aug 11 13:55:23 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 18:55:23 +0100 Subject: Queue cleanup In-Reply-To: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <4C62E40B.9050905@mrabarnett.plus.com> EW wrote: [snip] > So here the P2 thread has ended and gone away but I still have his > Queue lingering. > > So on a thread I can use is_alive() to check status and use join() to > clean up but I don't see any analogous functionality for Queues. How > do I kill them? I thought about putting a suicide message on the > Queue and then C1 would read it and set the variable to None but i'm > not sure setting the variable to None actually makes the Queue go > away. It could just end up sitting in memory unreferenced - and > that's not good. Additionally, I could have any number of consumer > threads reading that Queue so once the first one get the suicide note > the other consumer threads never would. > > I figure there has to be an elegant way for managing my Queues but so > far I can't find it. Any suggestions would be appreciated and thanks > in advance for any help. > An object will be available for garbage collection when nothing refers to it either directly or indirectly. If it's unreferenced then it will go away. As for the suicide note, if a consumer sees it then it can put it back into the queue so other consumers will see it and then forget about the queue (set the variable which refers to the queue to None, or, if the references are in a list, delete it from the list). From usernet at ilthio.net Wed Aug 11 13:56:13 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 17:56:13 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, RG wrote: > I'm writing a system in a different language but want to use a Python > library. I know of lots of ways to do this (embed a Python interpreter, > fire up a python server) but by far the easiest to implement is to have > the main program spawn a Python interpreter and interact with it through > its stdin/stdout. Or, open python using a socket. That way you have total control over how the information is transfered, as well as bi-directional transfer. From ericwoodworth at gmail.com Wed Aug 11 13:57:14 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 10:57:14 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <3a46969a-0f58-498b-8854-6e7d8b28dde6@j2g2000vbo.googlegroups.com> On Aug 11, 1:55?pm, MRAB wrote: > EW wrote: > > [snip] > > > > > So here the P2 thread has ended and gone away but I still have his > > Queue lingering. > > > So on a thread I can use is_alive() to check status and use join() to > > clean up but I don't see any analogous functionality for Queues. ?How > > do I kill them? ?I thought about putting a suicide message on the > > Queue and then C1 would read it and set the variable to None but i'm > > not sure setting the variable to None actually makes the Queue go > > away. ?It could just end up sitting in memory unreferenced - and > > that's not good. ?Additionally, I could have any number of consumer > > threads reading that Queue so once the first one get the suicide note > > the other consumer threads never would. > > > I figure there has to be an elegant way for managing my Queues but so > > far I can't find it. ?Any suggestions would be appreciated and thanks > > in advance for any help. > > An object will be available for garbage collection when nothing refers > to it either directly or indirectly. If it's unreferenced then it will > go away. > > As for the suicide note, if a consumer sees it then it can put it back > into the queue so other consumers will see it and then forget about the > queue (set the variable which refers to the queue to None, or, if the > references are in a list, delete it from the list). Ok great. I wasn't sure about the Garbage collection part of it. That's actually pretty easy. Thanks! From usernet at ilthio.net Wed Aug 11 14:06:42 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 18:06:42 +0000 (UTC) Subject: How to swallow traceback message References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: On 2010-08-11, Back9 wrote: > On Aug 11, 11:19?am, Tim Harig wrote: >> On 2010-08-11, Back9 wrote: >> > But when I try to exit it, normally I use Ctrl+ C key to quit it. >> > Problem is every time I do like it, it shows Traceback message and it >> > makes my app not professional. >> >> You have three options. >> >> ? ? ? ? 1. Exit more properly. >> >> ? ? ? ? 2. Catch and handle SIGINT yourself. >> >> ? ? ? ? 3. Wrap whatever section of your program is being interrupted in >> ? ? ? ? ? ? ? ? try/except to catch the KeyboardInterrupt exception when it >> ? ? ? ? ? ? ? ? is generated. > > I should have mentioned that I already use try/except > KeyboardInterrupt statement. > But it does not seem to work as I expected. The either your code is somewhere outside of the try/except block when it receives SIGINT, the exception is being caught somewhere below the try/except clause that you added for KeyboardInterrupt, or there is something wrong with your handling code. If you want much more help, you are going to have to post some code to give us some specifics to troubleshoot. From no.email at nospam.invalid Wed Aug 11 14:16:29 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 11:16:29 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> Message-ID: <7xd3tpqaki.fsf@ruckus.brouhaha.com> EW writes: > I thought about doing it that way and I could do it that way but it > still seems like there should be a way to clean up Queues on my own. > If I did it this way then I guess I'd be relying on garbage collection > when the script ended to clean up the Queues for me. Oh, I see. As long as it's possible to start new producer or consumer threads that touch a queue, obviously that queue has to still be around. If the program starts all its threads at the beginning, then runs til they exit, then does more stuff, then you could do something like: # make dictonary of queues, one queue per task type queues = {'sql': Queue(), 'logging': Queue(), ... } for i in threading.Thread(target=your_handler, args=[queues]) del queues and then when all the threads exit, there are no remaining references to the queues. But why do you care? Queues aren't gigantic structures, they're just a list (collections.deque) with an rlock. It's fine to let the gc clean them up; that's the whole point of having a gc in the first place. From nagle at animats.com Wed Aug 11 14:24:07 2010 From: nagle at animats.com (John Nagle) Date: Wed, 11 Aug 2010 11:24:07 -0700 Subject: Is there a Python equivalent to Perl's File::Listing::parse_dir Message-ID: <4c62ead3$0$1587$742ec2ed@news.sonic.net> Perl has a function which will take a remote directory page, in the form that most web sites return for a file directory, and parse it into a useful form: http://www.xav.com/perl/site/lib/File/Listing.html This is especially useful for FTP sites. Is there a Python equivalent of this? I'm converting some old Perl code. Even the Python FTP module doesn't have a directory parser. John Nagle From __peter__ at web.de Wed Aug 11 14:26:49 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Aug 2010 20:26:49 +0200 Subject: How to swallow traceback message References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: Back9 wrote: > I run my py app to display a file's contents, and it is normally very > long. > So I use it like below: > > python myapp.py input_file | more > to see them step by step. > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > Problem is every time I do like it, it shows Traceback message and it > makes my app not professional. > > How do I handle it gracefully. Step 1, provoke the error: $ python -c"while 1: print 42" | head -n1 42 Traceback (most recent call last): File "", line 1, in IOError: [Errno 32] Broken pipe Step 1a, read the error message carefully ;) Step 2, catch the error: $ python -c"try: while 1: print 42 except IOError as e: if e.errno != 32: raise " | head -n1 42 Step 3, repeat if necessary. IOError is only one example. Peter From rNOSPAMon at flownet.com Wed Aug 11 14:37:20 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 11:37:20 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , Tim Harig wrote: > On 2010-08-11, RG wrote: > > I'm writing a system in a different language but want to use a Python > > library. I know of lots of ways to do this (embed a Python interpreter, > > fire up a python server) but by far the easiest to implement is to have > > the main program spawn a Python interpreter and interact with it through > > its stdin/stdout. > > Or, open python using a socket. You mean a TCP/IP socket? Or a unix domain socket? The former has security issues, and the latter seems like a lot of work. Or is there an easy way to do it that I don't know about? rg From ericwoodworth at gmail.com Wed Aug 11 14:39:10 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 11:39:10 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> Message-ID: <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> On Aug 11, 2:16?pm, Paul Rubin wrote: > EW writes: > > I thought about doing it that way and I could do it that way but it > > still seems like there should be a way to clean up Queues on my own. > > If I did it this way then I guess I'd be relying on garbage collection > > when the script ended to clean up the Queues for me. > > Oh, I see. ?As long as it's possible to start new producer or consumer > threads that touch a queue, obviously that queue has to still be around. > If the program starts all its threads at the beginning, then runs til > they exit, then does more stuff, then you could do something like: > > ? ? # make dictonary of queues, one queue per task type > ? ? queues = {'sql': Queue(), 'logging': Queue(), ... } > > ? ? for i in > ? ? ? ?threading.Thread(target=your_handler, args=[queues]) > > ? ? del queues > > and then when all the threads exit, there are no remaining references to > the queues. ?But why do you care? ?Queues aren't gigantic structures, > they're just a list (collections.deque) with an rlock. ?It's fine to let > the gc clean them up; that's the whole point of having a gc in the first > place. Well I cared because I thought garbage collection would only happen when the script ended - the entire script. Since I plan on running this as a service it'll run for months at a time without ending. So I thought I was going to have heaps of Queues hanging out in memory, unreferenced and unloved. It seemed like bad practice so I wanted to get out ahead of it. But the GC doesn't work the way I thought it worked so there's really no problem I guess. I was just confused on garbage collection it seems. From pramo4d at gmail.com Wed Aug 11 14:43:46 2010 From: pramo4d at gmail.com (Pramod) Date: Wed, 11 Aug 2010 11:43:46 -0700 (PDT) Subject: How to input values of the matrix from keyboard in python Message-ID: Hi I want to know the how we input values into the matrix (N*N size) from keyboard in python, Here I wrote Matrix programe in C++ This asks values from key board and print on the console N*N matrix ; Thanks in advance .... #include using namespace std; int main() { double **a; int i,j,n; cout<<"Enter size of the matrix\n"; cin>>n; for(i=0;i>a[i][j]; cout< Hi all, Is there a way that I can startup my script and pass it a file? For example: ~$ python myscript.py mytext.txt and then access mytext.txt in myscript.py? As a long shot, for myscript.py I tried def __init__(fle): print fle expecting the full path to mytext.txt to be printed but that didn't work. Obviously I've never done this. I hope the above makes sense. any help will be greatly appreciated. Thanks, -- Bradley J. Hintze Graduate Student Duke University School of Medicine 801-712-8799 From no.email at nospam.invalid Wed Aug 11 14:52:27 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 11:52:27 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> Message-ID: <7xvd7h2d90.fsf@ruckus.brouhaha.com> EW writes: > Well I cared because I thought garbage collection would only happen > when the script ended - the entire script. Since I plan on running > this as a service it'll run for months at a time without ending. So I > thought I was going to have heaps of Queues hanging out in memory, > unreferenced and unloved. It seemed like bad practice so I wanted to > get out ahead of it. Even if GC worked that way it wouldn't matter, if you use just one queue per type of task. That number should be a small constant so the memory consumption is small. From falk at mauve.rahul.net Wed Aug 11 14:53:15 2010 From: falk at mauve.rahul.net (Edward A. Falk) Date: Wed, 11 Aug 2010 18:53:15 +0000 (UTC) Subject: urgent requirement at Hyderabad References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Message-ID: In article , Stefan Behnel wrote: >In case anyone wondered: Hyderabad is likely referring to some place in Asia: It's one of the high-tech cities in India. A lot of out-sourcing winds up there. -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From __peter__ at web.de Wed Aug 11 14:58:25 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Aug 2010 20:58:25 +0200 Subject: passing file from command line startup References: Message-ID: Bradley Hintze wrote: > Hi all, > > Is there a way that I can startup my script and pass it a file? For > example: > > ~$ python myscript.py mytext.txt > > and then access mytext.txt in myscript.py? > > As a long shot, for myscript.py I tried > > def __init__(fle): > print fle > > expecting the full path to mytext.txt to be printed but that didn't work. > > Obviously I've never done this. I hope the above makes sense. any help > will be greatly appreciated. > > Thanks, You are looking for sys.argv: $ cat tmp.py import sys print sys.argv $ python tmp.py one two 'many arguments' ['tmp.py', 'one', 'two', 'many arguments'] Around that simple mechanism fancier libraries have been built: http://docs.python.org/library/argparse.html Peter From robert.kern at gmail.com Wed Aug 11 15:03:11 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Aug 2010 14:03:11 -0500 Subject: passing file from command line startup In-Reply-To: References: Message-ID: On 8/11/10 1:47 PM, Bradley Hintze wrote: > Hi all, > > Is there a way that I can startup my script and pass it a file? For example: > > ~$ python myscript.py mytext.txt > > and then access mytext.txt in myscript.py? > > As a long shot, for myscript.py I tried > > def __init__(fle): > print fle > > expecting the full path to mytext.txt to be printed but that didn't work. > > Obviously I've never done this. I hope the above makes sense. any help > will be greatly appreciated. http://docs.python.org/library/sys#sys.argv I do recommend using argparse to process command line arguments, even for the simplest cases: http://docs.python.org/library/argparse -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From python at mrabarnett.plus.com Wed Aug 11 15:04:41 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 20:04:41 +0100 Subject: passing file from command line startup In-Reply-To: References: Message-ID: <4C62F449.4040204@mrabarnett.plus.com> Bradley Hintze wrote: > Hi all, > > Is there a way that I can startup my script and pass it a file? For example: > > ~$ python myscript.py mytext.txt > > and then access mytext.txt in myscript.py? > > As a long shot, for myscript.py I tried > > def __init__(fle): > print fle > > expecting the full path to mytext.txt to be printed but that didn't work. > > Obviously I've never done this. I hope the above makes sense. any help > will be greatly appreciated. > import sys print sys.argv From clp2 at rebertia.com Wed Aug 11 15:06:19 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 11 Aug 2010 12:06:19 -0700 Subject: How to input values of the matrix from keyboard in python In-Reply-To: References: Message-ID: On Wed, Aug 11, 2010 at 11:43 AM, Pramod wrote: > Hi > > ? I want to know the how we input values into the matrix (N*N size) > from keyboard in python, > > Here I wrote Matrix programe in C++ > > This ?asks values from key board and print on the console N*N matrix ; > > Thanks in advance .... > > > #include > using namespace std; > int main() > { > ? ? ? ?double **a; > ? ? ? ?int i,j,n; > ? ? ? ?cout<<"Enter size of the matrix\n"; > ? ? ? ?cin>>n; > ? ? ? ? ? ? ? ?for(i=0;i ? ? ? ? ? ? ? ?for(j=0;j ? ? ? ? ? ? ? ? ? ? ? ?a[i][j] = random(); > //or > ? ? ? ? ? ? ? ?//cin>>a[i][j]; > ? ? ? ? ? ? ? ?cout< ? ? ? ?} > ? ? ? ?for(i=0;i ? ? ? ? ? ? ? ?for(j=0;j ? ? ? ? ? ? ? ? ? ? ? ?cout< ? ? ? ? ? ? ? ?cout< ? ? ? ?} > ? ? ? ?delete [] a; > } from random import random from sys import exit while True: try: N = int(raw_input("Enter size of the matrix: ")) except ValueError: print "Invalid input. Try again." except EOFError: exit(1) else: break a = [[random() for j in xrange(N)] for i in xrange(N)] stringified = "\n".join("\t".join(row) for row in a) print stringified If you're doing serious work with matrices, look at the NumPy package. Cheers, Chris -- http://blog.rebertia.com From iamforufriends at gmail.com Wed Aug 11 15:07:21 2010 From: iamforufriends at gmail.com (UR DREEM GIRL) Date: Wed, 11 Aug 2010 12:07:21 -0700 (PDT) Subject: FIND A NEW HOT GIRL FROM YOUR AREA FREE AND ENJOY Message-ID: <05fe2ce2-ce52-4e2a-8cd0-0a82ed4b8930@u4g2000prn.googlegroups.com> FIND A NEW HOT GIRL FROM YOUR AREA FREE AND ENJOY CLICK... http://adultfriendfinder.com/go/g1250650-ppc http://adultfriendfinder.com/go/g1250650-ppc http://adultfriendfinder.com/go/g1250650-ppc From python at mrabarnett.plus.com Wed Aug 11 15:08:50 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 20:08:50 +0100 Subject: How to input values of the matrix from keyboard in python In-Reply-To: References: Message-ID: <4C62F542.7070803@mrabarnett.plus.com> Pramod wrote: > Hi > > I want to know the how we input values into the matrix (N*N size) > from keyboard in python, > > Here I wrote Matrix programe in C++ > > > This asks values from key board and print on the console N*N matrix ; > [snip] Read from the keyboard using raw_input() (in Python 2, or input() in Python 3) and convert to float. Incidentally, your C++ program doesn't allocate the array. From jearl at notengoamigos.org Wed Aug 11 15:20:41 2010 From: jearl at notengoamigos.org (Jason Earl) Date: Wed, 11 Aug 2010 13:20:41 -0600 Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> <4c610bd2$0$28655$c3e8da3@news.astraweb.com> <87aaouzkm1.fsf@benfinney.id.au> Message-ID: <87hbj1j6ra.fsf@notengoamigos.org> On Tue, Aug 10 2010, Ben Finney wrote: > Steven D'Aprano writes: > >> On Tue, 10 Aug 2010 20:07:06 +1200, Gregory Ewing wrote: >> > Is there any way for a non-.NET program to access a .NET library? Or >> > is it necessary to drink the entire bottle of .NET kool-aid? >> >> http://www.mono-project.com/Main_Page > > Anyone thinking of using Mono needs to be aware of the dangers of > software patents in general, and of .NET in paticular. > > The copyright license for Mono is under free software terms. But that > gives no license at all for the patents. Novell, who have an exclusive > deal for those patents, happily encourages use of Mono by third > parties. > > The controversy has raged for a number of years. For more coverage > than you have time for, see > . The issue has > polarised discussion, unfortunately, and there is a lot of > name-calling and hyperbole on the record now. > > As the Mono site hints, the patent situation for .NET is *very* muddy. > Microsoft hold patents covering much of .NET, but have made a > (non-binding) ?Community Promise? that applies to *some* parts of .NET > . Which is more of a promise than Microsoft has given to Python. I am not arguing for Mono, as I am not a fan. But if you honestly think that Python doesn't infringe on some of Microsoft's patents you are crazy. So where is the promise from Microsoft saying that they won't sue the Python development team into oblivion, or Python end users, for that matter? There isn't one. So while the Mono promise doesn't cover all of Mono, it does cover *some* of Mono, which is better than what Python can say. If you happen to be believe that Microsoft is likely to attack Free Software via patents then Mono is arguably the safest choice. Especially if you confine yourself to the ECMA-sponsored core and the Free Software libraries that are not re-implementations of Microsoft's technology. Jason From pramo4d at gmail.com Wed Aug 11 15:27:32 2010 From: pramo4d at gmail.com (Pramod) Date: Wed, 11 Aug 2010 12:27:32 -0700 (PDT) Subject: How to give matrix input from keyboard or file in python Message-ID: I want to write the following programm in python . Main objective is input from keyoard to enter elements into the matrix . Thanks in advance #include #include #include using namespace std; int main() { double **a; int i,j,n; cout<<"Enter size of the matrix\n"; cin>>n; a=new double* [n]; for(i=0;i>a[i][j]; cout< stringified = "\n".join("\t".join(row) for row in a) File "two.py", line 16, in stringified = "\n".join("\t".join(row) for row in a) TypeError: sequence item 0: expected string, float found Thanks in Advance From backgoodoo at gmail.com Wed Aug 11 15:31:17 2010 From: backgoodoo at gmail.com (Back9) Date: Wed, 11 Aug 2010 12:31:17 -0700 (PDT) Subject: most popular gui framework for python Message-ID: Hi, Does anyone know of what is the most popular gui framework for python application? TIA From python at mrabarnett.plus.com Wed Aug 11 15:33:17 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 20:33:17 +0100 Subject: Queue cleanup In-Reply-To: <7xvd7h2d90.fsf@ruckus.brouhaha.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> <7xvd7h2d90.fsf@ruckus.brouhaha.com> Message-ID: <4C62FAFD.1020102@mrabarnett.plus.com> Paul Rubin wrote: > EW writes: >> Well I cared because I thought garbage collection would only happen >> when the script ended - the entire script. Since I plan on running >> this as a service it'll run for months at a time without ending. So I >> thought I was going to have heaps of Queues hanging out in memory, >> unreferenced and unloved. It seemed like bad practice so I wanted to >> get out ahead of it. > > Even if GC worked that way it wouldn't matter, if you use just one queue > per type of task. That number should be a small constant so the memory > consumption is small. That's basically how _non_-garbage-collected languages work! :-) From suranap at gmail.com Wed Aug 11 15:35:48 2010 From: suranap at gmail.com (Pinku Surana) Date: Wed, 11 Aug 2010 12:35:48 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> Message-ID: <13e3dc53-f475-46ad-bd3c-ca023b7b6bcb@c38g2000vba.googlegroups.com> On Aug 11, 12:39?pm, fuglyducky wrote: > On Aug 11, 9:31?am, Pinku Surana wrote: > > > > > > > On Aug 11, 12:07?pm, fuglyducky wrote: > > > > I am a complete newbie to Python (and programming in general) and I > > > have no idea what I'm missing. Below is a script that I am trying to > > > work with and I cannot get it to work. When I call the final print > > > function, nothing prints. However, if I print within the individual > > > functions, I get the appropriate printout. > > > > Am I missing something??? Thanks in advance!!!! > > > > ################################################ > > > # Global variable > > > sample_string = "" > > > > def gen_header(sample_string): > > > ? ? HEADER = """ > > > ? ? mymultilinestringhere > > > ? ? """ > > > > ? ? sample_string += HEADER > > > ? ? return sample_string > > > > def gen_nia(sample_string): > > > ? ? NIA = """ > > > ? ? anothermultilinestringhere > > > ? ? """ > > > > ? ? sample_string += NIA > > > ? ? return sample_string > > > > gen_header(sample_string) > > > gen_nia(sample_string) > > > > print(sample_string) > > > There are 2 problems with your program. > > > (1) If you want to use a global variable in a function, you have to > > add the line "global sample_string" to the beginning of that > > function. > > > (2) Once you do (1), you will get an error because you've got > > sample_string as a global and a function parameter. Which one do you > > want to use in the function? You should change the name of the > > parameter to "sample" to solve that confusion. > > > Here's the result, which works for me: > > > sample_string = "" > > def gen_header(sample): > > ? ? global sample_string > > ? ? HEADER = """ > > ? ? mymultilinestringhere > > ? ? """ > > ? ? sample_string = sample + HEADER > > ? ? return sample_string > > def gen_nia(sample): > > ? ? global sample_string > > ? ? NIA = """ > > ? ? anothermultilinestringhere > > ? ? """ > > ? ? sample_string = sample + NIA > > ? ? return sample_string > > gen_header(sample_string) > > gen_nia(sample_string) > > print(sample_string) > > Thanks! That did the trick. > > I am a bit confused though. I tried to follow a sample in a book > (which works) where I didn't have to 1) pass the global variable as a > parameter into the function, 2) did not have to define the global > variable within the function. I apologize if this is a super stupid > question but if it is global, why do I have to pass it into the > function? Shouldn't the global variable be accessible from anywhere??? Since you're new to programming, it's important to understand the fundamentals. x = 0 # GLOBAL def fun(x): # PARAMETER, a type of LOCAL variable y = 1 # LOCAL x += y # Which x do you mean? The local or global? print x # What is this value? fun(x) print x # What is this value? Even though I used the same name "x" for a local and global variable, they are actually completely different. When I call "fun(x)" it COPIES the global value of "x" into the local variable "x" in "fun". In this code, Python assumes in "x += y" you want to use the LOCAL variable. To Python the code looks like this: x_global = 0 def fun(x_local): y_local = 1 x_local += y_local print x_local fun(x_global) print x_global # This is never changed! If that's not what you want, then you have to explicitly tell Python that you want to use the global value (this is not good programming style, by the way!). That's what the "global" keyword does. Try to write some small programs that pass around numbers and strings with different variable names. Try every combination you can think of until you get good at predicting what the output is. From cmpython at gmail.com Wed Aug 11 15:36:49 2010 From: cmpython at gmail.com (CM) Date: Wed, 11 Aug 2010 12:36:49 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <36998fb7-cbb6-4a10-83a6-f943068a6511@v15g2000yqe.googlegroups.com> On Aug 9, 8:10?am, Alex Barna wrote: > I know that this question has been asked for several times, but it > surprises that there is no tool under very active development and the > community activities are very low (mailing list posts). > > All the tools listed in: > > http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#GUITestingTools > > Comparing with AutoIt (www.autoitscript.com), it has tens to hundreds > of posts everyday. AutoIt uses a proprietary BASIC -like language, and > to be honest, I don't like it and I prefer a Pythonic solution. > > pywinauto seems to be the best choice but the community has been very > low also. The same happens in pyguiunit, pyAA, WATSUP, all development > seem to be ceased. > > So what happens to this field (Windows GUI automation) ? This is a little late, but you might want to check out Sikuli. Search for it in this forum, there is a long thread about it. It might be a new useful way to write GUI tests. I have no real idea, though. Che From usernet at ilthio.net Wed Aug 11 15:38:13 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 19:38:13 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, RG wrote: > In article , > Tim Harig wrote: > >> On 2010-08-11, RG wrote: >> > I'm writing a system in a different language but want to use a Python >> > library. I know of lots of ways to do this (embed a Python interpreter, >> > fire up a python server) but by far the easiest to implement is to have >> > the main program spawn a Python interpreter and interact with it through >> > its stdin/stdout. >> >> Or, open python using a socket. > > You mean a TCP/IP socket? Or a unix domain socket? The former has > security issues, and the latter seems like a lot of work. Or is there > an easy way to do it that I don't know about? I was referring to unix domain sockets or more specifically stream pipes. I guess it depends what language you are using and what libraries you have access to. Under C, working with stream pipes is no more trivial then using pipe(). You can simply create the socket descriptors using socketpair(). Keep one of the descriptors for your process and pass the other to the python child process as both stdin and stdout. From thomas at jollybox.de Wed Aug 11 15:38:47 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 11 Aug 2010 21:38:47 +0200 Subject: Is there a Python equivalent to Perl's File::Listing::parse_dir In-Reply-To: <4c62ead3$0$1587$742ec2ed@news.sonic.net> References: <4c62ead3$0$1587$742ec2ed@news.sonic.net> Message-ID: <201008112138.48097.thomas@jollybox.de> On Wednesday 11 August 2010, it occurred to John Nagle to exclaim: > This is especially useful for FTP sites. It sounds like you're trying to use HTTP to something a lot more easily done with FTP, without any reason not to use FTP. http://docs.python.org/library/ftplib.html#ftplib.FTP.dir From python at mrabarnett.plus.com Wed Aug 11 15:39:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 20:39:32 +0100 Subject: urgent requirement at Hyderabad In-Reply-To: References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Message-ID: <4C62FC74.2040300@mrabarnett.plus.com> Stefan Behnel wrote: > In case anyone wondered: Hyderabad is likely referring to some place in > Asia: > > http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29 > And Berlin is likely some place in Europe: http://en.wikipedia.org/wiki/Berlin_(disambiguation) :-) From ericjvandervelden at gmail.com Wed Aug 11 15:45:07 2010 From: ericjvandervelden at gmail.com (Eric J. Van der Velden) Date: Wed, 11 Aug 2010 12:45:07 -0700 (PDT) Subject: mi Message-ID: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> Hello, I have these types, class A: def __init__(s): super().__init__() print("A") class B(A): def __init__(s): super().__init__() print("B") class C(A): def __init__(s): super().__init__() print("C") class D(B,C): def __init__(s): super().__init__() print("D") If I do (in 3.1) >>> d=D() A C B D Why this order? I thought, first to D, then B, then A. He prints "A". He comes back in B and prints "B". He goes to C. Then somehow he doesn't go again to A. He prints "C". Then back to D and prints "D". Thanks, Eric J. From user at example.net Wed Aug 11 15:47:27 2010 From: user at example.net (J.O. Aho) Date: Wed, 11 Aug 2010 21:47:27 +0200 Subject: most popular gui framework for python In-Reply-To: References: Message-ID: <8cgd2fFjs7U1@mid.individual.net> Back9 wrote: > Does anyone know of what is the most popular gui framework for python > application? Don't think it's the most popular, but I think it may be the one which works for quite a lot of different platforms, PyQt, works fine on my desktop as cellphone. -- //Aho From debatem1 at gmail.com Wed Aug 11 15:51:24 2010 From: debatem1 at gmail.com (geremy condra) Date: Wed, 11 Aug 2010 12:51:24 -0700 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <4c6298c1$0$11101$c3e8da3@news.astraweb.com> Message-ID: On Wed, Aug 11, 2010 at 6:04 AM, Roy Smith wrote: > In article <4c6298c1$0$11101$c3e8da3 at news.astraweb.com>, > ?Steven D'Aprano wrote: > >> Sounds ridiculous, but apparently there are vast hordes of people who can >> barely program "Hello World" applying for programming jobs. One figure >> bandied about -- how accurately, I don't know -- is 199 out of every 200 >> job applicants for programming jobs are barely capable of writing a line >> of code. > > By the same token, there are lots of people with advanced degrees in > computer science who can't code their way out of a paper bag. > > One advantage of the take-home test is that you can prepare the test > once and amortize the preparation cost over many applicants. ?It's a big > investment of time to interview somebody. ?By the time I get up to > investing an hour or so of my time on a phone screen, I'd like to weed > out the obvious rejects as cheaply as possible. > > Even more interesting is to publish some problems on your web site and > instruct applicants to submit a solution to one of them along with their > resume. ?This makes the per-applicant cost to administer the exam > essentially zero. ?It also has the nice side-effect of weeding out the > resume spammers. ?To be honest, I've never done this, but I've seen > companies that do. ?I may try it sometime. I can't recall who it was, but I remember being very impressed by a company that did a variant of this a few years ago: they put programming problems on the sides of pay phones, taxis, etc. with a note that said 'If you can solve this, call us'. I have zero doubt that they got some top talent that way. Geremy Condra From no.email at nospam.invalid Wed Aug 11 16:11:23 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 13:11:23 -0700 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <4c6298c1$0$11101$c3e8da3@news.astraweb.com> Message-ID: <7xfwykoqok.fsf@ruckus.brouhaha.com> geremy condra writes: > I can't recall who it was, but I remember being very impressed by a > company that did a variant of this a few years ago: they put > programming problems on the sides of pay phones, taxis, etc. with a > note that said 'If you can solve this, call us'. I have zero doubt > that they got some top talent that way. Several companies have done that. You might be thinking of ITA Software: http://www.itasoftware.com/careers/puzzle_archive.html From thomas at jollybox.de Wed Aug 11 16:13:29 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 11 Aug 2010 22:13:29 +0200 Subject: most popular gui framework for python In-Reply-To: References: Message-ID: <201008112213.30328.thomas@jollybox.de> On Wednesday 11 August 2010, it occurred to Back9 to exclaim: > Hi, > > Does anyone know of what is the most popular gui framework for python > application? I'd guess at Tkinter - it's part of the standard library. Another quite popular option is PyGtk. Other good ones include wxPython, PyQt, and PySide. From raoulbia at gmail.com Wed Aug 11 16:14:35 2010 From: raoulbia at gmail.com (Baba) Date: Wed, 11 Aug 2010 13:14:35 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 Message-ID: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> level: beginner exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 packs, write an exhaustive search to find the largest number of McNuggets that cannot be bought in exact quantity. exercise source: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf please help me write this code i believe it's something along the lines of this: c=0 sol=[] for n in range (0,10): for a in range (0,10): for b in range (0,10): for c in range (0,10): sol=6*a+9*b+20*c if sol!=n: c+=1 if c==6: print sol From rNOSPAMon at flownet.com Wed Aug 11 16:20:59 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 13:20:59 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , Tim Harig wrote: > On 2010-08-11, RG wrote: > > In article , > > Tim Harig wrote: > > > >> On 2010-08-11, RG wrote: > >> > I'm writing a system in a different language but want to use a Python > >> > library. I know of lots of ways to do this (embed a Python interpreter, > >> > fire up a python server) but by far the easiest to implement is to have > >> > the main program spawn a Python interpreter and interact with it through > >> > its stdin/stdout. > >> > >> Or, open python using a socket. > > > > You mean a TCP/IP socket? Or a unix domain socket? The former has > > security issues, and the latter seems like a lot of work. Or is there > > an easy way to do it that I don't know about? > > I was referring to unix domain sockets or more specifically stream > pipes. I guess it depends what language you are using and what libraries > you have access to. Under C, working with stream pipes is no more trivial > then using pipe(). You can simply create the socket descriptors using > socketpair(). Keep one of the descriptors for your process and pass the > other to the python child process as both stdin and stdout. Ah. That is in fact exactly what I am doing, and that is how I first encountered this problem. rg From thomas at jollybox.de Wed Aug 11 16:24:35 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 11 Aug 2010 22:24:35 +0200 Subject: mi In-Reply-To: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> References: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> Message-ID: <201008112224.35960.thomas@jollybox.de> On Wednesday 11 August 2010, it occurred to Eric J. Van der Velden to exclaim: > Hello, > > I have these types, > > class A: > def __init__(s): > super().__init__() > print("A") > class B(A): > def __init__(s): > super().__init__() > print("B") > class C(A): > def __init__(s): > super().__init__() > print("C") > class D(B,C): > def __init__(s): > super().__init__() > print("D") > > If I do (in 3.1) > > >>> d=D() > > A > C > B > D > > Why this order? I thought, first to D, then B, then A. He prints "A". > He comes back in B and prints "B". He goes to C. Then somehow he > doesn't go again to A. He prints "C". Then back to D and prints "D". Think again about what you're seeing here. You're printing AFTER the call to super().__init__(). That means that it first walks the inheritance hierarchy, and then prints -- your trace is "the wrong way around" So, what happens is: you call D(). In it, super() delegates to B(). Which has super delegate to C(), which then has super() delegate finally to A(). D, B, C, A You say you were expecting D, B, A -- but what of C? You also imply that you would have expected two visits to A -- but that would defeat the point of super() -- you don't actually want one constructor to be called twice: the constructor almost certainly isn't written with that possibility in mind. > > Thanks, > > Eric J. From ericwoodworth at gmail.com Wed Aug 11 16:26:43 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 13:26:43 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> <7xvd7h2d90.fsf@ruckus.brouhaha.com> Message-ID: <9b270554-e7cb-48ec-aa0e-c78690a81b54@q26g2000vbn.googlegroups.com> On Aug 11, 2:52?pm, Paul Rubin wrote: > EW writes: > > Well I cared because I thought garbage collection would only happen > > when the script ended - the entire script. ?Since I plan on running > > this as a service it'll run for months at a time without ending. ?So I > > thought I was going to have heaps of Queues hanging out in memory, > > unreferenced and unloved. ?It seemed like bad practice so I wanted to > > get out ahead of it. > > Even if GC worked that way it wouldn't matter, if you use just one queue > per type of task. ?That number should be a small constant so the memory > consumption is small. Well I can't really explain it but 1 Queue per task for what I'm designing just doesn't feel right to me. It feels like it will lack future flexibility. I like having 1 Queue per producer thread object and the person instantiating that object can do whatever he wants with that Queue. I can't prove I'll need that level of flexibility but I don't see why it' bad to have. It's still a small number of Queues, it's just a small, variable, number of Queues. From news1234 at free.fr Wed Aug 11 16:48:26 2010 From: news1234 at free.fr (News123) Date: Wed, 11 Aug 2010 22:48:26 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4c630c9a$0$5445$426a74cc@news.free.fr> As said in the instructions. if you find six consecutive numbers, that can be bough in exact quantity, then you know, that all bigger numbers can also be bought in exact quantity. I would do a brute force approach first I would create one function, which will try to find out, whether one can buy an exact quantity of n nuggets. example function prototype def can_buy(n_nuggets): # here you have to write your code the function should return True or if you're curious a list of packages and quantities if quantity n_nuggets can be bought otherwise it should return False or an empty list. then you can create another function which will start with 6 nuggets (or if you like to with 1 nugget) and which will count how many times in sequence it managed to return a result. (by using the function can_buy() and managibng a counter) If it found 6 results in sequence, then you know, that all bigger numbers can also be bought and that the biggest number, which could not be bought was 6 numbers before. I think nobody here will write the soultion for you. If you write some more code and if you tell us what it's supposed to to and with what exectly you're having trouble with I can give you more hints. On 08/11/2010 10:14 PM, Baba wrote: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf > > please help me write this code > > i believe it's something along the lines of this: > > c=0 > sol=[] > for n in range (0,10): > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print sol Not very modular. > c=0 # c could have a meaningful name and probably a different one > # it seems, that you reuse c also in a for statement > sol=[] > for n in range (0,10): # n should not only go from 0 to 10 > # but from 0 until c is 6 # i'd put this in a separate function it makes it also easier for # you to understand and test > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): # c used here and lso as counter > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print "solution is",sol-6 > From peter.milliken at gmail.com Wed Aug 11 17:02:28 2010 From: peter.milliken at gmail.com (Peter) Date: Wed, 11 Aug 2010 14:02:28 -0700 (PDT) Subject: most popular gui framework for python References: Message-ID: <4b19ddc3-129d-40fc-b82f-41211f6105fa@s17g2000prh.googlegroups.com> On Aug 12, 6:13?am, Thomas Jollans wrote: > On Wednesday 11 August 2010, it occurred to Back9 to exclaim: > > > Hi, > > > Does anyone know of what is the most popular gui framework for python > > application? > > I'd guess at Tkinter - it's part of the standard library. > Another quite popular option is PyGtk. Other good ones include wxPython, PyQt, > and PySide. Lots of choices - you could try Jython as well, then you have access to all the Java GUI framework :-) Personally, I have used Tkinter, PMW (Widgets built on Tkinter) - all of my GUI stuff to date is written using these. I have tried WxPython - I found it quite difficult to learn, but this was quite some years ago now and perhaps there are some easy books that will help you ease into it. I am currently experimenting with PyQt - I have Mark Summerfield's book, "Rapid GUI Programming with Python and Qt" - very readable book. Now that the Qt license is more friendly to the "hobbyist" I think I will switch all of my GUI work over to PyQt. There are so many these days (just look at the Python wiki page on GUIs) that you can't really try them all - just not enough hours in the day. I would suggest you have a quick browse of what's available and then select one or two to focus on. Most are pretty well "portable" between multiple platforms - but realistically I have never used anything other than a Windoze platform cross-platform compatibility may not be such a big deal. I would strongly recommend reading the Python Wiki page on GUI programming: http://wiki.python.org/moin/GuiProgramming Peter From rNOSPAMon at flownet.com Wed Aug 11 17:07:27 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 14:07:27 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , RG wrote: > In article , > Tim Harig wrote: > > > On 2010-08-11, RG wrote: > > > In article , > > > Tim Harig wrote: > > > > > >> On 2010-08-11, RG wrote: > > >> > I'm writing a system in a different language but want to use a Python > > >> > library. I know of lots of ways to do this (embed a Python > > >> > interpreter, > > >> > fire up a python server) but by far the easiest to implement is to > > >> > have > > >> > the main program spawn a Python interpreter and interact with it > > >> > through > > >> > its stdin/stdout. > > >> > > >> Or, open python using a socket. > > > > > > You mean a TCP/IP socket? Or a unix domain socket? The former has > > > security issues, and the latter seems like a lot of work. Or is there > > > an easy way to do it that I don't know about? > > > > I was referring to unix domain sockets or more specifically stream > > pipes. I guess it depends what language you are using and what libraries > > you have access to. Under C, working with stream pipes is no more trivial > > then using pipe(). You can simply create the socket descriptors using > > socketpair(). Keep one of the descriptors for your process and pass the > > other to the python child process as both stdin and stdout. > > Ah. That is in fact exactly what I am doing, and that is how I first > encountered this problem. > > rg And now I have encountered another problem: -> print sys.stdin.encoding <- None But when I run from a terminal: [ron at mickey:~]$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'UTF-8' I thought the value of sys.stdin.encoding was hard-coded into the Python executable at compile time, but that's obviously wrong. So how does Python get the value of sys.stdin.encoding? rg From clp2 at rebertia.com Wed Aug 11 17:09:57 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 11 Aug 2010 14:09:57 -0700 Subject: mi In-Reply-To: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> References: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> Message-ID: On Wed, Aug 11, 2010 at 12:45 PM, Eric J. Van der Velden wrote: > Hello, > > I have these types, > > class A: > ? ? ? ?def __init__(s): > ? ? ? ? ? ? ? ?super().__init__() > ? ? ? ? ? ? ? ?print("A") > class B(A): > ? ? ? ?def __init__(s): > ? ? ? ? ? ? ? ?super().__init__() > ? ? ? ? ? ? ? ?print("B") > class C(A): > ? ? ? ?def __init__(s): > ? ? ? ? ? ? ? ?super().__init__() > ? ? ? ? ? ? ? ?print("C") > class D(B,C): > ? ? ? ?def __init__(s): > ? ? ? ? ? ? ? ?super().__init__() > ? ? ? ? ? ? ? ?print("D") > > If I do (in 3.1) >>>> d=D() > A > C > B > D > > Why this order? Well, it's clearer for illustration purposes if you do the print()s "preorder" (before the super calls) rather than "postorder", but anyway... Because that's how Python's Method Resolution Order (MRO) works. Very smart people have thought a lot about this. It is The Right Order (tm). To understand *why* it's right, read: http://www.python.org/download/releases/2.2.3/descrintro/#mro and (if you dare): http://www.python.org/download/releases/2.3/mro/ The order (of the method calls, not the print()s) is (extremely roughly) from most derived to most ancestral, without calling anything twice. Is that not a logical and sensible (albeit not necessarily obvious) rule? > I thought, first to D, then B, then A. He prints "A". > He comes back in B and prints "B". He goes to C. Then somehow he > doesn't go again to A. He prints "C". Then back to D and prints "D". "super()" is a bit of a misnomer. **It doesn't necessarily call a superclass method.** In fact, the Dylan programming language (which Python borrowed its MRO from) instead names the analogous function "next-method" because it calls the method that comes after the current one in the MRO. Here's what actually happened: D called B. Then B called *C* (seems bizarre, yes). C is obviously not a superclass of B; but this is the only way to make things work out right (see aforelinked docs). From there, C called A, and the rest is obvious. Multiple inheritance can get tricky; avoid it when possible. Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Wed Aug 11 17:13:04 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 11 Aug 2010 14:13:04 -0700 Subject: How to input values of the matrix from keyboard in python In-Reply-To: References: Message-ID: On Wed, Aug 11, 2010 at 12:06 PM, Chris Rebert wrote: > On Wed, Aug 11, 2010 at 11:43 AM, Pramod wrote: >> Hi >> >> ? I want to know the how we input values into the matrix (N*N size) >> from keyboard in python, >> >> Here I wrote Matrix programe in C++ >> >> This ?asks values from key board and print on the console N*N matrix ; >> >> Thanks in advance .... >> >> >> #include >> using namespace std; >> int main() >> { >> ? ? ? ?double **a; >> ? ? ? ?int i,j,n; >> ? ? ? ?cout<<"Enter size of the matrix\n"; >> ? ? ? ?cin>>n; >> ? ? ? ? ? ? ? ?for(i=0;i> ? ? ? ? ? ? ? ?for(j=0;j> ? ? ? ? ? ? ? ? ? ? ? ?a[i][j] = random(); >> //or >> ? ? ? ? ? ? ? ?//cin>>a[i][j]; >> ? ? ? ? ? ? ? ?cout<> ? ? ? ?} >> ? ? ? ?for(i=0;i> ? ? ? ? ? ? ? ?for(j=0;j> ? ? ? ? ? ? ? ? ? ? ? ?cout<> ? ? ? ? ? ? ? ?cout<> ? ? ? ?} >> ? ? ? ?delete [] a; >> } > > from random import random > from sys import exit > > while True: > ? ?try: > ? ? ? ?N = int(raw_input("Enter size of the matrix: ")) > ? ?except ValueError: > ? ? ? ?print "Invalid input. Try again." > ? ?except EOFError: > ? ? ? ?exit(1) > ? ?else: > ? ? ? ?break > > a = [[random() for j in xrange(N)] for i in xrange(N)] > stringified = "\n".join("\t".join(row) for row in a) > print stringified Should have prefaced that with an "untested" disclaimer. Make that: stringified = "\n".join("\t".join(str(cell) for cell in row) for row in a) - Chris From peter.milliken at gmail.com Wed Aug 11 17:14:42 2010 From: peter.milliken at gmail.com (Peter) Date: Wed, 11 Aug 2010 14:14:42 -0700 (PDT) Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: On Aug 11, 8:50?pm, Tim Chase wrote: > On 08/11/10 01:24, Terry Reedy wrote: > > > On 8/10/2010 8:08 PM, Roy Smith wrote: > >> In any case, if the candidate were to submit somebody else's > >> work, it would come out pretty quickly as we discussed their > >> code. ?I suppose one question I might ask would be, "Can you > >> explain why, when I copy-paste one of your comments into a > >> google search box, your entire program appears?" > > > Mostly likely because I wrote the original... > > > would be my answer. > > Unfortunately there are candidates who would give your answer but > then have trouble with "Then why are the Last-Modified HTTP > headers showing a date several months before our interview?" > It's as bad as the phone-interviews I've done where in the > background I can hear the person on the other end typing my > questions into a search box and reading off answers. ?On the > bright side, those are short interviews... ;-) > > -tkc I know we are straying somewhat here :-) But as an interviewer way back when in the never-never, I used to look at the interviewee's work history i.e. 18 months here, 12 months there, 6 months here etc and pretty much wipe them from my short-list based on that alone :-) Because it takes at least 3 months for a programmer to get "up to speed" fitting into your company and on your applications, they are usually only really productive and really "hitting their stride" at 6 months - somebody who "job hops" will already be looking for the next job by that time! I really did't have time to waste on these people - then there was the agents fee for finding them for you - big investment for zero return. So I would recommend to anybody that they attempt to maintain a stable work history in this respect. For example, my personal work history is 8, 7.5, 8.5, 0.5, 3, 3, 8 (years that is). My current company is extremely stable, I enjoy the work, so I don't see any reason why I won't be here until I retire (or die at my desk - whichever comes first :-)). Peter From thomas at jollybox.de Wed Aug 11 17:15:45 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 11 Aug 2010 23:15:45 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <201008112315.45841.thomas@jollybox.de> On Wednesday 11 August 2010, it occurred to Baba to exclaim: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. The MacDonald's at Nuremberg central station once sold me 25 in a 20-pack. So this won't work. > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00 > -introduction-to-computer-science-and-programming-fall-2008/assignments/pse > t2.pdf > > please help me write this code > > i believe it's something along the lines of this: > > c=0 > sol=[] > for n in range (0,10): > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print sol From emile at fenx.com Wed Aug 11 17:25:08 2010 From: emile at fenx.com (Emile van Sebille) Date: Wed, 11 Aug 2010 14:25:08 -0700 Subject: urgent requirement at Hyderabad In-Reply-To: <4C62FC74.2040300@mrabarnett.plus.com> References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> <4C62FC74.2040300@mrabarnett.plus.com> Message-ID: On 8/11/2010 12:39 PM MRAB said... > Stefan Behnel wrote: >> In case anyone wondered: Hyderabad is likely referring to some place >> in Asia: >> >> http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29 >> > And Berlin is likely some place in Europe: > > http://en.wikipedia.org/wiki/Berlin_(disambiguation) > > :-) And Paris is likely someplace in the US... http://en.wikipedia.org/wiki/Paris_%28disambiguation%29 Emile :)) From tormod.hagen at gmail.com Wed Aug 11 17:29:24 2010 From: tormod.hagen at gmail.com (tormod) Date: Wed, 11 Aug 2010 14:29:24 -0700 (PDT) Subject: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT) Message-ID: Hi, I've tried countless times to build & install cx_Oracle on Python 3.1.2, and failed every time, so I'd like to ask someone for help. I've included step-by-step (literally) description of my last try, with so much detail I could, to help clarify things. I can build without errors. I can install without errors. I fail to import. I'm using an NT box (os:Win7) Downloaded Oracle Instant Client 10.2.0.4 instantclient-basic-win32-10.2.0.4.zip --> extracted to C:\TEMP \ORAIC10\bin instantclient-sdk-win32-10.2.0.4.zip --> extracted to C:\TEMP \ORAIC10\sdk Downloaded source code(cx_Oracle-5.0.4.tar.gz) from http://cx-oracle.sourceforge.net/ --> extracted to C:\TEMP\Python\cx_Oracle Installed Python 3.1.2 --> C:\Python31 Installed MinGW 5.1.6 --> C:\MinGW Startet command prompt: cd C:\TEMP\Python\cx_Oracle PATH=%PATH%;C:\Python31;C:\MinGW\bin;C:\TEMP\ORAIC10\bin SET ORACLE_HOME=C:\TEMP\ORAIC10 SET LD_LIBRARY_PATH=C:\TEMP\ORAIC10\sdk\lib python setup.py build -c mingw32 python setup.py install start python: Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import cx_Oracle Traceback (most recent call last): File "", line 1, in ImportError: DLL load failed: The specified module could not be found. running build running build_ext building 'cx_Oracle' extension creating build creating build\temp.win32-3.1-10g creating build\temp.win32-3.1-10g\Release C:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\TEMP\ORAIC10\sdk \include -I C:\Python31\include -IC:\Python31\PC -c cx_Oracle.c -o build \temp.win32-3.1-10g\ Release\cx_oracle.o -DBUILD_VERSION=5.0.4 -DWITH_UNICODE writing build\temp.win32-3.1-10g\Release\cx_Oracle.def creating build\lib.win32-3.1-10g C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-3.1-10g \Release\cx_ oracle.o build\temp.win32-3.1-10g\Release\cx_Oracle.def -LC:\TEMP \ORAIC10\bin -L C:\TEMP\ORAIC10 -LC:\TEMP\ORAIC10\oci\lib\msvc -LC:\TEMP\ORAIC10\sdk \lib\msvc -L C:\Python31\libs -LC:\Python31\PCbuild -loci -lpython31 -lmsvcr90 -o build\lib.w in32-3.1-10g\cx_Oracle.pyd running install running build running build_ext running install_lib copying build\lib.win32-3.1-10g\cx_Oracle.pyd -> C:\Python31\Lib\site- packages running install_data running install_egg_info Removing C:\Python31\Lib\site-packages\cx_Oracle-5.0.4-py3.1.egg-info Writing C:\Python31\Lib\site-packages\cx_Oracle-5.0.4-py3.1.egg-info I've opened the cx_Oracle.pyd with Dependency Walker (http:// www.dependencywalker.com/) and DW reports it can't find: OCI.DLL, PYTHON31.DLL, MSVCR90.DLL (why?) Appreciate any help, even wildshots and 2 cents are welcome - I'll try everything. Cheers, Tom From no.email at nospam.invalid Wed Aug 11 17:38:50 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 14:38:50 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> <7xvd7h2d90.fsf@ruckus.brouhaha.com> <9b270554-e7cb-48ec-aa0e-c78690a81b54@q26g2000vbn.googlegroups.com> Message-ID: <7x4of0n82d.fsf@ruckus.brouhaha.com> EW writes: > Well I can't really explain it but 1 Queue per task for what I'm > designing just doesn't feel right to me. It feels like it will lack > future flexibility. That makes no sense at all. Multiple readers and writers per queue are the way Python queues are designed to work. The normal way to spray a bunch of concurrent tasks to worker threads is just have a bunch of workers listening to one queue. It's the same way at the producer end. From cs at zip.com.au Wed Aug 11 18:12:49 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 12 Aug 2010 08:12:49 +1000 Subject: Line-by-line processing when stdin is not a tty In-Reply-To: References: Message-ID: <20100811221249.GA3087@cskk.homeip.net> On 11Aug2010 12:35, Tim Harig wrote: | > The buffering is a performance choice. Every write requires a context | > switch from userspace to kernel space, and availability of data in the | > pipe will wake up a downstream process blocked trying to read. | > It is far more efficient to do as few such copies as possible, [...] | | Right, I don't question the optimization. I question whether the | intelligence that performes that optimation should be placed within cat or | whether it should be placed within the shell. It seems to me that the | shell has a better idea of how the command is being used and can therefore | make a better decision about whether or not buffering is appropriate. I would argue it's not much better placed, though it would be nice if the control could be issued from there. But it can't. Regarding the former, in this pipeline: cat some files... | python filter program | something else how shall the shell know if the python filter (to take the OP's case) wants its input line buffered (rare) or block buffered (usually ok)? What might be useful would be a way to attach an attribute to a pipe or other file descriptor indicating the desired buffering behaviour that writers to the file descriptor should adopt. Of course, the ugly sides to that are how many buffering regimes should it be possible to express and how and when should the upstream (writing) program decide to check? In a pipeline the pipes are made _before_ any of the programs commence because the programs need to be attached to the pipes (this is done before the programs themselves are dispatched). So, _after_ dispatch the python-wanting-line-buffering issues an ioctl on the pipe saying "I want line buffering". However, the upstream program may well already have commenced operation before that happens. It may even have run to completion before that happens! So, shall all upstream programs be required to poll? How often? On every write? Shall they receive a signal? What if they don't catch it? If the downstream program _requires_ line buffering then the whole situation is racey and unreliable. You can see that on reflection this isn't easy to resolve cleanly from _outside_ the writing program. To do it from inside requires all programs to sprout an option like GNU cat's -u option. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ What progress we are making. In the Middle Ages they would have burned me. Now they are content with burning my books. - Sigmund Freud From alex.lavoro.propio at gmail.com Wed Aug 11 18:45:44 2010 From: alex.lavoro.propio at gmail.com (Alex Barna) Date: Wed, 11 Aug 2010 15:45:44 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c628934$0$11101$c3e8da3@news.astraweb.com> Message-ID: <605127db-07d8-40e0-bef5-ad441d2b2605@x21g2000yqa.googlegroups.com> I'm afraid that my first post has not been understood correctly and most of the following posts are OT, as Ben Finney indicated. The GUI automation has a long history, perhaps since the first windowing system was invented. For years I've been doing this using several different technologies/languages. But to my surprise, this ares is not very *cultivated* by Pythonistas. Many projects (see the link in my first post) have lost the love of their maintainers and have not been updated for years. Except one, pywinauto, which has a recent release in April. However, the community activity (mailing list) is very low, website and documentation have not been updated for long also. All this freaks me out on adopting a technology like this : - is there still anyone using it ? - what if I encounter a problem but no body replies me in the mailing list ? Comparing with the rival AutoIt, using a BASIC-like language, which I don't like at all, has hundreads of post in the users' forum everyday. It makes me doubt: is Python the correct language to do GUI automation ? P.S.: hopefully it has been clarified, my original intention of the post is not to debate/discuss: - *why* automating GUI ? - whether GUI/CLI is better. - the points GUI or CLI is designed for. Obvious they are all OT. Alex Barna. From gelonida at gmail.com Wed Aug 11 19:07:25 2010 From: gelonida at gmail.com (Gelonida) Date: Thu, 12 Aug 2010 01:07:25 +0200 Subject: segfault with small pyqt script Message-ID: Hi Guys, I'm desperate. I'm having a real application, which fails rather often when finishing it. I'm not sure, whether any serious problem could be hidden behind it The script is a pyqt script, which segfaults most of the time on my ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. Trying to create the smallest possible test case I ended up with following script, which I named dodo.py and which i made executable with chmod +x ./dodo.py #!/usr/bin/env python from PyQt4.QtGui import QDialog,QGridLayout,QLabel,QComboBox,QPushButton,QApplication a = "one" b = "unused" c = "also unused" d= "ans also unused" e = "another var" f = "something" class MyForm(QDialog): def __init__(self,parent=None,config=None,ini_info=None): super(MyForm,self).__init__(parent=parent) grid = QGridLayout() quit_btn = QPushButton("Quit") quit_btn.clicked.connect(self.quit) grid.addWidget(quit_btn,0,0) name = "a_name" vals_box = QComboBox() vals_box.addItem("one") vals_box.addItem("two") grid.addWidget(vals_box,0,1) self.setLayout(grid) def quit(self): self.close() if __name__ == "__main__": app = QApplication([]) myform = MyForm() myform.show() retcode = app.exec_() print "last" In order to perform the test several times I typed on the command line: a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done As soon as the window shows up I click twice (slowly ) on 'one' and then on quit. Sample output can be seen here: gelonida at mypc:/my/directory$ a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done last last Segmentation fault last last Segmentation fault last Segmentation fault last Segmentation fault last last last last last Segmentation fault last last Segmentation fault last Segmentation fault as you see the segfault happens rather often. Does anybody see something suspicious with my code? Can anybody else reproduce this? as soon as I remove more lines the error seems to disappear. What else could I do to debug this issue? thanks for help or other ideas If I run my script with strace ./dodo.py I get following last lines for a run without error > rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f65d6b3b8f0}, {0x4d9820, [], SA_RESTORER, 0x7f65d6b3b8f0}, 8) = 0 > munmap(0x7f65c6344000, 622280) = 0 > brk(0x2d71000) = 0x2d71000 > poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLIN|POLLOUT}]) > read(7, "\22\0\233\6\2\0\300\5\2\0\300\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 384 > writev(7, [{"\232\7\2\0\210\0\300\0056\0\2\0\207\0\300\5<\0\2\0\211\0\300\5\232\7\2\0s\0\300\5"..., 540}, {NULL, 0}, {"", 0}], 3) = 540 > poll([{fd=7, events=POLLIN}], 1, -1) = 1 ([{fd=7, revents=POLLIN}]) > read(7, "\34\0\241\6r\0\300\5\234\1\0\0\377\261\220\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 1472 > read(7, 0x29fa704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}]) > writev(7, [{"O\7\2\0\1\0\300\5<\0\2\0\0\0\300\5+\0\1\0", 20}, {NULL, 0}, {"", 0}], 3) = 20 > poll([{fd=7, events=POLLIN}], 1, -1) = 1 ([{fd=7, revents=POLLIN}]) > read(7, "\1\2\333\6\0\0\0\0\5\0\300\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 4096) = 32 > read(7, 0x29fa704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > close(7) = 0 > write(19, "\1\v\3\200\1\0\0\0\0\0\0\0\t\0\0\0", 16) = 16 > close(19) = 0 > open("/proc/stat", O_RDONLY|O_CLOEXEC) = 7 > read(7, "cpu 59482 54 13580 7506040 4761"..., 8192) = 2439 > close(7) = 0 > writev(15, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12 > close(15) = 0 > writev(13, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12 > close(13) = 0 > close(12) = 0 > close(11) = 0 > unlink("/tmp/orbit-klausf/linc-1282-0-6094bc6991603") = 0 > close(14) = 0 > write(6, "@", 1) = 1 > close(6) = 0 > close(5) = 0 > rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_NOCLDSTOP, 0x7f65d6b3b8f0}, {0x7f65d40a3860, [], SA_RESTORER|SA_NOCLDSTOP, 0x7f65d6b3b8f0}, 8) = 0 > exit_group(0) and following when an error occurs: > writev(16, [{"<\10\2\0;\6\340\5F\6\5\0!\6\340\5\10\0\340\5\0\0\0\0U\0\33\0\232\7\2\0"..., 16380}, {NULL, 0}, {"", 0}], 3) = 16380 > read(16, 0xbc49d4, 4096) = -1 EAGAIN (Resource temporarily unavailable) > poll([{fd=16, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=16, revents=POLLOUT}]) > writev(16, [{"\232\10\t\0\3\6\340\5R\6\340\5C\6\340\5=\6\340\5\0\0\0\0\0\0\0\0\2\0\2\0"..., 4256}, {NULL, 0}, {"", 0}], 3) = 4256 > poll([{fd=16, events=POLLIN}], 1, -1) = 1 ([{fd=16, revents=POLLIN}]) > read(16, "\16\0\317\26s\0\340\5\0\0>\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 64 > read(16, 0xbc49d4, 4096) = -1 EAGAIN (Resource temporarily unavailable) > poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}]) > writev(7, [{"7\0\4\0\25\1\300\5\v\0\300\5\0\0\0\0007\1\4\0\26\1\300\5\v\0\300\5\0\0\0\0"..., 9940}, {NULL, 0}, {"", 0}], 3) = 9940 > read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > poll([{fd=3, events=POLLIN}, {fd=11, events=POLLIN|POLLPRI}, {fd=13, events=POLLIN|POLLPRI}, {fd=14, events=POLLIN|POLLPRI}, {fd=15, events=POLLIN|POLLPRI}, {fd=16, events=POLLIN}, {fd=17, events=POLLIN}, {fd=18, events=POLLIN}, {fd=19, events=POLLIN}, {fd=7, events=POLLIN}], 10, 0) = 0 (Timeout) > read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 > mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb00bc75000 > write(1, "last\n", 5last > ) = 5 > rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7fb0124088f0}, {0x4d9820, [], SA_RESTORER, 0x7fb0124088f0}, 8) = 0 > --- SIGSEGV (Segmentation fault) @ 0 (0) --- > +++ killed by SIGSEGV +++ > Segmentation fault thanks a lot for any ideas or explanations From gelonida at gmail.com Wed Aug 11 19:14:26 2010 From: gelonida at gmail.com (Gelonida) Date: Thu, 12 Aug 2010 01:14:26 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: Jusy FYI: I made further tests and can crash the python script even if I delete the linesassigning strings to variables a to f On 08/12/2010 01:07 AM, Gelonida wrote: > Hi Guys, > I'm desperate. I'm having a real application, which fails rather often > when finishing it. I'm not sure, whether any serious problem could be > hidden behind it > > The script is a pyqt script, which segfaults most of the time on my > ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. > > Trying to create the smallest possible test case I ended up with > following script, which I named dodo.py and which i made executable with > chmod +x ./dodo.py > > #!/usr/bin/env python > from PyQt4.QtGui import > QDialog,QGridLayout,QLabel,QComboBox,QPushButton,QApplication > a = "one" > b = "unused" > c = "also unused" > d= "ans also unused" > e = "another var" > f = "something" > class MyForm(QDialog): > def __init__(self,parent=None,config=None,ini_info=None): > super(MyForm,self).__init__(parent=parent) > grid = QGridLayout() > quit_btn = QPushButton("Quit") > quit_btn.clicked.connect(self.quit) > grid.addWidget(quit_btn,0,0) > name = "a_name" > vals_box = QComboBox() > vals_box.addItem("one") > vals_box.addItem("two") > grid.addWidget(vals_box,0,1) > self.setLayout(grid) > def quit(self): > self.close() > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > print "last" > > > > In order to perform the test several times I typed on the command line: > > a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done > > As soon as the window shows up > I click twice (slowly ) on 'one' and then on quit. > > Sample output can be seen here: > gelonida at mypc:/my/directory$ a="" ; while [ "$a" = "" ] ; do ./dodo.py ; > read -t 1 a ; done > last > last > Segmentation fault > last > last > Segmentation fault > last > Segmentation fault > last > Segmentation fault > last > last > last > last > last > Segmentation fault > last > last > Segmentation fault > last > Segmentation fault > > > as you see the segfault happens rather often. > > Does anybody see something suspicious with my code? > Can anybody else reproduce this? > as soon as I remove more lines the error seems to disappear. > > What else could I do to debug this issue? > > thanks for help or other ideas > > > > If I run my script with strace ./dodo.py > I get following last lines for a run without error >> rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f65d6b3b8f0}, {0x4d9820, [], SA_RESTORER, 0x7f65d6b3b8f0}, 8) = 0 >> munmap(0x7f65c6344000, 622280) = 0 >> brk(0x2d71000) = 0x2d71000 >> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLIN|POLLOUT}]) >> read(7, "\22\0\233\6\2\0\300\5\2\0\300\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 384 >> writev(7, [{"\232\7\2\0\210\0\300\0056\0\2\0\207\0\300\5<\0\2\0\211\0\300\5\232\7\2\0s\0\300\5"..., 540}, {NULL, 0}, {"", 0}], 3) = 540 >> poll([{fd=7, events=POLLIN}], 1, -1) = 1 ([{fd=7, revents=POLLIN}]) >> read(7, "\34\0\241\6r\0\300\5\234\1\0\0\377\261\220\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 1472 >> read(7, 0x29fa704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}]) >> writev(7, [{"O\7\2\0\1\0\300\5<\0\2\0\0\0\300\5+\0\1\0", 20}, {NULL, 0}, {"", 0}], 3) = 20 >> poll([{fd=7, events=POLLIN}], 1, -1) = 1 ([{fd=7, revents=POLLIN}]) >> read(7, "\1\2\333\6\0\0\0\0\5\0\300\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 4096) = 32 >> read(7, 0x29fa704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> close(7) = 0 >> write(19, "\1\v\3\200\1\0\0\0\0\0\0\0\t\0\0\0", 16) = 16 >> close(19) = 0 >> open("/proc/stat", O_RDONLY|O_CLOEXEC) = 7 >> read(7, "cpu 59482 54 13580 7506040 4761"..., 8192) = 2439 >> close(7) = 0 >> writev(15, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12 >> close(15) = 0 >> writev(13, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12 >> close(13) = 0 >> close(12) = 0 >> close(11) = 0 >> unlink("/tmp/orbit-klausf/linc-1282-0-6094bc6991603") = 0 >> close(14) = 0 >> write(6, "@", 1) = 1 >> close(6) = 0 >> close(5) = 0 >> rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_NOCLDSTOP, 0x7f65d6b3b8f0}, {0x7f65d40a3860, [], SA_RESTORER|SA_NOCLDSTOP, 0x7f65d6b3b8f0}, 8) = 0 >> exit_group(0) > > > and following when an error occurs: >> writev(16, [{"<\10\2\0;\6\340\5F\6\5\0!\6\340\5\10\0\340\5\0\0\0\0U\0\33\0\232\7\2\0"..., 16380}, {NULL, 0}, {"", 0}], 3) = 16380 >> read(16, 0xbc49d4, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> poll([{fd=16, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=16, revents=POLLOUT}]) >> writev(16, [{"\232\10\t\0\3\6\340\5R\6\340\5C\6\340\5=\6\340\5\0\0\0\0\0\0\0\0\2\0\2\0"..., 4256}, {NULL, 0}, {"", 0}], 3) = 4256 >> poll([{fd=16, events=POLLIN}], 1, -1) = 1 ([{fd=16, revents=POLLIN}]) >> read(16, "\16\0\317\26s\0\340\5\0\0>\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 64 >> read(16, 0xbc49d4, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}]) >> writev(7, [{"7\0\4\0\25\1\300\5\v\0\300\5\0\0\0\0007\1\4\0\26\1\300\5\v\0\300\5\0\0\0\0"..., 9940}, {NULL, 0}, {"", 0}], 3) = 9940 >> read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> poll([{fd=3, events=POLLIN}, {fd=11, events=POLLIN|POLLPRI}, {fd=13, events=POLLIN|POLLPRI}, {fd=14, events=POLLIN|POLLPRI}, {fd=15, events=POLLIN|POLLPRI}, {fd=16, events=POLLIN}, {fd=17, events=POLLIN}, {fd=18, events=POLLIN}, {fd=19, events=POLLIN}, {fd=7, events=POLLIN}], 10, 0) = 0 (Timeout) >> read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 >> mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb00bc75000 >> write(1, "last\n", 5last >> ) = 5 >> rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7fb0124088f0}, {0x4d9820, [], SA_RESTORER, 0x7fb0124088f0}, 8) = 0 >> --- SIGSEGV (Segmentation fault) @ 0 (0) --- >> +++ killed by SIGSEGV +++ >> Segmentation fault > > > > > thanks a lot for any ideas or explanations > > > > > > From giacomo.boffi at polimi.it Wed Aug 11 19:24:34 2010 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Thu, 12 Aug 2010 01:24:34 +0200 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? References: <4C5F992A.4040606@v.loewis.de> Message-ID: <86fwyk3f7x.fsf@aiuole.stru.polimi.it> "Martin v. Loewis" writes: > If you use the bdist_wininst, bdist_msi, or bdist_rpm distutils > commands, you get packages which support uninstallations very well. bdist_deb? -- Vorrei andare a lavorare in Sicilia, a max 15 km dal mare. Con chi devo parlare? Col capomafia distrettuale? Oppure bisogna sporcarsi le mani e fare la tessera di FI? -- Marvin, in IFQ From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 19:37:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 23:37:01 GMT Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4c63341c$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 > packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. Is this a trick question? I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) McNuggets. And that's not even close to the largest number that you can't buy. Unhelpfully yours, -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 19:42:24 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 23:42:24 GMT Subject: urgent requirement at Hyderabad References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> <4C62FC74.2040300@mrabarnett.plus.com> Message-ID: <4c633560$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 14:25:08 -0700, Emile van Sebille wrote: > On 8/11/2010 12:39 PM MRAB said... >> Stefan Behnel wrote: >>> In case anyone wondered: Hyderabad is likely referring to some place >>> in Asia: >>> >>> http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29 >>> >> And Berlin is likely some place in Europe: >> >> http://en.wikipedia.org/wiki/Berlin_(disambiguation) >> >> :-) > > And Paris is likely someplace in the US... > > http://en.wikipedia.org/wiki/Paris_%28disambiguation%29 No, I'm pretty sure it's a town in Australia filled with murderers... http://en.wikipedia.org/wiki/The_Cars_That_Ate_Paris -- Steven From chrischia82 at gmail.com Wed Aug 11 19:50:44 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Wed, 11 Aug 2010 16:50:44 -0700 (PDT) Subject: Python Tkinter Simple Qn Message-ID: Hi i have the following problem with Python Tkinter. I switch to switch the image background (which i used Tkinter.Label with image arg to display on the GUI). How can I do that? the callback function which i have created doesn't seem to work... some advice? below is my code: import Tkinter as tk from PIL import Image, ImageTk root = tk.Tk() # having problem with switching the image def callback(event): global root root.panel1.pack_forget() root.panel1.image = image2 root.panel1.pack() def app(): root.title('FIT 2022 Assignment 1') # pick an image file you have .bmp .jpg .gif. .png # load the file and covert it to a Tkinter image object imageFile = "c:\\test1.jpg" image1 = ImageTk.PhotoImage(Image.open(imageFile)) imageFile2 = "c:\\test2.jpg" image2 = ImageTk.PhotoImage(Image.open(imageFile2)) # get the image size w = image1.width() h = image1.height() # position coordinates of root 'upper left corner' x = 0 y = 0 # make the root window the size of the image root.geometry("%dx%d+%d+%d" % (w, h, x, y)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=image1) panel1.pack(side='top', fill='both', expand='yes') panel1.image = image1 panel1.bind("", callback) panel1.pack() root.mainloop() app() From ben+python at benfinney.id.au Wed Aug 11 19:52:29 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 12 Aug 2010 09:52:29 +1000 Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> <4c610bd2$0$28655$c3e8da3@news.astraweb.com> <87aaouzkm1.fsf@benfinney.id.au> <87hbj1j6ra.fsf@notengoamigos.org> Message-ID: <87mxsswvuq.fsf@benfinney.id.au> Jason Earl writes: > Which is more of a promise than Microsoft has given to Python. I am > not arguing for Mono, as I am not a fan. But if you honestly think > that Python doesn't infringe on some of Microsoft's patents you are > crazy. It's quite true that anyone can be sued, at any time, for anything. And any program can, because of the crazy patent system in many countries, be infringing any (usually large) number of software idea patent claims, without the programmers having done anything unusual to cause that situation. Microsoft, or any other party for that matter, very well may have any number of software idea patents that could be interpreted to cover Python's code. The main difference in the case of Mono is that Microsoft has widely and repeatedly asserted that such patents do exist, their assertions seem quite plausible since they wrote the specifications on which Mono is implemented, its ?Community Promise? very carefully does *not* grant any kind of binding permission to implement or use software ideas from those patents, and it has consistently wielded other such patents aggressively and maintains the willingness to continue to do so. None of that is true for Python. Which is why people aren't saying Python is a patent trap, but rather that Mono is. -- \ ?Most people, I think, don't even know what a rootkit is, so | `\ why should they care about it?? ?Thomas Hesse, Sony BMG, 2006 | _o__) | Ben Finney From ben+python at benfinney.id.au Wed Aug 11 20:00:36 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 12 Aug 2010 10:00:36 +1000 Subject: most popular gui framework for python References: Message-ID: <87iq3gwvh7.fsf@benfinney.id.au> Back9 writes: > Does anyone know of what is the most popular gui framework for python > application? The Python standard library comes with one, Tkinter . Recently the Tix extension is also available in the standard library bringing much richer and better-looking widgets to Tk. -- \ ?Dvorak users of the world flgkd!? ?Kirsten Chevalier, | `\ rec.humor.oracle.d | _o__) | Ben Finney From python at mrabarnett.plus.com Wed Aug 11 20:15:31 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 01:15:31 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <4c63341c$0$11101$c3e8da3@news.astraweb.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c63341c$0$11101$c3e8da3@news.astraweb.com> Message-ID: <4C633D23.5070903@mrabarnett.plus.com> Steven D'Aprano wrote: > On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote: > >> level: beginner >> >> exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 >> packs, write an exhaustive search to find the largest number of >> McNuggets that cannot be bought in exact quantity. > > Is this a trick question? > > I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) > McNuggets. And that's not even close to the largest number that you can't > buy. > If you'd looked at the link then you would've seen that it's mathematically possible. But then I expect you have a life! :-) From ben+python at benfinney.id.au Wed Aug 11 20:18:31 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 12 Aug 2010 10:18:31 +1000 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <87eie4wunc.fsf@benfinney.id.au> Alex Barna writes: > I know that this question has been asked for several times, [?] > So what happens to this field (Windows GUI automation [with Python]) ? Alex Barna writes: > It makes me doubt: is Python the correct language to do GUI > automation ? Your questions are definitely on-topic here. However, you might want to make use of the ?testing-in-python? forum where your questions are even *more* on-topic :-) -- \ ?We are stuck with technology when what we really want is just | `\ stuff that works.? ?Douglas Adams | _o__) | Ben Finney From nobody at nowhere.com Wed Aug 11 20:28:09 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 12 Aug 2010 01:28:09 +0100 Subject: How to capture all the environment variables from shell? References: <4C615D1B.7060204@syslang.net> Message-ID: On Wed, 11 Aug 2010 13:08:59 +1000, Cameron Simpson wrote: > The reason .bashrc gets overused for envars, aside from ignorance and > propagated bad habits, is that in a GUI desktop the setup sequence is > often a bit backwards. A conventional terminal/console login means you > get a login shell that sources your .{bash_}profile. And from there one > would start a GUI and all the .profile stuff has been run Once, as it > should be. But when the login itself is a GUI the various terminals get > started _before_ the .profile stuff gets sourced, because the terminal > is started by the desktop manager. Once common "fix" for this is to > make all new terminals run login shells. Ugh, but it does work. Er, not really. If you don't source your ~/.profile (etc) from e.g. ~/.xsession, GUI applications don't get to see the environment settings therein. The environment isn't just for shells. The reason why ~/.profile is only sourced by login shells is that it's supposed to be sourced exactly once, by the initial process of a session, i.e. the one from which all other programs descend. For a terminal-based login, "login" (or sshd or whatever) starts the shell as a login shell (with argv[0][0] == '-'), and the shell sets up the environment. For a desktop login, there is no login shell, so something else has to set up the environment. Simple enough; well, simple enough for anyone who understands Unix, processes, sessions, etc. But apparently too complex for the people who create desktop environments, who seem to think that the environment is somehow specific to shells. So you usually need to manually configure your session script (e.g. ~/.xsession for xdm) to set up the environment before the desktop environment gets a look-in. One caveat: if you set LD_LIBRARY_PATH, it will be unset when running a setuid or setgid program. This is sometimes the case for terminal emulators[1], in which case you need to have ~/.bashrc reinstate the setting. [1] Allocating a BSD-style pty requires root privilege, and writing utmp/wtmp entries requires write permission on the file. Modern systems have Unix98 ptys and a setgid helper program to manage the utmp/wtmp entries, so there shouldn't be any need for xterm etc to be setuid or setgid nowadays. From nobody at nowhere.com Wed Aug 11 20:42:51 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 12 Aug 2010 01:42:51 +0100 Subject: Line-by-line processing when stdin is not a tty References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: On Wed, 11 Aug 2010 10:32:41 +0000, Tim Harig wrote: >>> Usually you either >>> need an option on the upstream program to tell it to line >>> buffer explicitly >> >> once cat had an option -u doing exactly that but nowadays >> -u seems to be ignored >> >> http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html > > I have to wonder why cat knows or cares. The issue relates to the standard C library. By convention[1], stdin and stdout are line-buffered if the descriptor refers to a tty, and are block-buffered otherwise. stderr is always unbuffered. Any program which uses stdin and stdout without explicitly setting the buffering or using fflush() will exhibit this behaviour. [1] ANSI/ISO C is less specific; C99, 7.19.3p7: As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device. POSIX says essentially the same thing: From rNOSPAMon at flownet.com Wed Aug 11 21:21:43 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 18:21:43 -0700 Subject: How does Python get the value for sys.stdin.encoding? Message-ID: I thought it was hard-coded into the Python executable at compile time, but that is apparently not the case: [ron at mickey:~]$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys;print sys.stdin.encoding UTF-8 >>> ^D [ron at mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python None [ron at mickey:~]$ And indeed, trying to pipe unicode into Python doesn't work, even though it works fine when Python runs interactively. So how can I make this work? Thanks, rg From pavlovevidence at gmail.com Wed Aug 11 21:31:42 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 11 Aug 2010 18:31:42 -0700 (PDT) Subject: Deer Esurance Message-ID: <72ef108e-4c50-4076-b391-9c419059668c@h17g2000pri.googlegroups.com> If you're going to send me unsolicited email, the least you can do it include pics of Erin. Carl Banks From rNOSPAMon at flownet.com Wed Aug 11 21:49:26 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 18:49:26 -0700 Subject: Line-by-line processing when stdin is not a tty References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: In article , Nobody wrote: > On Wed, 11 Aug 2010 10:32:41 +0000, Tim Harig wrote: > > >>> Usually you either > >>> need an option on the upstream program to tell it to line > >>> buffer explicitly > >> > >> once cat had an option -u doing exactly that but nowadays > >> -u seems to be ignored > >> > >> http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html > > > > I have to wonder why cat knows or cares. > > The issue relates to the standard C library. By convention[1], stdin and > stdout are line-buffered if the descriptor refers to a tty, and are > block-buffered otherwise. stderr is always unbuffered. > > Any program which uses stdin and stdout without explicitly setting the > buffering or using fflush() will exhibit this behaviour. > > [1] ANSI/ISO C is less specific; C99, 7.19.3p7: > > As initially opened, the standard error stream is not fully > buffered; the standard input and standard output streams are > fully buffered if and only if the stream can be determined not > to refer to an interactive device. > > POSIX says essentially the same thing: > > This doesn't explain why "cat | cat" when run interactively outputs line-by-line (which it does). STDIN to the first cat is a TTY, but the second one isn't. For that matter, you can also do this: nc -l 1234 | cat and then telnet localhost 1234 and type at it, and it still works line-by-line. rg From bhanu.ramappa at gmail.com Wed Aug 11 22:15:42 2010 From: bhanu.ramappa at gmail.com (Bhanu Kumar) Date: Thu, 12 Aug 2010 07:45:42 +0530 Subject: python ide for ubuntu Message-ID: Hi All, Is there any good free python IDE available in Ubuntu? thanks, -Bhanu -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Wed Aug 11 22:24:49 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 11 Aug 2010 19:24:49 -0700 Subject: How does Python get the value for sys.stdin.encoding? In-Reply-To: References: Message-ID: On Wed, Aug 11, 2010 at 6:21 PM, RG wrote: > I thought it was hard-coded into the Python executable at compile time, > but that is apparently not the case: > > [ron at mickey:~]$ python > Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) > [GCC 4.2.1 (Apple Inc. build 5646)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys;print sys.stdin.encoding > UTF-8 >>>> ^D > [ron at mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python > None > [ron at mickey:~]$ > > And indeed, trying to pipe unicode into Python doesn't work, even though > it works fine when Python runs interactively. ?So how can I make this > work? > Sys.stdin and stdout are files, just like any other. There's nothing special about them at compile time. When the interpreter starts, it checks to see if they are ttys. If they are, then it tries to figure out the terminal's encoding based on the environment. The code for this is in pythonrun.c if you want to see exactly what it's doing. If stdout and stdin aren't ttys, then their encoding stays as None and the interpreter will use sys.getdefaultencoding() if you try printing Unicode strings. By the way, there is no such thing as piping Unicode into Python. Unicode is an abstract concept where each character maps to a codepoint. Pipes can only deal with bytes. You may be using one of the 5 encodings capable of holding the entire range of Unicode characters (UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE, and UTF-32 BE), but that's not the same thing as Unicode. You really have to watch your encodings when you pass data around between programs. There's no way to avoid it. From nyc61 at fibertel.com.ar Wed Aug 11 23:34:21 2010 From: nyc61 at fibertel.com.ar (apustilnik) Date: Wed, 11 Aug 2010 20:34:21 -0700 (PDT) Subject: globbal | creating networks Message-ID: Hi, i'd like to invite you to know this new way to keep in touch with friends, and meet new people! http://www.globbal.com.ar/login1.php Invite your friends to join, and start creating your own globbal networks! Are you ready to live a new experience? Are you ready to live globbal! Sign up now! From cs at zip.com.au Thu Aug 12 00:16:37 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 12 Aug 2010 14:16:37 +1000 Subject: How to capture all the environment variables from shell? In-Reply-To: References: Message-ID: <20100812041637.GA14479@cskk.homeip.net> On 12Aug2010 01:28, Nobody wrote: | On Wed, 11 Aug 2010 13:08:59 +1000, Cameron Simpson wrote: | > The reason .bashrc gets overused for envars, aside from ignorance and | > propagated bad habits, is that in a GUI desktop the setup sequence is | > often a bit backwards. A conventional terminal/console login means you | > get a login shell that sources your .{bash_}profile. And from there one | > would start a GUI and all the .profile stuff has been run Once, as it | > should be. But when the login itself is a GUI the various terminals get | > started _before_ the .profile stuff gets sourced, because the terminal | > is started by the desktop manager. Once common "fix" for this is to | > make all new terminals run login shells. Ugh, but it does work. | | Er, not really. If you don't source your ~/.profile (etc) from e.g. | ~/.xsession, GUI applications don't get to see the environment settings | therein. The environment isn't just for shells. I think we're in violent agreement here. I arrange to do exactly that in my own desktop setups. However, the ones that ship with distros generally don't, possibly because a shell-aborting error in the .profile (or unwanted interaction etc) will abort the GUI login/desktop-setup. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ The Puritan hated bear-baiting, not because it gave pain to the bear, but because it gave pleasure to the spectator. - Macaulay, History of England From gagsl-py2 at yahoo.com.ar Thu Aug 12 01:20:44 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Aug 2010 02:20:44 -0300 Subject: favicon.ico problem References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Message-ID: En Tue, 10 Aug 2010 01:32:49 -0300, Navkirat Singh escribi?: > I am having this strange problem. I have programmed a very basic > multiprocessing webserver using low level sockets. Each time the server > receives a request it spawns a new process to handle the request. Now > when through a web browser I type http://localhost:8001/ it > automatically creates two processes: One process to server the '/' path > and another one to serve the '/favicon.ico' path. I have not programmed > it to serve the latter. Infact I dont even know where that name > '/favicon.ico' comes from. Any insight into this weird behavior would be > greatly appreciated. It't the browser attempting to get an icon for the page. See http://en.wikipedia.org/wiki/Favicon -- Gabriel Genellina From nagle at animats.com Thu Aug 12 01:34:36 2010 From: nagle at animats.com (John Nagle) Date: Wed, 11 Aug 2010 22:34:36 -0700 Subject: urllib2 does not implement "with" Python 2.6 Message-ID: <4c6387f8$0$1587$742ec2ed@news.sonic.net> Somewhat to my surprise, in Python 2.6, with urllib2.urlopen(url) as fh : doesn't work. It fails with "AttributeError: addinfourl instance has no attribute '__exit__'". I thought that all the file-like objects supported "with" in 2.6. No? John Nagle From rNOSPAMon at flownet.com Thu Aug 12 01:50:43 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 22:50:43 -0700 Subject: How does Python get the value for sys.stdin.encoding? References: Message-ID: In article , Benjamin Kaplan wrote: > On Wed, Aug 11, 2010 at 6:21 PM, RG wrote: > > I thought it was hard-coded into the Python executable at compile time, > > but that is apparently not the case: > > > > [ron at mickey:~]$ python > > Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) > > [GCC 4.2.1 (Apple Inc. build 5646)] on darwin > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import sys;print sys.stdin.encoding > > UTF-8 > >>>> ^D > > [ron at mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python > > None > > [ron at mickey:~]$ > > > > And indeed, trying to pipe unicode into Python doesn't work, even though > > it works fine when Python runs interactively. ?So how can I make this > > work? > > > > Sys.stdin and stdout are files, just like any other. There's nothing > special about them at compile time. When the interpreter starts, it > checks to see if they are ttys. If they are, then it tries to figure > out the terminal's encoding based on the environment. The code for > this is in pythonrun.c if you want to see exactly what it's doing. Thanks. Looks like the magic incantation is: export PYTHONIOENCODING='utf-8' > By the way, there is no such thing as piping Unicode into Python. Yeah, I know. I should have said "piping UTF-8 encoded unicode" or something like that. > You really have to watch your encodings > when you pass data around between programs. There's no way to avoid > it. Yeah, I keep re-learning that lesson again and again. rg From no.email at nospam.invalid Thu Aug 12 02:14:19 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 23:14:19 -0700 Subject: urllib2 does not implement "with" Python 2.6 References: <4c6387f8$0$1587$742ec2ed@news.sonic.net> Message-ID: <7xr5i49x38.fsf@ruckus.brouhaha.com> John Nagle writes: > "AttributeError: addinfourl instance has no attribute '__exit__'". > > I thought that all the file-like objects supported "with" in 2.6. > No? I guess not. Use contextlib.closing. From zak.mc.kraken at libero.it Thu Aug 12 02:49:02 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Thu, 12 Aug 2010 08:49:02 +0200 Subject: Beyond the moratorium Message-ID: Hi all. I know, maybe I'm just lazily speculating, but I'm curious about what's next, in python, when GvR will stop the moratorium and will let changes in the language. I don't know what to expect... some syntax sugar about concurrent programming? static types? an erlang-style "bang" (!) process message passing? -- By ZeD From rNOSPAMon at flownet.com Thu Aug 12 02:50:13 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 23:50:13 -0700 Subject: Why can't I set sys.ps1 to a unicode string? Message-ID: More precisely, why does sys.ps1 not appear if I set it to a unicode string? This problem is hard for me to describe here because my newsreader is not properly unicode enabled, but here's the gist of it: Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> First, let's make sure our encodings are set properly: >>> import sys >>> sys.stdin.encoding 'utf-8' >>> sys.stdout.encoding 'utf-8' Looks good. Now, let's make two unicode strings, identical except for one character: >>> s1 = u'%%% %%% ' >>> s2 = u'%%% ' + u'\u262f' + '%%% ' >>> print s1 %%% %%% >>> print s2 %%% /&%%% If this were a properly unicode-enabled newsreader you would see a yin-yang symbol in the middle of s2. Now the weird part: >>> sys.ps1 = s1 %%% %%% sys.ps1 = s2 # This is as expected print s1 # But this isn't. There's no prompt! %%% %%% # Everything still works print s2 %%% /&%%% sys.ps1 = s1 # If we reset sys.ps1 we get our prompt back %%% %%% sys.ps1 = '>>> ' >>> sys.ps1 = u'>>> ' >>> So... why does having a non-ascii character in sys.ps1 make the prompt vanish? (If you're wondering why I care, I want to connect to an interactive python interpreter from another program, and I want a non-ascii delimiter to unambiguously mark the end of the interpreter's output on every interaction.) Thanks, rg From werner at thieprojects.ch Thu Aug 12 02:53:18 2010 From: werner at thieprojects.ch (Werner Thie) Date: Thu, 12 Aug 2010 08:53:18 +0200 Subject: python ide for ubuntu In-Reply-To: References: Message-ID: <4C639A5E.7090107@thieprojects.ch> Eclipse with pydev (great debugging) does the trick nicely, free of charge and throws in some other goodies (JScript/HTML/XML editing) too. I use the EE for Java developer version http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliosr Install pydev from Menu Help/Software Updates After ten years of Python coding and suffering thru most of the commercial products like VisualPython, Komodo, Wings, asf I heartily recommend Eclipse nowadays. If you want to stay as pythonesque as possible you could go with SPE which uses wxPython and integrates with Blender, although this project seems to be stalled. Werner On 12.08.2010 04:15, Bhanu Kumar wrote: > Hi All, > > Is there any good free python IDE available in Ubuntu? > > > thanks, > -Bhanu > -------------- next part -------------- A non-text attachment was scrubbed... Name: werner.vcf Type: text/x-vcard Size: 297 bytes Desc: not available URL: From eckhardt at satorlaser.com Thu Aug 12 03:01:38 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 12 Aug 2010 09:01:38 +0200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> <4C61E9A1.5090800@v.loewis.de> <88t9j7-ri5.ln1@satorlaser.homedns.org> <44d30ac7-931e-4eb0-9aed-f664c872d438@l20g2000yqm.googlegroups.com> Message-ID: sturlamolden wrote: > On 11 Aug, 08:40, Ulrich Eckhardt wrote: > Header (definition) and source (implementation) is not the same. I'm aware of this and that's not the thing I was talking about. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From stefan_ml at behnel.de Thu Aug 12 03:17:04 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 12 Aug 2010 09:17:04 +0200 Subject: Beyond the moratorium In-Reply-To: References: Message-ID: Vito 'ZeD' De Tullio, 12.08.2010 08:49: > I know, maybe I'm just lazily speculating, but I'm curious about what's > next, in python, when GvR will stop the moratorium and will let changes in > the language. > > I don't know what to expect... some syntax sugar about concurrent > programming? static types? an erlang-style "bang" (!) process message > passing? One of the reasons the moratorium was established was to reduce the time spent in overly speculative discussions about various features that will most likely not end up in the language anyway. Also note that your examples above span both the language and the stdlib, which are put under different constraints by the moratorium. Stefan From ben+python at benfinney.id.au Thu Aug 12 03:22:00 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 12 Aug 2010 17:22:00 +1000 Subject: Beyond the moratorium References: Message-ID: <871va4wb1j.fsf@benfinney.id.au> Vito 'ZeD' De Tullio writes: > I know, maybe I'm just lazily speculating, but I'm curious about > what's next, in python, when GvR will stop the moratorium and will let > changes in the language. Subscribe to the ?python-ideas? forum for the latest pie-in-the-sky discussions about how to change Python, including the occasional contribution from GvR on ideas that take his interest. -- \ ?In the long run, the utility of all non-Free software | `\ approaches zero. All non-Free software is a dead end.? ?Mark | _o__) Pilgrim, 2006 | Ben Finney From martin at v.loewis.de Thu Aug 12 03:26:15 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Thu, 12 Aug 2010 09:26:15 +0200 Subject: Why can't I set sys.ps1 to a unicode string? In-Reply-To: References: Message-ID: > So... why does having a non-ascii character in sys.ps1 make the prompt > vanish? I can't pinpoint it to a specific line of code. Most likely, it tries to encode the prompt as ASCII before writing it to stdout. That fails, and it silently ignores the error. FWIW, this is fixed in Python 3. Regards, Martin From news1234 at free.fr Thu Aug 12 03:39:32 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 09:39:32 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <4c63341c$0$11101$c3e8da3@news.astraweb.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c63341c$0$11101$c3e8da3@news.astraweb.com> Message-ID: <4C63A534.2040404@free.fr> Hi Steven, On 08/12/2010 01:37 AM, Steven D'Aprano wrote: > On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote: > >> level: beginner >> >> exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 >> packs, write an exhaustive search to find the largest number of >> McNuggets that cannot be bought in exact quantity. > > Is this a trick question? > > I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) > McNuggets. And that's not even close to the largest number that you can't > buy. You CAN buy that many Nuggets. You just need the money and of course you have to wait a little until they are ready. From ldo at geek-central.gen.new_zealand Thu Aug 12 03:39:41 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 12 Aug 2010 19:39:41 +1200 Subject: how to save a whole web page with something block References: <46c3cfc7-9339-4cd0-9ef9-4358730b706f@o7g2000prg.googlegroups.com> Message-ID: In message , Daniel Fetchinson wrote: > A web server may present different output depending on the client > used. It may also require execution of some JavaScript to insert HTML content. > So you might want to make urllib appear as a browser by sending the > appropriate headers. If the above is the case, then this won?t be enough. From debatem1 at gmail.com Thu Aug 12 04:03:10 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 12 Aug 2010 01:03:10 -0700 Subject: python ide for ubuntu In-Reply-To: <4C639A5E.7090107@thieprojects.ch> References: <4C639A5E.7090107@thieprojects.ch> Message-ID: On Wed, Aug 11, 2010 at 11:53 PM, Werner Thie wrote: > Eclipse with pydev (great debugging) does the trick nicely, free of charge > and throws in some other goodies (JScript/HTML/XML editing) too. > > I use the EE for Java developer version > > http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliosr > > Install pydev from Menu Help/Software Updates > > After ten years of Python coding and suffering thru most of the commercial > products like VisualPython, Komodo, Wings, asf I heartily recommend Eclipse > nowadays. > > If you want to stay as pythonesque as possible you could go with SPE which > uses wxPython and integrates with Blender, although this project seems to be > stalled. > > Werner Or you could use a text editor and a terminal and spare yourself the agony of dealing with 600MB of Java of questionable quality ;). And don't even get me started about all the unsigned OSGi bundles that float around in there. Geremy Condra From news1234 at free.fr Thu Aug 12 04:24:23 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 10:24:23 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4c63afb7$0$431$426a34cc@news.free.fr> On 08/11/2010 10:14 PM, Baba wrote: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf > > please help me write this code > > i believe it's something along the lines of this: > > c=0 > sol=[] > for n in range (0,10): > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print sol > If you're interested in more, than just finishing the exercise, then you should post your solution even if you have it already and read about all the tips how to make it faster or shorter or more readable From eric.brunel at pragmadev.com Thu Aug 12 04:42:51 2010 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 12 Aug 2010 10:42:51 +0200 Subject: Python Tkinter Simple Qn References: Message-ID: In article , ChrisChia wrote: > Hi i have the following problem with Python Tkinter. > I switch to switch the image background (which i used Tkinter.Label > with image arg to display on the GUI). > > How can I do that? the callback function which i have created doesn't > seem to work... It is usually way better to post the actual error than just saying "doesn't seem to work"? Here your problem is quite clear, but in most circumstances, it would be quite difficult to figure out what's happening. > some advice? > > below is my code: > > > import Tkinter as tk > from PIL import Image, ImageTk > > root = tk.Tk() > > # having problem with switching the image > def callback(event): > global root > root.panel1.pack_forget() > root.panel1.image = image2 The variable image2 is not known in this context, so no wonder the callback doesn't work. Let me guess: it says something like "NameError: name 'image2' is not defined"? > root.panel1.pack() > > > def app(): > > root.title('FIT 2022 Assignment 1') > > # pick an image file you have .bmp .jpg .gif. .png > # load the file and covert it to a Tkinter image object > imageFile = "c:\\test1.jpg" > image1 = ImageTk.PhotoImage(Image.open(imageFile)) > imageFile2 = "c:\\test2.jpg" > image2 = ImageTk.PhotoImage(Image.open(imageFile2)) Here, you create image2 as a local variable in function app. So the variable name will not be known outside of app. If you want it to be global, you have to add a line: global image2 at the beginning of your app function. Then it should work correctly. By the way, I usually find it better to organize a GUI into classes rather than using functions. This way, you could store the images in object attributes and define your callback as a method, and not as a function. > # get the image size > w = image1.width() > h = image1.height() > > > # position coordinates of root 'upper left corner' > x = 0 > y = 0 > > > # make the root window the size of the image > root.geometry("%dx%d+%d+%d" % (w, h, x, y)) > > > # root has no image argument, so use a label as a panel > panel1 = tk.Label(root, image=image1) > panel1.pack(side='top', fill='both', expand='yes') > panel1.image = image1 > panel1.bind("", callback) > > > panel1.pack() > root.mainloop() > > > app() HTH - Eric - From meitham at meitham.com Thu Aug 12 04:42:55 2010 From: meitham at meitham.com (meitham) Date: Thu, 12 Aug 2010 01:42:55 -0700 (PDT) Subject: most popular gui framework for python References: Message-ID: <981f0dbe-73b6-470f-ab87-869f387fc922@s9g2000yqd.googlegroups.com> On Aug 11, 8:31?pm, Back9 wrote: > Hi, > > Does anyone know of what is the most popular gui framework for python > application? > > TIA I used to prefer using GTK mainly because it is available on most platforms. I have realised the majority of the enterprises prefer to use browsers even for local applications. So a combination of django/ html/css/jquery/ajax now gives me the best gui I could get. This approach also forces me to separate logic from presentation, and the gui will be truly platform independent which could run on any device with a browser. Meitham From ph4nut at gmail.com Thu Aug 12 04:59:26 2010 From: ph4nut at gmail.com (ph4nut) Date: Thu, 12 Aug 2010 01:59:26 -0700 (PDT) Subject: Does anyone use Quixote for web developing? Message-ID: Hi all,I am learning Quixote a few days ago,,,and i have no idea about whether there is any Google Group talking about Quixote,so i post this post to check that is Quixote been talking in this group before or can i ask question about Quixote here! From jeanmichel at sequans.com Thu Aug 12 05:23:41 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 12 Aug 2010 11:23:41 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4C63BD9D.30602@sequans.com> Baba wrote: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf > > please help me write this code > > i believe it's something along the lines of this: > > c=0 > sol=[] > for n in range (0,10): > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print sol > > > for mcNugget in range(0,10): sendTo(trashbin) You're welcome :p JM From no.email at nospam.invalid Thu Aug 12 05:33:25 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Thu, 12 Aug 2010 02:33:25 -0700 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <7x1va4tbtm.fsf@ruckus.brouhaha.com> Baba writes: > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. Is that a homework problem? Hint: first convince yourself that a largest number actually exists. From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 12 05:40:59 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 12 Aug 2010 11:40:59 +0200 Subject: Does anyone use Quixote for web developing? In-Reply-To: References: Message-ID: <4c63c198$0$24088$426a74cc@news.free.fr> ph4nut a ?crit : > Hi all,I am learning Quixote a few days ago,,,and i have no idea about > whether there is any Google Group talking about Quixote,so i post this > post to check that is Quixote been talking in this group before or can > i ask question about Quixote here! From the project's home page: """ There is a mailing list for discussing Quixote and you should look there for information about obtaining the current release: * quixote-users """ From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 12 05:42:09 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 12 Aug 2010 11:42:09 +0200 Subject: python ide for ubuntu In-Reply-To: References: <4C639A5E.7090107@thieprojects.ch> Message-ID: <4c63c1df$0$24088$426a74cc@news.free.fr> geremy condra a ?crit : (about eclipse+pydev) > Or you could use a text editor and a terminal and spare yourself the > agony of dealing with 600MB of Java of questionable quality ;). +1 QOTW From xrgtn at yandex.ru Thu Aug 12 06:30:03 2010 From: xrgtn at yandex.ru (Alexander Gattin) Date: Thu, 12 Aug 2010 13:30:03 +0300 Subject: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT) In-Reply-To: References: Message-ID: <20100812103003.GA24917@xrgtn-q40> Hello, On Wed, Aug 11, 2010 at 02:29:24PM -0700, tormod wrote: > I've tried countless times to build & install cx_Oracle on Python > 3.1.2, and failed every time, so I'd like to ask someone for help. ... > I've opened the cx_Oracle.pyd with Dependency Walker (http:// > www.dependencywalker.com/) and DW reports it can't find: OCI.DLL, > PYTHON31.DLL, MSVCR90.DLL (why?) Does Windows have anything like LD_LIBRARY_PATH/SHLIB_PATH? > Appreciate any help, even wildshots and 2 cents are welcome - I'll try > everything. please try starting python -d (--debug IIRC) and then loading cx_Oracle manually (>>> import cx_Oracle). Usually it succeeds (sic!) but outputs a lot of symbol errors. // Problem with Oracle libs -- With best regards, xrgtn (+380501102966/+380636177128/xrgtn at jabber.kiev.ua) From downaold at gmail.com Thu Aug 12 06:44:24 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 12 Aug 2010 12:44:24 +0200 Subject: python ide for ubuntu In-Reply-To: References: Message-ID: <30CC6202-509E-4D09-9921-79A7B61C9351@gmail.com> Hi Bhanu, On Aug 12, 2010, at 4:15 AM, Bhanu Kumar wrote: > Hi All, > > Is there any good free python IDE available in Ubuntu? See a similar discussion at django-users mailing list: http://groups.google.com/group/django-users/browse_thread/thread/562189578285211 Cheers, Roald From downaold at gmail.com Thu Aug 12 07:04:58 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 12 Aug 2010 13:04:58 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <7x1va4tbtm.fsf@ruckus.brouhaha.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: On Aug 12, 2010, at 11:33 AM, Paul Rubin wrote: > Baba writes: >> exercise: given that packs of McNuggets can only be bought in 6, 9 or >> 20 packs, write an exhaustive search to find the largest number of >> McNuggets that cannot be bought in exact quantity. > > Is that a homework problem? Hint: first convince yourself that a > largest number actually exists. Good point. There is actually an upper bound. Let's take 6 packs of 20, that's 120 nuggets. Now 121 nuggets can be reached by substituting 1 pack of 20 with 2 packs of 6 and 1 pack of 9. 122 = 4*20 + 2*(2*6+9) 123 = 3*20 + 3*(2*6+9) ... 126 = 6*20 + 6 127 = 121 + 6 = 5*20 + (2*6 + 9) + 6 ... etcetera. Now you have to find the largest number below 120, which you can easily do with brute force (untested): can_be_bought = [False for i in range(120)] for twenties in range(6): for nines in range(14): for sixes in range(20): can_be_bought[twenties*20+nines*9+sixes*6] = True for i in reverse(range(120)): if not can_be_bought[i]: return i Cheers, Roald From msarro at gmail.com Thu Aug 12 07:41:47 2010 From: msarro at gmail.com (Matty Sarro) Date: Thu, 12 Aug 2010 07:41:47 -0400 Subject: Programming Puzzles? What's your favorite puzzle? Message-ID: Hey All! Hope your thursday is treating you well. I'm looking for suggestions on books of programming/engineering puzzles that range from beginners to advanced and even expert level problems. I know they exist; we had them back in college for practicing before the ACM programming competitions. However I can't seem to really find any books out there that look like they're what I'm seeking. Basically I haven't programmed a lot since I was in college, and that was about 9 years ago. I'm expected to do a bit more programming at my current job and I figure the best way to get back into things is to have some practical things to solve, and maybe have a bit of fun in the process. Anyone have any suggestions? Also, if you have any favorite puzzles/simple learning programs to suggest, please, share with the class :) -Matty -------------- next part -------------- An HTML attachment was scrubbed... URL: From drodrig at magicbrain.com Thu Aug 12 07:49:15 2010 From: drodrig at magicbrain.com (drodrig) Date: Thu, 12 Aug 2010 04:49:15 -0700 (PDT) Subject: Copying a file with a question mark in it's name in Windows Message-ID: A python script I use to backup files on a Windows 2003 server occasionally fails to retrieve the size of a file with a question mark in the name. The exception I get is "OSError #123 The filename, directory name, or volume label syntax is incorrect". I realize that technically a question mark in the name of a file on Windows is illegal, but nevertheless these files exist on the file system. It seems that they are created by Office 2007 Word, for the most part. The line that fails is: os.path.getsize(source) Where source is the full path to the file with the question mark in it's name. Any idea how to retrieve the file's size? Also, I imagine that after I overcome this hurdle, I'll need help finding a way to copy the file (assuming copy2() doesn't work). I've tried escaping the question mark ("\\?"). Same result. Although I could use the Windows "dir" command, parsing the results to find the size of the file then use the Windows "copy" command, I'd rather stay away from this type of solution. Any help is appreciated! From iktomus.heyokis at gmail.com Thu Aug 12 08:05:55 2010 From: iktomus.heyokis at gmail.com (=?TIS-620?B?4KLp0rnNuQ==?=) Date: Thu, 12 Aug 2010 05:05:55 -0700 (PDT) Subject: Long rant about Python in Education Message-ID: This is in response to one of the pyWiki pages: PythonAsAFirstLanguage. If there's a better place I could have posted this, please tell me about it. I will be posting this elsewhere over the next few ideas, because I feel it's my duty to spread this idea. It's not grandiose, just Quixotic. Someone wrote, "We could really use some success stories of Python in education." Right... Python was developed to be easily learnt by children. So that's not a declarative sentence. It's an implied question. Here's my answer. It took a while to write, but it's quite simple. Problem: Python won't be easily learnt by my stepchild, I know for a fact. She loves her laptop, but she calls me a nerd whenever Linux gets brought up at the dinner table. I'm not bitter about this. But I want you guys, especially the ones who are planning on having kids, as well as the ones who already have them, to understand what steps you can take to teach your kids Python. I've basically outlined an 'algorithm' for it here. If you don't have time to read a long, eccentric, rambling post, just 'read the lead' Solution to problem: 1) Only let them see you using the terminal. Don't even use Windows in the house. 2) Their first laptop should be installed with a nice, well-supported Linux distro. 3) Brush up on your Linux skills yourself. The bottom line: teach them to do beautiful things with the terminal. I believe Linux should be mastered by everyone who uses it. And I believe Linux (not Python) is the way to teach children to program. Especially intuitive ones. (In the Myers-Briggs scale.) Why is this important? Because the part of the world that most hates America right now is full of intuitives. And if we want not to be blown off the face of the earth in a few decades, we have to empower them in a very new way: we have to teach them to enjoy programming, enjoy computers, and develop their minds in a way that doesn't involve becoming 'Imams' who are essentially the learned mafia bosses of terrorism. I have mastered Classical Arabic. I once met a Pakistani and told him I had done so. We were in the middle of a theological debate. In the middle of his Islamic theology was, laughably enough, some Christian theology that I have no idea how it got there. Orthodox Islam has no concept of original sin, but he believed in it. That was a real surprise for me. Anyway, despite the fact that he'd only read translations of the Qur'an, whereas I'd read the original, he was not impressed. He said that Pakistan had many 'schools' for studying Arabic, and that there was an incredible number of 'students' there. These people aren't dumb, guys. They're just learning the wrong stuff. We can't change the schools, but we don't need to. Don't forget that Arabs and Central Asians both had education systems based on Islam before western education came with the French and British. The attempt to re-establish the primacy of that system of education is what Islamic terrorism is all about. It was based on memorizing/hearing the Qur'an, yes, then learning the meanings of the words by reading it. Actually, for an intuitive person, this is an excellent way to learn any language (find a text, find a recording, memorize the recording, intuit the meanings) and I have used it to learn Spanish, Chinese, and Arabic. How does this apply to Linux/Python? Having access to the /usr/bin directory means having access to a whole load of algorithms without even having to write them yourself! Hasn't anyone but me thought of how great that would be for kids? So, when you guys ban windows in the home and start breastfeeding your kids terminals (I was using a DOS terminal correctly at age 9, shouldn't be hard to teach them whippersnappers to use a -nix shell), then you can bring in Python. But first, start writing Python to put in their /usr/bin directories, so that they get comfortable with the idea that Python can be both scripted and compiled, and that programs are simply algorithms that get called using arguments. Then teach them to write Python stuff they can put into /usr/bin Important: ban windows entirely in the home. I cannot stress this enough. My stepdaughter is as good with computers as I was at her age, and I've seen her play around with the settings on her laptop when she's bored. Obviously, she wants to explore the machine sometimes, but windows has trained her mind not to look for geeky solutions. Windows has trained her to think of a computer as a magic machine, and not as an algorithm machine. Will the real Bill Gates please stand up. When I was her 10, my stepfather banned me from playing DOOM unless I could get it to work using the DOS command line. I did not manage to replace the .dll file he had deleted, but I did learn lots. Will the real Bill Gates please stand up, please stand up, please stand up... So, in conclusion: DO people of the free-thinking world want a Mozart Python genius to show off to the schools in Europe, Japan, Saudi (most importantly, because it's a very rich country), the US, and all the other richer countries... Do you? I do. I'll see that kid as some sort of divine messiah, the way this world is heading now. The minute we can get 10-year-old Python geniuses in countries like Pakistan, Algeria, and occupied Palestine, they will be superstars, inspire the upper classes in their respective countries to teach their kids programming, and our earth will no longer have anything to fear from Islamic terrorism (using Linux, which is the John the Baptist of this whole equation), because sooner or later, the terrorists who are just bored teenagers will start writing good programs. Also, my travels around the world have convinced me that Arabs will someday be be the best programmers on the earth. My stepdaughter has an Arab background, and her case convinces me further. She could be a great computer programmer, if windows hadn't spoiled her! Windows has spoiled them all, though, sadly... They (Arabs) have the typology for it -- far more intuitives than we white people do. But the way "globalization" has worked, turning the whole world into an empire run by rich countries, of course there's a revolt stirring in the poorer ones. It was bound to happen someday. The fat cats who run these globalizing corporations mostly read the Bible everyday and think the apocalypse is coming soon. It's their prophecy guys, their book. Not ours. The Linux shell is our Qur'an. Python is our New Testament. Will somebody please write the Torah already? Our new style of imperialism has also taught the Arabs and Central Asians that, in order to succeed in life, you have to be 'sensate' (Jung/Myers-Briggs again here. Please read up if you don't know what I'm talking about. The sensation function is what lets us do math, learn logic, sketch, play music, etc.) Want to cause an explosion of world peace? Want Python to change the world? I know this sounds grandiose guys, but I've just given you guys the answer. I've traveled the world including the parts of the Middle East where Bin Laden's doing most of his dirty work. I've done quite a bit of everything, and this is the answer: teach Python. But don't teach it first. Ban them from windows first. Important: When they want something done, make them figure out how to do it in the terminal. They will try, if they are good, because I tried. And unfortunately, since it was DOS, I did not have a whole slew of algorithms in the / usr/bin directory waiting to be learnt and studied. Also, I did not have a command history at my disposal. That's unfortunate, but it doesn't stop me from trying to master Linux now. A child who's mastered Linux at age 9 or 10 will be the first kid to get on international TV for learning good Python. . . He will be our era's Mozart... But you can't teach them Python until they're familiar with the workings of a computer. Don't even try. It's like trying to teach algrebra without geometry first -- the one was invented first, so it needs to be learned first. The fact that we now teach algebra first in some schools just makes people hate math. Ditto with teaching kids C/C++ who've never even touched linux. It's a scary education system... And my 2 cents is that the proliferation of western education creates hooligans, mafiosos, Imams who support terrorism, and other classes of thugs in societies where people are intuitive, like Pakistan or Egypt... Let's face it, guys. Our world only works in the favor of the few, the proud, the sensate. Thankfully, computers taught me everything I've ever learned. That's why I regard them in high esteem. My laptop is more than an object -- it is almost divine. What powers it? Electricity, which is almost divine. And what is greater than electricity? Ahh, the electromagnetic spectrum... the mystery of nature... Signing off for now to fight more terrorists, But not before a Coffee Break, Alec From mail at timgolden.me.uk Thu Aug 12 08:11:33 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 12 Aug 2010 13:11:33 +0100 Subject: Copying a file with a question mark in it's name in Windows In-Reply-To: References: Message-ID: <4C63E4F5.7050706@timgolden.me.uk> On 12/08/2010 12:49, drodrig wrote: > A python script I use to backup files on a Windows 2003 server > occasionally fails to retrieve the size of a file with a question mark > in the name. The exception I get is "OSError #123 The filename, > directory name, or volume label syntax is incorrect". I realize that > technically a question mark in the name of a file on Windows is > illegal, but nevertheless these files exist on the file system. It > seems that they are created by Office 2007 Word, for the most part. Could you show us the script you're using? I'm not aware of any way to get a question mark into a file name; even using the file namespace prefix \\?\ doesn't allow it as far as I can tell. Where are you seeing the question mark? Is it possible it's a placeholder for an unprintable character rather than an actual question mark? TJG From johnroth1 at gmail.com Thu Aug 12 08:20:42 2010 From: johnroth1 at gmail.com (John Roth) Date: Thu, 12 Aug 2010 05:20:42 -0700 (PDT) Subject: Beyond the moratorium References: <871va4wb1j.fsf@benfinney.id.au> Message-ID: <145c25ca-54fc-473b-941c-babf21d0b588@l25g2000prn.googlegroups.com> On Aug 12, 1:22?am, Ben Finney wrote: > Vito 'ZeD' De Tullio writes: > > > I know, maybe I'm just lazily speculating, but I'm curious about > > what's next, in python, when GvR will stop the moratorium and will let > > changes in the language. > > Subscribe to the ?python-ideas? forum for the latest pie-in-the-sky > discussions about how to change Python, including the occasional > contribution from GvR on ideas that take his interest. > > -- > ?\ ? ? ? ? ? ? ??In the long run, the utility of all non-Free software | > ? `\ ? ? ?approaches zero. All non-Free software is a dead end.? ?Mark | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Pilgrim, 2006 | > Ben Finney You might also want to look at PEP 3152, which was just posted. John Roth From sajuptpm at gmail.com Thu Aug 12 08:26:57 2010 From: sajuptpm at gmail.com (sajuptpm) Date: Thu, 12 Aug 2010 05:26:57 -0700 (PDT) Subject: Secure LDAP Configuration Message-ID: <81a712a4-3d1c-45f2-9fbf-deecd5e80068@g21g2000prn.googlegroups.com> I want to create an LDAP database for my company with following settings. Only the ldap user belongs to my company can search and view ldap entries I want to protect ldap user belongs to my company One ldap user can't search and view others details Only allow ldap users to authenticate with there username and password I need an LDAP administrator for my company.Only he can add and delete users from LDAP. For these how configure /etc/openldap/slapd.conf I need to add group and role infornations to ldap directory.Can i use existing attributes like 'ou' for these or need to add new attribute. Here is the LDAP entry i configured. dn: uid=user6,dc=localhost,dc=localdomain objectclass: top objectclass: person objectclass: inetorgperson ou: [('userGroup111','userr'),('adminGroup','admin'), ('Server111','operator')] cn: user6 sn: My company uid: user6 userPassword: 123456 ou: [('userGroup111','userr'),('adminGroup','admin'), ('Server111','operator')] <-----newly added group and role pair.Is it correct way???? Have any other way to do it. From iamforufriends at gmail.com Thu Aug 12 08:51:22 2010 From: iamforufriends at gmail.com (UR DREEM GIRL) Date: Thu, 12 Aug 2010 05:51:22 -0700 (PDT) Subject: 34,100,617 active members r waiting 4 live sex chat, dating ... Message-ID: 34,100,617 active members r waiting 4 live sex chat, dating ... click bellow.... http://www.adultfriendfinder.com/go/g1250650-ppc http://www.adultfriendfinder.com/go/g1250650-ppc http://www.adultfriendfinder.com/go/g1250650-ppc From h.goebel at crazy-compilers.com Thu Aug 12 09:03:34 2010 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Thu, 12 Aug 2010 15:03:34 +0200 Subject: Announcing: python-ghostscript 0.3 Message-ID: Announcing: python-ghostscript 0.3 A Python-Interface to the Ghostscript C-API using ctypes :Copyright: GNU Public License v3 (GPLv3) :Author: Hartmut Goebel :Homepage: http://bitbucket.org/htgoebel/python-ghostscript :Download: http://pypi.python.org/pypi/ghostscript `Ghostscript`__, is a well known interpreter for the PostScript language and for PDF. This package implements a interface to the Ghostscript C-API using `ctypes`__. Both a low-level and a pythonic, high-level interface are provided. __ http://www.ghostscript.com/ __ http://docs.python.org/library/ctypes.html This package is currently tested only under GNU/Linux. Please report whether it works in your environment, too. Thanks. Latest Changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :0.3 (2010-08-12): * Added support for win32: The DLL to load is searched in registry. * On other platforms: Be more inteligent about finding Ghostscript shared object file (fall back to ctypes.util.find_library() if `libgs.8.so` can not be loaded * Better error messages if lib/dll is not found. * Removed relative imports, so older versions of Python can be used. * Added nice project logo :0.2 (2010-08-06): * Fixed several bugs, esp. for running strings by Ghostscript. Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is an example for how to use the high-level interface of `python-ghostscript`. This implements a very basic ps2pdf-tool:: import sys import ghostscript args = [ "ps2pdf", # actual value doesn't matter "-dNOPAUSE", "-dBATCH", "-dSAFER", "-sDEVICE=pdfwrite", "-sOutputFile=" + sys.argv[1], "-c", ".setpdfwrite", "-f", sys.argv[2] ] ghostscript.Ghostscript(*args) -- Regards Hartmut Goebel | Hartmut Goebel | h.goebel at crazy-compilers.com | | www.crazy-compilers.com | compilers which you thought are impossible | From blur959 at hotmail.com Thu Aug 12 09:15:23 2010 From: blur959 at hotmail.com (blur959) Date: Thu, 12 Aug 2010 06:15:23 -0700 (PDT) Subject: Renaming OS files by file type in python Message-ID: <953bbeb2-b3a5-4882-999f-184f2a51d331@x24g2000pro.googlegroups.com> Hi all, I am creating a program that renames all files of the similar file type. But i am stuck at this part. I tried running this code and I got this error: new_name = os.rename(path, newpath) WindowsError: [Error 183] Cannot create a file when that file already exists. Hope you guys could help. import os directory = raw_input("Please input file directory. \n\n") s = raw_input("Please input a name to replace. \n\n") ext = raw_input("input file ext") for filename in listdir(directory): if ext in filename: path = join(directory, filename) fnpart = os.path.splitext(filename)[0] replace_name = filename.replace(fnpart, s) newpath = os.path.join(directory, replace_name) new_name = os.rename(path, newpath) print new_name From alekseymv at gmail.com Thu Aug 12 09:16:02 2010 From: alekseymv at gmail.com (Aleksey) Date: Thu, 12 Aug 2010 06:16:02 -0700 (PDT) Subject: Copying a file with a question mark in it's name in Windows References: Message-ID: On 12 ???, 18:49, drodrig wrote: > A python script I use to backup files on a Windows 2003 server > occasionally fails to retrieve the size of a file with a question mark > in the name. The exception I get is "OSError #123 The filename, > directory name, or volume label syntax is incorrect". I realize that > technically a question mark in the name of a file on Windows is > illegal, but nevertheless these files exist on the file system. It > seems that they are created by Office 2007 Word, for the most part. If "?" is a placeholder for an unprintable character you can try view real file name in IDLE: import glob print glob.glob(u'e:/full/path/to/file?') In path to file you must instead question use wild "?". Will be printed all like files. ----------------------------- Under Windows I too have similar problem: windows sometimes (from any programs - e.g. Firefox) save files with wrong names, but later do not manipulate with it. From davea at ieee.org Thu Aug 12 09:22:30 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 12 Aug 2010 09:22:30 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: <4C63F596.5000007@ieee.org> Roald de Vries wrote: >
On Aug > 12, 2010, at 11:33 AM, Paul Rubin wrote: >> Baba writes: >>> exercise: given that packs of McNuggets can only be bought in 6, 9 or >>> 20 packs, write an exhaustive search to find the largest number of >>> McNuggets that cannot be bought in exact quantity. >> >> Is that a homework problem? Hint: first convince yourself that a >> largest number actually exists. > > Good point. There is actually an upper bound. Let's take 6 packs of > 20, that's 120 nuggets. > Now 121 nuggets can be reached by substituting 1 pack of 20 with 2 > packs of 6 and 1 pack of 9. > 122 = 4*20 + 2*(2*6+9) > 123 = 3*20 + 3*(2*6+9) > ... > 126 = 6*20 + 6 > 127 = 121 + 6 = 5*20 + (2*6 + 9) + 6 > ... etcetera. > > Now you have to find the largest number below 120, which you can > easily do with brute force (untested): > > can_be_bought = [False for i in range(120)] > for twenties in range(6): > for nines in range(14): > for sixes in range(20): > can_be_bought[twenties*20+nines*9+sixes*6] = True > for i in reverse(range(120)): > if not can_be_bought[i]: return i > > Cheers, Roald > for i in reverse(range(120)): if not can_be_bought[i]: return i can probably be replaced by (untested): return len(can_be_bought) - reverse(can_be_bought).index(False) - 1 DaveA From davea at ieee.org Thu Aug 12 09:37:55 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 12 Aug 2010 09:37:55 -0400 Subject: Programming Puzzles? What's your favorite puzzle? In-Reply-To: References: Message-ID: <4C63F933.5010702@ieee.org> Matty Sarro wrote: > Hey All! > Hope your thursday is treating you well. I'm looking for suggestions on > books of programming/engineering puzzles that range from beginners to > advanced and even expert level problems. I know they exist; we had them back > in college for practicing before the ACM programming competitions. However I > can't seem to really find any books out there that look like they're what > I'm seeking. Basically I haven't programmed a lot since I was in college, > and that was about 9 years ago. I'm expected to do a bit more programming at > my current job and I figure the best way to get back into things is to have > some practical things to solve, and maybe have a bit of fun in the process. > > Anyone have any suggestions? > > Also, if you have any favorite puzzles/simple learning programs to suggest, > please, share with the class :) > > -Matty > > For puzzles: http://projecteuler.net http://www.pythonchallenge.com And you might get some ideas from: http://wiki.python.org/moin/CodingProjectIdeas DaveA From darcy at druid.net Thu Aug 12 09:39:12 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 12 Aug 2010 09:39:12 -0400 Subject: Long rant about Python in Education In-Reply-To: References: Message-ID: <20100812093912.ecefc452.darcy@druid.net> On Thu, 12 Aug 2010 05:05:55 -0700 (PDT) ??????? wrote: > have to teach them to enjoy programming, enjoy computers, and develop > their minds in a way that doesn't involve becoming 'Imams' who are > essentially the learned mafia bosses of terrorism. This is the point that I stopped reading your "message" and added you to my blacklist. Goodbye. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From as at sci.fi Thu Aug 12 09:42:17 2010 From: as at sci.fi (Anssi Saari) Date: Thu, 12 Aug 2010 16:42:17 +0300 Subject: How does Python get the value for sys.stdin.encoding? References: Message-ID: Benjamin Kaplan writes: > Sys.stdin and stdout are files, just like any other. There's nothing > special about them at compile time. When the interpreter starts, it > checks to see if they are ttys. If they are, then it tries to figure > out the terminal's encoding based on the environment. Just a related question, is looking at sys.stdin.encoding the proper way of doing things? I've been working on a script to display some email headers, some of which are encoded in MIME to various charsets. Until now I have used whatever locale.getdefaultlocale() returns as the target encoding, since "it seemed to work". Although on one computer the call returns ISO-8859-15 even though I don't quite understand why. From ericjvandervelden at gmail.com Thu Aug 12 09:43:30 2010 From: ericjvandervelden at gmail.com (Eric J. Van der Velden) Date: Thu, 12 Aug 2010 06:43:30 -0700 (PDT) Subject: __class__ of what Message-ID: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Hello, I have, class C: n=0 def __init__(s): __class__.n+=1 I do >>> C() This is fine. But of what thing I am taking the __class__ of? I can also do @staticmethod def p(): print(__class__.n) >>> C.p() 1 Thanks, Eric J. From neilc at norwich.edu Thu Aug 12 09:44:51 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 12 Aug 2010 13:44:51 GMT Subject: Programming Puzzles? What's your favorite puzzle? References: Message-ID: <8cic6jF98kU1@mid.individual.net> On 2010-08-12, Dave Angel wrote: > For puzzles: > > http://projecteuler.net ...if you like math problems. > http://www.pythonchallenge.com ...if you like fooling around with PIL, graphics and bytes. -- Neil Cerutti From doug.shawhan at gmail.com Thu Aug 12 09:49:24 2010 From: doug.shawhan at gmail.com (Doug) Date: Thu, 12 Aug 2010 06:49:24 -0700 (PDT) Subject: Using elementtree to Create HTML Form / Set "selected" Message-ID: I'm using elementtree to create a form. I would like to set the "selected" attribute. Setting using the usual option.set( "selected" = "" ) gives me how does one make which is what I need. From ph4nut at gmail.com Thu Aug 12 09:54:11 2010 From: ph4nut at gmail.com (ph4nut) Date: Thu, 12 Aug 2010 06:54:11 -0700 (PDT) Subject: Does anyone use Quixote for web developing? References: <4c63c198$0$24088$426a74cc@news.free.fr> Message-ID: On Aug 12, 5:40?pm, Bruno Desthuilliers wrote: > ph4nut a ?crit : > > > Hi all,I am learning Quixote a few days ago,,,and i have no idea about > > whether there is any Google Group talking about Quixote,so i post this > > post to check that is Quixote been talking in this group before or can > > i ask question about Quixote here! > > ?From the project's home page: > > """ > There is a mailing list for discussing Quixote and you should look there > for information about obtaining the current release: > > ? ? ?* quixote-users > """ Thanks,I will have a check! From ph4nut at gmail.com Thu Aug 12 09:54:26 2010 From: ph4nut at gmail.com (ph4nut) Date: Thu, 12 Aug 2010 06:54:26 -0700 (PDT) Subject: Does anyone use Quixote for web developing? References: <4c63c198$0$24088$426a74cc@news.free.fr> Message-ID: <9317fc1d-bfe6-48e2-9588-3f3573f22445@u4g2000prn.googlegroups.com> On Aug 12, 5:40?pm, Bruno Desthuilliers wrote: > ph4nut a ?crit : > > > Hi all,I am learning Quixote a few days ago,,,and i have no idea about > > whether there is any Google Group talking about Quixote,so i post this > > post to check that is Quixote been talking in this group before or can > > i ask question about Quixote here! > > ?From the project's home page: > > """ > There is a mailing list for discussing Quixote and you should look there > for information about obtaining the current release: > > ? ? ?* quixote-users > """ Thanks,I will have a check! From jeanmichel at sequans.com Thu Aug 12 10:06:05 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 12 Aug 2010 16:06:05 +0200 Subject: __class__ of what In-Reply-To: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> References: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Message-ID: <4C63FFCD.9090007@sequans.com> Eric J. Van der Velden wrote: > Hello, > > I have, > > class C: > n=0 > def __init__(s): > __class__.n+=1 > > Should be class C: n = 0 def __init__(self): self.__class__.n+=1 C.n+=1 # equivalent to this line (I prefer this one, more readable, less refactor-friendly) @classmethod def p(cls): print(cls.n) JM From eric.brunel at pragmadev.com Thu Aug 12 10:07:22 2010 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 12 Aug 2010 16:07:22 +0200 Subject: __class__ of what References: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Message-ID: In article <72151646-65cb-47bb-bd55-e7eb67577c05 at z10g2000yqb.googlegroups.com>, "Eric J. Van der Velden" wrote: > Hello, > > I have, > > class C: > n=0 > def __init__(s): > __class__.n+=1 > > > I do > >>> C() > > This is fine. No it's not, at least in Python 2.x: >>> C() Traceback (most recent call last): File "", line 1, in File "", line 4, in __init__ NameError: global name '__class__' is not defined > But of what thing I am taking the __class__ of? Nothing, precisely. You should write s.__class__ (and replace s by self while you're at it). > I can also do > > @staticmethod > def p(): > print(__class__.n) > > >>> C.p() > 1 No you can't, again in Python 2.x: >>> C.p() Traceback (most recent call last): File "", line 1, in File "", line 4, in p NameError: global name '__class__' is not defined Unless I'm missing something or something fundamental changed in Python 3, your examples do not work? > Thanks, > > Eric J. From __peter__ at web.de Thu Aug 12 10:21:07 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 16:21:07 +0200 Subject: __class__ of what References: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Message-ID: Eric J. Van der Velden wrote: > I have, > > class C: > n=0 > def __init__(s): > __class__.n+=1 > > > I do >>>> C() > > This is fine. But of what thing I am taking the __class__ of? > I can also do > > @staticmethod > def p(): > print(__class__.n) > >>>> C.p() > 1 I had no idea that this existed. __class__ was probably added to make super() calls without an explicit class argument possible in Python 3. It is made available as a closure: >>> class A: ... def f(self): __class__ ... def g(self): pass ... >>> A.f.__closure__[0].cell_contents >>> A.g.__closure__ is None True Peter From __peter__ at web.de Thu Aug 12 10:47:55 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 16:47:55 +0200 Subject: Using elementtree to Create HTML Form / Set "selected" References: Message-ID: Doug wrote: > I'm using elementtree to create a form. > > I would like to set the "selected" attribute. > > Setting using the usual > option.set( "selected" = "" ) Maybe that should be option.set(selected="selected"). I think > how does one make > > which is what I need. From doug.shawhan at gmail.com Thu Aug 12 10:55:24 2010 From: doug.shawhan at gmail.com (Doug) Date: Thu, 12 Aug 2010 07:55:24 -0700 (PDT) Subject: Using elementtree to Create HTML Form / Set "selected" References: Message-ID: <1b59481f-8a5a-41e3-9d09-baeb8a1f027b@d8g2000yqf.googlegroups.com> On Aug 12, 10:47?am, Peter Otten <__pete... at web.de> wrote: > Doug wrote: > > I'm using elementtree to create a form. > > > I would like to set the "selected" attribute. > > > Setting using the usual > > ?option.set( "selected" = "" ) > > Maybe that should be option.set(selected="selected"). I think > > > > how does one make > > ? > > which is what I need. Makes sense to me. Thanks! From sschwarzer at sschwarzer.net Thu Aug 12 11:05:45 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 12 Aug 2010 17:05:45 +0200 Subject: __class__ of what In-Reply-To: References: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Message-ID: <4C640DC9.80105@sschwarzer.net> Hello Jean-Michel, On 2010-08-12 16:06, Jean-Michel Pichavant wrote: > Eric J. Van der Velden wrote: > Should be > > class C: > n = 0 > def __init__(self): > self.__class__.n+=1 > C.n+=1 # equivalent to this line (I prefer this one, more > readable, less refactor-friendly) I think both lines have slightly different semantics if you consider instantiating an object of a derived class. (The following formatting is from IPython, thus the differences to the "usual" interpreter output.) Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >>> class C(object): ... n = 0 ... def __init__(self): ... self.__class__.n += 1 ... >>> class D(C): ... pass ... >>> d = D() >>> D.n 1 >>> C.n 0 Here, the augmented assignment looks up self.__class__.n which it doesn't find and so gets it from class C. The actual assignment assigns to D.n, however. On the other hand: >>> class C(object): ... n = 0 ... def __init__(self): ... C.n += 1 ... >>> class D(C): ... pass ... >>> d = D() >>> D.n 1 >>> C.n 1 Here, only C is changed. D doesn't get an own attribute n, and after the instantiation of d, D.n looks up and gets n from the base class C. Curiously, >>> dir(D) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'n'] seems to contain n (is it supposed to be listed here?), but >>> dict(D.__dict__) {'__doc__': None, '__module__': '__main__'} indicates that D doesn't contain n. But C does: >>> dict(C.__dict__) {'__dict__': , '__doc__': None, '__init__': , '__module__': '__main__', '__weakref__': , 'n': 1} I hope everything I wrote above is valid. If not, please correct me. :-) Anyway, depending on what you want, either of the two variants might be ok. In any case I'd include a meaningful comment on why you actually wrote what you wrote. :-) Stefan From dlanorslegov at rocketmail.com Thu Aug 12 11:12:33 2010 From: dlanorslegov at rocketmail.com (Dlanor Slegov) Date: Thu, 12 Aug 2010 08:12:33 -0700 (PDT) Subject: Inserting/Deleting newline(s) in very large text files Message-ID: <595550.37557.qm@web120110.mail.ne1.yahoo.com> Hi, I am dealing with very large text files (a few million lines) and would like to check and modify them according to a well defined format. The format requires?ONLY ONE?NEWLINE (followed by some sort of text) on top of the file and NO NEWLINE in the very end. The input files can be very diverse, such as?one file may have 2 newlines on top and none in the end or other may not have a newline on top and 5 in the end. The aim is to check these files &?introduce JUST ONE NEWLINE in the?TOP and NO NEWLINE in the BOTTOM. Any pointers will be appreciated. Thanks, DS. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Thu Aug 12 11:24:40 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 12 Aug 2010 09:24:40 -0600 Subject: Programming Puzzles? What's your favorite puzzle? In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 5:41 AM, Matty Sarro wrote: > Hey All! > Hope your thursday is treating you well. I'm looking for suggestions on > books of programming/engineering puzzles that range from beginners to > advanced and even expert level problems. I know they exist; we had them back > in college for practicing before the ACM programming competitions. However I > can't seem to really find any books out there that look like they're what > I'm seeking. Basically I haven't programmed a lot since I was in college, > and that was about 9 years ago. I'm expected to do a bit more programming at > my current job and I figure the best way to get back into things is to have > some practical things to solve, and maybe have a bit of fun in the process. > > Anyone have any suggestions? http://www.spoj.pl/ http://www.codechef.com/ Many of the problems at those sites are difficult in Python due to the time constraints, but they're well worth checking out. Cheers, Ian From p.c.j.kleiweg at rug.nl Thu Aug 12 11:36:38 2010 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Thu, 12 Aug 2010 17:36:38 +0200 (CEST) Subject: Announcing: python-ghostscript 0.3 In-Reply-To: References: Message-ID: Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010: > Here is an example for how to use the high-level interface of > `python-ghostscript`. This implements a very basic ps2pdf-tool:: > > import sys > import ghostscript > > args = [ > "ps2pdf", # actual value doesn't matter > "-dNOPAUSE", "-dBATCH", "-dSAFER", > "-sDEVICE=pdfwrite", > "-sOutputFile=" + sys.argv[1], > "-c", ".setpdfwrite", > "-f", sys.argv[2] > ] > > ghostscript.Ghostscript(*args) How is this different from os.system(' '.join(args)) ? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From p.c.j.kleiweg at rug.nl Thu Aug 12 11:36:38 2010 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Thu, 12 Aug 2010 17:36:38 +0200 Subject: Announcing: python-ghostscript 0.3 In-Reply-To: References: Message-ID: Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010: > Here is an example for how to use the high-level interface of > `python-ghostscript`. This implements a very basic ps2pdf-tool:: > > import sys > import ghostscript > > args = [ > "ps2pdf", # actual value doesn't matter > "-dNOPAUSE", "-dBATCH", "-dSAFER", > "-sDEVICE=pdfwrite", > "-sOutputFile=" + sys.argv[1], > "-c", ".setpdfwrite", > "-f", sys.argv[2] > ] > > ghostscript.Ghostscript(*args) How is this different from os.system(' '.join(args)) ? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From bavantgarde at yahoo.com Thu Aug 12 11:44:19 2010 From: bavantgarde at yahoo.com (BAvant Garde) Date: Thu, 12 Aug 2010 08:44:19 -0700 (PDT) Subject: unicode string alteration Message-ID: <155711.87581.qm@web83402.mail.sp1.yahoo.com> HELP!!! I need help with a unicode issue that has me stumped. I must be doing something? wrong because I don't believe this condition would have slipped thru testing. Wherever the string u'\udbff\udc00' occurs u'\U0010fc00' or unichr(1113088) is substituted and the file loses 1 character resulting in all trailing characters being shifted out of position. No other corrupt strings have been detected. ? ? The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04 where the maximum ord # is 1114111 (wide Python build). ? ? Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535 (narrow Python build) the string u'\U0010fc00' also occurs and it "seems" that the substitution takes place but no characters are lost and file sizes are ok. Note that ord(u'\U0010fc00') causes the following error: ???????????? "TypeError: ord() expected a character, but string of length 2 found" The condition is otherwise invisible in 2.5.4 and is handled internally without any apparent effect on processing with characters u'\udbff' and u'\udc00' each being separately accessible. The first part of the attachment repeats this email but also has examples and illustrates other related oddities. ? ? Any help would be greatly appreciated. Bruce -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: unicode_internals_question_linux2.txt URL: From nawabadeel at gmail.com Thu Aug 12 11:56:27 2010 From: nawabadeel at gmail.com (Sohail) Date: Thu, 12 Aug 2010 08:56:27 -0700 (PDT) Subject: How to parse a sentence using grammars provided by nltk? Message-ID: <1bf11039-012c-4f77-824e-4e7fc4c3eab0@a36g2000yqc.googlegroups.com> Hi, When I define my own production rules for the grammar the code below runs fine. Can anyone tell me how to use the built in grammars of nltk (if there are any)? >>> groucho_grammar = nltk.parse_cfg(""" ... S -> NP VP ... PP -> P NP ... NP -> Det N | Det N PP | 'I' ... VP -> V NP | VP PP ... Det -> 'an' | 'my' ... N -> 'elephant' | 'pajamas' ... V -> 'shot' ... P -> 'in' ... """) >>> sent = ['I', 'shot', 'an', 'elephant', 'in', 'my', 'pajamas'] >>> parser = nltk.ChartParser(groucho_grammar) >>> trees = parser.nbest_parse(sent) >>> for tree in trees: ... print tree thanks From zac256 at gmail.com Thu Aug 12 12:13:42 2010 From: zac256 at gmail.com (Zac Burns) Date: Thu, 12 Aug 2010 09:13:42 -0700 Subject: Extract stack from running python program Message-ID: Is there a utility to extract the stacks from a running python program that is hung? Sounds like a long shot but if anyone knows it would be you guys. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu Aug 12 12:16:08 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 17:16:08 +0100 Subject: Renaming OS files by file type in python In-Reply-To: <953bbeb2-b3a5-4882-999f-184f2a51d331@x24g2000pro.googlegroups.com> References: <953bbeb2-b3a5-4882-999f-184f2a51d331@x24g2000pro.googlegroups.com> Message-ID: <4C641E48.6080308@mrabarnett.plus.com> blur959 wrote: > Hi all, I am creating a program that renames all files of the similar > file type. But i am stuck at this part. I tried running this code and > I got this error: new_name = os.rename(path, newpath) > WindowsError: [Error 183] Cannot create a file when that file already > exists. Hope you guys could help. > [snip] As the traceback says, a file with that new name already exists. You can't have 2 files with the same name in the same folder. From dreadpiratejeff at gmail.com Thu Aug 12 12:19:22 2010 From: dreadpiratejeff at gmail.com (J) Date: Thu, 12 Aug 2010 12:19:22 -0400 Subject: OptParse and Constant values Message-ID: How do you use OptParse with constants? Example: usage = 'Usage: %prog [OPTIONS]' parser = OptionParser(usage) parser.add_option('-l','--level', action='store_const', default=LOG_INFO, help='Set the log level to inject into syslog (either an\ integer [0 - 7] or one of LOG_EMERG, LOG_ALERT,LOG_CRIT,\ LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG') (options,args) = parser.parse_args() print options always returns {'level':None} regarless of whether I call it with an int (0 - 7) or the const name (LOG_*) I'm importing syslog like so: from syslog import * so all the syslog constants should be available to me at run time (at least that's my understanding) so I'm doing something wrong here or just not understanding how to do a constant as an option. The basic gist of the above is that I'm writing a tool to do basic syslog testing by injecting messages and making sure they end up in the correct log file... I can do all of this manually or in a loop by looping through the various log levels, however, I want to be able to specify them at run-time using an optional argument. Any ideas on how to make this work, or at least why it's not doing what I thought it would do? Cheers Jeff From robert.kern at gmail.com Thu Aug 12 12:41:40 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Aug 2010 11:41:40 -0500 Subject: OptParse and Constant values In-Reply-To: References: Message-ID: On 8/12/10 11:19 AM, J wrote: > How do you use OptParse with constants? > > Example: > usage = 'Usage: %prog [OPTIONS]' > parser = OptionParser(usage) > parser.add_option('-l','--level', > action='store_const', > default=LOG_INFO, > help='Set the log level to inject into syslog (either an\ > integer [0 - 7] or one of LOG_EMERG, LOG_ALERT,LOG_CRIT,\ > LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG') > (options,args) = parser.parse_args() > > print options > > always returns {'level':None} regarless of whether I call it with an > int (0 - 7) or the const name (LOG_*) http://docs.python.org/library/optparse#standard-option-actions 'store_const' means that the option is a flag without arguments and stores the value provided by the 'const' keyword to add_option() (it defaults to None so that's what you get when you use that flag). This is not what you want. You just want the default 'store' action. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From john at castleamber.com Thu Aug 12 13:22:15 2010 From: john at castleamber.com (John Bokma) Date: Thu, 12 Aug 2010 12:22:15 -0500 Subject: Long rant about Python in Education References: Message-ID: <87tymz4ugo.fsf@castleamber.com> "D'Arcy J.M. Cain" writes: > On Thu, 12 Aug 2010 05:05:55 -0700 (PDT) > ??????? wrote: >> have to teach them to enjoy programming, enjoy computers, and develop >> their minds in a way that doesn't involve becoming 'Imams' who are >> essentially the learned mafia bosses of terrorism. > > This is the point that I stopped reading your "message" and added you > to my blacklist. Goodbye. For what it's worth, same here. Also, I don't think it's a good idea to force a learning environment or an OS on a child. IMO it works best if you let the child discover and be a guide, not "thou should not use Windows". Not so remarkable that the rant moves from an extremistic teaching environment to an extremistic world view. From hating everything that's not Linux and idolizing the CLI to hating everything that is different in general. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From python at mrabarnett.plus.com Thu Aug 12 13:31:29 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 18:31:29 +0100 Subject: unicode string alteration In-Reply-To: <155711.87581.qm@web83402.mail.sp1.yahoo.com> References: <155711.87581.qm@web83402.mail.sp1.yahoo.com> Message-ID: <4C642FF1.1050508@mrabarnett.plus.com> BAvant Garde wrote: > HELP!!! > I need help with a unicode issue that has me stumped. I must be doing > something wrong because I don't believe this condition would have > slipped thru testing. > > Wherever the string u'\udbff\udc00' occurs u'\U0010fc00' or > unichr(1113088) is substituted and the file loses 1 character resulting > in all trailing characters being shifted out of position. No other > corrupt strings have been detected. > > The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04 > where the maximum ord # is 1114111 (wide Python build). > > Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535 > (narrow Python build) the string u'\U0010fc00' also occurs and it > "seems" that the substitution takes place but no characters are lost and > file sizes are ok. Note that ord(u'\U0010fc00') causes the following error: > "TypeError: ord() expected a character, but string of > length 2 found" > The condition is otherwise invisible in 2.5.4 and is handled internally > without any apparent effect on processing with characters u'\udbff' and > u'\udc00' each being separately accessible. > > The first part of the attachment repeats this email but also has > examples and illustrates other related oddities. > > Any help would be greatly appreciated. > It's not an error, it's a "surrogate pair". Surrogate pairs are part of the Unicode specification. Unicode codepoints go up to U+0010FFFF. If you're using 16 bits per codepoint, like in a narrow build of Python, then the codepoints above U+FFFF _can't_ be represented directly, so they are represented by a pair of codepoints called a "surrogate pair". If, on the other hand, you're using 32 bits per codepoint, like in a wide build of Python, then the codepoints above U+FFFF _can_ be represented directly, so surrogate pairs aren't needed, and, indeed shouldn't be there. What you're seeing in the wide build is Python replacing a surrogate pair with the codepoint that it represents, which is actually the right thing to do because, as I said, the surrogate pairs really shouldn't be there. From rNOSPAMon at flownet.com Thu Aug 12 13:36:37 2010 From: rNOSPAMon at flownet.com (RG) Date: Thu, 12 Aug 2010 10:36:37 -0700 Subject: Why can't I set sys.ps1 to a unicode string? References: Message-ID: In article , "Martin v. Loewis" wrote: > > So... why does having a non-ascii character in sys.ps1 make the prompt > > vanish? > > I can't pinpoint it to a specific line of code. Most likely, it tries > to encode the prompt as ASCII before writing it to stdout. That fails, > and it silently ignores the error. > > FWIW, this is fixed in Python 3. Guess it's time to upgrade. :-) Thanks! rg From wherespythonmonks at gmail.com Thu Aug 12 13:45:12 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 13:45:12 -0400 Subject: inline exception handling in python Message-ID: Hi! I have on a few occasions now wanted to have inline-exception handling, like the inline if/else operator. For example, The following might raise ZeroDivisionError: f = n / d So, I can look before I leap (which is okay): f = float("nan") if d == 0 else n/d; But, what I'd like to be able to write is: f = n / d except float("nan"); Which I find much more appealing than: try: f = n / d except: f = float("nan") (Obviously, I am thinking about more complicated functions than "n/d" -- but this works as an example.) Thoughts? W From dreadpiratejeff at gmail.com Thu Aug 12 13:47:53 2010 From: dreadpiratejeff at gmail.com (J) Date: Thu, 12 Aug 2010 13:47:53 -0400 Subject: OptParse and Constant values In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 12:41, Robert Kern wrote: > On 8/12/10 11:19 AM, J wrote: >> >> How do you use OptParse with constants? > http://docs.python.org/library/optparse#standard-option-actions > > 'store_const' means that the option is a flag without arguments and stores > the value provided by the 'const' keyword to add_option() (it defaults to > None so that's what you get when you use that flag). This is not what you > want. You just want the default 'store' action. Thanks Robert... Sigh... head -> desk -> repeat :) From thomas at jollybox.de Thu Aug 12 14:08:01 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 20:08:01 +0200 Subject: inline exception handling in python In-Reply-To: References: Message-ID: <201008122008.02041.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: > try: > f = n / d > except: > f = float("nan") A catch-all except clause. Never a good idea. It's not as bad in this case, as there is only one expression, but there are still a couple of other exceptions that have a chance of occurring here: KeyboardInterrupt and SystemExit. So: try: f = n / d except ZeroDivisionError: f = float('nan') > f = n / d except float("nan"); So this syntax really isn't adequate for real use: catch-all except clauses are frowned upon, and rightfully so. Besides, more often than not, you want to have a finally clause around when you're dealing with exceptions. > (Obviously, I am thinking about more complicated functions than "n/d" > -- but this works as an example.) The more complex the function is, the more likely it is to raise an exception you can't handle that easily. From wherespythonmonks at gmail.com Thu Aug 12 14:19:13 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 14:19:13 -0400 Subject: inline exception handling in python In-Reply-To: <201008122008.02041.thomas@jollybox.de> References: <201008122008.02041.thomas@jollybox.de> Message-ID: On Thu, Aug 12, 2010 at 2:08 PM, Thomas Jollans wrote: > On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: >> try: >> ? ?f = n / d >> except: >> ? ?f = float("nan") > > A catch-all except clause. Never a good idea. It's not as bad in this case, as > there is only one expression, but there are still a couple of other exceptions > that have a chance of occurring here: KeyboardInterrupt and SystemExit. > So: > > try: > ? ?f = n / d > except ZeroDivisionError: > ? ?f = float('nan') > > >> f = n / d except float("nan"); > > So this syntax really isn't adequate for real use: catch-all except clauses > are frowned upon, and rightfully so. > > Besides, more often than not, you want to have a finally clause around when > you're dealing with exceptions. > > >> (Obviously, I am thinking about more complicated functions than "n/d" >> -- but this works as an example.) > > The more complex the function is, the more likely it is to raise an exception > you can't handle that easily. > -- > http://mail.python.org/mailman/listinfo/python-list > With a bit imagination the syntax can handle specific exceptions: f = n /d except except(ZeroDivisionError) float("nan") f = n /d except except(ZeroDivisionError) float("nan") except(ValueError) float("nan") But then we cannot bind to useful variable you say... I think the problem in my case is best solved by look before you leap, or a wrapper function. [I just hate function call overhead for this. ] Thanks, W From wherespythonmonks at gmail.com Thu Aug 12 14:25:25 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 14:25:25 -0400 Subject: inline exception handling in python In-Reply-To: References: <201008122008.02041.thomas@jollybox.de> Message-ID: On Thu, Aug 12, 2010 at 2:19 PM, wheres pythonmonks wrote: > On Thu, Aug 12, 2010 at 2:08 PM, Thomas Jollans wrote: >> On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: >>> try: >>> ? ?f = n / d >>> except: >>> ? ?f = float("nan") >> >> A catch-all except clause. Never a good idea. It's not as bad in this case, as >> there is only one expression, but there are still a couple of other exceptions >> that have a chance of occurring here: KeyboardInterrupt and SystemExit. >> So: >> >> try: >> ? ?f = n / d >> except ZeroDivisionError: >> ? ?f = float('nan') >> >> >>> f = n / d except float("nan"); >> >> So this syntax really isn't adequate for real use: catch-all except clauses >> are frowned upon, and rightfully so. >> >> Besides, more often than not, you want to have a finally clause around when >> you're dealing with exceptions. >> >> >>> (Obviously, I am thinking about more complicated functions than "n/d" >>> -- but this works as an example.) >> >> The more complex the function is, the more likely it is to raise an exception >> you can't handle that easily. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > With a bit imagination the syntax can handle specific exceptions: > > f = n /d except except(ZeroDivisionError) float("nan") > > f = n /d except except(ZeroDivisionError) float("nan") > except(ValueError) float("nan") > > But then we cannot bind to useful variable you say... > > I think the problem in my case is best solved by look before you leap, > or a wrapper function. ?[I just hate function call overhead for this. > ] > > Thanks, > > W > I mean something along these lines: f = n /d except(ZeroDivisionError) float("nan") except(ValueError) float("nan") From raoulbia at gmail.com Thu Aug 12 14:37:43 2010 From: raoulbia at gmail.com (Baba) Date: Thu, 12 Aug 2010 11:37:43 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> Message-ID: <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Hi News123 Thank You for helping me out. Indeed i am not looking for the code but rather for hints that direct my reasoning as well as hints as to how to write basic programs like this. You have broken down the approach into 2 parts. I have tried to solve part 1 but i'm not quite there yet. Here's my code: def can_buy(n_nuggets): for a in range (1,n_nuggets): for b in range (1,n_nuggets): for c in range (1,n_nuggets): if 6*a+9*b+20*c==n_nuggets: #print a,b,c,'n_nuggets=',n_nuggets return True else: return False can_buy(55) as you can see i am trying to loop through all combinations of values bewtween 1 and n_nuggets and when the equation resolves it should return True, else it should return False. I was hoping that when i then call my function and ask it to test a value nothing happens. What is wrong? My syntax? My semantic? Both? tnx Baba From python at mrabarnett.plus.com Thu Aug 12 14:42:12 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 19:42:12 +0100 Subject: inline exception handling in python In-Reply-To: References: Message-ID: <4C644084.9040500@mrabarnett.plus.com> wheres pythonmonks wrote: > Hi! > > I have on a few occasions now wanted to have inline-exception > handling, like the inline if/else operator. > > For example, > > The following might raise ZeroDivisionError: > > f = n / d > > So, I can look before I leap (which is okay): > > f = float("nan") if d == 0 else n/d; > > But, what I'd like to be able to write is: > > f = n / d except float("nan"); > > Which I find much more appealing than: > > try: > f = n / d > except: > f = float("nan") > > (Obviously, I am thinking about more complicated functions than "n/d" > -- but this works as an example.) > > Thoughts? > Discussed a year ago: [Python-Dev] (try-except) conditional expression similar to (if-else) conditional (PEP 308) http://code.activestate.com/lists/python-dev/90256/ From wherespythonmonks at gmail.com Thu Aug 12 14:54:07 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 14:54:07 -0400 Subject: inline exception handling in python In-Reply-To: <4C644084.9040500@mrabarnett.plus.com> References: <4C644084.9040500@mrabarnett.plus.com> Message-ID: On Thu, Aug 12, 2010 at 2:42 PM, MRAB wrote: > wheres pythonmonks wrote: >> >> Hi! >> >> I have on a few occasions now wanted to have inline-exception >> handling, like the inline if/else operator. >> >> For example, >> >> The following might raise ZeroDivisionError: >> >> f = n / d >> >> So, I can look before I leap (which is okay): >> >> f = float("nan") if d == 0 else n/d; >> >> But, what I'd like to be able to write is: >> >> f = n / d except float("nan"); >> >> Which I find much more appealing than: >> >> try: >> ? f = n / d >> except: >> ? f = float("nan") >> >> (Obviously, I am thinking about more complicated functions than "n/d" >> -- but this works as an example.) >> >> Thoughts? >> > Discussed a year ago: > > [Python-Dev] (try-except) conditional expression similar to (if-else) > conditional (PEP 308) > > http://code.activestate.com/lists/python-dev/90256/ > > -- > http://mail.python.org/mailman/listinfo/python-list > http://code.activestate.com/lists/python-dev/90256/ Nice -- excellent discussion and what I was looking for. I am guessing that no implementation materialized. From thomas at jollybox.de Thu Aug 12 14:57:02 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 20:57:02 +0200 Subject: inline exception handling in python In-Reply-To: References: <201008122008.02041.thomas@jollybox.de> Message-ID: <201008122057.03688.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: > [I just hate function call overhead for this.] I think you've got your priorities wrong. If you want to avoid unnecessary overhead, avoid exceptions more than functions. From homeusenet4 at brianhv.org Thu Aug 12 15:00:17 2010 From: homeusenet4 at brianhv.org (Brian Victor) Date: Thu, 12 Aug 2010 19:00:17 +0000 (UTC) Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: Baba wrote: > def can_buy(n_nuggets): [snip] > can_buy(55) > > as you can see i am trying to loop through all combinations of values > bewtween 1 and n_nuggets and when the equation resolves it should > return True, else it should return False. > > I was hoping that when i then call my function and ask it to test a > value nothing happens. What is wrong? My syntax? My semantic? Both? You're calling the function, but you're not doing anything with the result. If you use "print can_buy(55)" you'll see the result on the console. Presumably you'll actually want to use it in an if statement. -- Brian From tormod.hagen at gmail.com Thu Aug 12 15:00:34 2010 From: tormod.hagen at gmail.com (tormod) Date: Thu, 12 Aug 2010 12:00:34 -0700 (PDT) Subject: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT) References: Message-ID: <7762bda5-e1dc-461c-82a1-7eaa431b5bef@x25g2000yqj.googlegroups.com> On Aug 12, 12:30?pm, Alexander Gattin wrote: > Does Windows have anything like > LD_LIBRARY_PATH/SHLIB_PATH? No, isn't that only if I have an actual Oracle client installed (not the instant client)? But great tip, wasn't exactly the solution, but your question triggered me to check the Windows environment variables*. I included env. variable name PATH and the value ;C:\Python31;C:\MinGW\bin;C:\TEMP \ORAIC10\bin. Only thing I set manually in the command prompt was: SET ORACLE_HOME=C: \TEMP\ORAIC10 , before the build. *=I checked the setup.py script which says: userOracleHome = os.environ.get("ORACLE_HOME") Checking in Visual Basic::environ("path") only included info from the Windows env. variables, and not the ones I set via the command prompt with PATH=%PATH%;... so I reckon if it applies to VB it also does for os.environ I can now import without errors! Thanks Alexander for putting me in the right direction. From __peter__ at web.de Thu Aug 12 15:02:40 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 21:02:40 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: Baba wrote: > Thank You for helping me out. Indeed i am not looking for the code but > rather for hints that direct my reasoning as well as hints as to how > to write basic programs like this. > > You have broken down the approach into 2 parts. I have tried to solve > part 1 but i'm not quite there yet. Here's my code: > > def can_buy(n_nuggets): > for a in range (1,n_nuggets): > for b in range (1,n_nuggets): > for c in range (1,n_nuggets): > if 6*a+9*b+20*c==n_nuggets: > #print a,b,c,'n_nuggets=',n_nuggets > return True > else: > return False > > > can_buy(55) > > as you can see i am trying to loop through all combinations of values > bewtween 1 and n_nuggets and when the equation resolves it should > return True, else it should return False. > > I was hoping that when i then call my function and ask it to test a > value nothing happens. What is wrong? My syntax? My semantic? Both? First, the function gives up too early; it should only return False when all combinations of a, b, c (technically: the product of the ranges) have been tried. Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + 0*20 is never tried; fix your ranges accordingly. Peter From tjreedy at udel.edu Thu Aug 12 15:10:32 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Aug 2010 15:10:32 -0400 Subject: urllib2 does not implement "with" Python 2.6 In-Reply-To: <4c6387f8$0$1587$742ec2ed@news.sonic.net> References: <4c6387f8$0$1587$742ec2ed@news.sonic.net> Message-ID: On 8/12/2010 1:34 AM, John Nagle wrote: > Somewhat to my surprise, in Python 2.6, > > with urllib2.urlopen(url) as fh : > > doesn't work. It fails with > "AttributeError: addinfourl instance has no attribute '__exit__'". > > I thought that all the file-like objects supported "with" in 2.6. > No? This seems to work in 3.1, which first came out almost a year after 2.6. from urllib.request import urlopen with urlopen("http://www.python.org") as fh : pass -- Terry Jan Reedy From aahz at pythoncraft.com Thu Aug 12 15:24:14 2010 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2010 12:24:14 -0700 Subject: image resize doesn't work References: Message-ID: In article , Chris Hare wrote: > >And I see now what I did wrong - thanks for putting up with the questions. Posting that information is useful for any other newbies who might be following along.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From thomas at jollybox.de Thu Aug 12 15:25:59 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 21:25:59 +0200 Subject: Inserting/Deleting newline(s) in very large text files In-Reply-To: <595550.37557.qm@web120110.mail.ne1.yahoo.com> References: <595550.37557.qm@web120110.mail.ne1.yahoo.com> Message-ID: <201008122125.59751.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to Dlanor Slegov to exclaim: > Hi, > > I am dealing with very large text files (a few million lines) and would > like to check and modify them according to a well defined format. The > format requires ONLY ONE NEWLINE (followed by some sort of text) on top of > the file and NO NEWLINE in the very end. The input files can be very > diverse, such as one file may have 2 newlines on top and none in the end > or other may not have a newline on top and 5 in the end. > > > The aim is to check these files & introduce JUST ONE NEWLINE in the TOP and > NO NEWLINE in the BOTTOM. > > Any pointers will be appreciated. If the files are that long, you might want to avoid storing the whole file in memory at the same time. Have you already tried writing the program? If not, go write the program! (and then come back, possibly, if you have questions) PS: What a strange format that must be. Everybody agrees that text files should end with a line feed, because some text editors might mess up if they don't. From aahz at pythoncraft.com Thu Aug 12 15:31:46 2010 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2010 12:31:46 -0700 Subject: exception handling with sqlite db errors References: <2a47b306-45d1-474a-9f8e-5b71eba629c9@p11g2000prf.googlegroups.com> Message-ID: In article <2a47b306-45d1-474a-9f8e-5b71eba629c9 at p11g2000prf.googlegroups.com>, CM wrote: > >Maybe it's not much of an issue, but I think it would be a shame if >occasional hangs/crashes could be caused by these (rare?) database >conflicts if there is a good approach for avoiding them. I guess I >could put every last write to the db in a try/except block but I >thought there should be a more general solution, since that will >require many such exceptions and seems inelegant. Wrap all your uses of sqlite into a function that does the try/except; you only write the code once, then. As you progress, you can also change the code to retry operations. Here's some ugly code I wrote on top of SQLObject: from sqlobject.dbconnection import registerConnection from sqlobject.sqlite.sqliteconnection import SQLiteConnection class RetrySQLiteConnection(SQLiteConnection): """ Because SQLite is not really concurrent, having multiple processes read/write can result in locked DB failures. In addition, SQLObject doesn't properly protect operations in transations, so you can get spurious DB errors claiming that the DB is corrupt because of foreign key integrity failures. This subclass retries DatabaseError and OperationalError exceptions. """ MAX_RETRIES = 4 SAFE_DB_ERROR = [ 'database disk image is malformed', 'file is encrypted or is not a database', ] def _safe_db_error(self, exception): err = str(exception).lower() for safe_err in self.SAFE_DB_ERROR: if safe_err in err: return True return False def _check_integrity(self): conn = self.getConnection() try: i = 0 while True: i += 1 try: cursor = conn.cursor() query = "pragma integrity_check" SQLiteConnection._executeRetry(self, conn, cursor, query) result = cursor.fetchall() if result == [('ok',)]: return True else: logging.error("Bad integrity result: %s", result) return False except DatabaseError, e: if i < self.MAX_RETRIES: logging.info('integrity_check, try #%s: %s', i, e) time.sleep(2) else: logging.error('integrity_check, try #%s: %s', i, e) raise finally: self.releaseConnection(conn) def _executeRetry(self, conn, cursor, query): i = 0 while True: i += 1 try: return SQLiteConnection._executeRetry(self, conn, cursor, query) except OperationalError, e: if i < self.MAX_RETRIES: logging.warn('OperationalError, try #%s: %s', i, e) time.sleep(10) else: logging.error('OperationalError, try #%s: %s', i, e) raise except DatabaseError, e: if e.__class__ is not DatabaseError: # Don't retry e.g. IntegrityError raise if not self._safe_db_error(e): # Only retry specific errors raise if not self._check_integrity(): raise if i < self.MAX_RETRIES: logging.warn('DatabaseError, try #%s: %s', i, e) time.sleep(0.5) else: logging.error('DatabaseError, try #%s: %s', i, e) raise def conn_builder(): return RetrySQLiteConnection registerConnection(['retrysqlite'], conn_builder) def init(): dbpath = os.path.join(common.getSyncDataPath(), app.dbname) connection_string = "retrysqlite:" + dbpath global _connection _connection = connectionForURI(connection_string) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From nobody at nowhere.com Thu Aug 12 15:32:43 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 12 Aug 2010 20:32:43 +0100 Subject: Line-by-line processing when stdin is not a tty References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: On Wed, 11 Aug 2010 18:49:26 -0700, RG wrote: > This doesn't explain why "cat | cat" when run interactively outputs > line-by-line (which it does). STDIN to the first cat is a TTY, but the > second one isn't. GNU cat doesn't use stdio, it uses read() and write(), so there isn't any buffering. For more complex programs, using unbuffered I/O may not be practical, due to either code complexity or performance. From aahz at pythoncraft.com Thu Aug 12 15:32:54 2010 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2010 12:32:54 -0700 Subject: Announcing: python-ghostscript 0.3 References: Message-ID: In article , Peter Kleiweg wrote: >Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010: > >> Here is an example for how to use the high-level interface of >> `python-ghostscript`. This implements a very basic ps2pdf-tool:: >> >> import sys >> import ghostscript >> >> args = [ >> "ps2pdf", # actual value doesn't matter >> "-dNOPAUSE", "-dBATCH", "-dSAFER", >> "-sDEVICE=pdfwrite", >> "-sOutputFile=" + sys.argv[1], >> "-c", ".setpdfwrite", >> "-f", sys.argv[2] >> ] >> >> ghostscript.Ghostscript(*args) > >How is this different from os.system(' '.join(args)) ? You don't have problems with shell metacharacters. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From python at mrabarnett.plus.com Thu Aug 12 15:34:34 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 20:34:34 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: <4C644CCA.4060402@mrabarnett.plus.com> Baba wrote: > Hi News123 > > Thank You for helping me out. Indeed i am not looking for the code but > rather for hints that direct my reasoning as well as hints as to how > to write basic programs like this. > > You have broken down the approach into 2 parts. I have tried to solve > part 1 but i'm not quite there yet. Here's my code: > > def can_buy(n_nuggets): > for a in range (1,n_nuggets): > for b in range (1,n_nuggets): > for c in range (1,n_nuggets): > if 6*a+9*b+20*c==n_nuggets: > #print a,b,c,'n_nuggets=',n_nuggets > return True > else: > return False > > > can_buy(55) > > as you can see i am trying to loop through all combinations of values > bewtween 1 and n_nuggets and when the equation resolves it should > return True, else it should return False. > > I was hoping that when i then call my function and ask it to test a > value nothing happens. What is wrong? My syntax? My semantic? Both? > Think about it this way. How many packs of 20 would you need? You don't want too many, but too few is OK. Then, how many packs of 9 for the remaining nuggets? (Again, you don't want too many.) Then, how many packs of 6? If all the nuggets are accounted for, good, otherwise reduce the number of one of the packs and try again. Repeat as necessary. A couple of 'for' loops will do it. From thomas at jollybox.de Thu Aug 12 15:36:18 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 21:36:18 +0200 Subject: Why can't I set sys.ps1 to a unicode string? In-Reply-To: References: Message-ID: <201008122136.19067.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to RG to exclaim: > %%% /&%%% > > If this were a properly unicode-enabled newsreader you would see a > yin-yang symbol in the middle of s2. Are you sure about that? Now maybe the mailing list gateway is messing things up, but I rather suspect your newsreader (or USENET server) is sending out nonsense. After all, Unicode usually works around here. Some excerpts from the message, as I received it: Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit [...] >>> print s2 %%% /&%%% No quoted-printable. No UTF-7. Just three completely random characters? From downaold at gmail.com Thu Aug 12 15:42:59 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 12 Aug 2010 21:42:59 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: <37E4ACD0-BEC1-4693-8DB5-66FB342D73A9@gmail.com> On Aug 12, 2010, at 9:02 PM, Peter Otten wrote: > Baba wrote: > > >> Thank You for helping me out. Indeed i am not looking for the code >> but >> rather for hints that direct my reasoning as well as hints as to how >> to write basic programs like this. >> >> You have broken down the approach into 2 parts. I have tried to solve >> part 1 but i'm not quite there yet. Here's my code: >> >> def can_buy(n_nuggets): >> for a in range (1,n_nuggets): >> for b in range (1,n_nuggets): >> for c in range (1,n_nuggets): >> if 6*a+9*b+20*c==n_nuggets: >> #print a,b,c,'n_nuggets=',n_nuggets >> return True >> else: >> return False >> >> >> can_buy(55) >> >> as you can see i am trying to loop through all combinations of values >> bewtween 1 and n_nuggets and when the equation resolves it should >> return True, else it should return False. >> >> I was hoping that when i then call my function and ask it to test a >> value nothing happens. What is wrong? My syntax? My semantic? Both? > > First, the function gives up too early; it should only return False > when all > combinations of a, b, c (technically: the product of the ranges) > have been > tried. > > Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + > 0*20 is > never tried; fix your ranges accordingly. Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and n_nuggets/20 respectively. This will work, but does too much work. Cheers, Roald From p.c.j.kleiweg at rug.nl Thu Aug 12 15:55:47 2010 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Thu, 12 Aug 2010 21:55:47 +0200 Subject: Announcing: python-ghostscript 0.3 In-Reply-To: References: Message-ID: Aahz schreef op de 12e dag van de oogstmaand van het jaar 2010: > In article , > Peter Kleiweg wrote: > >Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010: > > > >> Here is an example for how to use the high-level interface of > >> `python-ghostscript`. This implements a very basic ps2pdf-tool:: > >> > >> import sys > >> import ghostscript > >> > >> args = [ > >> "ps2pdf", # actual value doesn't matter > >> "-dNOPAUSE", "-dBATCH", "-dSAFER", > >> "-sDEVICE=pdfwrite", > >> "-sOutputFile=" + sys.argv[1], > >> "-c", ".setpdfwrite", > >> "-f", sys.argv[2] > >> ] > >> > >> ghostscript.Ghostscript(*args) > > > >How is this different from os.system(' '.join(args)) ? > > You don't have problems with shell metacharacters. Then use os.spawnv(os.P_WAIT, args[0], args) -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From martin.hellwig at dcuktec.org Thu Aug 12 15:56:15 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 12 Aug 2010 20:56:15 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: On 08/11/10 21:14, Baba wrote: How about rephrasing that question in your mind first, i.e.: For every number that is one higher then the previous one*: If this number is dividable by: 6 or 9 or 20 or any combination of 6, 9, 20 than this number _can_ be bought in an exact number else print this number * There are an infinite amount of numbers, just imagine the biggest number you can think of and I say plus 1 :-) Next thing you have to do is figure out how to write this in python, particularly getting all the combinations of divisions can be tricky. Hint; you are not really interested in the division result but rather if a division would be complete or give a remainder (modulo operator). If you get an remainder this could be okay if that can divided by one of the other numbers, and so forth till you ran out of combinations. -- mph From nagle at animats.com Thu Aug 12 16:17:06 2010 From: nagle at animats.com (John Nagle) Date: Thu, 12 Aug 2010 13:17:06 -0700 Subject: Decompressing a file retrieved by URL seems too complex Message-ID: <4c6456cd$0$1623$742ec2ed@news.sonic.net> I'm reading a URL which is a .gz file, and decompressing it. This works, but it seems far too complex. Yet none of the "wrapping" you might expect to work actually does. You can't wrap a GzipFile around an HTTP connection, because GzipFile, reasonably enough, needs random access, and tries to do "seek" and "tell". Nor is the output descriptor from gzip general; it fails on "readline", but accepts "read". (No good reason for that.) So I had to make a second copy. John Nagle def readurl(url) : if url.endswith(".gz") : nd = urllib2.urlopen(url,timeout=TIMEOUTSECS) td1 = tempfile.TemporaryFile() # compressed file td1.write(nd.read()) # fetch and copy file nd.close() # done with network td2 = tempfile.TemporaryFile() # decompressed file td1.seek(0) # rewind gd = gzip.GzipFile(fileobj=td1, mode="rb") # wrap unzip td2.write(gd.read()) # decompress file td1.close() # done with compressed copy td2.seek(0) # rewind return(td2) # return file object for compressed object else : return(urllib2.urlopen(url,timeout=TIMEOUTSECS)) From wherespythonmonks at gmail.com Thu Aug 12 16:18:37 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 16:18:37 -0400 Subject: inline exception handling in python In-Reply-To: <201008122057.03688.thomas@jollybox.de> References: <201008122008.02041.thomas@jollybox.de> <201008122057.03688.thomas@jollybox.de> Message-ID: On Thu, Aug 12, 2010 at 2:57 PM, Thomas Jollans wrote: > On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: >> [I just hate function call overhead for this.] > > I think you've got your priorities wrong. If you want to avoid unnecessary > overhead, avoid exceptions more than functions. > > -- > http://mail.python.org/mailman/listinfo/python-list > Well I suppose it matters depending on the nature of the data you are looking at... But small function calls tend to be the death of interpreted languages... >>> timeit.timeit(""" def f(y,i): try: return(y/(i%10)) except: return(float("nan")) for i in range(100): x = f(7,i) """) 56.362180419240985 >>> timeit.timeit(""" for i in range(100): try: x = 7 / (i % 10) except: x = float("nan") """) 34.588313601484742 >>> From paddy3118 at googlemail.com Thu Aug 12 16:20:19 2010 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Aug 2010 13:20:19 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class Message-ID: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> I find myself needing to calculate the difference between two Counters or multisets or bags. I want those items that are unique to each bag. I know how to calculate it: >>> b = Counter(a=1, b=2) >>> c = Counter(a=3, b=1) >>> diff = (b - c) + (c - b) >>> (b - c) Counter({'b': 1}) >>> (c - b) Counter({'a': 2}) >>> diff Counter({'a': 2, 'b': 1}) But thought why doesn't this operation appear already as a method of the class? - Paddy. From news1234 at free.fr Thu Aug 12 16:28:09 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 22:28:09 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: <4C645959.7010207@free.fr> Hi Baba, The last tips should really help you getting started: for testing your function you could do: Below your uncorrected code and a test for it def can_buy(n_nuggets): for a in range (1,n_nuggets): for b in range (1,n_nuggets): for c in range (1,n_nuggets): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True else: return False # show the results for the first 50 numbers. for n in xrange(50): result = can_buy(n) # get the result (see Brian's comment) print("result of can_buy(%2d) is %s" % (n,result)) with the print statement in can_buy() you should immediately see some issues. as soon as can_buy seems to work, you could comment the print statement. Additionally: I would return [a,b,c] if you got a result and [] if you got no result. So you don't only seem whether you can buy n nuggets, but you can also see how (AND even verify the solution) the print statement should show you what Peter said. You just make one test and return immediately in the else statement Instead you should continue until you found a solution or until you tried all possibilities. After having fixed the fact, that you don't try all options, you'll see that your first success would be with 6+9+12 = 27 nuggets es you never try with 0 boxes of a kind. (as Peter mentioned) Finally as Roald says. if you can reduce the upper limit of your search ranges. if you have for example 13 nuggets you do not have to try 3 boxes of 6 as this is already 18, so trying only 0,1 or two boxes is enough You will now also see, what On 08/12/2010 09:42 PM, Roald de Vries wrote: > > On Aug 12, 2010, at 9:02 PM, Peter Otten wrote: > >> Baba wrote: >> >> >>> Thank You for helping me out. Indeed i am not looking for the code but >>> rather for hints that direct my reasoning as well as hints as to how >>> to write basic programs like this. >>> >>> You have broken down the approach into 2 parts. I have tried to solve >>> part 1 but i'm not quite there yet. Here's my code: >>> >>> def can_buy(n_nuggets): >>> for a in range (1,n_nuggets): >>> for b in range (1,n_nuggets): >>> for c in range (1,n_nuggets): >>> if 6*a+9*b+20*c==n_nuggets: >>> #print a,b,c,'n_nuggets=',n_nuggets >>> return True >>> else: >>> return False >>> >>> >>> can_buy(55) >>> >>> as you can see i am trying to loop through all combinations of values >>> bewtween 1 and n_nuggets and when the equation resolves it should >>> return True, else it should return False. >>> >>> I was hoping that when i then call my function and ask it to test a >>> value nothing happens. What is wrong? My syntax? My semantic? Both? >> >> First, the function gives up too early; it should only return False >> when all >> combinations of a, b, c (technically: the product of the ranges) have >> been >> tried. >> >> Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + >> 0*20 is >> never tried; fix your ranges accordingly. > > Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and > n_nuggets/20 respectively. This will work, but does too much work. > > Cheers, Roald > From jdnier at gmail.com Thu Aug 12 16:28:26 2010 From: jdnier at gmail.com (David Niergarth) Date: Thu, 12 Aug 2010 13:28:26 -0700 (PDT) Subject: default behavior References: Message-ID: <0272074b-8508-4b7a-a11e-3f004506f522@v41g2000yqv.googlegroups.com> Peter Otten <__pete... at web.de> wrote: > > >>> 1 .conjugate() > This is a syntax I never noticed before. My built-in complier (eyes) took one look and said: "that doesn't work." Has this always worked in Python but I never noticed? I see other instance examples also work. >>> '1' .zfill(2) '01' >>> 1.0 .is_integer() True and properties >>> 1.0 .real 1.0 Curiously, this works From news1234 at free.fr Thu Aug 12 16:35:12 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 22:35:12 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <4C645959.7010207@free.fr> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> Message-ID: <4C645B00.7090808@free.fr> One more small tip to verify whether your code is working: On 08/12/2010 10:28 PM, News123 wrote: > Hi Baba, Your code, but returning the result as suggested in my preious post: > def can_buy(n_nuggets): > for a in range (1,n_nuggets): > for b in range (1,n_nuggets): > for c in range (1,n_nuggets): > print "trying for %2d: %2d %2d %2d" % (n,a,b,c) > if 6*a+9*b+20*c==n_nuggets: > return [a,b,c] > else: > return [] > # show the results for the first 50 numbers. # and verify whether it's true for n in xrange(50): result = can_buy(n) # get the result (see Brian's commen print("result of can_buy(%2d) is %s" % (n,result)) if result: a,b,c = result if a*6+b*9+c*12 != n: print "ERROR: can_buy() gives wrong result" Alternatively you can use a nice python feature called asserts assert statements can be used to vrify whether your code works as expected. Nothing will be printed if the assertion is correct otherwise your program will abort and print the assertion error: Example: for n in xrange(50): result = can_buy(n) # get the result (see Brian's commen print("result of can_buy(%2d) is %s" % (n,result)) if result: a,b,c = result assert a*6+b*9+c*12 == n > > > with the print statement in can_buy() you should immediately see some > issues. > as soon as can_buy seems to work, you could comment the print statement. > > > Additionally: > I would return [a,b,c] if you got a result > and [] if you got no result. > > So you don't only seem whether you can buy n nuggets, but you can also > see how (AND even verify the solution) > > > the print statement should show you what Peter said. > You just make one test and return immediately in the else statement > > Instead you should continue until you found a solution or until you > tried all possibilities. > > After having fixed the fact, that you don't try all options, you'll see > that your first success would be with 6+9+12 = 27 nuggets es you never > try with 0 boxes of a kind. (as Peter mentioned) > > Finally as Roald says. > > if you can reduce the upper limit of your search ranges. > if you have for example 13 nuggets you do not have to try 3 boxes of 6 > as this is already 18, so trying only 0,1 or two boxes is enough > > > > > > > > You will now also see, what > On 08/12/2010 09:42 PM, Roald de Vries wrote: >> >> On Aug 12, 2010, at 9:02 PM, Peter Otten wrote: >> >>> Baba wrote: >>> >>> >>>> Thank You for helping me out. Indeed i am not looking for the code but >>>> rather for hints that direct my reasoning as well as hints as to how >>>> to write basic programs like this. >>>> >>>> You have broken down the approach into 2 parts. I have tried to solve >>>> part 1 but i'm not quite there yet. Here's my code: >>>> >>>> def can_buy(n_nuggets): >>>> for a in range (1,n_nuggets): >>>> for b in range (1,n_nuggets): >>>> for c in range (1,n_nuggets): >>>> if 6*a+9*b+20*c==n_nuggets: >>>> #print a,b,c,'n_nuggets=',n_nuggets >>>> return True >>>> else: >>>> return False >>>> >>>> >>>> can_buy(55) >>>> >>>> as you can see i am trying to loop through all combinations of values >>>> bewtween 1 and n_nuggets and when the equation resolves it should >>>> return True, else it should return False. >>>> >>>> I was hoping that when i then call my function and ask it to test a >>>> value nothing happens. What is wrong? My syntax? My semantic? Both? >>> >>> First, the function gives up too early; it should only return False >>> when all >>> combinations of a, b, c (technically: the product of the ranges) have >>> been >>> tried. >>> >>> Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + >>> 0*20 is >>> never tried; fix your ranges accordingly. >> >> Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and >> n_nuggets/20 respectively. This will work, but does too much work. >> >> Cheers, Roald >> > From jdnier at gmail.com Thu Aug 12 16:37:04 2010 From: jdnier at gmail.com (David Niergarth) Date: Thu, 12 Aug 2010 13:37:04 -0700 (PDT) Subject: default behavior References: <0272074b-8508-4b7a-a11e-3f004506f522@v41g2000yqv.googlegroups.com> Message-ID: [Oops, now complete...] Peter Otten <__pete... at web.de> wrote: > > > >>> 1 .conjugate() > This is a syntax I never noticed before. My built-in complier (eyes) took one look and said: "that doesn't work." Has this always worked in Python but I never noticed? I see other instance examples also work. ? >>> '1' .zfill(2) ? '01' ? >>> 1.0 .is_integer() ? True and properties ? >>> 1.0 .real ? 1.0 Curiously, a float literal works without space >>> 1.0.conjugate() 1.0 but not an int. >>> 1.conjugate() File "", line 1 1.conjugate() ^ SyntaxError: invalid syntax Anyway, I didn't realize int has a method you can call. --David From thomas at jollybox.de Thu Aug 12 16:37:30 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 22:37:30 +0200 Subject: shelf-like list? In-Reply-To: References: Message-ID: <201008122237.30461.thomas@jollybox.de> On Tuesday 10 August 2010, it occurred to kj to exclaim: > I'm looking for a module that implements "persistent lists": objects > that behave like lists except that all their elements are stored > on disk. IOW, the equivalent of "shelves", but for lists rather > than a dictionaries. > > Does anyone know of such a module? > > (I suppose that I could slap together a crude implementation of > such a thing by wrapping a shelf with suitable methods to simulate > the list interface. But I'd rather not roll my own if a tested > implementation already exist.) You could simply use pickle to save the data every once in a while. From nagle at animats.com Thu Aug 12 16:40:14 2010 From: nagle at animats.com (John Nagle) Date: Thu, 12 Aug 2010 13:40:14 -0700 Subject: Decompressing a file retrieved by URL seems too complex Message-ID: <4c645c39$0$1595$742ec2ed@news.sonic.net> (Repost with better indentation) I'm reading a URL which is a .gz file, and decompressing it. This works, but it seems far too complex. Yet none of the "wrapping" you might expect to work actually does. You can't wrap a GzipFile around an HTTP connection, because GzipFile, reasonably enough, needs random access, and tries to do "seek" and "tell". Nor is the output descriptor from gzip general; it fails on "readline", but accepts "read". (No good reason for that.) So I had to make a second copy. John Nagle def readurl(url) : if url.endswith(".gz") : nd = urllib2.urlopen(url,timeout=TIMEOUTSECS) td1 = tempfile.TemporaryFile() # compressed file td1.write(nd.read()) # fetch and copy file nd.close() # done with network td2 = tempfile.TemporaryFile() # decompressed file td1.seek(0) # rewind gd = gzip.GzipFile(fileobj=td1, mode="rb") # wrap unzip td2.write(gd.read()) # decompress file td1.close() # done with compressed copy td2.seek(0) # rewind return(td2) # return file object for compressed object else : return(urllib2.urlopen(url,timeout=TIMEOUTSECS)) From news1234 at free.fr Thu Aug 12 16:41:32 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 22:41:32 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4c645c7c$0$3675$426a74cc@news.free.fr> On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: > On 08/11/10 21:14, Baba wrote: > > > How about rephrasing that question in your mind first, i.e.: > > For every number that is one higher then the previous one*: > If this number is dividable by: > 6 or 9 or 20 or any combination of 6, 9, 20 > than this number _can_ be bought in an exact number > else > print this number > you are allowed to mix. 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 I guess, trying to find the result with divisions and remainders is overly complicated. Simple brute force trial to find a combination shall be enough. Also: if you know for example, that you can buy 101,102,103,104,105 and 106 nuggets, then you know, that you can buy any other larger amout of nuggets. 107 = 101 + one box of six 108 = 102 + one box of six . . . As soon as you found 6 sequential solutions you can stop searching. From bradley.h at aggiemail.usu.edu Thu Aug 12 16:43:40 2010 From: bradley.h at aggiemail.usu.edu (Bradley Hintze) Date: Thu, 12 Aug 2010 16:43:40 -0400 Subject: Floating numbers Message-ID: Hi all. Is there a way I can keep my floating point number as I typed it? For example, I want 34.52 to be 34.52 and NOT 34.5200000002. -- Bradley J. Hintze Graduate Student Duke University School of Medicine 801-712-8799 From jjposner at optimum.net Thu Aug 12 16:51:05 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 12 Aug 2010 16:51:05 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: <4C645EB9.7060105@optimum.net> On 8/12/2010 9:22 AM, Dave Angel wrote: >> >> Now you have to find the largest number below 120, which you can >> easily do with brute force Dept of overkill, iterators/generators division ... -John #------------------ from itertools import imap, product, ifilter from operator import mul box_sizes = (6, 9, 20) def sum_product(s1, s2): """ return "scalar product" of two sequences """ return sum(imap(mul, s1, s2)) def reachables(target): """ return generator of numbers that are <= target and are valid linear combos of McNuggets """ candidate_box_counts = product( xrange(target/box_sizes[0] + 1), xrange(target/box_sizes[1] + 1), xrange(target/box_sizes[2] + 1), ) gen = (sum_product(box_sizes, tup) for tup in candidate_box_counts) return (ifilter(lambda val, tgt=target: val < tgt, gen)) if __name__ == "__main__": tgt = 120 # thanks, Dave Angel unreachables = set(xrange(tgt)) - set(reachables(tgt)) print "Max unreachable:", max(unreachables) From __peter__ at web.de Thu Aug 12 16:52:03 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 22:52:03 +0200 Subject: default behavior References: <0272074b-8508-4b7a-a11e-3f004506f522@v41g2000yqv.googlegroups.com> Message-ID: David Niergarth wrote: > [Oops, now complete...] > Peter Otten <__pete... at web.de> wrote: >> >> > >>> 1 .conjugate() >> > This is a syntax I never noticed before. My built-in complier (eyes) > took one look and said: "that doesn't work." (1).conjugate may hurt a little less. Anyway, the space is only needed for the tokenizer that without it would produce a float immediately followed by a name. > Has this always worked in > Python but I never noticed? Probably. > I see other instance examples also work. > > >>> '1' .zfill(2) > '01' > >>> 1.0 .is_integer() > True > > and properties > > >>> 1.0 .real > 1.0 > > Curiously, a float literal works without space > > >>> 1.0.conjugate() > 1.0 > > but not an int. > > >>> 1.conjugate() > File "", line 1 > 1.conjugate() > ^ > SyntaxError: invalid syntax > > Anyway, I didn't realize int has a method you can call. > > --David From fuglyducky at gmail.com Thu Aug 12 17:06:46 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Thu, 12 Aug 2010 14:06:46 -0700 (PDT) Subject: re.sub and variables Message-ID: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> I have a function that I am attempting to call from another file. I am attempting to replace a string using re.sub with another string. The problem is that the second string is a variable. When I get the output, it shows the variable name rather than the value. Is there any way to pass a variable into a regex? If not, is there any other way to do this? I need to be able to dump the variable value into the replacement string. For what it's worth this is an XML file so I'm not afraid to use some sort of XML library but they look fairly complicated for a newbie like me. Also, this is py3.1.2 is that makes any difference. Thanks!!! ##################################################### import random import re import datetime def pop_time(some_string, start_time): global that_string rand_time = random.randint(0, 30) delta_time = datetime.timedelta(seconds=rand_time) for line in some_string: end_time = delta_time + start_time new_string = re.sub("thisstring", "thisstring\\end_time", some_string) start_time = end_time return new_string From invalid at invalid.invalid Thu Aug 12 17:20:18 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 12 Aug 2010 21:20:18 +0000 (UTC) Subject: Floating numbers References: Message-ID: On 2010-08-12, Bradley Hintze wrote: > Is there a way I can keep my floating point number as I typed it? No. > For example, I want 34.52 to be 34.52 and NOT 34.5200000002. You can't represent 34.52 using base-2 IEEE floating point (the HW floating point format used by pretty much all modern computers). 34.5200000002 is as close as you can get. When you enter a base-10 floating-point number, the computer will use the closest base-2 IEEE floating point number. Here are the nitty-gritty details: http://docs.sun.com/source/806-3568/ncg_goldberg.html Can you explain what your actual problem is? -- Grant Edwards grant.b.edwards Yow! I'm imagining a surfer at van filled with soy sauce! gmail.com From gherron at islandtraining.com Thu Aug 12 17:23:37 2010 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 12 Aug 2010 14:23:37 -0700 Subject: Floating numbers In-Reply-To: References: Message-ID: <4C646659.6010500@islandtraining.com> On 08/12/2010 01:43 PM, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. > > Is this a Python question? The answer is both Yes and No. The binary floating point representation of numbers on a computer cannot exactly represent most decimal number you would like to type. (Similar to the fact that you cannot represent 1/3 exactly in a decimal system.) But that's the internal representation, over which you have no control. You do, however, have control over how a number is displayed when printed. Python 2: Choose a format that displays the exact number of digits you want '%.2f' % a or let str(a) choose but not repr(a) which tries to get all the digits. (Adding to the confusion, you might also find it confusing to understand which of str() or repr() Python chooses to display a number.) Python 3: Python3 uses David Gay?s algorithm for chosing how to display floats. Both str(a) and repr(a) produce '34.52' for your example, which is probably just what you want. Gary Herron From invalid at invalid.invalid Thu Aug 12 17:24:14 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 12 Aug 2010 21:24:14 +0000 (UTC) Subject: Floating numbers References: Message-ID: On 2010-08-12, Grant Edwards wrote: > On 2010-08-12, Bradley Hintze wrote: > >> Is there a way I can keep my floating point number as I typed it? > > No. > >> For example, I want 34.52 to be 34.52 and NOT 34.5200000002. > > You can't represent 34.52 using base-2 IEEE floating point (the HW > floating point format used by pretty much all modern computers). > 34.5200000002 is as close as you can get. > > When you enter a base-10 floating-point number, the computer will use > the closest base-2 IEEE floating point number. > > Here are the nitty-gritty details: > > http://docs.sun.com/source/806-3568/ncg_goldberg.html Here is a gentler intro: http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate -- Grant Edwards grant.b.edwards Yow! If I felt any more at SOPHISTICATED I would DIE gmail.com of EMBARRASSMENT! From thomas at jollybox.de Thu Aug 12 17:24:48 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 23:24:48 +0200 Subject: Floating numbers In-Reply-To: References: Message-ID: <201008122324.49315.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to Bradley Hintze to exclaim: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. The conversion from decimal to binary and vice versa is inexact -- but they're the same number internally: Python 2.6.6rc1+ (r266rc1:83691, Aug 5 2010, 17:07:04) [GCC 4.4.5 20100728 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 34.52 34.520000000000003 >>> 34.520000000000003 == 34.52 True >>> Python 3 is a bit smarter when printing, so you don't really notice what's going on: Python 3.1.2 (release31-maint, Jul 8 2010, 09:18:08) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 34.52 34.52 >>> 34.520000000000003 34.52 >>> From philip at semanchuk.com Thu Aug 12 17:25:07 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 12 Aug 2010 17:25:07 -0400 Subject: Floating numbers In-Reply-To: References: Message-ID: <4A61DB54-FEC5-4649-B7FD-8C01EB650102@semanchuk.com> On Aug 12, 2010, at 4:43 PM, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. Hi Bradley, Use the Decimal type instead. It's not as convenient as float, but it will give you a consistent representation of your numbers. The behavior of floating point numbers surprises a lot of people and has been discussed at length a number of times here (and elsewhere). If you're in the mood for EXTREMELY thorough coverage of the subject, you can read this: http://docs.sun.com/source/806-3568/ncg_goldberg.html There's a gentler discussion of it here: http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding HTH Philip From invalid at invalid.invalid Thu Aug 12 17:25:13 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 12 Aug 2010 21:25:13 +0000 (UTC) Subject: Floating numbers References: Message-ID: On 2010-08-12, Grant Edwards wrote: >> Here are the nitty-gritty details: >> >> http://docs.sun.com/source/806-3568/ncg_goldberg.html > > Here is a gentler intro: > > http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate And another good page: http://docs.python.org/tutorial/floatingpoint.html -- Grant Edwards grant.b.edwards Yow! I feel like I'm at in a Toilet Bowl with a gmail.com thumbtack in my forehead!! From clp2 at rebertia.com Thu Aug 12 17:28:41 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 12 Aug 2010 14:28:41 -0700 Subject: Floating numbers In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 1:43 PM, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. See also: http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding Another option is to use the `decimal` module, which *can* exactly represent decimal numbers (to a user-specified finite precision) and is generally a bit more intuitive but /substantially/ slower: http://docs.python.org/library/decimal.html Cheers, Chris -- http://blog.rebertia.com From lists at cheimes.de Thu Aug 12 17:30:54 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 12 Aug 2010 23:30:54 +0200 Subject: Floating numbers In-Reply-To: References: Message-ID: > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. This isn't a Python issue. Python uses IEEE 754 [1] double precision floats like most other languages. 34.52 can't be stored in a float. The next valid float is 34.5200000002. Christian [1] http://en.wikipedia.org/wiki/IEEE_754 From fuglyducky at gmail.com Thu Aug 12 17:33:28 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Thu, 12 Aug 2010 14:33:28 -0700 (PDT) Subject: re.sub and variables References: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> Message-ID: On Aug 12, 2:06?pm, fuglyducky wrote: > I have a function that I am attempting to call from another file. I am > attempting to replace a string using re.sub with another string. The > problem is that the second string is a variable. When I get the > output, it shows the variable name rather than the value. Is there any > way to pass a variable into a regex? > > If not, is there any other way to do this? I need to be able to dump > the variable value into the replacement string. > > For what it's worth this is an XML file so I'm not afraid to use some > sort of XML library but they look fairly complicated for a newbie like > me. > > Also, this is py3.1.2 is that makes any difference. > > Thanks!!! > > ##################################################### > > import random > import re > import datetime > > def pop_time(some_string, start_time): > ? ? global that_string > > ? ? rand_time = random.randint(0, 30) > ? ? delta_time = datetime.timedelta(seconds=rand_time) > > ? ? for line in some_string: > ? ? ? ? end_time = delta_time + start_time > ? ? ? ? new_string = re.sub("thisstring", "thisstring\\end_time", > some_string) > ? ? ? ? start_time = end_time > > ? ? return new_string Disregard...I finally figured out how to use string.replace. That appears to work perfectly. Still...if anyone happens to know about passing a variable into a regex that would be great. From hexamorph at gmx.net Thu Aug 12 17:38:10 2010 From: hexamorph at gmx.net (Hexamorph) Date: Thu, 12 Aug 2010 23:38:10 +0200 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: <4C6469C2.8070408@gmx.net> Terry Reedy wrote: > On 8/9/2010 11:16 AM, Grant Edwards wrote: Just for the record: I sincerely apologize for my rant. I usually don't loose control so heavily, but this "Rick" person makes me mad (killfile'd now) >> IOW, the "Ugly American". No! That's not what I said. I'm myself one of those "bad germans" and I *entirely* agree with Mr. Reedy's comment: > Stereotypically bashing "Americans" is as ugly and obnoxious as bashing > any other ethnic group. I have traveled the world and Americans are no > worse, but are pretty much the same mix of good and bad. It is certainly > off-topic and inappropriate for this group. From thomas at jollybox.de Thu Aug 12 17:40:27 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 23:40:27 +0200 Subject: Decompressing a file retrieved by URL seems too complex In-Reply-To: <4c645c39$0$1595$742ec2ed@news.sonic.net> References: <4c645c39$0$1595$742ec2ed@news.sonic.net> Message-ID: <201008122340.27823.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to John Nagle to exclaim: > (Repost with better indentation) Good, good. > > def readurl(url) : > if url.endswith(".gz") : The file name could be anything. You should be checking the reponse Content- Type header -- that's what it's for. > nd = urllib2.urlopen(url,timeout=TIMEOUTSECS) > td1 = tempfile.TemporaryFile() # compressed file You can keep the whole thing in memory by using StringIO. > td1.write(nd.read()) # fetch and copy file You're reading the entire fire into memory anyway ;-) > nd.close() # done with network > td2 = tempfile.TemporaryFile() # decompressed file Okay, maybe there is somthing missing from GzipFile -- but still you could use StringIO again, I expect. > Nor is the output descriptor from gzip general; it fails > on "readline", but accepts "read". >>> from gzip import GzipFile >>> GzipFile.readline >>> GzipFile.readlines >>> GzipFile.__iter__ >>> What exactly is it that's failing, and how? > td1.seek(0) # rewind > gd = gzip.GzipFile(fileobj=td1, mode="rb") # wrap unzip > td2.write(gd.read()) # decompress file > td1.close() # done with compressed copy > td2.seek(0) # rewind > return(td2) # return file object for compressed object > else : > return(urllib2.urlopen(url,timeout=TIMEOUTSECS)) From carey.tilden at gmail.com Thu Aug 12 17:46:07 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Thu, 12 Aug 2010 14:46:07 -0700 Subject: inline exception handling in python In-Reply-To: References: <201008122008.02041.thomas@jollybox.de> <201008122057.03688.thomas@jollybox.de> Message-ID: On Thu, Aug 12, 2010 at 1:18 PM, wheres pythonmonks wrote: > Well I suppose it matters depending on the nature of the data you are > looking at... ?But small function calls tend to be the death of interpreted > languages... I would be interested to see a real application that had performance negatively impacted by function call overhead. Sure, it's easy to measure in micro benchmarks, but what about profiling a real application? Carey From news1234 at free.fr Thu Aug 12 18:31:58 2010 From: news1234 at free.fr (News123) Date: Fri, 13 Aug 2010 00:31:58 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: <4c64765e$0$28580$426a74cc@news.free.fr> On 08/12/2010 10:51 PM, John Posner wrote: > On 8/12/2010 9:22 AM, Dave Angel wrote: >>> >>> Now you have to find the largest number below 120, which you can >>> easily do with brute force > > Dept of overkill, iterators/generators division ... > > -John > > #------------------ > from itertools import imap, product, ifilter > from operator import mul > > box_sizes = (6, 9, 20) > > def sum_product(s1, s2): > """ > return "scalar product" of two sequences > """ > return sum(imap(mul, s1, s2)) > > def reachables(target): > """ > return generator of numbers that are <= target > and are valid linear combos of McNuggets > """ > candidate_box_counts = product( > xrange(target/box_sizes[0] + 1), > xrange(target/box_sizes[1] + 1), > xrange(target/box_sizes[2] + 1), > ) Couldn't this be rewritten as: candidate_box_counts = product( * [ xrange(target/sizes + 1) for size in box_sizes ] ) > > gen = (sum_product(box_sizes, tup) > for tup in candidate_box_counts) > > return (ifilter(lambda val, tgt=target: val < tgt, > gen)) > > if __name__ == "__main__": > tgt = 120 # thanks, Dave Angel > unreachables = set(xrange(tgt)) - set(reachables(tgt)) > print "Max unreachable:", max(unreachables) From missive at hotmail.com Thu Aug 12 18:53:31 2010 From: missive at hotmail.com (Lee Harr) Date: Fri, 13 Aug 2010 03:23:31 +0430 Subject: segfault with small pyqt script Message-ID: > I'm desperate. I'm having a real application, which fails rather often > when finishing it. I'm not sure, whether any serious problem could be > hidden behind it > > The script is a pyqt script, which segfaults most of the time on my > ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. Looks to be a known issue: http://www.google.com/search?q=pyqt+segfault+on+exit https://launchpad.net/bugs/561303 The last activity on that bug is almost 2 months ago... Hopefully the fix will be distributed soon. From bavantgarde at yahoo.com Thu Aug 12 18:57:50 2010 From: bavantgarde at yahoo.com (BAvant Garde) Date: Thu, 12 Aug 2010 15:57:50 -0700 (PDT) Subject: unicode string alteration In-Reply-To: <4C642FF1.1050508@mrabarnett.plus.com> Message-ID: <156365.97065.qm@web83402.mail.sp1.yahoo.com> Thanks MRAB, I'll have to do some reading about unicode surrogates. Also need to research which python versions/platforms are narrow builds and which are wide. Much to learn here. Thanks!? --- On Thu, 8/12/10, MRAB wrote: From: MRAB Subject: Re: unicode string alteration To: python-list at python.org Date: Thursday, August 12, 2010, 12:31 PM BAvant Garde wrote: > HELP!!! > I need help with a unicode issue that has me stumped. I must be doing something? wrong because I don't believe this condition would have slipped thru testing. > > Wherever the string u'\udbff\udc00' occurs u'\U0010fc00' or unichr(1113088) is substituted and the file loses 1 character resulting in all trailing characters being shifted out of position. No other corrupt strings have been detected. >? ? The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04 where the maximum ord # is 1114111 (wide Python build). >? ? Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535 (narrow Python build) the string u'\U0010fc00' also occurs and it "seems" that the substitution takes place but no characters are lost and file sizes are ok. Note that ord(u'\U0010fc00') causes the following error: >? ? ? ? ? ? ? "TypeError: ord() expected a character, but string of length 2 found" > The condition is otherwise invisible in 2.5.4 and is handled internally without any apparent effect on processing with characters u'\udbff' and u'\udc00' each being separately accessible. > > The first part of the attachment repeats this email but also has examples and illustrates other related oddities. >? ? Any help would be greatly appreciated. > It's not an error, it's a "surrogate pair". Surrogate pairs are part of the Unicode specification. Unicode codepoints go up to U+0010FFFF. If you're using 16 bits per codepoint, like in a narrow build of Python, then the codepoints above U+FFFF _can't_ be represented directly, so they are represented by a pair of codepoints called a "surrogate pair". If, on the other hand, you're using 32 bits per codepoint, like in a wide build of Python, then the codepoints above U+FFFF _can_ be represented directly, so surrogate pairs aren't needed, and, indeed shouldn't be there. What you're seeing in the wide build is Python replacing a surrogate pair with the codepoint that it represents, which is actually the right thing to do because, as I said, the surrogate pairs really shouldn't be there. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From bsalter01 at earthlink.net Thu Aug 12 19:09:10 2010 From: bsalter01 at earthlink.net (Brian Salter) Date: Thu, 12 Aug 2010 16:09:10 -0700 Subject: Importing libs on Windows? Message-ID: I've seen a number of tutorials that describe how to bring in a dll in python, but does anybody know of a tutorial for how to bring in a lib? Is it even possible? Thanks, in advance! From sjmachin at lexicon.net Thu Aug 12 19:14:57 2010 From: sjmachin at lexicon.net (John Machin) Date: Thu, 12 Aug 2010 16:14:57 -0700 (PDT) Subject: re.sub and variables References: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> Message-ID: <380d19dc-5aa3-426b-af04-cc2a35ef8d04@m35g2000prn.googlegroups.com> On Aug 13, 7:33?am, fuglyducky wrote: > On Aug 12, 2:06?pm, fuglyducky wrote: > > > > > I have a function that I am attempting to call from another file. I am > > attempting to replace a string using re.sub with another string. The > > problem is that the second string is a variable. When I get the > > output, it shows the variable name rather than the value. Is there any > > way to pass a variable into a regex? > > > If not, is there any other way to do this? I need to be able to dump > > the variable value into the replacement string. > > > For what it's worth this is an XML file so I'm not afraid to use some > > sort of XML library but they look fairly complicated for a newbie like > > me. > > > Also, this is py3.1.2 is that makes any difference. > > > Thanks!!! > > > ##################################################### > > > import random > > import re > > import datetime > > > def pop_time(some_string, start_time): > > ? ? global that_string > > > ? ? rand_time = random.randint(0, 30) > > ? ? delta_time = datetime.timedelta(seconds=rand_time) > > > ? ? for line in some_string: > > ? ? ? ? end_time = delta_time + start_time > > ? ? ? ? new_string = re.sub("thisstring", "thisstring\\end_time", > > some_string) > > ? ? ? ? start_time = end_time > > > ? ? return new_string > > Disregard...I finally figured out how to use string.replace. That > appears to work perfectly. Still...if anyone happens to know about > passing a variable into a regex that would be great. Instead of new_string = re.sub( "thisstring", "thisstring\\end_time", some_string) you probably meant to use something like new_string = re.sub( "thisstring", "thisstring" + "\\" + end_time, some_string) string.replace is antique and deprecated. You should be using methods of str objects, not functions in the string module. >>> s1 = "foobarzot" >>> s2 = s1.replace("bar", "-") >>> s2 'foo-zot' >>> From gherron at islandtraining.com Thu Aug 12 19:46:38 2010 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 12 Aug 2010 16:46:38 -0700 Subject: Importing libs on Windows? In-Reply-To: References: Message-ID: <4C6487DE.2070202@islandtraining.com> On 08/12/2010 04:09 PM, Brian Salter wrote: > I've seen a number of tutorials that describe how to bring in a dll in > python, but does anybody know of a tutorial for how to bring in a > lib? Is it even possible? > > Thanks, in advance! > > Look at the Python module named ctypes: http://docs.python.org/library/ctypes.html Gary Herron From bsalter01 at earthlink.net Thu Aug 12 20:52:33 2010 From: bsalter01 at earthlink.net (Brian Salter) Date: Thu, 12 Aug 2010 17:52:33 -0700 Subject: Importing libs on Windows? In-Reply-To: References: Message-ID: It appears that every example is calling a dll, and I'm looking to bring in a lib. Does ctypes work with libs too? "Gary Herron" wrote in message news:mailman.2044.1281656800.1673.python-list at python.org... > On 08/12/2010 04:09 PM, Brian Salter wrote: >> I've seen a number of tutorials that describe how to bring in a dll in >> python, but does anybody know of a tutorial for how to bring in a lib? >> Is it even possible? >> >> Thanks, in advance! >> >> > > Look at the Python module named ctypes: > http://docs.python.org/library/ctypes.html > > Gary Herron > > From nad at acm.org Thu Aug 12 21:14:10 2010 From: nad at acm.org (Ned Deily) Date: Thu, 12 Aug 2010 18:14:10 -0700 Subject: Floating numbers References: Message-ID: In article , Christian Heimes wrote: >> Is there a way I can keep my floating point number as I typed it? For >> example, I want 34.52 to be 34.52 and NOT 34.5200000002. > This isn't a Python issue. Python uses IEEE 754 [1] double precision > floats like most other languages. 34.52 can't be stored in a float. The > next valid float is 34.5200000002. Well, it is a *bit* of a Python issue since, as others have pointed out, Python's behavior has changed due to the implementation of Gay's rounding algorithm in 3.1 and also in 2.7: $ python2.6 -c 'print(repr(34.52))' 34.520000000000003 $ python2.7 -c 'print(repr(34.52))' 34.52 $ python3.1 -c 'print(repr(34.52))' 34.52 -- Ned Deily, nad at acm.org From benjamin.kaplan at case.edu Thu Aug 12 21:19:40 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 12 Aug 2010 18:19:40 -0700 Subject: Floating numbers In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 6:14 PM, Ned Deily wrote: > In article , > ?Christian Heimes wrote: >>> Is there a way I can keep my floating point number as I typed it? For >>> example, I want 34.52 to be 34.52 and NOT 34.5200000002. >> This isn't a Python issue. Python uses IEEE 754 [1] double precision >> floats like most other languages. 34.52 can't be stored in a float. The >> next valid float is 34.5200000002. > > Well, it is a *bit* of a Python issue since, as others have pointed out, > Python's behavior has changed due to the implementation of Gay's > rounding algorithm in 3.1 and also in 2.7: > > $ python2.6 -c 'print(repr(34.52))' > 34.520000000000003 > $ python2.7 -c 'print(repr(34.52))' > 34.52 > $ python3.1 -c 'print(repr(34.52))' > 34.52 > But that's not keeping the number the way it was typed. It's just not showing you the exact approximation. It doesn't get rid of rounding errors. >>> 34.52 34.52 >>> >>> _ * 10**10 345200000000.00006 > -- > ?Ned Deily, > ?nad at acm.org > > -- > http://mail.python.org/mailman/listinfo/python-list > From tycho at tycho.ws Thu Aug 12 21:40:30 2010 From: tycho at tycho.ws (Tycho Andersen) Date: Thu, 12 Aug 2010 20:40:30 -0500 Subject: Importing libs on Windows? In-Reply-To: References: Message-ID: <20100813014030.GT1506@mittens.Belkin> On Thu, Aug 12, 2010 at 04:09:10PM -0700, Brian Salter wrote: > I've seen a number of tutorials that describe how to bring in a dll > in python, but does anybody know of a tutorial for how to bring in a > lib? Is it even possible? I don't know if it's possible, but why do you want to do it? .lib files in Windows are static libraries, which traditionally aren't loaded dynamically. Is there some reason you can't use a DLL? \t From steve at REMOVE-THIS-cybersource.com.au Thu Aug 12 22:03:48 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 02:03:48 GMT Subject: re.sub and variables References: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> Message-ID: <4c64a804$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 14:33:28 -0700, fuglyducky wrote: > if anyone happens to know about > passing a variable into a regex that would be great. The same way you pass anything into any string. Regexes are ordinary strings. If you want to construct a string from a variable t = "orl", you can do any of these: "Hello w" + t + "d" "".join(["Hello", " ", "w", t, "d"]) "Hello w%sd" % t "Hello %s" % ("w" + t + "d") "Hello w%(var)sd" % {"var": t} "Hello wSPAMd".replace("SPAM", t) or many other variations. Constructing a regex is no different. -- Steven From nad at acm.org Thu Aug 12 22:10:38 2010 From: nad at acm.org (Ned Deily) Date: Thu, 12 Aug 2010 19:10:38 -0700 Subject: Floating numbers References: Message-ID: In article , Benjamin Kaplan wrote: > > Well, it is a *bit* of a Python issue since, as others have pointed out, > > Python's behavior has changed due to the implementation of Gay's > > rounding algorithm in 3.1 and also in 2.7: > > > > $ python2.6 -c 'print(repr(34.52))' > > 34.520000000000003 > > $ python2.7 -c 'print(repr(34.52))' > > 34.52 > > $ python3.1 -c 'print(repr(34.52))' > > 34.52 > But that's not keeping the number the way it was typed. It's just not > showing you the exact approximation. It doesn't get rid of rounding > errors. > >>> 34.52 > 34.52 > >>> >>> _ * 10**10 > 345200000000.00006 Yes, as discussed earlier in this thread and I didn't mean to imply otherwise. I should have worded my comment differently: the main reason for making it was to point out that the new float repr format feature is also in 2.7. -- Ned Deily, nad at acm.org From python at mrabarnett.plus.com Thu Aug 12 22:20:30 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Aug 2010 03:20:30 +0100 Subject: re.sub and variables In-Reply-To: <4c64a804$0$28668$c3e8da3@news.astraweb.com> References: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> <4c64a804$0$28668$c3e8da3@news.astraweb.com> Message-ID: <4C64ABEE.5040302@mrabarnett.plus.com> Steven D'Aprano wrote: > On Thu, 12 Aug 2010 14:33:28 -0700, fuglyducky wrote: > >> if anyone happens to know about >> passing a variable into a regex that would be great. > > The same way you pass anything into any string. > > Regexes are ordinary strings. If you want to construct a string from a > variable t = "orl", you can do any of these: > > "Hello w" + t + "d" > > "".join(["Hello", " ", "w", t, "d"]) > > "Hello w%sd" % t > > "Hello %s" % ("w" + t + "d") > > "Hello w%(var)sd" % {"var": t} > > "Hello wSPAMd".replace("SPAM", t) > > or many other variations. Constructing a regex is no different. > You just need to remember that if you pass a string into re.sub as a replacement then it'll be treated as a template. It's all in the documentation! :-) From jjposner at optimum.net Thu Aug 12 22:26:20 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 12 Aug 2010 22:26:20 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <4c64765e$0$28580$426a74cc@news.free.fr> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4c64765e$0$28580$426a74cc@news.free.fr> Message-ID: <4C64AD4B.1010006@optimum.net> On 8/12/2010 6:31 PM, News123 wrote: >> candidate_box_counts = product( >> xrange(target/box_sizes[0] + 1), >> xrange(target/box_sizes[1] + 1), >> xrange(target/box_sizes[2] + 1), >> ) > > Couldn't this be rewritten as: > candidate_box_counts = product( > * [ xrange(target/sizes + 1) for size in box_sizes ] > ) > Sure (except for the typo: "sizes" should be "size"). You could even use a generator expression instead of a list comprehension: candidate_box_counts = product( * ( xrange(target/size + 1) for size in box_sizes ) ) -John From matt at schinckel.net Thu Aug 12 22:52:07 2010 From: matt at schinckel.net (Matt Schinckel) Date: Thu, 12 Aug 2010 19:52:07 -0700 (PDT) Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <479d903d-2610-4755-a2aa-cd46540ff44d@y12g2000prb.googlegroups.com> On Aug 6, 8:15?am, "Rhodri James" wrote: > On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks ? > > wrote: > > Well, I am not convinced of the equivalence of not None and true: [snip] > >>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" > True > >>> a = "spam, eggs, chips and spam" > >>> b = "spam, eggs, chips and spam" > >>> a is b > False but: >>> a = "hello" >>> b = "hello" >>> a is b True Ooh, that looks dangerous. Are they the same object? >>> a += "o" >>> a 'helloo' >>> b 'hello' Phew. (Python does not make two copies of small strings until it needs to). Matt. From aahz at pythoncraft.com Thu Aug 12 23:24:12 2010 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2010 20:24:12 -0700 Subject: Decompressing a file retrieved by URL seems too complex References: <4c645c39$0$1595$742ec2ed@news.sonic.net> Message-ID: In article <4c645c39$0$1595$742ec2ed at news.sonic.net>, John Nagle wrote: > >I'm reading a URL which is a .gz file, and decompressing it. This >works, but it seems far too complex. Yet none of the "wrapping" >you might expect to work actually does. You can't wrap a GzipFile >around an HTTP connection, because GzipFile, reasonably enough, needs >random access, and tries to do "seek" and "tell". Nor is the output >descriptor from gzip general; it fails on "readline", but accepts >"read". (No good reason for that.) So I had to make a second copy. Also consider using zlib directly. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From iamforufriends at gmail.com Fri Aug 13 00:32:52 2010 From: iamforufriends at gmail.com (UR DREEM GIRL) Date: Thu, 12 Aug 2010 21:32:52 -0700 (PDT) Subject: morethen 34, 100, 617 active members r waiting 4 live hot chat, dating ... Message-ID: morethen 34,100,617 active members r waiting 4 live hot chat, dating ... free and eazy to meet and enjoy.... just click.... start.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From ldo at geek-central.gen.new_zealand Fri Aug 13 00:45:36 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 13 Aug 2010 16:45:36 +1200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: In message , Jean- Michel Pichavant wrote: > for mcNugget in range(0,10): > sendTo(trashbin) Ah, but should that be mcNugget.sendTo(trashbin) or trashbin.insert(mcNugget) ? From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 00:52:21 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 04:52:21 GMT Subject: Inserting/Deleting newline(s) in very large text files References: <595550.37557.qm@web120110.mail.ne1.yahoo.com> Message-ID: <4c64cf85$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 21:25:59 +0200, Thomas Jollans wrote: > Everybody agrees that text files > should end with a line feed, because some text editors might mess up if > they don't. For some definition of "everybody". Obviously the text editors which DON'T mess up don't make the assumption that all text files end with a newline. -- Steven From tjreedy at udel.edu Fri Aug 13 01:12:10 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Aug 2010 01:12:10 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: <479d903d-2610-4755-a2aa-cd46540ff44d@y12g2000prb.googlegroups.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <479d903d-2610-4755-a2aa-cd46540ff44d@y12g2000prb.googlegroups.com> Message-ID: On 8/12/2010 10:52 PM, Matt Schinckel wrote: >>>> a = "hello" >>>> b = "hello" >>>> a is b > True > > Ooh, that looks dangerous. Only for mutable objects > Are they the same object? Yes. >>>> a += "o" This is equivalent to a = a+"o". The expression creates a new object. The assignment binds the object to name 'a'. > (Python does not make two copies of small strings until it needs to). Python never copies *any* object until you ask it to. It never made a copy of the original 'a' here either. It combined the values of two string objects to make a new string object with a new value. -- Terry Jan Reedy From nobody at nowhere.com Fri Aug 13 01:34:52 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 13 Aug 2010 06:34:52 +0100 Subject: Floating numbers References: Message-ID: On Thu, 12 Aug 2010 18:19:40 -0700, Benjamin Kaplan wrote: > But that's not keeping the number the way it was typed. It's just not > showing you the exact approximation. Nor is 34.520000000000003 showing you the "exact approximation". The closest "double" to 34.52 is 4858258098025923 / 2**47, whose exact decimal representation is: 34.52000000000000312638803734444081783294677734375 The decimal representation of 1/(2**n) for n>0 always ends in 5. As a consequence of this, the exact decimal representation of any binary floating-point value which isn't itself an integer must end in 5. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 01:36:15 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 05:36:15 GMT Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> Message-ID: <4c64d9cf$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 13:20:19 -0700, Paddy wrote: > I find myself needing to calculate the difference between two Counters > or multisets or bags. Is this collections.Counter from Python 3.1? If so, you should say so, and if not, you should tell us which Counter class this is. It will save people (by which I mean *me*) from spending an unrewarding few minutes trying to import Counter in Python 2.5 and writing up a sarcastic response ... :) > I want those items that are unique to each bag. I know how to calculate > it: > > >>> b = Counter(a=1, b=2) > >>> c = Counter(a=3, b=1) > >>> diff = (b - c) + (c - b) > >>> (b - c) > Counter({'b': 1}) > >>> (c - b) > Counter({'a': 2}) > >>> diff > Counter({'a': 2, 'b': 1}) > > But thought why doesn't this operation appear already as a method of the > class? Don't know. Perhaps you should put in a feature request. -- Steven From nobody at nowhere.com Fri Aug 13 01:39:50 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 13 Aug 2010 06:39:50 +0100 Subject: Importing libs on Windows? References: Message-ID: On Thu, 12 Aug 2010 16:09:10 -0700, Brian Salter wrote: > I've seen a number of tutorials that describe how to bring in a dll in > python, but does anybody know of a tutorial for how to bring in a lib? Is > it even possible? No. ctypes relies upon the OS to actually load the library, and the OS doesn't provide any mechanism to load a ".lib" file. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 01:40:14 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 05:40:14 GMT Subject: inline exception handling in python References: Message-ID: <4c64dabe$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 20:08:01 +0200, Thomas Jollans wrote: [...] > Besides, more often than not, you want to have a finally clause around > when you're dealing with exceptions. Oh I don't know about that. Doing a quick and totally unscientific survey of my own code, I find that try...except with no finally outnumbers try...finally by about 10 to 1. In any case, any syntax for inline exception handling should be kept nice and lightweight. It shouldn't try to duplicate all the functionality of try...except...else...finally blocks. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 01:42:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 05:42:01 GMT Subject: inline exception handling in python References: <201008122008.02041.thomas@jollybox.de> Message-ID: <4c64db29$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 14:19:13 -0400, wheres pythonmonks wrote: > I think the problem in my case is best solved by look before you leap, > or a wrapper function. [I just hate function call overhead for this. ] Sounds suspiciously like premature micro-optimization to me. Function call overhead is tiny compared to the cost of catching an exception, and probably of a similar cost to looking before you leap. -- Steven From clp2 at rebertia.com Fri Aug 13 01:45:54 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 12 Aug 2010 22:45:54 -0700 Subject: EXOR or symmetric difference for the Counter class In-Reply-To: <4c64d9cf$0$28668$c3e8da3@news.astraweb.com> References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <4c64d9cf$0$28668$c3e8da3@news.astraweb.com> Message-ID: On Thu, Aug 12, 2010 at 10:36 PM, Steven D'Aprano wrote: > On Thu, 12 Aug 2010 13:20:19 -0700, Paddy wrote: > >> I find myself needing to calculate the difference between two Counters >> or multisets or bags. > > Is this collections.Counter from Python 3.1? "Changed in version **2.7**: Added Counter and OrderedDict." That is still ahead of the curve though. Cheers, Chris From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 01:51:40 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 05:51:40 GMT Subject: default behavior References: <0272074b-8508-4b7a-a11e-3f004506f522@v41g2000yqv.googlegroups.com> Message-ID: <4c64dd6b$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 13:28:26 -0700, David Niergarth wrote: > Peter Otten <__pete... at web.de> wrote: >> >> >>> 1 .conjugate() >> >> > This is a syntax I never noticed before. My built-in complier (eyes) > took one look and said: "that doesn't work." Has this always worked in > Python but I never noticed? Yes. Here is is working in Python 2.2: [steve at sylar ~]$ python2.2 Python 2.2.3 (#1, Aug 12 2010, 01:08:27) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 2 .__add__(3) 5 Syntactically, it also worked as far back as Python 1.5, although it is rather pointless since int objects didn't gain any methods until 2.2: [steve at sylar ~]$ python1.5 Python 1.5.2 (#1, Apr 1 2009, 22:55:54) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> 2 .__add__(3) Traceback (innermost last): File "", line 1, in ? AttributeError: 'int' object has no attribute '__add__' > I see other instance examples also work. > > >>> '1' .zfill(2) > '01' You don't need the space between strings and the attribute access: "1".zfill(2) is fine. You only need it for numbers, due to the ambiguity between the decimal point and dotted attribute access. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 02:03:54 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 06:03:54 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <479d903d-2610-4755-a2aa-cd46540ff44d@y12g2000prb.googlegroups.com> Message-ID: <4c64e04a$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 19:52:07 -0700, Matt Schinckel wrote: >>>> a = "hello" >>>> b = "hello" >>>> a is b > True > > Ooh, that looks dangerous. Are they the same object? You don't need another test to know that they are the same object. The `is` operator does exactly that: a is b *only* if a and b are the same object. >>>> a += "o" >>>> a > 'helloo' >>>> b > 'hello' > > Phew. This tests for mutability, not sameness. If strings were mutable, then modifying a in place would likewise cause b to be modified (because they are the same object). Here's an example: >>> a = b = [1, 2, 3] >>> a is b True >>> a += [4] >>> b [1, 2, 3, 4] But of course, if strings were mutable like lists, they wouldn't be cached! The consequences would be horrific if they were, unless Python's execution model were radically different. Copy-on-write perhaps? > (Python does not make two copies of small strings until it needs to). Python doesn't copy anything unless you ask it to. -- Steven From doulos05 at gmail.com Fri Aug 13 02:22:23 2010 From: doulos05 at gmail.com (JonathanB) Date: Thu, 12 Aug 2010 23:22:23 -0700 (PDT) Subject: extra rows in a CSV module output when viewed in excel 2007 Message-ID: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> The subject basically says it all, here's the code that's producing the csv file: def write2CSV(self,output): writer = csv.writer(open(output, 'w'), dialect='excel') writer.writerow(['Name','Description','Due Date','Subject', 'Grade','Maximum Grade', self.name, self.grade]) for row in self.assignment_list: writer.writerow(row.output2list()) return True Here's the text from the csv file my test-run outputs: Name,Description,Due Date,Subject,Grade,Maximum Grade,Test Student,2 Math Homework 8/21,Math Review pp. 103-104,2010-08-13,Math,10,10,, Math Test,Chapter 5,2010-09-21,Math,45,50,, Science Test,Matter,2010-09-11,Science,400,500,, When I view it in Excel, there's an extra row between every result. How can I remove those? From wuwei23 at gmail.com Fri Aug 13 02:52:41 2010 From: wuwei23 at gmail.com (alex23) Date: Thu, 12 Aug 2010 23:52:41 -0700 (PDT) Subject: extra rows in a CSV module output when viewed in excel 2007 References: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> Message-ID: On Aug 13, 4:22?pm, JonathanB wrote: > ? ? ? ? writer = csv.writer(open(output, 'w'), dialect='excel') I think - not able to test atm - that if you open the file in 'wb' mode instead it should be fine. From gelonida at gmail.com Fri Aug 13 03:11:40 2010 From: gelonida at gmail.com (Gelonida) Date: Fri, 13 Aug 2010 09:11:40 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: Lee, On 08/13/2010 12:53 AM, Lee Harr wrote: > >> I'm desperate. I'm having a real application, which fails rather often >> when finishing it. I'm not sure, whether any serious problem could be >> hidden behind it >> >> The script is a pyqt script, which segfaults most of the time on my >> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. > > > Looks to be a known issue: > http://www.google.com/search?q=pyqt+segfault+on+exit > https://launchpad.net/bugs/561303 > > The last activity on that bug is almost 2 months ago... > Hopefully the fix will be distributed soon. This seems to be the problem. In my case I can workaround the issue by adding one line. if __name__ == "__main__": app = QApplication([]) myform = MyForm() myform.show() retcode = app.exec_() myform = None # <<<< THIS IS THE WORK AROUND print "last" Thaks a lot From blur959 at hotmail.com Fri Aug 13 03:54:40 2010 From: blur959 at hotmail.com (blur959) Date: Fri, 13 Aug 2010 00:54:40 -0700 (PDT) Subject: How do I get number of files in a particular directory. Message-ID: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> Hi, all, Is there a way to get a number of files in a particular directory? I tried using os.walk, os.listdir but they are return me with a list, tuple of the files, etc. But I want it to return a number. Is it possible? From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 13 04:44:13 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 13 Aug 2010 10:44:13 +0200 Subject: How do I get number of files in a particular directory. In-Reply-To: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> Message-ID: <4c6505c5$0$9878$426a34cc@news.free.fr> blur959 a ?crit : > Hi, all, Is there a way to get a number of files in a particular > directory? I tried using os.walk, os.listdir but they are return me > with a list, tuple of the files, etc. But I want it to return a > number. Is it possible? len(any_sequence) From cs at zip.com.au Fri Aug 13 04:51:11 2010 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 13 Aug 2010 18:51:11 +1000 Subject: How do I get number of files in a particular directory. In-Reply-To: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> Message-ID: <20100813085110.GA4173@cskk.homeip.net> On 13Aug2010 00:54, blur959 wrote: | Hi, all, Is there a way to get a number of files in a particular | directory? I tried using os.walk, os.listdir but they are return me | with a list, tuple of the files, etc. But I want it to return a | number. Is it possible? Measure the length of the list returned to you? The len() built in function suggests itself... -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ From martin.hellwig at dcuktec.org Fri Aug 13 04:57:25 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 13 Aug 2010 09:57:25 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <4c645c7c$0$3675$426a74cc@news.free.fr> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION On 08/12/10 21:41, News123 wrote: > On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: >> On 08/11/10 21:14, Baba wrote: >> >> >> How about rephrasing that question in your mind first, i.e.: >> >> For every number that is one higher then the previous one*: >> If this number is dividable by: >> 6 or 9 or 20 or any combination of 6, 9, 20 >> than this number _can_ be bought in an exact number >> else >> print this number >> > > you are allowed to mix. > 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 I was aware of that, thats whhy I wrote: "or any combination of 6, 9, 20" > > I guess, trying to find the result with divisions and remainders is > overly complicated. Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 Type "help", "copyright", "credits" or "license" for more information. >>> MODULO_COMBINATIONS = [[20], [9], [6], ... [20, 9], [20, 6], [9, 20], ... [9, 6], [6, 20], [6, 9], ... [20, 9, 6], [20, 6, 9], [9, 20, 6], ... [9, 6, 20], [6, 20, 9], [6, 9, 20]] >>> >>> def apply_combinations_on(number): ... tmp = list() ... for combination in MODULO_COMBINATIONS: ... remainder = number ... for modulo_value in combination: ... if remainder == 0: ... remainder = None ... break ... ... result = remainder % modulo_value ... ... if result == remainder : ... remainder = None ... break ... ... remainder = result ... ... if remainder == 0: ... tmp.append(str(combination)) ... return(tmp) ... >>> print(apply_combinations_on(15)) ['[9, 6]'] >>> What is so over complicated about it? -- mph From blur959 at hotmail.com Fri Aug 13 05:18:11 2010 From: blur959 at hotmail.com (blur959) Date: Fri, 13 Aug 2010 02:18:11 -0700 (PDT) Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> Message-ID: <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Hi, I tried that, but it doesn't seem to work. My file directory has many different files extensions, and I want it to return me a number based on the number of files with similar files extensions. But when I tried running it, I get many weird numbers. Below is my code i had so far and the result. import os directory = raw_input("Please input file directory. \n\n") s = raw_input("Please input a name to replace. \n\n") ext = raw_input("input file ext") for files in os.listdir(directory): if ext in files: file_number = len(files) print file_number The result is: 13 13 13 6 15 8 10 10 8 7 5 where the result should be just 11. Can anyone help me? Thanks. From davea at ieee.org Fri Aug 13 05:23:31 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 13 Aug 2010 05:23:31 -0400 Subject: Importing libs on Windows? In-Reply-To: References: Message-ID: <4C650F13.7010704@ieee.org> Brian Salter wrote: > It appears that every example is calling a dll, and I'm looking to > bring in a lib. Does ctypes work with libs too? > > "Gary Herron" wrote in message > news:mailman.2044.1281656800.1673.python-list at python.org... >> On 08/12/2010 04:09 PM, Brian Salter wrote: >>> I've seen a number of tutorials that describe how to bring in a dll >>> in python, but does anybody know of a tutorial for how to bring in a >>> lib? Is it even possible? >>> >>> Thanks, in advance! >>> >>> >> >> Look at the Python module named ctypes: >> http://docs.python.org/library/ctypes.html >> >> Gary Herron >> >> > A lib file is not executable. It's a *description* of routines and data that has to be converted by a linker into actual executable code. The reason it's called a static lib is that once it is converted by the linker, the actual executable code resides inside the EXE file. So an application written in C doesn't ship with the lib file either (unless of course it's a compiler/linker). What's your actual goal? DaveA From sschwarzer at sschwarzer.net Fri Aug 13 05:30:37 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 13 Aug 2010 11:30:37 +0200 Subject: How do I get number of files in a particular directory. In-Reply-To: <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: <4C6510BD.2090800@sschwarzer.net> On 2010-08-13 11:18, blur959 wrote: > import os > > directory = raw_input("Please input file directory. \n\n") > s = raw_input("Please input a name to replace. \n\n") > ext = raw_input("input file ext") > > for files in os.listdir(directory): > if ext in files: > file_number = len(files) > print file_number > > > The result is: > 13 > 13 > 13 > 6 > 15 > 8 > 10 > 10 > 8 > 7 > 5 > > where the result should be just 11. Can anyone help me? Thanks. `os.listdir` returns a list of names. What you named `files` should actually be `filename`. What you got printed in the loop are the lengths of each filename. Stefan From jeanmichel at sequans.com Fri Aug 13 05:45:28 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 13 Aug 2010 11:45:28 +0200 Subject: writing \feff at the begining of a file Message-ID: <4C651438.50203@sequans.com> Hello python world, I'm trying to update the content of a $Microsoft$ VC2005 project files using a python application. Since those files are XML data, I assumed I could easily do that. My problem is that VC somehow thinks that the file is corrupted and update the file like the following: - +? Actually, is displayed in a different color by vim, telling me that this is some kind of special caracter code (I'm no familiar with such thing). After googling that, I have a clue : could be some unicode caracter use to indicate something ... well I don't know in fact ("UTF-8 files sometimes start with a byte-order marker (BOM) to indicate that they are encoded in UTF-8."). My problem is however simplier : how do I add such character at the begining of the file ? I tried f = open('paf', w) f.write(u'\ufeff') UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128) The error may be explicit but I have no idea how to proceed further. Any clue ? JM From __peter__ at web.de Fri Aug 13 05:46:03 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 11:46:03 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: Martin P. Hellwig wrote: > SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION > > On 08/12/10 21:41, News123 wrote: > >> On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: >>> On 08/11/10 21:14, Baba wrote: >>> >>> >>> How about rephrasing that question in your mind first, i.e.: >>> >>> For every number that is one higher then the previous one*: >>> If this number is dividable by: >>> 6 or 9 or 20 or any combination of 6, 9, 20 >>> than this number _can_ be bought in an exact number >>> else >>> print this number >>> >> >> you are allowed to mix. >> 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 > > I was aware of that, thats whhy I wrote: > "or any combination of 6, 9, 20" > >> >> I guess, trying to find the result with divisions and remainders is >> overly complicated. > > Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) > [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 > Type "help", "copyright", "credits" or "license" for more information. > >>> MODULO_COMBINATIONS = [[20], [9], [6], > ... [20, 9], [20, 6], [9, 20], > ... [9, 6], [6, 20], [6, 9], > ... [20, 9, 6], [20, 6, 9], [9, 20, 6], > ... [9, 6, 20], [6, 20, 9], [6, 9, 20]] > >>> > >>> def apply_combinations_on(number): > ... tmp = list() > ... for combination in MODULO_COMBINATIONS: > ... remainder = number > ... for modulo_value in combination: > ... if remainder == 0: > ... remainder = None > ... break > ... > ... result = remainder % modulo_value > ... > ... if result == remainder : > ... remainder = None > ... break > ... > ... remainder = result > ... > ... if remainder == 0: > ... tmp.append(str(combination)) > ... return(tmp) > ... > >>> print(apply_combinations_on(15)) > ['[9, 6]'] > >>> > > What is so over complicated about it? > Well, it was hard enough for me to run the code rather than just read it. I get >>> apply_combinations_on(21) [] which should be 1*9 + 2*6 What am I missing? Peter From mail at timgolden.me.uk Fri Aug 13 05:58:59 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 13 Aug 2010 10:58:59 +0100 Subject: writing \feff at the begining of a file In-Reply-To: <4C651438.50203@sequans.com> References: <4C651438.50203@sequans.com> Message-ID: <4C651763.3070306@timgolden.me.uk> On 13/08/2010 10:45, Jean-Michel Pichavant wrote: > My problem is however simplier : how do I add such character at the > begining of the file ? > I tried > > f = open('paf', w) f = open ("pag", "wb") f.write ("\xfe\xff") TJG From dickinsm at gmail.com Fri Aug 13 06:01:25 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 13 Aug 2010 03:01:25 -0700 (PDT) Subject: Floating numbers References: Message-ID: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> On Aug 12, 9:43?pm, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. Nitpick: unless you're on very unusual hardware, you're missing some zeros here. On my machine, under Python 2.6, the float 34.52 displays as 34.520000000000003, and the value stored internally is actually 34.52000000000000312638803734444081783294677734375; so that's within 1 part in 10**16 of the value you entered. Why do you care? That's a serious question, and its answer goes a long way to determining what you should do. - If you're doing calculations with this number, then the difference between the number Python stores and 34.52 is so miniscule that in normal situations it's not going to matter. In particular, if it represents some physical quantity then any error in the representation will be swamped by the inherent measurement error. IOW, it's not worth worrying about. - If you're printing this number, and you just want the output to look nice (why? perhaps because you're showing this to other people?), then use float formatting operations to limit the number of decimal places you're printing. For example, '%.6f' % my_float, or format(my_float, '.6f'), will give my_float to 6 places after the decimal point. Or, as others have mentioned, it just so happens that Python 2.7 and 3.x will output a nice representation for this float automatically. That wouldn't necessarily be true if the result were coming from a calculation, though, so you shouldn't rely on repr producing nice results in those versions of Python. - If you *really* need a number that represents the *exact* value 34.52, then use the decimal module, or perhaps consider using a simple home-brewed fixed-point representation. One situation where you might care is when doing financial calculations, and in particular when rounding a quantity to a smaller number of decimal digits. Here binary floats can give unpredictable results in halfway cases. (E.g., round(2.675, 2) might give 2.68 or 2.67, depending on what version of Python you're using, and also possibly depending on your platforms.) -- Mark From __peter__ at web.de Fri Aug 13 06:09:57 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 12:09:57 +0200 Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: blur959 wrote: > Hi, I tried that, but it doesn't seem to work. My file directory has > many different files extensions, and I want it to return me a number > based on the number of files with similar files extensions. But when I > tried running it, I get many weird numbers. Below is my code i had so > far and the result. Use glob.glob() instead of os.listdir() if you are only interested in files with a specific extension: >>> import glob >>> len(glob.glob("*.py")) 42 Peter From downaold at gmail.com Fri Aug 13 06:25:06 2010 From: downaold at gmail.com (Roald de Vries) Date: Fri, 13 Aug 2010 12:25:06 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <4C645EB9.7060105@optimum.net> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4C645EB9.7060105@optimum.net> Message-ID: <0E6BB339-057C-4B78-A0EB-AC4EA2FAF152@gmail.com> On Aug 12, 2010, at 10:51 PM, John Posner wrote: > On 8/12/2010 9:22 AM, Dave Angel wrote: >>> >>> Now you have to find the largest number below 120, which you can >>> easily do with brute force > tgt = 120 # thanks, Dave Angel Anytime, but I'm not Dave Angel. My previous algorithm was more efficient, but for those who like one- liners: [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) for b in range(x/9) for c in range(x/6))][-1] Cheers, Roald From darragh.ssa at gmail.com Fri Aug 13 06:31:09 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Fri, 13 Aug 2010 03:31:09 -0700 (PDT) Subject: Deditor -- pythonic text-editor Message-ID: Hey, I've finished my second version of deditor, a python text-editor for python under linux. It offers some python-only features like an interpreter, a code- analyzer, syntax-highlighting,... Are there some people in here who would like to test the app? (and maybe even help spread it) more info can be found on launchpad: https://launchpad.net/deditor or you can mail me darragh.ssa at gmail.com From downaold at gmail.com Fri Aug 13 06:38:53 2010 From: downaold at gmail.com (Roald de Vries) Date: Fri, 13 Aug 2010 12:38:53 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <0E6BB339-057C-4B78-A0EB-AC4EA2FAF152@gmail.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4C645EB9.7060105@optimum.net> <0E6BB339-057C-4B78-A0EB-AC4EA2FAF152@gmail.com> Message-ID: <0101CFDA-4A4D-463B-ABBE-830B1869B1AA@gmail.com> On Aug 13, 2010, at 12:25 PM, Roald de Vries wrote: > My previous algorithm was more efficient, but for those who like one- > liners: > > [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) > for b in range(x/9) for c in range(x/6))][-1] OK, I did some real testing now, and there's some small error in the above. All solutions for all x's are given by: [(x, a, b, c) for x in range(120) for a in range(x/20+1) for b in range(x/9+1) for c in range(x/6+1) if x == a*20+b*9+c*6] ... and all non-solutions by: [x for x in range(120) if not any(x == a*20+b*9+c*6 for a in range(x/20+1) for b in range(x/9+1) for c in range(x/6+1))] Cheers, Roald From srisimhan at gmail.com Fri Aug 13 06:40:05 2010 From: srisimhan at gmail.com (Srikanth N) Date: Fri, 13 Aug 2010 16:10:05 +0530 Subject: Python CGI windows Message-ID: Dear All, I Have certain clarification in python CGI. I use Python IDLE *1. How do we execute CGI Scripts in Windows? 2. How do i configure the Server?(If i use WAMP,XAMPP) 3. Is mod_python required for python cgi? * Someone Please revert back to me with the solution for the same.I would be at-most thankful -- Thanks & Regards, Srikanth.N -------------- next part -------------- An HTML attachment was scrubbed... URL: From eckhardt at satorlaser.com Fri Aug 13 06:43:44 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Fri, 13 Aug 2010 12:43:44 +0200 Subject: writing \feff at the begining of a file References: Message-ID: <08kfj7-7ei.ln1@satorlaser.homedns.org> Jean-Michel Pichavant wrote: > My problem is however simplier : how do I add such character [a BOM] > at the begining of the file ? > I tried > > f = open('paf', w) > f.write(u'\ufeff') > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in > position 0: ordinal not in range(128) Try the codecs module to open the file, which will then do all the transcoding between internal texts and external UTF-8 for you. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From martin.hellwig at dcuktec.org Fri Aug 13 06:51:22 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 13 Aug 2010 11:51:22 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: On 08/13/10 10:46, Peter Otten wrote: > Martin P. Hellwig wrote: > >> SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION No it wasn't :-) > which should be 1*9 + 2*6 > > What am I missing? > Aah interesting, 21 % 9 returns 3 instead of 12, which makes sense of course. I guess the algorithm has to be adapted in a way that if the value is bigger or equal twice the size of the modulo value you need to iterate over it, something like: for minus_multiplier in range(1, int(number, modulo_value)+2): number = number - (modulo_value * minus_multiplier) do the rest of the loop Probably another ten lines or so to make it working as it should -- mph From blur959 at hotmail.com Fri Aug 13 07:02:21 2010 From: blur959 at hotmail.com (blur959) Date: Fri, 13 Aug 2010 04:02:21 -0700 (PDT) Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: On Aug 13, 6:09?pm, Peter Otten <__pete... at web.de> wrote: > blur959 wrote: > > Hi, I tried that, but it doesn't seem to work. My file directory has > > many different files extensions, and I want it to return me a number > > based on the number of files with similar files extensions. But when I > > tried running it, I get many weird numbers. Below is my code i had so > > far and the result. > > Use glob.glob() instead of os.listdir() if you are only interested in files > with a specific extension: > > >>> import glob > >>> len(glob.glob("*.py")) > > 42 > > Peter Hi, I want to make it such that the user inputs a file extension and it prints the number of similar file extensions out. I tried doing this: directory = raw_input("input file directory") ext = raw_input("input file ext") file_list = len(glob.glob(ext)) print file_list And my result was this: 0 which it is suppose to be 11 May I know why? And how do I specify which directory it is searching the files extension from? I want the user to specify a directory and it searches the particular directory for the particular file extensions and prints the number out. Hope you guys could help. Thanks From dlanorslegov at rocketmail.com Fri Aug 13 07:14:37 2010 From: dlanorslegov at rocketmail.com (Dlanor Slegov) Date: Fri, 13 Aug 2010 04:14:37 -0700 (PDT) Subject: Inserting/Deleting newline(s) in very large text files In-Reply-To: References: <595550.37557.qm@web120110.mail.ne1.yahoo.com> Message-ID: <959582.50301.qm@web120114.mail.ne1.yahoo.com> I would greatly appreciate a python solution as this problem is only the head of a larger problem for which I am on a mission to write a FULL one-stop-shop python script. I am trying two things- iter() and fileinput module... Thanks! ________________________________ From: Matty Sarro To: Dlanor Slegov Sent: Thu, August 12, 2010 5:22:58 PM Subject: Re: Inserting/Deleting newline(s) in very large text files On Thu, Aug 12, 2010 at 11:12 AM, Dlanor Slegov wrote: Hi, > >I am dealing with very large text files (a few million lines) and would like to >check and modify them according to a well defined format. The format >requires?ONLY ONE?NEWLINE (followed by some sort of text) on top of the file and >NO NEWLINE in the very end. The input files can be very diverse, such as?one >file may have 2 newlines on top and none in the end or other may not have a >newline on top and 5 in the end. > > >The aim is to check these files &?introduce JUST ONE NEWLINE in the?TOP and NO >NEWLINE in the BOTTOM. > >Any pointers will be appreciated. > >Thanks, >DS. >?? > >-- >http://mail.python.org/mailman/listinfo/python-list > > If you're using a unix box you may want to look into sed. sed -i. '1i text to be inserted in first line' For example: sed -i.bak '1i alias bond0 bonding' /etc/modprobe.conf Would back up the original file to the initial filename plus the extension .bak. Then it would insert: alias bond0 bonding into /etc/modprobe.conf Into the 1st line of the file, moving everything else down one line. You can find some info on dealing with newlines here: http://www.grymoire.com/Unix/Sed.html#toc-uh-nl I know you're looking for a python solution, but this may be easier. Just a heads up. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Aug 13 07:21:58 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 13:21:58 +0200 Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: blur959 wrote: > On Aug 13, 6:09 pm, Peter Otten <__pete... at web.de> wrote: >> blur959 wrote: >> > Hi, I tried that, but it doesn't seem to work. My file directory has >> > many different files extensions, and I want it to return me a number >> > based on the number of files with similar files extensions. But when I >> > tried running it, I get many weird numbers. Below is my code i had so >> > far and the result. >> >> Use glob.glob() instead of os.listdir() if you are only interested in >> files with a specific extension: >> >> >>> import glob >> >>> len(glob.glob("*.py")) >> >> 42 >> >> Peter > > > Hi, I want to make it such that the user inputs a file extension and > it prints the number of similar file extensions out. > I tried doing this: > > directory = raw_input("input file directory") > ext = raw_input("input file ext") > > file_list = len(glob.glob(ext)) > print file_list > > > And my result was this: > 0 > which it is suppose to be 11 > > May I know why? And how do I specify which directory it is searching > the files extension from? I want the user to specify a directory and > it searches the particular directory for the particular file > extensions and prints the number out. > Hope you guys could help. The part of the filename you don't care about has to be replaced with a "*": import os import glob directory = raw_input("directory? ") ext = raw_input("file extension? ") pattern = os.path.join(directory, "*" + ext) matching_files = glob.glob(pattern) print len(matching_files), "matching files" Note that you'll learn a lot more when you look up in the documentation how the functions mentioned actually work instead of coming back here for every tiny detail. I you don't feel ready yet to understand enough of the Python documentation, go one step back and work your way through a tutorial or introductory book. A starting point is here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Peter From mikael.liljeroth at gmail.com Fri Aug 13 07:22:08 2010 From: mikael.liljeroth at gmail.com (Mikael Liljeroth) Date: Fri, 13 Aug 2010 13:22:08 +0200 Subject: Embedding, subinterpreters and dynamic types Message-ID: Hi, this is my first contact with the python community so I hope this is the right place for my two questions. They are both related to embedding and extending python. I'm writing a program that dynamically loads c++ modules that extend the functionality of my program. These modules are controlled by scripts. Currently I have embedded the v8 javascript engine but I would also like to support scripts written in python. I have a special interface between the c++ modules and the scripts to be able to support different scripting languages. Scripts are separated into different 'applications' that are executed in one process triggered by external events (no threading, since I'm working in an event driven system). The scripts should execute independently of each other. I solved this with v8 by switching between the applications' contexts. However, it seems like python has some issues with this. 1. To do some basic context switching I assume I should use a sub interpreter ie create a new thread state (without any actual threads). I cannot find any information on how to do this except creating the new thread state. Is this the preferred way of doing this, if so, how do I switch between different thread states and execute scripts in them? I assume scripts running in one thread state are isolated from scripts running in other thread states, like global variables and such (except for the GIL thing?) ? I do not care much about security problems like file descriptor issues and extension issues right now. 2. When a new C++ module is loaded into my program I want to create a representation of it in Python. Not as a type, but rather just return a single object instance reference of a new type representing the exported attributes and methods of the module's C++ class. In other words, I want to be able to do something like this obj = application.getObject("objectId"); where objectId is the name of an instance of that c++ module type. I do not want the script to be able to create new instances of this type, since this is done via xml in my program. Hence I would also like to be able to associate my C++ object with my returned python object to be able to manipulate it when methods are called on 'obj'. So how do I define a new type on the fly and create an instance of it, associated with a c++ pointer and return it in the c function representing the python method 'getObject' in my application module? Hope this makes any sense, let me know if something is unclear. Regards Mikael Liljeroth From davea at ieee.org Fri Aug 13 08:15:29 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 13 Aug 2010 08:15:29 -0400 Subject: How do I get number of files in a particular directory. In-Reply-To: References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: <4C653761.8090305@ieee.org> blur959 wrote: > On Aug 13, 6:09 pm, Peter Otten <__pete... at web.de> wrote: > >> blur959 wrote: >> >>> Hi, I tried that, but it doesn't seem to work. My file directory has >>> many different files extensions, and I want it to return me a number >>> based on the number of files with similar files extensions. But when I >>> tried running it, I get many weird numbers. Below is my code i had so >>> far and the result. >>> >> Use glob.glob() instead of os.listdir() if you are only interested in files >> with a specific extension: >> >> >>>>> import glob >>>>> len(glob.glob("*.py")) >>>>> >> 42 >> >> Peter >> > > > Hi, I want to make it such that the user inputs a file extension and > it prints the number of similar file extensions out. > I tried doing this: > > directory =aw_input("input file directory") > ext =aw_input("input file ext") > > file_list =en(glob.glob(ext)) > print file_list > > > And my result was this: > 0 > which it is suppose to be 11 > > May I know why? And how do I specify which directory it is searching > the files extension from? I want the user to specify a directory and > it searches the particular directory for the particular file > extensions and prints the number out. > Hope you guys could help. > > Thanks > > Glob doesn't do much useful unless there's a wildcard. And as you point out, it also needs the directory. You want to pass it something like mydirect/*.txt In your case, you might construct that with something like os.path.join(directory, "*." + ext) DaveA From wxjmfauth at gmail.com Fri Aug 13 10:03:23 2010 From: wxjmfauth at gmail.com (jmfauth) Date: Fri, 13 Aug 2010 07:03:23 -0700 (PDT) Subject: Floating numbers References: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> Message-ID: <24495a41-bae0-4965-9bfb-de55230c632d@a36g2000yqc.googlegroups.com> A quick question. I understand how to get these numbers 34.52000000000000312638803734444081783294677734375 and 47 (from 2**47) and the sign. with the decimal module, but I fail to find this one 4858258098025923 Possible? From blur959 at hotmail.com Fri Aug 13 10:40:42 2010 From: blur959 at hotmail.com (blur959) Date: Fri, 13 Aug 2010 07:40:42 -0700 (PDT) Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: Hi all, I got a problem with my script. Everything looks good so far but for some reason my os.rename isn't working. Can anyone tell me why? Hope you guys could help. Thanks. import os import glob directory = raw_input("directory? ") ext = raw_input("file extension? ") r = raw_input("replace name") pattern = os.path.join(directory, "*" + ext) matching_files = glob.glob(pattern) file_number = len(matching_files) for filename in os.listdir(directory): if ext in filename: path = os.path.join(directory, filename) seperated_names = os.path.splitext(filename)[0] replace_name = filename.replace(seperated_names, r) split_new_names = os.path.splitext(replace_name)[0] for pad_number in range(0, file_number): padded_numbers = "%04d" % pad_number padded_names = "%s_%s" % (split_new_names, padded_numbers) newpath = os.path.join(directory, padded_names) newpathext = "%s%s" % (newpath, ext) new_name = os.rename(path, newpathext) From patentsvnc at gmail.com Fri Aug 13 11:27:50 2010 From: patentsvnc at gmail.com (Den) Date: Fri, 13 Aug 2010 08:27:50 -0700 (PDT) Subject: Python "why" questions References: Message-ID: > ... However, the killer reason is: "it's what everybody > else does. If this were really true, lists would be 1-based. I go back to WATFOR; and Fortran (and I believe Cobol and PL/I, though I'm not positive about them) were 1-based. (Now that I think about it, PL/I, knowing IBM, could probably be set to use either) Back then, everyone else was doing 1-based lists. In my opinion, the reason lists are 0-based started with a lazy programmer who decided that his own comfort (using 0-based addressing at the machine level and not having to translate the high-level 1- based language index into a low-level 0-based index) was paramount over teaching the language and having it make sense in the real world. After all, not even Brian Kernighan thinks books start on page 0. I'm not singling out C in this case because it is a relatively low- level language for low-level programmers and 0-based lists make perfect sense in that context. But then every compiler/interpreter programmer after that stopped caring about it. I smile every time I see the non-nonsensical sentence "The first thing, therefore, is in thing[0]" in a programming language learning book or tutorial. I laugh every time I hear someone defend that as common sense. Every three year old watching Sesame Street knows counting things starts with '1', not '0'. When you were three and you counted your blocks, you started with '1', not '0'. The whole rest of the world understands that implicitly, even if their counting starts '1', '2', 'many'. 0-based lists are NOT common sense. They only make sense to the programmers of computer languages, and their fanbois. There may be loads of reasons for it, but don't throw common sense around as one of them. Den From dickinsm at gmail.com Fri Aug 13 11:43:24 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 13 Aug 2010 08:43:24 -0700 (PDT) Subject: Floating numbers References: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> <24495a41-bae0-4965-9bfb-de55230c632d@a36g2000yqc.googlegroups.com> Message-ID: On Aug 13, 3:03?pm, jmfauth wrote: > A quick question. > > I understand how to get these numbers > > 34.52000000000000312638803734444081783294677734375 > > and > > 47 (from 2**47) > > and the sign. > > with the decimal module, but I fail to find this one > > 4858258098025923 > > Possible? See the float.as_integer_ratio method. -- Mark From praveen.python.plone at gmail.com Fri Aug 13 12:46:34 2010 From: praveen.python.plone at gmail.com (Praveen) Date: Fri, 13 Aug 2010 09:46:34 -0700 (PDT) Subject: text to DB Message-ID: I have a text file in this format PRA 1:13 2:20 3:5 SRA 1:45 2:75 3:9 TRA 1:2 2:65 3:45 pattern is- Book Chapter:Verses now i have my DB schema like this book_id chapter_id versed_id 1 1 13 1 2 20 1 3 5 2 1 45 2 2 75 2 3 9 3 1 2 3 2 65 3 3 45 I want to write a pyhton script which read the text file and dump to DB could any one give me suggestion From thomas at jollans.com Fri Aug 13 12:50:12 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 18:50:12 +0200 Subject: Embedding, subinterpreters and dynamic types In-Reply-To: References: Message-ID: <4C6577C4.7010004@jollans.com> On 2010-08-13 13:22, Mikael Liljeroth wrote: > Hi, this is my first contact with the python community so I hope this > is the right place for my two questions. > They are both related to embedding and extending python. > > I'm writing a program that dynamically loads c++ modules that extend > the functionality of my program. > These modules are controlled by scripts. Currently I have embedded the > v8 javascript engine but I would also like to support scripts written > in python. I have a special interface between the c++ modules and the > scripts to be able to support different scripting languages. Scripts > are separated into different 'applications' that are executed in one > process triggered by external events (no threading, since I'm working > in an event driven system). The scripts should execute independently > of each other. I solved this with v8 by switching between the > applications' contexts. However, it seems like python has some issues > with this. > > 1. To do some basic context switching I assume I should use a sub > interpreter ie create a new thread state (without any actual threads). > I cannot find any information on how to do this except creating the > new thread state. Is this the preferred way of doing this, if so, how > do I switch between different thread states and execute scripts in > them? I assume scripts running in one thread state are isolated from > scripts running in other thread states, like global variables and such > (except for the GIL thing?) ? I do not care much about security > problems like file descriptor issues and extension issues right now. > Py_NewInterpreter does indeed sound like what you want. I have a feeling you're going to run into problems here sooner or later, say, when extension modules that aren't yours use static variables. As for switching interpreters, after skimming the docs, I'm guessing you're looking for PyEval_AcquireThread http://docs.python.org/py3k/c-api/init.html#PyEval_AcquireThread > 2. When a new C++ module is loaded into my program I want to create a > representation of it in Python. Not as a type, but rather just return > a single object instance reference of a new type representing the > exported attributes and methods of the module's C++ class. In other > words, I want to be able to do something like this obj = > application.getObject("objectId"); where objectId is the name of an > instance of that c++ module type. I do not want the script to be able > to create new instances of this type, since this is done via xml in my > program. Hence I would also like to be able to associate my C++ object > with my returned python object to be able to manipulate it when > methods are called on 'obj'. So how do I define a new type on the fly > and create an instance of it, associated with a c++ pointer and return > it in the c function representing the python method 'getObject' in my > application module? > How difficult this is obviously depends somewhat on how varied the types you create are, but in principle, there's no difference between creating a type statically and creating one on-the-fly: all you need to do to create a type is create a PyTypeObject structure with suitable function pointers. If you want to make it impossible to create a second instance of your type, you can simply create a tp_new or tp_init that raises an exception. If you have a good look at http://docs.python.org/py3k/extending/newtypes.html , you'll notice that most of the "creating a type" involves writing a static PyTypeObject structure -- you'll just have to allocate that yourself, and you should be good. From szport at gmail.com Fri Aug 13 13:00:56 2010 From: szport at gmail.com (zaur) Date: Fri, 13 Aug 2010 10:00:56 -0700 (PDT) Subject: how to make portable distribution of python 2.6? Message-ID: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> All greetings! How to make portable distribution of python 2.6? From simon at brunningonline.net Fri Aug 13 13:03:16 2010 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 13 Aug 2010 18:03:16 +0100 Subject: python interview quuestions In-Reply-To: <4c6298c1$0$11101$c3e8da3@news.astraweb.com> References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <4c6298c1$0$11101$c3e8da3@news.astraweb.com> Message-ID: On 11 August 2010 13:34:09 UTC+1, Steven D'Aprano wrote: > Getting interviewees to do a take-home problem just means you hire the > guy who is friends with a good programmer, rather than the good > programmer. We give a take-home problem. If we like the code we see, we invite the candidate to come in and pair with one of our devs in adding a simple feature or two to their own code. It's time consuming, but not so time consuming as hiring a weak dev. -- Cheers, Simon B. From thomas at jollans.com Fri Aug 13 13:14:44 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 19:14:44 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4C657D84.6030506@jollans.com> On 2010-08-13 17:27, Den wrote: > There may be loads of reasons for it, but don't throw common sense > around as one of them. > It's a good thing then that I didn't: >> ... However, the killer reason is: "it's what everybody >> else does. >> > "Where it all started" is that 0-based indexing gives languages like C a very nice property: a[i] and *(a+i) are equivalent in C. From a language design viewpoint, I think that's quite a strong argument. Languages based directly on C (C++, Objective C, ...) can't break with this for obvious reasons, and other language designers/implementers imitated this behaviour without any good reason to do so, or not to do so. In higher-level languages, it doesn't really matter. 1-based indexing might seam more intuitive, but in the end, it's just another thing you have to learn when learning a language, like "commas make tuples", and somebody studying a programming language learns it, and gets used to it if they aren't used to it already. From thomas at jollans.com Fri Aug 13 13:28:01 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 19:28:01 +0200 Subject: how to make portable distribution of python 2.6? In-Reply-To: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> References: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> Message-ID: <4C6580A1.2010203@jollans.com> On 2010-08-13 19:00, zaur wrote: > All greetings! > > How to make portable distribution of python 2.6? > I don't know, but what you're looking for probably already exists. Do you mean "portable" as in portable, i.e. "take this and build it for your system, it should work if your OS is supported"? Then you can get source tarballs from python.org http://python.org/download/ Or do you understand "portable" the way that is fashionable in the Windows world nowadays for some reason, i.e. "look, Ma, already installed if you happen to use Microsoft Windows of roughly the right version!" Then http://www.portablepython.com/ is exactly where Google would have lead you had you searched. From thomas at jollans.com Fri Aug 13 13:34:57 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 19:34:57 +0200 Subject: Python CGI windows In-Reply-To: References: Message-ID: <4C658241.5000203@jollans.com> On 2010-08-13 12:40, Srikanth N wrote: > *1. How do we execute CGI Scripts in Windows? > * You'll need a web server. > *2. How do i configure the Server?(If i use WAMP,XAMPP) > * For CGI, you just need your server configured for CGI, nothing Python-specific. It would surprise me if XAMPP didn't set up a working cgi-bin for your programming pleasure anyway. > *3. Is mod_python required for python cgi? > * No. mod_python is a completely different approach to running Python from the web. Don't use it, it's dead. If you want something similar, use mod_wsgi. ** Come to think of it, you should probably look into WSGI anyway -- you can run WSGI scripts via CGI for the time being, that's simple enough, and switch to something else for production, or for serious development, later on. > Someone Please revert back to me with the solution for the same.I > would be at-most thankful This line is fascinating, -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Fri Aug 13 13:36:08 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 13 Aug 2010 17:36:08 GMT Subject: Python "why" questions References: Message-ID: <8cle48FdneU1@mid.individual.net> On 2010-08-13, Thomas Jollans wrote: > 1-based indexing might seam more intuitive, but in the end, > it's just another thing you have to learn when learning a > language, like "commas make tuples", and somebody studying a > programming language learns it, and gets used to it if they > aren't used to it already. I think the main reason zero-based indexing is chosen in higher level languages is the following useful property: x[n:m] + x[m:len(x)] == x -- Neil Cerutti From thomas at jollans.com Fri Aug 13 13:36:44 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 19:36:44 +0200 Subject: Python CGI windows In-Reply-To: References: Message-ID: <4C6582AC.4010302@jollans.com> On 2010-08-13 12:40, Srikanth N wrote: > *2. How do i configure the Server?(If i use WAMP,XAMPP) > * Sorry, I forgot to link you to http://www.editrocket.com/articles/python_apache_windows.html Hope this helps. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Fri Aug 13 13:45:22 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Aug 2010 18:45:22 +0100 Subject: writing \feff at the begining of a file In-Reply-To: <4C651438.50203@sequans.com> References: <4C651438.50203@sequans.com> Message-ID: <4C6584B2.8060903@mrabarnett.plus.com> Jean-Michel Pichavant wrote: > Hello python world, > > I'm trying to update the content of a $Microsoft$ VC2005 project files > using a python application. > Since those files are XML data, I assumed I could easily do that. > > My problem is that VC somehow thinks that the file is corrupted and > update the file like the following: > > - > +? > > > Actually, is displayed in a different color by vim, telling me > that this is some kind of special caracter code (I'm no familiar with > such thing). > After googling that, I have a clue : could be some unicode caracter use > to indicate something ... well I don't know in fact ("UTF-8 files > sometimes start with a byte-order marker (BOM) to indicate that they are > encoded in UTF-8."). > > My problem is however simplier : how do I add such character at the > begining of the file ? > I tried > > f = open('paf', w) > f.write(u'\ufeff') > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in > position 0: ordinal not in range(128) > > The error may be explicit but I have no idea how to proceed further. Any > clue ? > In Python 2 the default encoding is 'ascii'. What you want is 'utf-8'. Use codecs.open() instead, with the 'utf-8-sig' encoding, which will include the BOM. From martin at address-in-sig.invalid Fri Aug 13 13:53:56 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Fri, 13 Aug 2010 17:53:56 +0000 (UTC) Subject: Python "why" questions References: Message-ID: On Fri, 13 Aug 2010 19:14:44 +0200, Thomas Jollans wrote: > "Where it all started" is that 0-based indexing gives languages like C a > very nice property: a[i] and *(a+i) are equivalent in C. From a language > design viewpoint, I think that's quite a strong argument. Languages > based directly on C (C++, Objective C, ...) can't break with this for > obvious reasons, and other language designers/implementers imitated this > behaviour without any good reason to do so, or not to do so. In > higher-level languages, it doesn't really matter. 1-based indexing might > seam more intuitive. > In a higher level language 1-based indexing is just as limiting as 0- based indexing. What you really want is the ability to declare the index range to suit the problem: in Algol 60 it is very useful to be able to declare something like: real sample[-500:750]; and Algol 68 went even further: flex [1:0] int count where the array bounds change dynamically with each assignment to 'count'. Iteration is supported by the lwb and upb operators which return the bounds of an array, so you can write: for i from lwb count to upb count do.... -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From python at mrabarnett.plus.com Fri Aug 13 13:57:24 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Aug 2010 18:57:24 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: <4C658784.9050404@mrabarnett.plus.com> Martin P. Hellwig wrote: > On 08/13/10 10:46, Peter Otten wrote: >> Martin P. Hellwig wrote: >> >>> SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION > No it wasn't :-) > >> which should be 1*9 + 2*6 >> >> What am I missing? >> > > Aah interesting, 21 % 9 returns 3 instead of 12, which makes sense of > course. I guess the algorithm has to be adapted in a way that if the > value is bigger or equal twice the size of the modulo value you need to > iterate over it, something like: > for minus_multiplier in range(1, int(number, modulo_value)+2): > number = number - (modulo_value * minus_multiplier) > do the rest of the loop > > Probably another ten lines or so to make it working as it should > I don't understand what you're trying to do. My solution would be: def can_buy(nuggets): for packs_20 in range(nuggets // 20, -1, -1): remaining_20 = nuggets - 20 * packs_20 for packs_9 in range(remaining_20 // 9, -1, -1): remaining_9 = remaining_20 - 9 * packs_9 if remaining_9 % 6 == 0: packs_6 = remaining_9 // 6 return [packs_6, packs_9, packs_20] return [] From nobody at nowhere.com Fri Aug 13 14:04:10 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 13 Aug 2010 19:04:10 +0100 Subject: writing \feff at the begining of a file References: Message-ID: On Fri, 13 Aug 2010 11:45:28 +0200, Jean-Michel Pichavant wrote: > I'm trying to update the content of a $Microsoft$ VC2005 project files > using a python application. > Since those files are XML data, I assumed I could easily do that. > > My problem is that VC somehow thinks that the file is corrupted and > update the file like the following: > > - > +? > > > Actually, is displayed in a different color by vim, telling me > that this is some kind of special caracter code (I'm no familiar with > such thing). U+FEFF is a "byte order mark" or BOM. Each Unicode-based encoding (UTF-8, UTF-16, UTF-16-LE, etc) will encode it differently, so it enables a program reading the file to determine the encoding before reading any actual data. > My problem is however simplier : how do I add such character at the > begining of the file ? > I tried Either: 1. Open the file as binary and write '\xef\xbb\xbf' to the file: f = open('foo.txt', 'wb') f.write('\xef\xbb\xbf') [You can also use the constant BOM_UTF8 from the codecs module.] 2. Open the file as utf-8 and write u'\ufeff' to the file: import codecs f = codecs.open('foo.txt', 'w', 'utf-8') f.write(u'\ufeff') 3. Open the file as utf-8-sig and don't write anything (or write an empty string): import codecs f = codecs.open('foo.txt', 'w', 'utf-8-sig') f.write('') The utf-8-sig codec automatically writes a BOM at the beginning of the file. It is present in Python 2.5 and later. From python at mrabarnett.plus.com Fri Aug 13 14:09:55 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Aug 2010 19:09:55 +0100 Subject: text to DB In-Reply-To: References: Message-ID: <4C658A73.5010904@mrabarnett.plus.com> Praveen wrote: > I have a text file in this format > PRA 1:13 2:20 3:5 > SRA 1:45 2:75 3:9 > TRA 1:2 2:65 3:45 > > pattern is- Book Chapter:Verses > > now i have my DB schema like this > book_id chapter_id versed_id > 1 1 13 > 1 2 20 > 1 3 5 > 2 1 45 > 2 2 75 > 2 3 9 > 3 1 2 > 3 2 65 > 3 3 45 > > I want to write a pyhton script which read the text file and dump to > DB > > could any one give me suggestion Read through the file a line at a time. For the first line the book_id is 1, for the second it's 2, etc. Split each line on whitespace, and then for all but the first entry (which is a name?) split on the colon to get the chapter_id and versed_id. Insert each tuple of (book_id, chapter_id, versed_id) into the DB. You haven't said what type of DB it is, so I can't help you there. Just read the documentation. From szport at gmail.com Fri Aug 13 14:23:59 2010 From: szport at gmail.com (zaur) Date: Fri, 13 Aug 2010 11:23:59 -0700 (PDT) Subject: how to make portable distribution of python 2.6? References: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> Message-ID: <21480f31-c156-408a-a354-70debaa2dedc@l6g2000yqb.googlegroups.com> On 13 ???, 21:28, Thomas Jollans wrote: > On 2010-08-13 19:00, zaur wrote:> All greetings! > > > How to make portable distribution of python 2.6? > > I don't know, but what you're looking for probably already exists. > > Do you mean "portable" as in portable, i.e. "take this and build it for > your system, it should work if your OS is supported"? Then you can get > source tarballs from python.org > > http://python.org/download/ > > Or do you understand "portable" the way that is fashionable in the > Windows world nowadays for some reason, i.e. "look, Ma, already > installed if you happen to use Microsoft Windows of roughly the right > version!" > > Thenhttp://www.portablepython.com/is exactly where Google would have > lead you had you searched. I want to realize howto build my own portable python in order to use them without installation. I want also to be able install modules (numpy, matplotlib, pyqt, etc...) when it is necessary. This very usefull for teaching python in computer classes. From raoulbia at gmail.com Fri Aug 13 14:25:32 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 13 Aug 2010 11:25:32 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> Message-ID: <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> Hi News 123, Ok i'm getting closer. I am able to write code that will output values that can be bought in exact quantity (truelist) and values that cannot be bought in exact quantities. For a range up to 29 i get this: true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28] the sixth value that passes the test of having an exact solution is 20 so that would mean that the last number i got that cannot be bought in exact quantity is 19 that doesn't seem quite right, does it? def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True return False truelist=[] falselist=[] for n_nuggets in range(30): result = can_buy(n_nuggets) if result==True: truelist=truelist+[n_nuggets,] else: falselist=falselist+[n_nuggets,] print 'true',truelist print 'false',falselist tnx Baba From raoulbia at gmail.com Fri Aug 13 14:25:47 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 13 Aug 2010 11:25:47 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> Message-ID: Hi News 123, Ok i'm getting closer. I am able to write code that will output values that can be bought in exact quantity (truelist) and values that cannot be bought in exact quantities. For a range up to 29 i get this: true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28] the sixth value that passes the test of having an exact solution is 20 so that would mean that the last number i got that cannot be bought in exact quantity is 19 that doesn't seem quite right, does it? def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True return False truelist=[] falselist=[] for n_nuggets in range(30): result = can_buy(n_nuggets) if result==True: truelist=truelist+[n_nuggets,] else: falselist=falselist+[n_nuggets,] print 'true',truelist print 'false',falselist tnx Baba From andrei.avk at gmail.com Fri Aug 13 14:30:57 2010 From: andrei.avk at gmail.com (AK) Date: Fri, 13 Aug 2010 14:30:57 -0400 Subject: Python Tutorial Message-ID: <4C658F61.9010708@gmail.com> Hello, I plan to make a new python tutorial and I'd like to collaborate with someone on it. I'm thinking of a slightly different approach than existing tutorials: the idea is that readers will learn from examples, going from small but complete and useful scripts to larger programs, similar to Django by Example: http://lightbird.net/dbe/ If you are interested and have a few years of experience with Python, drop me an email and we'll discuss this further... -ak From lie.1296 at gmail.com Fri Aug 13 14:31:45 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 14 Aug 2010 04:31:45 +1000 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <4c658ab2$1@dnews.tpgi.com.au> On 08/10/10 06:36, Bartc wrote: > And if the context is Python, I doubt whether the choice of 0-based over a > 1-based makes that much difference in execution speed. And I doubt anyone cares about execution speed when deciding whether to use 1-based or 0-based array. The reason why you want to choose the alternative that use less conversion to the other system is to simplify the source code. Many common mathematical/physics/economics formulas are expressed much simply if we use 0-based counting: * arithmetic series: - 1-based: s(n) = a + (n - 1) * d - 0-based: s(n) = a + n * d * geometric series: - 1-based: g(n) = a * r**(n - 1) - 0-based: g(n) = a * r**n * equation of motion: - 1-based: x(t) = a + 1/2 * a * (t - 1)**2 - 0-based: x(t) = a + 1/2 * a * t**2 * exponential growth/decay: - 1-based: d(t) = a * e**(k * (t - 1)) - 0-based: d(t) = a * e**(k*t) In fact, most textbooks would already uses 0-based formula for some of these formulas already. Most physics and economic textbooks would show the base 0 variation of the formula, and refers to t=0 as the point in time where the "event" started. I often used this model of thinking for 0-based array indices (and negative indices): -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 (7) instead of: In short, the choice of 0-based array is of practical purpose, rather than historical purpose. From lie.1296 at gmail.com Fri Aug 13 14:43:50 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 14 Aug 2010 04:43:50 +1000 Subject: Python "why" questions In-Reply-To: <4c658ab2$1@dnews.tpgi.com.au> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c658ab2$1@dnews.tpgi.com.au> Message-ID: <4c658d87$1@dnews.tpgi.com.au> Sorry the message gets cuts off by an accidental press of send button. On 08/14/10 04:31, Lie Ryan wrote: > On 08/10/10 06:36, Bartc wrote: >> And if the context is Python, I doubt whether the choice of 0-based over a >> 1-based makes that much difference in execution speed. > > And I doubt anyone cares about execution speed when deciding whether to > use 1-based or 0-based array. The reason why you want to choose the > alternative that use less conversion to the other system is to simplify > the source code. > > Many common mathematical/physics/economics formulas are expressed much > simply if we use 0-based counting: > > * arithmetic series: > - 1-based: s(n) = a + (n - 1) * d > - 0-based: s(n) = a + n * d > * geometric series: > - 1-based: g(n) = a * r**(n - 1) > - 0-based: g(n) = a * r**n > * equation of motion: > - 1-based: x(t) = a + 1/2 * a * (t - 1)**2 > - 0-based: x(t) = a + 1/2 * a * t**2 > * exponential growth/decay: > - 1-based: d(t) = a * e**(k * (t - 1)) > - 0-based: d(t) = a * e**(k*t) > > > In fact, most textbooks would already uses 0-based formula for some of > these formulas already. Most physics and economic textbooks would show > the base 0 variation of the formula, and refers to t=0 as the point in > time where the "event" started. > > I often used this model of thinking for 0-based array indices (and > negative indices): > > -7 -6 -5 -4 -3 -2 -1 > +---+---+---+---+---+---+---+ > | c | h | a | r | l | i | e | > +---+---+---+---+---+---+---+ > 0 1 2 3 4 5 6 (7) > > instead of: > so to repeat, I often use this model of thinking: -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 (7) instead of: -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 that is, the indices refers to the "gap" between the array entries. The "gap index" model highlights the naturalness of using 0-based array, negative indices, array slicing, and half-open. From wxjmfauth at gmail.com Fri Aug 13 14:46:50 2010 From: wxjmfauth at gmail.com (jmfauth) Date: Fri, 13 Aug 2010 11:46:50 -0700 (PDT) Subject: Floating numbers References: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> <24495a41-bae0-4965-9bfb-de55230c632d@a36g2000yqc.googlegroups.com> Message-ID: <77846e0a-251b-41f4-85d6-4e23e3dd260f@d8g2000yqf.googlegroups.com> On 13 ao?t, 17:43, Mark Dickinson wrote: > On Aug 13, 3:03?pm, jmfauth wrote: > > > > > A quick question. > > > I understand how to get these numbers > > > 34.52000000000000312638803734444081783294677734375 > > > and > > > 47 (from 2**47) > > > and the sign. > > > with the decimal module, but I fail to find this one > > > 4858258098025923 > > > Possible? > > See the float.as_integer_ratio method. > > -- > Mark Thanks. I *stupidely* forget this. jmf From hansmu at xs4all.nl Fri Aug 13 15:14:40 2010 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 13 Aug 2010 21:14:40 +0200 Subject: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT) In-Reply-To: <7762bda5-e1dc-461c-82a1-7eaa431b5bef@x25g2000yqj.googlegroups.com> References: <7762bda5-e1dc-461c-82a1-7eaa431b5bef@x25g2000yqj.googlegroups.com> Message-ID: <4c6599df$0$22933$e4fe514c@news.xs4all.nl> tormod wrote: > On Aug 12, 12:30 pm, Alexander Gattin wrote: >> Does Windows have anything like LD_LIBRARY_PATH/SHLIB_PATH? Yes and no. Windows uses PATH both for finding execuables and for finding DLLs. So if there's a DLL Windows cannot find, you need to add the folder containing that DLL to your PATH variable. > No, isn't that only if I have an actual Oracle client installed (not > the instant client)? Whether you use the instant client or an actual Oracle client is not the issue. You may or may not need LD_LIBRARY_PATH either way. When you import cx_Oracle on Linux, it loads a file named cx_Oracle.so which in turn loads two files named libclntsh.so and libnnz10.so. These two files are part of the Oracle client installation. The dynamic loader has a list of directories where it tries to find these files; if they aren't there, then the import of cx_Oracle will fail. In that case, you need to set LD_LIBRARY_PATH to the directory containing them (or talk your sysadmin into adding this directory to the default path. He'd do that by adding the directory to /etc/ld.so.conf and running ldconfig). Hope this helps, -- HansM From ian.g.kelly at gmail.com Fri Aug 13 15:25:07 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 13 Aug 2010 13:25:07 -0600 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> Message-ID: On Fri, Aug 13, 2010 at 12:25 PM, Baba wrote: > Hi News 123, > > Ok i'm getting closer. I am able to write code that will output values > that can be bought in exact quantity (truelist) and values that cannot > be bought in exact quantities. > > For a range up to 29 i get this: > true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] > false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, > 28] > > the sixth value that passes the test of having an exact solution is 20 > so that would mean that the last number i got that cannot be bought in > exact quantity is 19 > > that doesn't seem quite right, does it? It's not. You're not just trying to find the sixth value that can be bought in exact quantity, but a sequence of six values that can all be bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not sequential. From alister.ware at ntlworld.com Fri Aug 13 15:30:26 2010 From: alister.ware at ntlworld.com (Alister Ware) Date: Fri, 13 Aug 2010 19:30:26 GMT Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: On Fri, 13 Aug 2010 07:40:42 -0700, blur959 wrote: > Hi all, I got a problem with my script. Everything looks good so far but > for some reason my os.rename isn't working. Can anyone tell me why? Hope > you guys could help. Thanks. > You have a number of logic flaws in your code. 1st you do not actually need to know how many matching files you have. 2nd you need to rename the file inside the same loop that is splitting your file name (this is why you are failing, your rename loop has the same filename each time around), I knocked up a quick hack loosely based on your original code that will generate the file names for you. it has some stratigic print statements so you can see what is happening (always a good idea when debugging code) I have left the actual re-naming of the files for you to complete, I would also agree with the earlier suggestion that you work through some on line tutorials import os import glob def rename(filelist): #function to add a count to each filenale in a list count=0 for fullname in filelist: count+=1 print "full file path %s" % fullname path,filename=os.path.split(fullname) name,ext=os.path.splitext(filename) print "path: '%s' Name: '%s' Extn: '%s'" % (path,name,ext) newname="%s_%04d.%s" %(name,count,ext) print "New filename: '%s'" % newname # rename filename to newname goes here # dont forget you also need path directory = raw_input("directory? ") ext = raw_input("file extension? ") r = raw_input("replace name") pattern = os.path.join(directory, "*." + ext) matching_files = glob.glob(pattern) rename(matching_files) -- Nothing makes one so vain as being told that one is a sinner. Conscience makes egotists of us all. -- Oscar Wilde From inhahe at gmail.com Fri Aug 13 15:54:52 2010 From: inhahe at gmail.com (inhahe) Date: Fri, 13 Aug 2010 12:54:52 -0700 (PDT) Subject: struct pointing to another struct? Message-ID: say i have this definition: 1 typedef struct SDL_Surface { 2 Uint32 flags; /* Read-only */ 3 SDL_PixelFormat *format; /* Read-only */ 4 int w, h; /* Read-only */ 5 Uint16 pitch; /* Read-only */ 6 void *pixels; /* Read-write */ 7 SDL_Rect clip_rect; /* Read-only */ 8 int refcount; /* Read-mostly */ 9 10 /* This structure also contains private fields not shown here */ 11 } SDL_Surface; notice two pointers, format and pixels. say format has this definition. 1 typedef struct { 2 SDL_Palette *palette; 3 Uint8 BitsPerPixel; 4 Uint8 BytesPerPixel; 5 Uint8 Rloss, Gloss, Bloss, Aloss; 6 Uint8 Rshift, Gshift, Bshift, Ashift; 7 Uint32 Rmask, Gmask, Bmask, Amask; 8 Uint32 colorkey; 9 Uint8 alpha; 10 } SDL_PixelFormat; so say i want to create a mock sdl handle and pass it to some library function that requires an sdl handle. (would it even work? would i need to use an SDL_SWSURFACE?) so i make the pixelformat data using struct.pack, and make the surface data using struct.pack, but how do i link the surface data to the pixelformat data? if i just use id() it'll give me the memory address of the "box" for the string and not the string data itself. thanks. From __peter__ at web.de Fri Aug 13 16:07:45 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 22:07:45 +0200 Subject: struct pointing to another struct? References: Message-ID: inhahe wrote: > say i have this definition: > > 1 typedef struct SDL_Surface { > 2 Uint32 flags; /* Read-only */ > 3 SDL_PixelFormat *format; /* Read-only */ > 4 int w, h; /* Read-only */ > 5 Uint16 pitch; /* Read-only */ > 6 void *pixels; /* Read-write */ > 7 SDL_Rect clip_rect; /* Read-only */ > 8 int refcount; /* Read-mostly */ > 9 > 10 /* This structure also contains private fields not shown here > */ > 11 } SDL_Surface; > > notice two pointers, format and pixels. > say format has this definition. > > > 1 typedef struct { > 2 SDL_Palette *palette; > 3 Uint8 BitsPerPixel; > 4 Uint8 BytesPerPixel; > 5 Uint8 Rloss, Gloss, Bloss, Aloss; > 6 Uint8 Rshift, Gshift, Bshift, Ashift; > 7 Uint32 Rmask, Gmask, Bmask, Amask; > 8 Uint32 colorkey; > 9 Uint8 alpha; > 10 } SDL_PixelFormat; > > so say i want to create a mock sdl handle and pass it to some library > function that requires an sdl handle. (would it even work? would i > need to use an SDL_SWSURFACE?) > > so i make the pixelformat data using struct.pack, and make the surface > data using struct.pack, but how do i link the surface data to the > pixelformat data? if i just use id() it'll give me the memory address > of the "box" for the string and not the string data itself. thanks. I think you are looking at the wrong module; you need ctypes, not struct. http://docs.python.org/library/ctypes.html Peter From news1234 at free.fr Fri Aug 13 16:22:44 2010 From: news1234 at free.fr (News123) Date: Fri, 13 Aug 2010 22:22:44 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4C645EB9.7060105@optimum.net> <0E6BB339-057C-4B78-A0EB-AC4EA2FAF152@gmail.com> Message-ID: <4c65a994$0$20281$426a74cc@news.free.fr> Roald, What would your solution be if you weren't allowed to 'know' that 120 is an upper limit. Assume you were only allowed to 'know', that you won't find any other amount, which can't be bought A AOON A you found six solutions in a row? I have a rather straightforward solution trying from 0 nuggets on until I found six 'hits' in a row, but would be interested about other idioms. On 08/13/2010 12:38 PM, Roald de Vries wrote: > On Aug 13, 2010, at 12:25 PM, Roald de Vries wrote: >> My previous algorithm was more efficient, but for those who like >> one-liners: >> >> [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) >> for b in range(x/9) for c in range(x/6))][-1] > > OK, I did some real testing now, and there's some small error in the > above. All solutions for all x's are given by: > > [(x, a, b, c) for x in range(120) for a in range(x/20+1) for b in > range(x/9+1) for c in range(x/6+1) if x == a*20+b*9+c*6] > > ... and all non-solutions by: > > [x for x in range(120) if not any(x == a*20+b*9+c*6 for a in > range(x/20+1) for b in range(x/9+1) for c in range(x/6+1))] > > Cheers, Roald From inhahe at gmail.com Fri Aug 13 16:28:08 2010 From: inhahe at gmail.com (inhahe) Date: Fri, 13 Aug 2010 13:28:08 -0700 (PDT) Subject: struct pointing to another struct? References: Message-ID: On Aug 13, 4:07?pm, Peter Otten <__pete... at web.de> wrote: > inhahe wrote: > > say i have this definition: > > > ? ?1 typedef struct SDL_Surface { > > ? ?2 ? ? Uint32 flags; ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-only */ > > ? ?3 ? ? SDL_PixelFormat *format; ? ? ? ? ? ? ? ?/* Read-only */ > > ? ?4 ? ? int w, h; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-only */ > > ? ?5 ? ? Uint16 pitch; ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-only */ > > ? ?6 ? ? void *pixels; ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-write */ > > ? ?7 ? ? SDL_Rect clip_rect; ? ? ? ? ? ? ? ? ? ? /* Read-only */ > > ? ?8 ? ? int refcount; ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-mostly */ > > ? ?9 > > ? 10 ? /* This structure also contains private fields not shown here > > */ > > ? 11 } SDL_Surface; > > > notice two pointers, format and pixels. > > say format has this definition. > > > ? ?1 typedef struct { > > ? ?2 ? SDL_Palette *palette; > > ? ?3 ? Uint8 ?BitsPerPixel; > > ? ?4 ? Uint8 ?BytesPerPixel; > > ? ?5 ? Uint8 ?Rloss, Gloss, Bloss, Aloss; > > ? ?6 ? Uint8 ?Rshift, Gshift, Bshift, Ashift; > > ? ?7 ? Uint32 Rmask, Gmask, Bmask, Amask; > > ? ?8 ? Uint32 colorkey; > > ? ?9 ? Uint8 ?alpha; > > ? 10 } SDL_PixelFormat; > > > so say i want to create a mock sdl handle and pass it to some library > > function that requires an sdl handle. (would it even work? would i > > need to use an SDL_SWSURFACE?) > > > so i make the pixelformat data using struct.pack, and make the surface > > data using struct.pack, but how do i link the surface data to the > > pixelformat data? ?if i just use id() it'll give me the memory address > > of the "box" for the string and not the string data itself. ?thanks. > > I think you are looking at the wrong module; you need ctypes, not struct. > > http://docs.python.org/library/ctypes.html > > Peter can you (or anybody) tell me how to link one c struct to another using ctypes? Thx From jjposner at optimum.net Fri Aug 13 16:28:52 2010 From: jjposner at optimum.net (John Posner) Date: Fri, 13 Aug 2010 16:28:52 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4C645EB9.7060105@optimum.net> Message-ID: <4C65AB04.6000405@optimum.net> On 8/13/2010 6:25 AM, Roald de Vries wrote: > On Aug 12, 2010, at 10:51 PM, John Posner wrote: >> On 8/12/2010 9:22 AM, Dave Angel wrote: >>>> >>>> Now you have to find the largest number below 120, which you can >>>> easily do with brute force >> tgt = 120 # thanks, Dave Angel > > Anytime, but I'm not Dave Angel. Oops -- sorry for the erroneous attribution, Roald. -John From kxepal at gmail.com Fri Aug 13 16:47:09 2010 From: kxepal at gmail.com (Kxepal) Date: Fri, 13 Aug 2010 13:47:09 -0700 (PDT) Subject: Dump logging configuration Message-ID: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> Hi all! Sorry for dumb question if it is - I'd tried to google it before but have found nothing. Is there any way to dump current logging configuration for future loading it via fileConfig/dictConfig? From vamsikrishna.bandlamudi at gmail.com Fri Aug 13 16:50:48 2010 From: vamsikrishna.bandlamudi at gmail.com (Vamsi) Date: Fri, 13 Aug 2010 13:50:48 -0700 (PDT) Subject: Help to convert Number to String Message-ID: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> I am trying to count the number of lines in a file and insert into the file but getting the error message "TypeError: must be string or read-only character buffer, not int", Could you please help me how to correct this? here is the code lines1 = sum(1 for line in open('C:/test1.txt')) wfile = open('C:/test1.txt'', 'a') wfile.write(str(lines1).zfill(9)) wfile.close() Thanks. From news1234 at free.fr Fri Aug 13 17:02:52 2010 From: news1234 at free.fr (News123) Date: Fri, 13 Aug 2010 23:02:52 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: <4c65b2fd$0$11772$426a74cc@news.free.fr> On 08/13/2010 10:57 AM, Martin P. Hellwig wrote: > SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION > > On 08/12/10 21:41, News123 wrote: > >> On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: >>> On 08/11/10 21:14, Baba wrote: >>> >>> >>> How about rephrasing that question in your mind first, i.e.: >>> >>> For every number that is one higher then the previous one*: >>> If this number is dividable by: >>> 6 or 9 or 20 or any combination of 6, 9, 20 >>> than this number _can_ be bought in an exact number >>> else >>> print this number >>> >> >> you are allowed to mix. >> 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 > > I was aware of that, thats whhy I wrote: > "or any combination of 6, 9, 20" > >> >> I guess, trying to find the result with divisions and remainders is >> overly complicated. > > Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) > [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 > Type "help", "copyright", "credits" or "license" for more information. >>>> MODULO_COMBINATIONS = [[20], [9], [6], > ... [20, 9], [20, 6], [9, 20], > ... [9, 6], [6, 20], [6, 9], > ... [20, 9, 6], [20, 6, 9], [9, 20, 6], > ... [9, 6, 20], [6, 20, 9], [6, 9, 20]] >>>> >>>> def apply_combinations_on(number): > ... tmp = list() > ... for combination in MODULO_COMBINATIONS: > ... remainder = number > ... for modulo_value in combination: > ... if remainder == 0: > ... remainder = None > ... break > ... > ... result = remainder % modulo_value > ... > ... if result == remainder : > ... remainder = None > ... break > ... > ... remainder = result > ... > ... if remainder == 0: > ... tmp.append(str(combination)) > ... return(tmp) > ... >>>> print(apply_combinations_on(15)) > ['[9, 6]'] >>>> > > What is so over complicated about it? What I meant with complicated is your mathematical assumption about modulos, which are probably not obvious to everybody on the first glance. Saying, that you can find out, whether for integers a,b.c,n the equation n = a*6 + b*9 + c*20 is true by verifying whether n mod 6 == 0 or n mod 9 == 0 or (n mod 6) mod 9 == 0 or (n mod 9) mod 6 == 0 Trial error is not so smart, but much easier to explain to beginners. One can even return a,b,c for verification. Being a little (and incrementally) smart, the search space can then be reduced by some degrees with rather easy to explain and incremental assumptions, For given example the run times are so short, that it's not really an issue. Another advantage of brute force is, that you can return a,b,c and not only say, whether a,b,c exist. This allows simple verification or assertions during debugging and learning. # plain brute force. #------------------------------------ def can_buy(n_nuggets): for a in range (n_nuggets): for b in range (n_nuggets): for c in range (n_nuggets): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a + 9*b + 20*c == n_nuggets: return (a,b,c) return () # brute force but reduce the upper limit for each loop by saying, # that one can stop if one a*6 > n or b*9 > n or c*20 >n #------------------------------------------ def can_buy(n_nuggets): for a in range (n_nuggets / 6 + 1): for b in range (n_nuggets / 9 + 1): for c in range (n_nuggets / 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a + 9*b + 20*c == n_nuggets: return (a,b,c) return () # as above code, but try even less in inner loops by # removing what has been taken in outer loop #-------------------------------------------- def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1, left_6 / 9 + 1): left_9 = left_6 - b * 9 for c in range (1, left_9/ 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a+9*b+20*c==n_nuggets: return (a,b,c) return () # as above code, but do less multiplications # in inner loop #------------------------------------------- def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1, left_6 / 9 + 1): left_9 = left_6 - b * 9 for c in range (1, left_9/ 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 20*c == left_9: return (a,b,c) return () # as above code, but use modulo in inner loop # ------------------------------------------ def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1, left_6 / 9 + 1): left_9 = left_6 - b * 9 print "trying for %2d: %2d %2d c" % (n,a,b) if left_9 % 20 == 0: return (a,b,left_9/20) return () From __peter__ at web.de Fri Aug 13 17:03:32 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 23:03:32 +0200 Subject: struct pointing to another struct? References: Message-ID: inhahe wrote: > On Aug 13, 4:07 pm, Peter Otten <__pete... at web.de> wrote: >> inhahe wrote: >> > say i have this definition: >> >> > 1 typedef struct SDL_Surface { >> > 2 Uint32 flags; /* Read-only */ >> > 3 SDL_PixelFormat *format; /* Read-only */ >> > 4 int w, h; /* Read-only */ >> > 5 Uint16 pitch; /* Read-only */ >> > 6 void *pixels; /* Read-write */ >> > 7 SDL_Rect clip_rect; /* Read-only */ >> > 8 int refcount; /* Read-mostly */ >> > 9 >> > 10 /* This structure also contains private fields not shown here >> > */ >> > 11 } SDL_Surface; >> >> > notice two pointers, format and pixels. >> > say format has this definition. >> >> > 1 typedef struct { >> > 2 SDL_Palette *palette; >> > 3 Uint8 BitsPerPixel; >> > 4 Uint8 BytesPerPixel; >> > 5 Uint8 Rloss, Gloss, Bloss, Aloss; >> > 6 Uint8 Rshift, Gshift, Bshift, Ashift; >> > 7 Uint32 Rmask, Gmask, Bmask, Amask; >> > 8 Uint32 colorkey; >> > 9 Uint8 alpha; >> > 10 } SDL_PixelFormat; >> >> > so say i want to create a mock sdl handle and pass it to some library >> > function that requires an sdl handle. (would it even work? would i >> > need to use an SDL_SWSURFACE?) >> >> > so i make the pixelformat data using struct.pack, and make the surface >> > data using struct.pack, but how do i link the surface data to the >> > pixelformat data? if i just use id() it'll give me the memory address >> > of the "box" for the string and not the string data itself. thanks. >> >> I think you are looking at the wrong module; you need ctypes, not struct. >> >> http://docs.python.org/library/ctypes.html >> >> Peter > > can you (or anybody) tell me how to link one c struct to another using > ctypes? Thx I know it sounds old-fashioned, but the documentation is worth reading. It contains examples for structs, pointers and arrays, e. g. """ >>> from ctypes import * >>> class cell(Structure): ... pass ... >>> cell._fields_ = [("name", c_char_p), ... ("next", POINTER(cell))] >>> """ Peter From news1234 at free.fr Fri Aug 13 17:09:30 2010 From: news1234 at free.fr (News123) Date: Fri, 13 Aug 2010 23:09:30 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> Message-ID: <4c65b48a$0$12630$426a74cc@news.free.fr> Hi BAba, On 08/13/2010 09:25 PM, Ian Kelly wrote: > On Fri, Aug 13, 2010 at 12:25 PM, Baba wrote: >> Hi News 123, >> >> Ok i'm getting closer. I am able to write code that will output values >> that can be bought in exact quantity (truelist) and values that cannot >> be bought in exact quantities. >> >> For a range up to 29 i get this: >> true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] >> false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, >> 28] >> >> the sixth value that passes the test of having an exact solution is 20 >> so that would mean that the last number i got that cannot be bought in >> exact quantity is 19 >> >> that doesn't seem quite right, does it? As Thomas says: > > It's not. You're not just trying to find the sixth value that can be > bought in exact quantity, but a sequence of six values that can all be > bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not > sequential. Six True values in a row without a False value n between tells you, that you can stop searching. So you that's what you have to write A piece of code, which fetches true fals values for 0 to e.g. 200 nuggets and stops if you had 6 True values in a row. Think how you do it manually: you can try this even without the can_buy function and plug in th can_buy() function only if you ahve your detection of 6 True values in a row working. test_sequence = "0010011011101110111101111111011111" # below I use the enumerate function. # rather useful for going through a list AND having a counter value. # when plugging in your function you can switch back to # for n_nuggets in xramge(200): # perhaps here some initialisation for your searching for i, a_char in enumerat(test_suequence): print "entry %2d (%s) is %s" % (i,a_char,result) result = a_char == '1' # result is now true for a '1' # and false for a '0' # here some code to determine the length of the sequence if sequence_length == 6: print "I found a sequence of 6 and can stop searching" print "my solution is " From python at rcn.com Fri Aug 13 17:12:28 2010 From: python at rcn.com (Raymond Hettinger) Date: Fri, 13 Aug 2010 14:12:28 -0700 (PDT) Subject: shelf-like list? References: Message-ID: On Aug 12, 1:37?pm, Thomas Jollans wrote: > On Tuesday 10 August 2010, it occurred to kj to exclaim: > > > I'm looking for a module that implements "persistent lists": objects > > that behave like lists except that all their elements are stored > > on disk. ?IOW, the equivalent of "shelves", but for lists rather > > than a dictionaries. . . . > You could simply use pickle to save the data every once in a while. That is a very reasonable solution. From gelonida at gmail.com Fri Aug 13 17:13:26 2010 From: gelonida at gmail.com (Gelonida) Date: Fri, 13 Aug 2010 23:13:26 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: On 08/13/2010 09:11 AM, Gelonida wrote: > Lee, > > On 08/13/2010 12:53 AM, Lee Harr wrote: >> >>> I'm desperate. I'm having a real application, which fails rather often >>> when finishing it. I'm not sure, whether any serious problem could be >>> hidden behind it >>> >>> The script is a pyqt script, which segfaults most of the time on my >>> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. >> >> >> Looks to be a known issue: >> http://www.google.com/search?q=pyqt+segfault+on+exit >> https://launchpad.net/bugs/561303 >> >> The last activity on that bug is almost 2 months ago... >> Hopefully the fix will be distributed soon. > > > > This seems to be the problem. > > > In my case I can workaround the issue by adding one line. > > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > myform = None # <<<< THIS IS THE WORK AROUND > print "last" > For more complex multi widget examples it doesn't seem enough to just destroy the main widget. probably I had to recursively assign all widgets / dialogues sub widgets to None. So I'll just try to stay away from this pyqt release and stick with older or newer ones. From gelonida at gmail.com Fri Aug 13 17:13:37 2010 From: gelonida at gmail.com (Gelonida) Date: Fri, 13 Aug 2010 23:13:37 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: On 08/13/2010 09:11 AM, Gelonida wrote: > Lee, > > On 08/13/2010 12:53 AM, Lee Harr wrote: >> >>> I'm desperate. I'm having a real application, which fails rather often >>> when finishing it. I'm not sure, whether any serious problem could be >>> hidden behind it >>> >>> The script is a pyqt script, which segfaults most of the time on my >>> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. >> >> >> Looks to be a known issue: >> http://www.google.com/search?q=pyqt+segfault+on+exit >> https://launchpad.net/bugs/561303 >> >> The last activity on that bug is almost 2 months ago... >> Hopefully the fix will be distributed soon. > > > > This seems to be the problem. > > > In my case I can workaround the issue by adding one line. > > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > myform = None # <<<< THIS IS THE WORK AROUND > print "last" > For more complex multi widget examples it doesn't seem enough to just destroy the main widget. probably I had to recursively assign all widgets / dialogues sub widgets to None. So I'll just try to stay away from this pyqt release and stick with older or newer ones. From xahlee at gmail.com Fri Aug 13 17:18:53 2010 From: xahlee at gmail.com (Xah Lee) Date: Fri, 13 Aug 2010 14:18:53 -0700 (PDT) Subject: math symbols in unicode (grouped by purpose) Message-ID: some collection of math symbols in unicode. ? Math Symbols in Unicode http://xahlee.org/comp/unicode_math_operators.html ? Arrows in Unicode http://xahlee.org/comp/unicode_arrows.html ? Matching Brackets in Unicode http://xahlee.org/comp/unicode_matching_brackets.html these are grouped by the symbol's purpose as much as possible. i made them because i can't find unicode symbols grouped by purpose elsewhere. The unicode ?plane -> block? structure does not group symbols well, because the chars are added throughout the decades. Some symbols get added in one block, but later on related symbols get added elsewhere. For example, binary relational symbols are scattered in different unicode blocks. Same for binary operators, or all symbols used for set theory, etc. Sometimes a symbol has multiple uses in different math fields, so which block it gets added into unicode is not well defined. hope it's useful to some one. Xah ? http://xahlee.org/ ? From aahz at pythoncraft.com Fri Aug 13 17:34:57 2010 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2010 14:34:57 -0700 Subject: Floating numbers References: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> Message-ID: In article <595969e7-354f-456d-82b5-6aeafbabe419 at d8g2000yqf.googlegroups.com>, Mark Dickinson wrote: > > - If you *really* need a number that represents the *exact* value >34.52, then use the decimal module, or perhaps consider using a simple >home-brewed fixed-point representation. Don't use a home-brew fixed-point, rely on Uncle Tim! http://pythoncraft.com/FixedPoint.py -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From tjreedy at udel.edu Fri Aug 13 18:09:49 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Aug 2010 18:09:49 -0400 Subject: Python "why" questions In-Reply-To: References: Message-ID: On 8/13/2010 11:27 AM, Den wrote: > > I smile every time I see the non-nonsensical sentence "The first > thing, therefore, is in thing[0]" in a programming language learning > book or tutorial. I laugh every time I hear someone defend that as > common sense. If one thinks in terms of slicing at gap positions, the 'proper' indexes would range from 0.5 (average of 0 and 1) to n-0.5. For convenience, we round down or up. To put it another way, seq[n:n+1] is abbreviated as either seq[n] or seq[n+1]. Put this way, the first choice is at least as sensible as the second. Given that Python allows indexing from both end, I prefer 0,1,2,... and -1,-2,-3,... to 1,2,3... and 0,-1,-2,... or 1,2,3,... and -1,-2,-3. As someone else pointed out, discretizing a continuous variable starting at 0 gives 0,1,2,... so having indexes that match is handy. If a problem is formulated in terms of 1,2,3, one can simply leave the first cell blank rather than reformulate. If a problem is formulated in terms of 0,1,2,... and indexes are 1 based, then one must reformulate. > Every three year old watching Sesame Street knows > counting things starts with '1', not '0'. And that is the same mistake that most societies make, the mistake that put a lid on Greak math, science, and finance. All fresh counts begin with 0. Counting by people usually begins with a silent 0, just as fresh tallies begin with a blank stick or paper. But not always. For instance, lets count the people who have, up to noe, become billionaires with Python. We start with an overt 0. Now we can discuss whether the founders of Google should increase that to 2. Mechanical counting requires an overt 0. A car odometer starts at 0, not 1 and not . Have you never written a counting program? Starting with n = 1 instead of n = 0 before counting the first item would be a bad bug. > There may be loads of reasons for it, but don't throw common sense > around as one of them. I won't. Only a few (about 3 or 4) societies included a proper 0 in their number systems. -- Terry Jan Reedy From paddy3118 at googlemail.com Fri Aug 13 18:19:55 2010 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 13 Aug 2010 15:19:55 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <4c64d9cf$0$28668$c3e8da3@news.astraweb.com> Message-ID: <51310abd-bc61-434b-9498-ba055b469f95@a36g2000yqc.googlegroups.com> On Aug 13, 6:36?am, Steven D'Aprano wrote: > On Thu, 12 Aug 2010 13:20:19 -0700, Paddy wrote: > > I find myself needing to calculate the difference between two Counters > > or multisets or bags. > > Is this collections.Counter from Python 3.1? If so, you should say so, > and if not, you should tell us which Counter class this is. It will save > people (by which I mean *me*) from spending an unrewarding few minutes > trying to import Counter in Python 2.5 and writing up a sarcastic > response ... :) > > > I want those items that are unique to each bag. I know how to calculate > > it: > > > ? ? >>> b = Counter(a=1, b=2) > > ? ? >>> c = Counter(a=3, b=1) > > ? ? >>> diff = (b - c) + (c - b) > > ? ? >>> (b - c) > > ? ? Counter({'b': 1}) > > ? ? >>> (c - b) > > ? ? Counter({'a': 2}) > > ? ? >>> diff > > ? ? Counter({'a': 2, 'b': 1}) > > > But thought why doesn't this operation appear already as a method of the > > class? > > Don't know. Perhaps you should put in a feature request. > > -- > Steven Yes it is Counter in both 3.1 and 2.7 (And somewhere on Activestate too). Before I put in a feature request, I wanted to know if other have seen the need. From tjreedy at udel.edu Fri Aug 13 18:25:46 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Aug 2010 18:25:46 -0400 Subject: writing \feff at the begining of a file In-Reply-To: <4C651438.50203@sequans.com> References: <4C651438.50203@sequans.com> Message-ID: A short background to MRAB's answer which I will try to get right. The byte-order-mark was invented for UTF-16 encodings so the reader could determine whether the pairs of bytes are in little or big endiean order, depending on whether the first two bute are fe and ff or ff and fe (or maybe vice versa, does not matter here). The concept is meaningless for utf-8 which consists only of bytes in a defined order. This is part of the Unicode standard. However, Microsoft (or whoever) re-purposed (hijacked) that pair of bytes to serve as a non-standard indicator of utf-8 versus any non-unicode encoding. The result is a corrupted utf-8 stream that python accommodates with the utf-8-sig(nature) codec (versus the standard utf-8 codec). -- Terry Jan Reedy From ian.g.kelly at gmail.com Fri Aug 13 19:10:16 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 13 Aug 2010 17:10:16 -0600 Subject: Python "why" questions In-Reply-To: References: Message-ID: On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie wrote: > In a higher level language 1-based indexing is just as limiting as 0- > based indexing. What you really want is the ability to declare the index > range to suit the problem: in Algol 60 it is very useful to be able to > declare something like: > > ? ? ? ?real sample[-500:750]; Ugh, no. The ability to change the minimum index is evil. I don't much care whether a high-level language uses 0-based or 1-based indexing, but I do care that it is consistent. On the occasions when I am forced to use Visual Basic, the single biggest wart that drives me up a wall is constantly having to figure out whether the particular thing that I am currently indexing is 0-based or 1-based. Cheers, Ian From sschwarzer at sschwarzer.net Fri Aug 13 19:27:24 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 14 Aug 2010 01:27:24 +0200 Subject: Help to convert Number to String In-Reply-To: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> Message-ID: <4C65D4DC.7080101@sschwarzer.net> Hi Vamsi, On 2010-08-13 22:50, Vamsi wrote: > I am trying to count the number of lines in a file and insert into > the file but getting the error message "TypeError: must be string or > read-only character buffer, not int", Could you please help me how to > correct this? Which Python version do you use? For which statement exactly do you get the message? > here is the code > > lines1 = sum(1 for line in open('C:/test1.txt')) > wfile = open('C:/test1.txt'', 'a') You have two quotes here after the filename. These give a SyntaxError here. Python sees two concatenated strings, "C:/test1.txt" and ", " and stumbles over the a immediately after the closing quote of the second string. > wfile.write(str(lines1).zfill(9)) > wfile.close() If I remove the redundant quote character and substitute filenames appropriate for my system, everything works. Maybe the code you included in this post isn't the same which led to the error? Stefan From me+list/python at ixokai.io Fri Aug 13 19:37:40 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Fri, 13 Aug 2010 16:37:40 -0700 Subject: Simple Python Sandbox Message-ID: <4C65D744.10201@ixokai.io> Howdy-ho. So, I'm working on a project which embeds Python into a bigger system to provide extensibility. In this project, there's basically two types of people who will be entering python code. The trusted folks, who write code which are in files, and which can do anything. The untrusted folks, who are writing very simple chunks of code which can only do limited things. This latter group we want to sandbox as good as possible. Now, I know that its not possible to perfectly sandbox Python, and I know certain things will never be perfectly safe (like someone doing some crazy [0] * 100000 * 100000 and similar things). That's OK. For this sandbox, we're killing import, execfile, open, eval, reload in __builtin__. This all works well. However in previous discussions, I learned about: >>> [b for b in (1).__class__.__bases__[0].__class__.__subclasses__((1).__class__.__bases__[0]) if b.__name__ == 'file'][0]('../blahblah', 'w').write("Hi!") >>> ^D ixokai$ more ../blahblah Hi! And things like that. (The above may not be the most efficient way to do it). So, I had an idea: why not just do some simple sanitization. When input comes in, just directly replace __ with DISALLOWED, and add getattr/setattr/delattr to the mix of things we kill out of builtins. This second group of people are doing simple little scripting tasks, and not things that would ever involve needing to access a __method__, not even a normal one like __init__. Most of what they do is me.this or me.that("hi") and such. Occasionally there's a little simple logic, but that's it. Can you think of a way out of such a sandbox? A way to access disallowed stuff, not a way to DOS. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From debatem1 at gmail.com Fri Aug 13 19:57:50 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 13 Aug 2010 16:57:50 -0700 Subject: Simple Python Sandbox In-Reply-To: <4C65D744.10201@ixokai.io> References: <4C65D744.10201@ixokai.io> Message-ID: On Fri, Aug 13, 2010 at 4:37 PM, Stephen Hansen wrote: > Howdy-ho. > > So, I'm working on a project which embeds Python into a bigger system to > provide extensibility. In this project, there's basically two types of > people who will be entering python code. > > The trusted folks, who write code which are in files, and which can do > anything. > > The untrusted folks, who are writing very simple chunks of code which > can only do limited things. > > This latter group we want to sandbox as good as possible. Now, I know > that its not possible to perfectly sandbox Python, and I know certain > things will never be perfectly safe (like someone doing some crazy [0] * > 100000 * 100000 and similar things). That's OK. > > For this sandbox, we're killing import, execfile, open, eval, reload in > __builtin__. This all works well. However in previous discussions, I > learned about: > >>>> [b for b in > (1).__class__.__bases__[0].__class__.__subclasses__((1).__class__.__bases__[0]) > if b.__name__ == 'file'][0]('../blahblah', 'w').write("Hi!") >>>> ^D > ixokai$ more ../blahblah > Hi! > > And things like that. (The above may not be the most efficient way to do > it). So, I had an idea: why not just do some simple sanitization. When > input comes in, just directly replace __ with DISALLOWED, and add > getattr/setattr/delattr to the mix of things we kill out of builtins. > > This second group of people are doing simple little scripting tasks, and > not things that would ever involve needing to access a __method__, not > even a normal one like __init__. Most of what they do is me.this or > me.that("hi") and such. Occasionally there's a little simple logic, but > that's it. > > Can you think of a way out of such a sandbox? A way to access disallowed > stuff, not a way to DOS. You may want to check out repy- they use it in the Seattle restricted execution environment, and some pretty smart people claim it has decent security properties. Here's a summary of some of the things they don't allow: https://seattle.cs.washington.edu/wiki/PythonVsRepy Full disclosure: while I don't directly work on the repy environment, I have worked on some other parts of the Seattle project. Geremy Condra From me+list/python at ixokai.io Fri Aug 13 20:05:59 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Fri, 13 Aug 2010 17:05:59 -0700 Subject: Simple Python Sandbox In-Reply-To: References: <4C65D744.10201@ixokai.io> Message-ID: <4C65DDE7.8030203@ixokai.io> On 8/13/10 4:57 PM, geremy condra wrote: > You may want to check out repy- they use it in the Seattle restricted > execution environment, and some pretty smart people claim it has > decent security properties. Here's a summary of some of the things > they don't allow: > > https://seattle.cs.washington.edu/wiki/PythonVsRepy Thanks, I'll look at it. However, its essential we have a fully capable and powered Python for the first-class of people. They're not sandboxed at all. However, I'll check out what they've done for inspiration. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 21:06:14 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2010 01:06:14 GMT Subject: Help to convert Number to String References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> Message-ID: <4c65ec05$0$28668$c3e8da3@news.astraweb.com> On Fri, 13 Aug 2010 13:50:48 -0700, Vamsi wrote: > I am trying to count the number of lines in a file and insert into the > file but getting the error message "TypeError: must be string or > read-only character buffer, not int", Could you please help me how to > correct this? > > > here is the code > > lines1 = sum(1 for line in open('C:/test1.txt')) > wfile = open('C:/test1.txt'', 'a') > wfile.write(str(lines1).zfill(9)) > wfile.close() No, that ISN'T the code you are using. Don't re-type the code (introducing syntax errors), but copy and paste WORKING code. Also you need to copy and paste the EXACT error message you get, not just paraphrasing it. When I correct the obvious errors in your code above, it works for me: >>> f = open('test', 'w') >>> f.write('hello\nworld\n') 12 >>> f.close() >>> lines1 = sum(1 for line in open('test')) >>> wfile = open('test', 'a') >>> wfile.write(str(lines1).zfill(9)) 9 >>> wfile.close() and the file is correctly updated: >>> open('test').read() 'hello\nworld\n000000002' -- Steven From gogonai.alien76 at gmail.com Fri Aug 13 21:09:22 2010 From: gogonai.alien76 at gmail.com (ali nurwatoni) Date: Fri, 13 Aug 2010 18:09:22 -0700 (PDT) Subject: Dominate Mafia Wars Message-ID: <8b43ef4e-4093-4b06-8a65-49095b9256da@y32g2000prc.googlegroups.com> $27 Guide Show You How To Cheat Your Way To The Top. Guaranteed! http://onlinepartner.org/dominate-mafiawars-game Alinurwatoni Supervisor http://www.gogonai.info/?id=alien76 From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 21:54:27 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2010 01:54:27 GMT Subject: writing \feff at the begining of a file References: <4C651438.50203@sequans.com> Message-ID: <4c65f752$0$28668$c3e8da3@news.astraweb.com> On Fri, 13 Aug 2010 18:25:46 -0400, Terry Reedy wrote: > A short background to MRAB's answer which I will try to get right. > > The byte-order-mark was invented for UTF-16 encodings so the reader > could determine whether the pairs of bytes are in little or big endiean > order, depending on whether the first two bute are fe and ff or ff and > fe (or maybe vice versa, does not matter here). The concept is > meaningless for utf-8 which consists only of bytes in a defined order. > This is part of the Unicode standard. > > However, Microsoft (or whoever) re-purposed (hijacked) that pair of > bytes to serve as a non-standard indicator of utf-8 versus any > non-unicode encoding. The result is a corrupted utf-8 stream that python > accommodates with the utf-8-sig(nature) codec (versus the standard utf-8 > codec). Is there a standard way to autodetect the encoding of a text file? I do this: Open the file in binary mode; if the first three bytes are codecs.BOM_UTF8, then it's a Microsoft UTF-8 text file; otherwise if the first two byes are codecs.BOM_BE or codecs.BOM_LE, the encoding is utf-16- be or utf-16-le respectively. (I don't bother to check for other BOMs, such as for utf-32. There are *lots* of them, but in my experience the encodings are rarely used, and the BOMs aren't defined in the codecs module, so I don't bother to support them.) If there's no BOM, then re-open the file and read the first two lines. If either of them match this regex 'coding[=:]\s*([-\w.]+)' then I take the encoding name from that. This matches Python's behaviour, and supports EMACS and vi encoding declarations. Otherwise, there is no declared encoding, and I use whatever encoding I like (whatever was specified by the user or the application default). -- Steven From vamsikrishna.bandlamudi at gmail.com Fri Aug 13 22:43:38 2010 From: vamsikrishna.bandlamudi at gmail.com (Vamsi) Date: Fri, 13 Aug 2010 19:43:38 -0700 (PDT) Subject: Help to convert Number to String References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> <4C65D4DC.7080101@sschwarzer.net> Message-ID: <1e5a5939-42ab-4d8d-a969-a068dea0cb3a@t2g2000yqe.googlegroups.com> On Aug 13, 7:27?pm, Stefan Schwarzer wrote: > Hi Vamsi, > > On 2010-08-13 22:50, Vamsi wrote: > > > I am trying to count the number of lines in a file and insert ?into > > the file but getting the error message "TypeError: must be string or > > read-only character buffer, not int", Could you please help me how to > > correct this? > > Which Python version do you use? > > For which statement exactly do you get the message? > > > here is the code > > > lines1 = sum(1 for line in open('C:/test1.txt')) > > wfile = open('C:/test1.txt'', 'a') > > You have two quotes here after the filename. These give a > SyntaxError here. Python sees two concatenated strings, > "C:/test1.txt" and ", " and stumbles over the a immediately > after the closing quote of the second string. > > > wfile.write(str(lines1).zfill(9)) > > wfile.close() > > If I remove the redundant quote character and substitute > filenames appropriate for my system, everything works. > > Maybe the code you included in this post isn't the same > which led to the error? > > Stefan Thank you Stefan,I pasted only part of the code.I am new to Python and using 2.7.My actual code is as below, If I run the below code I am getting the error "TypeError: 'str' object is not callable" ,Now I found that I am using the "str" variable which is a function.Thanks a lot for your help. fileopen = open('C:/MPython/test.txt', 'r') str = fileopen.read() print str fileopen.close() lines1 = sum(1 for line in open('C:/MPython/test.txt')) wfile = open('C:/MPython/test.txt', 'a') wfile.write("\n") wfile.write(str(lines1).zfill(9)) wfile.close() From vamsikrishna.bandlamudi at gmail.com Fri Aug 13 22:45:11 2010 From: vamsikrishna.bandlamudi at gmail.com (Vamsi) Date: Fri, 13 Aug 2010 19:45:11 -0700 (PDT) Subject: Help to convert Number to String References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> <4c65ec05$0$28668$c3e8da3@news.astraweb.com> Message-ID: <5ded0e17-e240-4aee-9c60-d4d20f98c1ad@x21g2000yqa.googlegroups.com> On Aug 13, 9:06?pm, Steven D'Aprano wrote: > On Fri, 13 Aug 2010 13:50:48 -0700, Vamsi wrote: > > I am trying to count the number of lines in a file and insert ?into the > > file but getting the error message "TypeError: must be string or > > read-only character buffer, not int", Could you please help me how to > > correct this? > > > here is the code > > > lines1 = sum(1 for line in open('C:/test1.txt')) > > wfile = open('C:/test1.txt'', 'a') > > wfile.write(str(lines1).zfill(9)) > > wfile.close() > > No, that ISN'T the code you are using. > > Don't re-type the code (introducing syntax errors), but copy and paste > WORKING code. Also you need to copy and paste the EXACT error message you > get, not just paraphrasing it. > > When I correct the obvious errors in your code above, it works for me: > > > > >>> f = open('test', 'w') > >>> f.write('hello\nworld\n') > 12 > >>> f.close() > >>> lines1 = sum(1 for line in open('test')) > >>> wfile = open('test', 'a') > >>> wfile.write(str(lines1).zfill(9)) > 9 > >>> wfile.close() > > and the file is correctly updated: > > >>> open('test').read() > > 'hello\nworld\n000000002' > > -- > Steven Thank you Steve for your response. I pasted only part of the code.I am new to Python and using 2.7.My actual code is as below, If I run the below code I am getting the error "TypeError: 'str' object is not callable" ,Now I found that I am using the "str" variable which is a function.Thanks a lot for your help. fileopen = open('C:/MPython/test.txt', 'r') str = fileopen.read() print str fileopen.close() lines1 = sum(1 for line in open('C:/MPython/test.txt')) wfile = open('C:/MPython/test.txt', 'a') wfile.write("\n") wfile.write(str(lines1).zfill(9)) wfile.close() From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 23:04:17 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2010 03:04:17 GMT Subject: Simple Python Sandbox References: Message-ID: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: > Howdy-ho. > > So, I'm working on a project which embeds Python into a bigger system to > provide extensibility. In this project, there's basically two types of > people who will be entering python code. > > The trusted folks, who write code which are in files, and which can do > anything. > > The untrusted folks, who are writing very simple chunks of code which > can only do limited things. I suggest that if the untrusted code is only supposed to be simple and limited, you would be best off to write your own "mini-language" using Python syntax. E.g. if the untrusted users are only going to write code that does (say) simple arithmetic, then why give them the ability to create closures, use generator expressions, connect to web servers, etc? You might think that it's a lot of work to write a mini-language, even with the tools in the standard library, and it is. But it will probably be less work than securing Python :) The fact is that Python is not designed to be used by untrusted users, and it is REALLY hard to keep it in a sandbox. There was an attempt to sandbox Python, if I recall correctly it was the bastion module, but it turned out to be so leaky that it was removed from the standard library with extreme prejudice. Since then, others have been working on it, including Google, but I don't know how successful they've been. Here's an example... suppose you wish to allow reading files, but not writing them. Sounds simple? http://tav.espians.com/a-challenge-to-break-python-security.html Now, I'm not suggesting that the exploits there are directly applicable to your sandbox, but they give a small idea of the sorts of things you need to consider. -- Steven From ben+python at benfinney.id.au Fri Aug 13 23:04:34 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 14 Aug 2010 13:04:34 +1000 Subject: Help to convert Number to String References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> <4c65ec05$0$28668$c3e8da3@news.astraweb.com> <5ded0e17-e240-4aee-9c60-d4d20f98c1ad@x21g2000yqa.googlegroups.com> Message-ID: <87r5i1uc71.fsf@benfinney.id.au> Vamsi writes: > fileopen = open('C:/MPython/test.txt', 'r') > str = fileopen.read() The above statement clobbers the existing binding of ?str? to the built-in string type. From that point on, the built-in string type is no longer accessible by the name ?str?; that name accesses a different object. Choose a better name for the return value; make it describe what the value is for in the context of the program. in_file = open('C:/MPython/test.txt', 'r') in_file_content = in_file.read() print in_file_content in_file.close() # ? It also has the advantage of making your code more readable, since the names help indicate *why* the code is written the way it is. -- \ ?Creativity can be a social contribution, but only in so far as | `\ society is free to use the results.? ?Richard Stallman | _o__) | Ben Finney From zyzhu2000 at gmail.com Sat Aug 14 00:00:01 2010 From: zyzhu2000 at gmail.com (GZ) Date: Fri, 13 Aug 2010 21:00:01 -0700 (PDT) Subject: minidom help -- line number Message-ID: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> Hi All, I am writing a little program that reads the minidom tree built from an xml file. I would like to print out the line number of the xml file on the parts of the tree that are not valid. But I do not seem to find a way to correspond minidom nodes to line numbers. Can anyone give me some help? Thanks, gz From perica.zivkovic at gmail.com Sat Aug 14 03:35:39 2010 From: perica.zivkovic at gmail.com (Perica Zivkovic) Date: Sat, 14 Aug 2010 00:35:39 -0700 (PDT) Subject: how to make portable distribution of python 2.6? References: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> <21480f31-c156-408a-a354-70debaa2dedc@l6g2000yqb.googlegroups.com> Message-ID: Hi there, numpy, matplotlib are already parts of Portable Python, PyQt is coming in one of the next versions. Creating it is not so difficult, it is basically repackaging of the python core and the required modules. Tricky part is keeping it portable as big part of libs is storing their configuration settings all over the place or require python env. variables. Drop me an email an maybe I can help you by including modules you need in next release of Portable Python. I'm already helping several universities, maybe we can work together to create one distribution which targets computer classes (together with tutorials, documentation, how-to guides etc.) keep pythoning ! Perica Zivkovic On Aug 13, 8:23?pm, zaur wrote: > On 13 ???, 21:28, Thomas Jollans wrote: > > > > > > > On 2010-08-13 19:00, zaur wrote:> All greetings! > > > > How to make portable distribution of python 2.6? > > > I don't know, but what you're looking for probably already exists. > > > Do you mean "portable" as in portable, i.e. "take this and build it for > > your system, it should work if your OS is supported"? Then you can get > > source tarballs from python.org > > >http://python.org/download/ > > > Or do you understand "portable" the way that is fashionable in the > > Windows world nowadays for some reason, i.e. "look, Ma, already > > installed if you happen to use Microsoft Windows of roughly the right > > version!" > > > Then http://www.portablepython.com/ is exactly where Google would have > > lead you had you searched. > > I want to realize howto build my own portable python in order to use > them without installation. > I want also to be able install modules (numpy, matplotlib, pyqt, > etc...) when it is necessary. > This very usefull for teaching python in computer classes. From thomas at jollybox.de Sat Aug 14 05:27:58 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 14 Aug 2010 11:27:58 +0200 Subject: writing \feff at the begining of a file In-Reply-To: <4c65f752$0$28668$c3e8da3@news.astraweb.com> References: <4C651438.50203@sequans.com> <4c65f752$0$28668$c3e8da3@news.astraweb.com> Message-ID: <201008141127.59165.thomas@jollybox.de> On Saturday 14 August 2010, it occurred to Steven D'Aprano to exclaim: > On Fri, 13 Aug 2010 18:25:46 -0400, Terry Reedy wrote: > > A short background to MRAB's answer which I will try to get right. > > > > The byte-order-mark was invented for UTF-16 encodings so the reader > > could determine whether the pairs of bytes are in little or big endiean > > order, depending on whether the first two bute are fe and ff or ff and > > fe (or maybe vice versa, does not matter here). The concept is > > meaningless for utf-8 which consists only of bytes in a defined order. > > This is part of the Unicode standard. > > > > However, Microsoft (or whoever) re-purposed (hijacked) that pair of > > bytes to serve as a non-standard indicator of utf-8 versus any > > non-unicode encoding. The result is a corrupted utf-8 stream that python > > accommodates with the utf-8-sig(nature) codec (versus the standard utf-8 > > codec). > > Is there a standard way to autodetect the encoding of a text file? I do > this: No, there is no way to autodetect the encoding of a text file. > Open the file in binary mode; if the first three bytes are > codecs.BOM_UTF8, then it's a Microsoft UTF-8 text file; otherwise if the > first two byes are codecs.BOM_BE or codecs.BOM_LE, the encoding is utf-16- > be or utf-16-le respectively. Unless the file happens to be UCS-2/UTF-16, or it happens to be a UTF-8 with garbage at the top. > If there's no BOM, then re-open the file and read the first two lines. If > either of them match this regex 'coding[=:]\s*([-\w.]+)' then I take the > encoding name from that. This matches Python's behaviour, and supports > EMACS and vi encoding declarations. This is a completely different method, and probably the most common in real usage: 1. Assume the file is ASCII (or some similar code page), but be liberal about characters you don't recognize 2. Know the file format you're reading. 3. Switch encoding once you have reached an indication of which exact character set to use. For Python, use the coding cookie if it's there For XML, read the declaration. For HTML, look for a tag, or just guess If no encoding is specified in a way you recognize, then you're out of luck. You'd usually just guess. (better still, you'd know what encoding you're dealing with in the first place, but that's too much to ask, I suppose...) You can try to take an educated guess by cross-referencing character frequencies with tables for known encoding/language combinations. I think this is what Microsoft IE does when it encounters a web page of unspecified encoding. From martin at v.loewis.de Sat Aug 14 07:36:45 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 14 Aug 2010 13:36:45 +0200 Subject: writing \feff at the begining of a file In-Reply-To: <4c65f752$0$28668$c3e8da3@news.astraweb.com> References: <4C651438.50203@sequans.com> <4c65f752$0$28668$c3e8da3@news.astraweb.com> Message-ID: <4C667FCD.6040802@v.loewis.de> > Is there a standard way to autodetect the encoding of a text file? Use the chardet module: http://chardet.feedparser.org/ Regards, Martin From gslindstrom at gmail.com Sat Aug 14 08:29:33 2010 From: gslindstrom at gmail.com (gslindstrom) Date: Sat, 14 Aug 2010 05:29:33 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: On Aug 12, 4:33?am, Paul Rubin wrote: > Baba writes: > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > > 20 packs, write an exhaustive search to find the largest number of > > McNuggets that cannot be bought in exact quantity. > > Is that a homework problem? ?Hint: first convince yourself that a > largest number actually exists. If I recall, this was a "puzzler" on the NPR radio show "Car Talk". Still might be homework, though. From raoulbia at gmail.com Sat Aug 14 10:52:26 2010 From: raoulbia at gmail.com (Baba) Date: Sat, 14 Aug 2010 07:52:26 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> Message-ID: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> On Aug 13, 8:25?pm, Ian Kelly wrote: > It's not. ?You're not just trying to find the sixth value that can be > bought in exact quantity, but a sequence of six values that can all be > bought in exact quantity. ?The integers [6, 9, 12, 15, 18, 20] are not > sequential. Hi Ian, Thanks for stating the obvious. I obviously hadn't understood a fundamental part of the theorem which states that 6 SEQUENTIAL passes must be found! That's a good lesson learned and will help me in future exercises to make sure i understand the theory first. Thanks again! Ok so with your and News123's help (no offence to all others but i need to keep it simple at this stage)i was able to find the solution: 43 my code is probably not elegant but a huge step forward from where i started: def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return [a,b,c] return [] for n_nuggets in range(50): result1 = can_buy(n_nuggets) result2 = can_buy(n_nuggets+1) result3 = can_buy(n_nuggets+2) result4 = can_buy(n_nuggets+3) result5 = can_buy(n_nuggets+4) result6 = can_buy(n_nuggets+5) if result1!=[] and result2!=[] and result3!=[] and result4!=[] and result5!=[] and result6!=[]: if (n_nuggets+5)-n_nuggets==5: print n_nuggets-1 break i suppose this can be tweaked to make it shorter? For instance i wonder if i can do the same with less variable to be defined? tnx Baba From frederick.williams2 at tesco.net Sat Aug 14 11:24:30 2010 From: frederick.williams2 at tesco.net (Frederick Williams) Date: Sat, 14 Aug 2010 16:24:30 +0100 Subject: print v. print() Message-ID: <4C66B52E.3B49EC1@tesco.net> I am learning Python from Hammond & Robinson's _Python Programming on Win32_, January 2000 edition. This print "Sleeping for 10 seconds" which appears in some example code, fails to... um... Compile? Interpret? Well, whatever the word is, it fails. Trial and error revealed that print("Sleeping for 10 seconds") does the trick. I am using version 3.1.2, presumably the book's authors used some earlier version. So why the change from print to print()? I should warn you that I know nothing about computers in general or Python in particular. -- I can't go on, I'll go on. From aahz at pythoncraft.com Sat Aug 14 11:28:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 14 Aug 2010 08:28:44 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Grant Edwards wrote: > >I also looked at Modula-3 once, and thought it had some real promise, >but I think it's probably deader than Ada now. That's because you should be using Oberon instead. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From thomas at jollybox.de Sat Aug 14 11:30:28 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 14 Aug 2010 17:30:28 +0200 Subject: print v. print() In-Reply-To: <4C66B52E.3B49EC1@tesco.net> References: <4C66B52E.3B49EC1@tesco.net> Message-ID: <201008141730.29535.thomas@jollybox.de> On Saturday 14 August 2010, it occurred to Frederick Williams to exclaim: > I am learning Python from Hammond & Robinson's _Python Programming on > Win32_, January 2000 edition. This > > print "Sleeping for 10 seconds" > > which appears in some example code, fails to... um... Compile? > Interpret? Well, whatever the word is, it fails. Trial and error > revealed that > > print("Sleeping for 10 seconds") > > does the trick. I am using version 3.1.2, presumably the book's authors > used some earlier version. Yes, indeed. Python 3.0 changed a number of things, the most visible is removing the print statement in favour of the print() function. > So why the change from print to print()? There's no reason for print to be a statement -- it can just as well be a function, which makes the language more regular, and therefore quite possibly easier to learn. > > I should warn you that I know nothing about computers in general or > Python in particular. From mwilson at the-wire.com Sat Aug 14 11:44:22 2010 From: mwilson at the-wire.com (Mel) Date: Sat, 14 Aug 2010 11:44:22 -0400 Subject: print v. print() References: <4C66B52E.3B49EC1@tesco.net> Message-ID: Thomas Jollans wrote: > On Saturday 14 August 2010, it occurred to Frederick Williams to exclaim: >> So why the change from print to print()? > There's no reason for print to be a statement -- it can just as well be a > function, which makes the language more regular, and therefore quite > possibly easier to learn. The downside to a print() function is that assigning to `print` can mask the function, and leave a neophyte without any way to get output out of the program. The problem with that downside, I guess, is that rogue assignment to sys.stdout can kill a print statement just as dead as a print() function, so the statement's so-called advantage is not that great. Mel. From mwilson at the-wire.com Sat Aug 14 11:49:28 2010 From: mwilson at the-wire.com (Mel) Date: Sat, 14 Aug 2010 15:49:28 +0000 (UTC) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: Baba wrote: > def can_buy(n_nuggets): > for a in range (0,n_nuggets): > for b in range (0,n_nuggets): > for c in range (0,n_nuggets): > #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > if 6*a+9*b+20*c==n_nuggets: > return [a,b,c] > return [] > > for n_nuggets in range(50): > result1 = can_buy(n_nuggets) > result2 = can_buy(n_nuggets+1) > result3 = can_buy(n_nuggets+2) > result4 = can_buy(n_nuggets+3) > result5 = can_buy(n_nuggets+4) > result6 = can_buy(n_nuggets+5) > if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > if (n_nuggets+5)-n_nuggets==5: > print n_nuggets-1 > break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? That can_buy function is a computational heavyweight -- very repetitive when called inside a loop. It could be cheaper to compute a list of quantities that can be purchased, then check to see what's in the list -- or the set, if you optimize a bit more. Mel. From juanknebel at gmail.com Sat Aug 14 12:19:59 2010 From: juanknebel at gmail.com (Juan Andres Knebel) Date: Sat, 14 Aug 2010 13:19:59 -0300 Subject: python ide for ubuntu In-Reply-To: <30CC6202-509E-4D09-9921-79A7B61C9351@gmail.com> References: <30CC6202-509E-4D09-9921-79A7B61C9351@gmail.com> Message-ID: Hi Bhanu, if you want to use QT try eric4 for python2 or eric5 for python3. Is very nice IDE, but if you want to develop only pure python use kate or similar or eclipse if you need a nice way to see the debug processes On Thu, Aug 12, 2010 at 7:44 AM, Roald de Vries wrote: > Hi Bhanu, > > > On Aug 12, 2010, at 4:15 AM, Bhanu Kumar wrote: > >> Hi All, >> >> Is there any good free python IDE available in Ubuntu? >> > > See a similar discussion at django-users mailing list: > > http://groups.google.com/group/django-users/browse_thread/thread/562189578285211 > > Cheers, Roald > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Juan Andres Knebel -------------- next part -------------- An HTML attachment was scrubbed... URL: From thudfoo at opensuse.us Sat Aug 14 12:40:29 2010 From: thudfoo at opensuse.us (member thudfoo) Date: Sat, 14 Aug 2010 09:40:29 -0700 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: On 8/14/10, Baba wrote: > On Aug 13, 8:25 pm, Ian Kelly wrote: > >> It's not. You're not just trying to find the sixth value that can be >> bought in exact quantity, but a sequence of six values that can all be >> bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not >> sequential. > > Hi Ian, > > Thanks for stating the obvious. I obviously hadn't understood a > fundamental part of the theorem which states that 6 SEQUENTIAL passes > must be found! That's a good lesson learned and will help me in future > exercises to make sure i understand the theory first. Thanks again! > > Ok so with your and News123's help (no offence to all others but i > need to keep it simple at this stage)i was able to find the solution: > 43 > > my code is probably not elegant but a huge step forward from where i > started: > > def can_buy(n_nuggets): > for a in range (0,n_nuggets): > for b in range (0,n_nuggets): > for c in range (0,n_nuggets): > #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > if 6*a+9*b+20*c==n_nuggets: > return [a,b,c] > return [] > > for n_nuggets in range(50): > result1 = can_buy(n_nuggets) > result2 = can_buy(n_nuggets+1) > result3 = can_buy(n_nuggets+2) > result4 = can_buy(n_nuggets+3) > result5 = can_buy(n_nuggets+4) > result6 = can_buy(n_nuggets+5) > if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > if (n_nuggets+5)-n_nuggets==5: > print n_nuggets-1 > break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? > > tnx > Baba > One tweak: def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return [a,b,c] return [] for n_nuggets in range(50): if (can_buy(n_nuggets) and can_buy(n_nuggets+1) and can_buy(n_nuggets+2) and can_buy(n_nuggets+3) and can_buy(n_nuggets+4) and can_buy(n_nuggets+5)): print n_nuggets - 1 break From ian.g.kelly at gmail.com Sat Aug 14 12:43:38 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 14 Aug 2010 10:43:38 -0600 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: On Sat, Aug 14, 2010 at 8:52 AM, Baba wrote: > my code is probably not elegant but a huge step forward from where i > started: > > def can_buy(n_nuggets): > ? for a in range (0,n_nuggets): > ? ? ? for b in range (0,n_nuggets): > ? ? ? ? ? for c in range (0,n_nuggets): > ? ? ? ? ? ? ? #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > ? ? ? ? ? ? ? if 6*a+9*b+20*c==n_nuggets: > ? ? ? ? ? ? ? ? ? return [a,b,c] > ? return [] > > for n_nuggets in range(50): > ? ?result1 = can_buy(n_nuggets) > ? ?result2 = can_buy(n_nuggets+1) > ? ?result3 = can_buy(n_nuggets+2) > ? ?result4 = can_buy(n_nuggets+3) > ? ?result5 = can_buy(n_nuggets+4) > ? ?result6 = can_buy(n_nuggets+5) > ? ?if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > ? ? if (n_nuggets+5)-n_nuggets==5: > ? ? ? ?print n_nuggets-1 > ? ? ? ?break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? Instead of calling can_buy() 6 times on every iteration of the main loop, I would suggest maintaining a list of the sequential results. Just call it once on each number of nuggets in order. If the number of nuggets is purchasable, and the list is empty or the last item in the list is the number of nuggets - 1, then append the number of nuggets to the list. If the last item in the list is not the number of nuggets - 1, then they're not sequential and you start a new list. When the length of the list reaches 6, you're done, and the answer is equal to the first item in the list - 1. You can also improve the can_buy() function by tightening up the loop limits. You don't need to go all the way up to n_nuggets on each loop. From python at mrabarnett.plus.com Sat Aug 14 12:44:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 14 Aug 2010 17:44:15 +0100 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: <4C66C7DF.1010900@mrabarnett.plus.com> Baba wrote: > On Aug 13, 8:25 pm, Ian Kelly wrote: > >> It's not. You're not just trying to find the sixth value that can be >> bought in exact quantity, but a sequence of six values that can all be >> bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not >> sequential. > > Hi Ian, > > Thanks for stating the obvious. I obviously hadn't understood a > fundamental part of the theorem which states that 6 SEQUENTIAL passes > must be found! That's a good lesson learned and will help me in future > exercises to make sure i understand the theory first. Thanks again! > > Ok so with your and News123's help (no offence to all others but i > need to keep it simple at this stage)i was able to find the solution: > 43 > > my code is probably not elegant but a huge step forward from where i > started: > > def can_buy(n_nuggets): > for a in range (0,n_nuggets): > for b in range (0,n_nuggets): > for c in range (0,n_nuggets): > #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > if 6*a+9*b+20*c==n_nuggets: > return [a,b,c] > return [] > > for n_nuggets in range(50): > result1 = can_buy(n_nuggets) > result2 = can_buy(n_nuggets+1) > result3 = can_buy(n_nuggets+2) > result4 = can_buy(n_nuggets+3) > result5 = can_buy(n_nuggets+4) > result6 = can_buy(n_nuggets+5) > if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > if (n_nuggets+5)-n_nuggets==5: > print n_nuggets-1 > break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? > Increase the number of nuggets one by one and keep a count of the number of consecutive successes. If you can buy a number of nuggets exactly, increment the count, otherwise reset the count. When the count reaches 6 you know that you're at the end of a sequence of consecutive successes. From bhanu.ramappa at gmail.com Sat Aug 14 12:56:21 2010 From: bhanu.ramappa at gmail.com (Bhanu Kumar) Date: Sat, 14 Aug 2010 22:26:21 +0530 Subject: python ide for ubuntu In-Reply-To: References: <30CC6202-509E-4D09-9921-79A7B61C9351@gmail.com> Message-ID: Thanks!! On Sat, Aug 14, 2010 at 9:49 PM, Juan Andres Knebel wrote: > Hi Bhanu, > if you want to use QT try eric4 for python2 or eric5 for python3. Is very > nice IDE, but if you want to develop only pure python use kate or similar or > eclipse if you need a nice way to see the debug processes > > > On Thu, Aug 12, 2010 at 7:44 AM, Roald de Vries wrote: > >> Hi Bhanu, >> >> >> On Aug 12, 2010, at 4:15 AM, Bhanu Kumar wrote: >> >>> Hi All, >>> >>> Is there any good free python IDE available in Ubuntu? >>> >> >> See a similar discussion at django-users mailing list: >> >> http://groups.google.com/group/django-users/browse_thread/thread/562189578285211 >> >> Cheers, Roald >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > Juan Andres Knebel > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollybox.de Sat Aug 14 13:07:49 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 14 Aug 2010 19:07:49 +0200 Subject: minidom help -- line number In-Reply-To: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> References: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> Message-ID: <201008141907.49646.thomas@jollybox.de> On Saturday 14 August 2010, it occurred to GZ to exclaim: > Hi All, > > I am writing a little program that reads the minidom tree built from > an xml file. I would like to print out the line number of the xml file > on the parts of the tree that are not valid. But I do not seem to find > a way to correspond minidom nodes to line numbers. The DOM does not contain things like line number information. You work with the structure of the document, not the appearance of the file you happen to be using as a source. You can't use line numbers with minidom. For stream-based parsers like SAX and eXpat (both in the standard library) this makes more sense, and they both allow you to check the current line number in one way or another. From python at rcn.com Sat Aug 14 13:14:14 2010 From: python at rcn.com (Raymond Hettinger) Date: Sat, 14 Aug 2010 10:14:14 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> Message-ID: On Aug 12, 1:20?pm, Paddy wrote: > I find myself needing to calculate the difference between two Counters > or multisets or bags. > > I want those items that are unique to each bag. Tell us about your use cases. I'm curious how a program would ascribe semantic meaning to the result. The phrase "unique to each bag" doesn't quite cover it, perhaps something like "number in either source above the minimum held in common". AFAICT, I've never needed something like this as a primitive. Even the xor operation for regular sets is rarely used. > I know how to > calculate it: > > ? ? >>> b = Counter(a=1, b=2) > ? ? >>> c = Counter(a=3, b=1) > ? ? >>> diff = (b - c) + (c - b) > >>> diff > Counter({'a': 2, 'b': 1}) That seems simple enough. You could also use: diff = (b | c) - (b & c) # max(b,c) - min(b,c) Raymond From jjposner at optimum.net Sat Aug 14 13:27:53 2010 From: jjposner at optimum.net (John Posner) Date: Sat, 14 Aug 2010 13:27:53 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: <4C66D219.4040407@optimum.net> On 8/14/2010 10:52 AM, Baba wrote: > > for n_nuggets in range(50): > result1 = can_buy(n_nuggets) > result2 = can_buy(n_nuggets+1) > result3 = can_buy(n_nuggets+2) > result4 = can_buy(n_nuggets+3) > result5 = can_buy(n_nuggets+4) > result6 = can_buy(n_nuggets+5) > if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > if (n_nuggets+5)-n_nuggets==5: > print n_nuggets-1 > break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? [Other responders have covered a lots of the points I make below. I guess I need to be quicker!] First, congratulations on getting to a solution! Code can very often be made shorter, although it's not always worth your while to do so. And often, shorter code is less understandable code -- which makes a big difference if you need to revisit the code later on. Here are some things that can be done with your for-loop: 1. You don't need this "if" test, because it's always true: if (n_nuggets+5)-n_nuggets==5: 2. Whenever you find yourself inventing a series of variables like "result1", "result2", "result3", etc., think about using a list instead. results = [] for i in range(6): results.append(can_buy(n_nuggets + i)) And to get really fancy, you can use a single "list comprehension" statement to do it all results = [can_buy(n_nuggets + i) for i in range(6)] 3. Your "if" statement tests whether all the lists are non-empty. In Python, expressions (a) and (b) are equivalent: (a) if result[0] != [] (b) if result[0] So your "if" test can be expressed as: if (result[0] and result[1] and result[2] and result[3] and result[4] and result[5]) (The parentheses are not required by "if", but they *do* enable you to split the expression across two or more lines.) And you can use the "all" function to rescue this cumbersome statement; if all(results) After all this work, the code is getting pretty short: for n_nuggets in range(50): results = [can_buy(n_nuggets + i) for i in range(6)] if all(results): print n_nuggets-1 break 4. The variable "results" is defined in one statement, and then is used just once, in the very next statement. There's no harm in that, and I think it makes the mode easier to understand, but you can get rid of it: for n_nuggets in range(50): if all([can_buy(n_nuggets + i) for i in range(6)]): print n_nuggets-1 break But wait, there's more ... :-) So far, we've just refined the *implementation* of your algorithm. But the algorithm itself could use some work. * When n_nuggets==0, we compute can_buy(0), can_buy(1), can_buy(2), can_buy(3), can_buy(4), and can_buy(5). * When n_nuggets==1, we compute can_buy(1), can_buy(2), can_buy(3), can_buy(4), can_buy(5), and can_buy(6). ... and so on. We can use an algorithm in which can_buy(i) is computed just once for each value of i: can_buy_count = 0 n_nuggets = 0 while n_nuggets < 50: if can_buy(n_nuggets): can_buy_count += 1 else: can_buy_count = 0 if can_buy_count == 6: print n_nuggets - 6 break else: n_nuggets += 1 And here's how you could shorten *this* code: ### cbc = "can buy count" cbc = 0 n_nuggets = -1 while n_nuggets < 50: n_nuggets += 1 cbc = cbc+1 if can_buy(n_nuggets) else 0 if cbc == 6: print n_nuggets - 6 break HTH, John From zyzhu2000 at gmail.com Sat Aug 14 13:40:13 2010 From: zyzhu2000 at gmail.com (GZ) Date: Sat, 14 Aug 2010 10:40:13 -0700 (PDT) Subject: minidom help -- line number References: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> Message-ID: <7231eedc-59e5-4275-bb87-e493ebfe1e00@i13g2000yqd.googlegroups.com> On Aug 14, 12:07?pm, Thomas Jollans wrote: > On Saturday 14 August 2010, it occurred to GZ to exclaim: > > > Hi All, > > > I am writing a little program that reads the minidom tree built from > > an xml file. I would like to print out the line number of the xml file > > on the parts of the tree that are not valid. But I do not seem to find > > a way to correspond minidom nodes to line numbers. > > The DOM does not contain things like line number information. You work with > the structure of the document, not the appearance of the file you happen to be > using as a source. You can't use line numbers with minidom. > > For stream-based parsers like SAX and eXpat (both in the standard library) > this makes more sense, and they both allow you to check the current line > number in one way or another. So I am basically out of luck if I want to tie back to the original file for file error reporting etc. sounds like a deficiency to me. From thomas at jollybox.de Sat Aug 14 13:56:45 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 14 Aug 2010 19:56:45 +0200 Subject: minidom help -- line number In-Reply-To: <7231eedc-59e5-4275-bb87-e493ebfe1e00@i13g2000yqd.googlegroups.com> References: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> <7231eedc-59e5-4275-bb87-e493ebfe1e00@i13g2000yqd.googlegroups.com> Message-ID: <201008141956.45918.thomas@jollybox.de> On Saturday 14 August 2010, it occurred to GZ to exclaim: > On Aug 14, 12:07 pm, Thomas Jollans wrote: > > On Saturday 14 August 2010, it occurred to GZ to exclaim: > > > Hi All, > > > > > > I am writing a little program that reads the minidom tree built from > > > an xml file. I would like to print out the line number of the xml file > > > on the parts of the tree that are not valid. But I do not seem to find > > > a way to correspond minidom nodes to line numbers. > > > > The DOM does not contain things like line number information. You work > > with the structure of the document, not the appearance of the file you > > happen to be using as a source. You can't use line numbers with minidom. > > > > For stream-based parsers like SAX and eXpat (both in the standard > > library) this makes more sense, and they both allow you to check the > > current line number in one way or another. > > So I am basically out of luck if I want to tie back to the original > file for file error reporting etc. sounds like a deficiency to me. The DOM is disjunct from the original file, stream, string, etc. That's in the nature of the DOM, and it's probably true for most, if not all, DOM implementations, in other programming languages as well as Python. If you want to stay close to the file, you're better of with SAX. (or a similar approach, like eXpat) From ian.g.kelly at gmail.com Sat Aug 14 14:11:56 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 14 Aug 2010 12:11:56 -0600 Subject: minidom help -- line number In-Reply-To: <201008141956.45918.thomas@jollybox.de> References: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> <7231eedc-59e5-4275-bb87-e493ebfe1e00@i13g2000yqd.googlegroups.com> <201008141956.45918.thomas@jollybox.de> Message-ID: On Sat, Aug 14, 2010 at 11:56 AM, Thomas Jollans wrote: > The DOM is disjunct from the original file, stream, string, etc. That's in the > nature of the DOM, and it's probably true for most, if not all, DOM > implementations, in other programming languages as well as Python. > If you want to stay close to the file, you're better of with SAX. (or a > similar approach, like eXpat) The minidom parse function can also accept any SAX2 parser, so it should be possible to create a customized parser that stashes the line numbers somewhere and use that together with minidom. I've never attempted this myself, so I won't be able to help with details. Cheers, Ian From pramo4d at gmail.com Sat Aug 14 14:18:50 2010 From: pramo4d at gmail.com (Pramod) Date: Sat, 14 Aug 2010 11:18:50 -0700 (PDT) Subject: problem in using linalg solver in numpy Message-ID: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> Hi Friends When run the below program in python i got error like this , Matrix [[ 8 -6 2] [-4 11 -7] [ 4 -7 6]] row vecotr X [[ 28 -40 33]] Traceback (most recent call last): File "solve.py", line 16, in print A*B File "/usr/lib/python2.6/dist-packages/numpy/core/defmatrix.py", line 290, in __mul__ return N.dot(self, asmatrix(other)) ValueError: objects are not aligned #!/usr/bin/python N=3 from numpy import linalg from numpy import matrix fr=open('mat.txt','r') A=matrix([[int(fr.readline()) for j in range(N)]for i in range(N)]) B=matrix([[int(fr.readline())for j in range(N)]]) print 'Matrix \n',A print 'row vecotr X\n',B #A=matrix([[3,4],[5,2]]) #B=matrix([[11],[9]]) print A*B #y=linalg.solve(A,B) #print 'Solution vectoris \n',y The input file is 8 -6 2 -4 11 -7 4 -7 6 28 -40 33 please try to fix the error in the program Thankx in advance From resourts85 at gmail.com Sat Aug 14 14:21:57 2010 From: resourts85 at gmail.com (iqbal iqbal) Date: Sat, 14 Aug 2010 11:21:57 -0700 (PDT) Subject: Chrome ore Sell Pakistani 30% - 52%, Message-ID: <6fea6efb-7b02-414c-84aa-620528849fe4@g6g2000pro.googlegroups.com> Chrome ore Sell Pakistani 30% - 52%, http://buy-sell-pakistani-minerals.blogspot.com From chare at labr.net Sat Aug 14 14:30:59 2010 From: chare at labr.net (Chris Hare) Date: Sat, 14 Aug 2010 13:30:59 -0500 Subject: Tk window and contents will not display Message-ID: <372B84B3-5563-4DD7-A679-95FD940F3AB5@labr.net> The scenario is this: I want to loop around all of the images in a given directory (which I know will be images, but I guess I should check), show an image in a window, wait 2 seconds and show the next one and repeat that indefinitley, which will be until the user closes the window. This is the code I extracted from the larger program and made work - sort of - in a standalone fashion. When I run the code, each of the file names gets displayed, and I can view the images, so it has to be something I am doing wrong with this chunk of code. However, I don't see what the problem is. from Tkinter import * import time import os import ImageTk import Image class externalLoopDisplay: def show(self): # # Create a frame # self.window = Tk() self.f = Frame(self.window, bg="Gray") self.f.grid() self.btnRefresh = Button(self.f, text="Close", command=self.window.destroy, bg="Gray",highlightbackground="Red", highlightcolor="Green") self.btnRefresh.grid(row=0, column=2) self.loopImage() def loopImage(self): dir = "Radar/net17" while 1: fileList = os.listdir(dir) number = len(fileList) c = 1 for gifFile in fileList: print "externalLoopDisplay.show:","top of for loop " + str(c) + " of " + str(number) print "externalLoopDisplay.show:","showing file " + dir + "/" + gifFile self.window.title("Image " + str(c) + " of " + str(number)) image = Image.open(dir + "/" + gifFile) canvasWidth, canvasHeight = image.size self.w = Canvas(self.f, width=canvasWidth, height=canvasHeight) photo = ImageTk.PhotoImage(image=image) netRadarImage = Label(self.w, image=photo) netRadarImage.image = photo self.w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) time.sleep(10) c = c + 1 self.w.destroy() loop=externalLoopDisplay() loop.show() From __peter__ at web.de Sat Aug 14 14:46:01 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Aug 2010 20:46:01 +0200 Subject: problem in using linalg solver in numpy References: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> Message-ID: Pramod wrote: > When run the below program in python i got error like this , > > > Matrix > [[ 8 -6 2] > [-4 11 -7] > [ 4 -7 6]] > row vecotr X > [[ 28 -40 33]] > Traceback (most recent call last): > File "solve.py", line 16, in > print A*B > File "/usr/lib/python2.6/dist-packages/numpy/core/defmatrix.py", > line 290, in __mul__ > return N.dot(self, asmatrix(other)) > ValueError: objects are not aligned > A=matrix([[int(fr.readline()) for j in range(N)]for i in range(N)]) > B=matrix([[int(fr.readline())for j in range(N)]]) > print A*B Row or column; I can't remember which is which either. Try again with B = matrix([[int(fr.readline())] for j in range(N)] or A*B.transpose() Peter From python at mrabarnett.plus.com Sat Aug 14 15:06:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 14 Aug 2010 20:06:25 +0100 Subject: problem in using linalg solver in numpy In-Reply-To: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> References: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> Message-ID: <4C66E931.4030201@mrabarnett.plus.com> Pramod wrote: > Hi Friends > > > When run the below program in python i got error like this , > > > Matrix > [[ 8 -6 2] > [-4 11 -7] > [ 4 -7 6]] > row vecotr X > [[ 28 -40 33]] > Traceback (most recent call last): > File "solve.py", line 16, in > print A*B > File "/usr/lib/python2.6/dist-packages/numpy/core/defmatrix.py", > line 290, in __mul__ > return N.dot(self, asmatrix(other)) > ValueError: objects are not aligned > [snip] If you're trying to multiply element-wise use the 'multiply' function. From iamforufriends at gmail.com Sat Aug 14 15:31:54 2010 From: iamforufriends at gmail.com (UR DREEM GIRL) Date: Sat, 14 Aug 2010 12:31:54 -0700 (PDT) Subject: want to see Babe with huge boobs hard sex Message-ID: want to see Babe with huge boobs hard sex http://hotttubs.blogspot.com/ http://hotttubs.blogspot.com/ http://hotttubs.blogspot.com/ http://hotttubs.blogspot.com/ From me+list/python at ixokai.io Sat Aug 14 15:56:45 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 12:56:45 -0700 Subject: Simple Python Sandbox In-Reply-To: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> Message-ID: <4C66F4FD.1010102@ixokai.io> On 8/13/10 8:04 PM, Steven D'Aprano wrote: > On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: > >> Howdy-ho. >> >> So, I'm working on a project which embeds Python into a bigger system to >> provide extensibility. In this project, there's basically two types of >> people who will be entering python code. >> >> The trusted folks, who write code which are in files, and which can do >> anything. >> >> The untrusted folks, who are writing very simple chunks of code which >> can only do limited things. > > I suggest that if the untrusted code is only supposed to be simple and > limited, you would be best off to write your own "mini-language" using > Python syntax. I considered it and rejected it. The return from the effort required doesn't even vaguely come close to making it worth it. My worst case fall-back plan is to embed /another/ language (be it Lua or JavaScript through V8) and offer it a very limited environment. But I don't want to do that (and considering I solved the while True: pass problem last night, I'm pretty sure I won't decide to). > The fact is that Python is not designed to be used by untrusted users, > and it is REALLY hard to keep it in a sandbox. There was an attempt to > sandbox Python, if I recall correctly it was the bastion module, but it > turned out to be so leaky that it was removed from the standard library > with extreme prejudice. Since then, others have been working on it, > including Google, but I don't know how successful they've been. I know all this -- but its not relevant really, I think. I'm not trying to create a safe yet relatively complete or functional Python. All those efforts to sandbox Python fail because of the incredible dynamic nature of the language has lots of enticing little holes in it. But I'm not interested in a full or even vaguely full subset of Python, and I'm not requiring that this security be done on the code-level. For example, when you go to save your bit of code, it will go in and if it finds __ anywhere in the text it just replaces it with xx. And, since getattr is not available, '_' + '_' won't get you anywhere. > Here's an example... suppose you wish to allow reading files, but not > writing them. Sounds simple? > > http://tav.espians.com/a-challenge-to-break-python-security.html Yeah, I'm aware of this little challenge-- but every one of those exploits calls for a special attribute call or method creation which is impossible(I think) in my setup. Although Paul Cannon's little exploit is very interesting, and I'm going to go brute force murder try/except in a similar way to __ above (in this context, exceptions aren't important) now. > Now, I'm not suggesting that the exploits there are directly applicable > to your sandbox, but they give a small idea of the sorts of things you > need to consider. I'm creating a much, much more restrictive subset of Python then most sandboxes try to do-- I could make my own custom mini-language, except good lord, that's a whole lot of work since there are real needs for *some* programming power here. Or I could embed another language in a more restrictive way then Python is embedded-- but good lord, now I have to handle three languages to get things done :) I just need a certain limited context where someone can be handed certain Python objects and manipulate them. I'd like people to be able to use some fundamental Python power -- the rich, beautiful data types for example (notably in this case, strings), list comprehensions and stuff, to do what they need to do. Python's very easy, I'd like them to be able to use that easy. But I don't need anywhere near full Python power, so sweeping rules like, 'no, you can't even type __' or, 'sorry, no exception handling for you', work well. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From __peter__ at web.de Sat Aug 14 16:14:22 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Aug 2010 22:14:22 +0200 Subject: Tk window and contents will not display References: Message-ID: Chris Hare wrote: > The scenario is this: > > I want to loop around all of the images in a given directory (which I know > will be images, but I guess I should check), show an image in a window, > wait 2 seconds and show the next one and repeat that indefinitley, which > will be until the user closes the window. > > This is the code I extracted from the larger program and made work - sort > of - in a standalone fashion. When I run the code, each of the file names > gets displayed, and I can view the images, so it has to be something I am > doing wrong with this chunk of code. > > However, I don't see what the problem is. I have not looked at your code in detail, but event loops and time.sleep() don't play together very well. Use after(delay_in_milliseconds, callable) instead. Here's a simple example that loops over images passed from the command line: import Image import ImageTk import os import sys import Tkinter as tk from itertools import cycle def next_image(): imagefile = next(imagefiles) image = Image.open(imagefile) w, h = image.size image = image.resize((700, 700*h//w)) label.image = label["image"] = ImageTk.PhotoImage(image=image) root.title("Now showing %s" % os.path.basename(imagefile)) root.after(2000, next_image) if __name__ == "__main__": imagefiles = sys.argv[1:] assert imagefiles imagefiles = cycle(imagefiles) root = tk.Tk() label = tk.Label(root) label.pack() root.after_idle(next_image) root.mainloop() From cs at zip.com.au Sat Aug 14 17:25:52 2010 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 15 Aug 2010 07:25:52 +1000 Subject: Simple Python Sandbox In-Reply-To: <4C66F4FD.1010102@ixokai.io> References: <4C66F4FD.1010102@ixokai.io> Message-ID: <20100814212552.GA30391@cskk.homeip.net> On 14Aug2010 12:56, Stephen Hansen wrote: | On 8/13/10 8:04 PM, Steven D'Aprano wrote: | > On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: | >> So, I'm working on a project which embeds Python into a bigger system to | >> provide extensibility. In this project, there's basically two types of | >> people who will be entering python code. | >> | >> The trusted folks, who write code which are in files, and which can do | >> anything. | >> | >> The untrusted folks, who are writing very simple chunks of code which | >> can only do limited things. | > | > I suggest that if the untrusted code is only supposed to be simple and | > limited, you would be best off to write your own "mini-language" using | > Python syntax. | | I considered it and rejected it. The return from the effort required | doesn't even vaguely come close to making it worth it. Ok, what about this: run the untrusted code in a separate process, if necessary running as a user with different privileges. Provide objects that need to be shared as some sort of proxy. Then your untrusted users can do whatever they like in python because they won't be presented with the inner parts of the privileged stuff. This is all rather vague because I don't know exactly what your untrusted users need to be able to do, nor how. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Computers in the future may weigh no more than 1.5 tons. --Popular Mechanics, forecasting the relentless march of science, 1949 From aahz at pythoncraft.com Sat Aug 14 17:46:33 2010 From: aahz at pythoncraft.com (Aahz) Date: 14 Aug 2010 14:46:33 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: In article <7xeieevrze.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >I'm not sure what the hiring issue is. I think anyone skilled in C++ or >Java can pick up Ada pretty easily. It's mostly a subset of C++ with >different surface syntax. Heck, I learned Ada as a sixteen-year-old knowing only BASIC and Pascal. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From debatem1 at gmail.com Sat Aug 14 17:57:46 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 14 Aug 2010 14:57:46 -0700 Subject: Simple Python Sandbox In-Reply-To: <4C66F4FD.1010102@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: On Sat, Aug 14, 2010 at 12:56 PM, Stephen Hansen wrote: > On 8/13/10 8:04 PM, Steven D'Aprano wrote: >> On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: >> >>> Howdy-ho. >>> >>> So, I'm working on a project which embeds Python into a bigger system to >>> provide extensibility. In this project, there's basically two types of >>> people who will be entering python code. >>> >>> The trusted folks, who write code which are in files, and which can do >>> anything. >>> >>> The untrusted folks, who are writing very simple chunks of code which >>> can only do limited things. >> >> I suggest that if the untrusted code is only supposed to be simple and >> limited, you would be best off to write your own "mini-language" using >> Python syntax. > > I considered it and rejected it. The return from the effort required > doesn't even vaguely come close to making it worth it. My worst case > fall-back plan is to embed /another/ language (be it Lua or JavaScript > through V8) and offer it a very limited environment. But I don't want to > do that (and considering I solved the while True: pass problem last > night, I'm pretty sure I won't decide to). > >> The fact is that Python is not designed to be used by untrusted users, >> and it is REALLY hard to keep it in a sandbox. There was an attempt to >> sandbox Python, if I recall correctly it was the bastion module, but it >> turned out to be so leaky that it was removed from the standard library >> with extreme prejudice. Since then, others have been working on it, >> including Google, but I don't know how successful they've been. > > I know all this -- but its not relevant really, I think. I'm not trying > to create a safe yet relatively complete or functional Python. All those > efforts to sandbox Python fail because of the incredible dynamic nature > of the language has lots of enticing little holes in it. But I'm not > interested in a full or even vaguely full subset of Python, and I'm not > requiring that this security be done on the code-level. > > For example, when you go to save your bit of code, it will go in and if > it finds __ anywhere in the text it just replaces it with xx. And, since > getattr is not available, '_' + '_' won't get you anywhere. > >> Here's an example... suppose you wish to allow reading files, but not >> writing them. Sounds simple? >> >> http://tav.espians.com/a-challenge-to-break-python-security.html > > Yeah, I'm aware of this little challenge-- but every one of those > exploits calls for a special attribute call or method creation which is > impossible(I think) in my setup. > > Although Paul Cannon's little exploit is very interesting, and I'm going > to go brute force murder try/except in a similar way to __ above (in > this context, exceptions aren't important) now. > >> Now, I'm not suggesting that the exploits there are directly applicable >> to your sandbox, but they give a small idea of the sorts of things you >> need to consider. > > I'm creating a much, much more restrictive subset of Python then most > sandboxes try to do-- I could make my own custom mini-language, except > good lord, that's a whole lot of work since there are real needs for > *some* programming power here. Or I could embed another language in a > more restrictive way then Python is embedded-- but good lord, now I have > to handle three languages to get things done :) > > I just need a certain limited context where someone can be handed > certain Python objects and manipulate them. I'd like people to be able > to use some fundamental Python power -- the rich, beautiful data types > for example (notably in this case, strings), list comprehensions and > stuff, to do what they need to do. Python's very easy, I'd like them to > be able to use that easy. > > But I don't need anywhere near full Python power, so sweeping rules > like, 'no, you can't even type __' or, 'sorry, no exception handling for > you', work well. I assume you're cutting out the import machinery? Geremy Condra From chare at labr.net Sat Aug 14 18:00:12 2010 From: chare at labr.net (Chris Hare) Date: Sat, 14 Aug 2010 17:00:12 -0500 Subject: Tk window and contents will not display In-Reply-To: References: Message-ID: On Aug 14, 2010, at 3:14 PM, Peter Otten wrote: > Chris Hare wrote: > >> The scenario is this: >> >> I want to loop around all of the images in a given directory (which I know >> will be images, but I guess I should check), show an image in a window, >> wait 2 seconds and show the next one and repeat that indefinitley, which >> will be until the user closes the window. >> >> This is the code I extracted from the larger program and made work - sort >> of - in a standalone fashion. When I run the code, each of the file names >> gets displayed, and I can view the images, so it has to be something I am >> doing wrong with this chunk of code. >> >> However, I don't see what the problem is. > > I have not looked at your code in detail, but event loops and time.sleep() > don't play together very well. Use after(delay_in_milliseconds, callable) > instead. > > Here's a simple example that loops over images passed from the command line: > > import Image > import ImageTk > import os > import sys > import Tkinter as tk > > from itertools import cycle > > def next_image(): > imagefile = next(imagefiles) > image = Image.open(imagefile) > > w, h = image.size > image = image.resize((700, 700*h//w)) > > label.image = label["image"] = ImageTk.PhotoImage(image=image) > root.title("Now showing %s" % os.path.basename(imagefile)) > > root.after(2000, next_image) > > if __name__ == "__main__": > imagefiles = sys.argv[1:] > assert imagefiles > imagefiles = cycle(imagefiles) > > root = tk.Tk() > label = tk.Label(root) > label.pack() > > root.after_idle(next_image) > root.mainloop() > Thanks Peter. I threw away what I started with and merged your code into my class: class externalLoopDisplay: def show(self): main.logging.debug("externalLoopDisplay.show:","start") self.window = Tk() self.btnClose = Button(self.window, text="Close", command=self.window.destroy, bg=backColor,highlightbackground=warnColor, highlightcolor=okColor) self.btnClose.grid(row=0, column=2) self.label = Label(self.window) self.label.grid(row=1, column=0, columnspan=3) dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. .../Radar/net17/net17-YYYYMMDDHHMMSS.gif self.imagefiles = glob.glob(dirName + "/*.gif") self.imagefiles = cycle(self.imagefiles) self.window.after_idle(self.next_image) def next_image(self): imagefile = next(self.imagefiles) image = Image.open(imagefile) w, h = image.size image = image.resize((600, 550*h//w)) self.label.image = self.label["image"] = ImageTk.PhotoImage(image=image) # <==== bails here self.window.title("Now showing %s" % os.path.basename(imagefile)) self.window.after(2000, next_image) I marked where the code bails with an error saying pyimage2 doesn't exist. All of the images exist and worked just fine with your standalone script. Suggestions? From __peter__ at web.de Sat Aug 14 18:49:45 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Aug 2010 00:49:45 +0200 Subject: Tk window and contents will not display References: Message-ID: Chris Hare wrote: > Thanks Peter. I threw away what I started with and merged your code into > my class: > > class externalLoopDisplay: > > def show(self): > main.logging.debug("externalLoopDisplay.show:","start") > > self.window = Tk() > > self.btnClose = Button(self.window, text="Close", > command=self.window.destroy, > bg=backColor,highlightbackground=warnColor, > highlightcolor=okColor) self.btnClose.grid(row=0, column=2) > self.label = Label(self.window) self.label.grid(row=1, column=0, > columnspan=3) > dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. > .../Radar/net17/net17-YYYYMMDDHHMMSS.gif > self.imagefiles = glob.glob(dirName + "/*.gif") > self.imagefiles = cycle(self.imagefiles) > self.window.after_idle(self.next_image) > > def next_image(self): > imagefile = next(self.imagefiles) > image = Image.open(imagefile) > > w, h = image.size > image = image.resize((600, 550*h//w)) > > self.label.image = self.label["image"] = > ImageTk.PhotoImage(image=image) # <==== bails here > self.window.title("Now showing %s" % os.path.basename(imagefile)) > > self.window.after(2000, next_image) > > > I marked where the code bails with an error saying pyimage2 doesn't exist. > All of the images exist and worked just fine with your standalone script. > > Suggestions? Google says you are calling Tkinter.Tk() more than once where you should instead use Tkinter.Toplevel(). As you didn't post that part of the code it's hard to verify, but when I add a second root = tk.Tk() to my example script I get a very similar exception: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 498, in callit func(*args) File "cycle_image.py", line 16, in next_image label.image = label["image"] = ImageTk.PhotoImage(image=image) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1212, in __setitem__ self.configure({key: value}) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1205, in configure return self._configure('configure', cnf, kw) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1196, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) TclError: image "pyimage1" doesn't exist By the way: for future posts please remember to cut and paste the traceback, don't paraphrase the error message. Peter From bob at mellowood.ca Sat Aug 14 19:05:05 2010 From: bob at mellowood.ca (bvdp) Date: Sat, 14 Aug 2010 16:05:05 -0700 (PDT) Subject: Pop return from stack? Message-ID: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Assuming I have a module 'foo.py' with something like this: def error(s): print "Error", s sys.exit(1) def func(s): ... do some processing ... call error() if bad .. go to system exit. ... more processing and then I write a new program, test.py, which: import foo def myerror(s): print "new error message" foo.error = myerror a = foo.func(..) Now, if an error is encountered myerror() is called. Fine. But execution resumes in func(). Not exactly what I wanted. I can "fix" this simply by wrapping the call to foo.func() in a try/ expect and have myerror() raise an exception. This appears to work, but I'm hesitant to use this out of fear that I'm building up some kind of stack overflow or something which will bite me later. Is there a better way? Simplest for an old assembler guy like me would be pop a return address off the stack ... but python isn't assembler :) I don't want to change stuff in the foo.py module since it's part of an existing program. But, if I must, I suppose I could. I'd prefer to just short-circuit this if possible. Thanks. From chare at labr.net Sat Aug 14 19:23:02 2010 From: chare at labr.net (Chris Hare) Date: Sat, 14 Aug 2010 18:23:02 -0500 Subject: Tk window and contents will not display In-Reply-To: References: Message-ID: On Aug 14, 2010, at 5:49 PM, Peter Otten wrote: > Chris Hare wrote: > >> Thanks Peter. I threw away what I started with and merged your code into >> my class: >> >> class externalLoopDisplay: >> >> def show(self): >> main.logging.debug("externalLoopDisplay.show:","start") >> >> self.window = Tk() >> >> self.btnClose = Button(self.window, text="Close", >> command=self.window.destroy, >> bg=backColor,highlightbackground=warnColor, >> highlightcolor=okColor) self.btnClose.grid(row=0, column=2) >> self.label = Label(self.window) self.label.grid(row=1, column=0, >> columnspan=3) >> dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. >> .../Radar/net17/net17-YYYYMMDDHHMMSS.gif >> self.imagefiles = glob.glob(dirName + "/*.gif") >> self.imagefiles = cycle(self.imagefiles) >> self.window.after_idle(self.next_image) >> >> def next_image(self): >> imagefile = next(self.imagefiles) >> image = Image.open(imagefile) >> >> w, h = image.size >> image = image.resize((600, 550*h//w)) >> >> self.label.image = self.label["image"] = >> ImageTk.PhotoImage(image=image) # <==== bails here >> self.window.title("Now showing %s" % os.path.basename(imagefile)) >> >> self.window.after(2000, next_image) >> >> >> I marked where the code bails with an error saying pyimage2 doesn't exist. >> All of the images exist and worked just fine with your standalone script. >> >> Suggestions? > > Google says you are calling Tkinter.Tk() more than once where you should > instead use Tkinter.Toplevel(). As you didn't post that part of the code > it's hard to verify, but when I add a second > > root = tk.Tk() > > to my example script I get a very similar exception: > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ > return self.func(*args) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 498, in callit > func(*args) > File "cycle_image.py", line 16, in next_image > label.image = label["image"] = ImageTk.PhotoImage(image=image) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1212, in __setitem__ > self.configure({key: value}) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1205, in configure > return self._configure('configure', cnf, kw) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1196, in _configure > self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) > TclError: image "pyimage1" doesn't exist > > By the way: for future posts please remember to cut and paste the traceback, > don't paraphrase the error message. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list Yes - you are bang on. Thanks. One final question if I may, how would you suggest I handle checking for new files and adding them to the list? For example, if the loop is playing and a new image is added, how can I detect it and then refresh the list of file? I am stuck on that part with this new approach. Chris From thomas at jollybox.de Sat Aug 14 19:23:11 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 15 Aug 2010 01:23:11 +0200 Subject: Pop return from stack? In-Reply-To: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: <201008150123.12038.thomas@jollybox.de> On Sunday 15 August 2010, it occurred to bvdp to exclaim: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > print "Error", s > sys.exit(1) > > def func(s): > ... do some processing > ... call error() if bad .. go to system exit. > ... more processing > > and then I write a new program, test.py, which: > > import foo > > def myerror(s): > print "new error message" > > foo.error = myerror > > a = foo.func(..) > > Now, if an error is encountered myerror() is called. Fine. But > execution resumes in func(). Not exactly what I wanted. > > I can "fix" this simply by wrapping the call to foo.func() in a try/ > expect and have myerror() raise an exception. This appears to work, > but I'm hesitant to use this out of fear that I'm building up some > kind of stack overflow or something which will bite me later. An exception will walk up the stack, calling any cleaning-up code that needs to be done (removing object references, executing finally: blocks, exiting context managers properly. It won't break anything. Don't be afraid of Python's high-level features! > > Is there a better way? Simplest for an old assembler guy like me would > be pop a return address off the stack ... but python isn't > assembler :) Now that has a decent chance of messing things up and you (if you wrote decent assembly ;-)) know it -- without properly cleaning up before resuming execution in the right place, you could end up in a right state with memory leaks, leaked file descriptors, half-arsed database transactions, etc etc. > > I don't want to change stuff in the foo.py module since it's part of > an existing program. But, if I must, I suppose I could. I'd prefer to > just short-circuit this if possible. Exceptions. Simple. In the end, all system.exit does is raise a SystemExit exception... - Thomas From r.koebler at yahoo.de Sat Aug 14 19:24:00 2010 From: r.koebler at yahoo.de (Roland Koebler) Date: Sun, 15 Aug 2010 01:24:00 +0200 Subject: Simple Python Sandbox In-Reply-To: <4C66F4FD.1010102@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: <20100814232400.GA5205@localhost> Hi, > I know all this -- but its not relevant really, I think. I'm not trying > to create a safe yet relatively complete or functional Python. All those > efforts to sandbox Python fail because of the incredible dynamic nature > of the language has lots of enticing little holes in it. But I'm not > interested in a full or even vaguely full subset of Python, and I'm not > requiring that this security be done on the code-level. I had the same problem, and so I created a "pseudo-sandbox" for embedding Python in templates. This "pseudo-sandbox" creates a restricted Python environment, where only whitelisted functions/classes are allowed. Additionally, it prevents things like '0 .__class__'. You can find some documentation at http://simple-is-better.org/template/pyratemp.html#evaluation, and the pseudo-sandbox itself in my template-engine, class "EvalPseudoSandbox" on the website above. (Please write me if you have any comments.) But note that this is not a real sandbox! As soon as you allow *any* unsafe function (e.g. open, import, eval, getattr etc.), you can easily break out. Also, don't directly pass complete modules to the pseudo-sandbox, since they may contain unsafe functions/classes/etc. And be warned: There *may* also be ways to break out of the pseudo-sandbox even without passing unsafe functions to it -- although I don't know any. If you know or find such a way: Please tell me! You could also take a look at Jinja (which is also a template-engine), and which claims to include a sandbox. But the Jinja-sandbox seems to be much more complicated than my pseudo-sandbox, and I haven't analyzed it and don't know how it works. > For example, when you go to save your bit of code, it will go in and if > it finds __ anywhere in the text it just replaces it with xx. And, since > getattr is not available, '_' + '_' won't get you anywhere. I don't think that searching the text is the right way; in my pseudo-sandbox, I compile the code and search co_names for such names instead. > I just need a certain limited context where someone can be handed > certain Python objects and manipulate them. I'd like people to be able > to use some fundamental Python power -- the rich, beautiful data types > for example (notably in this case, strings), list comprehensions and > stuff, to do what they need to do. Python's very easy, I'd like them to > be able to use that easy. I was in the exact same position ;). (Although I don't have fully untrusted/bad users, and so my pseudo-sandbox is sufficient for my cases, even though I haven't proved that it really is secure...) regards, Roland From jyoung79 at kc.rr.com Sat Aug 14 19:44:50 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Sat, 14 Aug 2010 23:44:50 +0000 Subject: Working with PDFs? Message-ID: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> Just curious if anyone knows if it's possible to work with pdf documents with Python? I'd like to do the following: - Pull out text from each PDF page (to search for specific words) - Combine separate pdf documents into one document - Add bookmarks (with destination settings) A few programs I've been looking at are pdfminer, pyPDF, etc from this link: http://pypi.python.org/pypi?%3Aaction=search&term=pdf&submit=search Originally, I was using AppleScript and JavaScript to do this in Acrobat. But now Acrobat 9 has broken this process and I can't seem to make it work. I'd like to find other workarounds instead of having to rely on Adobe. Thanks for your help. Jay From __peter__ at web.de Sat Aug 14 19:46:20 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Aug 2010 01:46:20 +0200 Subject: Tk window and contents will not display References: Message-ID: Chris Hare wrote: > > On Aug 14, 2010, at 5:49 PM, Peter Otten wrote: > >> Chris Hare wrote: >> >>> Thanks Peter. I threw away what I started with and merged your code >>> into my class: >>> >>> class externalLoopDisplay: >>> >>> def show(self): >>> main.logging.debug("externalLoopDisplay.show:","start") >>> >>> self.window = Tk() >>> >>> self.btnClose = Button(self.window, text="Close", >>> command=self.window.destroy, >>> bg=backColor,highlightbackground=warnColor, >>> highlightcolor=okColor) self.btnClose.grid(row=0, column=2) >>> self.label = Label(self.window) self.label.grid(row=1, column=0, >>> columnspan=3) >>> dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. >>> .../Radar/net17/net17-YYYYMMDDHHMMSS.gif > Thanks. One final question if I may, how would you suggest I handle > checking for new files and adding them to the list? For example, if the > loop is playing and a new image is added, how can I detect it and then > refresh the list of file? > > I am stuck on that part with this new approach. > > Chris Replacing >>> self.imagefiles = glob.glob(dirName + "/*.gif") >>> self.imagefiles = cycle(self.imagefiles) with self.imagefiles = image_cycler(os.path.join(dirname, "*.gif")) where image_cycler() looks as follows def image_cycler(pattern): while True: for fn in glob.glob(pattern): yield fn would be the simplest way. Peter From steve at REMOVE-THIS-cybersource.com.au Sat Aug 14 20:06:35 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 00:06:35 GMT Subject: Simple Python Sandbox References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: <4c672f8a$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 01:24:00 +0200, Roland Koebler wrote: > I had the same problem, and so I created a "pseudo-sandbox" for > embedding Python in templates. This "pseudo-sandbox" creates a > restricted Python environment, where only whitelisted functions/classes > are allowed. Additionally, it prevents things like '0 .__class__'. Hmmm... is that meant just as an illustration of a general technique, or do you actually have something against the class of 0? 0 .__class__ seems pretty innocuous to me: >>> type(0) is 0 .__class__ is int True [...] > But note that this is not a real sandbox! As soon as you allow *any* > unsafe function (e.g. open, import, eval, getattr etc.), you can easily > break out. Isn't that true of any sandbox though? Surely by definition, if you allow an unsafe function in any sandbox, it's no longer an effective sandbox. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 14 20:09:19 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 00:09:19 GMT Subject: Simple Python Sandbox References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> Message-ID: <4c67302f$0$11100$c3e8da3@news.astraweb.com> On Sat, 14 Aug 2010 12:56:45 -0700, Stephen Hansen wrote: >> I suggest that if the untrusted code is only supposed to be simple and >> limited, you would be best off to write your own "mini-language" using >> Python syntax. > > I considered it and rejected it. The return from the effort required > doesn't even vaguely come close to making it worth it. I suppose that depends on how simple the untrusted code will be, but I guess you're in the best position to make that call. > My worst case > fall-back plan is to embed /another/ language (be it Lua or JavaScript > through V8) and offer it a very limited environment. But I don't want to > do that (and considering I solved the while True: pass problem last > night, I'm pretty sure I won't decide to). I assume you mean you've solved the problem of DOS attacks from users running infinite loops. How did you do that? -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 14 20:11:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 00:11:11 GMT Subject: print v. print() References: <4C66B52E.3B49EC1@tesco.net> Message-ID: <4c67309f$0$11100$c3e8da3@news.astraweb.com> On Sat, 14 Aug 2010 11:44:22 -0400, Mel wrote: > The downside to a print() function is that assigning to `print` can mask > the function, and leave a neophyte without any way to get output out of > the program. On the other hand, the upside to a print() function is that assigning to `print` can monkey-patch the function, allowing the advanced user to modify it's functionality at runtime. Whether that's a feature or a shooting offence is a matter of opinion. (I think it's a feature, albeit one which is easy to misuse.) -- Steven From no.email at please.post Sat Aug 14 20:13:24 2010 From: no.email at please.post (kj) Date: Sun, 15 Aug 2010 00:13:24 +0000 (UTC) Subject: shelf-like list? References: Message-ID: In Raymond Hettinger writes: >On Aug 12, 1:37=A0pm, Thomas Jollans wrote: >> On Tuesday 10 August 2010, it occurred to kj to exclaim: >> >> > I'm looking for a module that implements "persistent lists": objects >> > that behave like lists except that all their elements are stored >> > on disk. =A0IOW, the equivalent of "shelves", but for lists rather >> > than a dictionaries. > . . . >> You could simply use pickle to save the data every once in a while. >That is a very reasonable solution. Sorry I don't follow. Some sample code would be helpful. TIA, ~K From python at mrabarnett.plus.com Sat Aug 14 20:18:37 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 15 Aug 2010 01:18:37 +0100 Subject: Working with PDFs? In-Reply-To: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> References: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> Message-ID: <4C67325D.8060706@mrabarnett.plus.com> jyoung79 at kc.rr.com wrote: > Just curious if anyone knows if it's possible to work with pdf documents > with Python? I'd like to do the following: > > - Pull out text from each PDF page (to search for specific words) > - Combine separate pdf documents into one document > - Add bookmarks (with destination settings) > > A few programs I've been looking at are pdfminer, pyPDF, etc from this > link: > http://pypi.python.org/pypi?%3Aaction=search&term=pdf&submit=search > > Originally, I was using AppleScript and JavaScript to do this in Acrobat. > But now Acrobat 9 has broken this process and I can't seem to make it > work. I'd like to find other workarounds instead of having to rely on > Adobe. > Have you tried OpenOffice? From steve at REMOVE-THIS-cybersource.com.au Sat Aug 14 20:23:18 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 00:23:18 GMT Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: <4c673375$0$11100$c3e8da3@news.astraweb.com> On Sat, 14 Aug 2010 16:05:05 -0700, bvdp wrote: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > print "Error", s > sys.exit(1) > > def func(s): > ... do some processing > ... call error() if bad .. go to system exit. ... more processing > > and then I write a new program, test.py, which: > > import foo > > def myerror(s): > print "new error message" > > foo.error = myerror > > a = foo.func(..) This general technique is called "monkey patching". > Now, if an error is encountered myerror() is called. Fine. But execution > resumes in func(). Not exactly what I wanted. Of course it does. Your new error handler fails to exit, so execution resumes like it does after any other function. You can either manually exit from your own error handler: def myerror(s): print "new error message" sys.exit(2) or call the original error handler: def myerror(s): print "new error message" foo._error(s) That second technique requires some preparation before hand. In module foo, after defining the error() function, you then need to create a second, private, name to it: _error = error > I can "fix" this simply by wrapping the call to foo.func() in a try/ > expect and have myerror() raise an exception. This appears to work, but > I'm hesitant to use this out of fear that I'm building up some kind of > stack overflow or something which will bite me later. Exceptions are the standard way of doing things. That's what sys.exit() does -- it raises SystemExit exception. With very few exceptions, if you're writing your own error handlers like this, you're doing it wrong. Your error handler throws away useful debugging information, and it gives you no extra information that a standard Python traceback couldn't give. > Is there a better way? Simplest for an old assembler guy like me would > be pop a return address off the stack ... but python isn't assembler :) Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in Python, even VB in Python, but this is the first time I've meet some one who wants to write assembler in Python :) -- Steven From no.email at please.post Sat Aug 14 20:25:25 2010 From: no.email at please.post (kj) Date: Sun, 15 Aug 2010 00:25:25 +0000 (UTC) Subject: How to add silent stretches to MP3 using Python? Message-ID: Here's the problem: I have about 25,000 mp3 files, each lasting, *on average*, only a few seconds, though the variance is wide (the longest one lasts around 20 seconds). (These files correspond to sample sentences for foreign language training.) The problem is that there is basically no padding before and after the sound signal. I want to prepend about 2 seconds of silence to each file, and append another silent stretch at the end lasting either 2 seconds or some multiplier of the duration of the original file, whichever is greater. I know that manipulating MP3 audio programmatically is usually not easy, but this has got to be one of the simplest manipulations possible, so I'm hoping I'll be able to pull it off with Python. But I have not had much luck finding a Python library to do this. If someone knows how to do this, and could give me some pointers, I'd appreciate it. TIA! ~K From lists at cheimes.de Sat Aug 14 20:36:47 2010 From: lists at cheimes.de (Christian Heimes) Date: Sun, 15 Aug 2010 02:36:47 +0200 Subject: Simple Python Sandbox In-Reply-To: <4C66F4FD.1010102@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: > For example, when you go to save your bit of code, it will go in and if > it finds __ anywhere in the text it just replaces it with xx. And, since > getattr is not available, '_' + '_' won't get you anywhere. That's not as secure as you might think. First of all you can write "_" in more way than you may think. >>> 2*chr(0x5f) + "insecure" + 2*chr(0x5f) '__insecure__' >>> "\x5f\x5finsecure\x5f\x5f" '__insecure__' >>> str(u"\N{LOW LINE}\N{LOW LINE}insecure\N{LOW LINE}\N{LOW LINE}") '__insecure__' If you have access to eval, exec or compile you can easily work around your restrictions: >>> getattribute = eval("object.__getattribute__") >>> getattribute(int, "__new__")(int, "3") 3 As you can see, black listing isn't the best approach here. Christian From chare at labr.net Sat Aug 14 20:50:25 2010 From: chare at labr.net (Chris Hare) Date: Sat, 14 Aug 2010 19:50:25 -0500 Subject: Tk window and contents will not display In-Reply-To: References: Message-ID: <6DDC6BAF-EED6-452A-A2B9-00C2210049E6@labr.net> On Aug 14, 2010, at 6:46 PM, Peter Otten wrote: > Chris Hare wrote: > >> >> On Aug 14, 2010, at 5:49 PM, Peter Otten wrote: >> >>> Chris Hare wrote: >>> >>>> Thanks Peter. I threw away what I started with and merged your code >>>> into my class: >>>> >>>> class externalLoopDisplay: >>>> >>>> def show(self): >>>> main.logging.debug("externalLoopDisplay.show:","start") >>>> >>>> self.window = Tk() >>>> >>>> self.btnClose = Button(self.window, text="Close", >>>> command=self.window.destroy, >>>> bg=backColor,highlightbackground=warnColor, >>>> highlightcolor=okColor) self.btnClose.grid(row=0, column=2) >>>> self.label = Label(self.window) self.label.grid(row=1, column=0, >>>> columnspan=3) >>>> dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. >>>> .../Radar/net17/net17-YYYYMMDDHHMMSS.gif > >> Thanks. One final question if I may, how would you suggest I handle >> checking for new files and adding them to the list? For example, if the >> loop is playing and a new image is added, how can I detect it and then >> refresh the list of file? >> >> I am stuck on that part with this new approach. >> >> Chris > > Replacing > >>>> self.imagefiles = glob.glob(dirName + "/*.gif") >>>> self.imagefiles = cycle(self.imagefiles) > > with > > self.imagefiles = image_cycler(os.path.join(dirname, "*.gif")) > > where image_cycler() looks as follows > > def image_cycler(pattern): > while True: > for fn in glob.glob(pattern): > yield fn > > would be the simplest way. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list Perfect! Thank you From r.koebler at yahoo.de Sat Aug 14 20:51:28 2010 From: r.koebler at yahoo.de (Roland Koebler) Date: Sun, 15 Aug 2010 02:51:28 +0200 Subject: Simple Python Sandbox In-Reply-To: <4c672f8a$0$11100$c3e8da3@news.astraweb.com> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4c672f8a$0$11100$c3e8da3@news.astraweb.com> Message-ID: <20100815005128.GB5205@localhost> On Sun, Aug 15, 2010 at 12:06:35AM +0000, Steven D'Aprano wrote: > Hmmm... is that meant just as an illustration of a general technique, or > do you actually have something against the class of 0? It's a short illustration; 0 .__class__ itself is harmless, but e.g. 0 .__class__.__base__.__subclasses__() isn't. > > But note that this is not a real sandbox! As soon as you allow *any* > > unsafe function (e.g. open, import, eval, getattr etc.), you can easily > > break out. > > Isn't that true of any sandbox though? Surely by definition, if you allow > an unsafe function in any sandbox, it's no longer an effective sandbox. In my opinion, a "real" sandbox should allow to use "unsafe" functions (e.g. open(), import modules etc.) -- so you could run your normal code in it. But it should prevent the "bad" effects of the code, e.g. by redirecting I/O, limiting resources etc. regards, Roland From python.list at tim.thechases.com Sat Aug 14 20:57:54 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 14 Aug 2010 19:57:54 -0500 Subject: How to add silent stretches to MP3 using Python? In-Reply-To: References: Message-ID: <4C673B92.5090002@tim.thechases.com> > Here's the problem: I have about 25,000 mp3 files, each lasting, > *on average*, only a few seconds, though the variance is wide (the > longest one lasts around 20 seconds). (These files correspond to > sample sentences for foreign language training.) > > The problem is that there is basically no padding before and after > the sound signal. I want to prepend about 2 seconds of silence to > each file, and append another silent stretch at the end lasting > either 2 seconds or some multiplier of the duration of the original > file, whichever is greater. > > I know that manipulating MP3 audio programmatically is usually not > easy, but this has got to be one of the simplest manipulations > possible, so I'm hoping I'll be able to pull it off with Python. > > But I have not had much luck finding a Python library to do this. > If someone knows how to do this, and could give me some pointers, > I'd appreciate it. While it's (1) not 100% python and (2) doesn't allow for your "2 seconds...or some multiplier of the duration, whichever is greater", you can use mp3wrap[1] to losslessly join the files. If you happen to make a 2-seconds-of-silence MP3, you can then join your files together with the silence. For 25k files, you might have to stitch subsets of them together incrementally and then stitch together the resulting files. -tkc [1] http://mp3wrap.sourceforge.net/ or "apt-get install mp3wrap" here on my Debian box From pavlovevidence at gmail.com Sat Aug 14 22:26:09 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 14 Aug 2010 19:26:09 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: <88cb8d7f-efb6-4217-b65a-65e479fd4e5f@p22g2000pre.googlegroups.com> On Aug 14, 4:05?pm, bvdp wrote: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > ? ? print "Error", s > ? ? sys.exit(1) > > def func(s): > ? ? ... do some processing > ? ? ... call error() if bad .. go to system exit. > ? ? ... ?more processing > > and then I write a new program, test.py, which: > > import foo > > def myerror(s): > ? ? print "new error message" > > foo.error = myerror > > a = foo.func(..) > > Now, if an error is encountered myerror() is called. Fine. But > execution resumes in func(). Not exactly what I wanted. > > I can "fix" this simply by wrapping the call to foo.func() in a try/ > expect and have myerror() raise an exception. This appears to work, > but I'm hesitant to use this out of fear that I'm building up some > kind of stack overflow or something which will bite me later. What do you think a few words of data the stack are going to do? Just do it this way. Carl Banks From me+list/python at ixokai.io Sat Aug 14 22:43:13 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 19:43:13 -0700 Subject: Simple Python Sandbox In-Reply-To: <4c672f8a$0$11100$c3e8da3@news.astraweb.com> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4c672f8a$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4C675441.8090105@ixokai.io> On 8/14/10 5:06 PM, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 01:24:00 +0200, Roland Koebler wrote: > >> I had the same problem, and so I created a "pseudo-sandbox" for >> embedding Python in templates. This "pseudo-sandbox" creates a >> restricted Python environment, where only whitelisted functions/classes >> are allowed. Additionally, it prevents things like '0 .__class__'. > > Hmmm... is that meant just as an illustration of a general technique, or > do you actually have something against the class of 0? 0 .__class__ seems > pretty innocuous to me: > >>>> type(0) is 0 .__class__ is int > True Assuming you have a totally restricted environment, where none of the normal built-ins are available-- notably "type"-- in theory I thought once that you could exec pretty safely. Because there's just no access to anything! But, alas, someone showed me I was wrong. 0 .__class__ can lead you to "type". And type.__subclasses__ happily leads you to everything in the world. I solve this by just refusing to allow getattr, and __ anywhere in the file to be saved just gets turned into xx, so its impossible (I think) for users to access or use any special method. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From me+list/python at ixokai.io Sat Aug 14 22:48:14 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 19:48:14 -0700 Subject: Simple Python Sandbox In-Reply-To: <20100814212552.GA30391@cskk.homeip.net> References: <4C66F4FD.1010102@ixokai.io> <20100814212552.GA30391@cskk.homeip.net> Message-ID: <4C67556E.4080800@ixokai.io> On 8/14/10 2:25 PM, Cameron Simpson wrote: > Ok, what about this: run the untrusted code in a separate process, > if necessary running as a user with different privileges. Way too much overhead by a really significant margin: I need to do many, many, many, many, many very short (often very *very* short) little scripts. Doing IPC to separate processes, even if they're long-running, and handling proxying of my objects that these scripts need to read from and tweak in certain ways, would just kill performance. I really do need an embedded language -- and a very restricted subset of Python is really ideal for that, which is why I'm going for this. :) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From me+list/python at ixokai.io Sat Aug 14 22:54:11 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 19:54:11 -0700 Subject: Simple Python Sandbox In-Reply-To: <20100814232400.GA5205@localhost> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <20100814232400.GA5205@localhost> Message-ID: <4C6756D3.60205@ixokai.io> On 8/14/10 4:24 PM, Roland Koebler wrote: > You can find some documentation at > http://simple-is-better.org/template/pyratemp.html#evaluation, > and the pseudo-sandbox itself in my template-engine, class > "EvalPseudoSandbox" on the website above. > (Please write me if you have any comments.) How are you implementing refusing-names-beginning-with-underscore, out of curiosity? > You could also take a look at Jinja (which is also a template-engine), > and which claims to include a sandbox. But the Jinja-sandbox seems to > be much more complicated than my pseudo-sandbox, and I haven't analyzed > it and don't know how it works. I'll take a look. >> I just need a certain limited context where someone can be handed >> certain Python objects and manipulate them. I'd like people to be able >> to use some fundamental Python power -- the rich, beautiful data types >> for example (notably in this case, strings), list comprehensions and >> stuff, to do what they need to do. Python's very easy, I'd like them to >> be able to use that easy. > I was in the exact same position ;). > (Although I don't have fully untrusted/bad users, and so my pseudo-sandbox > is sufficient for my cases, even though I haven't proved that it really is > secure...) I don't *really* have a bunch fully untrusted / bad users, in fact I expect I will sort of trust all the people doing this level of coding -- but I believe that either incompetance and maliciousness is inevitable in any sort of online community, and making it at least as hard as possible to do damage while giving people as much freedom and tools to do great is the ideal goal. :) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From tjreedy at udel.edu Sat Aug 14 22:58:48 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Aug 2010 22:58:48 -0400 Subject: Working with PDFs? In-Reply-To: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> References: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> Message-ID: On 8/14/2010 7:44 PM, jyoung79 at kc.rr.com wrote: > Just curious if anyone knows if it's possible to work with pdf documents > with Python? I'd like to do the following: search python pdf library reportlab -- Terry Jan Reedy From me+list/python at ixokai.io Sat Aug 14 23:01:00 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 20:01:00 -0700 Subject: Simple Python Sandbox In-Reply-To: References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: <4C67586C.3020107@ixokai.io> On 8/14/10 5:36 PM, Christian Heimes wrote: >> For example, when you go to save your bit of code, it will go in and if >> it finds __ anywhere in the text it just replaces it with xx. And, since >> getattr is not available, '_' + '_' won't get you anywhere. > > That's not as secure as you might think. First of all you can write "_" > in more way than you may think. Well yes, I know-- but as I said in the original post, eval, exec, compile, getattr and such, are all unavailable. So its possible someone can write '_' in various ways (though I'm disallowing both chr and unichr for entirely different reasons), and they can even put them together so that there's a __ as a string in some variable, I can't find any way in which they would then be able to get to get a special method. Namely, type.__subclasses__ or object.__getattribute__. They can't enter any code which does blah.__class__, and they can't construct a string through twisty ways to then do getattr(blah, twisty) where twisty = "__class__". > If you have access to eval, exec or compile you can easily work around > your restrictions: I think its pretty much a given that if you're even trying to do some kind of restricted sandbox, eval and the like are the first things to go. :) > As you can see, black listing isn't the best approach here. But I have a two pronged strategy: the black list is only half of the equation. One, I'm blacklisting all the meta functions out of builtins. Eval, compile, getattr, and such. Then, I'm doing some blatant textual munging, making it so someone can not access any __special__ methods, or use exec. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From me+list/python at ixokai.io Sat Aug 14 23:07:37 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 20:07:37 -0700 Subject: Simple Python Sandbox In-Reply-To: <4c67302f$0$11100$c3e8da3@news.astraweb.com> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4c67302f$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4C6759F9.9040406@ixokai.io> On 8/14/10 5:09 PM, Steven D'Aprano wrote: >> My worst case >> fall-back plan is to embed /another/ language (be it Lua or JavaScript >> through V8) and offer it a very limited environment. But I don't want to >> do that (and considering I solved the while True: pass problem last >> night, I'm pretty sure I won't decide to). > > I assume you mean you've solved the problem of DOS attacks from users > running infinite loops. How did you do that? Since I only have to run this on Unix-isms, I'm using alarm()/signal(). The C code takes the hash of the source code that's going to be executed and marks it, then sets an alarm and executes the code (though its usually been compiled into a code object). There's no code which would -ever- in this situation take longer then 2 seconds to run (and that's extremely generous), but the alarm is 5: if the code doesn't return and cancel the alarm by then, I know the code is functionally broken. So, the signal handler records the hash of the code that failed -- it'll never be tried again -- logs an error message, and restarts the whole process (which happens seamlessly with virtually no user interruption, but this system is not architected in a way where its readily able to resume operation in the event of a signal interrupt). This isn't perfect: infinite loops it kills, but things like [0] * 10^^100 crash head first into the machine and bring it to a crawl. I haven't figured out a strategy for trying to address that yet, and ultimately, I may not find one. That's okay: perfection isn't my goal, infinite loops are easy enough to do on accident that halting them is important. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From clp2 at rebertia.com Sat Aug 14 23:08:17 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 14 Aug 2010 20:08:17 -0700 Subject: Pop return from stack? In-Reply-To: <4c673375$0$11100$c3e8da3@news.astraweb.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c673375$0$11100$c3e8da3@news.astraweb.com> Message-ID: On Sat, Aug 14, 2010 at 5:23 PM, Steven D'Aprano wrote: > Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in > Python, even VB in Python, but this is the first time I've meet some one > who wants to write assembler in Python :) +1 QOTW Cheers, Chris From debatem1 at gmail.com Sat Aug 14 23:11:48 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 14 Aug 2010 20:11:48 -0700 Subject: Simple Python Sandbox In-Reply-To: <4C6759F9.9040406@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4c67302f$0$11100$c3e8da3@news.astraweb.com> <4C6759F9.9040406@ixokai.io> Message-ID: On Sat, Aug 14, 2010 at 8:07 PM, Stephen Hansen wrote: > On 8/14/10 5:09 PM, Steven D'Aprano wrote: >>> My worst case >>> fall-back plan is to embed /another/ language (be it Lua or JavaScript >>> through V8) and offer it a very limited environment. But I don't want to >>> do that (and considering I solved the while True: pass problem last >>> night, I'm pretty sure I won't decide to). >> >> I assume you mean you've solved the problem of DOS attacks from users >> running infinite loops. How did you do that? > > Since I only have to run this on Unix-isms, I'm using alarm()/signal(). > The C code takes the hash of the source code that's going to be executed > and marks it, then sets an alarm and executes the code (though its > usually been compiled into a code object). > > There's no code which would -ever- in this situation take longer then 2 > seconds to run (and that's extremely generous), but the alarm is 5: if > the code doesn't return and cancel the alarm by then, I know the code is > functionally broken. > > So, the signal handler records the hash of the code that failed -- it'll > never be tried again -- logs an error message, and restarts the whole > process (which happens seamlessly with virtually no user interruption, > but this system is not architected in a way where its readily able to > resume operation in the event of a signal interrupt). > > This isn't perfect: infinite loops it kills, but things like [0] * > 10^^100 crash head first into the machine and bring it to a crawl. I > haven't figured out a strategy for trying to address that yet, and > ultimately, I may not find one. That's okay: perfection isn't my goal, > infinite loops are easy enough to do on accident that halting them is > important. cpulimit or a cgroups container can both be easy solutions here, depending on your exact needs. Geremy Condra From me+list/python at ixokai.io Sat Aug 14 23:18:14 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 20:18:14 -0700 Subject: Simple Python Sandbox In-Reply-To: References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4c67302f$0$11100$c3e8da3@news.astraweb.com> <4C6759F9.9040406@ixokai.io> Message-ID: <4C675C76.7080708@ixokai.io> On 8/14/10 8:11 PM, geremy condra wrote: > cpulimit or a cgroups container can both be easy solutions here, > depending on your exact needs. Hmm! I wasn't aware of those, I'll check that out. Thanks. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From debatem1 at gmail.com Sat Aug 14 23:30:18 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 14 Aug 2010 20:30:18 -0700 Subject: Simple Python Sandbox In-Reply-To: <4C675C76.7080708@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4c67302f$0$11100$c3e8da3@news.astraweb.com> <4C6759F9.9040406@ixokai.io> <4C675C76.7080708@ixokai.io> Message-ID: On Sat, Aug 14, 2010 at 8:18 PM, Stephen Hansen wrote: > On 8/14/10 8:11 PM, geremy condra wrote: >> cpulimit or a cgroups container can both be easy solutions here, >> depending on your exact needs. > > Hmm! I wasn't aware of those, I'll check that out. Thanks. Np. I wrote a set of cgroups bindings in Python a few years ago that I could probably lay my hands on if they'd help, although they may be out of date by now. Geremy Condra From ldo at geek-central.gen.new_zealand Sat Aug 14 23:45:51 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 15:45:51 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> <4C61E9A1.5090800@v.loewis.de> <88t9j7-ri5.ln1@satorlaser.homedns.org> <44d30ac7-931e-4eb0-9aed-f664c872d438@l20g2000yqm.googlegroups.com> Message-ID: In message <44d30ac7-931e-4eb0-9aed-f664c872d438 at l20g2000yqm.googlegroups.com>, sturlamolden wrote: > A C++ compiler can use Python's header files and link with Python's C API > correctly. But it cannot compile Python's C source code. A C compiler > is required to compile and build Python. Since when do you find a C++ compiler not accompanied by a C one? From bob at mellowood.ca Sun Aug 15 00:36:29 2010 From: bob at mellowood.ca (bvdp) Date: Sat, 14 Aug 2010 21:36:29 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: > An exception will walk up the stack, calling any cleaning-up code that needs > to be done (removing object references, executing finally: blocks, exiting > context managers properly. It won't break anything. Don't be afraid of > Python's high-level features! Okay, I believe you (and the rest of the gang. In my trivial program the exception in working ... so I'll leave it alone. Thanks. > - Thomas From bob at mellowood.ca Sun Aug 15 00:41:34 2010 From: bob at mellowood.ca (bvdp) Date: Sat, 14 Aug 2010 21:41:34 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c673375$0$11100$c3e8da3@news.astraweb.com> Message-ID: <6fa333b1-6474-407b-951a-452543e827bd@f6g2000pro.googlegroups.com> On Aug 14, 5:23?pm, Steven D'Aprano wrote: > This general technique is called "monkey patching". > New term for me :) > > Now, if an error is encountered myerror() is called. Fine. But execution > > resumes in func(). Not exactly what I wanted. > > Of course it does. Your new error handler fails to exit, so execution > resumes like it does after any other function. I guess I wasn't being clear. I don't want to exit in my new bit of code. Just continue a loop (which I didn't show in the example). > Exceptions are the standard way of doing things. That's what sys.exit() > does -- it raises SystemExit exception. Okay, didn't know that exit() was really an exception. Good to know. But, like I said, I'm not looking to exit. > > With very few exceptions, if you're writing your own error handlers like > this, you're doing it wrong. Your error handler throws away useful > debugging information, and it gives you no extra information that a > standard Python traceback couldn't give. Yeah, but I really don't want a traceback printed out for a user just because a file can't be found, or he's got a bad bit of syntax in his file. So, that's why I have the specific error routine. Works fine in the main program. > Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in > Python, even VB in Python, but this is the first time I've meet some one > who wants to write assembler in Python :) Naw, I had my fun with assembler in the good old days. Never want to write another line of it :) From invalid at invalid.invalid Sun Aug 15 00:58:40 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 15 Aug 2010 04:58:40 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-14, Aahz wrote: > Paul Rubin wrote: >> >>I'm not sure what the hiring issue is. I think anyone skilled in C++ or >>Java can pick up Ada pretty easily. It's mostly a subset of C++ with >>different surface syntax. > > Heck, I learned Ada as a sixteen-year-old knowing only BASIC and Pascal. Unfortunately, there just aren't that many Aahzes to hire (sixteen years old or otherwise), and of the non-Aahz progrommers out there it's shocking how many of them them are apparently incapable of learning a second language. Regardless of how easy something is to learn, management always wants to hire people who don't have to. -- Grant From zac256 at gmail.com Sun Aug 15 01:00:57 2010 From: zac256 at gmail.com (Zac Burns) Date: Sat, 14 Aug 2010 22:00:57 -0700 Subject: shelf-like list? In-Reply-To: References: Message-ID: This should help: http://docs.python.org/library/pickle.html -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games On Sat, Aug 14, 2010 at 5:13 PM, kj wrote: > In > Raymond Hettinger writes: > > >On Aug 12, 1:37=A0pm, Thomas Jollans wrote: > >> On Tuesday 10 August 2010, it occurred to kj to exclaim: > >> > >> > I'm looking for a module that implements "persistent lists": objects > >> > that behave like lists except that all their elements are stored > >> > on disk. =A0IOW, the equivalent of "shelves", but for lists rather > >> > than a dictionaries. > > . . . > >> You could simply use pickle to save the data every once in a while. > > >That is a very reasonable solution. > > Sorry I don't follow. Some sample code would be helpful. > TIA, > ~K > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 15 01:26:32 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 14 Aug 2010 22:26:32 -0700 Subject: shelf-like list? In-Reply-To: References: Message-ID: On Sat, Aug 14, 2010 at 5:13 PM, kj wrote: > In Raymond Hettinger writes: >>On Aug 12, 1:37=A0pm, Thomas Jollans wrote: >>> On Tuesday 10 August 2010, it occurred to kj to exclaim: >>> >>> > I'm looking for a module that implements "persistent lists": objects >>> > that behave like lists except that all their elements are stored >>> > on disk. =A0IOW, the equivalent of "shelves", but for lists rather >>> > than a dictionaries. >> . . . >>> You could simply use pickle to save the data every once in a while. > >>That is a very reasonable solution. > > Sorry I don't follow. ?Some sample code would be helpful. I would assume something along the lines of (untested): from pickle import dump MOD_THRESHOLD = 42 class PersistentList(list): def __init__(self, filepath): self.filepath = filepath self._mod_count = 0 def save(self): with open(self.filepath, 'w') as f: dump(self, f) self._mod_count = 0 def append(self, *args, **kwds): super(PersistentList, self).append(*args, **kwds) self._mod_count += 1 if self._mod_count >= MOD_THRESHOLD: # obviously time-since-last-dump or other # more sophisticated metrics might be used instead self.save() # define similar wrappers for list's other mutator methods: __delitem__, __iadd__, __imul__, __setitem__, extend, insert, pop, remove, etc. # using decorators should help decrease code duplication Cheers, Chris -- http://blog.rebertia.com From rami.chowdhury at gmail.com Sun Aug 15 02:32:24 2010 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sun, 15 Aug 2010 12:32:24 +0600 Subject: OpenCV_Problem In-Reply-To: References: Message-ID: On Sun, Aug 15, 2010 at 12:22, arihant nahata wrote: > Hi, > ?? ?I m new to python and openCV. I think you meant to send this to the list ;-) > i installed openCV and python and copied > the necessary folder. and even appended the sys.path. but then too the same > error. > > from opencv import cv > > File "C:\Python26\lib\site-packages\opencv\__init__.py", line 74,?in > > > from cv import * > File "C:\Python26\lib\site-packages\opencv\cv.py", line 25, in? > > _cv = swig_import_helper() > File "C:\Python26\lib\site-packages\opencv\cv.py", line 21, in > swig_import_helper > _mod = imp.load_module('_cv', fp, pathname, description) > ImportError: DLL load failed: The specified module could not be?found. > > can you help me with this?? > Regards, > > Arihant Is there a module _cv.dll in your sys.path? Regards, Rami From debatem1 at gmail.com Sun Aug 15 02:41:49 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 14 Aug 2010 23:41:49 -0700 Subject: Working with PDFs? In-Reply-To: References: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> Message-ID: On Sat, Aug 14, 2010 at 7:58 PM, Terry Reedy wrote: > On 8/14/2010 7:44 PM, jyoung79 at kc.rr.com wrote: >> >> Just curious if anyone knows if it's possible to work with pdf documents >> with Python? ?I'd like to do the following: > > search python pdf library > reportlab I second the reportlab recommendation; while I've never had to search PDFs etc, I've produced some very good-looking ones with it and was very happy with how little effort it took. Geremy Condra From bchang2002 at gmail.com Sun Aug 15 03:45:06 2010 From: bchang2002 at gmail.com (dontcare) Date: Sun, 15 Aug 2010 00:45:06 -0700 (PDT) Subject: [ANN]VTD-XML 2.9 Message-ID: <1c76256b-0010-42e0-af92-ec8dbffc1bc0@l32g2000prn.googlegroups.com> VTD-XML 2.9, the next generation XML Processing API for SOA and Cloud computing, has been released. Please visit https://sourceforge.net/projects/vtd-xml/files/ to download the latest version. * Strict Conformance #VTD-XML now fully conforms to XML namespace 1.0 spec * Performance Improvement #Significantly improved parsing performance for small XML files * Expand Core VTD-XML API #Adds getPrefixString(), and toNormalizedString2() * Cutting/Splitting #Adds getSiblingElementFragment() * A number of bug fixes and code enhancement including: #Fixes a bug for reading very large XML documents on some platforms #Fixes a bug in parsing processing instruction #Fixes a bug in outputAndReparse() From martin at v.loewis.de Sun Aug 15 03:51:49 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 15 Aug 2010 09:51:49 +0200 Subject: shelf-like list? In-Reply-To: References: Message-ID: > Does anyone know of such a module? ZODB supports persistent lists. Regards, Martin From darragh.ssa at gmail.com Sun Aug 15 04:03:47 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Sun, 15 Aug 2010 01:03:47 -0700 (PDT) Subject: Deditor -- pythonic text-editor References: Message-ID: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> I've noticed that there were a lot of downloads since I posted this topic, but I don't get any response from anyone so I actually still don't know whether it is good, bad, ugly, pretty, easy to use,... So please help me! :) From kmaha85 at gmail.com Sun Aug 15 06:33:45 2010 From: kmaha85 at gmail.com (p.mahalakshmi maha) Date: Sun, 15 Aug 2010 03:33:45 -0700 (PDT) Subject: MOVIES SONGS FITNESS FRIENDSHIPS AND MORE Message-ID: new movies new songs new fitness tips new friendships new actress MMS new EXCLUSIVE and MORE FREE www.123maza.com/25/shirt156/ www.slim.com/go/g1246010/ From ldo at geek-central.gen.new_zealand Sun Aug 15 06:40:12 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 22:40:12 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: In message , Aahz wrote: > Heck, I learned Ada as a sixteen-year-old knowing only BASIC and Pascal. Not so surprising, considering Ada was consciously modelled on Pascal. From ldo at geek-central.gen.new_zealand Sun Aug 15 06:49:42 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 22:49:42 +1200 Subject: Simple Python Sandbox References: <4C66F4FD.1010102@ixokai.io> <20100814212552.GA30391@cskk.homeip.net> Message-ID: In message , Stephen Hansen wrote: > On 8/14/10 2:25 PM, Cameron Simpson wrote: > >> Ok, what about this: run the untrusted code in a separate process, >> if necessary running as a user with different privileges. > > Way too much overhead by a really significant margin: I need to do many, > many, many, many, many very short (often very *very* short) little > scripts. Doing IPC to separate processes, even if they're long-running, > and handling proxying of my objects that these scripts need to read from > and tweak in certain ways, would just kill performance. Not necessarily. How about doing IPC via shared memory? From ldo at geek-central.gen.new_zealand Sun Aug 15 06:55:36 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 22:55:36 +1200 Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: In message <4c5db0ae$0$1641$742ec2ed at news.sonic.net>, John Nagle wrote: > The languages which have real multidimensional arrays, rather > than arrays of arrays, tend to use 1-based subscripts. That > reflects standard practice in mathematics. Actually I?d go one better, and say that the languages that have real multidimensional arrays allow you to explicitly specify both the lower and upper bounds of each dimension. E.g. Ada, ALGOL 68. Heck, even Pascal allowed you to do that. From no.email at please.post Sun Aug 15 06:58:14 2010 From: no.email at please.post (kj) Date: Sun, 15 Aug 2010 10:58:14 +0000 (UTC) Subject: shelf-like list? References: Message-ID: In Chris Rebert writes: >On Sat, Aug 14, 2010 at 5:13 PM, kj wrote: >> In Ra= >ymond Hettinger writes: >>>On Aug 12, 1:37=3DA0pm, Thomas Jollans wrote: >>>> On Tuesday 10 August 2010, it occurred to kj to exclaim: >>>> >>>> > I'm looking for a module that implements "persistent lists": objects >>>> > that behave like lists except that all their elements are stored >>>> > on disk. =3DA0IOW, the equivalent of "shelves", but for lists rather >>>> > than a dictionaries. >>> . . . >>>> You could simply use pickle to save the data every once in a while. >> >>>That is a very reasonable solution. >> >> Sorry I don't follow. =C2=A0Some sample code would be helpful. >I would assume something along the lines of (untested): >from pickle import dump >MOD_THRESHOLD =3D 42 >class PersistentList(list): > def __init__(self, filepath): > self.filepath =3D filepath > self._mod_count =3D 0 > def save(self): > with open(self.filepath, 'w') as f: > dump(self, f) > self._mod_count =3D 0 > def append(self, *args, **kwds): > super(PersistentList, self).append(*args, **kwds) > self._mod_count +=3D 1 > if self._mod_count >=3D MOD_THRESHOLD: > # obviously time-since-last-dump or other > # more sophisticated metrics might be used instead > self.save() Even though it is saved periodically to disk, it looks like the whole list remains in memory all the time? (If so, it's not what I'm looking for; the whole point of saving stuff to disk is to keep the list's memory footprint low.) ~K From no.email at please.post Sun Aug 15 06:58:44 2010 From: no.email at please.post (kj) Date: Sun, 15 Aug 2010 10:58:44 +0000 (UTC) Subject: shelf-like list? References: Message-ID: In "Martin v. Loewis" writes: >> Does anyone know of such a module? >ZODB supports persistent lists. Thanks; I'll check it out. ~K From ldo at geek-central.gen.new_zealand Sun Aug 15 07:00:15 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 23:00:15 +1200 Subject: Python "why" questions References: Message-ID: In message , Thomas Jollans wrote: > "Where it all started" is that 0-based indexing gives languages like C a > very nice property: a[i] and *(a+i) are equivalent in C. From a language > design viewpoint, I think that's quite a strong argument. It would be if pointers and arrays were the same thing in C. Only they?re not, quite. Which somewhat defeats the point of trying to make them look the same, don?t you think? From ldo at geek-central.gen.new_zealand Sun Aug 15 07:01:23 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 23:01:23 +1200 Subject: Python "why" questions References: Message-ID: In message , Ian Kelly wrote: > The ability to change the minimum index is evil. Pascal allowed you to do that. And nobody ever characterized Pascal as ?evil?. Not for that reason, anyway... From peter at www.pjb.com.au Sun Aug 15 07:08:08 2010 From: peter at www.pjb.com.au (Peter Billam) Date: 15 Aug 2010 11:08:08 GMT Subject: writing \feff at the begining of a file References: <4C651438.50203@sequans.com> <4c65f752$0$28668$c3e8da3@news.astraweb.com> <4C667FCD.6040802@v.loewis.de> Message-ID: On 2010-08-14, Martin v. Loewis wrote: >> Is there a standard way to autodetect the encoding of a text file? > Use the chardet module: > http://chardet.feedparser.org/ Very timely: the python-chardet package just seems to have appeared on debian squeeze :-) After my latest "aptitude safe-upgrade": box8 (debian) ~> aptitude show python-chardet Package: python-chardet State: installed Automatically installed: yes Version: 2.0.1-1 Priority: optional Section: python Maintainer: Piotr O?arowski Uncompressed Size: 721k Depends: python, python-support (>= 0.90.0) Description: universal character encoding detector Chardet takes a sequence of bytes in an unknown character encoding, and attempts to determine the encoding. Supported encodings: * ASCII, UTF-8, UTF-16 (2 variants), UTF-32 (4 variants) * Big5, GB2312, EUC-TW, HZ-GB-2312, ISO-2022-CN (Traditional and Simplified Chinese) * EUC-JP, SHIFT_JIS, ISO-2022-JP (Japanese) * EUC-KR, ISO-2022-KR (Korean) * KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251 (Cyrillic) * ISO-8859-2, windows-1250 (Hungarian) * ISO-8859-5, windows-1251 (Bulgarian) * windows-1252 (English) * ISO-8859-7, windows-1253 (Greek) * ISO-8859-8, windows-1255 (Visual and Logical Hebrew) * TIS-620 (Thai) This library is a port of the auto-detection code in Mozilla. Homepage: http://chardet.feedparser.org/ Regards, Peter -- Peter Billam www.pjb.com.au www.pjb.com.au/comp/contact.html From downaold at gmail.com Sun Aug 15 07:55:10 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 15 Aug 2010 13:55:10 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: > It would be if pointers and arrays were the same thing in C. Only > they?re > not, quite. Which somewhat defeats the point of trying to make them > look the > same, don?t you think? How are they not the same? The code snippet (in C/C++) below is valid, so arrays are just pointers. The only difference is that the notation x[4] reserves space for 4 (consecutive) ints, and the notation *y doesn't. int x[4]; int *y = x; Moreover, the following is valid (though unsafe) C/C++: int *x; int y = x[4]; Cheers, Roald From downaold at gmail.com Sun Aug 15 08:14:48 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 15 Aug 2010 14:14:48 +0200 Subject: Python "why" questions In-Reply-To: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: On Aug 7, 2010, at 9:14 PM, John Nagle wrote: > FORTRAN, MATLAB, and Octave all use 1-based subscripts. > > The languages which have real multidimensional arrays, rather > than arrays of arrays, tend to use 1-based subscripts. That > reflects standard practice in mathematics. True, but that something is "standard mathematical notation" doesn't mean it's preferable. For example, I have never seen keyword arguments in mathematical notation, and it's definitely not standard practice, but nobody would drop them in favor of standard mathematical notation. In fact, I think, regularly mathematical notation can be improved by standard programming notation. Moreover, I don't see what's so nice about 'real' multidimensional arrays; the way to construct multidimensional arrays from one- dimensional ones is more orthogonal. And you never *have* to think about them as being one-dimensional, it's just a bonus you can (sometimes) profit from. From debatem1 at gmail.com Sun Aug 15 08:16:45 2010 From: debatem1 at gmail.com (geremy condra) Date: Sun, 15 Aug 2010 05:16:45 -0700 Subject: Python "why" questions In-Reply-To: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> References: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> Message-ID: On Sun, Aug 15, 2010 at 4:55 AM, Roald de Vries wrote: > On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: >> >> It would be if pointers and arrays were the same thing in C. Only they?re >> not, quite. Which somewhat defeats the point of trying to make them look >> the >> same, don?t you think? > > How are they not the same? > > The code snippet (in C/C++) below is valid, so arrays are just pointers. The > only difference is that the notation x[4] reserves space for 4 (consecutive) > ints, and the notation *y doesn't. > > int x[4]; > int *y = x; > > Moreover, the following is valid (though unsafe) C/C++: > > int *x; > int y = x[4]; Just to demonstrate that they are different, the following code compiles cleanly: int main() { int *pointer; pointer++; return 0; } While this does not: int main() { int array[0]; array++; return 0; } Geremy Condra From downaold at gmail.com Sun Aug 15 08:20:53 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 15 Aug 2010 14:20:53 +0200 Subject: Python "why" questions In-Reply-To: References: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> Message-ID: <04B8092A-81B8-4139-9FE7-7366AC9400AC@gmail.com> On Aug 15, 2010, at 2:16 PM, geremy condra wrote: > On Sun, Aug 15, 2010 at 4:55 AM, Roald de Vries > wrote: >> On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: >>> >>> It would be if pointers and arrays were the same thing in C. Only >>> they?re >>> not, quite. Which somewhat defeats the point of trying to make >>> them look >>> the >>> same, don?t you think? >> >> How are they not the same? >> >> The code snippet (in C/C++) below is valid, so arrays are just >> pointers. The >> only difference is that the notation x[4] reserves space for 4 >> (consecutive) >> ints, and the notation *y doesn't. >> >> int x[4]; >> int *y = x; >> >> Moreover, the following is valid (though unsafe) C/C++: >> >> int *x; >> int y = x[4]; > > Just to demonstrate that they are different, the following code > compiles cleanly: > > int main() { > int *pointer; > pointer++; > return 0; > } > > While this does not: > > int main() { > int array[0]; > array++; > return 0; > } Interesting! Thanks for the lesson ;-). Cheers, Roald From davea at ieee.org Sun Aug 15 08:30:54 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 15 Aug 2010 08:30:54 -0400 Subject: Pop return from stack? In-Reply-To: <4c673375$0$11100$c3e8da3@news.astraweb.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c673375$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4C67DDFE.7090703@ieee.org> Steven D'Aprano wrote: > On Sat, 14 Aug 2010 16:05:05 -0700, bvdp wrote: > > >> >> >> def error(s): >> print "Error", s >> sys.exit(1) >> >> > This general technique is called "monkey patching". > > > > You can either manually exit from your own error handler: > > def myerror(s): > print "new error message" > sys.exit(2) > > > or call the original error handler: > > > def myerror(s): > print "new error message" > foo._error(s) > > > That second technique requires some preparation before hand. In module > foo, after defining the error() function, you then need to create a > second, private, name to it: > > _error = error > > > > Small point. The OP's request was that he not modify the called module, which is why he was considering monkey-patching. And you can readily avoid adding that line to the file. Just do something like this: import foo _olderror_func = foo.error def myerror(s) print "new error message" _olderror_func(s) DaveA From davea at ieee.org Sun Aug 15 08:39:26 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 15 Aug 2010 08:39:26 -0400 Subject: shelf-like list? In-Reply-To: References: Message-ID: <4C67DFFE.2030903@ieee.org> kj wrote: > >> self.save() >> > > Even though it is saved periodically to disk, it looks like the > whole list remains in memory all the time? (If so, it's not what > I'm looking for; the whole point of saving stuff to disk is to keep > the list's memory footprint low.) > > ~K > > It sounds like we all made the wrong assumption about your requirements. It's not persistence you want, but low memory footprint ? Do you or don't you also want the data to survive multiple runs of the program? If you want the data to be in a persistent disk file, you probably should use a database. And if you don't, then you could either increase the size of your swapfile, or use a more complex scheme to do a memory mapped file while the program is running, and delete it on exit. The swapfile is likely to be execute more quickly than anything else you could cook up in pure python. DaveA From chrischia82 at gmail.com Sun Aug 15 08:47:04 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Sun, 15 Aug 2010 05:47:04 -0700 (PDT) Subject: Simple Problem but tough for me if i want it in linear time Message-ID: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> dataList = [a, b, c, ...] where a, b, c are objects of a Class X. In Class X, it contains self.name and self.number If i wish to test whether a number (let's say 100) appears in one of the object, and return that object, is that only fast way of solving this problem without iterating through every object to see the number value? dataList.__contains__ can only check my object instance name... anyone can solve this in linear complexity? From davea at ieee.org Sun Aug 15 08:50:48 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 15 Aug 2010 08:50:48 -0400 Subject: Python "why" questions In-Reply-To: <04B8092A-81B8-4139-9FE7-7366AC9400AC@gmail.com> References: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> <04B8092A-81B8-4139-9FE7-7366AC9400AC@gmail.com> Message-ID: <4C67E2A8.5010505@ieee.org> Roald de Vries wrote: >
On Aug > 15, 2010, at 2:16 PM, geremy condra wrote: >> On Sun, Aug 15, 2010 at 4:55 AM, Roald de Vries >> wrote: >>> On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: >>>> >>>> It would be if pointers and arrays were the same thing in C. Only >>>> they?re >>>> not, quite. Which somewhat defeats the point of trying to make them >>>> look >>>> the >>>> same, don?t you think? >>> >>> How are they not the same? >>> >>> The code snippet (in C/C++) below is valid, so arrays are just >>> pointers. The >>> only difference is that the notation x[4] reserves space for 4 >>> (consecutive) >>> ints, and the notation *y doesn't. >>> >>> int x[4]; >>> int *y =x; >>> >>> Moreover, the following is valid (though unsafe) C/C++: >>> >>> int *x; >>> int y = x[4]; >> >> Just to demonstrate that they are different, the following code >> compiles cleanly: >> >> int main() { >> int *pointer; >> pointer++; >> return 0; >> } >> >> While this does not: >> >> int main() { >> int array[0]; >> array++; >> return 0; >> } > > Interesting! Thanks for the lesson ;-). > > Cheers, Roald > > That particular example doesn't really matter; it just shows that array is a *const* pointer. One that does matter, sometimes drastically, is sizeof(array) vs. sizeof(pointer). One interesting other effect of the compiler (nearly always) treating pointers and arrays the same is expressions like: int hexdigit = ...something... char ch = "0123456789abcdef"[hexdigit]; char ch2 = hexdigit["0123456789abcdef"; both are valid assignments, and equivalent to char ch3 = hexdigit + &("0123456789abcdef"); From __peter__ at web.de Sun Aug 15 09:14:33 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Aug 2010 15:14:33 +0200 Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: ChrisChia wrote: > dataList = [a, b, c, ...] > where a, b, c are objects of a Class X. > In Class X, it contains self.name and self.number > > If i wish to test whether a number (let's say 100) appears in one of > the object, and return that object, > is that only fast way of solving this problem without iterating > through every object to see the number value? > > dataList.__contains__ can only check my object instance name... > anyone can solve this in linear complexity? Well, iteration as in next(item for item in dataList if item.number == 100) is O(n) and list.__contains__() has no magic way to do better. If you need O(1) lookup you can use a dict or collections.defaultdict that maps item.number to a list (or set) of X instances: lookup = {} for item in dataList: lookup.setdefault(item.number, []).append(item) print lookup[100] Peter From rami.chowdhury at gmail.com Sun Aug 15 09:14:34 2010 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sun, 15 Aug 2010 19:14:34 +0600 Subject: OpenCV_Problem In-Reply-To: References: Message-ID: <201008151914.34334.rami.chowdhury@gmail.com> Hi Arihant, Please make sure your response goes out to the list -- I suggest using 'reply all' rather than 'reply'. Also, please make sure the previous conversation is included in your email -- otherwise people might not understand your problem and be able to help. On Sunday 15 August 2010 12:35:27 arihant nahata wrote: > This is what i have, > > >>> print sys.path > > ['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', > 'C:\\Python27\ > \lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', > 'C:\\Python27 > ', 'C:\\Python27\\lib\\site-packages', > 'C:\\OpenCV2.0\\Python2.6\\Lib\\site-pack > ages'] Can you let us know if a file called '_cv.dll' is in 'C: \OpenCV2.0\Python2.6\Lib\site-packages'? ---- Rami Chowdhury "Any sufficiently advanced incompetence is indistinguishable from malice." -- Grey's Law +1-408-597-7068 / +44-7875-841-046 / +88-01819-245544 From python at mrabarnett.plus.com Sun Aug 15 09:29:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 15 Aug 2010 14:29:15 +0100 Subject: Simple Problem but tough for me if i want it in linear time In-Reply-To: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: <4C67EBAB.5090105@mrabarnett.plus.com> ChrisChia wrote: > dataList = [a, b, c, ...] > where a, b, c are objects of a Class X. > In Class X, it contains self.name and self.number > > If i wish to test whether a number (let's say 100) appears in one of > the object, and return that object, > is that only fast way of solving this problem without iterating > through every object to see the number value? > > dataList.__contains__ can only check my object instance name... > anyone can solve this in linear complexity? Put them into a dict where the key is the number and the value is a list of the objects with that number. From chrischia82 at gmail.com Sun Aug 15 10:22:25 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Sun, 15 Aug 2010 07:22:25 -0700 (PDT) Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem Message-ID: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Hi all, i am trying to do a GUI with Tkinter package, but i am stuck no matter what... The problem right now is that my GUI has a label= 'A' (where 'A' is the text on display) i wish to run a program with 2 threads... one for my GUI and the other for the terminal where the terminal will keep listening to the user input (let's say if he enters 'B'), the GUI will update it's label to 'B'. It's easy to let the terminal wait after the user has entered the input. But the problem is that when the GUI loads up... the root.mainloop() doesn't seem to release the control, hence my thread cannot work on GUI. Is there a way to solve this problem? 2 threads; 1 more GUI and 1 more terminal. From f2h2d2 at gmail.com Sun Aug 15 10:22:33 2010 From: f2h2d2 at gmail.com (nais-saudi) Date: Sun, 15 Aug 2010 07:22:33 -0700 (PDT) Subject: Mecca direct transfer 24 hours Message-ID: <7da9d2fd-92c8-42af-a82f-18a4ef67c257@s9g2000yqd.googlegroups.com> Mecca direct transfer 24 hours You will not believe your eyes what you feel that a direct http://ar.justin.tv/bidayatv#/w/312906784/30 Fairy scenes The sections that cried and asked YouTube viewers translation: http://www.youtube.com/v/IFq9cjtrWlQ&rel=0 http://www.youtube.com/v/y2BN73Q-AJw&rel=0 http://www.youtube.com/v/nNFMvznJ-4c&rel=0 http://www.youtube.com/v/qVB9HNQ-w2I&rel=0 http://www.youtube.com/v/RWfR9z91j8I&rel=0 http://www.todayislam.com/yusuf.htm http://islamtomorrow.com From kentilton at gmail.com Sun Aug 15 10:38:17 2010 From: kentilton at gmail.com (Kenneth Tilton) Date: Sun, 15 Aug 2010 10:38:17 -0400 Subject: math symbols in unicode (grouped by purpose) In-Reply-To: References: Message-ID: <4c67fbe3$0$7109$607ed4bc@cv.net> On 8/13/2010 5:18 PM, Xah Lee wrote: > some collection of math symbols in unicode. > > ? Math Symbols in Unicode > http://xahlee.org/comp/unicode_math_operators.html I am surprised you do not include the numeric character codes. kt > > ? Arrows in Unicode > http://xahlee.org/comp/unicode_arrows.html > > ? Matching Brackets in Unicode > http://xahlee.org/comp/unicode_matching_brackets.html > > these are grouped by the symbol's purpose as much as possible. > > i made them because i can't find unicode symbols grouped by purpose > elsewhere. > > The unicode ?plane -> block? structure does not group symbols well, > because the chars are added throughout the decades. Some symbols get > added in one block, but later on related symbols get added elsewhere. > For example, binary relational symbols are scattered in different > unicode blocks. Same for binary operators, or all symbols used for set > theory, etc. Sometimes a symbol has multiple uses in different math > fields, so which block it gets added into unicode is not well defined. > > hope it's useful to some one. > > Xah > ? http://xahlee.org/ > > ? -- http://www.stuckonalgebra.com "The best Algebra tutorial program I have seen... in a class by itself." Macworld From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 10:47:12 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 14:47:12 GMT Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: <4c67fdef$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 05:47:04 -0700, ChrisChia wrote: > dataList = [a, b, c, ...] > where a, b, c are objects of a Class X. In Class X, it contains > self.name and self.number > > If i wish to test whether a number (let's say 100) appears in one of the > object, and return that object, > is that only fast way of solving this problem without iterating through > every object to see the number value? > > dataList.__contains__ can only check my object instance name... > anyone can solve this in linear complexity? If all you want is *linear* time, then simply iterating over the items will do the job: for item in dataList: if item.number == 100: do_something_with(item) break If you want *less* than linear time, then keep the list sorted and do a binary search, which gives you O(log N) time. Don't sort the list each time, because that's O(N*log N). Or use a dict, which gives you O(1) time. -- Steven From emile at fenx.com Sun Aug 15 11:13:17 2010 From: emile at fenx.com (Emile van Sebille) Date: Sun, 15 Aug 2010 08:13:17 -0700 Subject: shelf-like list? In-Reply-To: References: Message-ID: On 8/15/2010 3:58 AM kj said... > In "Martin v. Loewis" writes: > >>> Does anyone know of such a module? > >> ZODB supports persistent lists. > > Thanks; I'll check it out. > I wouldn't expect a low memory footprint however. :) Emile From raoulbia at gmail.com Sun Aug 15 11:38:03 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 15 Aug 2010 08:38:03 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: Hi John, Thanks for your submission! I've improved a lot and everone's help so far has been thrilling amd is very good for my self-study motivation :) ok so i think i'm clear on how to approach this problem and on how to write basic but clean Python code to solve it. The next step is to generalise this code so that other pack quantities could be tested: "generalize this idea to work with any size packages of McNuggets, not just 6, 9, and 20. For simplicity, however, we will assume that nuggets are provided in three different sized packages" I thought this should be relatively straightforward and it does work if i test it for the values 6,9&20 but if i test for 2,3,4 i would expect the result to be 1 but it returns nothing def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/6+1): for b in range (0,n_nuggets/9+1): for c in range (0,n_nuggets/20+1): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(x,y,z): cbc=0 #cbc=can_buy counter packages =[x,y,z] for n_nuggets in range(50): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print "Largest number of McNuggets that cannot be bought in exact quantity: %d" %(solution) diophantine_nuggets(2,3,4) From raoulbia at gmail.com Sun Aug 15 11:44:15 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 15 Aug 2010 08:44:15 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: Hi John, Thanks for your submission! I've improved a lot and everone's help so far has been thrilling and is very good for my self-study motivation :) ok so i think i'm clear on how to approach this problem and on how to write basic but clean Python code to solve it. The next step is to generalise this code so that other pack quantities could be tested: "generalize this idea to work with any size packages of McNuggets, not just 6, 9, and 20. For simplicity, however, we will assume that nuggets are provided in three different sized packages" I thought this should be relatively straightforward and it does work if i test it for the values 6,9&20 but if i test for 2,3,4 i would expect the result to be 1 but it returns nothing def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/6+1): for b in range (0,n_nuggets/9+1): for c in range (0,n_nuggets/20+1): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(x,y,z): cbc=0 #cbc=can_buy counter packages =[x,y,z] for n_nuggets in range(50): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print "Largest number of McNuggets that cannot be bought in exact quantity: %d" %(solution) diophantine_nuggets(2,3,4) From emile at fenx.com Sun Aug 15 11:58:56 2010 From: emile at fenx.com (Emile van Sebille) Date: Sun, 15 Aug 2010 08:58:56 -0700 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: On 8/15/2010 8:44 AM Baba said... > Hi John, > > Thanks for your submission! I've improved a lot and everone's help so > far has been thrilling and is very good for my self-study > motivation :) > > ok so i think i'm clear on how to approach this problem and on how to > write basic but clean Python code to solve it. > > The next step is to generalise this code so that other pack quantities > could be tested: "generalize this idea to work with any size packages > of McNuggets, not just 6, 9, and 20. For simplicity, however, we will > assume that nuggets are provided in three different sized packages" > > I thought this should be relatively straightforward and it does work > if i test it for the values 6,9&20 but if i test for 2,3,4 i would > expect the result to be 1 but it returns nothing > Because can_buy still uses denominators 6,9&20 - try packages[0],[1]&[2] Emile > def can_buy(n_nuggets,packages): > for a in range (0,n_nuggets/6+1): > for b in range (0,n_nuggets/9+1): > for c in range (0,n_nuggets/20+1): > #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > if packages[0]*a+packages[1]*b > +packages[2]*c==n_nuggets: > return True > return False > > def diophantine_nuggets(x,y,z): > cbc=0 #cbc=can_buy counter > packages =[x,y,z] > for n_nuggets in range(50): > result=can_buy(n_nuggets,packages) > if result: > cbc+=1 > else: > cbc=0 > if cbc==6: > solution=n_nuggets-6 > print "Largest number of McNuggets that cannot be bought in > exact quantity: %d" %(solution) > > diophantine_nuggets(2,3,4) From ian.g.kelly at gmail.com Sun Aug 15 12:04:27 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Aug 2010 10:04:27 -0600 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: On Sun, Aug 15, 2010 at 9:58 AM, Emile van Sebille wrote: > On 8/15/2010 8:44 AM Baba said... >> >> Hi John, >> >> Thanks for your submission! I've improved a lot and everone's help so >> far has been thrilling and is very good for my self-study >> motivation :) >> >> ok so i think i'm clear on how to approach this problem and on how to >> write basic but clean Python code to solve it. >> >> The next step is to generalise this code so that other pack quantities >> could be tested: "generalize this idea to work with any size packages >> of McNuggets, not just 6, 9, and 20. For simplicity, however, we will >> assume that nuggets are provided in three different sized packages" >> >> I thought this should be relatively straightforward and it does work >> if i test it for the values 6,9&20 but if i test for 2,3,4 i would >> expect the result to be 1 but it returns nothing >> > > Because can_buy still uses denominators 6,9&20 - try packages[0],[1]&[2] Also, note that testing for 6 buyable quantities in a row is correct for 6, 9, 20 but is not necessarily correct for other denominations. You should think about how many you need to find in sequence for any given input of x, y, and z. Cheers, Ian From nagle at animats.com Sun Aug 15 12:10:09 2010 From: nagle at animats.com (John Nagle) Date: Sun, 15 Aug 2010 09:10:09 -0700 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4c681161$0$1624$742ec2ed@news.sonic.net> On 8/15/2010 4:00 AM, Lawrence D'Oliveiro wrote: > In message, Thomas > Jollans wrote: > >> "Where it all started" is that 0-based indexing gives languages like C a >> very nice property: a[i] and *(a+i) are equivalent in C. From a language >> design viewpoint, I think that's quite a strong argument. > > It would be if pointers and arrays were the same thing in C. Only they?re > not, quite. Which somewhat defeats the point of trying to make them look the > same, don?t you think? In retrospect, C's "pointer=array" concept was a terrible mistake. It's a historical artifact; early C (pre K&R, as shipped with "research UNIX" V6 and PWB) had no notion of typing; all "struct" pointers were interchangeable and elements of a "struct" were just offsets of a pointer. That was fixed, but arrays weren't. The fundamental problem with "array=pointer" is that it results in lying to the language. Consider the declaration of "read": int read(int fd, char* buf, size_t n); This is a a lie. "buf" is not a pointer to a character. It's an array. And, the bad part, the compiler doesn't know how big it is. The syntax should have been something like int read(int fd, &char[n] buf, size_t n); This says the type of the argument is an array of char of length n, and it's being passed by reference. "read" then knows how big "buf" is. This design error in C is the cause of most buffer overflow crashes and security holes. John Nagle From jjposner at optimum.net Sun Aug 15 12:24:42 2010 From: jjposner at optimum.net (John Posner) Date: Sun, 15 Aug 2010 12:24:42 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: <4C6814CA.6070503@optimum.net> On 8/15/2010 11:38 AM, Baba wrote: In addition to the points that Emile and Ian made ... > > def diophantine_nuggets(x,y,z): > cbc=0 #cbc=can_buy counter > packages =[x,y,z] You can take advantage of a nifty "syntax convenience feature" here. Instead of loading all of the function's arguments into a list "manually", you can make it happen automatically: def diophantine_nuggets(x,y,z): cbc = 0 packages =[x,y,z] ... becomes ... def diophantine_nuggets(*packages): cbc = 0 The asterisk (*) in the function's signature does the trick. > for n_nuggets in range(50): Careful -- in the general case, you might need to search beyond 50 for your answer! Best, John From chare at labr.net Sun Aug 15 12:39:37 2010 From: chare at labr.net (Chris Hare) Date: Sun, 15 Aug 2010 11:39:37 -0500 Subject: adding a "windows" item to a menu bar dynamically Message-ID: <0F5747FA-FB21-49A3-82FE-8176EA172791@labr.net> I want to add a "Windows" menu item to my menu bar, so when another Toplevel window is opened, I can add that to the menu bar in case the user accidentally clicks on a different window and moves the Toplevel under something else. Then when the window is closed, remove the window from the menu Any ideas on how to do this? Thanks From mback1 at live.se Sun Aug 15 12:56:31 2010 From: mback1 at live.se (Mikael B) Date: Sun, 15 Aug 2010 18:56:31 +0200 Subject: NZEC what is it? Message-ID: Hi I use, among other things, a site, http://www.codechef.com to learn python. I don't know what platform they use. I use linux. When I submit this little piece of code to them: import sys import math #main s=sys.stdin.read() int_list=s.split() for a in int_list[1:]: print math.factorial(int(a)) they generate a runtime error :NZEC but I don't (python 2.6) What is NZEC and what could cause it in these few lines of code? Regards Mikael -------------- next part -------------- An HTML attachment was scrubbed... URL: From raoulbia at gmail.com Sun Aug 15 13:11:48 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 15 Aug 2010 10:11:48 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> Message-ID: Hi All, @Emile tnx for spotting the mistake. Should have seen it myself. @John & Ian i had a look around but couldn't find a general version of below theorem If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in 6, 9 and 20 packs. I must admit that i'm not keen on spending too much time on purely mathematical questions. It seems that this has to do with Frobenius Number? re range the exercise seems to suggest to limit it to 200 so feel free to enlighten me on this last part. In the meantime the almost complete code is: def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/packages[0]+1): for b in range (0,n_nuggets/packages[1]+1): for c in range (0,n_nuggets/packages[2]+1): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(*packages): cbc=0 #cbc=can_buy counter #packages =[x,y,z] for n_nuggets in range(200): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print "Largest number of McNuggets that cannot be bought in exact quantity: %d" %(solution) break diophantine_nuggets(2,3,4) From python at mrabarnett.plus.com Sun Aug 15 13:22:54 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 15 Aug 2010 18:22:54 +0100 Subject: NZEC what is it? In-Reply-To: References: Message-ID: <4C68226E.7020809@mrabarnett.plus.com> Mikael B wrote: > Hi > I use, among other things, a site, http://www.codechef.com to learn > python. > I don't know what platform they use. I use linux. > > When I submit this little piece of code to them: > > import sys > import math > > #main > > s=sys.stdin.read() > > int_list=s.split() > > for a in int_list[1:]: > print math.factorial(int(a)) > > > they generate a runtime error :NZEC but I don't (python 2.6) > > What is NZEC and what could cause it in these few lines of code? > I googled for it and found that it means "non-zero exit code", perhaps due to an exception. Not a helpful message! :-) What happens if you deliberately raise an exception, eg: raise ValueError From xahlee at gmail.com Sun Aug 15 13:57:32 2010 From: xahlee at gmail.com (Xah Lee) Date: Sun, 15 Aug 2010 10:57:32 -0700 (PDT) Subject: math symbols in unicode (grouped by purpose) References: <4c67fbe3$0$7109$607ed4bc@cv.net> Message-ID: hi kenny! Xah Lee wrote: > some collection of math symbols in unicode. > ? Math Symbols in Unicode > ? ?http://xahlee.org/comp/unicode_math_operators.html Kenneth Tilton wrote: > I am surprised you do not include the numeric character codes. i thought about it, but the page would get unwieldy. To make it work well one might have to implement javascript so that mouse hover can popup a balloon with info about the char... my javascript isn't so great... maybe sometimes down the road. but if you want a unicode char browser: ? Emacs xub-mode; A Unicode Browser http://xahlee.org/emacs/unicode-browser.html i feel that's the best unicode browser/palette/codemap kinda app there is. (in my humble opinion, more useful than Apple's Character palette, or Windows charmap.) if you are not a emacs user, i'd even say download emacs and use it just for it just for browser unicode chars. (you'll need emacs23.1 at least) Xah From tjreedy at udel.edu Sun Aug 15 14:17:56 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Aug 2010 14:17:56 -0400 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: On 8/15/2010 10:22 AM, ChrisChia wrote: > Hi all, > i am trying to do a GUI with Tkinter package, but i am stuck no matter > what... > The problem right now is that my GUI has a label= 'A' (where 'A' is > the text on display) > > i wish to run a program with 2 threads... one for my GUI and the other > for the terminal where the terminal will keep listening to the user > input (let's say if he enters 'B'), the GUI will update it's label to > 'B'. Makes no sense to me. GUI = graphics user interface. Interface = input from and output to the user. Additional threads for for other activities that may block or be compute intensive, not a separate text user interface. > It's easy to let the terminal wait after the user has entered the > input. > But the problem is that when the GUI loads up... the > > root.mainloop() > > doesn't seem to release the control, That seems to be the point of a GUI -- Terry Jan Reedy From zdoor at xs4all.nl Sun Aug 15 14:24:07 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Sun, 15 Aug 2010 20:24:07 +0200 Subject: Opposite of split Message-ID: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> Looking for a method that does the opposite of 'split', i.e. elements in a list are automatically concatenated with a user selectable spacer in between e.g. '\t'. This is to prepare lines to be written to a sequential file by 'write'. All hints welcome. Regards, Alex van der Spek From the_mineo at web.de Sun Aug 15 14:27:35 2010 From: the_mineo at web.de (Wieland Hoffmann) Date: Sun, 15 Aug 2010 20:27:35 +0200 Subject: Opposite of split In-Reply-To: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> Message-ID: On 15.08.2010 20:24, Alex van der Spek wrote: > Looking for a method that does the opposite of 'split', i.e. elements in > a list are automatically concatenated with a user selectable spacer in > between e.g. '\t'. >>> " ".join(["i","am","a","list"]) 'i am a list' Wieland From gherron at islandtraining.com Sun Aug 15 14:35:15 2010 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 15 Aug 2010 11:35:15 -0700 Subject: Opposite of split In-Reply-To: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> Message-ID: <4C683363.3080305@islandtraining.com> On 08/15/2010 11:24 AM, Alex van der Spek wrote: > Looking for a method that does the opposite of 'split', i.e. elements > in a list are automatically concatenated with a user selectable spacer > in between e.g. '\t'. This is to prepare lines to be written to a > sequential file by 'write'. > > All hints welcome. > > Regards, > Alex van der Spek Strings have a join method for this: '\t'.join(someList) Gary Herron From mback1 at live.se Sun Aug 15 14:46:29 2010 From: mback1 at live.se (Mikael B) Date: Sun, 15 Aug 2010 20:46:29 +0200 Subject: NZEC what is it? In-Reply-To: References: , <4C68226E.7020809@mrabarnett.plus.com>, Message-ID: From: mback1 at live.se To: python at mrabarnett.plus.com Subject: RE: NZEC what is it? Date: Sun, 15 Aug 2010 19:58:44 +0200 > Date: Sun, 15 Aug 2010 18:22:54 +0100 > From: python at mrabarnett.plus.com > To: python-list at python.org > Subject: Re: NZEC what is it? > > Mikael B wrote: > > Hi > > I use, among other things, a site, http://www.codechef.com to learn > > python. > > I don't know what platform they use. I use linux. > > > > When I submit this little piece of code to them: > > > > import sys > > import math > > > > #main > > > > s=sys.stdin.read() > > > > int_list=s.split() > > > > for a in int_list[1:]: > > print math.factorial(int(a)) > > > > > > they generate a runtime error :NZEC but I don't (python 2.6) > > > > What is NZEC and what could cause it in these few lines of code? > > > I googled for it and found that it means "non-zero exit code", perhaps > due to an exception. Not a helpful message! :-) > > What happens if you deliberately raise an exception, eg: > > raise ValueError If I add to the end I just get 'ValueError' I tried to add '1/0' but got 'ZeroDivisionError' Maybe I should try to add 'sys.exit(0)' and see what happens if I submit again... > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacek2v at gmail.com Sun Aug 15 14:50:24 2010 From: jacek2v at gmail.com (jacek2v) Date: Sun, 15 Aug 2010 11:50:24 -0700 (PDT) Subject: Simple Python Sandbox References: Message-ID: <0c395f99-b66e-4099-a65d-734d10e6f072@f42g2000yqn.googlegroups.com> On Aug 14, 1:37?am, Stephen Hansen wrote: > Can you think of a way out of such a sandbox? A way to access disallowed > stuff, not a way to DOS. Hi, I have strange idea :): use Google Apps. You'll need prepare some interfaces for your apps (for example via WebServices) Maybe it is wrong way, maybe not :) Regards From skip at pobox.com Sun Aug 15 14:50:53 2010 From: skip at pobox.com (skip at pobox.com) Date: Sun, 15 Aug 2010 13:50:53 -0500 Subject: Programmers (esp. Windows) needed for SpamBayes Message-ID: <19560.14093.442876.487409@montanaro.dyndns.org> If you have some time to devote to a popular open source Python project, we can use some development help with SpamBayes, particularly on Windows and with Outlook 2010: http://wiki.python.org/moin/VolunteerOpportunities#SpamBayesProject Thanks, -- Skip Montanaro - skip at pobox.com - http://www.smontanaro.net/ From forever.arihant at gmail.com Sun Aug 15 14:54:50 2010 From: forever.arihant at gmail.com (arihant nahata) Date: Mon, 16 Aug 2010 00:24:50 +0530 Subject: OpenCV_Problem In-Reply-To: <201008151914.34334.rami.chowdhury@gmail.com> References: <201008151914.34334.rami.chowdhury@gmail.com> Message-ID: Hi, There is no file named _cv.dll file in the directory that you mentioned -------------- next part -------------- An HTML attachment was scrubbed... URL: From howe.steven at gmail.com Sun Aug 15 15:10:10 2010 From: howe.steven at gmail.com (Steven Howe) Date: Sun, 15 Aug 2010 12:10:10 -0700 Subject: Opposite of split In-Reply-To: <4C683363.3080305@islandtraining.com> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> Message-ID: <4C683B92.9060803@gmail.com> On 08/15/2010 11:35 AM, Gary Herron wrote: > On 08/15/2010 11:24 AM, Alex van der Spek wrote: >> Looking for a method that does the opposite of 'split', i.e. elements >> in a list are automatically concatenated with a user selectable >> spacer in between e.g. '\t'. This is to prepare lines to be written >> to a sequential file by 'write'. >> >> All hints welcome. >> >> Regards, >> Alex van der Spek > > Strings have a join method for this: > '\t'.join(someList) > > Gary Herron or maybe: ----------------------------------------- res = "" for item in myList: res = "%s\t%s" % ( res, item ) myList = ["abc","def","hjk"] res = "" for item in myList: res = "%s\t%s" % ( res, item ) res '\tabc\tdef\thjk' print res abc def hjk Note the leading tab. ----------------------------------------- So: >>> res.strip() 'abc\tdef\thjk' >>> print res.strip() abc def hjk simple enough. Strange you had to ask. sph From mwilson at the-wire.com Sun Aug 15 15:15:34 2010 From: mwilson at the-wire.com (Mel) Date: Sun, 15 Aug 2010 15:15:34 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> Message-ID: Baba wrote: > Hi All, > > @Emile tnx for spotting the mistake. Should have seen it myself. > > @John & Ian i had a look around but couldn't find a general version of > below theorem > If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some x, > then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in 6, 9 and 20 packs. Not that hard. When you can buy nuggets `n` to a pack (6 for example) then if you have schemes for buying k,k+1,k+2,...,k+n-1 nuggets, you can create a scheme for buying any number of nuggets >= k . At worst just buy packs of `n` until the number left to buy is between k and k+n-1 inclusive, then follow the scheme for that number. Mel. From forever.arihant at gmail.com Sun Aug 15 15:25:38 2010 From: forever.arihant at gmail.com (arihant nahata) Date: Mon, 16 Aug 2010 00:55:38 +0530 Subject: OpenCV_Problem In-Reply-To: <201008151914.34334.rami.chowdhury@gmail.com> References: <201008151914.34334.rami.chowdhury@gmail.com> Message-ID: Hi, There is no file named _cv.dll file in the directory that you mentioned -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Sun Aug 15 15:52:06 2010 From: nagle at animats.com (John Nagle) Date: Sun, 15 Aug 2010 12:52:06 -0700 Subject: Pop return from stack? In-Reply-To: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: <4c684566$0$1619$742ec2ed@news.sonic.net> On 8/14/2010 4:05 PM, bvdp wrote: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > print "Error", s > sys.exit(1) > > def func(s): > ... do some processing > ... call error() if bad .. go to system exit. > ... more processing Fix "func". That's terrible Python. No standard Python library module calls system exit to handle an error. So that must be in your code. Standard procedure for errors is to raise an exception. John Nagle From jerradgenson at gmail.com Sun Aug 15 15:59:08 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 12:59:08 -0700 (PDT) Subject: Tkinter/threading issue Message-ID: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Hello, I'm learning Tkinter, and I have an issue that I'd appreciate help with. I have a program that initializes a GUI (I'll call this the "GUI process"), then spawns another process that listens on a network via the TCP/IP protocol for incoming strings (I'll call this the "server process"). Everything works well up to this point. What I want to happen next is for the server process to update a label in the GUI process when it receives a message from the network. First I tried passing a control variable for the label's text into the server process, but when I updated the control variable, nothing happened(no error messages, no feedback of any kind). I tried piping the message from the server process into the GUI process using os.write() and os.read() - and this works, but not the way I need it to. I need the label to be updated automatically, without any intervention from the user (at the moment, it only works when the user clicks an "Update" button). I tried having the GUI process check the pipe for messages automatically, but when I do this it hangs when there's nothing in the pipe. I've tried other avenues as well, but probably nothing worth mentioning. If you have any suggestions, I would be very grateful. From jerradgenson at gmail.com Sun Aug 15 16:01:13 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 13:01:13 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Message-ID: <6853768f-1c0a-43b7-ad20-04010e47c4cb@m1g2000yqo.googlegroups.com> I should also mention that I'm running Ubuntu 10.04 and Python 2.6.5. From thomas at jollybox.de Sun Aug 15 16:28:44 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 15 Aug 2010 22:28:44 +0200 Subject: Tkinter/threading issue In-Reply-To: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Message-ID: <201008152228.45303.thomas@jollybox.de> On Sunday 15 August 2010, it occurred to Jerrad Genson to exclaim: > Hello, > > I'm learning Tkinter, and I have an issue that I'd appreciate help > with. I have a program that initializes a GUI (I'll call this the "GUI > process"), then spawns another process that listens on a network via > the TCP/IP protocol for incoming strings (I'll call this the "server > process"). Everything works well up to this point. Okay, so you want your TCP (or is it UDP? not that it matters - but "TCP/IP" is not a protocol) server to sit in a separate process. May I ask why? Either way, you first need to trigger something inside the GUI process when a network packet arrives. The easiest way would of course be to have the server in the same process... Anyway, IPC. You say you're using Ubuntu. If you're only targetting UNIX-like systems, you can use os.fork() to create the new process -- you're probably doing so anyway (?) -- and use socket.socketpair or os.pipe to create a pipe between parent and child. If you're launching the process with subprocess.Popen, you can simply use the standard files (stdin, stdout,...) as a pipe. If the processes are completely separate, you'd need to use some convention to create a socket between the two, eithe a AF_LOCAL/AF_UNIX socket, or, if you want to support Windows and the likes, a local loopback TCP socket (->127.0.0.1) Once you've got a pipe between the two processes - or the network server within your GUI process - you just have to wait for a message to come flying in, and then update the widget. There are a couple of ways of waiting for a message without disrupting the GUI: you can either create a separate thread in which you, wait for input, or you can add a piece of code to the main loop (I don't know how difficult this is with Tkinter -- shouldn't be too tricky) that checks if there's any news, typically by calling select.select with a zero timeout. > > What I want to happen next is for the server process to update a label > in the GUI process when it receives a message from the network. First > I tried passing a control variable for the label's text into the > server process, but when I updated the control variable, nothing > happened(no error messages, no feedback of any kind). > > I tried piping the message from the server process into the GUI > process using os.write() and os.read() - and this works, but not the > way I need it to. I need the label to be updated automatically, > without any intervention from the user (at the moment, it only works > when the user clicks an "Update" button). I tried having the GUI > process check the pipe for messages automatically, but when I do this > it hangs when there's nothing in the pipe. > > I've tried other avenues as well, but probably nothing worth > mentioning. If you have any suggestions, I would be very grateful. From raoulbia at gmail.com Sun Aug 15 16:36:03 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 15 Aug 2010 13:36:03 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> Message-ID: <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Hi Mel, indeed i thought of generalising the theorem as follows: If it is possible to buy n, n+1,?, n+(x-1) sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in x, y and z packs. so with diophantine_nuggets(7,10,21) i would need 7 passes result:53 but with (10,20,30) and 10 passes i get no result so i'm not sure i'm on the right path... From jerradgenson at gmail.com Sun Aug 15 16:53:08 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 13:53:08 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Message-ID: Thank you for the reply. When I said "TCP/IP" protocol, what I meant was this: http://en.wikipedia.org/wiki/Internet_Protocol_Suite. The reason the server is in a separate process is because it needs to continually be listening for network packets, which would disrupt the GUI. In any case, that part is working fine - I actually have everything you mentioned implemented already, in mostly the way you described it, except for the very last part where the GUI label gets updated. I tried creating a "listener" thread that waits for a message to appear on its pipe from the server process, and then updates the label using a control variable. Again, nothing happens. The program doesn't hang, or throw an exception, but the label isn't being updated either - I presume because I'm trying to set the control variable in a thread separate from the GUI. I'll post some of the code so you can see what I'm talking about. From jerradgenson at gmail.com Sun Aug 15 16:55:49 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 13:55:49 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Message-ID: <69cab38e-76f6-40d8-ae36-6c930b0c3452@l6g2000yqb.googlegroups.com> class MessageServer: '''Creates a message server object that listens for textual information and sends it back to the main program. Intended to be spawned as a separate process. ''' def __init__(self, port_number, server_send, server_receive): '''@param server_send The pipe MessageServer uses to send text back to the main program. @param port_number The port the server listens on the network at. ''' self.server_send = server_send self.server_receive = server_receive self.client_socket = None self.address = None self.error_logger = errorlogger.ErrorLogger(program_name=PROGRAM_NAME) self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind(('localhost', port_number)) self.server_socket.listen(1) self.listen() def listen(self): # listen for messages until process is killed # if a message is received, send it back to the main program (self.client_socket, self.address) = self.server_socket.accept() while True: input_stream = str(self.client_socket.recv(1024)) if len(input_stream) != 0: os.write(self.server_send, input_stream) input_stream = None From jerradgenson at gmail.com Sun Aug 15 16:59:17 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 13:59:17 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> <69cab38e-76f6-40d8-ae36-6c930b0c3452@l6g2000yqb.googlegroups.com> Message-ID: def check_message(self, spawn=True): '''Method for pulling message from server process.''' if spawn: self.pid2 = os.fork() if self.pid2 == 0: if verbose: print('message checker initialized') # repeat message check forever while True: incoming_data = os.read(self.client_receive, 1024) if verbose: print('Message receive successful') if verbose: print('Message: ' + incoming_data) self.update_messages(incoming_data) def update_messages(self, new_text=False): '''Adds new string to conversation box. @param new_text The string to be added. ''' if not new_text: new_text = INCOMING_DATA try: current_text = self.chat_text.get() current_text += '\n' + new_text self.chat_text.set(current_text) except: error_details = 'Fatal Error. Message update failed. Program will now close.' tkMessageBox.showerror('Update Error', error_details) error_details += '\nINCOMING_DATA: ' + new_text error_details += '\ncurrent_text: ' + current_text stack_trace = traceback.format_stack() self.error_logger.log_error(stack=stack_trace, details=error_details) self.exit_program(force=True) From hpj at urpla.net Sun Aug 15 17:17:13 2010 From: hpj at urpla.net (Hans-Peter Jansen) Date: Sun, 15 Aug 2010 23:17:13 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: <201008152317.13757.hpj@urpla.net> On Thursday 12 August 2010, 01:07:25 Gelonida wrote: > Hi Guys, > I'm desperate. I'm having a real application, which fails rather often > when finishing it. I'm not sure, whether any serious problem could be > hidden behind it > > The script is a pyqt script, which segfaults most of the time on my > ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. > > Trying to create the smallest possible test case I ended up with > following script, which I named dodo.py and which i made executable with > chmod +x ./dodo.py > > #!/usr/bin/env python > from PyQt4.QtGui import > QDialog,QGridLayout,QLabel,QComboBox,QPushButton,QApplication > a = "one" > b = "unused" > c = "also unused" > d= "ans also unused" > e = "another var" > f = "something" > class MyForm(QDialog): > def __init__(self,parent=None,config=None,ini_info=None): > super(MyForm,self).__init__(parent=parent) > grid = QGridLayout() > quit_btn = QPushButton("Quit") > quit_btn.clicked.connect(self.quit) > grid.addWidget(quit_btn,0,0) > name = "a_name" > vals_box = QComboBox() > vals_box.addItem("one") > vals_box.addItem("two") > grid.addWidget(vals_box,0,1) > self.setLayout(grid) > def quit(self): > self.close() > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > print "last" > > > > In order to perform the test several times I typed on the command line: > > a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done > > As soon as the window shows up > I click twice (slowly ) on 'one' and then on quit. For a starter, tell us the versions of python-sip, and python-qt4 or however they're called in Ubuntu. For the record, python-sip-4.10.5-1.1 python-qt4-4.7.4-1.1 doesn't show this behavior. Pete From fons at kokkinizita.net Sun Aug 15 17:21:51 2010 From: fons at kokkinizita.net (fons at kokkinizita.net) Date: Sun, 15 Aug 2010 23:21:51 +0200 Subject: execfile() and locals() Message-ID: <20100815212150.GA4280@zita2> Hello all, The documentation on execfile() and locals() makes it clear that code executed from execfile() can not modify local variables in the function from wich execfile() was called. Two questions about this: 1. Is there some way to circumvent this limitation (apart from explicitly copying variables to/from a dictionary passed as locals to execfile()) ? 2. (for experts only I guess) I'd like to understand *why* this is the case. TIA, -- FA There are three of them, and Alleline. From ian.g.kelly at gmail.com Sun Aug 15 17:39:57 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Aug 2010 17:39:57 -0400 Subject: NZEC what is it? In-Reply-To: References: Message-ID: On Sun, Aug 15, 2010 at 12:56 PM, Mikael B wrote: > Hi > ?I use, among other things,? a site,? http://www.codechef.com? to learn > python. > I don't know what platform they use. I use? linux. > > When I submit this little piece of? code to them: > > import sys > import math > > #main > > s=sys.stdin.read() > > int_list=s.split() > > for a in int_list[1:]: > ??????? print math.factorial(int(a)) > > > they generate a runtime error :NZEC?? but I don't? (python 2.6) > > What is NZEC? and what could cause it in these few lines of code? Non-zero exit code. Unless you're calling sys.exit, this normally means your program raised an uncaught exception. In the case of your program, I believe that codechef currently uses Python 2.5. The math.factorial function was added in Python 2.6, so it would not be available. Cheers, Ian From ian.g.kelly at gmail.com Sun Aug 15 17:51:18 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Aug 2010 17:51:18 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Message-ID: On Sun, Aug 15, 2010 at 4:36 PM, Baba wrote: > Hi Mel, > > indeed i thought of generalising the theorem as follows: > If it is possible to buy n, n+1,?, n+(x-1) sets of McNuggets, for some > x, then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in x, y and z packs. > > so with diophantine_nuggets(7,10,21) i would need 7 passes > result:53 > > but with (10,20,30) and 10 passes i get no result You're on the right track. In the case of (10,20,30) there is no largest exactly purchasable quantity. Any quantity that does not end with a 0 will not be exactly purchasable. I suspect that there exists a largest unpurchasable quantity iff at least two of the pack quantities are relatively prime, but I have made no attempt to prove this. Cheers, Ian From thomas at jollybox.de Sun Aug 15 17:55:06 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 15 Aug 2010 23:55:06 +0200 Subject: execfile() and locals() In-Reply-To: <20100815212150.GA4280@zita2> References: <20100815212150.GA4280@zita2> Message-ID: <201008152355.06702.thomas@jollybox.de> On Sunday 15 August 2010, it occurred to fons at kokkinizita.net to exclaim: > Hello all, > > The documentation on execfile() and locals() makes it clear that code > executed from execfile() can not modify local variables in the function > from wich execfile() was called. Two questions about this: > > 1. Is there some way to circumvent this limitation (apart from explicitly > copying variables to/from a dictionary passed as locals to execfile()) ? > > 2. (for experts only I guess) I'd like to understand *why* this is the > case. You can't assign to local variables via locals(), or in any way at all, except by assigning locally. >>> def f(): ... x = 1 ... locals()['x'] = 2 ... return x ... >>> f() 1 >>> The reason is, I think, that local variable access is optimized: variables you assign inside the function are defined to be local (unless you specify otherwise), and a fetching a local variable doesn't involve an expensive may- or-may-not-work dict lookup: >>> x = 1 >>> def g(): ... x ... x = 2 ... >>> x 1 >>> g() Traceback (most recent call last): File "", line 1, in File "", line 2, in g UnboundLocalError: local variable 'x' referenced before assignment >>> If a local variable assignment were hidden behind an execfile(), or a "from foo import *", or a locals()[...] assignment, it wouldn't be possibly to tell if something is local or not. From mback1 at live.se Sun Aug 15 17:55:53 2010 From: mback1 at live.se (Mikael B) Date: Sun, 15 Aug 2010 23:55:53 +0200 Subject: NZEC what is it? In-Reply-To: References: , Message-ID: > From: ian.g.kelly at gmail.com > Date: Sun, 15 Aug 2010 17:39:57 -0400 > Subject: Re: NZEC what is it? > To: python-list at python.org > > On Sun, Aug 15, 2010 at 12:56 PM, Mikael B wrote: > > Hi > > I use, among other things, a site, http://www.codechef.com to learn > > python. > > I don't know what platform they use. I use linux. > > > > When I submit this little piece of code to them: > > > > import sys > > import math > > > > #main > > > > s=sys.stdin.read() > > > > int_list=s.split() > > > > for a in int_list[1:]: > > print math.factorial(int(a)) > > > > > > they generate a runtime error :NZEC but I don't (python 2.6) > > > > What is NZEC and what could cause it in these few lines of code? > > Non-zero exit code. Unless you're calling sys.exit, this normally > means your program raised an uncaught exception. > > In the case of your program, I believe that codechef currently uses > Python 2.5. The math.factorial function was added in Python 2.6, so > it would not be available. > > Cheers, > Ian Ahaa! Thank you. regards Mikael -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 19:24:25 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 23:24:25 GMT Subject: execfile() and locals() References: Message-ID: <4c687728$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 23:21:51 +0200, fons wrote: > Hello all, > > The documentation on execfile() and locals() makes it clear that code > executed from execfile() can not modify local variables in the function > from wich execfile() was called. Two questions about this: > > 1. Is there some way to circumvent this limitation (apart from > explicitly copying variables to/from a dictionary passed as locals to > execfile()) ? Chances are very good that if you're using exec or execfile inside a function, you probably don't need to. > 2. (for experts only I guess) I'd like to understand *why* this is the > case. As an optimization, local variables don't live inside a dict namespace. The space for those locals is allocated at compile time, and locals() returns a copy of the variables in a dict. However, the action of exec is a little more subtle, and mysterious, as seen by this example in Python 3.1: >>> def f(): ... x = 1 ... print(locals()) ... exec("x=2; y=0") ... print(locals()) ... >>> >>> f() {'x': 1} {'y': 0, 'x': 1} This shows that exec was able to create a new local variable, but not modify an existing one -- this is completely unintuitive to me. I would have guessed the opposite. And worse: >>> f.__code__.co_varnames ('x',) >>> f.__code__.co_nlocals 1 So where does the newly-created local `y` live, if not in a dict namespace and not in the usual variable slots? Curiouser and curiouser... -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 19:33:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 23:33:10 GMT Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> Message-ID: <4c687936$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 12:10:10 -0700, Steven Howe wrote: >> Strings have a join method for this: >> '\t'.join(someList) >> >> Gary Herron > or maybe: > ----------------------------------------- > res = "" > for item in myList: > res = "%s\t%s" % ( res, item ) Under what possible circumstances would you prefer this code to the built- in str.join method? Particularly since the code isn't even correct, as it adds a spurious tab character at the beginning of the result string. (By the way, your solution, to call res.strip(), is incorrect, as it removes too much.) -- Steven From chare at labr.net Sun Aug 15 19:41:11 2010 From: chare at labr.net (Chris Hare) Date: Sun, 15 Aug 2010 18:41:11 -0500 Subject: python strings and {} in Tkinter entry widgets Message-ID: I have some code that pulls a value from a database. In this case, it is three space delimited words. When I display the value in a Tkinter.Entry widget, the text has curly braces around it, even when there are none in the surrounding the text in the database. Is this normal, and how do I prevent it or remove them correctly before displaying the text in the Entry widget? Thanks From nadiasvertex at gmail.com Sun Aug 15 19:45:49 2010 From: nadiasvertex at gmail.com (Christopher) Date: Sun, 15 Aug 2010 16:45:49 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? Message-ID: I have the following problem: Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> t="Python26" >>> import re >>> re.sub(r"python\d\d", "Python27", t) 'Python26' >>> re.sub(r"python\d\d", "Python27", t, re.IGNORECASE) 'Python26' >>> re.sub(r"Python\d\d", "Python27", t, re.IGNORECASE) 'Python27' >>> --- Perhaps this is intended behavior, but it seems like the last two results should be the same, not the first two. In other words, the call to re.sub with re.IGNORECASE on should return "Python27" not "Python26". This appears to be the case when using compiled pattern matching: >>> r=re.compile(r"python\d\d", re.IGNORECASE) >>> r.sub("Python27", t) 'Python27' --- Is this a known bug? Is it by design for some odd reason? From roy at panix.com Sun Aug 15 19:58:54 2010 From: roy at panix.com (Roy Smith) Date: Sun, 15 Aug 2010 19:58:54 -0400 Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: In article <4c687936$0$11100$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 12:10:10 -0700, Steven Howe wrote: > > >> Strings have a join method for this: > >> '\t'.join(someList) > >> > >> Gary Herron > > or maybe: > > ----------------------------------------- > > res = "" > > for item in myList: > > res = "%s\t%s" % ( res, item ) > > > Under what possible circumstances would you prefer this code to the built- > in str.join method? > > Particularly since the code isn't even correct, as it adds a spurious tab > character at the beginning of the result string. I think you answered your own question. The possible circumstance would be a "find the bug" question on a programming interview :-) Actually, there is (at least) one situation where this produces the correct result, can you find it? The other problem is that the verbose version is O(n^2) and str.join() is O(n). From darcy at druid.net Sun Aug 15 20:03:55 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 15 Aug 2010 20:03:55 -0400 Subject: Opposite of split In-Reply-To: <4c687936$0$11100$c3e8da3@news.astraweb.com> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: <20100815200355.47f0ca2d.darcy@druid.net> On 15 Aug 2010 23:33:10 GMT Steven D'Aprano wrote: > Under what possible circumstances would you prefer this code to the built- > in str.join method? I assumed that it was a trap for someone asking for us to do his homework. I also thought that it was a waste of time because I knew that twenty people would jump in with the correct answer because of "finally, one that I can answer" syndrome. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 20:07:53 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 00:07:53 GMT Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: Message-ID: <4c688159$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 16:45:49 -0700, Christopher wrote: > I have the following problem: > >>>> t="Python26" >>>> import re >>>> re.sub(r"python\d\d", "Python27", t) > 'Python26' >>>> re.sub(r"python\d\d", "Python27", t, re.IGNORECASE) > 'Python26' >>>> re.sub(r"Python\d\d", "Python27", t, re.IGNORECASE) > 'Python27' > Is this a known bug? Is it by design for some odd reason? >>> help(re.sub) Help on function sub in module re: sub(pattern, repl, string, count=0) ... You're passing re.IGNORECASE (which happens to equal 2) as a count argument, not as a flag. Try this instead: >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) 'Python27' -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 20:10:31 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 00:10:31 GMT Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c6881f7$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 19:58:54 -0400, Roy Smith wrote: > Actually, > there is (at least) one situation where this produces the correct > result, can you find it? When myList is empty, it correctly gives the empty string. -- Steven From greg.ewing at canterbury.ac.nz Sun Aug 15 20:33:51 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 16 Aug 2010 12:33:51 +1200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <8crequF9tpU1@mid.individual.net> Ian Kelly wrote: > On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie > wrote: >> real sample[-500:750]; > Ugh, no. The ability to change the minimum index is evil. Not always; it can have its uses, particularly when you're using the array as a mapping rather than a collection. Pascal had a nice feature where you could use any ordinal type as an array index, and sometimes it was handy to have things like an array indexed by the characters 'A' to 'Z', or the values (Red, Green, Blue). Typically you didn't need to do arithmetic on the indices in those case, though. Python addresses this by having separate types for sequences and mappings. -- Greg From alex at moreati.org.uk Sun Aug 15 20:36:07 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Sun, 15 Aug 2010 17:36:07 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> Message-ID: <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> On Aug 16, 1:07?am, Steven D'Aprano wrote: > You're passing re.IGNORECASE (which happens to equal 2) as a count > argument, not as a flag. Try this instead: > > >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) > 'Python27' Basically right, but in-line flags must be placed at the start of a pattern, or the result is undefined. Also in Python 2.7 re.sub() has a flags argument. Python 2.7.0+ (release27-maint:83286, Aug 16 2010, 01:25:58) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> t = 'Python26' >>> re.sub(r'(?i)python\d\d', 'Python27', t) 'Python27' >>> re.sub(r'python\d\d', 'Python27', t, flags=re.IGNORECASE) 'Python27' Alex From hammer777123 at gmail.com Sun Aug 15 20:43:03 2010 From: hammer777123 at gmail.com (hammer777123) Date: Sun, 15 Aug 2010 17:43:03 -0700 (PDT) Subject: NewaveMoneyMaker__FREE 30 Day Trial__4,650 Followers In 7 days Message-ID: <5f75e005-e0fa-4d17-8e9d-d1d11de822e3@i13g2000yqd.googlegroups.com> NewaveMoneyMaker__FREE 30 Day Trial__4,650 Followers In 7 days http://tinyurl.com/2gx63ye Want Better Than The "Average" P_ _ _ _ Size? 2 FREE Bottles http://mhlnk.com/DF434BFB Free $5.00 to Join___$0.5 Paid Per Click http://tinyurl.com/3xanc6c From greg.ewing at canterbury.ac.nz Sun Aug 15 20:47:28 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 16 Aug 2010 12:47:28 +1200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <8crfkeFdl0U1@mid.individual.net> Roald de Vries wrote: > On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: > >> Which somewhat defeats the point of trying to make them >> look the >> same, don?t you think? > > How are they not the same? One way to see that they're not *exactly* the same is the fact that sizeof("python rocks") is 13, not sizeof(char *). Arrays exist as a distinct concept in the type system. What is true is that when you use the name of an array in an expression, it evaluates to a pointer to its first element. And array indexing is defined in terms of what happens to the resulting pointer, rather than being done directly on the array itself. -- Greg From greg.ewing at canterbury.ac.nz Sun Aug 15 20:53:52 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 16 Aug 2010 12:53:52 +1200 Subject: Python "why" questions In-Reply-To: References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: <8crg0eFfbkU1@mid.individual.net> > On Aug 7, 2010, at 9:14 PM, John Nagle wrote: > >> The languages which have real multidimensional arrays, rather >> than arrays of arrays, tend to use 1-based subscripts. That >> reflects standard practice in mathematics. Not always -- mathematicians use whatever starting index is most convenient for the problem at hand. For example, the constant term of a polynomial is usually called term 0, not term 1. So to a mathematician, an array being used to hold polynomial coefficents would most naturally be indexed from 0. I suspect that part of the reason Fortran uses 1-based indexing is that people hadn't had enough experience with high-level languages back then to realise the awkwardness it often leads to, and they were relying on "common sense". -- Greg From roy at panix.com Sun Aug 15 20:59:36 2010 From: roy at panix.com (Roy Smith) Date: Sun, 15 Aug 2010 20:59:36 -0400 Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: In article <8crg0eFfbkU1 at mid.individual.net>, Gregory Ewing wrote: > Not always -- mathematicians use whatever starting index is > most convenient for the problem at hand. Which may be 0, 1, or something else. There are plenty of situations, for example, where you might want to use both positive and negative indices. Which work with Python lists, but not the way a mathematician would expect :-) In general, I've found, "Because that's the way they do it in math", to be an unreliable guide to, "How should we do it in a programming language?" It's often a reasonable place to start, but there are other considerations. From python at mrabarnett.plus.com Sun Aug 15 21:13:43 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 16 Aug 2010 02:13:43 +0100 Subject: Python 2.7 re.IGNORECASE broken in re.sub? In-Reply-To: <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> Message-ID: <4C6890C7.9040001@mrabarnett.plus.com> Alex Willmer wrote: > On Aug 16, 1:07 am, Steven D'Aprano cybersource.com.au> wrote: >> You're passing re.IGNORECASE (which happens to equal 2) as a count >> argument, not as a flag. Try this instead: >> >>>>> re.sub(r"python\d\d" + '(?i)', "Python27", t) >> 'Python27' > > Basically right, but in-line flags must be placed at the start of a > pattern, or the result is undefined. Also in Python 2.7 re.sub() has a > flags argument. > [snip] In re such flags apply to the entire regex, no matter where they appear. This even applies to the (?x) (VERBOSE) flag; if re sees it at the end of the regex then it has to re-scan the entire regex! For clarity and compatibility with other regex implementations, put it initially. From bob at mellowood.ca Sun Aug 15 21:43:49 2010 From: bob at mellowood.ca (bvdp) Date: Sun, 15 Aug 2010 18:43:49 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: On Aug 15, 12:52?pm, John Nagle wrote: > On 8/14/2010 4:05 PM, bvdp wrote: > > > Assuming I have a module 'foo.py' with something like this: > > > def error(s): > > ? ? ?print "Error", s > > ? ? ?sys.exit(1) > > > def func(s): > > ? ? ?... do some processing > > ? ? ?... call error() if bad .. go to system exit. > > ? ? ?... ?more processing > > ? ? Fix "func". ?That's terrible Python. ? No standard Python library > module calls system exit to handle an error. ?So that must be in > your code. ? Standard procedure for errors is to raise an > exception. Not to belabor the point .. but "func" is not a standard lib module. It's part of a much larger application ... and in that application it makes perfect sense to terminate the application if it encounters an error. I fail to see the problem with this. Why would an APPLICATION raise a error or not exit to the system? Does it help to note that error() as defined in the application prints out a helpful message, etc? The whole problem I was having is that I was trying to tie a small application (an helper to the main application) to use a bit of the existing code as a pseudo-library. Certainly, if the code I was interfacing with was a standar Python module ... well, then this thread would not exist in the first place. However, I have gotten hit with more than one comment like yours. So, could you please clarify? Is it bad form to exit an application with sys.exit(1) when an error in a file the application is processing is found? Honestly, I'm not trying to be argumentative ... just trying to understand. Thanks. From jerradgenson at gmail.com Sun Aug 15 22:03:00 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 19:03:00 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> <69cab38e-76f6-40d8-ae36-6c930b0c3452@l6g2000yqb.googlegroups.com> Message-ID: <904096b9-2348-4c5a-9869-90f2ff9e8eda@k10g2000yqa.googlegroups.com> Well, I figured it out. Thanks anyway for your help. From flebber.crue at gmail.com Sun Aug 15 23:30:02 2010 From: flebber.crue at gmail.com (flebber) Date: Sun, 15 Aug 2010 20:30:02 -0700 (PDT) Subject: Python XML and tables using math Message-ID: <81a2406a-af83-4904-ae26-a41bc626fe0e@u31g2000pru.googlegroups.com> I am looking at a project that will import and modify an XML file and then export it to a table. Currently a flat file table system should be fine. I want to export the modified data to the table and then perform a handful of maths(largely simple statistical functions) to the data and then print out the resultant modified tables. I was planning on using Python 2.7 for the project. Has anyone used a guide to acheive something similar? I would like to read up on it so I can assess my options and best methods, any hints or tips? From carey.tilden at gmail.com Mon Aug 16 00:01:04 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Sun, 15 Aug 2010 21:01:04 -0700 Subject: Pop return from stack? In-Reply-To: References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: On Sun, Aug 15, 2010 at 6:43 PM, bvdp wrote: > Not to belabor the point .. but "func" is not a standard lib module. > It's part of a much larger application ... and in that application it > makes perfect sense to terminate the application if it encounters an > error. I fail to see the problem with this. Why would an APPLICATION > raise a error or not exit to the system? For me, the main reason is to ensure the application has only one exit point. There's only one spot to maintain the code for closing files, cleaning up network connections, displaying errors to the user, etc. It makes it really easy to change your mind later about what to do with errors. It also lets you unify handling of your own errors with errors generated by 3rd party code. Carey From ldo at geek-central.gen.new_zealand Mon Aug 16 00:28:46 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 16 Aug 2010 16:28:46 +1200 Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: In message <8crg0eFfbkU1 at mid.individual.net>, Gregory Ewing wrote: > For example, the constant term of a polynomial is usually called term 0, > not term 1. That is not some kind of ordinal numbering of the terms, that is the power of the variable involved. And polynomials can have negative powers, too. From chrischia82 at gmail.com Mon Aug 16 00:36:01 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Sun, 15 Aug 2010 21:36:01 -0700 (PDT) Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: On Aug 16, 4:17?am, Terry Reedy wrote: > On 8/15/2010 10:22 AM, ChrisChia wrote: > > > Hi all, > > i am trying to do a GUI with Tkinter package, but i am stuck no matter > > what... > > The problem right now is that my GUI has a label= 'A' (where 'A' is > > the text on display) > > > i wish to run a program with 2 threads... one for my GUI and the other > > for the terminal where the terminal will keep listening to the user > > input (let's say if he enters 'B'), the GUI will update it's label to > > 'B'. > > Makes no sense to me. GUI = graphics user interface. Interface = input > from and output to the user. Additional threads for for other activities > that may block or be compute intensive, not a separate text user interface. > > > It's easy to let the terminal wait after the user has entered the > > input. > > But the problem is that when the GUI loads up... the > > > root.mainloop() > > > doesn't seem to release the control, > > That seems to be the point of a GUI > > -- > Terry Jan Reedy The idea has is that the interface acts as a window to display the text type from the terminal. It's a crazy idea but i wish to implement something that way. The GUI in the case will display any text that the user enters from the terminal... Any idea to make both the processes running and listening at the same time? From jemygraw at gmail.com Mon Aug 16 01:13:54 2010 From: jemygraw at gmail.com (=?GB2312?B?vfD2zvbO?=) Date: Mon, 16 Aug 2010 05:13:54 +0000 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: Hi Man, I have done that according to your requirements Here is the code {code} > #!/usr/bin/python > > import Tkinter > > import threading > > >> root=Tkinter.Tk() > > root.geometry("100x100") > > v=Tkinter.StringVar() > > label=Tkinter.Label(root,textvariable=v,fg="red") > > label.pack(fill=Tkinter.X,expand=1) > > >> >> def getInput(): > > while True: > > global v > > inputStr=raw_input("Enter>>") > > v.set(inputStr) > > t1=threading.Thread(target=getInput,args=()) > > t1.start() > > >> Tkinter.mainloop() > > > {code} 2010/8/16 ChrisChia > On Aug 16, 4:17 am, Terry Reedy wrote: > > On 8/15/2010 10:22 AM, ChrisChia wrote: > > > > > Hi all, > > > i am trying to do a GUI with Tkinter package, but i am stuck no matter > > > what... > > > The problem right now is that my GUI has a label= 'A' (where 'A' is > > > the text on display) > > > > > i wish to run a program with 2 threads... one for my GUI and the other > > > for the terminal where the terminal will keep listening to the user > > > input (let's say if he enters 'B'), the GUI will update it's label to > > > 'B'. > > > > Makes no sense to me. GUI = graphics user interface. Interface = input > > from and output to the user. Additional threads for for other activities > > that may block or be compute intensive, not a separate text user > interface. > > > > > It's easy to let the terminal wait after the user has entered the > > > input. > > > But the problem is that when the GUI loads up... the > > > > > root.mainloop() > > > > > doesn't seem to release the control, > > > > That seems to be the point of a GUI > > > > -- > > Terry Jan Reedy > > > The idea has is that the interface acts as a window to display the > text type from the terminal. > It's a crazy idea but i wish to implement something that way. > > The GUI in the case will display any text that the user enters from > the terminal... > > Any idea to make both the processes running and listening at the same > time? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jemygraw at gmail.com Mon Aug 16 01:17:21 2010 From: jemygraw at gmail.com (Jemy) Date: Mon, 16 Aug 2010 05:17:21 +0000 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: On Mon, Aug 16, 2010 at 5:13 AM, ??? wrote: > Hi Man, > I have done that according to your requirements > Here is the code > {code} > >> #!/usr/bin/python >> >> import Tkinter >> >> import threading >> >> >>> root=Tkinter.Tk() >> >> root.geometry("100x100") >> >> v=Tkinter.StringVar() >> >> label=Tkinter.Label(root,textvariable=v,fg="red") >> >> label.pack(fill=Tkinter.X,expand=1) >> >> >>> >>> def getInput(): >> >> while True: >> >> global v >> >> inputStr=raw_input("Enter>>") >> >> v.set(inputStr) >> >> t1=threading.Thread(target=getInput,args=()) >> >> t1.start() >> >> >>> Tkinter.mainloop() >> >> >> {code} > > 2010/8/16 ChrisChia > > On Aug 16, 4:17 am, Terry Reedy wrote: >> > On 8/15/2010 10:22 AM, ChrisChia wrote: >> > >> > > Hi all, >> > > i am trying to do a GUI with Tkinter package, but i am stuck no matter >> > > what... >> > > The problem right now is that my GUI has a label= 'A' (where 'A' is >> > > the text on display) >> > >> > > i wish to run a program with 2 threads... one for my GUI and the other >> > > for the terminal where the terminal will keep listening to the user >> > > input (let's say if he enters 'B'), the GUI will update it's label to >> > > 'B'. >> > >> > Makes no sense to me. GUI = graphics user interface. Interface = input >> > from and output to the user. Additional threads for for other activities >> > that may block or be compute intensive, not a separate text user >> interface. >> > >> > > It's easy to let the terminal wait after the user has entered the >> > > input. >> > > But the problem is that when the GUI loads up... the >> > >> > > root.mainloop() >> > >> > > doesn't seem to release the control, >> > >> > That seems to be the point of a GUI >> > >> > -- >> > Terry Jan Reedy >> >> >> The idea has is that the interface acts as a window to display the >> text type from the terminal. >> It's a crazy idea but i wish to implement something that way. >> >> The GUI in the case will display any text that the user enters from >> the terminal... >> >> Any idea to make both the processes running and listening at the same >> time? >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- Hi,I am Jemy -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: tkm.py Type: text/x-python Size: 371 bytes Desc: not available URL: From jemygraw at gmail.com Mon Aug 16 01:17:54 2010 From: jemygraw at gmail.com (Jemy) Date: Mon, 16 Aug 2010 05:17:54 +0000 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: I attached the source file On Mon, Aug 16, 2010 at 5:17 AM, Jemy wrote: > > > On Mon, Aug 16, 2010 at 5:13 AM, ??? wrote: > >> Hi Man, >> I have done that according to your requirements >> Here is the code >> {code} >> >>> #!/usr/bin/python >>> >>> import Tkinter >>> >>> import threading >>> >>> >>>> root=Tkinter.Tk() >>> >>> root.geometry("100x100") >>> >>> v=Tkinter.StringVar() >>> >>> label=Tkinter.Label(root,textvariable=v,fg="red") >>> >>> label.pack(fill=Tkinter.X,expand=1) >>> >>> >>>> >>>> def getInput(): >>> >>> while True: >>> >>> global v >>> >>> inputStr=raw_input("Enter>>") >>> >>> v.set(inputStr) >>> >>> t1=threading.Thread(target=getInput,args=()) >>> >>> t1.start() >>> >>> >>>> Tkinter.mainloop() >>> >>> >>> {code} >> >> 2010/8/16 ChrisChia >> >> On Aug 16, 4:17 am, Terry Reedy wrote: >>> > On 8/15/2010 10:22 AM, ChrisChia wrote: >>> > >>> > > Hi all, >>> > > i am trying to do a GUI with Tkinter package, but i am stuck no >>> matter >>> > > what... >>> > > The problem right now is that my GUI has a label= 'A' (where 'A' is >>> > > the text on display) >>> > >>> > > i wish to run a program with 2 threads... one for my GUI and the >>> other >>> > > for the terminal where the terminal will keep listening to the user >>> > > input (let's say if he enters 'B'), the GUI will update it's label to >>> > > 'B'. >>> > >>> > Makes no sense to me. GUI = graphics user interface. Interface = input >>> > from and output to the user. Additional threads for for other >>> activities >>> > that may block or be compute intensive, not a separate text user >>> interface. >>> > >>> > > It's easy to let the terminal wait after the user has entered the >>> > > input. >>> > > But the problem is that when the GUI loads up... the >>> > >>> > > root.mainloop() >>> > >>> > > doesn't seem to release the control, >>> > >>> > That seems to be the point of a GUI >>> > >>> > -- >>> > Terry Jan Reedy >>> >>> >>> The idea has is that the interface acts as a window to display the >>> text type from the terminal. >>> It's a crazy idea but i wish to implement something that way. >>> >>> The GUI in the case will display any text that the user enters from >>> the terminal... >>> >>> Any idea to make both the processes running and listening at the same >>> time? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> > > > -- > Hi,I am Jemy > -- Hi,I am Jemy -------------- next part -------------- An HTML attachment was scrubbed... URL: From jemygraw at gmail.com Mon Aug 16 01:24:26 2010 From: jemygraw at gmail.com (Jemy) Date: Mon, 16 Aug 2010 05:24:26 +0000 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: http://effbot.org/tkinterbook/label.htm Hope this url will be of some help to you all. Regards Jemy -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Mon Aug 16 01:44:48 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 15 Aug 2010 22:44:48 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: <40a6bfac-3f4b-43f4-990b-224cb2b654d3@i19g2000pro.googlegroups.com> On Aug 15, 6:43?pm, bvdp wrote: > On Aug 15, 12:52?pm, John Nagle wrote: > > > > > On 8/14/2010 4:05 PM, bvdp wrote: > > > > Assuming I have a module 'foo.py' with something like this: > > > > def error(s): > > > ? ? ?print "Error", s > > > ? ? ?sys.exit(1) > > > > def func(s): > > > ? ? ?... do some processing > > > ? ? ?... call error() if bad .. go to system exit. > > > ? ? ?... ?more processing > > > ? ? Fix "func". ?That's terrible Python. ? No standard Python library > > module calls system exit to handle an error. ?So that must be in > > your code. ? Standard procedure for errors is to raise an > > exception. > > Not to belabor the point .. but "func" is not a standard lib module. > It's part of a much larger application ... and in that application it > makes perfect sense to terminate the application if it encounters an > error. I fail to see the problem with this. Why would an APPLICATION > raise a error or not exit to the system? > > Does it help to note that error() as defined in the application prints > out a helpful message, etc? > > The whole problem I was having is that I was trying to tie a small > application (an helper to the main application) to use a bit of the > existing code as a pseudo-library. Certainly, if the code I was > interfacing with was a standar Python module ... well, then this > thread would not exist in the first place. > > However, I have gotten hit with more than one comment like yours. So, > could you please clarify? Is it bad form to exit an application with > sys.exit(1) when an error in a file the application is processing is > found? > > Honestly, I'm not trying to be argumentative ... just trying to > understand. The One Obvious Way to handle errors in Python is to raise an exception, and catching it wherever you can proceed. If you can't proceed, either don't catch it, or catch it at the top level. Example (Python 2.6): class MyException(Exception): pass def some_function deep in call tree(): # do some stuff if is_error(): # will be caught way up the stack, in main raise MyException(error_message) # do some stuff if there wasn't an error def main(): try: run_program() except MyException as exc: print >> sys.stderr, str(exc) sys.exit(1) If you call sys.exit() deep within your call tree, the world won't come to an end, but raising an exception is the preferred way to do it. FWIW, I think it perfectly reasonable to let an application print a traceback on an error. I've gotten a few bug reports on a little tool I maintain where the user copies the traceback to me, it it's helped me diagnose their issues a lot. Carl Banks From stefan_ml at behnel.de Mon Aug 16 02:00:30 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 16 Aug 2010 08:00:30 +0200 Subject: Python XML and tables using math In-Reply-To: <81a2406a-af83-4904-ae26-a41bc626fe0e@u31g2000pru.googlegroups.com> References: <81a2406a-af83-4904-ae26-a41bc626fe0e@u31g2000pru.googlegroups.com> Message-ID: flebber, 16.08.2010 05:30: > I am looking at a project that will import and modify an XML file and > then export it to a table. Currently a flat file table system should > be fine. > > I want to export the modified data to the table and then perform a > handful of maths(largely simple statistical functions) to the data and > then print out the resultant modified tables. > > I was planning on using Python 2.7 for the project. > > Has anyone used a guide to acheive something similar? I would like to > read up on it so I can assess my options and best methods, any hints > or tips? That can usually be done in a couple of lines in Python. The approach I keep recommending is to use cElementTree (in the stdlib), potentially its iterparse() function if the file is too large to easily fit into memory, but the code won't change much either way. You might want to skip through this list a bit, similar questions have been coming up every couple of weeks. The responses often include mostly complete implementations that you can borrow from. Stefan From bob.martin at excite.com Mon Aug 16 07:24:26 2010 From: bob.martin at excite.com (Bob Martin) Date: Mon, 16 Aug 2010 07:24:26 BST Subject: Python "why" questions References: Message-ID: <8cs3sqF18dU4@mid.individual.net> in 639663 20100815 120123 Lawrence D'Oliveiro wrote: >In message , Ian Kelly >wrote: > >> The ability to change the minimum index is evil. > >Pascal allowed you to do that. And nobody ever characterized Pascal as >???evil???. Not for that reason, anyway... Why do you refer to Pascal in the past tense? I use it most days (Delphi & Free Pascal). From alanwilter at gmail.com Mon Aug 16 03:06:20 2010 From: alanwilter at gmail.com (Alan) Date: Mon, 16 Aug 2010 08:06:20 +0100 Subject: errors and exception Message-ID: Hello, I am using things like: except Exception as inst: and with open("myfile.txt") as f: for line in f: print line Things that seems to be new in python 2.6 and higher, however reading http://docs.python.org/tutorial/errors.html and this not clear when this new syntaxes appeared. My trouble is that I want to make something similar above compatible with python 2.5, but when running python2.5 I got: except Exception as msg: ^ SyntaxError: invalid syntax If there's a way (e.g. from __future__ ..., inherited modified Exception class, etc) that could give a solution to keep my code in python 2.6 syntax as above but compatible with python 2.5, that would be appreciated. Many thanks in advance, Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From stndshp at gmail.com Mon Aug 16 03:20:17 2010 From: stndshp at gmail.com (Standish P) Date: Mon, 16 Aug 2010 00:20:17 -0700 (PDT) Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? Message-ID: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? Because a stack has push and pop, it is able to release and allocate memory. We envisage an exogenous stack which has malloc() associated with a push and free() associated with a pop. The algorithm using the stack would have to be "perfect" to prevent stack overflow or condition of infinite recursion depth. This would involve data type checking to filter out invalid input. The task must be casted in an algorithm that uses the stack. Then the algorithm must be shown to be heuristically or by its metaphor, to be correct using informal reasoning. Are there any standard textbooks or papers that show stacks implemented in C/C++/Python/Forth with malloc/free in push and pop ? If Forth is a general processing language based on stack, is it possible to convert any and all algorithms to stack based ones and thus avoid memory leaks since a pop automatically releases memory when free is an intrinsic part of it. K&R ANSI has the example of modular programming showing how to implement a stack but he uses a fixed length array. It is also possibly an endogenous stack. We look for an exogenous stack so that element size can vary. ======= Standish P From gelonida at gmail.com Mon Aug 16 03:22:27 2010 From: gelonida at gmail.com (Gelonida) Date: Mon, 16 Aug 2010 09:22:27 +0200 Subject: segfault with small pyqt script In-Reply-To: <201008152317.13757.hpj@urpla.net> References: <201008152317.13757.hpj@urpla.net> Message-ID: Hi Hans-Peter, It seems, that my other posts did not get through. On 08/15/2010 11:17 PM, Hans-Peter Jansen wrote: > For a starter, tell us the versions of python-sip, and python-qt4 or however > they're called in Ubuntu. For the record, > python-sip-4.10.5-1.1 > python-qt4-4.7.4-1.1 > doesn't show this behavior. > > Pete The problem seems to be known for 4.7.2. For simple code I managed to work around the issue. For the real more complicated I didn't. So it seems I'll have to avoid 4.7.2. Please see below: On 08/13/2010 09:11 AM, Gelonida wrote: > > Lee, > > > > On 08/13/2010 12:53 AM, Lee Harr wrote: >> >> >>> >>> I'm desperate. I'm having a real application, which fails rather often >>> >>> when finishing it. I'm not sure, whether any serious problem could be >>> >>> hidden behind it >>> >>> >>> >>> The script is a pyqt script, which segfaults most of the time on my >>> >>> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. >> >> >> >> >> >> Looks to be a known issue: >> >> http://www.google.com/search?q=pyqt+segfault+on+exit >> >> https://launchpad.net/bugs/561303 >> >> >> >> The last activity on that bug is almost 2 months ago... >> >> Hopefully the fix will be distributed soon. > > > > > > > > This seems to be the problem. > > > > > > In my case I can workaround the issue by adding one line. > > > > if __name__ == "__main__": > > app = QApplication([]) > > myform = MyForm() > > myform.show() > > retcode = app.exec_() > > myform = None # <<<< THIS IS THE WORK AROUND > > print "last" > > For more complex multi widget examples it doesn't seem enough to just destroy the main widget. probably I had to recursively assign all widgets / dialogues sub widgets to None. So I'll just try to stay away from this pyqt release and stick with older or newer ones. From gherron at islandtraining.com Mon Aug 16 03:29:26 2010 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 16 Aug 2010 00:29:26 -0700 Subject: errors and exception In-Reply-To: References: Message-ID: <4C68E8D6.2060908@islandtraining.com> On 08/16/2010 12:06 AM, Alan wrote: > Hello, > > I am using things like: > except Exception as inst: > and The old syntax for exceptions still works in Python2.x (all versions). The new syntax works in Python2.6+ and Python3. try: whatever except Exception,msg: # Old syntax print msg > > > with open("myfile.txt") as f: > for line in f: > print line You don't need the new fangled with statement if you want to be compatible with older versions of Python2. (It's nice and convenient, but not necessary.) f = open("myfile.txt") for line in f: print line f.close() # This is what the "with" statement guarantees; so now just do it yourself Gary Herron > Things that seems to be new in python 2.6 and higher, however reading > http://docs.python.org/tutorial/errors.html and this not clear when > this new syntaxes appeared. > > My trouble is that I want to make something similar above compatible > with python 2.5, but when running python2.5 I got: > > except Exception as msg: > ^ > SyntaxError: invalid syntax > If there's a way (e.g. from __future__ ..., inherited modified > Exception class, etc) that could give a solution to keep my code in > python 2.6 syntax as above but compatible with python 2.5, that would > be appreciated. > > Many thanks in advance, > > Alan > -- > Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate > Department of Biochemistry, University of Cambridge. > 80 Tennis Court Road, Cambridge CB2 1GA, UK. > >>http://www.bio.cam.ac.uk/~awd28 << -------------- next part -------------- An HTML attachment was scrubbed... URL: From alf.p.steinbach+usenet at gmail.com Mon Aug 16 03:38:57 2010 From: alf.p.steinbach+usenet at gmail.com (Alf P. Steinbach /Usenet) Date: Mon, 16 Aug 2010 09:38:57 +0200 Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: * Standish P, on 16.08.2010 09:20: > [garble garble] Nonsense article "We look for an exogenous stack" cross-posted to [comp.lang.c], [comp.lang.c++], [comp.theory], [comp.lang.python], [comp.lang.forth]. Please refrain from following up on Standish' article. Cheers, - Alf -- blog at From urban.dani at gmail.com Mon Aug 16 03:40:45 2010 From: urban.dani at gmail.com (Daniel Urban) Date: Mon, 16 Aug 2010 09:40:45 +0200 Subject: errors and exception In-Reply-To: <4C68E8D6.2060908@islandtraining.com> References: <4C68E8D6.2060908@islandtraining.com> Message-ID: > f = open("myfile.txt") > for line in f: > ? print line > f.close()?? # This is what the "with" statement guarantees; so now just do > it yourself Not exactly. More like: f = open("myfile.txt") try: for line in f: print line finally: f.close() Daniel From stefan_ml at behnel.de Mon Aug 16 03:40:47 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 16 Aug 2010 09:40:47 +0200 Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: Standish P, 16.08.2010 09:20: > We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. What's your use case? Stefan From clp2 at rebertia.com Mon Aug 16 03:42:17 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 16 Aug 2010 00:42:17 -0700 Subject: errors and exception In-Reply-To: <4C68E8D6.2060908@islandtraining.com> References: <4C68E8D6.2060908@islandtraining.com> Message-ID: On Mon, Aug 16, 2010 at 12:29 AM, Gary Herron wrote: > On 08/16/2010 12:06 AM, Alan wrote: >> Hello, >> I am using things like: >> with open("myfile.txt") as f: >> for line in f: >> print line > > You don't need the new fangled with statement if you want to be compatible > with older versions of Python2.? (It's nice and convenient, but not > necessary.) > > f = open("myfile.txt") > for line in f: > ? print line > f.close()?? # This is what the "with" statement guarantees; so now just do > it yourself Well, technically the equivalent would be: f = open("myfile.txt") try: for line in f: print line finally: f.close() It's just that the for-loop and print happen to be extremely unlikely to throw exceptions; presumably the OP's actual code is more complex. Cheers, Chris -- http://blog.rebertia.com From nikos.the.gr33k at gmail.com Mon Aug 16 03:45:59 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 16 Aug 2010 00:45:59 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> Message-ID: <69045ba4-f4cf-4426-abfd-8d5bd81b99d5@c10g2000yqi.googlegroups.com> On 10 ???, 01:43, MRAB wrote: > ????? wrote: > > D:\>convert.py > > ? File "D:\convert.py", line 34 > > SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line > > 34, but no > > ?encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor > > details > > > D:\> > > > What does it refering too? what character cannot be identified? > > > Line 34 is: > > > src_data = src_data.replace( '', '

> color=green> ??????? ??????????: %(counter)d ' ) > > Didn't you say that you're using Python 2.7 now? The default file > encoding will be ASCII, but your file isn't ASCII, it contains Greek > letters. Add the encoding line: > > ? ? ?# -*- coding: utf-8 -*- > > and check that the file is saved as UTF-8. > > > Also, > > > for currdir, files, dirs in os.walk('test'): > > > ? ?for f in files: sctually its for currdir, dirs, filesin os.walk('test'): thats whay ti couldnt run!! :-) After changifn this and made some other modification my convertion script finally run! Here it is for someone that might want a similar functionality. ====================================================================== #!/usr/bin/python # -*- coding: utf-8 -*- import re, os, sys count = 520 for currdir, dirs, files in os.walk('d:\\akis'): for f in files: if f.lower().endswith("php"): # get abs path to filename src_f = os.path.join(currdir, f) # open php src file f = open(src_f, 'r') src_data = f.read() f.close() # Grab the id number contained within the php code and insert it above all other data found = re.search( r'PageID = (\d+)', src_data ) if found: id = found.group(1) else: id = count =+ 1 src_data = ( '\n\n' % id ) + src_data # replace php tags and contents within src_data = re.sub( r'(?s)<\?(.*?)\?>', '', src_data ) # add template variables src_data = src_data.replace( '', '

??????? ??????????: %(counter)d ' ) # open same php file for storing modified data f = open(src_f, 'w') f.write(src_data) f.close() # rename edited .php file to .html extension dst_f = src_f.replace('.php', '.html') os.rename( src_f, dst_f ) print ( "renaming: %s => %s\n" % (src_f, dst_f) ) From nick_keighley_nospam at hotmail.com Mon Aug 16 03:47:44 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Mon, 16 Aug 2010 00:47:44 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> this is heavily x-posted I'm answering from comp.lang.c On 16 Aug, 08:20, Standish P wrote: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? I'm having trouble understanding your question (I read your whole post before replying). I strongly suspect the only connection your question has with C is that you are using C as your implementation language. I think you're trying to ask a question about memory management. You might be better off asking your question in a general programming new group such as comp.programming (sadly rather quiet these days). Note that C doesn't do automatic garbage collection. Memory is either freed on exit from a scope (stack-like memory lifetime) or explicitly (using free()). Static memory is, conceptually, never freed. > Because a stack has push and pop, it is able to release and allocate > memory. I'm not sure what you mean by some of the terms you use. In a sense a pop *is* a release. The memory is no longer available for use. > We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. "exogenous"? Why would you do this? Are you envisioning a stack of pointers? The pointers pointing to dynamically allocated memory? Well, yes, sure you could implement this in C. It isn't garbage collection by any standard definition of the term. > The algorithm using the stack would have to be "perfect" to prevent > stack overflow or condition of infinite recursion depth. the memory lifetimes must be stack-like (or close to stack-like) > This would > involve data type checking to filter out invalid input. I'd be more concerned about the memory allocation/dealllocation pattern rather than the data types. > The task must > be casted in an algorithm that uses the stack. Then the algorithm must > be shown to be heuristically or by its metaphor, to be correct using > informal reasoning. why informal reasoning? Why not formal reasoning? > Are there any standard textbooks or papers that show stacks > implemented in C/C++/Python/Forth with malloc/free in push and pop ? well it doesn't sound very hard... > If Forth is a general processing language based on stack, is it > possible to convert any and all algorithms to stack based ones and > thus avoid memory leaks since a pop automatically releases memory when > free is an intrinsic part of it. don't understand the question. - is forth a general purpose language? Yes - are all algorithms stack based? No some compuations simply need to hang onto memeory for a long time alloc (obj1) alloc (obj2) alloc (obj3) free (obj2) long_computation() free(obj3) free(obj1) this simply isn't stack based. the memory for obj2 cannot be reused on stack based scheme whilst long_computation() is going on. > K&R ANSI has the example of modular programming showing how to > implement a stack but he uses a fixed length array. It is also > possibly an endogenous stack. We look for an exogenous stack so that > element size can vary. malloc the memory? I see no garbage collection in your post From downaold at gmail.com Mon Aug 16 04:23:52 2010 From: downaold at gmail.com (Roald de Vries) Date: Mon, 16 Aug 2010 10:23:52 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Message-ID: <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> On Aug 15, 2010, at 11:51 PM, Ian Kelly wrote: > On Sun, Aug 15, 2010 at 4:36 PM, Baba wrote: >> Hi Mel, >> >> indeed i thought of generalising the theorem as follows: >> If it is possible to buy n, n+1,?, n+(x-1) sets of McNuggets, for >> some >> x, then it is possible to buy any number of McNuggets >= x, given >> that >> McNuggets come in x, y and z packs. >> >> so with diophantine_nuggets(7,10,21) i would need 7 passes >> result:53 >> >> but with (10,20,30) and 10 passes i get no result > > You're on the right track. In the case of (10,20,30) there is no > largest exactly purchasable quantity. Any quantity that does not end > with a 0 will not be exactly purchasable. > > I suspect that there exists a largest unpurchasable quantity iff at > least two of the pack quantities are relatively prime, but I have made > no attempt to prove this. That for sure is not correct; packs of 2, 4 and 7 do have a largest unpurchasable quantity. I'm pretty sure that if there's no common divisor for all three (or more) packages (except one), there is a largest unpurchasable quantity. That is: ? i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x| y) means "x is no divider of y" Cheers, Roald From stndshp at gmail.com Mon Aug 16 04:33:51 2010 From: stndshp at gmail.com (Standish P) Date: Mon, 16 Aug 2010 01:33:51 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> Message-ID: On Aug 16, 12:47?am, Nick Keighley wrote: > this is heavily x-posted I'm answering from comp.lang.c > > On 16 Aug, 08:20, Standish P wrote: > > > [Q] How far can stack [LIFO] solve do automatic garbage collection and > > prevent memory leak ? > > I'm having trouble understanding your question (I read your whole post > before replying). I strongly suspect the only connection your question > has with C is that you are using C as your implementation language. I > think you're trying to ask a question about memory management. You > might be better off asking your question in a general programming new > group such as comp.programming (sadly rather quiet these days). > > Note that C doesn't do automatic garbage collection. Memory is either > freed on exit from a scope (stack-like memory lifetime) or explicitly > (using free()). Static memory is, conceptually, never freed. > > > Because a stack has push and pop, it is able to release and allocate > > memory. > > I'm not sure what you mean by some of the terms you use. In a sense a > pop *is* a release. The memory is no longer available for use. > > > We envisage an exogenous stack which has malloc() associated > > with a push and free() associated with a pop. > > "exogenous"? Why would you do this? Are you envisioning a stack of > pointers? The pointers pointing to dynamically allocated memory? Well, > yes, sure you could implement this in C. It isn't garbage collection > by any standard definition of the term. I can clarify what I mean. Most books implement a stack with a fixed length array of chars and push chars into it, for eg k&r. I have a dynamically allocated array of pointers. The cons cell is allocated as well as the data is allocated for every push and the pointer points to its_curr_val.next. Similarly, every pop would move the pointer to its_curr_val.prev. It would also free the cons cell and the data after making a copy of the data. Below I explain your point on memory hanging. > > The algorithm using the stack would have to be "perfect" to prevent > > stack overflow or condition of infinite recursion depth. > > the memory lifetimes must be stack-like (or close to stack-like) > > > This would > > involve data type checking to filter out invalid input. > > I'd be more concerned about the memory allocation/dealllocation > pattern rather than the data types. > > > The task must > > be casted in an algorithm that uses the stack. Then the algorithm must > > be shown to be heuristically or by its metaphor, to be correct using > > informal reasoning. > > why informal reasoning? Why not formal reasoning? > > > Are there any standard textbooks or papers that show stacks > > implemented in C/C++/Python/Forth with malloc/free in push and pop ? > > well it doesn't sound very hard... > > > If Forth is a general processing language based on stack, is it > > possible to convert any and all algorithms to stack based ones and > > thus avoid memory leaks since a pop automatically releases memory when > > free is an intrinsic part of it. > > don't understand the question. > > ? ?- is forth a general purpose language? Yes > ? ?- are all algorithms stack based? No Does Forth uses stack for all algorithms ? Does it use pointers , ie indirect addressing ? If it can/must use stack then every algorithm could be made stack based. > some compuations simply need to hang onto memeory for a long time > > ? ? alloc (obj1) > ? ? alloc (obj2) > ? ? alloc (obj3) > > ? ? free (obj2) > ? ? long_computation() > ? ? free(obj3) > ? ? free(obj1) > > this simply isn't stack based. the memory for obj2 cannot be reused on > stack based scheme whilst long_computation() is going on. In theory the memory can be locked by a long_computation() . But a non- stacked based algorithm can also ignore freeing a memory and cause memory leak, just as an improper usage of stack cause the above problem. The purpose of a stack is to hold intermediate results ONLY. Only intermediate results should be below the long_computation, not those that need not wait for it. That is why heuristic or metaphorical thinking which considers all aspects simultaneously in a visual human brain thinking has less chance of error in conceiving such solutions than formal disjoint and symbolic thought. > > K&R ANSI has the example of modular programming showing how to > > implement a stack but he uses a fixed length array. It is also > > possibly an endogenous stack. We look for an exogenous stack so that > > element size can vary. > > malloc the memory? I see no garbage collection in your post a stack properly used does not need separate garbage collection. freeing is an automatic part of calling pop. Thats the superiority of a stack based algorithm over linked lists of unrestricted kinds. ======= Standish P From mahaboobnisha at gmail.com Mon Aug 16 04:45:03 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Mon, 16 Aug 2010 01:45:03 -0700 (PDT) Subject: comp.lang.python Message-ID: <2eda16fd-857f-4fe0-8402-89e52682888c@i4g2000prf.googlegroups.com> www.127760.blogspot.com From darragh.ssa at gmail.com Mon Aug 16 04:52:52 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 16 Aug 2010 01:52:52 -0700 (PDT) Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> Message-ID: <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> I still keep getting more downloads then usual which is awesome, but I still don't get any kind of response! please mail me or reply to this post with what you think, You can tell me that the program sucks but if you want to, do it in such a way that you also describe what exactly is the problem and not just say "the total" I really need some response because I'm working on version 0.2.1 and I want to know what there should be changed/added From nick_keighley_nospam at hotmail.com Mon Aug 16 05:25:06 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Mon, 16 Aug 2010 02:25:06 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> Message-ID: On 16 Aug, 09:33, Standish P wrote: > On Aug 16, 12:47?am, Nick Keighley > > On 16 Aug, 08:20, Standish P wrote: this is heavily x-posted I'm answering from comp.lang.c I also note that another poster has suggested you are a troll/loon you seem to be using some computer science-like terms but in an oddly non-standard manner > > > [Q] How far can stack [LIFO] solve do automatic garbage collection and > > > prevent memory leak ? no at all. How can a goldfish whistle? > > I'm having trouble understanding your question (I read your whole post > > before replying). I strongly suspect the only connection your question > > has with C is that you are using C as your implementation language. I > > think you're trying to ask a question about memory management. You > > might be better off asking your question in a general programming new > > group such as comp.programming (sadly rather quiet these days). this still applies > > Note that C doesn't do automatic garbage collection. Memory is either > > freed on exit from a scope (stack-like memory lifetime) or explicitly > > (using free()). Static memory is, conceptually, never freed. > > > > Because a stack has push and pop, it is able to release and allocate > > > memory. > > > I'm not sure what you mean by some of the terms you use. In a sense a > > pop *is* a release. The memory is no longer available for use. > > > > We envisage an exogenous stack which has malloc() associated > > > with a push and free() associated with a pop. > > > "exogenous"? Why would you do this? Are you envisioning a stack of > > pointers? The pointers pointing to dynamically allocated memory? Well, > > yes, sure you could implement this in C. It isn't garbage collection > > by any standard definition of the term. > > I can clarify what I mean. > > Most books implement a stack with a fixed length array of chars and > push chars into it, for eg k&r. this isn't inherent to a stack implementaion. A stack could be a malloced block of memory or a linked list. > I have a dynamically allocated array of pointers. The cons cell is that *what*? Are you trying to implement Lisp in C or something. Try comp.lang.lisp for some help there. Have you read "Lisp In Small Pieces"? Good fun. > allocated as well as the data is allocated for every push and the > pointer points to its_curr_val.next. I'm lost. What does a cons cell have to do with a fixed array of pointers? Why do you need dynamic memory? Aren't cons cells usually of fixed size? How can a Lisp-like language use a stack based memory allocation strategy? > Similarly, every pop would move the pointer to its_curr_val.prev. It > would also free the cons cell and the data after making a copy of the > data. Below I explain your point on memory hanging. > > > > The algorithm using the stack would have to be "perfect" to prevent > > > stack overflow or condition of infinite recursion depth. > > > the memory lifetimes must be stack-like (or close to stack-like) > > > > This would > > > involve data type checking to filter out invalid input. > > > I'd be more concerned about the memory allocation/dealllocation > > pattern rather than the data types. > > > > The task must > > > be casted in an algorithm that uses the stack. Then the algorithm must > > > be shown to be heuristically or by its metaphor, to be correct using > > > informal reasoning. > > > why informal reasoning? Why not formal reasoning? > > > > Are there any standard textbooks or papers that show stacks > > > implemented in C/C++/Python/Forth with malloc/free in push and pop ? > > > well it doesn't sound very hard... > > > > If Forth is a general processing language based on stack, is it > > > possible to convert any and all algorithms to stack based ones and > > > thus avoid memory leaks since a pop automatically releases memory when > > > free is an intrinsic part of it. > > > don't understand the question. > > > ? ?- is forth a general purpose language? Yes > > ? ?- are all algorithms stack based? No > > Does Forth uses stack for all algorithms ? don't know. Ask the Forth people. Some algoritms are fundamentally not stack based. If you try to implement them in Forth then either some memory isn't claimed as soon as possible (a leak) or there is some way to to have non-stack based memory management. > Does it use pointers , ie > indirect addressing ? If it can/must use stack then every algorithm > could be made stack based. > > > some compuations simply need to hang onto memeory for a long time > > > ? ? alloc (obj1) > > ? ? alloc (obj2) > > ? ? alloc (obj3) > > > ? ? free (obj2) > > ? ? long_computation() > > ? ? free(obj3) > > ? ? free(obj1) > > > this simply isn't stack based. the memory for obj2 cannot be reused on > > stack based scheme whilst long_computation() is going on. > > In theory the memory can be locked by a long_computation(). But a non- > stacked based algorithm can also ignore freeing a memory and cause > memory leak, just as an improper usage of stack cause the above > problem. The purpose of a stack is to hold intermediate results ONLY. no not really > Only intermediate results should be below the long_computation, not > those that need not wait for it. then you don't have stack-based memory allocation. Make your mind up. > That is why heuristic or metaphorical > thinking which considers all aspects simultaneously in a visual human > brain thinking has less chance of error in conceiving such solutions > than formal disjoint and symbolic thought. sorry, I thought we were talking about computer programming not hippy crustal healing. > > > K&R ANSI has the example of modular programming showing how to > > > implement a stack but he uses a fixed length array. It is also > > > possibly an endogenous stack. We look for an exogenous stack so that > > > element size can vary. > > > malloc the memory? I see no garbage collection in your post > > a stack properly used does not need separate garbage collection. > freeing is an automatic part of calling pop. > > Thats the superiority of a stack based algorithm over linked lists of > unrestricted kinds. and also its weakness. From egbert.bouwman at xs4all.nl Mon Aug 16 05:44:56 2010 From: egbert.bouwman at xs4all.nl (Egbert Bouwman) Date: Mon, 16 Aug 2010 11:44:56 +0200 Subject: When the first line of a file tells something about the other lines Message-ID: <1281951896.4744.2.camel@para.lan> Often the first line of a file tells how to read or interpret the other lines. Depending on the result, you then have to ... - skip the first line, or - treat the first line in another special way, or - treat the first line in the same way as the other lines. I can handle this by opening the file twice, the first time for reading the first line only. I suppose there exists a more elegant solution. Below is the structure of what I do now. Please comment. f = open(file_name,"r") # eerste opening file_line = f.readline() special = True if some_condition else False f.close() f = open(file_name,"r") # tweede opening if not special: # use first line, read previously stripped_line = file_line.strip() else: # skip first file_line, or treat in another special way: f.next() # read other lines: for file_line in f: stripped_line = file_line.strip() # now do something with stripped_line f.close() egbert -- Egbert Bouwman Keizersgracht 197-II 1016 DS Amsterdam Tel 0(031)20 6257991 From __peter__ at web.de Mon Aug 16 05:59:57 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Aug 2010 11:59:57 +0200 Subject: When the first line of a file tells something about the other lines References: Message-ID: Egbert Bouwman wrote: > Often the first line of a file tells how to read or interpret the other > lines. > Depending on the result, you then have to ... > - skip the first line, or > - treat the first line in another special way, or > - treat the first line in the same way as the other lines. > > I can handle this by opening the file twice, > the first time for reading the first line only. > I suppose there exists a more elegant solution. > Below is the structure of what I do now. > Please comment. > > f = open(file_name,"r") # eerste opening > file_line = f.readline() > special = True if some_condition else False > f.close() > > f = open(file_name,"r") # tweede opening > if not special: > # use first line, read previously > stripped_line = file_line.strip() > else: > # skip first file_line, or treat in another special way: > f.next() > # read other lines: > for file_line in f: > stripped_line = file_line.strip() > # now do something with stripped_line > f.close() with open(filename) as lines: first_line = next(lines, "") if special(first_line): # ... else: lines = itertools.chain([first_line], lines) for line in lines: # ... From prologic at shortcircuit.net.au Mon Aug 16 06:01:36 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 16 Aug 2010 20:01:36 +1000 Subject: GSM to ISO / UCS2 to ISO Message-ID: HI all, In an effort to avoid re-inventing the wheel so to speak I was wondering if anyone's come across libraries/tools, etc that achieve the same kind of functionality as the tools library in this java app. http://code.google.com/p/ipddump/source/browse/trunk/src/ipddump/tools/Gsm2Iso.java Thanks, cheers James -- -- James Mills -- -- "Problems are solved by method" From flebber.crue at gmail.com Mon Aug 16 06:11:24 2010 From: flebber.crue at gmail.com (flebber) Date: Mon, 16 Aug 2010 03:11:24 -0700 (PDT) Subject: Python XML and tables using math References: <81a2406a-af83-4904-ae26-a41bc626fe0e@u31g2000pru.googlegroups.com> Message-ID: On Aug 16, 4:00?pm, Stefan Behnel wrote: > flebber, 16.08.2010 05:30: > > > I am looking at a project that will import and modify an XML file and > > then export it to a table. Currently a flat file table system should > > be fine. > > > I want to export the modified data to the table and then perform a > > handful of maths(largely simple statistical functions) to the data and > > then print out the resultant modified tables. > > > I was planning on using Python 2.7 for the project. > > > Has anyone used a guide to acheive something similar? I would like to > > read up on it so I can assess my options and best methods, any hints > > or tips? > > That can usually be done in a couple of lines in Python. The approach I > keep recommending is to use cElementTree (in the stdlib), potentially its > iterparse() function if the file is too large to easily fit into memory, > but the code won't change much either way. > > You might want to skip through this list a bit, similar questions have been > coming up every couple of weeks. The responses often include mostly > complete implementations that you can borrow from. > > Stefan okay I found http://effbot.org/zone/celementtree.htm so I will have a read through there. I have been creating an every expanding macro/VBA project in Excel and due to slightly changin source document - the header order changes - it causes the project to crash out. I was hoping python and XML may be a bit more robust. From praveen.python.plone at gmail.com Mon Aug 16 06:17:06 2010 From: praveen.python.plone at gmail.com (Praveen) Date: Mon, 16 Aug 2010 03:17:06 -0700 (PDT) Subject: text to DB References: Message-ID: <86b95d78-fd4f-4ac0-8712-db77b749bff1@h40g2000pro.googlegroups.com> On Aug 14, 11:15?am, Dennis Lee Bieber wrote: > On Fri, 13 Aug 2010 09:46:34 -0700 (PDT), Praveen > declaimed the following in > gmane.comp.python.general: > > > I have a text file in this format > > PRA 1:13 2:20 3:5 > > SRA 1:45 2:75 3:9 > > TRA 1:2 2:65 3:45 > > > pattern is- Book Chapter:Verses > > > now i have my DB schema like this > > book_id ? ? ? ? ? ?chapter_id ? ? ? versed_id > > ? ? ? ? Off hand, I'd say that's an incomplete schema since there is not > enough information available to reconstruct the input data... > > ? ? ? ? I'd say there should be a second relation containing > > book_id book_name > > > > > could any one give me suggestion > > ? ? ? ? Is there a possibility that a given book "name" can appear multiple > times? > > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ f = open("/Users/Trellisys/Desktop//BibleDB/Booktable.txt","r") bk=[] cv = [] j=1 d={} for line in f: for l in line.split(): if l.isalnum(): bk.append(j) j = j+1 else: cv.append(l.split(":")) '''for i in l.split(":"): if i.isalpha(): #print i,j j = j+1 else: #print i''' print bk print cv output [1,2,3] but i am not getting how to map chapterId and versesId with bookId Regards, Praveen From bieffe62 at gmail.com Mon Aug 16 06:46:07 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Mon, 16 Aug 2010 03:46:07 -0700 (PDT) Subject: Comparing lists Message-ID: <5f89432d-47a0-405f-9601-7f04a7818248@c10g2000yqi.googlegroups.com> Hi all, anybody can point me to a description of how the default comparison of list objects (or other iterables) works? Apparently l1 < l2 is equivalent to all ( x < y for x,y in zip( l1, l2) ), has is shown in the following tests, but I can't find it described anywhere: >>> [1,2,3] < [1,3,2] True >>> [1,2,3] < [1,2,4] True >>> [1,2,3] < [2,2,3] True >>> [1,2,3] < [0,1,3] False >>> [1,2,3] < [0,2,3] False >>> [1,2,3] < [1,1,3] False >>> [1,2,3] < [1,2,2] False Ciao --- FB From nikos.the.gr33k at gmail.com Mon Aug 16 06:57:58 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 16 Aug 2010 03:57:58 -0700 (PDT) Subject: Problem checking an existing browser cookie Message-ID: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> # initialize cookie cookie = Cookie.SimpleCookie() cookie.load( os.environ.get('HTTP_COOKIE', '') ) mycookie = cookie.get('visitor') if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| yandex|13448|spider|crawl)', host ) is None: blabla... ======================== I checked and Chrome has a cookie names visitor with a value of nikos within. So, i have to ask why the if fails? Thank you. From efotinis at oohay.com Mon Aug 16 07:06:30 2010 From: efotinis at oohay.com (eliasf) Date: Mon, 16 Aug 2010 14:06:30 +0300 Subject: Comparing lists References: <5f89432d-47a0-405f-9601-7f04a7818248@c10g2000yqi.googlegroups.com> Message-ID: On Mon, 16 Aug 2010 13:46:07 +0300, Francesco Bochicchio wrote: > anybody can point me to a description of how the default comparison of > list objects (or other iterables) works? Sequences of the same type are compared using lexicographical ordering: http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types From hnsri49 at gmail.com Mon Aug 16 07:07:52 2010 From: hnsri49 at gmail.com (srinivas hn) Date: Mon, 16 Aug 2010 17:07:52 +0600 Subject: MS Word Document to html conversion Message-ID: Hi, I am working on application where it requires uploaded document from has to be converted to the html pages.Am searching for the suitable python package i dint found any thing apart from word2html.py.But the word2html.py is not available for download anywhere can any one suggest me how to solve this problem. Thanks in advance Srinivas HN -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:13:17 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:13:17 GMT Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> Message-ID: <4c691d4c$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 01:52:52 -0700, Kruptein wrote: > I still keep getting more downloads then usual which is awesome, but I > still don't get any kind of response! Welcome to the real world. For every user who sends you an email, you'll probably have 1000 who don't. Or 10,000. > please mail me or reply to this > post with what you think, You can tell me that the program sucks but if > you want to, do it in such a way that you also describe what exactly is > the problem and not just say "the total" You've asked for feedback at least three times now. It's probably time to stop hassling people. When you have another release ready, then you can ask again. Until then, be grateful that people are at least downloading it! > I really need some response because I'm working on version 0.2.1 and I > want to know what there should be changed/added If nobody asks for any changes, then just keep doing what you're doing. -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:17:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:17:11 GMT Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: <4c691e37$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 16:28:46 +1200, Lawrence D'Oliveiro wrote: > In message <8crg0eFfbkU1 at mid.individual.net>, Gregory Ewing wrote: > >> For example, the constant term of a polynomial is usually called term >> 0, not term 1. > > That is not some kind of ordinal numbering of the terms, that is the > power of the variable involved. > > And polynomials can have negative powers, too. Not so. Polynomials, by definition, are limited to non-negative integer powers. You're thinking of a "polynomial quotient", otherwise known as a "rational function". http://mathworld.wolfram.com/Polynomial.html -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:18:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:18:11 GMT Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: <4c691e73$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 21:01:04 -0700, Carey Tilden wrote: > On Sun, Aug 15, 2010 at 6:43 PM, bvdp wrote: > >> Not to belabor the point .. but "func" is not a standard lib module. >> It's part of a much larger application ... and in that application it >> makes perfect sense to terminate the application if it encounters an >> error. I fail to see the problem with this. Why would an APPLICATION >> raise a error or not exit to the system? > > For me, the main reason is to ensure the application has only one exit > point. There's only one spot to maintain the code for closing files, > cleaning up network connections, displaying errors to the user, etc. You mean all the things that Python's garbage collector already does for you? *wink* -- Steven From malcolm.mclean5 at btinternet.com Mon Aug 16 07:20:22 2010 From: malcolm.mclean5 at btinternet.com (Malcolm McLean) Date: Mon, 16 Aug 2010 04:20:22 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <93c048b8-013d-425f-ac69-c112f12ddaa3@v41g2000yqv.googlegroups.com> On Aug 16, 10:20?am, Standish P wrote: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? > Most programs can be written so that most of their memory allocations are matched by destructors at the same level. However the allocations that can't be written this way typically tend to be the small frequently-called ones used for nodes in dynamic graph objects, or small resizeable buffers to hold strings and the like. This is where you get the performance hit with repeated calls to malloc() and free(). So generally it's not worthwhile writing a stack allocator for a normal program. That's not to say there aren't a few individual cases where it can help performance. (See the chapter "Memory games" in my book Basic Agorithms for details about memory allocation strategies). From __peter__ at web.de Mon Aug 16 07:22:28 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Aug 2010 13:22:28 +0200 Subject: Comparing lists References: <5f89432d-47a0-405f-9601-7f04a7818248@c10g2000yqi.googlegroups.com> Message-ID: Francesco Bochicchio wrote: > Hi all, > > anybody can point me to a description of how the default comparison of > list objects (or other iterables) works? > > Apparently l1 < l2 is equivalent to all ( x < y for x,y in > zip( l1, l2) ), has is shown in the following tests, but I can't find > it described anywhere: > >>>> [1,2,3] < [1,3,2] > True >>>> [1,2,3] < [1,2,4] > True >>>> [1,2,3] < [2,2,3] > True >>>> [1,2,3] < [0,1,3] > False >>>> [1,2,3] < [0,2,3] > False >>>> [1,2,3] < [1,1,3] > False >>>> [1,2,3] < [1,2,2] > False > > > Ciao > --- > FB Quoting http://docs.python.org/reference/expressions.html """ Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length. If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]). """ From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:23:02 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:23:02 GMT Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> Message-ID: <4c691f96$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 17:36:07 -0700, Alex Willmer wrote: > On Aug 16, 1:07?am, Steven D'Aprano cybersource.com.au> wrote: >> You're passing re.IGNORECASE (which happens to equal 2) as a count >> argument, not as a flag. Try this instead: >> >> >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) >> 'Python27' > > Basically right, but in-line flags must be placed at the start of a > pattern, or the result is undefined. Pardon me, but that's clearly not correct, as proven by the fact that the above example works. You can say that the flags *should* go at the start, for the sake of efficiency, or ease of comprehension, or tradition, or to appease the Regex Cops who roam the streets beating up those who don't write regexes in the approved fashion. But it isn't true that they *must* go at the front. -- Steven From martin at address-in-sig.invalid Mon Aug 16 07:25:20 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Mon, 16 Aug 2010 11:25:20 +0000 (UTC) Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: On Mon, 16 Aug 2010 12:33:51 +1200, Gregory Ewing wrote: > Ian Kelly wrote: >> On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie >> wrote: > >>> real sample[-500:750]; > >> Ugh, no. The ability to change the minimum index is evil. > > Not always; it can have its uses, particularly when you're using the > array as a mapping rather than a collection. > Say you have intensity data captured from an X-ray goniometer from 160 degrees to 30 degrees at 0.01 degree resolution. Which is most evil of the following? 1) real intensity[16000:3000] for i from lwb intensity to upb intensity plot(i/100, intensity[i]); 2) double angle[13000]; double intensity[13000]; for (int i = 0; i < 13000; i++) plot(angle[i], intensity[i]); 3) struct { double angle; double intensity } measurement; measurement m[13000]; for (int i = 0; i < 13000; i++) plot(m[i].angle, m[i].intensity); 4) double intensity[13000]; for (int i = 0; i < 13000; i++) plot((16000 - i)/100, intensity[i]) To my mind (1) is much clearer to read and far less error-prone to write, while zero-based indexing forces you to use code like (2), (3) or (4), all of which obscure rather than clarify what the program is doing. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From __peter__ at web.de Mon Aug 16 07:26:09 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Aug 2010 13:26:09 +0200 Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> <4c691d4c$0$11100$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 16 Aug 2010 01:52:52 -0700, Kruptein wrote: > >> I still keep getting more downloads then usual which is awesome, but I >> still don't get any kind of response! > > Welcome to the real world. For every user who sends you an email, you'll > probably have 1000 who don't. Or 10,000. > > >> please mail me or reply to this >> post with what you think, You can tell me that the program sucks but if >> you want to, do it in such a way that you also describe what exactly is >> the problem and not just say "the total" > > You've asked for feedback at least three times now. It's probably time to > stop hassling people. When you have another release ready, then you can > ask again. Until then, be grateful that people are at least downloading > it! > > >> I really need some response because I'm working on version 0.2.1 and I >> want to know what there should be changed/added > > If nobody asks for any changes, then just keep doing what you're doing. Or you can introduce a bug; if your users don't start complaining you don't have any... Peter From __peter__ at web.de Mon Aug 16 07:31:31 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Aug 2010 13:31:31 +0200 Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> Message-ID: ????? wrote: > # initialize cookie > cookie = Cookie.SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > mycookie = cookie.get('visitor') > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > yandex|13448|spider|crawl)', host ) is None: > blabla... > ======================== > > I checked and Chrome has a cookie names visitor with a value of nikos > within. > So, i have to ask why the if fails? Maybe it's because != != == From nadiasvertex at gmail.com Mon Aug 16 07:40:12 2010 From: nadiasvertex at gmail.com (Christopher) Date: Mon, 16 Aug 2010 04:40:12 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> Message-ID: <0e5c2967-e617-4423-a0ee-675d76c8cb47@l6g2000yqb.googlegroups.com> On Aug 15, 8:07?pm, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 16:45:49 -0700, Christopher wrote: > > I have the following problem: > > >>>> t="Python26" > >>>> import re > >>>> re.sub(r"python\d\d", "Python27", t) > > 'Python26' > >>>> re.sub(r"python\d\d", "Python27", t, re.IGNORECASE) > > 'Python26' > >>>> re.sub(r"Python\d\d", "Python27", t, re.IGNORECASE) > > 'Python27' > > Is this a known bug? ?Is it by design for some odd reason? > >>> help(re.sub) > > Help on function sub in module re: > > ? ? sub(pattern, repl, string, count=0) > ? ? ... > > You're passing re.IGNORECASE (which happens to equal 2) as a count > argument, not as a flag. Try this instead: > > >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) > > 'Python27' > Thanks. Somehow I didn't notice that other argument after looking at it a million times. :-) From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:44:06 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:44:06 GMT Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: <4c692485$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 18:43:49 -0700, bvdp wrote: [...] > However, I have gotten hit with more than one comment like yours. So, > could you please clarify? Is it bad form to exit an application with > sys.exit(1) when an error in a file the application is processing is > found? My two cents worth... The distinction I like to make is between *planned* and *unplanned* exits. Planned exits are things like the user choosing Quit from the menu, or a command line tool exiting after printing a usage message. "Exit the application" is part of the application's user interface, and therefore it is appropriate to exit the application. These aren't errors, the exception isn't called "SystemError" but SystemExit, and it's not necessary to print a traceback. Such exits should usually only exist in the front-end (user-interface) code, rarely or never in the back-end. But *unplanned* exits are errors, and so you should not disguise them as planned exits by raising SystemExit, any more than you would disguise them as a keyboard interruption by raising KeyboardInterrupt. Raise an appropriate exception, and let Python's normal exception-handling code clean up and exit for you. I make one more design choice: if there's an unrecoverable error in user input (as opposed unexpectedly bad data or a program bug), I suppress the traceback, but any other unrecoverable error, I allow it to print. Something vaguely like this: if __name__ == '__main__': try: main() except getopt.GetoptError, e: # Unrecoverable error in command line options. print e.args[0] sys.exit(42) # or whatever value is appropriate except Exception, e: log_exception(e) # whatever... raise SystemExit won't be caught, and will just exit normally. Any other exception won't be caught either, but will lead to a traceback. -- Steven From jeanmichel at sequans.com Mon Aug 16 07:48:48 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 16 Aug 2010 13:48:48 +0200 Subject: Dump logging configuration In-Reply-To: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> References: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> Message-ID: <4C6925A0.8090701@sequans.com> Kxepal wrote: > Hi all! > Sorry for dumb question if it is - I'd tried to google it before but > have found nothing. > > Is there any way to dump current logging configuration for future > loading it via fileConfig/dictConfig? > I may be wrong but I don't think so. JM From cournape at gmail.com Mon Aug 16 07:54:21 2010 From: cournape at gmail.com (David Cournapeau) Date: Mon, 16 Aug 2010 20:54:21 +0900 Subject: Python "why" questions In-Reply-To: <8crg0eFfbkU1@mid.individual.net> References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing wrote: >> On Aug 7, 2010, at 9:14 PM, John Nagle wrote: >> >>> ?The languages which have real multidimensional arrays, rather >>> than arrays of arrays, tend to use 1-based subscripts. ?That >>> reflects standard practice in mathematics. > > Not always -- mathematicians use whatever starting index is > most convenient for the problem at hand. Yes, there are many engineering fields where index starts at 0. Partly for the reason you have stated concerning polynomials, especially since this extend to series, which are pervasive in numerical computing. In linear algebra, though, I remember to have always noted matrices indexes in the [1,n] range, not [0,n-1]. In general, I suspect this is much more a tradition than any kind of very reasoned thinking (and conversely, I find most arguments for 0-indexing and against one-indexing rather ... unconvincing. What's awkward is when you have to constantly change from one to the other). cheers, David From jah.alarm at gmail.com Mon Aug 16 08:05:34 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Mon, 16 Aug 2010 05:05:34 -0700 (PDT) Subject: Textvariable display in label (GUI design) Message-ID: <993d9560-564d-47f0-b2db-6f0c6404ae81@g6g2000pro.googlegroups.com> hi, pls help me out with the following issue: I wrote a function that uses a for loop that changes a value of a certain variable each iteration. What I want is by clicking a button in GUI (with the command bound to this function) this value each iteration is displayed in a textbox (label). So far only one (starting value) is displayed. thanks, Alex From spinoza1111 at yahoo.com Mon Aug 16 08:08:00 2010 From: spinoza1111 at yahoo.com (spinoza1111) Date: Mon, 16 Aug 2010 05:08:00 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: On Aug 16, 3:20?pm, Standish P wrote: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? > > Because a stack has push and pop, it is able to release and allocate > memory. We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. > > The algorithm using the stack would have to be "perfect" to prevent > stack overflow or condition of infinite recursion depth. This would > involve data type checking to filter out invalid input. The task must > be casted in an algorithm that uses the stack. Then the algorithm must > be shown to be heuristically or by its metaphor, to be correct using > informal reasoning. > > Are there any standard textbooks or papers that show stacks > implemented in C/C++/Python/Forth with malloc/free in push and pop ? > If Forth is a general processing language based on stack, is it > possible to convert any and all algorithms to stack based ones and > thus avoid memory leaks since a pop automatically releases memory when > free is an intrinsic part of it. > > K&R ANSI has the example of modular programming showing how to > implement a stack but he uses a fixed length array. It is also > possibly an endogenous stack. We look for an exogenous stack so that > element size can vary. > > ======= > Standish P Garbage collection doesn't use a stack. It uses a "heap", which is in the abstract a collection of memory blocks of different lengths, divided into two lists, generally represented as linked lists: 1. A list of blocks that are free and may be used to store new data 2. A list of blocks that are in use, or haven't been freed (yet) There is no way you could do memory management of all but the most trivial and fixed-length data chunks using a stack. Sure, you could reserve thousands of bytes on the stack for an array but suppose your language allows arrays to grow or shrink. To keep its property of being adjacent, you'd have to do something horrible such as move unrelated data allocated later, which raises all sorts of security issues, doesn't it. A stack, or something which works like a stack (that is, a stack) is a necessary but not sufficient condition for a working C runtime because C functions can call themselves recursively, whether directly or indirectly. If this last condition did not obtain, each function could give the functions it calls some of its own memory and the called function could save a fixed set of non-stacked general registers in that area; this was in fact the practice on IBM 370 and in assembler language at a time when many "data processing managers" though recursion was a Communist plot. However, data structures of variable size, or data structures that merely take up a lot of space, don't play nice with others on the stack, so, we place their address on the stack and store them in another place, which was named the heap, probably, as a sort of witticism. Gilbert and Sullivan: If anyone anything lacks He'll find it all ready in stacks was wrong, and needs to be brought up to date: You cannot do everything in a stack Unless you code an almighty hack If you're a coding Knight who says, "Neep", You'll probably need to implement a heap A pile a heap of benefits you'll reap If only my advice in your brain you'll keep And avoid memory leaks from which data doth seep By using a well-implemented, well structured, and well-documented Heap! [Chorus of Sailors] We will to heart your advice take, and always use a heap! [Soloist] Oh thank you do To this be true And always my sage advice do keep That you always need to use a heap! From spinoza1111 at yahoo.com Mon Aug 16 08:14:35 2010 From: spinoza1111 at yahoo.com (spinoza1111) Date: Mon, 16 Aug 2010 05:14:35 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <93c048b8-013d-425f-ac69-c112f12ddaa3@v41g2000yqv.googlegroups.com> Message-ID: <7e095f76-b69f-4abe-b5ae-53844972fc6c@g21g2000prn.googlegroups.com> On Aug 16, 7:20?pm, Malcolm McLean wrote: > On Aug 16, 10:20?am, Standish P wrote:> [Q] How far can stack [LIFO] solve do automatic garbage collection and > > prevent memory leak ? > > Most programs can be written so that most of their memory allocations > are matched by destructors at the same level. > > However the allocations that can't be written this way typically tend > to be the small frequently-called ones used for nodes in dynamic graph > objects, or small resizeable buffers to hold strings and the like. > This is where you get the performance hit with repeated calls to > malloc() and free(). > > So generally it's not worthwhile writing a stack allocator for a > normal program. That's not to say there aren't a few individual cases > where it can help performance. (See the chapter "Memory games" in my > book Basic Agorithms for details about memory allocation strategies). Even if it's a troll, it was droll. In a language that of necessity has a runtime stack or something that works like a stack (eg., a stack) one finds that the need for explicit stacks is lessened. For example, in my compiler for [start shameless plug] "Build Your Own .Net Language and Compiler [end shameless plug] I did not need to use an explicit stack to do recursive descent. Instead, I simply called finer grained procedures, passing the compiler state as a parameter, allowing the runtime stack to manage the return. To build an explicit stack in this program would have been folly, for it would have been necessary to either preallocate the stack and thus legislate the maximum complexity of source code, or use a lot of memory management in the pre-existing runtime heap. You didn't tell us you published a book. Can you identify the publisher? From efotinis at oohay.com Mon Aug 16 08:34:07 2010 From: efotinis at oohay.com (eliasf) Date: Mon, 16 Aug 2010 15:34:07 +0300 Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> <4c691d4c$0$11100$c3e8da3@news.astraweb.com> Message-ID: On Mon, 16 Aug 2010 14:26:09 +0300, Peter Otten <__peter__ at web.de> wrote: > Steven D'Aprano wrote: >> If nobody asks for any changes, then just keep doing what you're doing. > Or you can introduce a bug; if your users don't start complaining you don't > have any... Even that doesn't work. They may blog or tweet about it, complain on foreign forums, and set up petitions about it, but they will never, EVER send you an email. It's very disheartening. From alex at moreati.org.uk Mon Aug 16 08:46:17 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Mon, 16 Aug 2010 05:46:17 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> <4c691f96$0$11100$c3e8da3@news.astraweb.com> Message-ID: On Aug 16, 12:23?pm, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 17:36:07 -0700, Alex Willmer wrote: > > On Aug 16, 1:07?am, Steven D'Aprano > cybersource.com.au> wrote: > >> You're passing re.IGNORECASE (which happens to equal 2) as a count > >> argument, not as a flag. Try this instead: > > >> >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) > >> 'Python27' > > > Basically right, but in-line flags must be placed at the start of a > > pattern, or the result is undefined. > > Pardon me, but that's clearly not correct, as proven by the fact that the > above example works. Undefined includes 'might work sometimes'. I refer you to the Python documentation: "Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined." http://docs.python.org/library/re.html#regular-expression-syntax From neilc at norwich.edu Mon Aug 16 09:21:02 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 16 Aug 2010 13:21:02 GMT Subject: Python "why" questions References: <4c681161$0$1624$742ec2ed@news.sonic.net> Message-ID: <8css9uFn0pU1@mid.individual.net> On 2010-08-15, John Nagle wrote: > In retrospect, C's "pointer=array" concept was a terrible > mistake. C arrays are not pointers. -- Neil Cerutti From alex at moreati.org.uk Mon Aug 16 09:33:31 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Mon, 16 Aug 2010 06:33:31 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> <4c691f96$0$11100$c3e8da3@news.astraweb.com> Message-ID: <56d68b7b-ff6b-4fe8-88c7-a1b68bf0df76@c10g2000yqi.googlegroups.com> On Aug 16, 1:46?pm, Alex Willmer wrote: > "Note that the (?x) flag changes how the expression is parsed. It > should be used first in the expression string, or after one or more > whitespace characters. If there are non-whitespace characters before > the flag, the results are undefined. > "http://docs.python.org/library/re.html#regular-expression-syntax Hmm, I found a lot of instances that place (?iLmsux) after non- whitespace characters http://google.com/codesearch?hl=en&lr=&q=file:\.py[w]%3F$+[^[:space:]%22']%2B\(\%3F[iLmsux]%2B\) including two from the Python unit tests, re_test.py lines 109-110. Perhaps the documentation is overly cautious.. From r.koebler at yahoo.de Mon Aug 16 09:38:14 2010 From: r.koebler at yahoo.de (Roland Koebler) Date: Mon, 16 Aug 2010 15:38:14 +0200 Subject: Simple Python Sandbox In-Reply-To: <4C6756D3.60205@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <20100814232400.GA5205@localhost> <4C6756D3.60205@ixokai.io> Message-ID: <20100816133814.GA22789@localhost> On Sat, Aug 14, 2010 at 07:54:11PM -0700, Stephen Hansen wrote: > How are you implementing refusing-names-beginning-with-underscore, out > of curiosity? I compile the expressions and look into co_names, e.g.: >>> expr = "0 .__class__" >>> c=compile(expr,"","eval") >>> c.co_names ('__class__',) regards, Roland From q_crack at yahoo.com Mon Aug 16 09:38:59 2010 From: q_crack at yahoo.com (Alexandru Ionescu) Date: Mon, 16 Aug 2010 06:38:59 -0700 (PDT) Subject: About UpdateLayeredWindow Message-ID: <272482.95979.qm@web53502.mail.re2.yahoo.com> Hello, In the last two weeks I've been trying to properly use UpdateLayeredWindow in Python but I'm only getting errors. I searched a lot on the internet and you are the only person who posted about using ULW in Python. I tried with ctypes and I also tried with win32gui & win32api. I got all kinds of errors. In the end I got to error code 5 (ERROR_ACCESS_DENIED) and nothing appears on the screen. Please send me a small working example in Python of UpdateLayeredWindow, either using ctypes or win32gui & win32api. My email address is q_crack at yahoo.com Thank you, Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From vikas.mahajan12 at gmail.com Mon Aug 16 09:40:06 2010 From: vikas.mahajan12 at gmail.com (Vikas Mahajan) Date: Mon, 16 Aug 2010 19:10:06 +0530 Subject: passing variables as object attributes Message-ID: Hello to all I am new to python. I am facing problem to use variables as object attributes. I have to use loop and dynamically add attributes to a object and for this purpose I have to use variables with object names. For example-: Let us say object car has an attribute engine, then varname = "engine" car.varname = "dummy value" is giving me Error: object car does not have attribute varname. Please tell me how can I use variables as objects attributes. Thanks. From nitinpawar432 at gmail.com Mon Aug 16 09:53:39 2010 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Mon, 16 Aug 2010 19:23:39 +0530 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: you would need to define a class first with its attiributes and then you may want to initiate the variables by calling the class initilializer On Mon, Aug 16, 2010 at 7:10 PM, Vikas Mahajan wrote: > Hello to all > > I am new to python. I am facing problem to use variables as object > attributes. I have to use loop and dynamically add attributes to a > object and for this purpose I have to use variables with object names. > > For example-: > Let us say object car has an attribute engine, then > varname = "engine" > car.varname = "dummy value" > is giving me Error: object car does not have attribute varname. > > Please tell me how can I use variables as objects attributes. > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.koebler at yahoo.de Mon Aug 16 10:01:42 2010 From: r.koebler at yahoo.de (Roland Koebler) Date: Mon, 16 Aug 2010 16:01:42 +0200 Subject: Simple Python Sandbox In-Reply-To: <4C67586C.3020107@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4C67586C.3020107@ixokai.io> Message-ID: <20100816140142.GB22789@localhost> On Sat, Aug 14, 2010 at 08:01:00PM -0700, Stephen Hansen wrote: > > As you can see, black listing isn't the best approach here. > > But I have a two pronged strategy: the black list is only half of the > equation. One, I'm blacklisting all the meta functions out of builtins. But blacklists are *never* secure. Sorry, but you should fully understand this before even thinking about more detailed security. Why are you blacklisting the "known-bad" functions instead of whitelising the allowed ones?? regards, Roland From egbertum at xs4all.nl Mon Aug 16 10:02:35 2010 From: egbertum at xs4all.nl (egbert) Date: Mon, 16 Aug 2010 16:02:35 +0200 Subject: When the first line of a file tells something about the other lines In-Reply-To: References: Message-ID: <20100816140235.GA9843@xs4all.nl> On Mon, Aug 16, 2010 at 11:59:57AM +0200, Peter Otten wrote: > > with open(filename) as lines: > first_line = next(lines, "") > if special(first_line): > # ... > else: > lines = itertools.chain([first_line], lines) > for line in lines: > # ... Beautiful. And a nice suggestion to read the itertools docs. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From vikas.mahajan12 at gmail.com Mon Aug 16 10:08:15 2010 From: vikas.mahajan12 at gmail.com (Vikas Mahajan) Date: Mon, 16 Aug 2010 19:38:15 +0530 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: On 16 August 2010 19:23, Nitin Pawar wrote: > you would need to define a class first with its attiributes and then you may > want to initiate the variables by calling the class initilializer > Actually I have to dynamically add attributes to a object. I am writing python script for FreeCAD software. I am using loop to create multiple cylinders and I am writing following code-: cyname = "Cylinder" FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) FreeCAD.ActiveDocument.cyname.Radius= .5 FreeCAD.ActiveDocument.cyname.Height= 10 And I am getting this error-: AttributeError: 'App.Document' object has no attribute 'cyname' But when I use Cylinder in place of cyname, I am not getting any error. Please help. Thanks. From stef.mientki at gmail.com Mon Aug 16 10:27:53 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 16 Aug 2010 16:27:53 +0200 Subject: does someone has a binary 32-bit windows installer for arac ? Message-ID: <4C694AE9.2000907@gmail.com> thanks, Stef Mientki From pruebauno at latinmail.com Mon Aug 16 10:28:10 2010 From: pruebauno at latinmail.com (nn) Date: Mon, 16 Aug 2010 07:28:10 -0700 (PDT) Subject: passing variables as object attributes References: Message-ID: <53e8ac38-57f5-4830-889e-5295ee9e7dbf@q22g2000yqm.googlegroups.com> On Aug 16, 10:08?am, Vikas Mahajan wrote: > On 16 August 2010 19:23, Nitin Pawar wrote:> you would need to define a class first with its attiributes and then you may > > want to initiate the variables by calling the class initilializer > > Actually I have to dynamically add attributes to a object. I am > writing python script for ?FreeCAD software. I am using loop to create > multiple cylinders and I am writing following code-: > cyname = "Cylinder" > FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) > FreeCAD.ActiveDocument.cyname.Radius= .5 > FreeCAD.ActiveDocument.cyname.Height= 10 > > And I am getting this error-: > AttributeError: 'App.Document' object has no attribute 'cyname' > > But when I use Cylinder in place of cyname, I am not getting any error. > > Please help. > > Thanks. From pruebauno at latinmail.com Mon Aug 16 10:30:07 2010 From: pruebauno at latinmail.com (nn) Date: Mon, 16 Aug 2010 07:30:07 -0700 (PDT) Subject: passing variables as object attributes References: Message-ID: On Aug 16, 10:08?am, Vikas Mahajan wrote: > On 16 August 2010 19:23, Nitin Pawar wrote:> you would need to define a class first with its attiributes and then you may > > want to initiate the variables by calling the class initilializer > > Actually I have to dynamically add attributes to a object. I am > writing python script for ?FreeCAD software. I am using loop to create > multiple cylinders and I am writing following code-: > cyname = "Cylinder" > FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) > FreeCAD.ActiveDocument.cyname.Radius= .5 > FreeCAD.ActiveDocument.cyname.Height= 10 > > And I am getting this error-: > AttributeError: 'App.Document' object has no attribute 'cyname' > > But when I use Cylinder in place of cyname, I am not getting any error. > > Please help. > > Thanks. This might work: cyname = "Cylinder" FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) getattr(FreeCAD.ActiveDocument,cyname).Radius= .5 getattr(FreeCAD.ActiveDocument,cyname).Height= 10 From chrischia82 at gmail.com Mon Aug 16 10:30:08 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Mon, 16 Aug 2010 07:30:08 -0700 (PDT) Subject: how to switch image in tkinter? making it mutable? how? Message-ID: <414ff6dd-73ef-48df-bd2b-080a2c710e5b@h17g2000pri.googlegroups.com> I have this: image1 = ImageTk.PhotoImage(file = "c:\\f1.jpg") image2 = ImageTk.PhotoImage(file = "c:\\f2.jpg") imagelist.append(image1) imagelist.append(image2) self.label = tk.Label(image = imagelist[0]) is there a way that i can create a method to switch the display the image2 (imagelist 2nd element) without using label.bind? can i make an image mutable? From jeanmichel at sequans.com Mon Aug 16 10:53:44 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 16 Aug 2010 16:53:44 +0200 Subject: Dump logging configuration In-Reply-To: <4C6925A0.8090701@sequans.com> References: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> <4C6925A0.8090701@sequans.com> Message-ID: <4C6950F8.1050205@sequans.com> Jean-Michel Pichavant wrote: > Kxepal wrote: >> Hi all! >> Sorry for dumb question if it is - I'd tried to google it before but >> have found nothing. >> >> Is there any way to dump current logging configuration for future >> loading it via fileConfig/dictConfig? >> > I may be wrong but I don't think so. > > JM Please understand that I don't think such feature exists (to oppose to thinking that I'm not wrong :o) ) JM From jackokring at gmail.com Mon Aug 16 10:59:40 2010 From: jackokring at gmail.com (jacko) Date: Mon, 16 Aug 2010 07:59:40 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: > is it possible to convert any and all algorithms to stack based ones and thus avoid memory leaks? No, not really. If you keep the allocated things and free them in reverse order on exit, then well yes, but practically, early free() frees memory for reuse on low memory systems. In this sense not 'reversed' out of order free is essential in some contexts. The question then becomes what is the best heap fragmentation/ compaction strategy and what is the best allocation algorithm to allocate addresses? From ian.g.kelly at gmail.com Mon Aug 16 11:04:29 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 16 Aug 2010 11:04:29 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> Message-ID: On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries wrote: >> I suspect that there exists a largest unpurchasable quantity iff at >> least two of the pack quantities are relatively prime, but I have made >> no attempt to prove this. > > That for sure is not correct; packs of 2, 4 and 7 do have a largest > unpurchasable quantity. 2 and 7 are relatively prime, so this example fits my hypothesis. > I'm pretty sure that if there's no common divisor for all three (or more) > packages (except one), there is a largest unpurchasable quantity. That is: ? > i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x|y) means "x is no divider of y" No. If you take the (2,4,7) example and add another pack size of 14, it does not cause quantities that were previously purchasable to become unpurchasable. Ian From steve.ferg.bitbucket at gmail.com Mon Aug 16 11:17:20 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Mon, 16 Aug 2010 08:17:20 -0700 (PDT) Subject: question about pdb assignment statements Message-ID: In this little script:
 import pdb
 pdb.set_trace()
 def main():
     xm = 123
     print("Hello,world!")
 main()
 
When I run this, I use pdb to step through it until I reach the point in main() where the xm variable has been initialized, and then I try to use pdb to reset the value of xm, and I can't. Does anybody know why? As I understand the documentation, http://docs.python.org/library/pdb.html I *should* be able to do this. [!]statement Execute the (one-line) statement in the context of the current stack frame. Is there something about "in the context of the current stack frame" that I don't understand? Or is it a bug (or a limitation) in pdb? From eric.brunel at pragmadev.nospam.com Mon Aug 16 11:27:17 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Mon, 16 Aug 2010 17:27:17 +0200 Subject: how to switch image in tkinter? making it mutable? how? References: <414ff6dd-73ef-48df-bd2b-080a2c710e5b@h17g2000pri.googlegroups.com> Message-ID: In article <414ff6dd-73ef-48df-bd2b-080a2c710e5b at h17g2000pri.googlegroups.com>, ChrisChia wrote: > I have this: > image1 = ImageTk.PhotoImage(file = "c:\\f1.jpg") > image2 = ImageTk.PhotoImage(file = "c:\\f2.jpg") > > imagelist.append(image1) > imagelist.append(image2) > > self.label = tk.Label(image = imagelist[0]) > > is there a way that i can create a method to switch the display the > image2 (imagelist 2nd element) > without using label.bind? > > can i make an image mutable? Unfortunately, I don't know the package ImageTk you're using. But at tk level, images are mutable without problem. It seems however that the tcl commands allowing to read an existing image from a file are not exposed at Tkinter level. But it is still possible to send the command to the underlying tcl interpreter to do it: from Tkinter import * root = Tk() image = PhotoImage(file='f1.gif') label = Label(root, image=image) ## When you want to change the image: root.tk.call(image, 'read', 'f2.gif', '-shrink') This will only work with image formats supported in the tcl/tk core, which are basically only GIF so far. BTW, I don't understand why you talk about label.bind? If you need to do anything when the label is clicked, you have to make a binding on the label whatever it is. HTH anyway. - Eric - From malcolm.mclean5 at btinternet.com Mon Aug 16 11:31:48 2010 From: malcolm.mclean5 at btinternet.com (Malcolm McLean) Date: Mon, 16 Aug 2010 08:31:48 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <93c048b8-013d-425f-ac69-c112f12ddaa3@v41g2000yqv.googlegroups.com> <7e095f76-b69f-4abe-b5ae-53844972fc6c@g21g2000prn.googlegroups.com> Message-ID: On Aug 16, 3:14?pm, spinoza1111 wrote: > > To build an explicit stack in this program would have been folly, for > it would have been necessary to either preallocate the stack and thus > legislate the maximum complexity of source code, or use a lot of > memory management in the pre-existing runtime heap. > The problem is that if you reallocate the stack, you invalidate all pointers to objects on it. So you have to use handles instead. At which point you might as well admit that you are no longer programming in C. > > > You didn't tell us you published a book. Can you identify the > publisher?- Hide quoted text - > It's a print on demand, by Lulu. O'Reilley said they liked it but they couldn't sell books on C. (I've an open invitation to write a computer book for them in another language). I don't really recommend print on demand. The nice thing is that you can sell the book for about half the price it would cost under a traditional publishing model. The problem is that people still use acceptance by a traditional publisher as a filter. From eric.brunel at pragmadev.nospam.com Mon Aug 16 11:32:51 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Mon, 16 Aug 2010 17:32:51 +0200 Subject: Textvariable display in label (GUI design) References: <993d9560-564d-47f0-b2db-6f0c6404ae81@g6g2000pro.googlegroups.com> Message-ID: In article <993d9560-564d-47f0-b2db-6f0c6404ae81 at g6g2000pro.googlegroups.com>, Jah_Alarm wrote: > hi, > > pls help me out with the following issue: I wrote a function that uses > a for loop that changes a value of a certain variable each iteration. > What I want is by clicking a button in GUI (with the command bound to > this function) this value each iteration is displayed in a textbox > (label). So far only one (starting value) is displayed. > > thanks, > > Alex First, with posts like this, you're highly unlikely to get any useful answer: please strip down your code to the smallest part that displays the problem, post this code here, explaining what you're expecting and what you're getting. Otherwise, people just won't know what you're talking about unless they have a crystal ball? Now using my own crystal ball: if you don't return the control to the GUI each time your variable is increased, the GUI won't get a chance to update itself. Since you seem to use Tkinter (another wild guess?), you probably need a call to the update_idletasks method on any Tkinter widget each time you change your TextVariable. HTH - Eric - From daniel.harjanto at gmail.com Mon Aug 16 11:34:08 2010 From: daniel.harjanto at gmail.com (misterdi) Date: Mon, 16 Aug 2010 08:34:08 -0700 (PDT) Subject: passing variables as object attributes References: Message-ID: On Aug 16, 8:40?pm, Vikas Mahajan wrote: > Hello to all > > I am new to python. I am facing problem to use variables as object > attributes. I have to use loop and dynamically add attributes to a > object and for this purpose I have to use variables with object names. > > For example-: > Let us say object car has an attribute engine, then > varname = "engine" > car.varname = "dummy value" > is giving me Error: object car does not have attribute varname. > > Please tell me how can I use variables as objects attributes. > > Thanks. I'm not a python expert, so this may not be accurate For me it is easier to define a class that represent the object, and then set attribute for the object. for example : # define a class with no attribute class Car(): pass # instance the class mycar = Car() # dynamically set attribute to the instance newattr = "engine" setattr(mycar, newattr, "dummy value") # or dynamically set attribute to the Class so every instance will inherit it classattr = "color" setattr(mycar, classattr, "yellow") But as I mention, I'm not an expert so maybe it's not a pythonic way to add attribute to an object. Cheers, From kxepal at gmail.com Mon Aug 16 11:40:50 2010 From: kxepal at gmail.com (Kxepal) Date: Mon, 16 Aug 2010 08:40:50 -0700 (PDT) Subject: Dump logging configuration References: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> <4C6925A0.8090701@sequans.com> Message-ID: <7093a1d9-294e-4831-a2bf-4e68285d25e3@v8g2000yqe.googlegroups.com> On Aug 16, 6:53?pm, Jean-Michel Pichavant wrote: > Jean-Michel Pichavant wrote: > > Kxepal wrote: > >> Hi all! > >> Sorry for dumb question if it is - I'd tried to google it before but > >> have found nothing. > > >> Is there any way todumpcurrentloggingconfiguration for future > >> loading it via fileConfig/dictConfig? > > > I may be wrong but I don't think so. > > > JM > > Please understand that I don't think such feature exists (to oppose to > thinking that I'm not wrong :o) ) > > JM Ah, you have break my dream, but thanks(: It's a pity, because it very handy feature, but now I see a lot of problems to implement it with current logging flexibility. From darragh.ssa at gmail.com Mon Aug 16 11:41:25 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 16 Aug 2010 08:41:25 -0700 (PDT) Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> <4c691d4c$0$11100$c3e8da3@news.astraweb.com> Message-ID: <82fc086c-4a07-404b-a7c2-744c7dc70b6a@x25g2000yqj.googlegroups.com> on steven, peter and eliasf: Well okay I'm new to the world of developing programs, if I encounter problems I directly post a bug on the relevant page, that's maybe why I was a bit frustrated :) but what you three say is indeed true.. From ian.g.kelly at gmail.com Mon Aug 16 11:42:25 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 16 Aug 2010 11:42:25 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> Message-ID: On Mon, Aug 16, 2010 at 11:04 AM, Ian Kelly wrote: > On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries wrote: >>> I suspect that there exists a largest unpurchasable quantity iff at >>> least two of the pack quantities are relatively prime, but I have made >>> no attempt to prove this. >> >> That for sure is not correct; packs of 2, 4 and 7 do have a largest >> unpurchasable quantity. > > 2 and 7 are relatively prime, so this example fits my hypothesis. Although now that I think about it some more, there are counter-examples. For example, the pack sizes (6, 10, 15) have a largest unpurchasable quantity of 29, but no two of those are relatively prime. I'm going to revise my hypothesis to state that a largest unpurchasable quantity exists iff some there exists some relatively prime subset of the pack sizes of cardinality 2 or greater. Cheers, Ian From carey.tilden at gmail.com Mon Aug 16 12:03:30 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Mon, 16 Aug 2010 09:03:30 -0700 Subject: Pop return from stack? In-Reply-To: <4c691e73$0$11100$c3e8da3@news.astraweb.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> <4c691e73$0$11100$c3e8da3@news.astraweb.com> Message-ID: On Mon, Aug 16, 2010 at 4:18 AM, Steven D'Aprano wrote: > > On Sun, 15 Aug 2010 21:01:04 -0700, Carey Tilden wrote: > >> On Sun, Aug 15, 2010 at 6:43 PM, bvdp wrote: >> >>> Not to belabor the point .. but "func" is not a standard lib module. >>> It's part of a much larger application ... and in that application it >>> makes perfect sense to terminate the application if it encounters an >>> error. I fail to see the problem with this. Why would an APPLICATION >>> raise a error or not exit to the system? >> >> For me, the main reason is to ensure the application has only one exit >> point. ?There's only one spot to maintain the code for closing files, >> cleaning up network connections, displaying errors to the user, etc. > > You mean all the things that Python's garbage collector already does for > you? Are you actually disagreeing with the point or just poking fun at my examples? If the former, well, phooey. If the latter, c'est la vie. > *wink* :-P Carey From jeanmichel at sequans.com Mon Aug 16 12:20:51 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 16 Aug 2010 18:20:51 +0200 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: <4C696563.90401@sequans.com> Vikas Mahajan wrote: > On 16 August 2010 19:23, Nitin Pawar wrote: > >> you would need to define a class first with its attiributes and then you may >> want to initiate the variables by calling the class initilializer >> >> > Actually I have to dynamically add attributes to a object. I am > writing python script for FreeCAD software. I am using loop to create > multiple cylinders and I am writing following code-: > cyname = "Cylinder" > FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) > FreeCAD.ActiveDocument.cyname.Radius= .5 > FreeCAD.ActiveDocument.cyname.Height= 10 > > And I am getting this error-: > AttributeError: 'App.Document' object has no attribute 'cyname' > > But when I use Cylinder in place of cyname, I am not getting any error. > > Please help. > > Thanks. > obj.attribute = 5 <=> setattr(obj, "attribute", 5) obj.attribute <=> getattr(obj, "attribute") So considering your example, getattr(FreeCAD.ActiveDocument, cyname).Radius = .5 should do the trick. JM From zdoor at xs4all.nl Mon Aug 16 12:26:46 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Mon, 16 Aug 2010 18:26:46 +0200 Subject: Opposite of split In-Reply-To: References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl><4C683363.3080305@islandtraining.com><4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c6966c8$0$22937$e4fe514c@news.xs4all.nl> Thanks much, Nope, no homework. This was a serious question from a serious but perhaps simple physicist who grew up with Algol, FORTRAN and Pascal, taught himself VB(A) and is looking for a replacement of VB and finding that in Python. You can guess my age now. Most of my work I do in R nowadays but R is not flexible enough for some file manipulation operations. I use the book by Lutz ("Learning Python"). The join method for strings is in there. I did not have the book at hand and I was jetlagged too. I do apologize for asking a simple question. I had no idea that some would go to the extent of giving trick solutions for simple, supposedly homework questions. Bear in mind Python is a very feature rich language. You cannot expect all newbies to remember everything. By the way, I had a working program that did what I wanted using still simpler string concatenation. Replaced that now by tab.join([lines[i][k][2] for i in range(5)]), k being a loop counter. Judge for yourself. That is the level I am at after 6 weeks of doing excercises from my programming book on Pascal in Python. Thanks for the help. I do hope there is no entry level for using this group. If there is, I won't meet it for a while. Alex van der Spek "D'Arcy J.M. Cain" wrote in message news:mailman.2159.1281917130.1673.python-list at python.org... > On 15 Aug 2010 23:33:10 GMT > Steven D'Aprano wrote: >> Under what possible circumstances would you prefer this code to the >> built- >> in str.join method? > > I assumed that it was a trap for someone asking for us to do his > homework. I also thought that it was a waste of time because I knew > that twenty people would jump in with the correct answer because of > "finally, one that I can answer" syndrome. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From zdoor at xs4all.nl Mon Aug 16 12:29:06 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Mon, 16 Aug 2010 18:29:06 +0200 Subject: EOFError with fileinput Message-ID: <4c696751$0$22940$e4fe514c@news.xs4all.nl> Using the fileinput module to process lists of files: >>>for line in fileinput.input(logs): Unfortunately, EOFError does not seem to indicate the end-of-file condition correctly when using fileinput. How would you find the EOF file for all the files in the file list 'logs'? Thank you, Alex van der Spek From jeff.hobbs at gmail.com Mon Aug 16 12:40:01 2010 From: jeff.hobbs at gmail.com (Jeff Hobbs) Date: Mon, 16 Aug 2010 09:40:01 -0700 (PDT) Subject: python strings and {} in Tkinter entry widgets References: Message-ID: <64720a7d-35a7-4e00-afc1-ed33bc9810ec@g6g2000pro.googlegroups.com> On Aug 15, 4:41?pm, Chris Hare wrote: > I have some code that pulls a value from a database. ?In this case, it is three space delimited words. ?When I display the value in a Tkinter.Entry widget, the text has curly braces around it, even when there are none in the surrounding the text in the database. > > Is this normal, and how do I prevent it or remove them correctly before displaying the text in the Entry widget? Python ['', '', ''] == Tcl {{} {} {}} Python 'a word' == Tcl {a word} You are getting a literal translation occurring, and you need to split/ join or index the items properly. Without being more clear how you want to represent your data, what you need isn't clear. Perhaps you just need to reference the first index of the variable, or ... who knows, there are lots of possibilities. Jeff From downaold at gmail.com Mon Aug 16 12:43:48 2010 From: downaold at gmail.com (Roald de Vries) Date: Mon, 16 Aug 2010 18:43:48 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> Message-ID: On Aug 16, 2010, at 5:04 PM, Ian Kelly wrote: > On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries > wrote: >>> I suspect that there exists a largest unpurchasable quantity iff at >>> least two of the pack quantities are relatively prime, but I have >>> made >>> no attempt to prove this. >> >> That for sure is not correct; packs of 2, 4 and 7 do have a largest >> unpurchasable quantity. > > 2 and 7 are relatively prime, so this example fits my hypothesis. I now notice I misread your post (as 'iff the least two pack quantities are relatively prime') >> I'm pretty sure that if there's no common divisor for all three (or >> more) >> packages (except one), there is a largest unpurchasable quantity. >> That is: ? >> i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x|y) means "x is no >> divider of y" > > No. If you take the (2,4,7) example and add another pack size of 14, > it does not cause quantities that were previously purchasable to > become unpurchasable. Then what is the common divisor of 2, 4, 7 and 14? Not 2 because ?(2| 7), not anything higher than 2 because that's no divisor of 2. Cheers, Roald From zdoor at xs4all.nl Mon Aug 16 12:44:08 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Mon, 16 Aug 2010 18:44:08 +0200 Subject: Opposite of split In-Reply-To: References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl><4C683363.3080305@islandtraining.com><4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c696ada$0$22941$e4fe514c@news.xs4all.nl> Perhaps the ones here who think I was trying to make you do my homework can actually help me for real. Since I run my own company (not working for any of the big ones) I can't afford official training in anything. So I teach myself, help is always welcome and sought for. If that feels like doing homework for me, so be it. The fact is that I do try to learn Python. It can do things I thought required much more coding. Look at the attached. It builds a concordance table first. That was an excercise from a book on Pascal programming. In Pascal the solution is 2 pages of code. In Python it is 8 lines. Beautiful! Anybody catches any other ways to improve my program (attached), you are most welcome. Help me learn, that is one of the objectives of this newsgroup, right? Or is it all about exchanging the next to impossible solution to the never to happen unreal world problems? Regards, Alex van der Spek "D'Arcy J.M. Cain" wrote in message news:mailman.2159.1281917130.1673.python-list at python.org... > On 15 Aug 2010 23:33:10 GMT > Steven D'Aprano wrote: >> Under what possible circumstances would you prefer this code to the >> built- >> in str.join method? > > I assumed that it was a trap for someone asking for us to do his > homework. I also thought that it was a waste of time because I knew > that twenty people would jump in with the correct answer because of > "finally, one that I can answer" syndrome. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: MergeLog2Auto.py URL: From fuglyducky at gmail.com Mon Aug 16 12:47:44 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Mon, 16 Aug 2010 09:47:44 -0700 (PDT) Subject: Newbie: strftime object error message Message-ID: I am trying to call a function with a couple additional parameters. Unfortunately, for whatever reason I am unable to get this to work. I am assuming that line is not passing correctly but I don't understand why??? I can't share all of the code because it has IP in it but below are the pertinent snippets. Thanks in advance! ################################################################################## PY: 3.1.2 FUNCTION CALL: text_file = open(file_name, "r") for line in text_file: new_foo = pop_time(current_time, line) # current_time = datetime.datetime.now() FUNCTION: def pop_time(line, cur_time): global new_string global current_time # Generate random time between 0 and 30 seconds # Changes the time delta every time function is run rand_time = random.randint(0, 30) delta_time = datetime.timedelta(seconds=rand_time) # Sets the time format for string output format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") ERROR MSG: format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") AttributeError: 'str' object has no attribute 'strftime' NOTE: current_time prints within the function, line does not From jeff.hobbs at gmail.com Mon Aug 16 12:57:47 2010 From: jeff.hobbs at gmail.com (Jeff Hobbs) Date: Mon, 16 Aug 2010 09:57:47 -0700 (PDT) Subject: how to switch image in tkinter? making it mutable? how? References: <414ff6dd-73ef-48df-bd2b-080a2c710e5b@h17g2000pri.googlegroups.com> Message-ID: On Aug 16, 7:30?am, ChrisChia wrote: > I have this: > image1 = ImageTk.PhotoImage(file = "c:\\f1.jpg") > image2 = ImageTk.PhotoImage(file = "c:\\f2.jpg") > > imagelist.append(image1) > imagelist.append(image2) > > self.label ?= tk.Label(image = imagelist[0]) > > is there a way that i can create a method to switch the display the > image2 (imagelist 2nd element) > without using label.bind? > > can i make an image mutable? self.label.configure(image = imagelist[1]) will change the image displayed. With PIL images, you can use image1.fromstring(...) that should have a similar effect, in that it changes the underlying image data and the label will display that. Whether you need to label.bind or something else to effect this change is up to you. You could have it happen on a timer, triggered by an event, or randomly effected by solar flares, depending on your application's needs. Jeff From breamoreboy at yahoo.co.uk Mon Aug 16 12:58:35 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 16 Aug 2010 17:58:35 +0100 Subject: EOFError with fileinput In-Reply-To: <4c696751$0$22940$e4fe514c@news.xs4all.nl> References: <4c696751$0$22940$e4fe514c@news.xs4all.nl> Message-ID: On 16/08/2010 17:29, Alex van der Spek wrote: > Using the fileinput module to process lists of files: > >>>> for line in fileinput.input(logs): > > Unfortunately, EOFError does not seem to indicate the end-of-file > condition correctly when using fileinput. > > How would you find the EOF file for all the files in the file list 'logs'? > > Thank you, > Alex van der Spek I'm not sure exactly what you're asking here. Could you a brief description as to what you're trying to achieve, then put the question again. Cheers. Mark Lawrence. From darcy at druid.net Mon Aug 16 13:04:07 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 16 Aug 2010 13:04:07 -0400 Subject: Opposite of split In-Reply-To: <4c6966c8$0$22937$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c6966c8$0$22937$e4fe514c@news.xs4all.nl> Message-ID: <20100816130407.2ca17c15.darcy@druid.net> On Mon, 16 Aug 2010 18:26:46 +0200 "Alex van der Spek" wrote: > Nope, no homework. This was a serious question from a serious but perhaps > simple physicist who grew up with Algol, FORTRAN and Pascal, taught himself > VB(A) and is looking for a replacement of VB and finding that in Python. You > can guess my age now. > > Most of my work I do in R nowadays but R is not flexible enough for some > file manipulation operations. I use the book by Lutz ("Learning Python"). > The join method for strings is in there. I did not have the book at hand and > I was jetlagged too. I do apologize for asking a simple question. I'm not actually the one that presented the convuluted example. I think the one who did just felt that someone had a question and they were passing it to the group instead of doing a simple Google search. The "solution" he posted looked like something designed to make the teacher scratch his head and ask embarrassing questions of the student. > Thanks for the help. I do hope there is no entry level for using this group. > If there is, I won't meet it for a while. I think that the only thing people expect is that you do a quick search first and show that you have tried first. Some questions have been asked and answered so many times that a search of the archives finds what you want without waiting for an answer. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From vikas.mahajan12 at gmail.com Mon Aug 16 13:05:46 2010 From: vikas.mahajan12 at gmail.com (Vikas Mahajan) Date: Mon, 16 Aug 2010 22:35:46 +0530 Subject: passing variables as object attributes In-Reply-To: <4C696563.90401@sequans.com> References: <4C696563.90401@sequans.com> Message-ID: @All Thanks a lot. getattr and setattr functions solved my problem. From jacky.chao.wang at gmail.com Mon Aug 16 13:06:57 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 10:06:57 -0700 (PDT) Subject: How to convert bytearray into integer? Message-ID: Hi there, Recently I'm facing a problem to convert 4 bytes on an bytearray into an 32-bit integer. So far as I can see, there're 3 ways: a) using struct module, b) using ctypes module, and c) manually manipulation. Are there any other ways? My sample is as following: ----- import struct import ctypes def test_struct(buf, offset): return struct.unpack_from("I", buf, offset)[0] def test_ctypes(buf, offset): return ctypes.c_uint32.from_buffer(buf, offset).value def test_multi(buf, offset): return buf[offset] + (buf[offset+1] << 8) + (buf[offset+2] << 16) + (buf[offset+3] << 24) buf_w = bytearray(5) buf_w[1] = 1 buf_r = buffer(buf_w) if __name__ == '__main__': import timeit t1 = timeit.Timer("test_struct(buf_r, 1)", "from __main__ import test_struct, buf_r") t2 = timeit.Timer("test_ctypes(buf_w, 1)", "from __main__ import test_ctypes, buf_w") t3 = timeit.Timer("test_multi(buf_w, 1)", "from __main__ import test_multi, buf_w") print t1.timeit(number=1000) print t2.timeit(number=1000) print t3.timeit(number=1000) ----- Yet the results are bit confusing: ----- number = 10000 0.0081958770752 0.012549161911 0.0112121105194 number = 1000 0.00087308883667 0.00125789642334 0.00110197067261 number = 100 0.0000917911529541 # 9.17911529541e-05 0.000133991241455 0.00011420249939 number = 10 1.69277191162e-05 2.19345092773e-05 1.69277191162e-05 number = 1 1.00135803223e-05 1.00135803223e-05 5.96046447754e-06 ----- As the number of benchmarking loops decreasing, method c which is manually manipulating overwhelms the former 2 methods. However, if number == 10K, the struct method wins. Why does it happen? Thanks, Jacky (jacky.chao.wang#gmail.com) From chare at labr.net Mon Aug 16 13:11:58 2010 From: chare at labr.net (Chris Hare) Date: Mon, 16 Aug 2010 12:11:58 -0500 Subject: python strings and {} in Tkinter entry widgets In-Reply-To: <64720a7d-35a7-4e00-afc1-ed33bc9810ec@g6g2000pro.googlegroups.com> References: <64720a7d-35a7-4e00-afc1-ed33bc9810ec@g6g2000pro.googlegroups.com> Message-ID: <11151F2F-7BEA-4D75-95B7-B64FB47D4EA5@labr.net> On Aug 16, 2010, at 11:40 AM, Jeff Hobbs wrote: > On Aug 15, 4:41 pm, Chris Hare wrote: >> I have some code that pulls a value from a database. In this case, it is three space delimited words. When I display the value in a Tkinter.Entry widget, the text has curly braces around it, even when there are none in the surrounding the text in the database. >> >> Is this normal, and how do I prevent it or remove them correctly before displaying the text in the Entry widget? > > Python ['', '', ''] == Tcl {{} {} {}} > Python 'a word' == Tcl {a word} > > You are getting a literal translation occurring, and you need to split/ > join or index the items properly. Without being more clear how you > want to represent your data, what you need isn't clear. Perhaps you > just need to reference the first index of the variable, or ... who > knows, there are lots of possibilities. > > Jeff > -- > http://mail.python.org/mailman/listinfo/python-list Actually I want all of the words, as they form the name of an organization entered by the user. So the space delimited words should be displayed without the {} in the tkinker entry box. The contents of the widget is a persons first and last name, space delimited From darcy at druid.net Mon Aug 16 13:17:29 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 16 Aug 2010 13:17:29 -0400 Subject: Opposite of split In-Reply-To: <4c696ada$0$22941$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> Message-ID: <20100816131729.aa587dc3.darcy@druid.net> On Mon, 16 Aug 2010 18:44:08 +0200 "Alex van der Spek" wrote: > Perhaps the ones here who think I was trying to make you do my homework can You keep replying to my message but as I pointed out in my previous message, I'm not the one who thought that you posted a homework question. I'm the one who thought that the other poster thought that you posted a homework question. Honestly, while I thought it was a question that could have been answered faster with a Google search, it did not look like a homework question to me. > actually help me for real. Since I run my own company (not working for any > of the big ones) I can't afford official training in anything. So I teach > myself, help is always welcome and sought for. If that feels like doing > homework for me, so be it. Well, it is "home" work but there is nothing wrong with asking for help anyway. When people complain about homework questions it is generally because someone has posted the question verbatim from the assignment and asks for a complete solution. That's annoying. What you have done here is good because you show some work and ask for help with it. Slightly better would be to ask specific questions about areas that you are struggling with but this is good. > The fact is that I do try to learn Python. It can do things I thought > required much more coding. Look at the attached. It builds a concordance > table first. That was an excercise from a book on Pascal programming. In > Pascal the solution is 2 pages of code. In Python it is 8 lines. Beautiful! I guess the real entry level test here is that you have to be smart enough to choose Python since it is the best language. You pass. :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From patrickwasp at gmail.com Mon Aug 16 13:17:51 2010 From: patrickwasp at gmail.com (Waspinator) Date: Mon, 16 Aug 2010 10:17:51 -0700 (PDT) Subject: How can I bundle a PyGTK program in windows so my users don't need to install Python or the GTK+ libs? Message-ID: <58dcc52c-e3d8-483c-8a95-f59928d61fad@c16g2000vbp.googlegroups.com> I found this question on http://faq.pygtk.org/index.py?file=faq21.005.htp&req=show but the answer did not help me. For example I have a simple program below that I would like to 'compile' with py2exe (or anything else if it's simpler) to run in windows as a single bundled executable file with no installation (no INNO setup), and no requirements for gtk or python installations. I doesn't matter if the .exe file is 30 MB to only display a hello world app, as long as it works. (although the smaller the better) The application already works in my windows test environment because I have installed python 2.6 with pygtk and a gtk bundle. Can someone please provide some simple and clear instructions on how I can do this? Thanks, Waspinator simple.py ------------------------------------------------------------------- import gtk window = gtk.Window() window.set_title("PyGTK Test Window") window.connect("destroy", gtk.main_quit) window.show_all() gtk.main() ------------------------------------------------------------------- From paddy3118 at googlemail.com Mon Aug 16 13:21:12 2010 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 16 Aug 2010 10:21:12 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> Message-ID: <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> On 14 Aug, 18:14, Raymond Hettinger wrote: > On Aug 12, 1:20?pm, Paddy wrote: > > > I find myself needing to calculate the difference between two Counters > > or multisets or bags. > > > I want those items that are unique to each bag. > > Tell us about your use cases. ?I'm curious how a program would ascribe > semantic meaning to the result. ?The phrase "unique to each bag" > doesn't quite cover it, perhaps something like "number in either > source above the minimum held in common". > > AFAICT, I've never needed something like this as a primitive. ?Even > the xor operation for regular sets is rarely used. > > > I know how to > > calculate it: > > > ? ? >>> b = Counter(a=1, b=2) > > ? ? >>> c = Counter(a=3, b=1) > > ? ? >>> diff = (b - c) + (c - b) > > ? ? >>> diff > > ? ? Counter({'a': 2, 'b': 1}) > > That seems simple enough. > You could also use: > > ?diff = (b | c) - (b & c) ? # max(b,c) - min(b,c) > > Raymond Hi Raymond and others, Lets say you have two *sets* of integers representing two near-copies of some system, then a measure of their difference could be calculated as: len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 % If the two collections of integers are allowed duplicates then you need a Counter/bag/multi-set type and the diff calculation I gave originally. Thanks. From breamoreboy at yahoo.co.uk Mon Aug 16 13:27:21 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 16 Aug 2010 18:27:21 +0100 Subject: Newbie: strftime object error message In-Reply-To: References: Message-ID: On 16/08/2010 17:47, fuglyducky wrote: > I am trying to call a function with a couple additional parameters. > Unfortunately, for whatever reason I am unable to get this to work. I > am assuming that line is not passing correctly but I don't understand > why??? > > I can't share all of the code because it has IP in it but below are > the pertinent snippets. > > Thanks in advance! > > ################################################################################## > > PY: 3.1.2 > > > FUNCTION CALL: > text_file = open(file_name, "r") > for line in text_file: > new_foo = pop_time(current_time, line) > # current_time = datetime.datetime.now() > > > FUNCTION: > def pop_time(line, cur_time): Look at the two arguments to pop_time, when you make the actual call they are swapped. > global new_string > global current_time > > > # Generate random time between 0 and 30 seconds > # Changes the time delta every time function is run > rand_time = random.randint(0, 30) > delta_time = datetime.timedelta(seconds=rand_time) > > # Sets the time format for string output > format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") > > > ERROR MSG: > format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") > AttributeError: 'str' object has no attribute 'strftime' > > > NOTE: current_time prints within the function, line does not HTH. Mark Lawrence. From zdoor at xs4all.nl Mon Aug 16 13:27:32 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Mon, 16 Aug 2010 19:27:32 +0200 Subject: EOFError with fileinput In-Reply-To: <4c696751$0$22940$e4fe514c@news.xs4all.nl> References: <4c696751$0$22940$e4fe514c@news.xs4all.nl> Message-ID: <4c697506$0$22918$e4fe514c@news.xs4all.nl> Here is an excerpt. It works because the end condition is a fixed number (ln==10255), the approximate number of data lines in a file. If I replace that condition by EOFError, the program does not do the intended work. It appears as if EOFError is always true in this case. +++++++++++++++++++++++++++++++++++++++++++ for line in fileinput.input(logs): if line.split()[0]=='DataID': datsec=True ln=0 if datsec: lines[fn].append(line.split()) ln+=1 if ln==10255: datsec=False fileinput.nextfile() fn+=1 print fileinput.filename().rsplit('\\',1)[1] fileinput.close() +++++++++++++++++++++++++++++++++++++++++++ Regards, Alex van der Spek "Alex van der Spek" wrote in message news:4c696751$0$22940$e4fe514c at news.xs4all.nl... > Using the fileinput module to process lists of files: > >>>>for line in fileinput.input(logs): > > Unfortunately, EOFError does not seem to indicate the end-of-file > condition correctly when using fileinput. > > How would you find the EOF file for all the files in the file list 'logs'? > > Thank you, > Alex van der Spek From cbrown at cbrownsystems.com Mon Aug 16 13:28:13 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Mon, 16 Aug 2010 10:28:13 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Message-ID: <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> On Aug 16, 1:23?am, Roald de Vries wrote: > On Aug 15, 2010, at 11:51 PM, Ian Kelly wrote: > > > > > On Sun, Aug 15, 2010 at 4:36 PM, Baba wrote: > >> Hi Mel, > > >> indeed i thought of generalising the theorem as follows: > >> If it is possible to buy n, n+1,?, n+(x-1) sets of McNuggets, for ? > >> some > >> x, then it is possible to buy any number of McNuggets >= x, given ? > >> that > >> McNuggets come in x, y and z packs. > > >> so with diophantine_nuggets(7,10,21) i would need 7 passes > >> result:53 > > >> but with (10,20,30) and 10 passes i get no result > > > You're on the right track. ?In the case of (10,20,30) there is no > > largest exactly purchasable quantity. ?Any quantity that does not end > > with a 0 will not be exactly purchasable. > > > I suspect that there exists a largest unpurchasable quantity iff at > > least two of the pack quantities are relatively prime, but I have made > > no attempt to prove this. > > That for sure is not correct; packs of 2, 4 and 7 do have a largest ? > unpurchasable quantity. > But 2 is coprime to 7. I think a better counterexample is 6, 10, 15; no two are coprime, but there is a largest unpurchasable quantity. > I'm pretty sure that if there's no common divisor for all three (or ? > more) packages (except one), there is a largest unpurchasable ? > quantity. That is: ? i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x| > y) means "x is no divider of y" > It's easy to prove that there is a largest unpurchasble quantity iff gcd(x,y,z) = 1. First, suppose d = gcd(x, y, z); then for some x', y', z' we have that x = d*x', y = d*y', z = d*z'; and so for any a, b, c: a*x + b*y + c*z = a*d*x' + b*d*y' + c*d*z' = d*(a*x' + b*y' + c*z') which means that d must always divide the total number of nuggets purchasable; thus if d >1, there is no largest unpurchasable quantity (you cannot purchase n*d + 1 nuggets for any n). To go the other way, if d = 1, then there exists integers (not neccessarily positive) such that a*x + b*y + c*z = 1 so therefore (a*x)*x + (b*x)*y + (c*x)*z = x Choose A, B, and C to be positive integers with A + a*x >= 0 B + b*x >= 0 C + c*x >= 0 Then we get a sequence of x consecutive numbers, all purchasable, via (A + i*a)*x + (B + i*b)*x + (C + i*c)*z = (Ax + By + Cz) + i*(ax + by cz) = (Ax + By + Cz) + i with i in range(x). The next consecutive number is then achieved via (Ax + By + Cz) + x = (A+1)x + By + Cz and so on. Cheers - Chas From python at mrabarnett.plus.com Mon Aug 16 13:28:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 16 Aug 2010 18:28:32 +0100 Subject: Newbie: strftime object error message In-Reply-To: References: Message-ID: <4C697540.6070408@mrabarnett.plus.com> fuglyducky wrote: > I am trying to call a function with a couple additional parameters. > Unfortunately, for whatever reason I am unable to get this to work. I > am assuming that line is not passing correctly but I don't understand > why??? > [snip] The function's parameters are the wrong way round. From python.koda at gmail.com Mon Aug 16 13:42:22 2010 From: python.koda at gmail.com (Alban Nona) Date: Mon, 16 Aug 2010 13:42:22 -0400 Subject: os.stat st_mtime problem Message-ID: Hello, Im stuck with this problem: I would like to os.stat st_mtime to copy only the files that have different modification date. so I found something on internet using this kind of line: if os.stat(dest).st_mtime - os.stat(src).st_mtime > 1: shutil.copy2 (src, dst) So I adapted it to my script like that: if sys.argv[1] == 'update': if os.stat(localPath).st_mtime != os.stat(networkPath).st_mtime: os.system('xcopy /E /I /Q /Y "%s" "%s"' % (networkPath, localPath)) else: print "Everything match" localPath is equal to : "c:\test\prod\" and networkPath to : "d:\test\prod\" the content of this paths is another directory: "v001", where there some tga files. Now I dont even know if os.stat compare the modified version of every files contained in localPath and networkPath, or does it compare only the v001 info ? If there a way to do it for every file ? Thank you ! (PS: I want to avoid filecmp :p) -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollybox.de Mon Aug 16 13:50:14 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 16 Aug 2010 19:50:14 +0200 Subject: How to convert bytearray into integer? In-Reply-To: References: Message-ID: <201008161950.14956.thomas@jollybox.de> On Monday 16 August 2010, it occurred to Jacky to exclaim: > Hi there, > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > an 32-bit integer. So far as I can see, there're 3 ways: > a) using struct module, Yes, that's what it's for, and that's what you should be using. > b) using ctypes module, and Yeeaah, that would work, but that's really not what it's for. from_buffer wants a writable buffer interface, which is unlikely to be what you want. > c) manually manipulation. Well, yes, you can do that, but it gets messy when you're working with more complex data structures, or you have to consider byte order. > Are there any other ways? You could write a C extension module tailored to your specific purpose ;-) > number = 1 > 1.00135803223e-05 > 1.00135803223e-05 > 5.96046447754e-06 > ----- > > As the number of benchmarking loops decreasing, method c which is > manually manipulating overwhelms the former 2 methods. However, if > number == 10K, the struct method wins. > > Why does it happen? struct wins because it's built for the job. As for the small numbers: don't take these numbers seriously. Just don't. This may be caused by the way your OS's scheduler handles things for all I know. If there is an explanation for this unscientific observation, I have two guesses what it might be: * struct and ctypes still need to do some setup work, or something * somebody is optimising something, but doesn't know what they should be optimising in the first place after only a few iterations. From iamforufriends at gmail.com Mon Aug 16 13:54:49 2010 From: iamforufriends at gmail.com (babe-with-huge-boobs-hard-sex) Date: Mon, 16 Aug 2010 10:54:49 -0700 (PDT) Subject: just click and meet ur dearest girl nearest u Message-ID: <65fd9dc3-c9d5-4b50-83b8-f34a5f841c46@u31g2000pru.googlegroups.com> just click and meet ur dearest girl nearest u morethen 34 million active members r waiting 4 live hot chat, dating ... free.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From ian.g.kelly at gmail.com Mon Aug 16 13:55:01 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 16 Aug 2010 13:55:01 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> Message-ID: On Mon, Aug 16, 2010 at 12:43 PM, Roald de Vries wrote: >>> I'm pretty sure that if there's no common divisor for all three (or more) >>> packages (except one), there is a largest unpurchasable quantity. That >>> is: ? >>> i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x|y) means "x is no divider of y" >> >> No. ?If you take the (2,4,7) example and add another pack size of 14, >> it does not cause quantities that were previously purchasable to >> become unpurchasable. > > Then what is the common divisor of 2, 4, 7 and 14? Not 2 because ?(2|7), not > anything higher than 2 because that's no divisor of 2. Ah, I misread what you meant as well. From tjreedy at udel.edu Mon Aug 16 14:03:28 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 16 Aug 2010 14:03:28 -0400 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: On 8/16/2010 9:40 AM, Vikas Mahajan wrote: > Hello to all > I am new to python. Hi, welcome to Python. Hint 1: 'Variable' is a rather loose term with many meanings. Better to think in terms of 'name' ('identifier'), which is specifically defined, and 'object'. > I am facing problem to use variables as object attributes. Your problem is that you have a attribute name stored in a string object, rather than being an unquoted literal in the code. > I have to use loop and dynamically add attributes to a > object and for this purpose I have to use variables with object names. You have to use strings with attribute names. Not uncommon > For example-: > Let us say object car has an attribute engine, then > varname = "engine" > car.varname = "dummy value" setattr(car, varname, "dummy value") is the runtime replacement for car.engine = "dummy value" Note that 'setattr(car, "engine", "dummy value")' would work but is never needed, since if you have the attribute name itself, you just write the assignment. hasattr and getattr are similar. -- Terry Jan Reedy From raoulbia at gmail.com Mon Aug 16 14:04:27 2010 From: raoulbia at gmail.com (Baba) Date: Mon, 16 Aug 2010 11:04:27 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> Message-ID: Hi Chas, Roald, These are all complicated formula that i believe are not expected at this level. If you look at the source (see my first submission) you will see that this exercise is only the second in a series called "Introduction to Programming". Therefore i am convinced that there is a much simpler solution. Now, i believe that the number of consecutive passes required to make this work is equal to the smallest number of pack sizes. So if we have packs of (9,12,21) the number of passes needed would be 9 and the theorem would read "If it is possible to buy n,n+1,n+2,...n+8 nuggets it is possible to buy any number of nuggets >= 9 given that they come in packs of 9,12,21" However i turn in circles because i don't seem to get any results for some random pack combinations like (9,12,21) or (10,20,30). The must always be a solution i'm thinking, be it the smallest pack - 1 Thoughts? tnx Raoul From erather at forth.com Mon Aug 16 14:09:57 2010 From: erather at forth.com (Elizabeth D Rather) Date: Mon, 16 Aug 2010 08:09:57 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> Message-ID: On 8/15/10 10:33 PM, Standish P wrote: ... I don't understand a lot of your post (and it's clear that I'm not alone). I don't know whether it's a (human) language problem or simply an issue of your having read too many books and not having enough practical experience, but at least I can try to address the Forth questions. >>> If Forth is a general processing language based on stack, is it >>> possible to convert any and all algorithms to stack based ones and >>> thus avoid memory leaks since a pop automatically releases memory when >>> free is an intrinsic part of it. Forth uses two stacks. The "data stack" is used for passing parameters between subroutines ("words") and is completely under the control of the programmer. Words expect parameters on this stack; they remove them, and leave only explicit results. The "return stack" is used primarily for return addresses when words are called, although it is also available for auxiliary uses under guidelines which respect the primary use for return addresses. Although implementations vary, in most Forths stacks grow from a fixed point (one for each stack) into otherwise-unused memory. The space involved is allocated when the program is launched, and is not managed as a heap and allocated or deallocated by any complicated mechanism. On multitasking Forth systems, each task has its own stacks. Where floating point is implemented (Forth's native arithmetic is integer-based), there is usually a separate stack for floats, to take advantage of hardware FP stacks. >> - is forth a general purpose language? Yes >> - are all algorithms stack based? No > > Does Forth uses stack for all algorithms ? Does it use pointers , ie > indirect addressing ? If it can/must use stack then every algorithm > could be made stack based. Forth uses its data stack for parameter passing and storage of temporary values. It is also possible to define variables, strings, and arrays in memory, in which case their addresses may be passed on the data stack. Forth is architecturally very simple. Memory allocations for variables, etc., are normally static, although some implementations include facilities for heaps as needed by applications. Hope this helps. If you are interested in learning more about Forth, there are several books available (try Amazon). Get one of the more recent ones, some of which I wrote. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From stndshp at gmail.com Mon Aug 16 14:21:16 2010 From: stndshp at gmail.com (Standish P) Date: Mon, 16 Aug 2010 11:21:16 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <6ef9faad-b067-4940-8e96-28d2cb8141a8@q22g2000yqm.googlegroups.com> On Aug 16, 12:38?am, "Alf P. Steinbach /Usenet" wrote: > * Standish P, on 16.08.2010 09:20: > > > [garble garble] > > Nonsense article "We look for an exogenous stack" cross-posted to > > ? ?[comp.lang.c], > ? ?[comp.lang.c++], > ? ?[comp.theory], > ? ?[comp.lang.python], > ? ?[comp.lang.forth]. > > Please refrain from following up on Standish' article. I am sorry that I did not post one of those porn baiting spams featuring YOUR MOTHER NUDE that you so like for others to see - AND - that you never complain about. Go and continue with your work and dont mess in my threads. Cheers, Standish > > Cheers, > > - Alf > > -- > blog at From fuglyducky at gmail.com Mon Aug 16 14:25:03 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Mon, 16 Aug 2010 11:25:03 -0700 (PDT) Subject: Newbie: strftime object error message References: Message-ID: On Aug 16, 10:27?am, Mark Lawrence wrote: > On 16/08/2010 17:47, fuglyducky wrote: > > > > > I am trying to call a function with a couple additional parameters. > > Unfortunately, for whatever reason I am unable to get this to work. I > > am assuming that line is not passing correctly but I don't understand > > why??? > > > I can't share all of the code because it has IP in it but below are > > the pertinent snippets. > > > Thanks in advance! > > > ################################################################################## > > > PY: 3.1.2 > > > FUNCTION CALL: > > text_file = open(file_name, "r") > > for line in text_file: > > ? ? ?new_foo = pop_time(current_time, line) > > # current_time = datetime.datetime.now() > > > FUNCTION: > > def pop_time(line, cur_time): > > Look at the two arguments to pop_time, when you make the actual call > they are swapped. > > > > > ? ? ?global new_string > > ? ? ?global current_time > > > ? ? ?# Generate random time between 0 and 30 seconds > > ? ? ?# Changes the time delta every time function is run > > ? ? ?rand_time = random.randint(0, 30) > > ? ? ?delta_time = datetime.timedelta(seconds=rand_time) > > > ? ? ?# Sets the time format for string output > > ? ? ?format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") > > > ERROR MSG: > > ? ? ?format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") > > AttributeError: 'str' object has no attribute 'strftime' > > > NOTE: current_time prints within the function, line does not > > HTH. > > Mark Lawrence. Oh jeez!!! Thanks! Man...looking at this stuff for so long it's easy to miss the obvious!!! Thanks and sorry for the waste of time. From jjposner at optimum.net Mon Aug 16 14:33:14 2010 From: jjposner at optimum.net (John Posner) Date: Mon, 16 Aug 2010 14:33:14 -0400 Subject: Opposite of split In-Reply-To: <4c696ada$0$22941$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl><4C683363.3080305@islandtraining.com><4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> Message-ID: <4C69846A.2020605@optimum.net> On 8/16/2010 12:44 PM, Alex van der Spek wrote: > > Anybody catches any other ways to improve my program (attached), you are > most welcome. 1. You don't need to separate out special characters (TABs, NEWLINEs, etc.) in a string. So: bt='-999.25'+'\t''-999.25'+'\t''-999.25'+'\t''-999.25'+'\t'+'-999.25' ... can be ... bt='-999.25\t-999.25\t-999.25\t-999.25\t-999.25' BTW, I think you made a couple of "lucky errors" in this statement. Where there are two consecutive apostrophe (') characters, did you mean to put a plus sign in between? Your statement is valid because the Python interpreter concatenates strings for you: >>> x = 'foo''bar' >>> x == 'foobar' True >>> x = 'foo' 'bar' >>> x == 'foobar' True 2. Take a look at the functions in the os.path module: http://docs.python.org/library/os.path.html These functions might simplify your pathname manipulations. (I didn't look closely enough to know for sure.) 3. An alternative to: alf.write(tp+'\t'+vf+'\t'+vq+'\t'+al+'\t'+bt+'\t'+vs+'\n') ... is ... alf.write("\t".join((tp, vf, vq, al, bt, vs)) + "\n") 4. I suggest using a helper function to bring that super-long column-heading line (alf.write('Timestamp ...) under control: def multi_field_names(base_name, count, sep_string): names = [base_name + " " + str(i) for i in range(1, count+1)] return sep_string.join(names) HTH, John From python at mrabarnett.plus.com Mon Aug 16 14:35:08 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 16 Aug 2010 19:35:08 +0100 Subject: os.stat st_mtime problem In-Reply-To: References: Message-ID: <4C6984DC.3030509@mrabarnett.plus.com> Alban Nona wrote: > Hello, > > Im stuck with this problem: > I would like to os.stat st_mtime to copy only the files that have > different modification date. > so I found something on internet using this kind of line: > > if os.stat(dest).st_mtime - os.stat(src).st_mtime > 1: > shutil.copy2 (src, dst) > So I adapted it to my script like that: > > if sys.argv[1] == 'update': > if os.stat(localPath).st_mtime != os.stat(networkPath).st_mtime: > os.system('xcopy /E /I /Q /Y "%s" "%s"' % (networkPath, > localPath)) > else: > print "Everything match" > > localPath is equal to : "c:\test\prod\" > and networkPath to : "d:\test\prod\" > > the content of this paths is another directory: "v001", where there some > tga files. > > Now I dont even know if os.stat compare the modified version of every > files contained in localPath and networkPath, or does it compare only > the v001 info ? > If there a way to do it for every file ? > os.stat doesn't compare anything, it just returns info about a single file or directory. From anthra.norell at bluewin.ch Mon Aug 16 14:40:52 2010 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Mon, 16 Aug 2010 20:40:52 +0200 Subject: Simple Problem but tough for me if i want it in linear time In-Reply-To: References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: <1281984052.2354.8.camel@hatchbox-one> On Sun, 2010-08-15 at 15:14 +0200, Peter Otten wrote: > ChrisChia wrote: > > > dataList = [a, b, c, ...] > > where a, b, c are objects of a Class X. > > In Class X, it contains self.name and self.number > > > > If i wish to test whether a number (let's say 100) appears in one of > > the object, and return that object, > > is that only fast way of solving this problem without iterating > > through every object to see the number value? > > > > dataList.__contains__ can only check my object instance name... > > anyone can solve this in linear complexity? > > Well, iteration as in > > next(item for item in dataList if item.number == 100) > > is O(n) and list.__contains__() has no magic way to do better. If you need > O(1) lookup you can use a dict or collections.defaultdict that maps > item.number to a list (or set) of X instances: > > lookup = {} > for item in dataList: > lookup.setdefault(item.number, []).append(item) > > print lookup[100] > > > Peter > How about >>> [obj for obj in dataList if obj.number == 100] That should create a list of all objects whose .number is 100. No need to cycle through a loop. If .number doesn't repeat get your object at index 0. The approach may seem inefficient for the purpose of extracting a single item, but the list needs to be gone through in any case and the list comprehension is surely the most efficient way to do it. Frederic From jacky.chao.wang at gmail.com Mon Aug 16 15:08:34 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 12:08:34 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: Hi Thomas, Thanks for your comments! Please check mine inline. On Aug 17, 1:50?am, Thomas Jollans wrote: > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > Hi there, > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > an 32-bit integer. ?So far as I can see, there're 3 ways: > > a) using struct module, > > Yes, that's what it's for, and that's what you should be using. My concern is that struct may need to parse the format string, construct the list, and de-reference index=0 for this generated list to get the int out. There should be some way more efficient? > > > b) using ctypes module, and > > Yeeaah, that would work, but that's really not what it's for. from_buffer > wants a writable buffer interface, which is unlikely to be what you want. Actually my buffer is writable --- it's an bytearray. Turning it into a R/O one make me to do extra effort: wrapping the bytearray into buffer(). My question is, this operation seems like to be much simpler than the former one, and it's very straightforward as well. Why is it slow? > > > c) manually manipulation. > > Well, yes, you can do that, but it gets messy when you're working with more > complex data structures, or you have to consider byte order. agree. :) > > > Are there any other ways? > > You could write a C extension module tailored to your specific purpose ;-) Ha, yes. Actually I've already modified socketmodule.c myself --- it's hard to image why socket object provides the interface: socket.recv_from(buf[, num_bytes[, flags]]) but forget the more generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]]) So do socket.send(...). > > > number = 1 > > 1.00135803223e-05 > > 1.00135803223e-05 > > 5.96046447754e-06 > > ----- > > > As the number of benchmarking loops decreasing, method c which is > > manually manipulating overwhelms the former 2 methods. ?However, if > > number == 10K, the struct method wins. > > > Why does it happen? > > struct wins because it's built for the job. > > As for the small numbers: don't take these numbers seriously. Just don't. This > may be caused by the way your OS's scheduler handles things for all I know. If > there is an explanation for this unscientific observation, I have two guesses > what it might be: > ?* struct and ctypes still need to do some setup work, or something > ?* somebody is optimising something, but doesn't know what they should be > ? ?optimising in the first place after only a few iterations. Agree. Thanks. - Jacky From dickinsm at gmail.com Mon Aug 16 15:36:26 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 16 Aug 2010 12:36:26 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: On Aug 16, 8:08?pm, Jacky wrote: > Hi Thomas, > > Thanks for your comments! ?Please check mine inline. > > On Aug 17, 1:50?am, Thomas Jollans wrote: > > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > > Hi there, > > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > > an 32-bit integer. ?So far as I can see, there're 3 ways: > > > a) using struct module, > > > Yes, that's what it's for, and that's what you should be using. > > My concern is that struct may need to parse the format string, > construct the list, and de-reference index=0 for this generated list > to get the int out. > > There should be some way more efficient? Well, you can improve on the struct solution by using the struct.Struct class to avoid parsing the format string repeatedly: >>> import struct >>> S = struct.Struct('>> S.unpack_from(buffer(bytearray([1,2,3,4,5]))) (67305985,) This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit build of Python 2.6) though; it's probably more effective for long format strings. Adding: def test_struct2(buf, offset, S=struct.Struct(' References: Message-ID: <201008162138.00980.thomas@jollybox.de> On Monday 16 August 2010, it occurred to Jacky to exclaim: > Hi Thomas, > > Thanks for your comments! Please check mine inline. > > On Aug 17, 1:50 am, Thomas Jollans wrote: > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > Hi there, > > > > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > > an 32-bit integer. So far as I can see, there're 3 ways: > > > a) using struct module, > > > > Yes, that's what it's for, and that's what you should be using. > > My concern is that struct may need to parse the format string, > construct the list, and de-reference index=0 for this generated list > to get the int out. > > There should be some way more efficient? The struct module is written in C, not in Python. It does have to parse a string, yes, so, if you wrote your own, limited, C function to do the job, it might be marginally faster. > > > > b) using ctypes module, and > > > > Yeeaah, that would work, but that's really not what it's for. from_buffer > > wants a writable buffer interface, which is unlikely to be what you want. > > Actually my buffer is writable --- it's an bytearray. Turning it into > a R/O one make me to do extra effort: wrapping the bytearray into > buffer(). > > My question is, this operation seems like to be much simpler than the > former one, and it's very straightforward as well. Why is it slow? Unlike struct, it constructs an object you're not actually interested in around your int. > it's hard to image why socket object provides the interface: > socket.recv_from(buf[, num_bytes[, flags]]) but forget the more > generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]]) Well, that's what pointer arithmetic (in C) or slices (in Python) are for! There's an argument to be made for sticking close to the traditional (originally C) interface here - it's familiar. - Thomas From mwilson at the-wire.com Mon Aug 16 15:52:41 2010 From: mwilson at the-wire.com (Mel) Date: Mon, 16 Aug 2010 15:52:41 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> Message-ID: Baba wrote: [ ... ] > Now, i believe that the number of consecutive passes required to make > this work is equal to the smallest number of pack sizes. So if we have > packs of (9,12,21) the number of passes needed would be 9 and the > theorem would read > > "If it is possible to buy n,n+1,n+2,...n+8 nuggets it is possible to > buy any number of nuggets >= 9 given that they come in packs of > 9,12,21" That's the proper statement. > > However i turn in circles because i don't seem to get any results for > some random pack combinations like (9,12,21) or (10,20,30). That "if it is possible" is the big if. If every package you can buy has a multiple of 3, then every possible purchase will be a multiple of 3. Nothing that leaves a remainder of 1 or 2 will ever show up. > > The must always be a solution i'm thinking, be it the smallest pack - > 1 The set (9/3, 12/3, 21/3) settles down pretty quickly: >>> s = nuggets.buyable_set ((3, 4, 7)) >>> nuggets.print_from (s, xrange(20)) 0 set([]) 3 set([0]) 4 set([0]) 6 set([3]) 7 set([0, 3, 4]) 8 set([4]) 9 set([6]) 10 set([3, 6, 7]) 11 set([8, 4, 7]) 12 set([8, 9]) 13 set([9, 10, 6]) 14 set([10, 11, 7]) 15 set([8, 11, 12]) 16 set([9, 12, 13]) 17 set([10, 13, 14]) 18 set([11, 14, 15]) 19 set([16, 12, 15]) >>> The printout here is the 'genaeology' of each purchase -- the set of smaller purchases from which you can reach each one. After ...,6,7,8,... every larger number can be reached. Mel. From dickinsm at gmail.com Mon Aug 16 15:53:21 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 16 Aug 2010 12:53:21 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: On Aug 16, 8:36?pm, Mark Dickinson wrote: > On Aug 16, 8:08?pm, Jacky wrote: > > My concern is that struct may need to parse the format string, > > construct the list, and de-reference index=0 for this generated list > > to get the int out. > > > There should be some way more efficient? > > Well, you can improve on the struct solution by using the > struct.Struct class to avoid parsing the format string repeatedly: > > >>> import struct > >>> S = struct.Struct(' >>> S.unpack_from(buffer(bytearray([1,2,3,4,5]))) > > (67305985,) > > This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit > build of Python 2.6) though; ?it's probably more effective for long > format strings. Sorry, this was inaccurate: this makes almost *no* significant difference on my machine for large test runs (10000 and up). For small ones, though, it's faster. The reason is that the struct module caches (up to 100, in the current implementation) previously used format strings, so with your tests you're only ever parsing the format string once anyway. Internally, the struct module converts that format string to a Struct object, and squirrels that Struct object away into its cache, which is implemented as a dict from format strings to Struct objects. So the next time that the format string is used it's simply looked up in the cache, and the Struct object retrieved. By the way, in Python 3.2 there's yet another fun way to do this, using int.from_bytes. >>> int.from_bytes(bytearray([1,2,3,4]), 'little') 67305985 -- Mark From giacomo.boffi at polimi.it Mon Aug 16 15:57:59 2010 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Mon, 16 Aug 2010 21:57:59 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Message-ID: <868w46qqig.fsf@aiuole.stru.polimi.it> Baba writes: > Hi Mel, > > indeed i thought of generalising the theorem as follows: > If it is possible to buy n, n+1,~, n+(x-1) sets of McNuggets, for some > x, then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in x, y and z packs. > > so with diophantine_nuggets(7,10,21) i would need 7 passes > result:53 > > but with (10,20,30) and 10 passes i get no result you need at least an odd number in your set, because summing even numbers only you'll never get an odd result From raoulbia at gmail.com Mon Aug 16 16:18:39 2010 From: raoulbia at gmail.com (Baba) Date: Mon, 16 Aug 2010 13:18:39 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <868w46qqig.fsf@aiuole.stru.polimi.it> Message-ID: <8e7ad85e-750b-48ef-9ca8-36690fa2cbcf@p7g2000yqa.googlegroups.com> well i still believe that the key is the smallest sized pack and there's no need to go into higher mathematics to solve this problem. I think below code works within the limits of the exercise which states to look at a maximum range of 200 in order not to search forever. packages=[2,103,105] min_size=min(packages[0],packages[1],packages[2]) cbc=0 #cbc=can_buy counter for n_nuggets in range(1,200): if cbc>=min_size: break can_buy=False for a in range (n_nuggets/packages[0]+1): for b in range (n_nuggets/packages[1]+1): for c in range (n_nuggets/packages[2]+1): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b+packages[2]*c==n_nuggets: can_buy=True break if can_buy==True: cbc+=1 else: cbc=0 sol=n_nuggets print sol Baba From jjposner at optimum.net Mon Aug 16 16:52:35 2010 From: jjposner at optimum.net (John Posner) Date: Mon, 16 Aug 2010 16:52:35 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <8e7ad85e-750b-48ef-9ca8-36690fa2cbcf@p7g2000yqa.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <868w46qqig.fsf@aiuole.stru.polimi.it> <8e7ad85e-750b-48ef-9ca8-36690fa2cbcf@p7g2000yqa.googlegroups.com> Message-ID: <4C69A513.1050802@optimum.net> On 8/16/2010 4:18 PM, Baba wrote: > > packages=[2,103,105] > min_size=min(packages[0],packages[1],packages[2]) or: min_size = min(packages) -John From rantingrick at gmail.com Mon Aug 16 18:36:35 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 16 Aug 2010 15:36:35 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: <8fa1a70c-c40b-40fd-8dc7-2cb155fbc8b1@l6g2000yqb.googlegroups.com> Message-ID: <07f2804d-c212-4f84-b0de-dd0e80ab5bca@u26g2000yqu.googlegroups.com> On Aug 9, 8:19?am, Mike Kent wrote: > On Aug 8, 8:43?pm, rantingrick wrote: > Xah, this is really you, isn't it. ?Come on, confess. *MOI*, How could *I* be xah. I really don't like Ruby however he gushes over it all the time. And he does not like Python that much either. We are total opposites, really. From kevin.p.dwyer at gmail.com Mon Aug 16 18:37:55 2010 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Mon, 16 Aug 2010 22:37:55 +0000 (UTC) Subject: question about pdb assignment statements References: Message-ID: On Mon, 16 Aug 2010 08:17:20 -0700, Steve Ferg wrote: > In this little script: > >
>  import pdb
>  pdb.set_trace()
>  def main():
>      xm = 123
>      print("Hello,world!")
>  main()
>  
> > When I run this, I use pdb to step through it until I reach the point in > main() where the xm variable has been initialized, and then I try to use > pdb to reset the value of xm, and I can't. > > Does anybody know why? > > As I understand the documentation, > http://docs.python.org/library/pdb.html I *should* be able to do this. > > [!]statement > Execute the (one-line) statement in the context of the current stack > frame. > > Is there something about "in the context of the current stack frame" > that I don't understand? Or is it a bug (or a limitation) in pdb? I think this may be the issue raised in bug 5215 (http://bugs.python.org/issue5215), committed in r71006. Displaying a changed variable using the "p" command reverts the variable to its previous value. If you try pdb.set_trace() def main(): xm = 123 print("Hello,world!") print xm and change xm before it's printed (but do not display using "p") it seems to work as expected. Hope that helps, Kev From kevin.p.dwyer at gmail.com Mon Aug 16 18:39:58 2010 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Mon, 16 Aug 2010 22:39:58 +0000 (UTC) Subject: question about pdb assignment statements References: Message-ID: On Mon, 16 Aug 2010 08:17:20 -0700, Steve Ferg wrote: > In this little script: > >
>  import pdb
>  pdb.set_trace()
>  def main():
>      xm = 123
>      print("Hello,world!")
>  main()
>  
> > When I run this, I use pdb to step through it until I reach the point in > main() where the xm variable has been initialized, and then I try to use > pdb to reset the value of xm, and I can't. > > Does anybody know why? > > As I understand the documentation, > http://docs.python.org/library/pdb.html I *should* be able to do this. > > [!]statement > Execute the (one-line) statement in the context of the current stack > frame. > > Is there something about "in the context of the current stack frame" > that I don't understand? Or is it a bug (or a limitation) in pdb? I should have added my version: Python 2.6.2 (r262:71600, Jun 17 2010, 13:37:45) [GCC 4.4.1 [gcc-4_4-branch revision 150839]] on linux2 From rantingrick at gmail.com Mon Aug 16 18:58:15 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 16 Aug 2010 15:58:15 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> Message-ID: <61fb7586-d8c0-4d65-8e82-d9c6b313511a@a36g2000yqc.googlegroups.com> On Aug 8, 8:15?pm, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 17:43:03 -0700, rantingrick wrote: > > Ruby has what they > > call a "Here Doc". Besides picking the most boneheaded name for such an > > object > > It's standard terminology that has been around for a long time in many > different languages. Just because something has been around around for a long time does not necessarily mean it's was a good idea to begin with. STRAWMAN! > > As you can see it is another example of tacked on functionality that was > > not carefully considered before hand. > > I disagree. It's an old and venerable technique, and very useful on the > rare occasion that you have lots of quotation marks in a string. (...snip...) > ? Python strings have four delimiters: > ? (1) single quote ' > ? (2) double quote " > ? (3) single-quote here-doc ''' > ? (4) double-quote here-doc """ > > ? plus equivalent raw-strings of each kind. > > Trying writing that as a single literal in Python without escapes. There > are work-arounds, of course, like using implicit concatenation, but > they're ugly. Yes, with the choices we have today writing strings like you mention is terribly asinine. And don't forget about filepaths and regexps too with all the backslashing nonsense! However, there is a simple solution to this mess. Python "double quote strings" and Python """multiline strings"""(that are delimited by leading and trailing double quote triplets) should behave as they do today. However Python 'single quote strings' and Python '''multiline strings'''(that are delimited by leading and trailing single quote triplets) should be raw so that they do not interpret escape sequences. Yes i know this would break backwards compatibility *again* but this functionality should have been made available in Py3000 since we were already breaking it anyhow. Why do we need both """X""" AND '''X''' this if they do exactly the same thing? Also why do we need both "X" AND 'X' if they do exactly the same thing. A real chance to make something special was missed and i hope one day we come to the realization that this proposed functionality of strings (raw and normal) is sorely needed in Python. > In Ruby they decided to be more general, so you can define whatever > heredoc you need to quote whatever literal string you need. That's not > bone-headed. The fact that Ruby has multi line strings (*ahem*... HEREDOC's) is not at all the point i take issue with. I take issue with the boneheaded syntax. Have you ever tried to grep Ruby heredocs? It would have been so much easier if they had made a spec like this... mystring = :{ blah blah blah blahblah blah blah blah blah }: Or at least *some* static token instead of just creating something on the fly each time.... now thats boneheaded! From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 19:10:41 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 23:10:41 GMT Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> <4c691f96$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c69c571$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 05:46:17 -0700, Alex Willmer wrote: > On Aug 16, 12:23?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sun, 15 Aug 2010 17:36:07 -0700, Alex Willmer wrote: >> > On Aug 16, 1:07?am, Steven D'Aprano > > cybersource.com.au> wrote: >> >> You're passing re.IGNORECASE (which happens to equal 2) as a count >> >> argument, not as a flag. Try this instead: >> >> >> >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) >> >> 'Python27' >> >> > Basically right, but in-line flags must be placed at the start of a >> > pattern, or the result is undefined. >> >> Pardon me, but that's clearly not correct, as proven by the fact that >> the above example works. > > Undefined includes 'might work sometimes'. I refer you to the Python > documentation: > > "Note that the (?x) flag changes how the expression is parsed. It should > be used first in the expression string, or after one or more whitespace > characters. If there are non-whitespace characters before the flag, the > results are undefined." > http://docs.python.org/library/re.html#regular-expression-syntax Well so it does. I stand corrected. I note though that even the docs say "should" rather than "must". I wonder whether the documentation author is just being cautious, because I've seen comments on the python-dev list that imply that the current behaviour of flags (that their effect is global to the regex) is supported. E.g.: http://code.activestate.com/lists/python-dev/98681/ At the point that people are seriously considering changing the behaviour of a replacement re engine in order to support the current "undefined" behaviour, perhaps that behaviour isn't quite so undefined and the docs need to be re-written? -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 19:17:41 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 23:17:41 GMT Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: <4c69c715$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 20:40:52 +0200, Frederic Rentsch wrote: > How about > >>>> [obj for obj in dataList if obj.number == 100] > > That should create a list of all objects whose .number is 100. No need > to cycle through a loop. What do you think the list comprehension does, if not cycle through a loop? -- Steven From fons at kokkinizita.net Mon Aug 16 19:19:42 2010 From: fons at kokkinizita.net (fons at kokkinizita.net) Date: Tue, 17 Aug 2010 01:19:42 +0200 Subject: execfile() and locals() In-Reply-To: <4c687728$0$11100$c3e8da3@news.astraweb.com> References: <4c687728$0$11100$c3e8da3@news.astraweb.com> Message-ID: <20100816231942.GA4219@zita2> On Sun, Aug 15, 2010 at 11:24:25PM +0000, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 23:21:51 +0200, fons wrote: > > > The documentation on execfile() and locals() makes it clear that code > > executed from execfile() can not modify local variables in the function > > from wich execfile() was called. Two questions about this: > > > > 1. Is there some way to circumvent this limitation (apart from > > explicitly copying variables to/from a dictionary passed as locals to > > execfile()) ? > > Chances are very good that if you're using exec or execfile inside a > function, you probably don't need to. In this case that would probably be true (see below). > As an optimization, local variables don't live inside a dict namespace. > The space for those locals is allocated at compile time, and locals() > returns a copy of the variables in a dict. > > However, the action of exec is a little more subtle, and mysterious, as > seen by this example in Python 3.1: > > >>> def f(): > ... x = 1 > ... print(locals()) > ... exec("x=2; y=0") > ... print(locals()) > ... > >>> > >>> f() > {'x': 1} > {'y': 0, 'x': 1} > > This shows that exec was able to create a new local variable, but not > modify an existing one -- this is completely unintuitive to me. I would > have guessed the opposite. And worse: > > >>> f.__code__.co_varnames > ('x',) > >>> f.__code__.co_nlocals > 1 > > So where does the newly-created local `y` live, if not in a dict > namespace and not in the usual variable slots? > > Curiouser and curiouser... Indeed... and I tried your example also in 2.6, and there it 'just works'. I've been reading a bit on execfile() and friends on various locations on the web, and there seems to be some controversy about it. One poster even wrote 'If you need execfile() you have a design problem'. I don't agree - in this case I use an interpreted language exactly to be able to do such things as made possible by execfile(). The application is a GUI one used to control electronic musical instruments and audio processors in a 'live performance' situation. Its main window shows a collection of buttons, rotary controls, sliders, etc., which trigger things when used. For example, clicking on a button could start a timed sequence of actions, each action being e.g. a message sent to a synthesis program or an audio processor, and/or some changes to the GUI itself. Such a sequence could be quite complex, defining it may require loops and conditions, or even interaction with other sequences, so the natural way is to define it as code and not as data. Users of the system are assumed to know basic Python, without being experts or expected to understand things such as the ones we are discussing. Sequences will run for some time, many of them can run at the same time, so each of them will be executed in a separate thread if required. A basic requirement for the system is that all actions can be redefined while the program is running, hence the need for execfile() or something similar. Shift-click on a GUI item presents a menu with options to modify its actions, one of them is to edit the file defining the code associated with the item. Now there are two ways to use execfile() or equivalent: 1. Actually execute the file when e.g. a button is clicked. 2. Execute it when the action is defined (i.e. when the user has finished editing the file). In the case the file should define a function which will be executed when triggered. I'll probably use the second way - the function will be precompiled, and most errors will show up before it is actually executed. Ciao, -- FA There are three of them, and Alleline. From ldo at geek-central.gen.new_zealand Mon Aug 16 19:30:18 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 17 Aug 2010 11:30:18 +1200 Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: In message <5fa7b287-0199-4349-ae0d-c34c8461cdcd at 5g2000yqz.googlegroups.com>, Standish P wrote: > We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. Since when are malloc(3) and free(3) exogenous? From alon.sebastian at gmail.com Mon Aug 16 19:45:52 2010 From: alon.sebastian at gmail.com (Sebastian Alonso) Date: Mon, 16 Aug 2010 20:45:52 -0300 Subject: Running pygtk app under windows. Message-ID: Hey everyone, I'm trying to be able to run my app, which uses pygtk, under windows, but unfortunately I'm having big problems with it. The main purpose of this is to later on make an .exe file but i havent even been able to run the app at least. I've followed every single step from this faq http://faq.pygtk.org/index.py?file=faq21.001.htp&req=show and when i try to run the example the example they offer I get this: "Traceback (most recent call last): File "", line 1, in import gtk File "C:\Python26\lib\site-packages\gtk-2.0\gtk\__init__.py", line 30, in import gobject as _gobject File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 26, in from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, \ File "C:\Python26\lib\site-packages\gtk-2.0\glib\__init__.py", line 22, in from glib._glib import * ImportError: DLL load failed: Specified module cannot be found." Do you have any clue on what could be happening ? I've tried most of the things you would expect to make anything work on windows, reboot, unistall everything and re-install everything again, yet it wont work... Thanks in advanced. Seba -------------- next part -------------- An HTML attachment was scrubbed... URL: From jah.alarm at gmail.com Mon Aug 16 19:46:37 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Mon, 16 Aug 2010 16:46:37 -0700 (PDT) Subject: Textvariable display in label (GUI design) References: <993d9560-564d-47f0-b2db-6f0c6404ae81@g6g2000pro.googlegroups.com> Message-ID: On Aug 17, 3:32?am, Eric Brunel wrote: > In article > <993d9560-564d-47f0-b2db-6f0c6404a... at g6g2000pro.googlegroups.com>, > > ?Jah_Alarm wrote: > > hi, > > > pls help me out with the following issue: I wrote a function that uses > > a for loop that changes a value of a certain variable each iteration. > > What I want is by clicking a button in GUI (with the command bound to > > this function) this value each iteration is displayed in a textbox > > (label). So far only one (starting value) is displayed. > > > thanks, > > > Alex > > First, with posts like this, you're highly unlikely to get any useful > answer: please strip down your code to the smallest part that displays > the problem, post this code here, explaining what you're expecting and > what you're getting. Otherwise, people just won't know what you're > talking about unless they have a crystal ball? > > Now using my own crystal ball: if you don't return the control to the > GUI each time your variable is increased, the GUI won't get a chance to > update itself. Since you seem to use Tkinter (another wild guess?), you > probably need a call to the update_idletasks method on any Tkinter > widget each time you change your TextVariable. > > HTH > ?- Eric - Thanks, but where is this command used, in the button than runs the algorithm, the label or the function itself? From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 19:51:44 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 23:51:44 GMT Subject: EOFError with fileinput References: <4c696751$0$22940$e4fe514c@news.xs4all.nl> <4c697506$0$22918$e4fe514c@news.xs4all.nl> Message-ID: <4c69cf10$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 19:27:32 +0200, Alex van der Spek wrote: > Here is an excerpt. It works because the end condition is a fixed number > (ln==10255), the approximate number of data lines in a file. If I > replace that condition by EOFError, the program does not do the intended > work. It appears as if EOFError is always true in this case. I don't understand what you mean by "replace that condition by EOFError". I can only guess you mean what you say literally, and replace the test: if ln==10255: with the test: if EOFError: If not, then I have no idea what you mean. But if that is what you're doing, then you're doing it completely wrong! Exceptions aren't flags that get set globally by magic. You have completely misunderstood Python's programming model. In this case, the point of using fileinput is so you don't need to care about the EOF of each file. fileinput takes care of that for you, automatically detecting the end of file and switching to the next file as needed. You only need to call fileinput.nextfile() if you want to switch to the next file *before* reaching end-of-file. The usual way to use fileinput is something like: import fileinput for line in fileinput.input(list_of_filenames): process(line) which will process all the lines in each file in turn. I'm not entirely sure what you are attempting to do in your example code. It doesn't help that you are using variable names like fn and ln. But I will take a guess. Here's my attempt to re-write and simplify it, by changing the condition from "is this the last line?" to "is this the first line?". import fileinput import os file_number = -1 lines = [ [] for i in len(logs)) ] for line in fileinput.input(logs): if fileinput.isfirstline(): file_number += 1 pathname, filename = os.path.split(fileinput.filename()) print filename words = line.split() if not words: # Line was blank (just whitespace) and can be ignored. continue if word[0] == 'DataID': lines[file_number].append(words) fileinput.close() -- Steven From jah.alarm at gmail.com Mon Aug 16 20:37:45 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Mon, 16 Aug 2010 17:37:45 -0700 (PDT) Subject: random number generation Message-ID: <7d76d377-6a55-4320-afa4-8425719d8e6e@n19g2000prf.googlegroups.com> hi, I need to generate a binary array with a specified average proportion of 1s (e.g. [1 0 0 0 0 1 0 0] has this proportion = 25%). In Matlab I run something like random(m,n)

References: <7d76d377-6a55-4320-afa4-8425719d8e6e@n19g2000prf.googlegroups.com> Message-ID: <51CFE393-93EC-465D-8F1D-9F72721B2690@bryant.edu> On Aug 16, 2010, at 20:37 , Jah_Alarm wrote: > hi, > > I need to generate a binary array with a specified average proportion > of 1s (e.g. [1 0 0 0 > > 0 1 0 0] has this proportion = 25%). In Matlab I run something like > random(m,n)

> between 0 and 1. I'm trying to use random.randint(0,2,size=[m,n]), but > I don't understand how to specify this proportion p. > if you're coming from matlab, then you should use the numpy package (and you can post questions on the numpy list). In that case, you can do: from numpy import * random.rand(5,7)<0.25 array([[False, True, True, False, False, True, False], [False, False, False, False, True, False, False], [ True, False, False, False, False, False, True], [ True, False, True, False, False, False, False], [False, False, False, False, False, False, False]], dtype=bool) just like matlab. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais http://bblais.blogspot.com/ From jacky.chao.wang at gmail.com Mon Aug 16 20:57:45 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 17:57:45 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: Hi Mark, Thanks for your reply. Agree and I'll use your suggestions. Thanks! -Jacky On Aug 17, 3:36?am, Mark Dickinson wrote: > On Aug 16, 8:08?pm, Jacky wrote: > > > Hi Thomas, > > > Thanks for your comments! ?Please check mine inline. > > > On Aug 17, 1:50?am, Thomas Jollans wrote: > > > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > > > Hi there, > > > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > > > an 32-bit integer. ?So far as I can see, there're 3 ways: > > > > a) using struct module, > > > > Yes, that's what it's for, and that's what you should be using. > > > My concern is that struct may need to parse the format string, > > construct the list, and de-reference index=0 for this generated list > > to get the int out. > > > There should be some way more efficient? > > Well, you can improve on the struct solution by using the > struct.Struct class to avoid parsing the format string repeatedly: > > >>> import struct > >>> S = struct.Struct(' >>> S.unpack_from(buffer(bytearray([1,2,3,4,5]))) > > (67305985,) > > This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit > build of Python 2.6) though; ?it's probably more effective for long > format strings. Adding: > > def test_struct2(buf, offset, S=struct.Struct(' ? ? return S.unpack_from(buf, offset)[0] > > to your test code, I see a speedup of around 8% over your test_struct. > > By the way, you may want to consider using an explicit byte-order/size > marker in your format string; ?i.e., use ' forces a 4-byte little-endian interpretation, regardless of the > platform you're running Python on. > > -- > Mark- Hide quoted text - > > - Show quoted text - From jacky.chao.wang at gmail.com Mon Aug 16 21:00:09 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 18:00:09 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: <38b3c3b4-5a06-4fe1-9e5f-7194142a3606@f20g2000pro.googlegroups.com> On Aug 17, 3:38?am, Thomas Jollans wrote: > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > > > > > Hi Thomas, > > > Thanks for your comments! ?Please check mine inline. > > > On Aug 17, 1:50 am, Thomas Jollans wrote: > > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > > Hi there, > > > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > > > an 32-bit integer. ?So far as I can see, there're 3 ways: > > > > a) using struct module, > > > > Yes, that's what it's for, and that's what you should be using. > > > My concern is that struct may need to parse the format string, > > construct the list, and de-reference index=0 for this generated list > > to get the int out. > > > There should be some way more efficient? > > The struct module is written in C, not in Python. It does have to parse a > string, yes, so, if you wrote your own, limited, C function to do the job, it > might be marginally faster. > > > > > > > b) using ctypes module, and > > > > Yeeaah, that would work, but that's really not what it's for. from_buffer > > > wants a writable buffer interface, which is unlikely to be what you want. > > > Actually my buffer is writable --- it's an bytearray. ?Turning it into > > a R/O one make me to do extra effort: wrapping the bytearray into > > buffer(). > > > My question is, this operation seems like to be much simpler than the > > former one, and it's very straightforward as well. ?Why is it slow? > > Unlike struct, it constructs an object you're not actually interested in > around your int. > > > it's hard to image why socket object provides the interface: > > socket.recv_from(buf[, num_bytes[, flags]]) but forget the more > > generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]]) > > Well, that's what pointer arithmetic (in C) or slices (in Python) are for! > There's an argument to be made for sticking close to the traditional > (originally C) interface here - it's familiar. Hi Thomas, - I'm not quite follow you. It will be great if you could show me some code no this part... > > ?- Thomas- Hide quoted text - > > - Show quoted text - From roy at panix.com Mon Aug 16 21:00:17 2010 From: roy at panix.com (Roy Smith) Date: Mon, 16 Aug 2010 21:00:17 -0400 Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: In article , Martin Gregorie wrote: > Say you have intensity data captured from an X-ray goniometer from 160 > degrees to 30 degrees at 0.01 degree resolution. Which is most evil of > the following? > > 1) real intensity[16000:3000] > for i from lwb intensity to upb intensity > plot(i/100, intensity[i]); How about (totally inventing syntax as I go along): 5) real intensity[160.0 : 30.0 : 0.01] for index, value in intensity: plot(index, value) From jacky.chao.wang at gmail.com Mon Aug 16 21:05:26 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 18:05:26 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: On Aug 17, 3:53?am, Mark Dickinson wrote: > On Aug 16, 8:36?pm, Mark Dickinson wrote: > > > > > > > On Aug 16, 8:08?pm, Jacky wrote: > > > My concern is that struct may need to parse the format string, > > > construct the list, and de-reference index=0 for this generated list > > > to get the int out. > > > > There should be some way more efficient? > > > Well, you can improve on the struct solution by using the > > struct.Struct class to avoid parsing the format string repeatedly: > > > >>> import struct > > >>> S = struct.Struct(' > >>> S.unpack_from(buffer(bytearray([1,2,3,4,5]))) > > > (67305985,) > > > This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit > > build of Python 2.6) though; ?it's probably more effective for long > > format strings. > > Sorry, this was inaccurate: ?this makes almost *no* significant > difference on my machine for large test runs (10000 and up). ?For > small ones, though, it's faster. ?The reason is that the struct module > caches (up to 100, in the current implementation) previously used > format strings, so with your tests you're only ever parsing the format > string once anyway. ?Internally, the struct module converts that > format string to a Struct object, and squirrels that Struct object > away into its cache, which is implemented as a dict from format > strings to Struct objects. ?So the next time that the format string is > used it's simply looked up in the cache, and the Struct object > retrieved. > > By the way, in Python 3.2 there's yet another fun way to do this, > using int.from_bytes. > > >>> int.from_bytes(bytearray([1,2,3,4]), 'little') Thanks! It looks pretty like the ctypes way. ;) > > 67305985 > > -- > Mark- Hide quoted text - > > - Show quoted text - From python at rcn.com Mon Aug 16 21:10:27 2010 From: python at rcn.com (Raymond Hettinger) Date: Mon, 16 Aug 2010 18:10:27 -0700 (PDT) Subject: random number generation References: <7d76d377-6a55-4320-afa4-8425719d8e6e@n19g2000prf.googlegroups.com> Message-ID: On Aug 16, 5:37?pm, Jah_Alarm wrote: > hi, > > I need to generate a binary array with a specified average proportion > of 1s (e.g. [1 0 0 0 > > 0 1 0 0] has this proportion = 25%). In Matlab I run something like > random(m,n)

> between 0 and 1. I'm trying to use random.randint(0,2,size=[m,n]), but > I don't understand how to specify this proportion p. Try this: >>> from random import random >>> [1 if random() < 0.25 else 0 for i in range(20)] [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0] Raymond From ariel.bys at gmail.com Mon Aug 16 21:19:28 2010 From: ariel.bys at gmail.com (AlphaBravo) Date: Mon, 16 Aug 2010 18:19:28 -0700 (PDT) Subject: 2 Regex Questions Message-ID: <4f350848-9f12-4c0d-aaaa-a35467b3f3a4@c10g2000yqi.googlegroups.com> Hello Comp.Lang,Python, 1) How do I parse Basic Posix RE's in Python (i need it because of some old scripts and a specific OS developed in Seattle) 2) How can I split a string into sections that MATCH a regex (rather then splitting by seperator). Tokenizer-style but ignoring every place from where I can't start a match? - Thanks, Ariel Ben-Yehuda -- - Ariel Ben-Yehuda From python at rcn.com Mon Aug 16 21:29:33 2010 From: python at rcn.com (Raymond Hettinger) Date: Mon, 16 Aug 2010 18:29:33 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> Message-ID: <2abafeea-78e6-454c-8c3d-debe888d2bc7@h40g2000pro.googlegroups.com> [Paddy] > Lets say you have two *sets* of integers representing two near-copies > of some system, then a measure of their difference could be calculated > as: > > len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 % > > If the two collections of integers are allowed duplicates then you > need a Counter/bag/multi-set type and the diff calculation I gave > originally. Thanks for sharing your use case. It's unlikely that I will add this method to the Counter API because the rarity of use case does not warrant the added API complexity. IMO, adding a method like this makes the class harder to learn, understand and remember. It doesn't seem like much of a win over using the existing alternatives: * (b - c) + (c - b) * (b | c) - (b & c) * DIY using the two counters as simple dicts * writing a subclass providing additional binary operations I would like to see someone post a subclass to the ASPN Cookbook that adds a number of interesting, though not common operations. Your symmetric_difference() method could be one. A dot_product() operation could be another. Elementwise arithmetic is another option (we already have add and subtract, but could possibly use multiply, divide, etc). Scaling operations are another possibility (multiple all elements by five, for example). The Counter() class has low aspirations. It is a dictionary that fills-in missing values with zero and is augmented by a handful of basic methods for managing the counts. Raymond From chrischia82 at gmail.com Mon Aug 16 21:38:06 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Mon, 16 Aug 2010 18:38:06 -0700 (PDT) Subject: how to switch image in tkinter? making it mutable? how? References: <414ff6dd-73ef-48df-bd2b-080a2c710e5b@h17g2000pri.googlegroups.com> Message-ID: On Aug 17, 2:57?am, Jeff Hobbs wrote: > On Aug 16, 7:30?am, ChrisChia wrote: > > > I have this: > > image1 = ImageTk.PhotoImage(file = "c:\\f1.jpg") > > image2 = ImageTk.PhotoImage(file = "c:\\f2.jpg") > > > imagelist.append(image1) > > imagelist.append(image2) > > > self.label ?= tk.Label(image = imagelist[0]) > > > is there a way that i can create a method to switch the display the > > image2 (imagelist 2nd element) > > without using label.bind? > > > can i make an image mutable? > > self.label.configure(image = imagelist[1]) will change the image > displayed. > With PIL images, you can use image1.fromstring(...) that should have a > similar effect, in that it changes the underlying image data and the > label will display that. > > Whether you need to label.bind or something else to effect this change > is up to you. ?You could have it happen on a timer, triggered by an > event, or randomly effected by solar flares, depending on your > application's needs. > > Jeff Yes... I don't intend to make it mutable anymore... thanks to Jeff for the self.label.configure i don't even know about the configure method. I m very new to tkinter. Thanks everyone!!! From hammer777123 at gmail.com Mon Aug 16 21:53:50 2010 From: hammer777123 at gmail.com (hammer777123) Date: Mon, 16 Aug 2010 18:53:50 -0700 (PDT) Subject: RECEIVE $60 JUST FOR JOINING FREE MEMBERS Message-ID: RECEIVE $60 JUST FOR JOINING FREE MEMBERS http://tinyurl.com/2dwcgxf Join for Free and Get $10 http://www.geostring.com/?1226648 NewaveMoneyMaker__FREE 30 Day Trial__4,650 Followers In 7 days http://tinyurl.com/2gx63ye Want Better Than The "Average" P_ _ _ _ Size? 2 FREE Bottles http://mhlnk.com/DF434BFB Free $5.00 to Join___$0.5 Paid Per Click http://tinyurl.com/3xanc6c From ldo at geek-central.gen.new_zealand Mon Aug 16 22:00:32 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 17 Aug 2010 14:00:32 +1200 Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: In message , Roy Smith wrote: > 5) real intensity[160.0 : 30.0 : 0.01] How many elements in that array? a) 2999 b) 3000 c) neither of the above From roy at panix.com Mon Aug 16 22:29:27 2010 From: roy at panix.com (Roy Smith) Date: Mon, 16 Aug 2010 22:29:27 -0400 Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message , Roy Smith wrote: > > > 5) real intensity[160.0 : 30.0 : 0.01] > > How many elements in that array? > > a) 2999 > b) 3000 > c) neither of the above c) neither of the above. More specifically, 13,001 (if I counted correctly). From andrei.avk at gmail.com Mon Aug 16 22:35:49 2010 From: andrei.avk at gmail.com (AK) Date: Mon, 16 Aug 2010 22:35:49 -0400 Subject: 79 chars or more? Message-ID: <4C69F585.5050504@gmail.com> As monitors are getting bigger, is there a general change in opinion on the 79 chars limit in source files? I've experimented with 98 characters per line and I find it quite a bit more comfortable to work with that length, even though sometimes I have to edit files in 80 width terminals, it's still easier to adapt to some inconvenience when that happens than the other way around, since about 95% of time or more, I do use wider editor window or terminal. Is going over 79 still a terrible thing to do? -andrei From prologic at shortcircuit.net.au Mon Aug 16 22:42:19 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 17 Aug 2010 12:42:19 +1000 Subject: 79 chars or more? In-Reply-To: <4C69F585.5050504@gmail.com> References: <4C69F585.5050504@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: > As monitors are getting bigger, is there a general change in opinion on > the 79 chars limit in source files? I've experimented with 98 characters > per line and I find it quite a bit more comfortable to work with that > length, even though sometimes I have to edit files in 80 width > terminals, it's still easier to adapt to some inconvenience when that > happens than the other way around, since about 95% of time or more, I do > use wider editor window or terminal. > > Is going over 79 still a terrible thing to do? ?-andrei My personal opinion (despite monitors being wider) is the horizontal scrolling isn't worth it. Stick to a 80-char width. cheers james -- -- James Mills -- -- "Problems are solved by method" From roy at panix.com Mon Aug 16 22:50:57 2010 From: roy at panix.com (Roy Smith) Date: Mon, 16 Aug 2010 22:50:57 -0400 Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> Message-ID: In article , James Mills wrote: > On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: > > As monitors are getting bigger, is there a general change in opinion on > > the 79 chars limit in source files? I've experimented with 98 characters > > per line and I find it quite a bit more comfortable to work with that > > length, even though sometimes I have to edit files in 80 width > > terminals, it's still easier to adapt to some inconvenience when that > > happens than the other way around, since about 95% of time or more, I do > > use wider editor window or terminal. > > > > Is going over 79 still a terrible thing to do? ??-andrei > > My personal opinion (despite monitors being wider) is > the horizontal scrolling isn't worth it. Stick to a 80-char width. I disagree with James. I have no problem with going wider than 80, if it improves readability by not forcing you to fold lines in unnatural places. There's more important things to worry about. From andrei.avk at gmail.com Mon Aug 16 22:59:17 2010 From: andrei.avk at gmail.com (AK) Date: Mon, 16 Aug 2010 22:59:17 -0400 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> Message-ID: <4C69FB05.7070307@gmail.com> On 08/16/2010 10:42 PM, James Mills wrote: > On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: >> As monitors are getting bigger, is there a general change in opinion on >> the 79 chars limit in source files? I've experimented with 98 characters >> per line and I find it quite a bit more comfortable to work with that >> length, even though sometimes I have to edit files in 80 width >> terminals, it's still easier to adapt to some inconvenience when that >> happens than the other way around, since about 95% of time or more, I do >> use wider editor window or terminal. >> >> Is going over 79 still a terrible thing to do? -andrei > > My personal opinion (despite monitors being wider) is > the horizontal scrolling isn't worth it. Stick to a 80-char width. But.. why horizontal scrolling, isn't autowrap much better than that? -andrei From prologic at shortcircuit.net.au Mon Aug 16 23:00:51 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 17 Aug 2010 13:00:51 +1000 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 12:50 PM, Roy Smith wrote: > I disagree with James. ?I have no problem with going wider than 80, if > it improves readability by not forcing you to fold lines in unnatural > places. > > There's more important things to worry about. Roy, under normal circumstances I would agree with you and have a different opinion. However being vision impaired restricts the available width (irregardless of the width of the monitor) of text I'm able to view at once. :) cheers James -- -- James Mills -- -- "Problems are solved by method" From sigma.z.1980 at gmail.com Mon Aug 16 23:07:14 2010 From: sigma.z.1980 at gmail.com (Aram Ter-Sarkissov) Date: Mon, 16 Aug 2010 20:07:14 -0700 (PDT) Subject: array manipulation- Message-ID: hi, this is probably a very silly question, but I can't get my hear around it unfortunately( I have an array (say, mat=rand(3,5)) from which I 'pull out' a row (say, s1=mat[1,]). The problem is, the shape of this row s1 is not [1,5], as I would expect, but rather [5,], which means that I can't, for example, concateante mat and s1 rowwise. thanks for the help From kreglet at gmail.com Mon Aug 16 23:33:55 2010 From: kreglet at gmail.com (kreglet) Date: Mon, 16 Aug 2010 22:33:55 -0500 Subject: bash: syntax error near unexpected token Message-ID: Hello, I started learning python last year. All of this time i have used the terminal and gedit to create, modify, and test my applications and modules. For some reason I can not do this any more. I'll try to do my best to explain whats happening. I have a script modtest.py which has a function to test if an int is even or odd. Before: desktop:~/bin$ modtest.py desktop:~/bin$ evenodd(45) 45 is odd Now: desktop:~/bin$ modtest.py desktop:~/bin$ evenodd(45) bash: syntax error near unexpected token `45' The above is just an example. ALL of my scripts that worked before no longer work in the terminal yet they work in the python interpreter. Does anyone know what the problem might be and how I can fix it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Mon Aug 16 23:40:42 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 16 Aug 2010 23:40:42 -0400 Subject: bash: syntax error near unexpected token In-Reply-To: References: Message-ID: On Mon, Aug 16, 2010 at 11:33 PM, kreglet wrote: > Hello, > > I started learning python last year. All of this time i have used the > terminal and gedit to create, modify, and test my applications and modules. > For some reason I can not do this any more. > I'll try to do my best to explain whats happening. > > I have a script modtest.py which has a function to test if an int is even or > odd. > > Before: > desktop:~/bin$ modtest.py > desktop:~/bin$ evenodd(45) > 45 is odd > That never worked. You can execute Python scripts from the shell, but not arbitrary Python functions. Perhaps you were calling Python using the -i flag, which runs the interactive interpreter after the script is finished executing. $ python -i modtest.py >>> evenodd(45) 45 is odd > Now: > desktop:~/bin$ modtest.py > desktop:~/bin$ evenodd(45) > bash: syntax error near unexpected token `45' > And this is what's supposed to happen any time you try this in any shell. When you call evenodd, bash looks for a program or shell built-in called evenodd. Which doesn't exist. > The above is just an example. ALL of my scripts that worked before no longer > work in the terminal yet they work in the python interpreter. > > Does anyone know what the problem might be and how I can fix it? > > From steve-REMOVE-THIS at cybersource.com.au Mon Aug 16 23:51:19 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 17 Aug 2010 03:51:19 GMT Subject: 79 chars or more? References: Message-ID: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 22:35:49 -0400, AK wrote: > As monitors are getting bigger, is there a general change in opinion on > the 79 chars limit in source files? I've experimented with 98 characters > per line and I find it quite a bit more comfortable to work with that > length, even though sometimes I have to edit files in 80 width > terminals, it's still easier to adapt to some inconvenience when that > happens than the other way around, since about 95% of time or more, I do > use wider editor window or terminal. > > Is going over 79 still a terrible thing to do? -andrei For your own code, you are free to do anything you like :) But if you want to submit code to the Python standard library, you have to restrict lines to 79 characters. This is no different from any other project -- you need to stick to the project's coding conventions. There are still good reasons to stick with 79 chars, even on large screen monitors. People with poor vision will appreciate being able to increase the font size. Others might like to have two windows side-by-side, each showing 79 characters. Some people don't have wide monitors. -- Steven From robert.kern at gmail.com Mon Aug 16 23:56:20 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 16 Aug 2010 22:56:20 -0500 Subject: Python "why" questions In-Reply-To: References: <8crequF9tpU1@mid.individual.net> Message-ID: On 8/16/10 9:29 PM, Roy Smith wrote: > In article, > Lawrence D'Oliveiro wrote: > >> In message, Roy Smith wrote: >> >>> 5) real intensity[160.0 : 30.0 : 0.01] >> >> How many elements in that array? >> >> a) 2999 >> b) 3000 >> c) neither of the above > > c) neither of the above. More specifically, 13,001 (if I counted > correctly). 13000, actually. Floating point is a bitch. [~/Movies] |1> import numpy [~/Movies] |2> len(numpy.r_[160.0:30.0:-0.01]) 13000 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Mon Aug 16 23:58:33 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 16 Aug 2010 22:58:33 -0500 Subject: array manipulation- In-Reply-To: References: Message-ID: On 8/16/10 10:07 PM, Aram Ter-Sarkissov wrote: > hi, this is probably a very silly question, but I can't get my hear > around it unfortunately( > > I have an array (say, mat=rand(3,5)) from which I 'pull out' a row > (say, s1=mat[1,]). The problem is, the shape of this row s1 is not > [1,5], as I would expect, but rather [5,], which means that I can't, > for example, concateante mat and s1 rowwise. > > thanks for the help You can ask numpy questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From jah.alarm at gmail.com Tue Aug 17 00:07:09 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Mon, 16 Aug 2010 21:07:09 -0700 (PDT) Subject: update of elements in GUI Message-ID: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> hi, I've already asked this question but so far the progress has been small. I'm running Tkinter. I have some elements on the screen (Labels, most importantly) which content has to be updated every iteration of the algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm using the update_idletasks() command in the function itself after the variable.set(...) command. The variable type is IntVar(), and the mistake I'm getting is 'IntVar instance has no attribute 'update_idletasks'. No updates are displayed, of course. Without the GUI the algorithm (it's a genetic algorithm) is working fine, but I need to make it available to other people via GUI cheers, Alex From steve-REMOVE-THIS at cybersource.com.au Tue Aug 17 00:10:31 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 17 Aug 2010 04:10:31 GMT Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 22:56:20 -0500, Robert Kern wrote: > On 8/16/10 9:29 PM, Roy Smith wrote: >> In article, >> Lawrence D'Oliveiro wrote: >> >>> In message, Roy Smith wrote: >>> >>>> 5) real intensity[160.0 : 30.0 : 0.01] >>> >>> How many elements in that array? >>> >>> a) 2999 >>> b) 3000 >>> c) neither of the above >> >> c) neither of the above. More specifically, 13,001 (if I counted >> correctly). > > 13000, actually. Floating point is a bitch. > > [~/Movies] > |1> import numpy > > [~/Movies] > |2> len(numpy.r_[160.0:30.0:-0.01]) > 13000 Actually, the answer is 0, not 13000, because the step size is given as 0.01, not -0.01. >>> import numpy >>> len(numpy.r_[160.0:30.0:-0.01]) 13000 >>> len(numpy.r_[160.0:30.0:0.01]) 0 -- Steven From tom.harris at setec.com.au Tue Aug 17 00:11:40 2010 From: tom.harris at setec.com.au (Tom Harris) Date: Tue, 17 Aug 2010 14:11:40 +1000 Subject: Eval cannot see globals from another module Message-ID: <668645A55F306549B1C6D0D0602A2F9C831230@mail1.mel.setec.com.au> Greetings, I want a debugging function with the effect of the function below (in a seperate module): def dump(expr): print expr, '=', eval(expr) foo = 33 dump('foo') Of course this fails when called from another module because eval does not know the globals or locals of the caller. Is there a way to make this work? TomH -------- Email from setec.com.au does not necessarily represent the official policy of SETEC Pty Ltd. See http://www.setec.com.au/emaildisclaimer20060629.html for details. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrei.avk at gmail.com Tue Aug 17 00:12:47 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 00:12:47 -0400 Subject: 79 chars or more? In-Reply-To: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> Message-ID: <4C6A0C3F.9060900@gmail.com> On 08/16/2010 11:51 PM, Steven D'Aprano wrote: > On Mon, 16 Aug 2010 22:35:49 -0400, AK wrote: > >> As monitors are getting bigger, is there a general change in opinion on >> the 79 chars limit in source files? I've experimented with 98 characters >> per line and I find it quite a bit more comfortable to work with that >> length, even though sometimes I have to edit files in 80 width >> terminals, it's still easier to adapt to some inconvenience when that >> happens than the other way around, since about 95% of time or more, I do >> use wider editor window or terminal. >> >> Is going over 79 still a terrible thing to do? -andrei > > For your own code, you are free to do anything you like :) > > But if you want to submit code to the Python standard library, you have > to restrict lines to 79 characters. This is no different from any other > project -- you need to stick to the project's coding conventions. > > > There are still good reasons to stick with 79 chars, even on large screen > monitors. People with poor vision will appreciate being able to increase > the font size. Others might like to have two windows side-by-side, each > showing 79 characters. Some people don't have wide monitors. There's no doubt that there are pro's and con's, but to be fair, it's not like code becomes unreadable over 79 chars - the difference is that when your terminal is 80 chars, it's less convenient for you to read code that's wider and when your terminal is wider, it's less convenient to read code that's 79 chars. I guess I'm just curious what percentage of people prefer 79chars - is it 5/95% or 15/85% or 50/50? -andrei > > > > From prologic at shortcircuit.net.au Tue Aug 17 00:26:29 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 17 Aug 2010 14:26:29 +1000 Subject: 79 chars or more? In-Reply-To: <4C6A0C3F.9060900@gmail.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 2:12 PM, AK wrote: > There's no doubt that there are pro's and con's, but to be fair, it's > not like code becomes unreadable over 79 chars - the difference is that > when your terminal is 80 chars, it's less convenient for you to read > code that's wider and when your terminal is wider, it's less convenient > to read code that's 79 chars. I guess there are two-sides to the coin here so to speak. See I'm vision impaired so I prefer a 79 char width in my own projects and expect those that work with me to use the same standards (stick to project standards as Steven says). The other side is this... I'm of the opinion that if you're writing a line of code that's excessively long (>80char or say >100chars), then you might want to reconsider what you're doing :) (It might be wrong). cheers james -- -- James Mills -- -- "Problems are solved by method" From cbrown at cbrownsystems.com Tue Aug 17 00:31:50 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Mon, 16 Aug 2010 21:31:50 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> Message-ID: <97d677a0-8d15-4d18-9e06-74eef08bd39c@q16g2000prf.googlegroups.com> On Aug 16, 11:04?am, Baba wrote: > Hi Chas, Roald, > > These are all complicated formula that i believe are not expected at > this level. If you look at the source (see my first submission) you > will see that this exercise is only the second in a series called > "Introduction to Programming". Therefore i am convinced that there is > a much simpler solution. The question I was responding to (a different one than your original question) was whether there was a proof of Baba's conjecture that a largest unobtainable quantity was possible if, and only if, the three numbers in question had a gcd of 1. Roald had something like a "gut feeling" that it was true, but such things are generally much more clear cut than "gut feelings" - they can often easily be /proven/ to be true or false, given the right mental tools. In this case, that proof I gave doesn't immediately yield a concrete answer to your /original/ question - assuming that a largest obtainable solution is possible, /how/ do we find the largest unobtainable solution? But it certainly identifies the conditions whereby we can easily and quickly say that there is no such solution, or conversely that such a solution must exist; and that is often extremely helpful to finding an algorithm that /does/ answer your original question. (One thing it does provide is an upper bound to the space of solutions that you should be looking at - and finding upper bounds and lower bounds is a common programming task. Again, this isn't something that you might be "expected" to know about at your level of study, but it doesn't hurt you to be aware of it either :)!) > > Now, i believe that the number of consecutive passes required to make > this work is equal to the smallest number of pack sizes. That is your belief, your intuition; and developing good intuitions is good... BUT... > So if we have > packs of (9,12,21) the number of passes needed would be 9 and... ... and now whatever you might go on to add is simply "going off into the weeds", because I have just proven that there can be /no/ such solution in that case: all three of those numbers are divisible by 3, so you are not "on the trail" when trying to figure out a general solution by considering examples of the type you mention. At your level of study, such things may seem overly complicated (and are certainly /not/ required to simply answer the question as originally stated). But consider the thread in this group called "python interview questions": http://groups.google.com/group/comp.lang.python/browse_frm/thread/bb4d3514e9842f9e# The "FizzBuzz" question involves a similar very basic grasp of the type of mathematical reasoning and thinking that is most valued in programmers in the job market. Of course, your Python class is not the right place to be focusing exclusively on this sort of mathematics, but I would encourage you to simultaneously educate yourself both in the /language/ learning of Python (which is what your class is largely about), along with the more universally applicable skill set that comes from understanding the mathematical justifications of a "good" algorithm That additional knowledge will serve you equally well whether you are programming in Python, Perl, Ruby, Java, C++, D, F, R, and so on (surely someone will claim "Z" as a language soon, if they haven't already...). > ... the > theorem would read > > "If it is possible to buy n,n+1,n+2,...n+8 nuggets it is possible to > buy any number of nuggets >= 9 given that they come in packs of > 9,12,21" > So I would ask as a simple exercise: how would you go about /proving/ that your assertion is actually a /theorem/, and not just a pretty solid hunch that your statement is true because for small enough numbers you can easily "do it in your head"? Yes, it's "clearly true", but that is not a proof! That is the muscle which is exercised by mathematical reasoning. > However i turn in circles because i don't seem to get any results for > some random pack combinations like (9,12,21) or (10,20,30). > Well, your intuitions are certainly close to the mark. But if you added to your study a course on discrete mathematics, then you would also immediately see why such turning in circles obviously can bear no fruit, and that would give you a great advantage in solving far more difficult and yet common problems of this type. Cheers - Chas From woooee at gmail.com Tue Aug 17 00:47:24 2010 From: woooee at gmail.com (woooee) Date: Mon, 16 Aug 2010 21:47:24 -0700 (PDT) Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> Message-ID: On Aug 16, 9:07?pm, Jah_Alarm wrote: I have some elements on the screen (Labels, most > importantly) which content has to be updated every iteration of the > algorithm The variable type is IntVar() You would use int_var_name.set(some_number) From andrei.avk at gmail.com Tue Aug 17 00:50:39 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 00:50:39 -0400 Subject: 79 chars or more? In-Reply-To: References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> Message-ID: <4C6A151F.7070803@gmail.com> On 08/17/2010 12:26 AM, James Mills wrote: > On Tue, Aug 17, 2010 at 2:12 PM, AK wrote: >> There's no doubt that there are pro's and con's, but to be fair, it's >> not like code becomes unreadable over 79 chars - the difference is that >> when your terminal is 80 chars, it's less convenient for you to read >> code that's wider and when your terminal is wider, it's less convenient >> to read code that's 79 chars. > > I guess there are two-sides to the coin here so to speak. See I'm > vision impaired > so I prefer a 79 char width in my own projects and expect those that work > with me to use the same standards (stick to project standards as Steven says). > > The other side is this... I'm of the opinion that if you're writing a > line of code > that's excessively long (>80char or say>100chars), then you might want to > reconsider what you're doing :) (It might be wrong). I stay away from ugly cramped one-liners; I mostly run over 79 when I have a few `and` and `or` clauses or long strings. I've also noticed something interesting: going from 79 to 99 affects a relatively large number of lines, but going over 99 (i.e. 99 to 132) is much, much rarer. By the way, the reason I asked is that we're working on a python tutorial and I realized that even though I'm used to 99, I wasn't sure if it's ok to teach that to new users or not.. -andrei From prologic at shortcircuit.net.au Tue Aug 17 01:08:53 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 17 Aug 2010 15:08:53 +1000 Subject: 79 chars or more? In-Reply-To: <4C6A151F.7070803@gmail.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <4C6A151F.7070803@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 2:50 PM, AK wrote: > By the way, the reason I asked is that we're working on a python > tutorial and I realized that even though I'm used to 99, I wasn't sure > if it's ok to teach that to new users or not.. In my opinion it would be "okay" to teach. However: Bare in mind other considerations for smaller width conventions and the reasons for them. Make your students aware of standards and get them into the habit of following standards early on. cheers James -- -- James Mills -- -- "Problems are solved by method" From torriem at gmail.com Tue Aug 17 01:15:53 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 16 Aug 2010 23:15:53 -0600 Subject: 79 chars or more? In-Reply-To: <4C69FB05.7070307@gmail.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> Message-ID: <4C6A1B09.6070905@gmail.com> On 08/16/2010 08:59 PM, AK wrote: > But.. why horizontal scrolling, isn't autowrap much better than that? Wouldn't it really make a visual mess of Python code if lines wrapped? Maybe if they wrapped smartly. In general, the only time I find my lines longer than 75 characters are strings or sometimes conditionals for if statements. But normally I can wrap them manually so that things look neat and tidy. In general if I find myself consistently going longer than 75 or 80 characters, I need to refactor my code to make it more manageable. If I have to scroll up five pages to find the beginning of a block, that normally means my code could be simplified and improved. From torriem at gmail.com Tue Aug 17 01:20:51 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 16 Aug 2010 23:20:51 -0600 Subject: 79 chars or more? In-Reply-To: <4C6A151F.7070803@gmail.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <4C6A151F.7070803@gmail.com> Message-ID: <4C6A1C33.8040206@gmail.com> On 08/16/2010 10:50 PM, AK wrote: > I stay away from ugly cramped one-liners; I mostly run over 79 when I > have a few `and` and `or` clauses or long strings. I've also noticed > something interesting: going from 79 to 99 affects a relatively large > number of lines, but going over 99 (i.e. 99 to 132) is much, much rarer. I have found something similar, despite my previous post. But you can normally break the and and or long clauses with backslash line-continuators. You can also break strings similarly: a = "This is a really long line that ordinarily would " \ "be long. Test message: %s " % ( message_string) > By the way, the reason I asked is that we're working on a python > tutorial and I realized that even though I'm used to 99, I wasn't sure > if it's ok to teach that to new users or not.. I wouldn't worry about it if I were you. Once they know how to program in Python then you can work on that. Probably more important to be taught the reasons behind PEP8. You could probably say that many coders recommend that lines not exceed 80 characters, and state that code in the standard library has to be less than that, but that on occasion longer lines are probably not going to kill them. From eric.brunel at pragmadev.nospam.com Tue Aug 17 03:19:59 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Tue, 17 Aug 2010 09:19:59 +0200 Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> Message-ID: In article <24dc97b3-a8b5-4638-9cf5-a397f1eae295 at q16g2000prf.googlegroups.com>, Jah_Alarm wrote: > hi, I've already asked this question but so far the progress has been > small. > > I'm running Tkinter. I have some elements on the screen (Labels, most > importantly) which content has to be updated every iteration of the > algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm > using the update_idletasks() command in the function itself after the > variable.set(...) command. The variable type is IntVar(), and the > mistake I'm getting is 'IntVar instance has no attribute > 'update_idletasks'. No updates are displayed, of course. You have to call update_idletasks on a Tkinter *widget*, not a variable. You can call it on your window (Tk or Toplevel instance) or on your label for example. This way, it should work. > Without the GUI the algorithm (it's a genetic algorithm) is working > fine, but I need to make it available to other people via GUI > > cheers, > > Alex From eric.brunel at pragmadev.nospam.com Tue Aug 17 03:21:59 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Tue, 17 Aug 2010 09:21:59 +0200 Subject: Textvariable display in label (GUI design) References: <993d9560-564d-47f0-b2db-6f0c6404ae81@g6g2000pro.googlegroups.com> Message-ID: In article , Jah_Alarm wrote: > On Aug 17, 3:32??am, Eric Brunel > wrote: > > In article > > <993d9560-564d-47f0-b2db-6f0c6404a... at g6g2000pro.googlegroups.com>, > > > > ??Jah_Alarm wrote: > > > hi, > > > > > pls help me out with the following issue: I wrote a function that uses > > > a for loop that changes a value of a certain variable each iteration. > > > What I want is by clicking a button in GUI (with the command bound to > > > this function) this value each iteration is displayed in a textbox > > > (label). So far only one (starting value) is displayed. > > > > > thanks, > > > > > Alex > > > > First, with posts like this, you're highly unlikely to get any useful > > answer: please strip down your code to the smallest part that displays > > the problem, post this code here, explaining what you're expecting and > > what you're getting. Otherwise, people just won't know what you're > > talking about unless they have a crystal ball?? > > > > Now using my own crystal ball: if you don't return the control to the > > GUI each time your variable is increased, the GUI won't get a chance to > > update itself. Since you seem to use Tkinter (another wild guess??), you > > probably need a call to the update_idletasks method on any Tkinter > > widget each time you change your TextVariable. > > > > HTH > > ??- Eric - > > Thanks, but where is this command used, in the button than runs the > algorithm, the label or the function itself? Wherever you want, the only requirement being that you should have a widget at hand, in a class attribute or a global variable or whatever. I would put it just after I do any my_variable.set(???) if possible. From __peter__ at web.de Tue Aug 17 03:23:09 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Aug 2010 09:23:09 +0200 Subject: 2 Regex Questions References: <4f350848-9f12-4c0d-aaaa-a35467b3f3a4@c10g2000yqi.googlegroups.com> Message-ID: AlphaBravo wrote: > 2) How can I split a string into sections that MATCH a regex (rather > then splitting by seperator). Tokenizer-style but ignoring every place > from where I can't start a match? >>> import re >>> re.compile("[abc]+").findall("abcxaaa! abba") ['abc', 'aaa', 'abba'] From ldo at geek-central.gen.new_zealand Tue Aug 17 03:47:38 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 17 Aug 2010 19:47:38 +1200 Subject: 79 chars or more? References: Message-ID: In message , AK wrote: > As monitors are getting bigger, is there a general change in opinion on > the 79 chars limit in source files? WHAT 79-character limit in source files? I currently have my Emacs windows set at 100 characters wide, and I?m thinking of going wider. Remember, the old hardcopy terminals used to produce 132-character-wide listings. From michele.simionato at gmail.com Tue Aug 17 03:59:12 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 17 Aug 2010 00:59:12 -0700 (PDT) Subject: 79 chars or more? References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> Message-ID: <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> On Aug 17, 6:50?am, AK wrote: > On 08/17/2010 12:26 AM, James Mills wrote: > By the way, the reason I asked is that we're working on a python > tutorial and I realized that even though I'm used to 99, I wasn't sure > if it's ok to teach that to new users or not.. > > ? ?-andrei It is certainly NOT useful to teach a convention which is explicitly discouraged in the Python guidelines (PEP 8). Having said that, I particularly *hate* people using long lines, and I usually reindent the code of my coworkers not following that convention. The reason is that my Emacs is set to 79 chars and longer code looks ugly, that I look at two-side diffs all the time, and that sometimes I want to print on paper the code I have to work with. OTOH, I do not see a single advantage in using long lines. Michele Simionato From torbenm at diku.dk Tue Aug 17 04:17:58 2010 From: torbenm at diku.dk (Torben Ægidius Mogensen) Date: Tue, 17 Aug 2010 10:17:58 +0200 Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <7zaaolzm89.fsf@ask.diku.dk> Standish P writes: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? > > Because a stack has push and pop, it is able to release and allocate > memory. We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. See http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 http://portal.acm.org/citation.cfm?doid=174675.177855 http://www.springerlink.com/content/m2074884n6gt612h/ Torben From giacomo.boffi at polimi.it Tue Aug 17 04:48:51 2010 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Tue, 17 Aug 2010 10:48:51 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: <86wrrppqto.fsf@aiuole.stru.polimi.it> Paul Rubin writes: > Baba writes: >> exercise: given that packs of McNuggets can only be bought in 6, 9 or >> 20 packs, write an exhaustive search to find the largest number of >> McNuggets that cannot be bought in exact quantity. > > Is that a homework problem? yes, and no it was a homework problem, assigned in 2008, as clearly stated by the OP most of what was discussed on the ng was clearly stated in the introduction to the actual problem, so that we can thank Baba for NOT having read the text of the assignment, leavin' us a couple of days of amusing and interesting posts -- Mangiate pure le vostre carote, noi mangeremo le nostre salsicce! -- Claud, in IHC From hpj at urpla.net Tue Aug 17 05:08:39 2010 From: hpj at urpla.net (Hans-Peter Jansen) Date: Tue, 17 Aug 2010 11:08:39 +0200 Subject: segfault with small pyqt script In-Reply-To: References: <201008152317.13757.hpj@urpla.net> Message-ID: <201008171108.39638.hpj@urpla.net> On Monday 16 August 2010, 09:22:27 Gelonida wrote: > Hi Hans-Peter, > > > It seems, that my other posts did not get through. > > On 08/15/2010 11:17 PM, Hans-Peter Jansen wrote: > > For a starter, tell us the versions of python-sip, and python-qt4 or > > however they're called in Ubuntu. For the record, > > python-sip-4.10.5-1.1 > > python-qt4-4.7.4-1.1 > > doesn't show this behavior. > > > > The problem seems to be known for 4.7.2. > For simple code I managed to work around the issue. > For the real more complicated I didn't. So it seems > I'll have to avoid 4.7.2. > [...] > > For more complex multi widget examples it doesn't seem enough to just > destroy the main widget. > probably I had to recursively assign all widgets / dialogues sub widgets > to None. > > So I'll just try to stay away from this pyqt release and stick with > older or newer ones. If you test sip 4.10.5 by chance, it would be nice to leave a brief note about the outcome. As long as you replace (qscintilla, if you use it), sip and PyQt, the probability of a bad influence on your system is pretty small. Replacing PyKDE aka kdebindings4 might not be that easy, though.. I might even get around also building Ubuntu packages in openSUSE build service one day... Various openSUSE builds are available here: http://download.opensuse.org/repositories/home:/frispete:/pyqt/ Pete From jeanmichel at sequans.com Tue Aug 17 05:28:33 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 17 Aug 2010 11:28:33 +0200 Subject: 79 chars or more? In-Reply-To: <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> Message-ID: <4C6A5641.4070109@sequans.com> Michele Simionato wrote: > On Aug 17, 6:50 am, AK wrote: > >> On 08/17/2010 12:26 AM, James Mills wrote: >> By the way, the reason I asked is that we're working on a python >> tutorial and I realized that even though I'm used to 99, I wasn't sure >> if it's ok to teach that to new users or not.. >> >> -andrei >> > > It is certainly NOT useful to teach a convention which is explicitly > discouraged in the Python guidelines (PEP 8). Having said that, I > particularly *hate* people using long lines, and I usually reindent > the code of my coworkers not following that convention. > The reason is that my Emacs is set to 79 chars and longer code looks > ugly, that I look at two-side diffs all the time, and that sometimes I > want to print on paper the code I have to work with. OTOH, I do not > see a single advantage in using long lines. > > Michele Simionato > Using long lines can sometimes improve readability, procude better shaped code, 'cause wrapping code to 79 chars may not be "natural" in all cases. We do have a strong habit using meaningfull & plain names in our code, no i, j, k ; cmdLine is always replaced by commandLine. So lines can easily exceed 79 chars and wrapping it would'nt be easy. I'm not saying wrapping to 79 is wrong, I'm just saying that they are advantages of using long lines (the 1st obvious one being not to care about wrapping text). Saying that, if one intend to distribute its code, he should stick to 80 chars per line. JM From ariel.bys at gmail.com Tue Aug 17 05:35:24 2010 From: ariel.bys at gmail.com (AlphaBravo) Date: Tue, 17 Aug 2010 02:35:24 -0700 (PDT) Subject: 2 Regex Questions References: <4f350848-9f12-4c0d-aaaa-a35467b3f3a4@c10g2000yqi.googlegroups.com> Message-ID: On Aug 17, 10:23?am, Peter Otten <__pete... at web.de> wrote: > AlphaBravo wrote: > > ?2) How can I split a string into sections that MATCH a regex (rather > > then splitting by seperator). Tokenizer-style but ignoring every place > > from where I can't start a match? > >>> import re > >>> re.compile("[abc]+").findall("abcxaaa! abba") > > ['abc', 'aaa', 'abba'] Thanks for 2 From jah.alarm at gmail.com Tue Aug 17 05:49:46 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Tue, 17 Aug 2010 02:49:46 -0700 (PDT) Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> Message-ID: <26c363c8-11d7-49b9-a1c1-251ab5ff934e@p22g2000pre.googlegroups.com> thanks. The thing is, the objects actually get updated without this command, but when I run the GUI outside of python shell (i.e. in command prompt as python filename.py or compile it to .exe file) the objects do not get updated. I tried Label(mainframe,textvariable=var).grid(column=1,row=1).update_idletasks() and mainframe.update_idletasks() but it still doesn't work. On Aug 17, 7:19?pm, Eric Brunel wrote: > In article > <24dc97b3-a8b5-4638-9cf5-a397f1eae... at q16g2000prf.googlegroups.com>, > > ?Jah_Alarm wrote: > > hi, I've already asked this question but so far the progress has been > > small. > > > I'm running Tkinter. I have some elements on the screen (Labels, most > > importantly) which content has to be updated every iteration of the > > algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm > > using the update_idletasks() command in the function itself after the > > variable.set(...) command. The variable type is IntVar(), and the > > mistake I'm getting is 'IntVar instance has no attribute > > 'update_idletasks'. No updates are displayed, of course. > > You have to call update_idletasks on a Tkinter *widget*, not a variable. > You can call it on your window (Tk or Toplevel instance) or on your > label for example. This way, it should work. > > > > > Without the GUI the algorithm (it's a genetic algorithm) is working > > fine, but I need to make it available to other people via GUI > > > cheers, > > > Alex From tania786786 at gmail.com Tue Aug 17 05:53:58 2010 From: tania786786 at gmail.com (tania tani) Date: Tue, 17 Aug 2010 02:53:58 -0700 (PDT) Subject: EARN 10$ PER ADVERTISEMENT OF 60 SEC Message-ID: MESSAGE NO 1 FOR YOU READ IT. http://www.fineptc.com/index.php?ref=imranraza460 Hello my dear friend, I hope you will be fine. i want to tell you the authentic way to make money with no investment. Here you can make 60 dollars in just six minutes. No investment its free.....Trial is essential... 1 Just click on the obove link 2 create your account on the website. ( it will take 2 or three minutesits absouloutely free no subscription fee ) 3 Now loging with your username and the password 4 Then click on the "" view adds"" tab 5 There will be 6 or 7 adds links ( consisting 60 seconds each ) 6 Click on a particular add and watch it for 1 min. (when you click on a add link , remember open one add at a time. a new window will be open and a countdown timing for one minute will be start on upper left side of the web page when its staps you will be asked to click a specific number eg click 1 1 2 3 4. you have to click on it) 7 This one minute add will give you 10 US $ DOLLAR. 8 Hence watch other adds one by one. 9 Finally you will find 60 dollars on you status by checking "' my account "' 10 You have earned 60 dollars you can repeat you view adds again on next day moreover if you introduce a new guy with your reffence you will be entitled to get 50% of the refferal(which means that if the person reffered by you take his /her adds daily he will receives dollars you will be 50% of his/her daily work. Trust me its free and its really works 11 This is not a Fake.This is 100% sure you will get your money. CLICK ON THE ABOVE LINK NEAR "MESSAGE NO 1 FOR YOU"..........RIGHT NOW IMPORTANT INSTRUCTIONS: YOU CAN TAKE YOUR UNIQUE REFFERAL LINK BY CLICKING ON "PROMOTE" OPTION ON THE WEB SITE. YOU CAN FEED BACK ME ON THIS E MAIL ID. "imran.raza460 at gmail.com" ____________________________________________________________________________________________ MESSAGE NO 2 FOR YOU READ IT. http://www.buxbillionaire.com/?ref=imranraza460 Hello my dear friend, I hope you will be fine. i want to tell you the authentic way to make money with no investment. Here you can make 80 OR 40 US $ dollars in just six minutes. No investment its free.....Trial is essential... 1 Just click on the obove link 2 create your account on the website. ( it will take 2 or three minutesits absouloutely free no subscription fee ) 3 Now loging with your username and the password 4 Then click on the "" view adds"" tab 5 There will be 4 or 8 adds links ( consisting 60 seconds each ) 6 Click on a particular add and watch it for 1 min. (when you click on a add link , remember open one add at a time. a new window will be open and a countdown timing for one minute will be start ons upper left side of the web page when its staps you will be asked to click a specific number eg click 05 05 02 03 04. click on 05 you have to click on it) 7 This one minute add will give you 10 US $ DOLLAR. 8 Hence watch other adds one by one. 9 Finally you will find 40 or some time 80 US $ dollars on you status by checking "' my account "' 10 You have earned 60 dollars you can repeat your view adds again on next day moreover if you introduce a new guy with your reffence you will be entitled to get 10 $ per click of the reffferal(which means that if the person reffered by you take his /her adds daily you will be received 10 $ per add of his/ her daily work.means equal to him/her Trust me its free and its really works 11 This is not a Fake.This is 100% sure you will get your money. CLICK ON THE ABOVE LINK near " MESSAGE NO 2 FOR YOU..........RIGHT NOW IMPORTANT INSTRUCTIONS: YOU CAN TAKE YOUR UNIQUE REFFERAL LINK BY CLICKING ON "PROMOTION TOLLS" OPTION ON THE WEB SITE. YOU CAN FEED BACK ME ON THIS E MAIL ID. "imran.raza460 at gmail.com" _____________________________________________________________________________________________ MESSAGE NO 3 FOR YOU READ IT. http://www.buxmillionaire.com/?ref=imranraza460 Hello my dear friend, I hope you will be fine. i want to tell you the authentic way to make money with no investment. Here you can make 230 US $ dollars in just 23 minutes. No investment its free.....Trial is essential... 1 Just click on the obove link 2 create your account on the website. ( it will take 2 or three minutesits absouloutely free no subscription fee ) 3 Now loging with your username and the password ( also enter security code shown below password ) 4 Then click on the "" view adds"" tab 5 There will be 4 or 8 adds links ( consisting 60 seconds each ) 6 Click on a particular add and watch it for 1 min. (when you click on a add link , remember open one add at a time. a new window will be open and a countdown timing for one minute will be start ons upper left side of the web page when its staps you will be asked to click a specific number eg click 05 05 02 03 04. click on 05 you have to click on it) 7 This one minute add will give you 10 US $ DOLLAR. 8 Hence watch other adds one by one. 9 Finally you will find 230 US $ dollars per day on your status by checking "' my account "' 10 You have earned 230 dollars you can repeat your view adds again on next day moreover if you introduce a new guy with your reffence you will be entitled to get 10 $ per click of the reffferal (which means that if the person reffered by you take his /her adds daily you will be received dollars. 10 $ per add of his/her daily work. Trust me its free and its really works 11 This is not a Fake.This is 100% sure you will get your money. CLICK ON THE ABOVE LINK near " MESSAGE NO 2 FOR YOU..........RIGHT NOW IMPORTANT INSTRUCTIONS: YOU CAN TAKE YOUR UNIQUE REFFERAL LINK BY CLICKING ON "PROMOTION TOLLS" OPTION ON THE WEB SITE. YOU CAN FEED BACK ME ON THIS E MAIL ID. "imran.raza460 at gmail.com" ________________________________________________________________________________________________ Another link for making money is here also try this one also http://www.bigextracash.com/aft/9b6cc578.html From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 17 06:42:00 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 17 Aug 2010 12:42:00 +0200 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: <4c6a6773$0$9118$426a74cc@news.free.fr> Vikas Mahajan a ?crit : > On 16 August 2010 19:23, Nitin Pawar wrote: >> you would need to define a class first with its attiributes and then you may >> want to initiate the variables by calling the class initilializer >> > Actually I have to dynamically add attributes to a object. I am > writing python script for FreeCAD software. I am using loop to create > multiple cylinders and I am writing following code-: > cyname = "Cylinder" > FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) > FreeCAD.ActiveDocument.cyname.Radius= .5 > FreeCAD.ActiveDocument.cyname.Height= 10 > > And I am getting this error-: > AttributeError: 'App.Document' object has no attribute 'cyname' Indeed. > But when I use Cylinder in place of cyname, I am not getting any error. Of course. > Please help. I don't have FreeCAD installed, I won't install it, and I'm not going to read FreeCAD's doc neither, but you may want to check whether FreeCAD.ActiveDocument.addObject actually returns the newly created objet (which would be a sensible behaviour). If so, you'd just have to keep a ref to this object, ie: cylinder = FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) cylinder.Radius = 0.5 # etc Else, you can always get this ref using getattr, ie: FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) cylinder = getattr(FreeCAD.ActiveDocument, cyname) cylinder.Radius = 0.5 # etc And while you're at it, you could save on both typing and execution time by keepin a ref to the document object itself: doc = FreeCAD.ActiveDocument for cyname in ("cylinder1, "cylinder2", "cylinderN"): doc.addObject("Part::Cylinder",cyname) cylinder = getattr(doc, cyname) cylinder.Radius = 0.5 # etc HTH From bartc at freeuk.com Tue Aug 17 06:50:32 2010 From: bartc at freeuk.com (BartC) Date: Tue, 17 Aug 2010 11:50:32 +0100 Subject: 79 chars or more? In-Reply-To: References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com><4C6A0C3F.9060900@gmail.com> Message-ID: "James Mills" wrote in message news:mailman.2222.1282019212.1673.python-list at python.org... > On Tue, Aug 17, 2010 at 2:12 PM, AK wrote: >> There's no doubt that there are pro's and con's, but to be fair, it's >> not like code becomes unreadable over 79 chars - the difference is that >> when your terminal is 80 chars, it's less convenient for you to read >> code that's wider and when your terminal is wider, it's less convenient >> to read code that's 79 chars. > > I guess there are two-sides to the coin here so to speak. See I'm > vision impaired > so I prefer a 79 char width in my own projects That's not a good argument for everyone else to do the same. Someone else might prefer 40 columns for similar reasons. (Anyway can't a 100-column width be squeezed into the same angular field as 80-columns, just by using a narrower font, when necessary? Assuming the problem is field width rather than acuity) > The other side is this... I'm of the opinion that if you're writing a > line of code > that's excessively long (>80char or say >100chars), then you might want to > reconsider what you're doing :) (It might be wrong). I generally use 100 columns. It's useful for being able to write same-line comments with meaningful content... (I've used 80-column hardware (teletypes and such) years ago, I thought such restrictions had vanished long ago) -- Bartc From jah.alarm at gmail.com Tue Aug 17 07:02:23 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Tue, 17 Aug 2010 04:02:23 -0700 (PDT) Subject: message box in Tkinter Message-ID: <61cbd1cb-bd6d-49aa-818f-d28c460980ea@x18g2000pro.googlegroups.com> I need to display a message box at the click of a button. I od the following: from Tkinter import * def msg1(): messagebox.showinfo(message='Have a good day') Button(mainframe,text="About",command=msg1()).grid(column=360,row=36,sticky=W) I get the error msg 'global name 'messagebox' is not defined' When I try importing messagebox from Tkinter i get an error message that this module doesn't exist. thanks From matt at scotweb.co.uk Tue Aug 17 07:20:52 2010 From: matt at scotweb.co.uk (Matt Saxton) Date: Tue, 17 Aug 2010 12:20:52 +0100 Subject: message box in Tkinter In-Reply-To: <61cbd1cb-bd6d-49aa-818f-d28c460980ea@x18g2000pro.googlegroups.com> References: <61cbd1cb-bd6d-49aa-818f-d28c460980ea@x18g2000pro.googlegroups.com> Message-ID: <20100817122052.7bff8ae9.matt@scotweb.co.uk> On Tue, 17 Aug 2010 04:02:23 -0700 (PDT) Jah_Alarm wrote: > > When I try importing messagebox from Tkinter i get an error message > that this module doesn't exist. > I believe what you want is Tkinter.Message -- Matt Saxton From eric.brunel at pragmadev.nospam.com Tue Aug 17 08:12:01 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Tue, 17 Aug 2010 14:12:01 +0200 Subject: message box in Tkinter References: <61cbd1cb-bd6d-49aa-818f-d28c460980ea@x18g2000pro.googlegroups.com> Message-ID: In article <61cbd1cb-bd6d-49aa-818f-d28c460980ea at x18g2000pro.googlegroups.com>, Jah_Alarm wrote: > I need to display a message box at the click of a button. I od the > following: > > from Tkinter import * > > def msg1(): > messagebox.showinfo(message='Have a good day') > > > Button(mainframe,text="About",command=msg1()).grid(column=360,row=36,sticky=W) > > I get the error msg 'global name 'messagebox' is not defined' > > When I try importing messagebox from Tkinter i get an error message > that this module doesn't exist. > > thanks Where did you find any reference to something called messagebox? The actual module name is tkMessageBox and it should be imported separately: import tkMessageBox tkMessageBox.showinfo(message='Have a good day') Should work that way. HTH - Eric - From jah.alarm at gmail.com Tue Aug 17 08:16:06 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Tue, 17 Aug 2010 05:16:06 -0700 (PDT) Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> <26c363c8-11d7-49b9-a1c1-251ab5ff934e@p22g2000pre.googlegroups.com> Message-ID: <6b659d20-670f-4952-bfd6-684faf1ec0cf@i18g2000pro.googlegroups.com> In MATLAB this command is drawnow, just in case On Aug 17, 9:49?pm, Jah_Alarm wrote: > thanks. The thing is, the objects actually get updated without this > command, but when I run the GUI outside of python shell (i.e. in > command prompt as python filename.py or compile it to .exe file) the > objects do not get updated. I tried > Label(mainframe,textvariable=var).grid(column=1,row=1).update_idletasks() > and mainframe.update_idletasks() but it still doesn't work. > > On Aug 17, 7:19?pm, Eric Brunel > wrote: > > > > > In article > > <24dc97b3-a8b5-4638-9cf5-a397f1eae... at q16g2000prf.googlegroups.com>, > > > ?Jah_Alarm wrote: > > > hi, I've already asked this question but so far the progress has been > > > small. > > > > I'm running Tkinter. I have some elements on the screen (Labels, most > > > importantly) which content has to be updated every iteration of the > > > algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm > > > using the update_idletasks() command in the function itself after the > > > variable.set(...) command. The variable type is IntVar(), and the > > > mistake I'm getting is 'IntVar instance has no attribute > > > 'update_idletasks'. No updates are displayed, of course. > > > You have to call update_idletasks on a Tkinter *widget*, not a variable. > > You can call it on your window (Tk or Toplevel instance) or on your > > label for example. This way, it should work. > > > > Without the GUI the algorithm (it's a genetic algorithm) is working > > > fine, but I need to make it available to other people via GUI > > > > cheers, > > > > Alex From eric.brunel at pragmadev.nospam.com Tue Aug 17 08:19:25 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Tue, 17 Aug 2010 14:19:25 +0200 Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> <26c363c8-11d7-49b9-a1c1-251ab5ff934e@p22g2000pre.googlegroups.com> Message-ID: (Top-post corrected; please don't do that, it makes messages very hard to read via usenet?) In article <26c363c8-11d7-49b9-a1c1-251ab5ff934e at p22g2000pre.googlegroups.com>, Jah_Alarm wrote: > On Aug 17, 7:19?pm, Eric Brunel > wrote: > > You have to call update_idletasks on a Tkinter *widget*, not a variable. > > You can call it on your window (Tk or Toplevel instance) or on your > > label for example. This way, it should work. > > > thanks. The thing is, the objects actually get updated without this > command, but when I run the GUI outside of python shell (i.e. in > command prompt as python filename.py or compile it to .exe file) the > objects do not get updated. I tried > Label(mainframe,textvariable=var).grid(column=1,row=1).update_idletasks() > and mainframe.update_idletasks() but it still doesn't work. I think you're really misunderstanding something here: the call to update_idletasks is a one shot call to the GUI to basically tell it to refresh itself. So each time you change anything that should be displayed, you have to call that method again, or your changes will only be seen when the control returns to the GUI, which is basically at the end of your processing. The fact that it works when you're doing it interactively is normal. In this mode, you don't have a GUI event loop running, so the GUI updates itself all the time automatically. This is never true in programs you run the 'normal' way, i.e via: python filename.py And by the way, Label(?).grid(?).update_idletasks() had no chance to work anyway: the grid method doesn't return anything, so you're trying to call the update_idletasks method on None here? HTH - Eric - From neilc at norwich.edu Tue Aug 17 08:42:15 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 17 Aug 2010 12:42:15 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> Message-ID: <8cved7Fr7qU3@mid.individual.net> On 2010-08-17, Michael Torrie wrote: > In general if I find myself consistently going longer than 75 > or 80 characters, I need to refactor my code to make it more > manageable. If I have to scroll up five pages to find the > beginning of a block, that normally means my code could be > simplified and improved. Looking through my code, the split-up lines almost always include string literals or elimination of meaningless temporary variables, e.g.: self.expiration_date = translate_date(find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') The other cases are when indentation levels get the best of me, but I'm too lazy to refactor. -- Neil Cerutti From roy at panix.com Tue Aug 17 09:05:50 2010 From: roy at panix.com (Roy Smith) Date: Tue, 17 Aug 2010 09:05:50 -0400 Subject: 79 chars or more? References: Message-ID: In article , Lawrence D'Oliveiro wrote: > In message , AK wrote: > > > As monitors are getting bigger, is there a general change in opinion on > > the 79 chars limit in source files? > > WHAT 79-character limit in source files? > > I currently have my Emacs windows set at 100 characters wide, and I???m > thinking of going wider. > > Remember, the old hardcopy terminals used to produce 132-character-wide > listings. Those of you who think "old hardcopy terminals" did 132 wide obviously don't remember the ASR-33 :-) From martin at address-in-sig.invalid Tue Aug 17 10:01:42 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Tue, 17 Aug 2010 14:01:42 +0000 (UTC) Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> Message-ID: On Tue, 17 Aug 2010 13:00:51 +1000, James Mills wrote: > Roy, under normal circumstances I would agree with you and have a > different opinion. However being vision impaired restricts the available > width (irregardless of the width of the monitor) of text I'm able to > view at once. > I'm with James here because: 1) ssh terminal windows generally come up as 24 x 80 2) at 24 x 80 I can get more ssh terminal windows on the desktop with minimal overlap than I can do with longer/wider windows. BTW, James, would it be a bore to add a space after the two hyphens at the top of your sig, i.e. use "-- ", not "--"? That way most news readers will automatically remove your sig when replying to your post. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From sschwarzer at sschwarzer.net Tue Aug 17 10:14:05 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 17 Aug 2010 16:14:05 +0200 Subject: Opposite of split In-Reply-To: <4c696ada$0$22941$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl><4C683363.3080305@islandtraining.com><4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> Message-ID: <4C6A992D.5020802@sschwarzer.net> Hi Alex, On 2010-08-16 18:44, Alex van der Spek wrote: > Anybody catches any other ways to improve my program (attached), you are > most welcome. Help me learn, that is one of the objectives of this > newsgroup, right? Or is it all about exchanging the next to impossible > solution to the never to happen unreal world problems? I don't know what a concordance table is, and I haven't looked a lot into your program, but anyway here are some things I noticed at a glance: | #! usr/bin/env python | # Merge log files to autolog file | import os | import fileinput | #top='C:\\Documents and Settings\\avanderspek\\My Documents\\CiDRAdata\\Syncrude\\CSL\\August2010' | top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010' If you have backslashes in strings, you might want to use "raw strings". Instead of "c:\\Users\\ZDoor" you'd write r"c:\Users\ZDoor" (notice the r in front of the string). | i,j,k=0,0,0 | date={} I suggest to use more spacing to make the code more readable. Have a look at http://www.python.org/dev/peps/pep-0008/ for more formatting (and other) tips. | fps=0.3048 | tab='\t' | | bt='-999.25'+'\t''-999.25'+'\t''-999.25'+'\t''-999.25'+'\t'+'-999.25' If these numbers are always the same, you should use something like NUMBER = "-999.25" COLUMNS = 5 bt = "\t".join(COLUMNS * [NUMBER]) (with better naming, of course). Why don't you use `tab` here? I _highly_ recommend to use longer (unabbreviated) names. | al='Status'+'\t'+'State'+'\t'+'-999.25' | | for root,dirs,files in os.walk(top): | #Build a concordance table of days on which data was collected | for name in files: | ext=name.split('.',1)[1] There's a function `splitext` in `os.path`. | if ext=='txt': | dat=name.split('_')[1].split('y')[1] | if dat in date.keys(): You can just write `if dat in date` (in Python versions >= 2.2, I think). | date[dat]+=1 | else: | date[dat]=1 | print 'Concordance table of days:' | print date | print 'List of files processed:' | #Build a list of same day filenames, 5 max for a profile meter,skip first and last days | for f in sorted(date.keys())[2:-1]: | logs=[] | for name in files: | ext=name.split('.')[1] | if ext=='txt': | dat=name.split('_')[1].split('y')[1] I guess I'd move the parsing stuff (`x.split(s)[i]` etc.) into small functions with meaningful names. After that I'd probably notice there's much redundancy and refactor them. ;) | if dat==f: | logs.append(os.path.join(root,name)) | #Open the files and read line by line | datsec=False | lines=[[] for i in range(5)] One thing to watch out for: The above is different from `[[]] * 5` which uses the _same_ empty list for all entries. Probably the semantics you chose is correct. | fn=0 | for line in fileinput.input(logs): | if line.split()[0]=='DataID': | datsec=True | ln=0 | if datsec: | lines[fn].append(line.split()) | ln+=1 | if ln==10255: This looks like a "magic number" and should be turned into a constant. | datsec=False | fileinput.nextfile() | fn+=1 | print fileinput.filename().rsplit('\\',1)[1] | fileinput.close() | aut='000_AutoLog'+f+'.log' | out=os.path.join(root,aut) | alf=open(out,'w') | alf.write('Timestamp (mm/dd/yyyy hh:mm:ss) VF 1 VF 2 VF 3 VF 4 VF 5 Q 1 Q 2 Q 3 Q 4 Q 5 Status State Metric Band Temperature 1 Band Temperature 2 Band Temperature 3 Band Temperature 4 Band Temperature 5 SPL 1 SPL 2 SPL 3 SPL 4 SPL 5'+'\n') | for wn in range(1,10255,1): You don't need to write the step argument if it's 1. | for i in range(5): | lines[i][wn][2]=str(float(lines[i][wn][2])/fps) | tp=lines[0][wn][0]+' '+lines[0][wn][1] | vf=tab.join([lines[i][wn][2] for i in range(5)]) | vq=tab.join([lines[i][wn][3] for i in range(5)]) | vs=tab.join([lines[i][wn][4] for i in range(5)]) | #sf=tab.join([lines[i][wn][5] for i in range(5)]) | #sq=tab.join([lines[i][wn][6] for i in range(5)]) | #ss=tab.join([lines[i][wn][7] for i in range(5)]) Maybe use an extra function? def choose_a_better_name(): return tab.join([lines[index][wn][2] for index in range(5)]) Moreover, the repetition of this line looks as if you wanted to put the right hand sides of the assignments in a list, instead of assigning to distinct names (`vf` etc.). By the way, you use the number 5 a lot. I guess this should be a constant, too. | alf.write(tp+'\t'+vf+'\t'+vq+'\t'+al+'\t'+bt+'\t'+vs+'\n') Suggestion: Use tab.join([tp, vf, vq, al, bt, vs]) + "\n" Again, not using distinct variables would have an advantage here. | alf.close() | print "Done" Stefan From awaretek at gmail.com Tue Aug 17 10:21:23 2010 From: awaretek at gmail.com (Ron) Date: Tue, 17 Aug 2010 07:21:23 -0700 (PDT) Subject: Python for MultiTouch! Message-ID: Along with the news of Unbuntu supporting multitouch, I saw this and just had to share, I think its really nice: PyMT http://the-space-station.com/2010/8/16/python-multitouch:-pymt-0-5-released From sschwarzer at sschwarzer.net Tue Aug 17 10:28:02 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 17 Aug 2010 16:28:02 +0200 Subject: 79 chars or more? In-Reply-To: <8cved7Fr7qU3@mid.individual.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> Message-ID: <4C6A9C72.4040708@sschwarzer.net> Hi Neil, On 2010-08-17 14:42, Neil Cerutti wrote: > On 2010-08-17, Michael Torrie wrote: >> In general if I find myself consistently going longer than 75 >> or 80 characters, I need to refactor my code to make it more >> manageable. If I have to scroll up five pages to find the >> beginning of a block, that normally means my code could be >> simplified and improved. > > Looking through my code, the split-up lines almost always include > string literals or elimination of meaningless temporary > variables, e.g.: > > self.expiration_date = translate_date(find(response, > 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') I'd probably reformat this to self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') or even self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') for consistency. This not only limits the width but also makes the nesting of the calls more visible. Stefan From awaretek at gmail.com Tue Aug 17 10:29:28 2010 From: awaretek at gmail.com (Ron) Date: Tue, 17 Aug 2010 07:29:28 -0700 (PDT) Subject: scrapelib for web scraping Message-ID: Shameless plug for a web scraping tool my son is involved in creating, called scrapelib. He is on leave from university and is a consultant for the Sunlight Foundation creating something called the Fifty States Project to monitor lobbyist money to state governments in the USA. http://github.com/mikejs/scrapelib From awaretek at gmail.com Tue Aug 17 10:33:59 2010 From: awaretek at gmail.com (Ron) Date: Tue, 17 Aug 2010 07:33:59 -0700 (PDT) Subject: Podcast about Python's versions and implementations Message-ID: <53e47b75-c046-451a-8c14-94f2ba7e3abb@z30g2000prg.googlegroups.com> New podcast up is a look at the various versions and implementations of Python, including Python 3, Python 2, PyPy, IronPython, Jython, Stackless, Psycho, Shedskin, Cython, Unladen Swallow, Berp, etc. http://www.awaretek.com/python/ Ron From lie.1296 at gmail.com Tue Aug 17 10:59:05 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 18 Aug 2010 00:59:05 +1000 Subject: Python "why" questions In-Reply-To: References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: <4c6a8cff$1@dnews.tpgi.com.au> On 08/16/10 21:54, David Cournapeau wrote: > On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing > wrote: >>> On Aug 7, 2010, at 9:14 PM, John Nagle wrote: >>> >>>> The languages which have real multidimensional arrays, rather >>>> than arrays of arrays, tend to use 1-based subscripts. That >>>> reflects standard practice in mathematics. >> >> Not always -- mathematicians use whatever starting index is >> most convenient for the problem at hand. > > Yes, there are many engineering fields where index starts at 0. Partly > for the reason you have stated concerning polynomials, especially > since this extend to series, which are pervasive in numerical > computing. In linear algebra, though, I remember to have always noted > matrices indexes in the [1,n] range, not [0,n-1]. I'm sure some would prefer to denote it as [0, n) From robert.kern at gmail.com Tue Aug 17 11:22:27 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 17 Aug 2010 10:22:27 -0500 Subject: Python "why" questions In-Reply-To: <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> References: <8crequF9tpU1@mid.individual.net> <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> Message-ID: On 8/16/10 11:10 PM, Steven D'Aprano wrote: > On Mon, 16 Aug 2010 22:56:20 -0500, Robert Kern wrote: > >> On 8/16/10 9:29 PM, Roy Smith wrote: >>> In article, >>> Lawrence D'Oliveiro wrote: >>> >>>> In message, Roy Smith wrote: >>>> >>>>> 5) real intensity[160.0 : 30.0 : 0.01] >>>> >>>> How many elements in that array? >>>> >>>> a) 2999 >>>> b) 3000 >>>> c) neither of the above >>> >>> c) neither of the above. More specifically, 13,001 (if I counted >>> correctly). >> >> 13000, actually. Floating point is a bitch. >> >> [~/Movies] >> |1> import numpy >> >> [~/Movies] >> |2> len(numpy.r_[160.0:30.0:-0.01]) >> 13000 > > > Actually, the answer is 0, not 13000, because the step size is given as > 0.01, not -0.01. > >>>> import numpy >>>> len(numpy.r_[160.0:30.0:-0.01]) > 13000 >>>> len(numpy.r_[160.0:30.0:0.01]) > 0 Roy wasn't using numpy/Python semantics but made-up semantics (following Martin Gregorie's made-up semantics to which he was replying) which treat the step size as a true size, not a size and direction. The direction is determined from the start and stop parameters. It's an almost-reasonable design. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From neilc at norwich.edu Tue Aug 17 11:31:54 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 17 Aug 2010 15:31:54 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <8cvobaF1r0U2@mid.individual.net> On 2010-08-17, Stefan Schwarzer wrote: > Hi Neil, > > On 2010-08-17 14:42, Neil Cerutti wrote: >> Looking through my code, the split-up lines almost always >> include string literals or elimination of meaningless >> temporary variables, e.g.: >> >> self.expiration_date = translate_date(find(response, >> 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') > > I'd probably reformat this to > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', '%m%d%Y') > > or even > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') > > for consistency. > > This not only limits the width but also makes the nesting of > the calls more visible. Those are nice improvements. Thanks! -- Neil Cerutti From neilc at norwich.edu Tue Aug 17 11:36:57 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 17 Aug 2010 15:36:57 GMT Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> <4C6A992D.5020802@sschwarzer.net> Message-ID: <8cvokpF1r0U3@mid.individual.net> On 2010-08-17, Stefan Schwarzer wrote: > Hi Alex, > > On 2010-08-16 18:44, Alex van der Spek wrote: >> Anybody catches any other ways to improve my program (attached), you are >> most welcome. Help me learn, that is one of the objectives of this >> newsgroup, right? Or is it all about exchanging the next to impossible >> solution to the never to happen unreal world problems? > > I don't know what a concordance table is, and I haven't > looked a lot into your program, but anyway here are some > things I noticed at a glance: > >| #! usr/bin/env python >| # Merge log files to autolog file >| import os >| import fileinput >| #top='C:\\Documents and Settings\\avanderspek\\My Documents\\CiDRAdata\\Syncrude\\CSL\\August2010' >| top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010' > > If you have backslashes in strings, you might want to use "raw > strings". Instead of "c:\\Users\\ZDoor" you'd write > r"c:\Users\ZDoor" (notice the r in front of the string). That's good general advice. But in the specific case of file paths, using '/' as the separator is supported, and somewhat preferable. -- Neil Cerutti From darcy at druid.net Tue Aug 17 11:42:56 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 17 Aug 2010 11:42:56 -0400 Subject: 79 chars or more? In-Reply-To: <4C6A9C72.4040708@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <20100817114256.d960549b.darcy@druid.net> On Tue, 17 Aug 2010 16:28:02 +0200 Stefan Schwarzer wrote: > I'd probably reformat this to > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', '%m%d%Y') > > or even > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') You can extend this if there are complicated sub-calls. Probably overkill for this example but here is the idea. self.expiration_date = translate_date( find( response, 'MPNExpirationDate', ).text, '%Y-%m-%d', '%m%d%Y' ) I also moved the closing brace down to align with the line that opened that block. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From zdoor at xs4all.nl Tue Aug 17 11:44:57 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Tue, 17 Aug 2010 17:44:57 +0200 Subject: EOFError with fileinput In-Reply-To: References: <4c696751$0$22940$e4fe514c@news.xs4all.nl> Message-ID: <4c6aae79$0$22942$e4fe514c@news.xs4all.nl> Thanks all! I understand better now. I had no idea that EOFError was an exception. I was looking for a function to tell me when the end of a sequential file is reached as in all of the 4 programming languages that I do know this is a requirement. Will modify my program accordingly. Alex van der Spek From andrei.avk at gmail.com Tue Aug 17 11:44:58 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 11:44:58 -0400 Subject: 79 chars or more? In-Reply-To: <4C6A9C72.4040708@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <4C6AAE7A.70109@gmail.com> On 08/17/2010 10:28 AM, Stefan Schwarzer wrote: > Hi Neil, > > On 2010-08-17 14:42, Neil Cerutti wrote: >> On 2010-08-17, Michael Torrie wrote: >>> In general if I find myself consistently going longer than 75 >>> or 80 characters, I need to refactor my code to make it more >>> manageable. If I have to scroll up five pages to find the >>> beginning of a block, that normally means my code could be >>> simplified and improved. >> >> Looking through my code, the split-up lines almost always include >> string literals or elimination of meaningless temporary >> variables, e.g.: >> >> self.expiration_date = translate_date(find(response, >> 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') > > I'd probably reformat this to > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', '%m%d%Y') > > or even > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') > > for consistency. > > This not only limits the width but also makes the nesting of > the calls more visible. > > Stefan Doesn't this create the problem of functions growing too long to fit in a screen? I think it's very useful to try to keep function size low enough so that you can view the whole function without having to scroll up and down. (even though that's not always possible) -ak From invalid at invalid.invalid Tue Aug 17 11:46:31 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 17 Aug 2010 15:46:31 +0000 (UTC) Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> <4C6A992D.5020802@sschwarzer.net> <8cvokpF1r0U3@mid.individual.net> Message-ID: On 2010-08-17, Neil Cerutti wrote: > On 2010-08-17, Stefan Schwarzer wrote: >> Hi Alex, >> >> On 2010-08-16 18:44, Alex van der Spek wrote: >>> Anybody catches any other ways to improve my program (attached), you are >>> most welcome. Help me learn, that is one of the objectives of this >>> newsgroup, right? Or is it all about exchanging the next to impossible >>> solution to the never to happen unreal world problems? >> >> I don't know what a concordance table is, and I haven't >> looked a lot into your program, but anyway here are some >> things I noticed at a glance: >> >>| #! usr/bin/env python >>| # Merge log files to autolog file >>| import os >>| import fileinput >>| #top='C:\\Documents and Settings\\avanderspek\\My Documents\\CiDRAdata\\Syncrude\\CSL\\August2010' >>| top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010' >> >> If you have backslashes in strings, you might want to use "raw >> strings". Instead of "c:\\Users\\ZDoor" you'd write >> r"c:\Users\ZDoor" (notice the r in front of the string). > > That's good general advice. But in the specific case of file > paths, using '/' as the separator is supported, and somewhat > preferable. Unless you're going to be passing them to cmd.exe or other utilities via subprocess/popen. -- Grant Edwards grant.b.edwards Yow! MY income is ALL at disposable! gmail.com From moss.rich at gmail.com Tue Aug 17 12:07:28 2010 From: moss.rich at gmail.com (Rich Moss) Date: Tue, 17 Aug 2010 09:07:28 -0700 (PDT) Subject: Python Developer - HFT Trading firm - Chicago, IL Message-ID: Python developer needed for math/trading applications and research at leading HFT firm. The person we are searching for will have a strong background with python programming and the ability to work with very large historical datasets. You should have a very strong math background as well. This can involve writing very complicated python scripts and programs! You will work very closely with traders and quantitative analysts in their equities trading group on state-of-the- art trading strategy and execution systems. Requires: Strong python programming experience developing applications and scripts using complex regular expressions Strong math knowledge and education Experience working with massive datatsets/historical data This company is a top-tier electronic, algorithmic trading firm, located in Chicago, IL. This firm is one of the most advanced high frequency electronic trading firms in the world and uses python throughout the company, as well as other languages. This firm has a culture that rewards creativity and hard work. No third parties, please. We will not consider candidates from outside the USA. No telecommuting. We offer very generous compensation (best in the industry), fantastic benefits and very generous relocation packages. Please contact me immediately with a resume! Send resumes to: Rich Moss rich at mossltd.com From sschwarzer at sschwarzer.net Tue Aug 17 12:21:53 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 17 Aug 2010 18:21:53 +0200 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <4C6AB721.3060603@sschwarzer.net> On 2010-08-17 17:44, AK wrote: > On 08/17/2010 10:28 AM, Stefan Schwarzer wrote: >> I'd probably reformat this to >> >> self.expiration_date = translate_date( >> find(response, 'MPNExpirationDate').text, >> '%Y-%m-%d', '%m%d%Y') >> >> or even >> >> self.expiration_date = translate_date( >> find(response, 'MPNExpirationDate').text, >> '%Y-%m-%d', >> '%m%d%Y') >> >> for consistency. >> >> This not only limits the width but also makes the nesting of >> the calls more visible. > > Doesn't this create the problem of functions growing too long to fit in > a screen? I think it's very useful to try to keep function size low > enough so that you can view the whole function without having to scroll > up and down. (even though that's not always possible) -ak I think I'd extract some part of the function into a new function then. In my opinion, the reasoning is similar to the case, "Can't I use two spaces per indentation level? That way I don't run so easily into the right margin if I have more than five indentations in a function." ;-) Stefan From rodrick.brown at gmail.com Tue Aug 17 12:40:39 2010 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Tue, 17 Aug 2010 12:40:39 -0400 Subject: Open a command pipe for reading Message-ID: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> I have a fairly large file 1-2GB in size that I need to process line by line but I first need to convert the file to text using a 3rd party tool that prints the records also line by line. I've tried using Popen to do this with no luck. I'm trying to simulate /bin/foo myfile.dat And as the records are being printed do some calculations. pipe = Popen(exttool,shell=True,stdout=PIPE).stdout for data in pipe.readlines(): print data, This operation blocks forever I'm guessing it's trying to process the entire file at once. Sent from my iPhone 4. From andrei.avk at gmail.com Tue Aug 17 12:43:02 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 12:43:02 -0400 Subject: 79 chars or more? In-Reply-To: <4C6AB721.3060603@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> Message-ID: <4C6ABC16.4070006@gmail.com> On 08/17/2010 12:21 PM, Stefan Schwarzer wrote: > On 2010-08-17 17:44, AK wrote: >> On 08/17/2010 10:28 AM, Stefan Schwarzer wrote: >>> I'd probably reformat this to >>> >>> self.expiration_date = translate_date( >>> find(response, 'MPNExpirationDate').text, >>> '%Y-%m-%d', '%m%d%Y') >>> >>> or even >>> >>> self.expiration_date = translate_date( >>> find(response, 'MPNExpirationDate').text, >>> '%Y-%m-%d', >>> '%m%d%Y') >>> >>> for consistency. >>> >>> This not only limits the width but also makes the nesting of >>> the calls more visible. >> >> Doesn't this create the problem of functions growing too long to fit in >> a screen? I think it's very useful to try to keep function size low >> enough so that you can view the whole function without having to scroll >> up and down. (even though that's not always possible) -ak > > I think I'd extract some part of the function into a new > function then. In my opinion, the reasoning is similar to > the case, "Can't I use two spaces per indentation level? > That way I don't run so easily into the right margin if I > have more than five indentations in a function." ;-) I think to some extent it's a matter of taste. I bet most people would agree that on the balance, 2-space indentations makes code much less readable, despite saving a bit of space. But let me ask you, would you really prefer to have: >>> self.expiration_date = translate_date( >>> find(response, 'MPNExpirationDate').text, >>> '%Y-%m-%d', '%m%d%Y') (or the 4-line version of this above), even when it necessitates creation of a new function, rather than have this code on two lines? After all, I think it's a matter of balance between readability, expressiveness and succinctness. If I split a function in two, that still means that understanding the functionality of the code will require scrolling around and looking at the second function. I guess what I'm trying to say that we shouldn't just care about readability of lines but also readability of functions and blocks of functionality (that may include several functions that accomplish a single "task".) -andrei From neilc at norwich.edu Tue Aug 17 13:07:14 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 17 Aug 2010 17:07:14 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> Message-ID: <8cvtu2F6v3U1@mid.individual.net> On 2010-08-17, AK wrote: > After all, I think it's a matter of balance between > readability, expressiveness and succinctness. If I split a > function in two, that still means that understanding the > functionality of the code will require scrolling around and > looking at the second function. I guess what I'm trying to say > that we shouldn't just care about readability of lines but also > readability of functions and blocks of functionality (that may > include several functions that accomplish a single "task".) When considering creating variables and functions, I try to use the same rule of thumb: If I can come up with a good name for it relatively quickly, then it probably deserves to exist. If all I can think of is 'func' or 'x', then it's an artifact that I hope to avoid. Splitting a function in two need not obscure the meaning, and may even improve it, *if* the names of the new functions are good. -- Neil Cerutti From stndshp at gmail.com Tue Aug 17 13:10:57 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 10:10:57 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <93c048b8-013d-425f-ac69-c112f12ddaa3@v41g2000yqv.googlegroups.com> Message-ID: <74bce7c5-8a97-4a45-8d85-2ae48145b4e1@x21g2000yqa.googlegroups.com> On Aug 16, 4:20?am, Malcolm McLean wrote: > On Aug 16, 10:20?am, Standish P wrote:> [Q] How far can stack [LIFO] solve do automatic garbage collection and > > prevent memory leak ? > > Most programs can be written so that most of their memory allocations > are matched by destructors at the same level. > > However the allocations that can't be written this way typically tend > to be the small frequently-called ones used for nodes in dynamic graph > objects, or small resizeable buffers to hold strings and the like. > This is where you get the performance hit with repeated calls to > malloc() and free(). > > So generally it's not worthwhile writing a stack allocator for a > normal program. That's not to say there aren't a few individual cases > where it can help performance. (See the chapter "Memory games" in my > book Basic Agorithms for details about memory allocation strategies). all the page numbers in your books TOC have a little varying offset from actual, pictures are nice for kids .. From vikas.mahajan12 at gmail.com Tue Aug 17 13:19:16 2010 From: vikas.mahajan12 at gmail.com (Vikas Mahajan) Date: Tue, 17 Aug 2010 22:49:16 +0530 Subject: passing variables as object attributes In-Reply-To: <4c6a6773$0$9118$426a74cc@news.free.fr> References: <4c6a6773$0$9118$426a74cc@news.free.fr> Message-ID: I got the concept to get and set object attributes and now can handle similar problems effectively. Thanks to all for your help. From stndshp at gmail.com Tue Aug 17 13:21:11 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 10:21:11 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> > Garbage collection doesn't use a stack. It uses a "heap", which is in > the abstract a collection of memory blocks of different lengths, > divided into two lists, generally represented as linked lists: > > 1. ?A list of blocks that are free and may be used to store new data > > 2. ?A list of blocks that are in use, or haven't been freed (yet) Is this all that a heap is or is there more to it ? I have been looking for simple but complete explanation of heap for a while and not gotten to it. I think I am looking for a stack allocation on the same pattern. In a disk, a file is fragmented in many contiguous blocks and is accessed automatically. > There is no way you could do memory management of all but the most > trivial and fixed-length data chunks using a stack. Sure, you could > reserve thousands of bytes on the stack for an array but suppose your > language allows arrays to grow or shrink. To keep its property of > being adjacent, you'd have to do something horrible such as move > unrelated data allocated later, which raises all sorts of security > issues, doesn't it. > A stack, or something which works like a stack (that is, a stack) is a > necessary but not sufficient condition for a working C runtime because > C functions can call themselves recursively, whether directly or > indirectly. If this last condition did not obtain, each function could > give the functions it calls some of its own memory and the called > function could save a fixed set of non-stacked general registers in > that area; this was in fact the practice on IBM 370 and in assembler > language at a time when many "data processing managers" though > recursion was a Communist plot. > > However, data structures of variable size, or data structures that > merely take up a lot of space, don't play nice with others on the > stack, so, we place their address on the stack and store them in > another place, which was named the heap, probably, as a sort of > witticism. > > Gilbert and Sullivan: > > If anyone anything lacks > He'll find it all ready in stacks This you might want to take this to the Forth people because they are marketing their language as a cure for all that plagues programming today. > was wrong, and needs to be brought up to date: > > You cannot do everything in a stack > Unless you code an almighty hack > If you're a coding Knight who says, "Neep", > You'll probably need to implement a heap > A pile a heap of benefits you'll reap > If only my advice in your brain you'll keep > And avoid memory leaks from which data doth seep > By using a well-implemented, well structured, and well-documented > Heap! > > [Chorus of Sailors] > We will to heart your advice take, and always use a heap! > > [Soloist] > Oh thank you do > To this be true > And always my sage advice do keep > That you always need to use a heap!- Hide quoted text - > > - Show quoted text - From iamforufriends at gmail.com Tue Aug 17 13:29:22 2010 From: iamforufriends at gmail.com (babe is waiting) Date: Tue, 17 Aug 2010 10:29:22 -0700 (PDT) Subject: easy to fine a hot girl from your city, Message-ID: <83f704eb-7946-4758-9b5d-bec366094dc6@l25g2000prn.googlegroups.com> easy to fine a hot girl from your city, just follow the girl.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From stndshp at gmail.com Tue Aug 17 13:34:04 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 10:34:04 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> Message-ID: <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> On Aug 16, 11:09?am, Elizabeth D Rather wrote: > On 8/15/10 10:33 PM, Standish P wrote: > > >>> If Forth is a general processing language based on stack, is it > >>> possible to convert any and all algorithms to stack based ones and > >>> thus avoid memory leaks since a pop automatically releases memory when > >>> free is an intrinsic part of it. > > Forth uses two stacks. ?The "data stack" is used for passing parameters > between subroutines ("words") and is completely under the control of the > programmer. ?Words expect parameters on this stack; they remove them, > and leave only explicit results. ?The "return stack" is used primarily > for return addresses when words are called, although it is also > available for auxiliary uses under guidelines which respect the primary > use for return addresses. > > Although implementations vary, in most Forths stacks grow from a fixed > point (one for each stack) into otherwise-unused memory. ?The space > involved is allocated when the program is launched, and is not managed > as a heap and allocated or deallocated by any complicated mechanism. ?On > multitasking Forth systems, each task has its own stacks. ?Where > floating point is implemented (Forth's native arithmetic is > integer-based), there is usually a separate stack for floats, to take > advantage of hardware FP stacks. > > >> ? ? - is forth a general purpose language? Yes > >> ? ? - are all algorithms stack based? No > > > Does Forth uses stack for all algorithms ? Does it use pointers , ie > > indirect addressing ? If it can/must use stack then every algorithm > > could be made stack based. > > Forth uses its data stack for parameter passing and storage of temporary > values. ?It is also possible to define variables, strings, and arrays in > memory, in which case their addresses may be passed on the data stack. > > Forth is architecturally very simple. ?Memory allocations for variables, > etc., are normally static, although some implementations include > facilities for heaps as needed by applications. > although some implementations include facilities for heaps as needed by applications. How are these heaps being implemented ? Is there some illustrative code or a book showing how to implement these heaps in C for example ? Are dictionaries of forth and postscript themselves stacks if we consider them as nested two column tables which lisp's lists are in essence, but only single row. Multiple rows would just be multiple instances of it at the same level inside parens. we can peek into stacks which is like car. if it is not unusually costly computation, why not allow it ? there is no need to restrict to push and pop. roll( stack_name, num) itself can give all those postfix permutations that push and pop cant generate with a single stack. Can we use dictionaries to generate multiple stacks inside one global stack ? From martin at address-in-sig.invalid Tue Aug 17 13:36:13 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Tue, 17 Aug 2010 17:36:13 +0000 (UTC) Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> Message-ID: On Tue, 17 Aug 2010 10:22:27 -0500, Robert Kern wrote: > On 8/16/10 11:10 PM, Steven D'Aprano wrote: >> On Mon, 16 Aug 2010 22:56:20 -0500, Robert Kern wrote: >> >>> On 8/16/10 9:29 PM, Roy Smith wrote: >>>> In article, >>>> Lawrence D'Oliveiro wrote: >>>> >>>>> In message, Roy Smith >>>>> wrote: >>>>> >>>>>> 5) real intensity[160.0 : 30.0 : 0.01] >>>>> >>>>> How many elements in that array? >>>>> >>>>> a) 2999 >>>>> b) 3000 >>>>> c) neither of the above >>>> >>>> c) neither of the above. More specifically, 13,001 (if I counted >>>> correctly). >>> >>> 13000, actually. Floating point is a bitch. >>> >>> [~/Movies] >>> |1> import numpy >>> >>> [~/Movies] >>> |2> len(numpy.r_[160.0:30.0:-0.01]) >>> 13000 >> >> >> Actually, the answer is 0, not 13000, because the step size is given as >> 0.01, not -0.01. >> >>>>> import numpy >>>>> len(numpy.r_[160.0:30.0:-0.01]) >> 13000 >>>>> len(numpy.r_[160.0:30.0:0.01]) >> 0 > > Roy wasn't using numpy/Python semantics but made-up semantics (following > Martin Gregorie's made-up semantics to which he was replying) which > treat the step size as a true size, not a size and direction. The > direction is determined from the start and stop parameters. It's an > almost-reasonable design. That wasn't a made-up example: AFAICR and ignoring a missing semi-colon it was an Algol 68 snippet. The semantics of the for statement and the use of lwb and upb operators to extract the bounds from a 1-dimensional array are correct A68, but OTOH its a very long time since I last programmed in that language. I used that rather than Python because Algol 68 supports the non-zero lower bound and treats the array limits as attributes of the array. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From james.kanze at gmail.com Tue Aug 17 13:44:27 2010 From: james.kanze at gmail.com (James Kanze) Date: Tue, 17 Aug 2010 10:44:27 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: On Aug 17, 6:21 pm, Standish P wrote: > > Garbage collection doesn't use a stack. It uses a "heap", > > which is in the abstract a collection of memory blocks of > > different lengths, divided into two lists, generally > > represented as linked lists: > > 1. A list of blocks that are free and may be used to store > > new data > > 2. A list of blocks that are in use, or haven't been freed (yet) > Is this all that a heap is or is there more to it ? There are many different ways to implement a heap. The above is not a good one, and I doubt that it's really used anywhere. > I have been looking for simple but complete explanation of > heap for a while and not gotten to it. Complete in what sense? The basic principle of how to use it is simple. As for how to implement it, there are many different algorithms that can be used. > I think I am looking for a stack allocation on the same > pattern. Stack allocation is far, far simpler (usually). > In a disk, a file is fragmented in many contiguous blocks and > is accessed automatically. At the system level, the same thing holds for memory, and the actual physical memory is "fragmented" into contiguous blocks, each the size of a page. The MMU (hardware) makes this transparent to user programs, however. > > There is no way you could do memory management of all but the most > > trivial and fixed-length data chunks using a stack. The length isn't the issue. The order of allocation and freeing is. (For many specific uses, stack based allocators can and have been used, but they don't work for generally allocation.) -- James Kanze From drodrig at magicbrain.com Tue Aug 17 14:03:05 2010 From: drodrig at magicbrain.com (drodrig) Date: Tue, 17 Aug 2010 11:03:05 -0700 (PDT) Subject: [SOLVED]: Copying a file with a question mark in it's name in Windows References: Message-ID: <549b2846-004d-4977-a2e9-20667182aefb@v8g2000yqe.googlegroups.com> On Aug 12, 9:16?am, Aleksey wrote: > On 12 ???, 18:49,drodrig wrote: > > > A python script I use to backup files on a Windows 2003 server > > occasionally fails to retrieve the size of a file with a question mark > > in the name. The exception I get is "OSError #123 The filename, > > directory name, or volume label syntax is incorrect". I realize that > > technically a question mark in the name of a file on Windows is > > illegal, but nevertheless these files exist on the file system. It > > seems that they are created by Office 2007 Word, for the most part. (Sorry for the late reply) Thank you. The questions marks are indeed placeholders for unprintable characters. The glob module did the trick. > > If "?" is a placeholder for an unprintable character you can try view > real file name in IDLE: > > ? import glob > ? print glob.glob(u'e:/full/path/to/file?') > > In path to file you must instead question use wild "?". > Will be printed all like files. > > ----------------------------- > Under Windows I too have similar problem: windows sometimes (from any > programs - e.g. Firefox) save files with wrong names, but later > do not manipulate with it. From stndshp at gmail.com Tue Aug 17 14:20:11 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 11:20:11 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <7zaaolzm89.fsf@ask.diku.dk> Message-ID: <89467860-45ac-4a3b-ac17-f11a19429187@i13g2000yqd.googlegroups.com> On Aug 17, 1:17?am, torb... at diku.dk (Torben ?gidius Mogensen) wrote: > Standish P writes: > > [Q] How far can stack [LIFO] solve do automatic garbage collection and > > prevent memory leak ? > > > Because a stack has push and pop, it is able to release and allocate > > memory. We envisage an exogenous stack which has malloc() associated > > with a push and free() associated with a pop. > > See How many programmers have applied the ideas of these papers in their programming practice ? I paste the abstract for convenience > http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 Abstract: This paper describes a memory management discipline for programs that perform dynamic memory allocation and de-allocation. At runtime, all values are put into regions. The store consists of a stack of regions. All points of region allocation and deallocation are inferred automatically, using a type and effect based program analysis. The scheme does not assume the presence of a garbage collector. The scheme was first presented by Tofte and Talpin (1994); subsequently, it has been tested in The ML Kit with Regions, a region-based, garbage- collection free implementation of the Standard ML Core language, which includes recursive datatypes, higher-order functions and updatable references (Birkedal et al. 96, Elsman and Hallenberg 95). This paper defines a region-based dynamic semantics for a skeletal programming language extracted from Standard ML. We present the inference system which specifies where regions can be allocated and de-allocated and a detailed proof that the system is sound wi... > > http://portal.acm.org/citation.cfm?doid=174675.177855 ABSTRACT We present a translation scheme for the polymorphically typed call-by- value &lgr;-calculus. All runtime values, including function closures, are put into regions. The store consists of a stack of regions. Region inference and effect inference are used to infer where regions can be allocated and de-allocated. Recursive functions are handled using a limited form of polymorphic recursion. The translation is proved correct with respect to a store semantics, which models as a region- based run-time system. Experimental results suggest that regions tend to be small, that region allocation is frequent and that overall memory demands are usually modest, even without garbage collection. > > http://www.springerlink.com/content/m2074884n6gt612h/ > Abstract We report on our experience with designing, implementing, proving correct, and evaluating a region-based memory management system. dynamic storage management - regions - Standard ML > ? ? ? ? Torben From almar.klein at gmail.com Tue Aug 17 14:26:12 2010 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 17 Aug 2010 20:26:12 +0200 Subject: 79 chars or more? In-Reply-To: <4C6ABC16.4070006@gmail.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6ABC16.4070006@gmail.com> Message-ID: On 17 August 2010 18:43, AK wrote: > On 08/17/2010 12:21 PM, Stefan Schwarzer wrote: > >> On 2010-08-17 17:44, AK wrote: >> >>> On 08/17/2010 10:28 AM, Stefan Schwarzer wrote: >>> >>>> I'd probably reformat this to >>>> >>>> self.expiration_date = translate_date( >>>> find(response, 'MPNExpirationDate').text, >>>> '%Y-%m-%d', '%m%d%Y') >>>> >>>> or even >>>> >>>> self.expiration_date = translate_date( >>>> find(response, 'MPNExpirationDate').text, >>>> '%Y-%m-%d', >>>> '%m%d%Y') >>>> >>>> for consistency. >>>> >>>> This not only limits the width but also makes the nesting of >>>> the calls more visible. >>>> >>> >>> Doesn't this create the problem of functions growing too long to fit in >>> a screen? I think it's very useful to try to keep function size low >>> enough so that you can view the whole function without having to scroll >>> up and down. (even though that's not always possible) -ak >>> >> >> I think I'd extract some part of the function into a new >> function then. In my opinion, the reasoning is similar to >> the case, "Can't I use two spaces per indentation level? >> That way I don't run so easily into the right margin if I >> have more than five indentations in a function." ;-) >> > > I think to some extent it's a matter of taste. I bet most people would > agree that on the balance, 2-space indentations makes code much less > readable, despite saving a bit of space. > > But let me ask you, would you really prefer to have: > > > self.expiration_date = translate_date( >>>> find(response, 'MPNExpirationDate').text, >>>> '%Y-%m-%d', '%m%d%Y') >>>> >>> > (or the 4-line version of this above), even when it necessitates > creation of a new function, rather than have this code on two lines? > > After all, I think it's a matter of balance between readability, > expressiveness and succinctness. If I split a function in two, that > still means that understanding the functionality of the code will > require scrolling around and looking at the second function. I guess > what I'm trying to say that we shouldn't just care about readability of > lines but also readability of functions and blocks of functionality > (that may include several functions that accomplish a single "task".) > > -andrei > > -- > http://mail.python.org/mailman/listinfo/python-list > I am in favor of the 80-char limit also. Besides the arguments listed above, when using an IDE it gives you that extra horizontal space to fit some IDE specific tools (such as source structure). I must admit that I'm sometimes slightly frustrated when an expression is JUST 81 chars, and I *need* to reformat to two lines. On the other hand, very long lines are hard to read also. I guess the limit must be placed somewhere, and for historical reasons, 80 chars makes the most sense IMO. On a related note, why is the limit mentioned in PEP8 79 chars, and not 80? I never understood this :) Cheers, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From hwfwguy at gmail.com Tue Aug 17 14:29:36 2010 From: hwfwguy at gmail.com (Brad) Date: Tue, 17 Aug 2010 11:29:36 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> Message-ID: On Aug 17, 10:34?am, Standish P wrote: > On Aug 16, 11:09?am, Elizabeth D Rather wrote: > > How are these heaps being implemented ? Is there some illustrative > code or a book showing how to implement these heaps in C for example ? > Forth does not use a heap, except maybe to implement malloc/free which many Forth apps do not use. The dictionary is a linked list structure. Now seems like a good time for you to teach yourself Forth (by studying the best commercial implementation you can find) since you seem to be working with a clean slate. But I will say a few things about stacks in general. There are many ways to implement stacks. The simplest is to declare some space for the stack and then post-increment or pre-decrement a stack pointer depending on whether you're pushing or popping. Normally you make the memory for them big enough that they don't overflow. If you are concerned about stack overflow you can change the implementation. Add bounds checking, for example. Another trick is to use an 8-bit stack pointer. Then you will have a circular stack. If there is underflow or overflow it at least will not step on other data. It will only return bad data, which you may find preferable to an ugly crash. OTOH, bugs that cause spectacular failures tend to be discovered. You can also initialize the stack memory with a pattern like 0xDEAD and then after sufficiently exercising the code, examine the memory contents to see the "high water mark" of the stack pointer. -Brad From tjreedy at udel.edu Tue Aug 17 14:47:32 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Aug 2010 14:47:32 -0400 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6ABC16.4070006@gmail.com> Message-ID: On 8/17/2010 2:26 PM, Almar Klein wrote: > On a related note, why is the limit mentioned in PEP8 79 chars, and not > 80? I never understood this :) A newline char or block or underline cursor makes 80. The importance depended on the terminal. 80 chars on the last line could especially be a problem. -- Terry Jan Reedy From stndshp at gmail.com Tue Aug 17 14:53:27 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 11:53:27 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: On Aug 16, 12:20?am, Standish P wrote: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? > Because a stack has push and pop, it is able to release and allocate > memory. We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. > The algorithm using the stack would have to be "perfect" to prevent > stack overflow or condition of infinite recursion depth. This would > involve data type checking to filter out invalid input. The task must > be casted in an algorithm that uses the stack. Then the algorithm must > be shown to be heuristically or by its metaphor, to be correct using > informal reasoning. > Are there any standard textbooks or papers that show stacks > implemented in C/C++/Python/Forth with malloc/free in push and pop ? > If Forth is a general processing language based on stack, is it > possible to convert any and all algorithms to stack based ones and > thus avoid memory leaks since a pop automatically releases memory when > free is an intrinsic part of it. > K&R ANSI has the example of modular programming showing how to > implement a stack but he uses a fixed length array. It is also > possibly an endogenous stack. We look for an exogenous stack so that > element size can vary. > > ======= > Standish P Another way to pose my question, as occurred to me presently is to ask if a stack is a good abstraction for programming ? Certainly, it is the main abstraction in Forth and Postscript and implementable readily in C,C++ and I assume python. It is true that the other languages such as F/PS also have borrowed lists from lisp in the name of nested-dictionaries and mathematica calls them nested-tables as its fundamental data structure. I am asking for a characterization of algorithms that benefit from this abstraction or programming paradigm and comparison with others. The whole case of OOP is the clustering of thought, ie book-keeping, in the mind of the programmer around fewer objects than ten or twenty fold functions. so the name of the game is the same, ie to help the programmer keep track of things for writing fault free code without chasing every case, easy visualization, easy recall and communication with fellow programmers of abstract concepts in terms of real world objects and easy modification and code reuse. From python at mrabarnett.plus.com Tue Aug 17 14:56:28 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 17 Aug 2010 19:56:28 +0100 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6ABC16.4070006@gmail.com> Message-ID: <4C6ADB5C.70300@mrabarnett.plus.com> Almar Klein wrote: > [snip] > > I am in favor of the 80-char limit also. Besides the arguments listed > above, when using an IDE it gives you that extra horizontal space to fit > some IDE specific tools (such as source structure). > > I must admit that I'm sometimes slightly frustrated when an expression > is JUST 81 chars, and I *need* to reformat to two lines. On the other > hand, very long lines are hard to read also. I guess the limit must be > placed somewhere, and for historical reasons, 80 chars makes the most > sense IMO. > > On a related note, why is the limit mentioned in PEP8 79 chars, and not > 80? I never understood this :) > If the display is limited to 80 characters then after printing the 80th the cursor will be at the start of the next line and the newline will cause the display to leave a blank line (unless the display has some intelligence and supports pending newlines, of course). From tjreedy at udel.edu Tue Aug 17 14:57:22 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Aug 2010 14:57:22 -0400 Subject: 79 chars or more? In-Reply-To: References: Message-ID: On 8/17/2010 3:47 AM, Lawrence D'Oliveiro wrote: > In message, AK wrote: > >> As monitors are getting bigger, is there a general change in opinion on >> the 79 chars limit in source files? > > WHAT 79-character limit in source files? Only for stdlib. Python itself has no particular limit. The dev discussed the issue perhaps a year ago. Enough people wanted or needed the current stdlib limit that they decided to stick with it. A reason not mentioned much is that some people have trouble following packed lines that are too much longer. Wide-page textbooks routinely put text in two columns for easier reading. This is less of a factor with jagged edge text, but if the limit were increased to say 150, there would be people writing multi-line 150 char wide text blocks. -- Terry Jan Reedy From hansmu at xs4all.nl Tue Aug 17 14:59:25 2010 From: hansmu at xs4all.nl (Hans Mulder) Date: Tue, 17 Aug 2010 20:59:25 +0200 Subject: bash: syntax error near unexpected token In-Reply-To: References: Message-ID: <4c6adc4c$0$22918$e4fe514c@news.xs4all.nl> Benjamin Kaplan wrote: > On Mon, Aug 16, 2010 at 11:33 PM, kreglet wrote: >> desktop:~/bin$ modtest.py >> desktop:~/bin$ evenodd(45) >> bash: syntax error near unexpected token `45' >> > > And this is what's supposed to happen any time you try this in any > shell. When you call evenodd, bash looks for a program or shell > built-in called evenodd. Which doesn't exist. That's not what "syntax error means". If the problem were that evenodd does not exist as a shell function, the error would have been "bash: evenodd: command not found". I do not understand why bash says the token `45' is unexpected. The '(' token is the problem. It's a syntax error because in bash syntax function arguments are not enclosed in parentheses: $ function evenodd { > if (( $1 % 2 )) > then echo $1 is odd > else echo $1 is even > fi > } $ evenodd 45 45 is odd $ evenodd(45) bash: syntax error near unexpected token `45' $ Of course, this is completely off-topic. -- HansM From news1234 at free.fr Tue Aug 17 15:14:34 2010 From: news1234 at free.fr (News123) Date: Tue, 17 Aug 2010 21:14:34 +0200 Subject: Opposite of split In-Reply-To: References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> <4C6A992D.5020802@sschwarzer.net> <8cvokpF1r0U3@mid.individual.net> Message-ID: <4c6adf9a$0$12224$426a74cc@news.free.fr> On 08/17/2010 05:46 PM, Grant Edwards wrote: > On 2010-08-17, Neil Cerutti wrote: >> On 2010-08-17, Stefan Schwarzer wrote: >>> Hi Alex, >>> >>> On 2010-08-16 18:44, Alex van der Spek wrote: >>>> Anybody catches any other ways to improve my program (attached), you are >>>> most welcome. Help me learn, that is one of the objectives of this >>>> newsgroup, right? Or is it all about exchanging the next to impossible >>>> solution to the never to happen unreal world problems? >>> >>> I don't know what a concordance table is, and I haven't >>> looked a lot into your program, but anyway here are some >>> things I noticed at a glance: >>> >>> | #! usr/bin/env python >>> | # Merge log files to autolog file >>> | import os >>> | import fileinput >>> | #top='C:\\Documents and Settings\\avanderspek\\My Documents\\CiDRAdata\\Syncrude\\CSL\\August2010' >>> | top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010' >>> >>> If you have backslashes in strings, you might want to use "raw >>> strings". Instead of "c:\\Users\\ZDoor" you'd write >>> r"c:\Users\ZDoor" (notice the r in front of the string). >> >> That's good general advice. But in the specific case of file >> paths, using '/' as the separator is supported, and somewhat >> preferable. > > Unless you're going to be passing them to cmd.exe or other utilities > via subprocess/popen. > in that case you could use os.path.normpath() prior to passing it to an external program und use slashies internally. A little less performant, but in my opinion nicer typing. From jak at isp2dial.com Tue Aug 17 15:14:50 2010 From: jak at isp2dial.com (John Kelly) Date: Tue, 17 Aug 2010 19:14:50 +0000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <8onl66tuq3k7a500atbpjtlj2bgbnpe0dq@4ax.com> On Tue, 17 Aug 2010 11:53:27 -0700 (PDT), Standish P wrote: >Another way to pose my question, as occurred to me presently is to ask >if a stack is a good abstraction for programming ? Certainly, it is >the main abstraction in Forth and Postscript and implementable readily >in C,C++ and I assume python. >so the name of the game is the same, ie to help the programmer keep >track of things for writing fault free code without chasing every >case, easy visualization, easy recall and communication with fellow >programmers of abstract concepts in terms of real world objects and >easy modification and code reuse. "Go is an attempt to combine the ease of programming of an interpreted, dynamically typed language with the efficiency and safety of a statically typed, compiled language. It also aims to be modern, with support for networked and multicore computing" "To make the stacks small, Go's run-time uses segmented stacks. A newly minted goroutine is given a few kilobytes, which is almost always enough. When it isn't, the run-time allocates (and frees) extension segments automatically" http://golang.org/doc/go_lang_faq.html -- Web mail, POP3, and SMTP http://www.beewyz.com/freeaccounts.php From almar.klein at gmail.com Tue Aug 17 15:31:07 2010 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 17 Aug 2010 21:31:07 +0200 Subject: 79 chars or more? In-Reply-To: References: Message-ID: > > A reason not mentioned much is that some people have trouble following > packed lines that are too much longer. Wide-page textbooks routinely put > text in two columns for easier reading. This is less of a factor with jagged > edge text, but if the limit were increased to say 150, there would be people > writing multi-line 150 char wide text blocks. > You're right. From Lshort (the introduction to Latex): "On average, no line should be longer than 66 characters." This applies to regular text, not for code per see, but it makes a strong case against (very) long lines. Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From john.passaniti at gmail.com Tue Aug 17 15:32:00 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Tue, 17 Aug 2010 12:32:00 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> On Aug 17, 2:53?pm, Standish P wrote: > Another way to pose my question, as occurred to me presently is > to ask if a stack is a good abstraction for programming ? > Certainly, it is the main abstraction in Forth and Postscript > and implementable readily in C,C++ and I assume python. A stack is a fine abstraction for some kinds of programming. It fails for others. In languages where functions are first-class entities that can be stored and passed around like any other kind of data, stacks can be problematic because a function can out-live the stack frame they were created in. > It is true that the other languages such as F/PS also have borrowed > lists from lisp in the name of nested-dictionaries and mathematica > calls them nested-tables as its fundamental data structure. No. > The whole case of OOP is the clustering of thought, ie book-keeping, > in the mind of the programmer around fewer objects than ten or twenty > fold functions. That's one view of OOP. It's not the only one. > so the name of the game is the same, ie to help the programmer keep > track of things for writing fault free code without chasing every > case, easy visualization, easy recall and communication with fellow > programmers of abstract concepts in terms of real world objects and > easy modification and code reuse. You, like probably everyone else who has thought about how to "simplify" languages will eventually end up at the same place-- you'll have a model that meets your objectives, but with some programmers will find is unnecessarily limiting. More importantly, you'll run into some classes of problems for which your simple model makes things inordinately complicated relative to what other languages and paradigms offer. Here's a better idea: Become familiar with the languages you've cited, and more. I would recommend Forth, Lisp, Smalltalk or Ruby, Lua or JavaScript. Learn each and then come back and tell us if you think limiting the programmer to objects with stack-ordered lifetimes is enough. Oh, and while you're at it, dip your toes into a problem domain you don't normally do any work in. If you're an embedded systems guy, then spend some time writing a non-trivial web application. Go outside your comfort zone and find a problem domain where cherished idioms and tools no longer apply. I think it will open your eyes. From sschwarzer at sschwarzer.net Tue Aug 17 15:32:14 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 17 Aug 2010 21:32:14 +0200 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> Message-ID: <4C6AE3BE.5040908@sschwarzer.net> Hi Andrei, On 2010-08-17 18:43, AK wrote: > But let me ask you, would you really prefer to have: > >>>> self.expiration_date = translate_date( >>>> find(response, 'MPNExpirationDate').text, >>>> '%Y-%m-%d', '%m%d%Y') > > (or the 4-line version of this above), even when it necessitates > creation of a new function, rather than have this code on two lines? Given that the reformatted code is three lines and the former code two lines, I probably wouldn't change anything but the formatting as shown. :) > After all, I think it's a matter of balance between readability, > expressiveness and succinctness. If I split a function in two, that > still means that understanding the functionality of the code will > require scrolling around and looking at the second function. I guess > what I'm trying to say that we shouldn't just care about readability of > lines but also readability of functions and blocks of functionality > (that may include several functions that accomplish a single "task".) I think you're right here; you should keep the overall readability or (maintainability on the whole) in mind. I agree with Neil that good refactoring can _improve_ the understandability of the code, and it won't necessarily require you to look up the code of the extracted function or method. Stefan From almar.klein at gmail.com Tue Aug 17 15:33:12 2010 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 17 Aug 2010 21:33:12 +0200 Subject: 79 chars or more? In-Reply-To: <4C6ADB5C.70300@mrabarnett.plus.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6ABC16.4070006@gmail.com> <4C6ADB5C.70300@mrabarnett.plus.com> Message-ID: > If the display is limited to 80 characters then after printing the 80th > the cursor will be at the start of the next line and the newline will > cause the display to leave a blank line (unless the display has some > intelligence and supports pending newlines, of course). Ahah! So Windows users should actually limit their text to 78 chars? :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrei.avk at gmail.com Tue Aug 17 15:54:23 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 15:54:23 -0400 Subject: 79 chars or more? In-Reply-To: <4C6AE3BE.5040908@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6AE3BE.5040908@sschwarzer.net> Message-ID: <4C6AE8EF.9050506@gmail.com> On 08/17/2010 03:32 PM, Stefan Schwarzer wrote: > Hi Andrei, > > On 2010-08-17 18:43, AK wrote: >> But let me ask you, would you really prefer to have: >> >>>>> self.expiration_date = translate_date( >>>>> find(response, 'MPNExpirationDate').text, >>>>> '%Y-%m-%d', '%m%d%Y') >> >> (or the 4-line version of this above), even when it necessitates >> creation of a new function, rather than have this code on two lines? > > Given that the reformatted code is three lines and the > former code two lines, I probably wouldn't change anything > but the formatting as shown. :) > >> After all, I think it's a matter of balance between readability, >> expressiveness and succinctness. If I split a function in two, that >> still means that understanding the functionality of the code will >> require scrolling around and looking at the second function. I guess >> what I'm trying to say that we shouldn't just care about readability of >> lines but also readability of functions and blocks of functionality >> (that may include several functions that accomplish a single "task".) > > I think you're right here; you should keep the overall > readability or (maintainability on the whole) in mind. > > I agree with Neil that good refactoring can _improve_ the > understandability of the code, and it won't necessarily > require you to look up the code of the extracted > function or method. I can certainly agree with that - although this sort of refactoring (when I do it) is driven by the logic of the code rather than the need to spread a long line over several lines :-). -andrei From barry at python.org Tue Aug 17 15:55:20 2010 From: barry at python.org (Barry Warsaw) Date: Tue, 17 Aug 2010 15:55:20 -0400 Subject: Python 2.6.6 release candidate 2 now available. Message-ID: <20100817155520.0d02675f@heresy> Hello fellow Python enthusiasts, The source tarballs and Windows installers for the second (and hopefully last) Python 2.6.6 release candidate is now available: http://www.python.org/download/releases/2.6.6/ We've had a handful of important fixes since rc1, and of course a huge number of bugs have been fixed since 2.6.5, with the full NEWS file available here: http://www.python.org/download/releases/2.6.6/NEWS.txt We would love it if you can download, install, and test this version with your favorite projects and on your favorite platforms. We expect to release Python 2.6.6 final on August 24, 2010. Please note that with the release of Python 2.7 final on July 3, 2010, and in accordance with Python policy, Python 2.6.6 is the last scheduled bug fix maintenance release of the 2.6 series. Because of this, your testing of this release candidate will help immensely. We plan on continuing to support source-only security fixes in Python 2.6 for the next five years. My thanks go out to everyone who has contributed with code, testing and bug tracker gardening for Python 2.6.6. The excellent folks on #python-dev are true Pythonic heros. Enjoy, -Barry (on behalf of the Python development community) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: not available URL: From ringemup at gmail.com Tue Aug 17 15:55:21 2010 From: ringemup at gmail.com (Nan) Date: Tue, 17 Aug 2010 12:55:21 -0700 (PDT) Subject: subprocess.Popen calling httpd reload never finishes Message-ID: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Hi folks -- I have a Python script running under Apache/mod_wsgi that needs to reload Apache configs as part of its operation. The script continues to execute after the subprocess.Popen call. The communicate() method returns the correct text ("Reloading httpd: [ OK ]"), and I get a returncode of 0. But the python script (Django) that calls Popen never seems to complete (by returning an HTTP response. Any other Popen call I've tried exits properly. Here's some sample code: args = ['sudo /etc/init.d/httpd reload'] proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, close_fds=True) (stdout_txt, stderr_txt) = proc.communicate("") proc.wait() logging.debug('%d %s


%s' % (proc.returncode, stdout_txt, stderr_txt)) logging.debug('still executing') return HttpResponse('done') The logging statements are output, but the script doesn't exit. If you substitute "sudo ls -l" or "sudo /etc/init.d/httpd configtest" for "sudo /etc/init.d/httpd reload", the exits properly. Any idea what I might be doing wrong? Thanks! From clp2 at rebertia.com Tue Aug 17 15:57:43 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 17 Aug 2010 12:57:43 -0700 Subject: Open a command pipe for reading In-Reply-To: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> References: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 9:40 AM, Rodrick Brown wrote: > I have a fairly large file 1-2GB in size that I need to process line by line but I first need to convert the file to text using a 3rd party tool that prints the records also line by line. > > I've tried using Popen to do this with no luck. I'm trying to simulate > > /bin/foo myfile.dat > > And as the records are being printed do some calculations. > > pipe = Popen(exttool,shell=True,stdout=PIPE).stdout I'd strongly suggest trying to avoid shell=True. > for data in pipe.readlines(): for data in pipe: > ? ?print data, > > This operation blocks forever I'm guessing it's trying to process the entire file at once. Indeed, that's how readlines() works, so don't use it. http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects Cheers, Chris -- http://blog.rebertia.com From thomas at jollybox.de Tue Aug 17 16:05:24 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 17 Aug 2010 22:05:24 +0200 Subject: Open a command pipe for reading In-Reply-To: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> References: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> Message-ID: <201008172205.27126.thomas@jollybox.de> On Tuesday 17 August 2010, it occurred to Rodrick Brown to exclaim: > I have a fairly large file 1-2GB in size that I need to process line by > line but I first need to convert the file to text using a 3rd party tool > that prints the records also line by line. > > I've tried using Popen to do this with no luck. I'm trying to simulate > > /bin/foo myfile.dat > > And as the records are being printed do some calculations. > > pipe = Popen(exttool,shell=True,stdout=PIPE).stdout > > for data in pipe.readlines(): > print data, > > This operation blocks forever I'm guessing it's trying to process the > entire file at once. Yes. It is. That's what you're telling it to do: file.readline returns a list of all the lines in the file. What you want to do is iterate over the stream, as in: for line in pipe: process(line) Also, there's probably no need to use shell=True. > > Sent from my iPhone 4. Is that a fact? This is so interesting. Phones these days. Almost as annoyingly obnoxious as gmx and yahoo mail. From stndshp at gmail.com Tue Aug 17 16:19:23 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 13:19:23 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> Message-ID: <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> On Aug 17, 12:32?pm, John Passaniti wrote: > On Aug 17, 2:53?pm, Standish P wrote: > > > Another way to pose my question, as occurred to me presently is > > to ask if a stack is a good abstraction for programming ? > > Certainly, it is the main abstraction in Forth and Postscript > > and implementable readily in C,C++ and I assume python. > > A stack is a fine abstraction for some kinds of programming. ?It fails > for others. ?In languages where functions are first-class entities > that can be stored and passed around like any other kind of data, > stacks can be problematic because a function can out-live the stack > frame they were created in. > > > It is true that the other languages such as F/PS also have borrowed > > lists from lisp in the name of nested-dictionaries and mathematica > > calls them nested-tables as its fundamental data structure. > > No. you are contradicting an earlier poster from forth who admitted the part on dicts. > > > The whole case of OOP is the clustering of thought, ie book-keeping, > > in the mind of the programmer around fewer objects than ten or twenty > > fold functions. > > That's one view of OOP. ?It's not the only one. and what can you add to enlighten the readers on the other view ? > > > so the name of the game is the same, ie to help the programmer keep > > track of things for writing fault free code without chasing every > > case, easy visualization, easy recall and communication with fellow > > programmers of abstract concepts in terms of real world objects and > > easy modification and code reuse. > > You, like probably everyone else who has thought about how to > "simplify" languages will eventually end up at the same place-- you'll > have a model that meets your objectives, but with some programmers > will find is unnecessarily limiting. ?More importantly, you'll run > into some classes of problems for which your simple model makes things > inordinately complicated relative to what other languages and > paradigms offer. The objective is to discuss those cases via specific examples (not generalities), and talk ABOUT them, not AROUND them. > Here's a better idea: ? Its a very fine wild goose chase project statement. > Become familiar with the languages you've > cited, and more. ?I would recommend Forth, Lisp, Smalltalk or Ruby, > Lua or JavaScript. ?Learn each and then come back and tell us if you > think limiting the programmer to objects with stack-ordered lifetimes > is enough. ?Oh, and while you're at it, dip your toes into a problem > domain you don't normally do any work in. ?If you're an embedded > systems guy, then spend some time writing a non-trivial web > application. ?Go outside your comfort zone and find a problem domain > where cherished idioms and tools no longer apply. ?I think it will > open your eyes. From a.j.romanista at gmail.com Tue Aug 17 16:19:53 2010 From: a.j.romanista at gmail.com (ata.jaf) Date: Tue, 17 Aug 2010 13:19:53 -0700 (PDT) Subject: Looking for an appropriate encoding standard that supports all languages Message-ID: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> I am developing a little program in Mac with wxPython. But I have problems with the characters that are not in ASCII. Like some special characters in French or Turkish. So I am looking for a way to solve this. Like an encoding standard that supports all languages. Or some other way. Thanks Ata Jafari From stndshp at gmail.com Tue Aug 17 16:22:09 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 13:22:09 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On Aug 17, 1:19?pm, Standish P wrote: > On Aug 17, 12:32?pm, John Passaniti wrote: > > > > > > > On Aug 17, 2:53?pm, Standish P wrote: > > > > Another way to pose my question, as occurred to me presently is > > > to ask if a stack is a good abstraction for programming ? > > > Certainly, it is the main abstraction in Forth and Postscript > > > and implementable readily in C,C++ and I assume python. > > > A stack is a fine abstraction for some kinds of programming. ?It fails > > for others. ?In languages where functions are first-class entities > > that can be stored and passed around like any other kind of data, > > stacks can be problematic because a function can out-live the stack > > frame they were created in. > > > > It is true that the other languages such as F/PS also have borrowed > > > lists from lisp in the name of nested-dictionaries and mathematica > > > calls them nested-tables as its fundamental data structure. > > > No. > > you are contradicting an earlier poster from forth who admitted the > part on dicts. > > > > > > The whole case of OOP is the clustering of thought, ie book-keeping, > > > in the mind of the programmer around fewer objects than ten or twenty > > > fold functions. > > > That's one view of OOP. ?It's not the only one. > > and what can you add to enlighten the readers on the other view ? > > > > > > so the name of the game is the same, ie to help the programmer keep > > > track of things for writing fault free code without chasing every > > > case, easy visualization, easy recall and communication with fellow > > > programmers of abstract concepts in terms of real world objects and > > > easy modification and code reuse. > > > You, like probably everyone else who has thought about how to > > "simplify" languages will eventually end up at the same place-- you'll > > have a model that meets your objectives, but with some programmers > > will find is unnecessarily limiting. ?More importantly, you'll run > > into some classes of problems for which your simple model makes things > > inordinately complicated relative to what other languages and > > paradigms offer. > > The objective is to discuss those cases via specific examples (not > generalities), and talk ABOUT them, not AROUND them. > > > Here's a better idea: ? > > Its a very fine wild goose chase project statement. > > > > > Become familiar with the languages you've > > cited, and more. ?I would recommend Forth, Lisp, Smalltalk or Ruby, > > Lua or JavaScript. ?Learn each and then come back and tell us if you > > think limiting the programmer to objects with stack-ordered lifetimes > > is enough. ?Oh, and while you're at it, dip your toes into a problem > > domain you don't normally do any work in. ?If you're an embedded > > systems guy, then spend some time writing a non-trivial web > > application. ?Go outside your comfort zone and find a problem domain > > where cherished idioms and tools no longer apply. ?I think it will > > open your eyes program a universe simulator using a turing machine. From erather at forth.com Tue Aug 17 16:37:17 2010 From: erather at forth.com (Elizabeth D Rather) Date: Tue, 17 Aug 2010 10:37:17 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On 8/17/10 10:19 AM, Standish P wrote: > On Aug 17, 12:32 pm, John Passaniti wrote: ... >>> It is true that the other languages such as F/PS also have borrowed >>> lists from lisp in the name of nested-dictionaries and mathematica >>> calls them nested-tables as its fundamental data structure. >> >> No. > > you are contradicting an earlier poster from forth who admitted the > part on dicts. Not at all. A Forth dictionary is a simple linked list, not the complicated kind of nested structures you're referring to. You really seem addicted to very complex structures. They really aren't necessary for general programming. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From thomas at jollybox.de Tue Aug 17 16:55:42 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 17 Aug 2010 22:55:42 +0200 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> Message-ID: <201008172255.46662.thomas@jollybox.de> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > I am developing a little program in Mac with wxPython. > But I have problems with the characters that are not in ASCII. Like > some special characters in French or Turkish. > So I am looking for a way to solve this. Like an encoding standard > that supports all languages. Or some other way. Anything that supports all of Unicode will do. Like UTF-8. If your text is mostly Latin, then just go for UTF-8, if you use other alphabets extensively, you might want to consider UTF-16, which might the use a little less space. From raoulbia at gmail.com Tue Aug 17 17:44:22 2010 From: raoulbia at gmail.com (Baba) Date: Tue, 17 Aug 2010 14:44:22 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> Message-ID: <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> On Aug 16, 6:28?pm, "cbr... at cbrownsystems.com" wrote: > First, suppose d = gcd(x, y, z); then for some x', y', z' we have that > x = d*x', y = d*y', z = d*z'; and so for any a, b, c: > could you explain the notation? what is the difference btw x and x' ? what is x = d*x', y supposed to say? > To go the other way, if d = 1, then there exists integers (not > neccessarily positive) such that > > a*x + b*y + c*z = 1 > what's the link with 6*a+9*b+20*c=n except the similarity? furthermore i came across this: For k = 3, efficient algorithms have been given by Greenberg and Davison ; if x1 < x2 < x3, these algorithms run in time bounded by a polynomial in log x3. Kannan gave a very complicated algorithm that runs in polynomial time in log xk if k is fixed, but is wildly exponential in k. However, Ram??rez Alfons??n proved that the general problem is NP-hard, under Turing reductions, by reducing from the integer knapsack problem. So it seems very likely that there is no simple formula for computing g(x1, x2, . . . , xk) for arbitrary k. source: http://arxiv.org/PS_cache/arxiv/pdf/0708/0708.3224v1.pdf i would be interested in the answer to problem 3: explain in English why the theorem is true @Giacomo: when you say that i have not read the text of the assignment i tend to disagree. Therefore could you point out what it is i overlooked that should help me prove my assumption for the generalisation? Enjoy the sausages btw :) tnx Baba From paddy3118 at googlemail.com Tue Aug 17 17:47:55 2010 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 17 Aug 2010 14:47:55 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> <2abafeea-78e6-454c-8c3d-debe888d2bc7@h40g2000pro.googlegroups.com> Message-ID: On 17 Aug, 02:29, Raymond Hettinger wrote: > [Paddy] > > > Lets say you have two *sets* of integers representing two near-copies > > of some system, then a measure of their difference could be calculated > > as: > > > len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 % > > > If the two collections of integers are allowed duplicates then you > > need a Counter/bag/multi-set type and the diff calculation I gave > > originally. > > Thanks for sharing your use case. > > It's unlikely that I will add this method to the Counter API because > the rarity of use case does not warrant the added API complexity. > IMO, adding a method like this makes the class harder to learn, > understand and remember. ?It doesn't seem like much of a win over > using the existing alternatives: > > ?* (b - c) + (c - b) > ?* (b | c) - (b & c) > ?* DIY using the two counters as simple dicts > ?* writing a subclass providing additional binary operations > > I would like to see someone post a subclass to the ASPN Cookbook that > adds a number of interesting, though not common operations. ?Your > symmetric_difference() method could be one. ?A dot_product() operation > could be another. ?Elementwise arithmetic is another option (we > already have add and subtract, but could possibly use multiply, > divide, etc). ?Scaling operations are another possibility (multiple > all elements by five, for example). > > The Counter() class has low aspirations. ?It is a dictionary that > fills-in missing values with zero and is augmented by a handful of > basic methods for managing the counts. > > Raymond I created this that could be an addition to the bottom of the Python 3 collections.Counter class definition: def __xor__(self, other): ''' symmetric difference: Subtract count, but keep only abs results with non-zero counts. >>> Counter('abbbc') ^ Counter('bccd') Counter({'b': 2, 'a': 1, 'c': 1, 'd': 1}) >>> a, b = Counter('abbbc'), Counter('bccd') >>> (a-b) + (b - a) == a ^ b True ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem in set(self) | set(other): newcount = self[elem] - other[elem] if newcount != 0: result[elem] = newcount if newcount > 0 else -newcount return result - Paddy. From roy at panix.com Tue Aug 17 17:54:29 2010 From: roy at panix.com (Roy Smith) Date: Tue, 17 Aug 2010 17:54:29 -0400 Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> Message-ID: In article , Martin Gregorie wrote: > > Roy wasn't using numpy/Python semantics but made-up semantics (following > > Martin Gregorie's made-up semantics to which he was replying) which > > treat the step size as a true size, not a size and direction. The > > direction is determined from the start and stop parameters. It's an > > almost-reasonable design. > > That wasn't a made-up example: AFAICR and ignoring a missing semi-colon > it was an Algol 68 snippet. It was a made up example. Any similarity to a real programming language, living or dead, was purely a coincidence. I suspect I've probably also written a viable code snippet in Whitespace as well (http://compsoc.dur.ac.uk/whitespace/). That, too, is a coincidence. From roy at panix.com Tue Aug 17 17:55:35 2010 From: roy at panix.com (Roy Smith) Date: Tue, 17 Aug 2010 17:55:35 -0400 Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> <4c6a8cff$1@dnews.tpgi.com.au> Message-ID: In article <4c6a8cff$1 at dnews.tpgi.com.au>, Lie Ryan wrote: > On 08/16/10 21:54, David Cournapeau wrote: > > On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing > > wrote: > >>> On Aug 7, 2010, at 9:14 PM, John Nagle wrote: > >>> > >>>> The languages which have real multidimensional arrays, rather > >>>> than arrays of arrays, tend to use 1-based subscripts. That > >>>> reflects standard practice in mathematics. > >> > >> Not always -- mathematicians use whatever starting index is > >> most convenient for the problem at hand. > > > > Yes, there are many engineering fields where index starts at 0. Partly > > for the reason you have stated concerning polynomials, especially > > since this extend to series, which are pervasive in numerical > > computing. In linear algebra, though, I remember to have always noted > > matrices indexes in the [1,n] range, not [0,n-1]. > > I'm sure some would prefer to denote it as [0, n) Only if there's an emacs mode which can do the parenthesis matching correctly ;-) From nobody at nowhere.com Tue Aug 17 17:58:09 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 17 Aug 2010 22:58:09 +0100 Subject: 79 chars or more? References: Message-ID: On Mon, 16 Aug 2010 22:35:49 -0400, AK wrote: > As monitors are getting bigger, is there a general change in opinion on > the 79 chars limit in source files? I've experimented with 98 characters > per line and I find it quite a bit more comfortable to work with that > length, even though sometimes I have to edit files in 80 width > terminals, it's still easier to adapt to some inconvenience when that > happens than the other way around, since about 95% of time or more, I do > use wider editor window or terminal. > > Is going over 79 still a terrible thing to do? -andrei If the the limit isn't 79, then what is it? Or are 1000-column lines okay? Often, simply having a convention is more important than the precise details. E.g. I don't particularly care how I configure my text editor's auto-formatting settings, but I do care about not having to change those settings for each file. For code which will never be read or edited by anyone other than yourself, use whatever conventions you want. If you're going to publish the code, it's a good idea to stick to established standards (80-column lines, 8-column tabs, no gratuitous use of non-ASCII characters, etc). Apart from "altruistic" reasons, bear in mind that the next time you apply for a job, the employer may look at your code not just to determine your programming competence, but also whether you're likely to be a "team player". Code which doesn't follow normal conventions says "I've only ever worked on my own, not with other people". I can't stress enough how big a factor this is. Writing code by yourself and working as part of a team are almost entirely different skills. Anyone who regularly hires programmers will be only too aware of the difference. From debatem1 at gmail.com Tue Aug 17 18:04:43 2010 From: debatem1 at gmail.com (geremy condra) Date: Tue, 17 Aug 2010 15:04:43 -0700 Subject: Python "why" questions In-Reply-To: <4c6a8cff$1@dnews.tpgi.com.au> References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> <4c6a8cff$1@dnews.tpgi.com.au> Message-ID: On Tue, Aug 17, 2010 at 7:59 AM, Lie Ryan wrote: > On 08/16/10 21:54, David Cournapeau wrote: >> On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing >> wrote: >>>> On Aug 7, 2010, at 9:14 PM, John Nagle wrote: >>>> >>>>> ?The languages which have real multidimensional arrays, rather >>>>> than arrays of arrays, tend to use 1-based subscripts. ?That >>>>> reflects standard practice in mathematics. >>> >>> Not always -- mathematicians use whatever starting index is >>> most convenient for the problem at hand. >> >> Yes, there are many engineering fields where index starts at 0. Partly >> for the reason you have stated concerning polynomials, especially >> since this extend to series, which are pervasive in numerical >> computing. In linear algebra, though, I remember to have always noted >> matrices indexes in the [1,n] range, not [0,n-1]. > > I'm sure some would prefer to denote it as [0, n) Count me in on that, that'd be great. Geremy Condra From abhijeet.thatte at gmail.com Tue Aug 17 18:21:38 2010 From: abhijeet.thatte at gmail.com (abhijeet thatte) Date: Tue, 17 Aug 2010 15:21:38 -0700 Subject: Need to import stuff Message-ID: Hi, I need to import few files depending on the user input. For eg if user gives an input as "abcd" then I will have * import "abcd.py".* Can not have any hard coding in the code. Does any one know how to solve the problem. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Aug 17 18:27:39 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 17 Aug 2010 18:27:39 -0400 Subject: Need to import stuff In-Reply-To: References: Message-ID: On Tue, Aug 17, 2010 at 6:21 PM, abhijeet thatte wrote: > Hi, > I need to import few files depending on the user input. For eg if user gives > an input as "abcd" then I will have??import "abcd.py". > Can not have any hard coding in the code. Does any one know how to solve the > problem. Use the __import__ function ( http://docs.python.org/library/functions.html#__import__ ), like this: user_module = __import__("abdc") user_module.do_stuff() -- Jerry From paddy3118 at googlemail.com Tue Aug 17 18:27:45 2010 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 17 Aug 2010 15:27:45 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> <2abafeea-78e6-454c-8c3d-debe888d2bc7@h40g2000pro.googlegroups.com> Message-ID: <79c11629-1092-4c6c-9fe9-4fdea65f4f33@s9g2000yqd.googlegroups.com> On Aug 17, 10:47?pm, Paddy wrote: > On 17 Aug, 02:29, Raymond Hettinger wrote: > > > > > [Paddy] > > > > Lets say you have two *sets* of integers representing two near-copies > > > of some system, then a measure of their difference could be calculated > > > as: > > > > len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 % > > > > If the two collections of integers are allowed duplicates then you > > > need a Counter/bag/multi-set type and the diff calculation I gave > > > originally. > > > Thanks for sharing your use case. > > > It's unlikely that I will add this method to the Counter API because > > the rarity of use case does not warrant the added API complexity. > > IMO, adding a method like this makes the class harder to learn, > > understand and remember. ?It doesn't seem like much of a win over > > using the existing alternatives: > > > ?* (b - c) + (c - b) > > ?* (b | c) - (b & c) > > ?* DIY using the two counters as simple dicts > > ?* writing a subclass providing additional binary operations > > > I would like to see someone post a subclass to the ASPN Cookbook that > > adds a number of interesting, though not common operations. ?Your > > symmetric_difference() method could be one. ?A dot_product() operation > > could be another. ?Elementwise arithmetic is another option (we > > already have add and subtract, but could possibly use multiply, > > divide, etc). ?Scaling operations are another possibility (multiple > > all elements by five, for example). > > > The Counter() class has low aspirations. ?It is a dictionary that > > fills-in missing values with zero and is augmented by a handful of > > basic methods for managing the counts. > > > Raymond > > I created this that could be an addition to the bottom of the Python 3 > collections.Counter class definition: > > ? ? def __xor__(self, other): > ? ? ? ? ''' symmetric difference: Subtract count, but keep only abs > results with non-zero counts. > > ? ? ? ? >>> Counter('abbbc') ^ Counter('bccd') > ? ? ? ? Counter({'b': 2, 'a': 1, 'c': 1, 'd': 1}) > ? ? ? ? >>> a, b = Counter('abbbc'), Counter('bccd') > ? ? ? ? >>> (a-b) + (b - a) == a ^ b > ? ? ? ? True > > ? ? ? ? ''' > ? ? ? ? if not isinstance(other, Counter): > ? ? ? ? ? ? return NotImplemented > ? ? ? ? result = Counter() > ? ? ? ? for elem in set(self) | set(other): > ? ? ? ? ? ? newcount = self[elem] - other[elem] > ? ? ? ? ? ? if newcount != 0: > ? ? ? ? ? ? ? ? result[elem] = newcount if newcount > 0 else -newcount > ? ? ? ? return result > > - Paddy. And heres the cartesian product/multiply: def __mul__(self, other): '''Multiply counts by an integer; or cartesioan product of two counters. >>> Counter('abbb') * 3 Counter({'b': 9, 'a': 3}) >>> Counter('12') * Counter('21') Counter({('2', '1'): 1, ('1', '2'): 1, ('1', '1'): 1, ('2', '2'): 1}) >>> Counter('122') * Counter('211') Counter({('2', '1'): 4, ('1', '1'): 2, ('2', '2'): 2, ('1', '2'): 1}) ''' if isinstance(other, int): return Counter(**dict((k, v*other) for k,v in self.items())) elif isinstance(other, Counter): return Counter( (x, y) for x in self.elements() for y in other.elements() ) else: return NotImplemented (Although I don't have a use case for this one). - Paddy. From abhijeet.thatte at gmail.com Tue Aug 17 18:40:28 2010 From: abhijeet.thatte at gmail.com (abhijeet thatte) Date: Tue, 17 Aug 2010 15:40:28 -0700 Subject: Fwd: Need to import stuff In-Reply-To: References: Message-ID: Hi, Thanks for the reply. But I guess it does not support nested file paths. If user gives 'abcd' then I need to import "*/Do/Stuff/abcd*". Out of which only *"abcd" is taken run time. Do and Stuff are fixed. * *I got an error "*ImportError: Import by filename is not supported.". Any solution?? On Tue, Aug 17, 2010 at 3:27 PM, Jerry Hill wrote: > On Tue, Aug 17, 2010 at 6:21 PM, abhijeet thatte > wrote: > > Hi, > > I need to import few files depending on the user input. For eg if user > gives > > an input as "abcd" then I will have import "abcd.py". > > Can not have any hard coding in the code. Does any one know how to solve > the > > problem. > > Use the __import__ function ( > http://docs.python.org/library/functions.html#__import__ ), like this: > > user_module = __import__("abdc") > user_module.do_stuff() > > -- > Jerry > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at googlemail.com Tue Aug 17 18:46:17 2010 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 17 Aug 2010 15:46:17 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> <2abafeea-78e6-454c-8c3d-debe888d2bc7@h40g2000pro.googlegroups.com> Message-ID: <37830391-3813-4591-bbcb-91038bf6f432@5g2000yqz.googlegroups.com> On Aug 17, 2:29?am, Raymond Hettinger wrote: > I would like to see someone post a subclass to the ASPN Cookbook that > adds a number of interesting, though not common operations. ?Your > symmetric_difference() method could be one. ?A dot_product() operation > could be another. ?Elementwise arithmetic is another option (we > already have add and subtract, but could possibly use multiply, > divide, etc). ?Scaling operations are another possibility (multiple > all elements by five, for example). > > > Raymond Sample code is at http://code.activestate.com/recipes/577362-extension-to-python-3-counter-class/ From rodrick.brown at gmail.com Tue Aug 17 19:49:28 2010 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Tue, 17 Aug 2010 19:49:28 -0400 Subject: 0 length field in time string References: <61ACDB22F695024F87600CD2255B3F6B6307FC8C5D@NYWEXMBX2127.msad.ms.com> Message-ID: Anyone know why I'm getting the following error when trying to parse the following string is there a better method to use? #57=2010081708240065 - sample string passed to fmt_datetime def fmt_datetime(tag57): tag57 = tag57[3:len(tag57)] year = int ( tag57[0:4] ) mon = int ( tag57[4:6] ) day = int ( tag57[6:8]) hour = int ( tag57[8:10] ) min = int ( tag57[10:12] ) sec = int ( tag57[12:14] ) msec = int ( tag57[14:16] ) dt = datetime.datetime(year,mon,day,hour,min,sec) return '{:%Y-%m-%d %H:%M:%S}'.format(dt) File "./delta_delay.py", line 27, in fmt_datetime return '{:%Y-%m-%d %H:%M:%S}'.format(dt) ValueError: zero length field name in format -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 17 20:12:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 01:12:52 +0100 Subject: 0 length field in time string In-Reply-To: References: <61ACDB22F695024F87600CD2255B3F6B6307FC8C5D@NYWEXMBX2127.msad.ms.com> Message-ID: <4C6B2584.1060602@mrabarnett.plus.com> Rodrick Brown wrote: > Anyone know why I'm getting the following error when trying to parse the > following string is there a better method to use? > > #57=2010081708240065 - sample string passed to fmt_datetime > > def fmt_datetime(tag57): > tag57 = tag57[3:len(tag57)] > year = int ( tag57[0:4] ) > mon = int ( tag57[4:6] ) > day = int ( tag57[6:8]) > hour = int ( tag57[8:10] ) > min = int ( tag57[10:12>] ) > sec = int ( tag57[12:14>] ) > msec = int ( tag57[14:16] ) > You could use: dt = datetime.datetime.strptime(tag57[3 : 17], "%Y%m%d%H%M%S") > dt = datetime.datetime(year,mon,day,hour,min,sec) > return '{:%Y-%m-%d %H:%M:%S}'.format(dt) > > File "./delta_delay.py", line 27, in fmt_datetime > return '{:%Y-%m-%d %H:%M:%S}'.format(dt) > ValueError: zero length field name in format > You haven't supplied an argument name or position (required in Python 2.6): return '{0:%Y-%m-%d %H:%M:%S}'.format(dt) From marduk at letterboxes.org Tue Aug 17 20:14:29 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 17 Aug 2010 20:14:29 -0400 Subject: subprocess.Popen calling httpd reload never finishes In-Reply-To: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> References: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Message-ID: <1282090469.456104.35.camel@paska> On Tue, 2010-08-17 at 12:55 -0700, Nan wrote: > Hi folks -- > > I have a Python script running under Apache/mod_wsgi that needs to > reload Apache configs as part of its operation. The script continues > to execute after the subprocess.Popen call. The communicate() method > returns the correct text ("Reloading httpd: [ OK ]"), and I get a > returncode of 0. But the python script (Django) that calls Popen > never seems to complete (by returning an HTTP response. > > Any other Popen call I've tried exits properly. Here's some sample > code: > > args = ['sudo /etc/init.d/httpd reload'] > proc = subprocess.Popen(args, stdin=subprocess.PIPE, > stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, > close_fds=True) > (stdout_txt, stderr_txt) = proc.communicate("") > proc.wait() > logging.debug('%d %s
%s' % (proc.returncode, stdout_txt, > stderr_txt)) > logging.debug('still executing') > return HttpResponse('done') > > The logging statements are output, but the script doesn't exit. If > you substitute "sudo ls -l" or "sudo /etc/init.d/httpd configtest" for > "sudo /etc/init.d/httpd reload", the exits properly. > > Any idea what I might be doing wrong? > > Thanks! Django runs inside apache. It's kinda weird to have an apache process restart itself and expect it to return to the caller. If the init script does like mine, "reload" executes "apachectl -k graceful" What that instructs apache to do is to restart, but only kill the process(es) when there are no more connections. So apache is waiting for your connection to close, but you are inside an HTTP request waiting for apache to restart. So you have a race condition here. It's not advisable to have apache kill itself and expect it to send a status back to you telling you it's dead. See the apache docs[1] for a better explanation. http://httpd.apache.org/docs/2.0/stopping.html#graceful From woooee at gmail.com Tue Aug 17 20:55:52 2010 From: woooee at gmail.com (woooee) Date: Tue, 17 Aug 2010 17:55:52 -0700 (PDT) Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> Message-ID: On Aug 16, 9:07?pm, Jah_Alarm wrote: > hi, I've already asked this question but so far the progress has been > small. > > I'm running Tkinter. I have some elements on the screen (Labels, most > importantly) which content has to be updated every iteration of the > algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm > using the update_idletasks() command in the function itself after the > variable.set(...) command. The variable type is IntVar(), and the > mistake I'm getting is 'IntVar instance has no attribute > 'update_idletasks'. No updates are displayed, of course. > > Without the GUI the algorithm (it's a genetic algorithm) is working > fine, but I need to make it available to other people via GUI > > cheers, > > Alex This program I had lying around and it will hopefully make things clearer. The integer under the second label (i.e. the 3rd label) increases by on every time you click the "Print Contents" button. The variable associated with the second label and the entry box update as you change the entry box's contents, all with no calls to update_idletasks(). class EntryTest: """ shows using the same StringVar in the second list box and in the entry box """ def __init__(self): self.top = Tkinter.Tk() self.top.title("Test of Entry") self.top.geometry("200x150+10+10") self.str_1 = Tkinter.StringVar() label_lit = Tkinter.StringVar() self.int_lit = Tkinter.IntVar() label_1 = Tkinter.Label(self.top, textvariable = label_lit ) label_1.pack() label_lit.set( "Test of Label") label_2 = Tkinter.Label(self.top, textvariable = self.str_1 ) label_2.pack() label_3 = Tkinter.Label(self.top, textvariable = self.int_lit ) label_3.pack() self.int_lit.set(0) entry_1 = Tkinter.Entry(self.top, textvariable=self.str_1) entry_1.pack() self.str_1.set( "Entry Initial Value" ) print_button = Tkinter.Button(self.top, text='PRINT CONTENTS', command=self.getit, bg='blue', fg='white' ) print_button.pack(fill=Tkinter.X, expand=1) exit_button= Tkinter.Button(self.top, text='EXIT', command=self.top.quit, bg='red', fg='white' ) exit_button.pack(fill=Tkinter.X, expand=1) entry_1.focus_set() self.top.mainloop() ##----------------------------------------------------------------- def getit(self) : print "getit: variable passed =", self.str_1.get() x = self.int_lit.get() self.int_lit.set(x+1) ##=============================================================== if "__main__" == __name__ : ET=EntryTest() print "under __main__ =", ET.str_1.get() From steve.ferg.bitbucket at gmail.com Tue Aug 17 21:20:41 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Tue, 17 Aug 2010 18:20:41 -0700 (PDT) Subject: question about pdb assignment statements References: Message-ID: Thanks mucho!! From john.passaniti at gmail.com Tue Aug 17 21:38:39 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Tue, 17 Aug 2010 18:38:39 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On Aug 17, 4:19?pm, Standish P wrote: > > > It is true that the other languages such as F/PS also have borrowed > > > lists from lisp in the name of nested-dictionaries and mathematica > > > calls them nested-tables as its fundamental data structure. > > > No. > > you are contradicting an earlier poster from forth who admitted the > part on dicts. Then they are wrong. You asked if Forth "borrowed" lists from Lisp. It did not. In Lisp, lists are constructed with pair of pointers called a "cons cell". That is the most primitive component that makes up a list. Forth has no such thing; in Forth, the dictionary (which is traditionally, but not necessarily a list) is a data structure that links to the previous word with a pointer. This is in fact one of the nice things about Lisp; because all lists are created out of the same primitive cons cell, you can consistently process any list in the system. In Forth, any lists (such as the dictionary, if it is a list) are specific to their purpose and have to be treated individually. I don't know what you mean by "nested-dictionaries." There is no such thing in Forth. Dictionaries don't nest. You can create wordlists, but each wordlist is flat. When most people think of a nested dictionary, they would think of a structure that would allow any arbitrary level of nesting, not a string of flat wordlists. > > > The whole case of OOP is the clustering of thought, ie book-keeping, > > > in the mind of the programmer around fewer objects than ten or twenty > > > fold functions. > > > That's one view of OOP. ?It's not the only one. > > and what can you add to enlighten the readers on the other view ? How one views OOP depends on the language and implementation. Your statement about having fewer than "ten or twenty fold" functions is completely arbitrary and is more a matter of style and skill in decomposition than an intrinsic quality about objects. The poetic "clustering of thought" is vague but a I guess could be an informal notion of the bundling of related state and methods. And referring to it as "book-keeping" suggests some kind of static relationship between state and methods, although that is not the case in architectures that stress dynamic relationships. Many people only know OOP through static, class-based models (such as in languages like C++). But there are other models. Objects can also be represented not with classes but by cloning existing objects and then mutating them as needed. Objects can also be represented with a functional interface using a closure around an environment. In such cases, objects may be far more fluid than in static class-based models, and shift over time into different roles. In such systems, "book-keeping" isn't static. Or put another way, the language and implementation drive the flavor that a particular object has. > > You, like probably everyone else who has thought about how to > > "simplify" languages will eventually end up at the same place-- you'll > > have a model that meets your objectives, but with some programmers > > will find is unnecessarily limiting. ?More importantly, you'll run > > into some classes of problems for which your simple model makes things > > inordinately complicated relative to what other languages and > > paradigms offer. > > The objective is to discuss those cases via specific examples (not > generalities), and talk ABOUT them, not AROUND them. I'd be happy to discuss specific examples, but your understanding of Forth is flawed, and until you learn more about Forth, I don't think it would be helpful. And actually, I did provide a specific example. You apparently didn't understand it, so let me be more explicit. Here is a function in Scheme: (define (hello name) (lambda () (begin (display "Hello ") (display name)))) This defines a function that returns another function. You can think of this as a constructor for a light-weight object that has one value ("name") and one default method (to print "Hello "). The function that is returned can be stored, passed around, and otherwise out-live the invocation of this function. For example: (define example (hello "John")) In your stack mindset, the value "John" would disappear after the call to "hello". But in Scheme, the value lives on, as it is part of the closure captured at the time the function was created. A stack mindset would not allow this. And this would eliminate the vast majority of functional programming from your language's abilities. Maybe you don't care, or maybe you still don't see the value in this. In that case, I suggest you learn the language and then think about what your stack mindset prevents. > > Here's a better idea: ? > > Its a very fine wild goose chase project statement. No, it is a vivid example of what you don't know-- and what you don't know is what will limit you later. From russ.paielli at gmail.com Tue Aug 17 22:15:54 2010 From: russ.paielli at gmail.com (Russ P.) Date: Tue, 17 Aug 2010 19:15:54 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> On Aug 7, 5:54?am, "D'Arcy J.M. Cain" wrote: > Would said beginner also be surprised that a newborn baby is zero years > old or would it be more natural to call them a one year old? ?Zero > based counting is perfectly natural. You're confusing continuous and discrete variables. Time is a continuous variable, but a list index is discrete. Take a look at any numbered list, such as the top ten football teams or the top ten software companies. Have you ever seen such a list start with zero? If so, where? I sure haven't. When I studied linear algebra way back, vector and matrix indices also always started with one, and I assume they still do. The convention of starting with zero may have had some slight performance advantage in the early days of computing, but the huge potential for error that it introduced made it a poor choice in the long run, at least for high-level languages. From nikos.the.gr33k at gmail.com Tue Aug 17 23:15:24 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Tue, 17 Aug 2010 20:15:24 -0700 (PDT) Subject: String substitution VS proper mysql escaping Message-ID: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> =============================== cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) =============================== Someone told me NOT to do string substitution ("%") on SQL statements and to let MySQLdb do it for me, with proper escaping like the following =============================== cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s ORDER BY date DESC''', (page,)) =============================== The difference is that if some external source can control "page", and they put in a value like 100 ; DELETE FROM visitors; SELECT * FROM visitors i will be losing my database table data. a) I wanted to ask what is proper escaping mean and why after variable page syntax has a comma and as i have the script now why don't my code as i have it now for string reproduction =============================== http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors " =============================== don't reproduce the problem of actual deleting my data. I don't care losing it! I just want to see that happening with my own eyes! From dan.kluev at gmail.com Wed Aug 18 00:26:32 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Wed, 18 Aug 2010 15:26:32 +1100 Subject: String substitution VS proper mysql escaping In-Reply-To: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> References: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> Message-ID: 2010/8/18 ????? > a) I wanted to ask what is proper escaping mean and > > Proper escaping means that value is wrapped in quotes properly, and quotes and backslashes (or any other special to RDBMS symbol) are escaped with backslashes. why after variable page syntax has a comma > Comma just means its tuple. (page) is equal to page, while (page,) is one-element tuple which contains page: >>> ('123') '123' >>> ('123',) ('123',) > why don't my code as i have it now for string reproduction > > =============================== > http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT > * FROM visitors " > =============================== > > don't reproduce the problem of actual deleting my data. I don't care > losing it! > > I just want to see that happening with my own eyes! > > Your script there just throws an exception for any page data, and most likely does not run any query at all: > 28 # open current html template and get the page ID number > 29 # > ================================================================================================================= > 30 f = open( '/home/webville/public_html/' + page ) > 31 > 32 # read first line of the file > f undefined, builtin open = , page = ['index.html', '100'] > TypeError: cannot concatenate 'str' and 'list' objects > Besides, using user-provided data and just concatenating it to filename like that is definitely bad idea. You should use os.path.join() at least. Regarding that kind of SQL injection, typically driver will stop it to happen when you provide 2 queries at once delimited by ';', so drop table would not work. However its possible to issue UNION's to retrieve sensitive data from your database. -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Wed Aug 18 00:31:22 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 18 Aug 2010 14:31:22 +1000 Subject: String substitution VS proper mysql escaping In-Reply-To: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> References: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> Message-ID: <20100818043122.GA27336@cskk.homeip.net> On 17Aug2010 20:15, ????? wrote: | =============================== | cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = | '%s' ORDER BY date DESC ''' % (page) ) | =============================== | | Someone told me NOT to do string substitution ("%") on SQL statements | and to let MySQLdb do it | for me, with proper escaping like the following | | =============================== | cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s | ORDER BY date DESC''', (page,)) | =============================== | | The difference is that if some external source can control "page", | and | they put in a value like | 100 ; DELETE FROM visitors; SELECT * FROM visitors | i will be losing my database table data. That other difference is that the mysql dialect support knows how to correctly escape a string for insertion into an SQL statement. You may not, or may forget to pre-escape the string, etc. Using the MySQLdb stuff do it for you is reliable and robust. | a) I wanted to ask what is proper escaping mean and why after variable | page syntax has a comma Because this: (page) means the same thing as: page i.e. the argument to the "%" operator is just the string in page. This: (page,) is a _tuple_ containing a single element, the page variable. A bit like: [page] which is a list containing a single element. The trailing comma is needed to tell python you want to use a tuple, not the bare string. The "%" operator has special knowledge that is it is passed as string instead of a list or tuple or other sequence then it should act _as_ _if_ it had been passed a single element tuple containing the string. Otherwise, because a string _is_ a sequence the "%" might want to treat the string "foo" as the sequence: ("f", "o", "o") Run these three loops to see the difference: for s in "foo": print s for s in ("foo"): print s for s in ("foo",): print s Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ I couldn't think of anything else to do with it, so I put it on the web. From dan.kluev at gmail.com Wed Aug 18 00:39:06 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Wed, 18 Aug 2010 15:39:06 +1100 Subject: Need to import stuff In-Reply-To: References: Message-ID: On Wed, Aug 18, 2010 at 9:40 AM, abhijeet thatte wrote: > Hi, > > Thanks for the reply. But I guess it does not support nested file paths. > If user gives 'abcd' then I need to import "*/Do/Stuff/abcd*". Out of > which only *"abcd" is taken run time. Do and Stuff are fixed. * > *I got an error "*ImportError: Import by filename is not supported.". Any > solution?? > > For complex importing, you can use imp module, http://docs.python.org/library/imp.html Like this: module_desc = imp.find_module(name, [base_path]) module = imp.load_module(full_name, *module_desc) -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From bidda.gowda at gmail.com Wed Aug 18 03:19:31 2010 From: bidda.gowda at gmail.com (Bidda Gowda) Date: Wed, 18 Aug 2010 12:49:31 +0530 Subject: Call Java Code from python Message-ID: Hi, I have a project coming up where i have to integrate our existing Python based web application with Java Programs. Basically i should be able to call Java programs which comes in the form of jars. Whats the best way to call these jars from python ? I looked at jpype and tried with small program and it works. Are there any other tools which can do the same or if any how are they compared to jpype ? -- B Gowda. From nagle at animats.com Wed Aug 18 03:29:41 2010 From: nagle at animats.com (John Nagle) Date: Wed, 18 Aug 2010 00:29:41 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <89467860-45ac-4a3b-ac17-f11a19429187@i13g2000yqd.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <7zaaolzm89.fsf@ask.diku.dk> <89467860-45ac-4a3b-ac17-f11a19429187@i13g2000yqd.googlegroups.com> Message-ID: <4c6b8be3$0$1588$742ec2ed@news.sonic.net> On 8/17/2010 11:20 AM, Standish P wrote: > On Aug 17, 1:17 am, torb... at diku.dk (Torben ?gidius Mogensen) wrote: >> Standish P writes: >>> [Q] How far can stack [LIFO] solve do automatic garbage collection and >>> prevent memory leak ? >> >>> Because a stack has push and pop, it is able to release and allocate >>> memory. We envisage an exogenous stack which has malloc() associated >>> with a push and free() associated with a pop. >> >> See > > How many programmers have applied the ideas of these papers in their > programming practice ? I paste the abstract for convenience > >> http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 > > Abstract: > This paper describes a memory management discipline for programs that > perform dynamic memory allocation and de-allocation. At runtime, all > values are put into regions. The store consists of a stack of regions. > All points of region allocation and deallocation are inferred > automatically, using a type and effect based program analysis. The > scheme does not assume the presence of a garbage collector. That's actually an interesting idea. If you can figure out object lifetimes at compile time, allocation can be made far more efficient. One of the basic questions is whether a function will ever "keep" an object. That is, will the function ever keep a reference to an object that outlives the return from the function? In many cases, one can easily determine at compile time that a function will never keep a passed object. In such a case, you don't have to do reference count updates on the object. Most math functions have this property, even vector and matrix math functions - they have no persistent state. Python could use a bit of this. If a function argument can be identified as "non-kept", then the function doesn't need to do reference count updates on it. If a local variable in a function is used only by "non-keep" functions and operations, it can be created on the stack and released cheaply at block exit. One can go much further in lifetime inference than this, as the papers demonstrate. There's a big win in the simple optimization of identifying "non-keep" parameters, especially in mathematical work where they're very common. It's not clear that getting fancier than that is a win. Does Shed Skin have this optimization? It should. John Nagle From torbenm at diku.dk Wed Aug 18 03:39:12 2010 From: torbenm at diku.dk (Torben Ægidius Mogensen) Date: Wed, 18 Aug 2010 09:39:12 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <7zaaolzm89.fsf@ask.diku.dk> <89467860-45ac-4a3b-ac17-f11a19429187@i13g2000yqd.googlegroups.com> Message-ID: <7zk4noe5en.fsf@ask.diku.dk> Standish P writes: > On Aug 17, 1:17?am, torb... at diku.dk (Torben ?gidius Mogensen) wrote: >> Standish P writes: >> > [Q] How far can stack [LIFO] solve do automatic garbage collection and >> > prevent memory leak ? >> >> See > >> http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 >> http://portal.acm.org/citation.cfm?doid=174675.177855 >> http://www.springerlink.com/content/m2074884n6gt612h/ >> ? ? ? ? Torben > How many programmers have applied the ideas of these papers in their > programming practice ? The method was built into a SML compiler which was used (among other things) to build a web server, which was used (among other things) to make the web pages and course administrative system at the IT University of Copenhagen, Denmark. Good enough for you? Torben From sschwarzer at sschwarzer.net Wed Aug 18 03:44:14 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 18 Aug 2010 09:44:14 +0200 Subject: Call Java Code from python In-Reply-To: References: Message-ID: <4C6B8F4E.90503@sschwarzer.net> Hi Bidda, On 2010-08-18 09:19, Bidda Gowda wrote: > I have a project coming up where i have to integrate our existing > Python based web application with Java Programs. Basically i should be > able to call Java programs which comes in the form of jars. Whats the > best way to call these jars from python ? > > I looked at jpype and tried with small program and it works. Are there > any other tools which can do the same or if any how are they compared > to jpype ? Here are some slides from a talk by Andreas Schreiber, "Mixing Python and Java", which might help: http://www.slideshare.net/onyame/mixing-python-and-java Personally, I've used JCC for accessing Lucene (a search engine framework implemented in Java). It was a bit rough in some places, but overall quite usable. Stefan From andresen.nils at googlemail.com Wed Aug 18 04:09:38 2010 From: andresen.nils at googlemail.com (Nils) Date: Wed, 18 Aug 2010 01:09:38 -0700 (PDT) Subject: use of gtk in a nautilus extension Message-ID: <0408bd91-a578-400a-82ab-2329e129faef@j8g2000yqd.googlegroups.com> Hi, I am having some trouble opening a simple message/dialog to the user from a natilus extension.. I have written a simple nautilus extension using python. It adds one MenuItem to the context menu. for testing I wanted to open a simple dialog when the user clicks this menuitem. (The code can be found - with some nice formatting here: http://stackoverflow.com/questions/3325772/use-gtk-in-a-nautilus-extension-using-python) The code is as follows: --- cut --- import gtk import nautilus import os def alert(message): """A function to debug""" dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, message) dialog.run() dialog.destroy() class TestExtension(nautilus.MenuProvider): def __init__(self): pass def get_file_items(self, window, files): items = [] """Called when the user selects a file in Nautilus.""" item = nautilus.MenuItem("NautilusPython::test_item", "Test", "Test") item.connect("activate", self.menu_activate_cb, files) items.append(item) return items def menu_activate_cb(self, menu, files): """Called when the user selects the menu.""" for name in files: alert(name) --- cut --- When I click on the menuitem nothing happens... But when I replace def alert(message) like this: def alert(message): """A function to debug""" easygui.msgbox(message) and obviously drop import gtk and add import easygui, The dialog does appear. Can someone tell me why this is ?? Yours, Nils From ldo at geek-central.gen.new_zealand Wed Aug 18 04:16:33 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 18 Aug 2010 20:16:33 +1200 Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> Message-ID: In message , Martin Gregorie wrote: > 1) ssh terminal windows generally come up as 24 x 80 My terminal windows come up by default at something like 40 lines by 100 characters. > 2) at 24 x 80 I can get more ssh terminal windows on the desktop with > minimal overlap than I can do with longer/wider windows. I have 8 terminal windows open at once, they all fit fine, with room for an Emacs window and whatever else I might occasionally squeeze into there. Hint: I use tabs as well as windows. From nick_keighley_nospam at hotmail.com Wed Aug 18 04:39:09 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Wed, 18 Aug 2010 01:39:09 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> Message-ID: <518b97c6-78ad-4ce9-9967-c7f72ea74109@5g2000yqz.googlegroups.com> On 17 Aug, 18:34, Standish P wrote: > On Aug 16, 11:09?am, Elizabeth D Rather wrote: > > On 8/15/10 10:33 PM, Standish P wrote: > > > >>> If Forth is a general processing language based on stack, is it > > >>> possible to convert any and all algorithms to stack based ones and > > >>> thus avoid memory leaks since a pop automatically releases memory when > > >>> free is an intrinsic part of it. > > > Forth uses two stacks. ?The "data stack" is used for passing parameters > > between subroutines ("words") and is completely under the control of the > > programmer. ?Words expect parameters on this stack; they remove them, > > and leave only explicit results. ?The "return stack" is used primarily > > for return addresses when words are called, although it is also > > available for auxiliary uses under guidelines which respect the primary > > use for return addresses. > > > Although implementations vary, in most Forths stacks grow from a fixed > > point (one for each stack) into otherwise-unused memory. ?The space > > involved is allocated when the program is launched, and is not managed > > as a heap and allocated or deallocated by any complicated mechanism. ?On > > multitasking Forth systems, each task has its own stacks. ?Where > > floating point is implemented (Forth's native arithmetic is > > integer-based), there is usually a separate stack for floats, to take > > advantage of hardware FP stacks. > > > >> ? ? - is forth a general purpose language? Yes > > >> ? ? - are all algorithms stack based? No > > > > Does Forth uses stack for all algorithms ? Does it use pointers , ie > > > indirect addressing ? If it can/must use stack then every algorithm > > > could be made stack based. > > > Forth uses its data stack for parameter passing and storage of temporary > > values. ?It is also possible to define variables, strings, and arrays in > > memory, in which case their addresses may be passed on the data stack. > > > Forth is architecturally very simple. ?Memory allocations for variables, > > etc., are normally static, although some implementations include > > facilities for heaps as needed by applications. > > although some implementations include facilities for heaps as needed by applications. > > How are these heaps being implemented ? Is there some illustrative > code or a book showing how to implement these heaps in C for example ? any book of algorithms I'd have thought http://en.wikipedia.org/wiki/Dynamic_memory_allocation http://www.flounder.com/inside_storage_allocation.htm I've no idea how good either of these is > Are dictionaries of forth and postscript themselves stacks if we > consider them as nested two column tables which lisp's lists are in > essence, but only single row. Multiple rows would just be multiple > instances of it at the same level inside parens. I can't make much sense of that. But you seem to see Lisp data structures in all sorts of strange places. I don't see that Lisp lists are "nested two column tables" > we can peek into stacks which is like car. no. > if it is not unusually > costly computation, why not allow it ? there is no need to restrict to > push and pop. some stacks have a top() operation. > roll( stack_name, num) > > itself can give all those postfix permutations that push and pop cant > generate with a single stack. Can we use dictionaries to generate > multiple stacks inside one global stack ? I've no idea what you on about From landimatte at gmail.com Wed Aug 18 04:54:43 2010 From: landimatte at gmail.com (Matteo Landi) Date: Wed, 18 Aug 2010 10:54:43 +0200 Subject: Python Developer - HFT Trading firm - Chicago, IL In-Reply-To: References: Message-ID: Hi Rich, I think it's better for you to post the message here ( http://www.python.org/community/jobs/ ). Regards, On Tue, Aug 17, 2010 at 6:07 PM, Rich Moss wrote: > > Python developer needed for math/trading applications and research at > leading HFT firm. The person we are searching for will have a strong > background with python programming and the ability to work with very > large historical datasets. You should have a very strong math > background as well. This can involve writing very complicated python > scripts and programs! You will work very closely with traders and > quantitative analysts in their equities trading group on state-of-the- > art trading strategy and execution systems. > > Requires: > > Strong python programming experience developing applications and > scripts using complex regular expressions > > Strong math knowledge and education > Experience working with massive datatsets/historical data > > This company is a top-tier electronic, algorithmic trading firm, > located in Chicago, IL. This firm is one of the most advanced high > frequency electronic trading firms in the world and uses python > throughout the company, as well as other languages. This firm has a > culture that rewards creativity and hard work. No third parties, > please. We will not consider candidates from outside the USA. No > telecommuting. We offer very generous compensation (best in the > industry), fantastic benefits and very generous relocation packages. > Please contact me immediately with a resume! > > Send resumes to: > > Rich Moss > rich at mossltd.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From jeanmichel at sequans.com Wed Aug 18 04:57:00 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 18 Aug 2010 10:57:00 +0200 Subject: 79 chars or more? In-Reply-To: <20100817114256.d960549b.darcy@druid.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <20100817114256.d960549b.darcy@druid.net> Message-ID: <4C6BA05C.2000906@sequans.com> D'Arcy J.M. Cain wrote: > On Tue, 17 Aug 2010 16:28:02 +0200 > Stefan Schwarzer wrote: > >> I'd probably reformat this to >> >> self.expiration_date = translate_date( >> find(response, 'MPNExpirationDate').text, >> '%Y-%m-%d', '%m%d%Y') >> >> or even >> >> self.expiration_date = translate_date( >> find(response, 'MPNExpirationDate').text, >> '%Y-%m-%d', >> '%m%d%Y') >> > > You can extend this if there are complicated sub-calls. Probably > overkill for this example but here is the idea. > > self.expiration_date = translate_date( > find( > response, > 'MPNExpirationDate', > ).text, > '%Y-%m-%d', > '%m%d%Y' > ) > > I also moved the closing brace down to align with the line that opened > that block. > > If this is supposed to convice 80+ chars users, that's an epic failure :) This is exactly the kind of layout I'm happy to not use by not caring about the line width. At least, if you still want to stick with 79 chars, do something like text = find(response, 'MPNExpirationDate', ).text self.expiration_date = translate_date(text,'%Y-%m-%d', '%m%d%Y') JM From nick_keighley_nospam at hotmail.com Wed Aug 18 05:02:01 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Wed, 18 Aug 2010 02:02:01 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: <19ff939d-6cc0-4b27-b0a2-85406967434d@l6g2000yqb.googlegroups.com> On 17 Aug, 21:37, Elizabeth D Rather wrote: > On 8/17/10 10:19 AM, Standish P wrote > > On Aug 17, 12:32 pm, John Passaniti ?wrote: > >>> It is true that the other languages such as F/PS also have borrowed > >>> lists from lisp in the name of nested-dictionaries and mathematica > >>> calls them nested-tables as its fundamental data structure. > > >> No. > > > you are contradicting an earlier poster from forth who admitted the > > part on dicts. he's saying a forth dictionary isn't a lisp s-exp. Well it isn't. > Not at all. ?A Forth dictionary is a simple linked list, not the > complicated kind of nested structures you're referring to. ?You really > seem addicted to very complex structures. I thought he had the opposite problem! I thought it was trying to knock in all his programming nails with same stack-based hammer. > ?They really aren't necessary for general programming. whaever *that* is From nikos.the.gr33k at gmail.com Wed Aug 18 05:07:16 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Wed, 18 Aug 2010 12:07:16 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <20100818043122.GA27336@cskk.homeip.net> References: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> <20100818043122.GA27336@cskk.homeip.net> Message-ID: <4C6BA2C4.4000309@gmail.com> ???? 18/8/2010 7:31 ??, ?/? Cameron Simpson ??????: > On 17Aug2010 20:15, ????? wrote: > | =============================== > | cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = > | '%s' ORDER BY date DESC ''' % (page) ) > | =============================== > | > | Someone told me NOT to do string substitution ("%") on SQL statements > | and to let MySQLdb do it > | for me, with proper escaping like the following > | > | =============================== > | cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s > | ORDER BY date DESC''', (page,)) > | =============================== > | > | The difference is that if some external source can control "page", > | and > | they put in a value like > | 100 ; DELETE FROM visitors; SELECT * FROM visitors > | i will be losing my database table data. > > That other difference is that the mysql dialect support knows how to > correctly escape a string for insertion into an SQL statement. You may > not, or may forget to pre-escape the string, etc. Using the MySQLdb > stuff do it for you is reliable and robust. Can you please tell me what escaping means by giving me an example of what is escaped and whats isn't? Also hwo can i delete my data for testing purposes as? http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors" I get an error... > | a) I wanted to ask what is proper escaping mean and why after variable > | page syntax has a comma > > Because this: > > (page) > > means the same thing as: > > page > > i.e. the argument to the "%" operator is just the string in page. > > This: > > (page,) > > is a _tuple_ containing a single element, the page variable. > A bit like: > > [page] > > which is a list containing a single element. The trailing comma is > needed to tell python you want to use a tuple, not the bare string. > > The "%" operator has special knowledge that is it is passed as string instead > of a list or tuple or other sequence then it should act _as_ _if_ it had been > passed a single element tuple containing the string. > %s and %d is behaving the same due to % expecting a string instead of an integer? > Otherwise, because a string _is_ a sequence the "%" might want to treat > the string "foo" as the sequence: > > ("f", "o", "o") cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s ORDER BY date DESC''', page) But it alss might treat it an entity, i mean since 'page' is a variable containing a string why not just 'page' as it is expecting 'page' variable to give its value when asked? > Run these three loops to see the difference: > > for s in "foo": > print s > for s in ("foo"): > print s > for s in ("foo",): > print s > > Cheers, >>> for s in "nikos": print s n i k o s # this handles the string "nikos" as a series of chars right? >>> for s in ("nikos"): print s n i k o s # this handles the string "nikos" as a series of chars too but what si the difference with the above in htis with the parentheses? is "nikos" is handles still as string here? >>> for s in ("nikos",): print s nikos # Here yes it handles "nikos" as the 1st item of a tuple nikos >>> for s in ["nikos"]: print s nikos # Here? why is it behaving fifferent than the above ("nikos") and is proccessign it all chars in one? >>> for s in ["nikos",]: print s nikos # Here it handles "nikos" as the 1st item of a list right? From sschwarzer at sschwarzer.net Wed Aug 18 05:11:09 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 18 Aug 2010 11:11:09 +0200 Subject: 79 chars or more? In-Reply-To: <4c6b956e@dnews.tpgi.com.au> References: <4C69F585.5050504@gmail.com> <4c6b956e@dnews.tpgi.com.au> Message-ID: <4C6BA3AD.3050500@sschwarzer.net> Hi Lie, On 2010-08-18 12:02, Lie Ryan wrote: > On 08/17/10 12:59, AK wrote: >> On 08/16/2010 10:42 PM, James Mills wrote: >>> My personal opinion (despite monitors being wider) is >>> the horizontal scrolling isn't worth it. Stick to a 80-char width. >> >> But.. why horizontal scrolling, isn't autowrap much better than that? > > Do you seriously use autowrapper when writing code? I think he means wrapping on the screen, not actually inserting line breaks. Stefan From as at sci.fi Wed Aug 18 05:40:07 2010 From: as at sci.fi (Anssi Saari) Date: Wed, 18 Aug 2010 12:40:07 +0300 Subject: Working with PDFs? References: Message-ID: writes: > - Pull out text from each PDF page (to search for specific words) > - Combine separate pdf documents into one document > - Add bookmarks (with destination settings) PDF Shuffler is a Python app which does PDF merging and splitting very well. I don't think it does anything else, though, but maybe that's where your code comes in? From cs at zip.com.au Wed Aug 18 05:50:17 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 18 Aug 2010 19:50:17 +1000 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6BA2C4.4000309@gmail.com> References: <4C6BA2C4.4000309@gmail.com> Message-ID: <20100818095017.GA30475@cskk.homeip.net> On 18Aug2010 12:07, Nik Gr wrote: | ???? 18/8/2010 7:31 ??, ?/? Cameron Simpson ??????: | >On 17Aug2010 20:15, ????? wrote: | >| =============================== | >| cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = | >| '%s' ORDER BY date DESC ''' % (page) ) | >| =============================== | >| | >| Someone told me NOT to do string substitution ("%") on SQL statements | >| and to let MySQLdb do it | >| for me, with proper escaping like the following | >| | >| =============================== | >| cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s | >| ORDER BY date DESC''', (page,)) | >| =============================== | >| | >| The difference is that if some external source can control "page", | >| and | >| they put in a value like | >| 100 ; DELETE FROM visitors; SELECT * FROM visitors | >| i will be losing my database table data. | > | >That other difference is that the mysql dialect support knows how to | >correctly escape a string for insertion into an SQL statement. You may | >not, or may forget to pre-escape the string, etc. Using the MySQLdb | >stuff do it for you is reliable and robust. | | Can you please tell me what escaping means by giving me an example | of what is escaped and whats isn't? In your plain substitution example above: cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) Supposing page is the string "100". This will produce the SQL statement: SELECT host, hits, date FROM visitors WHERE page = '100' ORDER BY date DESC which looks ok. But suppose page was the string: bill o'reilly Then your SQL statement looks like this: SELECT host, hits, date FROM visitors WHERE page = 'bill o'reilly' ORDER BY date DESC To the SQL engine this looks like the string "bill o" followed by an SQL instruction named "reilly", and then the opening quote for another string. Invalid SQL. The procedure used to avoid this problem (to insert an _arbitrary_ string into the SQL statement) is to "escape" problematic characters in strings when placing them into SQL statements. In this case, the quote character in the string is the SQL "end string" character. Therefore the string must be modified in the SQL statement to be correctly expressed. IIRC, SQL uses the quote doubling convention for strings, so this: SELECT host, hits, date FROM visitors WHERE page = 'bill o''reilly' ORDER BY date DESC is how one would write the literal SQL for that. The MySQLdb library will do this and a host of other equivalent things automatically and correctly and consistently when you pass page as a parameter to the execute() method, needing no special attention or detailed syntactic knowledge on your part when you write your program. [...snip...] | >The "%" operator has special knowledge that is it is passed as string instead | >of a list or tuple or other sequence then it should act _as_ _if_ it had been | >passed a single element tuple containing the string. | > | %s and %d is behaving the same due to % expecting a string instead | of an integer? I haven't checked. I make a point of using the (page,) form (i.e. always use a tuple, even with just one argument) these days. That way there is no ambiguity. | >Otherwise, because a string _is_ a sequence the "%" might want to treat | >the string "foo" as the sequence: | > | > ("f", "o", "o") | cursor.execute('''SELECT host, hits, date FROM visitors WHERE | page=%s ORDER BY date DESC''', page) | | But it alss might treat it an entity, i mean since 'page' is a | variable containing a string why not just 'page' as it is expecting | 'page' variable to give its value when asked? A string is also a sequence of characters. | >Run these three loops to see the difference: | > | > for s in "foo": | > print s | > for s in ("foo"): | > print s | > for s in ("foo",): | > print s | > | >Cheers, | >>> for s in "nikos": | print s | | | n | i | k | o | s | | # this handles the string "nikos" as a series of chars right? Yes. | >>> for s in ("nikos"): | print s | | | n | i | k | o | s | | # this handles the string "nikos" as a series of chars too but what | si the difference with the above in htis with the parentheses? is | "nikos" is handles still as string here? It is exactly the same as the first loop. Just as: 1 + 3 is exactly the same as: (1) + (3) | >>> for s in ("nikos",): | print s | | nikos | | # Here yes it handles "nikos" as the 1st item of a tuple Yep. | >>> for s in ["nikos"]: | print s | | nikos | | # Here? why is it behaving fifferent than the above ("nikos") and is | proccessign it all chars in one? ("nikos",) is a single element tuple. ["nikos"] is a single element list. ["nikos",] is also a single element list, just written like the tuple. You don't see the ["nikos",] form very often because ["nikos"] is not ambiguous. It is only because ("nikos") gets reduced to plain "nikos" just like the arithmetic above that you see the ("nikos",) form - the comma makes it a tuple. | >>> for s in ["nikos",]: | print s | | | nikos | | # Here it handles "nikos" as the 1st item of a list right? Yes. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Everything is gone; Your life's work has been destroyed. Squeeze trigger (yes/no)? - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From lie.1296 at gmail.com Wed Aug 18 06:02:40 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 18 Aug 2010 20:02:40 +1000 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> Message-ID: <4c6b956e@dnews.tpgi.com.au> On 08/17/10 12:59, AK wrote: > On 08/16/2010 10:42 PM, James Mills wrote: >> On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: >>> As monitors are getting bigger, is there a general change in opinion on >>> the 79 chars limit in source files? I've experimented with 98 characters >>> per line and I find it quite a bit more comfortable to work with that >>> length, even though sometimes I have to edit files in 80 width >>> terminals, it's still easier to adapt to some inconvenience when that >>> happens than the other way around, since about 95% of time or more, I do >>> use wider editor window or terminal. >>> >>> Is going over 79 still a terrible thing to do? -andrei >> >> My personal opinion (despite monitors being wider) is >> the horizontal scrolling isn't worth it. Stick to a 80-char width. > > But.. why horizontal scrolling, isn't autowrap much better than that? Do you seriously use autowrapper when writing code? From spinoza1111 at yahoo.com Wed Aug 18 06:09:14 2010 From: spinoza1111 at yahoo.com (spinoza1111) Date: Wed, 18 Aug 2010 03:09:14 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> On Aug 18, 1:21?am, Standish P wrote: > > Garbage collection doesn't use a stack. It uses a "heap", which is in > > the abstract a collection of memory blocks of different lengths, > > divided into two lists, generally represented as linked lists: > > > 1. ?A list of blocks that are free and may be used to store new data > > > 2. ?A list of blocks that are in use, or haven't been freed (yet) > > Is this all that a heap is or is there more to it ? I have been > looking for simple but complete explanation of heap for a while and > not gotten to it. I think I am looking for a stack allocation on the > same pattern. In a disk, a file is fragmented in many contiguous > blocks and is accessed automatically. > > > > > > > There is no way you could do memory management of all but the most > > trivial and fixed-length data chunks using a stack. Sure, you could > > reserve thousands of bytes on the stack for an array but suppose your > > language allows arrays to grow or shrink. To keep its property of > > being adjacent, you'd have to do something horrible such as move > > unrelated data allocated later, which raises all sorts of security > > issues, doesn't it. > > A stack, or something which works like a stack (that is, a stack) is a > > necessary but not sufficient condition for a working C runtime because > > C functions can call themselves recursively, whether directly or > > indirectly. If this last condition did not obtain, each function could > > give the functions it calls some of its own memory and the called > > function could save a fixed set of non-stacked general registers in > > that area; this was in fact the practice on IBM 370 and in assembler > > language at a time when many "data processing managers" though > > recursion was a Communist plot. > > > However, data structures of variable size, or data structures that > > merely take up a lot of space, don't play nice with others on the > > stack, so, we place their address on the stack and store them in > > another place, which was named the heap, probably, as a sort of > > witticism. > > > Gilbert and Sullivan: > > > If anyone anything lacks > > He'll find it all ready in stacks > > This you might want to take this to the Forth people because they are > marketing their language as a cure for all that plagues programming > today. No, they're not. Stack based languages have seen better days and Forth (and the SL/1 language I supported with compilers at Bell-Northern Research) were last in fashion in the 1970s. Processors seldom could multitask, so it wasn't recognized that the stack could be a performance bottleneck, where stack operations cannot be pipelined or executed in parallel. John Hennessy of Stanford and MIPS made the stack must die case at ACM ASPLOS in 1987. Niklaus Wirth was also at this conference at which I was a fly on the wall, maintaining that the stack was good for reliability and verifiability of software. Forth had a snowball's chance because it forces ordinary programmers to think in Reverse Polish notation and is for the above reasons hard to pipeline, although of course it can be pipelined. > > > > > was wrong, and needs to be brought up to date: > > > You cannot do everything in a stack > > Unless you code an almighty hack > > If you're a coding Knight who says, "Neep", > > You'll probably need to implement a heap > > A pile a heap of benefits you'll reap > > If only my advice in your brain you'll keep > > And avoid memory leaks from which data doth seep > > By using a well-implemented, well structured, and well-documented > > Heap! > > > [Chorus of Sailors] > > We will to heart your advice take, and always use a heap! > > > [Soloist] > > Oh thank you do > > To this be true > > And always my sage advice do keep > > That you always need to use a heap!- Hide quoted text - > > > - Show quoted text - From bartc at freeuk.com Wed Aug 18 06:38:11 2010 From: bartc at freeuk.com (BartC) Date: Wed, 18 Aug 2010 11:38:11 +0100 Subject: 79 chars or more? In-Reply-To: References: Message-ID: "Roy Smith" wrote in message news:roy-319E47.09055017082010 at news.panix.com... > In article , > Lawrence D'Oliveiro wrote: > >> In message , AK >> wrote: >> >> > As monitors are getting bigger, is there a general change in opinion on >> > the 79 chars limit in source files? >> >> WHAT 79-character limit in source files? >> >> I currently have my Emacs windows set at 100 characters wide, and I??Tm >> thinking of going wider. >> >> Remember, the old hardcopy terminals used to produce 132-character-wide >> listings. > > Those of you who think "old hardcopy terminals" did 132 wide obviously > don't remember the ASR-33 :-) ASR33s I think might have been 72 columns wide (and punched cards had a similar restriction). However, lineprinter output was more likely to be 132 columns. -- bartc From python.list at tim.thechases.com Wed Aug 18 06:45:37 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 18 Aug 2010 05:45:37 -0500 Subject: String substitution VS proper mysql escaping In-Reply-To: <20100818095017.GA30475@cskk.homeip.net> References: <4C6BA2C4.4000309@gmail.com> <20100818095017.GA30475@cskk.homeip.net> Message-ID: <4C6BB9D1.8070806@tim.thechases.com> On 08/18/10 04:50, Cameron Simpson wrote: > ("nikos",) is a single element tuple. > ["nikos"] is a single element list. > ["nikos",] is also a single element list, just written like the tuple. > > You don't see the ["nikos",] form very often because ["nikos"] is not > ambiguous. I most frequently see/use the trailing comma in a one-item list when I expect additional items will be accrued later, so it makes my version-control diffs tidier: items = [ "nikos", ] Then a month later, I add items = [ "nikos", "cameron", ] My diff is just items = [ "nikos", + "cameron", ] which is quite easy to understand. However if my original was items = [ "nikos" ] and I later want to make it items = [ "nikos", "cameron" ] the diff then becomes items = [ - "nikos" + "nikos", + "cameron" ] which isn't nearly as easy to read & understand because I now have to notice the inter-linear differences ("did something more than the new-comma happen?"). -tkc From ldo at geek-central.gen.new_zealand Wed Aug 18 07:18:06 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 18 Aug 2010 23:18:06 +1200 Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: In message <4C6A9C72.4040708 at sschwarzer.net>, Stefan Schwarzer wrote: > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') Might I suggest (guessing at the argument keywords here) : self.expiration_date = translate_date \ ( TheText = find(response, 'MPNExpirationDate').text, ToFormat ='%Y-%m-%d', FromFormat ='%m%d%Y' ) Presumably FromFormat should be localizable, rather than hard-coded. See, that?s the kind of thing you notice when you think about the code in this way. From news1234 at free.fr Wed Aug 18 07:20:49 2010 From: news1234 at free.fr (News123) Date: Wed, 18 Aug 2010 13:20:49 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: <4c6bc211$0$9876$426a34cc@news.free.fr> On 08/17/2010 11:44 PM, Baba wrote: > On Aug 16, 6:28 pm, "cbr... at cbrownsystems.com" > wrote: > >> First, suppose d = gcd(x, y, z); then for some x', y', z' we have that >> x = d*x', y = d*y', z = d*z'; and so for any a, b, c: >> > > > could you explain the notation? > > what is the difference btw x and x' ? > > what is x = d*x', y supposed to say? > > gcd(x,y,z) determines the greates number by which all three numbers can be devided. 2,4,6 for example are all divided by 2 thus d=2 now you dived x,y,z by d and call them x' , y' , z' The point is if x,y,z have a gcd grater than one, then you know for sure, that you will never be able to find the a finit greates amount, which cannot be bought if xmymz are all divisible by d, then any combination will also be dividible by d thas any number not dividible by d ( for d > 1) for example n*d + 1 can not be bought From paulo.jpinto at gmail.com Wed Aug 18 07:54:44 2010 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: Wed, 18 Aug 2010 04:54:44 -0700 (PDT) Subject: Python 2.7 support for PyWin32 Message-ID: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Hi everyone, does anyone know when PyWin is going to support Python 2.7? I tried to look for information, but to no avail. Thanks in advance, Paulo From roy at panix.com Wed Aug 18 07:57:18 2010 From: roy at panix.com (Roy Smith) Date: Wed, 18 Aug 2010 07:57:18 -0400 Subject: 79 chars or more? References: Message-ID: In article , "BartC" wrote: > >> Remember, the old hardcopy terminals used to produce 132-character-wide > >> listings. > > > > Those of you who think "old hardcopy terminals" did 132 wide obviously > > don't remember the ASR-33 :-) > > ASR33s I think might have been 72 columns wide (and punched cards had a > similar restriction). Yeah, I was trying to remember if it was 72 or 80. Hmmm, looks like you're right, it *is* 72 (http://www.pdp8.net/asr33/asr33.shtml). Punched cards (at least the common ones used by an 029 or 129 punch machine) were 80 columns. The 72 column restriction was an artificial one imposed by some programming languages such as Fortran. Columns 73-80 could be used to punch a sequence number, so that if you dropped your deck, you could re-assemble it by running it through a card sorter. > However, lineprinter output was more likely to be 132 columns. Yeah, but I wouldn't call a line printer a "terminal". From roy at panix.com Wed Aug 18 08:00:24 2010 From: roy at panix.com (Roy Smith) Date: Wed, 18 Aug 2010 08:00:24 -0400 Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4c6b956e@dnews.tpgi.com.au> Message-ID: In article <4c6b956e at dnews.tpgi.com.au>, Lie Ryan wrote: > On 08/17/10 12:59, AK wrote: > > On 08/16/2010 10:42 PM, James Mills wrote: > >> On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: > >>> As monitors are getting bigger, is there a general change in opinion on > >>> the 79 chars limit in source files? I've experimented with 98 characters > >>> per line and I find it quite a bit more comfortable to work with that > >>> length, even though sometimes I have to edit files in 80 width > >>> terminals, it's still easier to adapt to some inconvenience when that > >>> happens than the other way around, since about 95% of time or more, I do > >>> use wider editor window or terminal. > >>> > >>> Is going over 79 still a terrible thing to do? -andrei > >> > >> My personal opinion (despite monitors being wider) is > >> the horizontal scrolling isn't worth it. Stick to a 80-char width. > > > > But.. why horizontal scrolling, isn't autowrap much better than that? > > > Do you seriously use autowrapper when writing code? I absolutely use auto-indent, parenthesis matching, and syntax coloring. >From time to time, I turn on auto-wrap, but generally find it more annoying than useful and turn it back off again. From breamoreboy at yahoo.co.uk Wed Aug 18 08:33:32 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 18 Aug 2010 13:33:32 +0100 Subject: Python 2.7 support for PyWin32 In-Reply-To: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> References: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Message-ID: On 18/08/2010 12:54, paulo.jpinto at gmail.com wrote: > Hi everyone, > > does anyone know when PyWin is going to support Python 2.7? > > I tried to look for information, but to no avail. > > Thanks in advance, > Paulo It was created on 2009-07-08!!! See:- http://sourceforge.net/projects/pywin32/files/pywin32/ Cheers. Mark Lawrence. From bauketilma at gmail.com Wed Aug 18 08:56:27 2010 From: bauketilma at gmail.com (Duim) Date: Wed, 18 Aug 2010 05:56:27 -0700 (PDT) Subject: when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray' Message-ID: Although I'm sure somewhere this issue is discussed in this (great) group, I didn't know the proper search words for it (although I tried). I'm using python (2.6) scientifically mostly, and created a simple class to store time series (my 'Signal' class). I need this class to have a possibility to get multiplied by an array, but pre and post multiplication have different mathematical outcomes ( basically A* B != B*A ) . Post multiplication by an array works fine defining __mul__ in the Signal class, but pre multiplication does not. It keeps trying to multiply all elements separately instead to send this array to my __rmul__ function. How can I fix this without the need for a separate 'multiplysignal(A,B)' function? To make things easy I've made a small example: [code] import numpy as np class Signal(object): def __init__(self,data,dt): self.data=data self.dt=dt def Nch(self): return self.data.shape[0] def __mul__(self,other): print 'mul called! ',other if isinstance(other,type(np.array([1,2]))): #it's an array: use dot product: return Signal(np.dot(self.data,other),self.dt) if other.__class__.__name__=='Signal': # do something pass def __rmul__(self,other): print 'rmul called! ',other if isinstance(other,type(np.array([1,2]))): #it's an array: use dot product: return Signal(np.dot(other,self.data),self.dt) if other.__class__.__name__=='Signal': # do something pass mySignal=Signal(np.array([[1.,2],[4,5]]),1.) myArray=np.array([[1.,2.],[4.,3.]]) result_mul = mySignal*myArray result_rmul = myArray*mySignal #called 4 times for all members once! #result: #mul called! [[ 1. 2.] # [ 4. 3.]] #rmul called! 1.0 #rmul called! 2.0 #rmul called! 4.0 #rmul called! 3.0 [/code] From morfeokmg at gmail.com Wed Aug 18 09:12:40 2010 From: morfeokmg at gmail.com (Mauricio Martinez Garcia) Date: Wed, 18 Aug 2010 08:12:40 -0500 Subject: error Compile libxml2 from python 2.6.4 Message-ID: <4C6BDC48.6030806@gmail.com> Hi!. Have the next error on install libxml2. python/bin/python setup.py install failed to find headers for libxml2: update includes_dir This my version of python ==> /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python/bin/python Python 2.6.5 (r265:79063, Jul 21 2010, 13:05:40) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. I'm Installing libxml2 for python 2.6.5, and this error break the install. The python path prefix is /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python, and i don't privileges of root. The configuration to be personalized, in prefix path. My compile line is: ./configure --with-python=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python \ --prefix=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml \ --with-libxml-include-prefix=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/pythonPruebas/libxml2/libxml2-INC/usr/local/include/libxml2/libxml This is the output when finalize compiling this is message: Enabled Schemas/Relax-NG support configure: creating ./config.status config.status: creating libxml2.spec config.status: creating Makefile config.status: creating include/Makefile config.status: creating include/libxml/Makefile config.status: creating doc/Makefile config.status: creating doc/examples/Makefile config.status: creating example/Makefile config.status: creating python/Makefile config.status: creating python/tests/Makefile config.status: creating include/libxml/xmlversion.h config.status: creating xml2-config config.status: creating libxml-2.0.pc config.status: creating libxml-2.0-uninstalled.pc config.status: creating xml2Conf.sh config.status: creating python/setup.py config.status: creating config.h config.status: config.h is unchanged config.status: executing depfiles commands And this is output of make install: Libraries have been installed in: /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python/lib/python2.6/site-packages If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the `-LLIBDIR' flag during linking and do at least one of the following: - add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution - use the `-LLIBDIR' linker flag See any operating system documentation about shared libraries for more information, such as the ld(1) and ld.so(8) manual pages. Making install in tests No suffix list. No suffix list. /bin/sh ../../mkinstalldirs /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples mkdir -p -- /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples (for test in build.py attribs.py tst.py tstxpath.py xpathext.py push.py pushSAX.py pushSAXhtml.py error.py serialize.py validate.py tstURI.py cutnpaste.py xpathret.py xpath.py outbuf.py inbuf.py resolver.py regexp.py reader.py reader2.py reader3.py reader4.py reader5.py reader6.py reader7.py walker.py ctxterror.py readererr.py relaxng.py thread2.py tst.xml valid.xml invalid.xml; \ do ../.././install-sh -c -m 0644 ./$test /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples ; done) This an issue?, or bug? Greetings. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bartc at freeuk.com Wed Aug 18 09:34:22 2010 From: bartc at freeuk.com (BartC) Date: Wed, 18 Aug 2010 14:34:22 +0100 Subject: 79 chars or more? In-Reply-To: References: Message-ID: "Roy Smith" wrote in message news:roy-181632.07571818082010 at news.panix.com... > In article , > "BartC" wrote: > >> >> Remember, the old hardcopy terminals used to produce >> >> 132-character-wide >> >> listings. >> > >> > Those of you who think "old hardcopy terminals" did 132 wide obviously >> > don't remember the ASR-33 :-) >> >> ASR33s I think might have been 72 columns wide (and punched cards had a >> similar restriction). > > Yeah, I was trying to remember if it was 72 or 80. Hmmm, looks like > you're right, it *is* 72 (http://www.pdp8.net/asr33/asr33.shtml). > > Punched cards (at least the common ones used by an 029 or 129 punch > machine) were 80 columns. The 72 column restriction was an artificial > one imposed by some programming languages such as Fortran. Columns > 73-80 could be used to punch a sequence number, so that if you dropped > your deck, you could re-assemble it by running it through a card sorter. I'm sure there was a continuation column too. That would mean long lines had to be split up, but if the width was longer, that would not be necessary. >> However, lineprinter output was more likely to be 132 columns. > > Yeah, but I wouldn't call a line printer a "terminal". Source code tended to be perused and marked up on a printout, then corrected at a terminal. So the terminal's width was less important, until fast VDUs came in then printouts were used less, and it made sense to adjust to common 25x80 displays. (I tend to use 60x100 now, sometimes even wider; editing using 25x80 now is like doing keyhole surgery...) -- bartc From ringemup at gmail.com Wed Aug 18 09:58:27 2010 From: ringemup at gmail.com (Nan) Date: Wed, 18 Aug 2010 06:58:27 -0700 (PDT) Subject: subprocess.Popen calling httpd reload never finishes References: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Message-ID: On Aug 17, 8:14?pm, Albert Hopkins wrote: > On Tue, 2010-08-17 at 12:55 -0700, Nan wrote: > > Hi folks -- > > > I have a Python script running under Apache/mod_wsgi that needs to > > reload Apache configs as part of its operation. ?The script continues > > to execute after the subprocess.Popen call. ?The communicate() method > > returns the correct text ("Reloading httpd: [ ?OK ?]"), and I get a > > returncode of 0. ?But the python script (Django) that calls Popen > > never seems to complete (by returning an HTTP response. > > > Any other Popen call I've tried exits properly. ?Here's some sample > > code: > > > ? ? ? ? ? ?args = ['sudo /etc/init.d/httpd reload'] > > ? ? ? ? ? ?proc = subprocess.Popen(args, stdin=subprocess.PIPE, > > stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, > > close_fds=True) > > ? ? ? ? ? ?(stdout_txt, stderr_txt) = proc.communicate("") > > ? ? ? ? ? ?proc.wait() > > ? ? ? ? ? ?logging.debug('%d %s
%s' % (proc.returncode, stdout_txt, > > stderr_txt)) > > ? ? ? ? ? ?logging.debug('still executing') > > ? ? ? ? ? ?return HttpResponse('done') > > > The logging statements are output, but the script doesn't exit. ?If > > you substitute "sudo ls -l" or "sudo /etc/init.d/httpd configtest" for > > "sudo /etc/init.d/httpd reload", the exits properly. > > > ?Any idea what I might be doing wrong? > > > Thanks! > > Django runs inside apache. ?It's kinda weird to have an apache process > restart itself and expect it to return to the caller. > > If the init script does like mine, "reload" executes "apachectl -k > graceful" ? What that instructs apache to do is to restart, but only > kill the process(es) when there are no more connections. ?So apache is > waiting for your connection to close, but you are inside an HTTP request > waiting for apache to restart. ?So you have a race condition here. > > It's not advisable to have apache kill itself and expect it to send a > status back to you telling you it's dead. > > See the apache docs[1] for a better explanation. > > http://httpd.apache.org/docs/2.0/stopping.html#graceful Ah, I'd been told that there would be no conflict, and that this was just reloading the configuration, not restarting Apache. I do need the web app to instruct Apache to reload because just before this it's creating new VirtualHosts that need to be recognized. Is there a better way to do this (e.g. to say "start doing this once I'm finished")? I'm getting a status code and output from the call before the Django script stops executing... Is there a way to stop waiting for the process to complete once I have those? From andrei.avk at gmail.com Wed Aug 18 10:01:15 2010 From: andrei.avk at gmail.com (AK) Date: Wed, 18 Aug 2010 10:01:15 -0400 Subject: 79 chars or more? In-Reply-To: <4C6BA3AD.3050500@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4c6b956e@dnews.tpgi.com.au> <4C6BA3AD.3050500@sschwarzer.net> Message-ID: <4C6BE7AB.5070105@gmail.com> On 08/18/2010 05:11 AM, Stefan Schwarzer wrote: > Hi Lie, > > On 2010-08-18 12:02, Lie Ryan wrote: >> On 08/17/10 12:59, AK wrote: >>> On 08/16/2010 10:42 PM, James Mills wrote: >>>> My personal opinion (despite monitors being wider) is >>>> the horizontal scrolling isn't worth it. Stick to a 80-char width. >>> >>> But.. why horizontal scrolling, isn't autowrap much better than that? >> >> Do you seriously use autowrapper when writing code? > > I think he means wrapping on the screen, not actually > inserting line breaks. > > Stefan Yes, exactly (:set wrap in Vim). -andrei From anthra.norell at bluewin.ch Wed Aug 18 10:03:58 2010 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Wed, 18 Aug 2010 16:03:58 +0200 Subject: Simple Problem but tough for me if i want it in linear time In-Reply-To: <4c69c715$0$11100$c3e8da3@news.astraweb.com> References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> <4c69c715$0$11100$c3e8da3@news.astraweb.com> Message-ID: <1282140238.2398.99.camel@hatchbox-one> On Mon, 2010-08-16 at 23:17 +0000, Steven D'Aprano wrote: > On Mon, 16 Aug 2010 20:40:52 +0200, Frederic Rentsch wrote: > > > How about > > > >>>> [obj for obj in dataList if obj.number == 100] > > > > That should create a list of all objects whose .number is 100. No need > > to cycle through a loop. > > What do you think the list comprehension does, if not cycle through a > loop? > > > -- > Steven What I think is that list comprehensions cycle through a loop a lot faster than a coded loop (for n in ...:). As at the time of my post only coded loops had been proposed and the OP was concerned about speed, I thought I'd propose a list comprehension. I guess my explanation was poorly phrased. Thanks for the reminder. Frederic From mail at timgolden.me.uk Wed Aug 18 10:28:15 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 18 Aug 2010 15:28:15 +0100 Subject: Python 2.7 support for PyWin32 In-Reply-To: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> References: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Message-ID: <4C6BEDFF.5060403@timgolden.me.uk> On 18/08/2010 12:54, paulo.jpinto at gmail.com wrote: > Hi everyone, > > does anyone know when PyWin is going to support Python 2.7? > > I tried to look for information, but to no avail. > > Thanks in advance, > Paulo It already does and has done for a while: http://sourceforge.net/projects/pywin32/files/ TJG From darcy at druid.net Wed Aug 18 10:38:24 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 18 Aug 2010 10:38:24 -0400 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <20100818103824.3a2796ae.darcy@druid.net> On Wed, 18 Aug 2010 23:18:06 +1200 Lawrence D'Oliveiro wrote: > Might I suggest (guessing at the argument keywords here) : > > self.expiration_date = translate_date \ > ( > TheText = find(response, 'MPNExpirationDate').text, > ToFormat ='%Y-%m-%d', > FromFormat ='%m%d%Y' > ) I sometimes use a backslash continuation but it always feels like a failure to me. It's an irrational reaction and I'm not sure why I feel like that. However, if you are going to do it in order to line up the parenthese I would prefer this style. self.expiration_date = translate_date \ ( TheText = find(response, 'MPNExpirationDate').text, ToFormat ='%Y-%m-%d', FromFormat ='%m%d%Y' ) This way you can see not only the block structure at a glance but also the block starter that it is part of. > > Presumably FromFormat should be localizable, rather than hard-coded. > > See, that?s the kind of thing you notice when you think about the code in > this way. The other thing that jumps out at me is having the input format different than the output format. In any case you need a better date input function. There's no reason in this day and age to force users into a particular input form. You should think about creating a utility function that converts any date that is unambiguous. My scripts generally accept all of the following. Sep 1 2010 september 1, 2010 2010-9-1 (I have never seen "Y/D/M" format) 2010/9/1 2010 9 1 12/25/2010 25/12/2010 2010/12/25 It fails on the following. sep 31 2010 (impossible) 2010/25/12 (impossible - Y/D/M never happens) 9/1/2010 (ambiguous - there is no consistiency when year is last field) foo (not a date) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Wed Aug 18 10:49:51 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 18 Aug 2010 10:49:51 -0400 Subject: 79 chars or more? In-Reply-To: <4C6BA05C.2000906@sequans.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <20100817114256.d960549b.darcy@druid.net> <4C6BA05C.2000906@sequans.com> Message-ID: <20100818104951.506a0d2b.darcy@druid.net> On Wed, 18 Aug 2010 10:57:00 +0200 Jean-Michel Pichavant wrote: > D'Arcy J.M. Cain wrote: > > You can extend this if there are complicated sub-calls. Probably > > overkill for this example but here is the idea. > > > > self.expiration_date = translate_date( > > find( > > response, > > 'MPNExpirationDate', > > ).text, > > '%Y-%m-%d', > > '%m%d%Y' > > ) > > > > I also moved the closing brace down to align with the line that opened > > that block. > > > If this is supposed to convice 80+ chars users, that's an epic failure :) > This is exactly the kind of layout I'm happy to not use by not caring > about the line width. As I said above, this was overkill designed to show the idea. Of course I would never split up short calls like that in real code. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From peterwfh2000 at gmail.com Wed Aug 18 11:04:54 2010 From: peterwfh2000 at gmail.com (PETER WONG F H (+971 50 8320722)) Date: Wed, 18 Aug 2010 08:04:54 -0700 (PDT) Subject: Required Buy Palm Jumeirah aprt AND Springs villa, 050-8320722 Message-ID: Dear I have a client who is looking to buy apartment and Villa : 1. the palm jumeirah 3 bed + maid room sea view only (any building) 2. springs type 3E 3. springs type 3M 4. springs type 4E Please send me your direct availabilities, or call me, viewing tomorrow, thank you! Peter Wong F.H ??? (????RERA BRN: 8866) Mob ?? : +971 50 83 20 722 Fax ?? : +971 4 32 30 895 E-mail ?? : peterwfh2000 at gmail.com Company ?? : Pinky Real Estate Broker????? (????RERA ORN: 1866) Website : http://groups.google.com/group/dubai-property-club From paulo.jpinto at gmail.com Wed Aug 18 11:14:20 2010 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: Wed, 18 Aug 2010 08:14:20 -0700 (PDT) Subject: Python 2.7 support for PyWin32 References: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Message-ID: Thanks for the heads up. My error was to only look for the green download button. There you still get 2.6 as default download. -- Paulo On Aug 18, 4:28?pm, Tim Golden wrote: > On 18/08/2010 12:54, paulo.jpi... at gmail.com wrote: > > > Hi everyone, > > > does anyone know when PyWin is going to support Python 2.7? > > > I tried to look for information, but to no avail. > > > Thanks in advance, > > Paulo > > It already does and has done for a while: > > ? ?http://sourceforge.net/projects/pywin32/files/ > > TJG From marduk at letterboxes.org Wed Aug 18 12:37:22 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 18 Aug 2010 12:37:22 -0400 Subject: subprocess.Popen calling httpd reload never finishes In-Reply-To: References: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Message-ID: <1282149442.216434.19.camel@paska> On Wed, 2010-08-18 at 06:58 -0700, Nan wrote: > Ah, I'd been told that there would be no conflict, and that this was > just reloading the configuration, not restarting Apache. > > I do need the web app to instruct Apache to reload because just before > this it's creating new VirtualHosts that need to be recognized. Is > there a better way to do this (e.g. to say "start doing this once I'm > finished")? > > I'm getting a status code and output from the call before the Django > script stops executing... Is there a way to stop waiting for the > process to complete once I have those? I have a wireless router with a built in web server. Sometimes it needs to "reload" it's config. Basically what it's doing is rebooting the entire router (I can see this if I'm actuall watching the router). All it is doing, I'm pretty sure, is calling some program that forks another process and then exits the main program. The forked process then reboots the router. Meanwhile before that happens the web server sends a response. Basically in the response it sends an HTTP Refresh with x number of seconds. Presumably x is longer than the time it requires for the router to reboot. The router reboots, the browser refreshes and viola. You probably need to so something similar in that your request calls a program that forks off and restarts apaches. It should probably not do so immediately so that your request has time to send a response with a refresh header (but that shouldn't take long). After a second or so, apache will have restarted and the browser will have refreshed. so (untested): def reload(request): subprocess.call(['my_apache_reloader']) # this should fork and exit response = HttpResponse() response['Refresh']='3; url=%s' % reverse(home) # chk back in 3 secs return response BTW There is a Django mailing list where this might be more appropriate to discuss. -a From randrange at gmail.com Wed Aug 18 12:49:53 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 09:49:53 -0700 Subject: Problem Creating NewLines in PDF Message-ID: Hello I am generating a PDF in web2py but its ignoring my line breaks. randname = random.randrange(1, 10001) styles = getSampleStyleSheet() title = "My Title" doc = SimpleDocTemplate("primer.pdf") story = [] story.append(Paragraph(strftime("%a, %d %b %Y %H:%M:%S", gmtime()),styles["Heading2"])) para = ParagraphStyle(name="output", fontName='Helvetica', fontSize=12) story.append(Paragraph(str(result_list), para)) doc.build(story) response.headers['Content-Type']='application/pdf' response.headers['Content-Disposition'] = 'attachment;filename='+str(randname)+'-.pdf' return response.stream(open("primer.pdf", 'rb')) result_list is a generated list. The pdf ignores line breaks and outputs it as a list so [' '] are included also. Any idea how I can create line breaks and get rid of the [' '] *cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Aug 18 13:10:23 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 18:10:23 +0100 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: <4C6C13FF.2050807@mrabarnett.plus.com> Andrew Evans wrote: > Hello I am generating a PDF in web2py but its ignoring my line breaks. > > randname = random.randrange(1, 10001) > styles = getSampleStyleSheet() > title = "My Title" > doc = SimpleDocTemplate("primer.pdf") > story = [] > story.append(Paragraph(strftime("%a, %d %b %Y %H:%M:%S", > gmtime()),styles["Heading2"])) > para = ParagraphStyle(name="output", fontName='Helvetica', > fontSize=12) > story.append(Paragraph(str(result_list), para)) str(result_list) is converting the list into a string. Did you mean to do that? > doc.build(story) > response.headers['Content-Type']='application/pdf' > response.headers['Content-Disposition'] = > 'attachment;filename='+str(randname)+'-.pdf' > return response.stream(open("primer.pdf", 'rb')) > > > result_list is a generated list. The pdf ignores line breaks and outputs > it as a list so [' '] are included also. Any idea how I can create line > breaks and get rid of the [' '] > From brandon.harris at reelfx.com Wed Aug 18 13:37:11 2010 From: brandon.harris at reelfx.com (Brandon Harris) Date: Wed, 18 Aug 2010 12:37:11 -0500 Subject: Using re.sub with %s In-Reply-To: References: Message-ID: <4C6C1A47.9020907@reelfx.com> Having trouble using %s with re.sub test = '/my/word/whats/wrong' re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) return is /my/@0/whats/wrong however if I cast a value with letters as opposed to numbers re.sub('(/)word(/)', r'\1\%s\2'%'gosh', test) return is /my/gosh/whats/wrong Any help would be good. I've tried passing the value as an int, or recasting that value as something else, passing it as a raw string, removing the r and just double escaping the groups. Brandon L. Harris From neilc at norwich.edu Wed Aug 18 13:37:45 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 18 Aug 2010 17:37:45 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <8d2k39Fuv2U2@mid.individual.net> On 2010-08-18, D'Arcy J.M. Cain wrote: > The other thing that jumps out at me is having the input format > different than the output format. In any case you need a > better date input function. There's no reason in this day and > age to force users into a particular input form. You should > think about creating a utility function that converts any date > that is unambiguous. My scripts generally accept all of the > following. Under the hood, translate_date just use strptime and strftime, so the formats are whatever those functions support. Moreover, I'm converting one known format (the one in the XML) to another required format (the one required by another program). There's no need to guess the format. -- Neil Cerutti From cbrown at cbrownsystems.com Wed Aug 18 13:38:11 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Wed, 18 Aug 2010 10:38:11 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: On Aug 17, 2:44?pm, Baba wrote: > On Aug 16, 6:28?pm, "cbr... at cbrownsystems.com" > > wrote: > > First, suppose d = gcd(x, y, z); then for some x', y', z' we have that > > x = d*x', y = d*y', z = d*z'; and so for any a, b, c: > > ? ?could you explain the notation? > > ? ?what is the difference btw x and x' ? > > ? ?what is x = d*x', y supposed to say? x', y', z' are names for three natural numbers; I could have chosen r, s, t. "x=d*x'" above simply notes that since x is divisible by d, it can be written as the product of d and some other natural number, and the same is true for both y and z. therefore sums of multiples of x, y and z are always divisible by d. > > > To go the other way, if d = 1, then there exists integers (not > > neccessarily positive) such that > > > a*x + b*y + c*z = 1 > > ? ?what's the link with 6*a+9*b+20*c=n except the similarity? > The link is that it shows that if we have some u, v, and w with 6*u + 9*v + 20*w = n, and we can find some a, b, and c which satisfy 6*a + 9*b + 20*c = 1 then if we let r = u + a, s = v + b, and t = w + c, we get that 6*r + 9*s + 20*t = n+1 although r, s, and t are not neccessarily positive numbers (as they must be to solve your original problem). However, if u, v, and w are sufficiently large compared to a, b, and c, then r, s and t WILL all be positive. But we can only find such an a,b, and c because the gcd of 6, 9, and 20 is equal to 1; that is why you can't solve this problem for nugget pack sizes 6, 12, and 21. Note that if there is one solution (a,b,c) to the gcd equation, there infinitely many tuples (a,b,c) which satisfy the gcd equation, for example: 6*0 + 9*9 + 20*(-4) = 1 6*(-5) + 9*(-1) + 20*2 = 1 6*2 + 9*1 + 20*(-1) = 1 So the proof I gave regarded the /existence/ of a largest unobtainable, not an algorithm for obtaining one. However from the last of those three examples, we can see (details are in my original proof) that the largest unobtainable must be less than 6*0 + 9*0 + 20*(1*5) = 100 so it is potentially helpful for finding an upper bound to the problem. > furthermore i came across this: > > For k = 3, efficient algorithms > have been given by Greenberg and Davison ; if x1 < x2 < x3, these > algorithms run in > time bounded by a polynomial in log x3. Kannan ?gave a very > complicated algorithm > that runs in polynomial time in log xk if k is fixed, but is wildly > exponential in k. However, > Ram??rez Alfons??n proved that the general problem is NP-hard, under > Turing reductions, > by reducing from the integer knapsack problem. So it seems very likely > that there is no > simple formula for computing g(x1, x2, . . . , xk) for arbitrary k. > > source:http://arxiv.org/PS_cache/arxiv/pdf/0708/0708.3224v1.pdf > > i would be interested in the answer to problem 3: explain in English > why the theorem is true > I haven't looked at the link; but to be honest it's unlikely you would understand it if you are having trouble with the much simpler question regarding solutions in the case of 6, 12, and 21. Cheers - Chas From randrange at gmail.com Wed Aug 18 13:48:54 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 10:48:54 -0700 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: Hello yes This line doesn't seem to want to accept a list for some strange reason story.append(Paragraph(str(result_list), para)) *cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From raoulbia at gmail.com Wed Aug 18 13:52:35 2010 From: raoulbia at gmail.com (Baba) Date: Wed, 18 Aug 2010 10:52:35 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: Hi Chas Thanks for that and i agree on your last remark :) re the number of required consecutive passes required: The number of required consecutive passes is equal to the smallest number because after that you can get any amount of nuggets by just adding the smallest nugget pack to some other number. This is only true if gcd(a,b,c)=1. Thanks to all for the help in getting to the bottom of the exercise. I have truly enjoyed this and most importantly i have learned some new things. Hadn't really done any mathematics in a long time and only starting programming so this was good to get up to speed. kind regards to everyone! Baba From thomas at jollybox.de Wed Aug 18 14:21:32 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 18 Aug 2010 20:21:32 +0200 Subject: Using re.sub with %s In-Reply-To: <4C6C1A47.9020907@reelfx.com> References: <4C6C1A47.9020907@reelfx.com> Message-ID: <201008182021.35465.thomas@jollybox.de> On Wednesday 18 August 2010, it occurred to Brandon Harris to exclaim: > Having trouble using %s with re.sub > > test = '/my/word/whats/wrong' > re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) > > return is /my/@0/whats/wrong > This has nothing to do with %, of course: >>> re.sub('(/)word(/)', r'\1\%d\2'%1000, test) '/my/@0/whats/wrong' >>> re.sub('(/)word(/)', r'\1\1000\2', test) '/my/@0/whats/wrong' let's see if we can get rid of that zero: >>> re.sub('(/)word(/)', r'\1\100\2', test) '/my/@/whats/wrong' so '\100' appears to be getting replaced with '@'. Why? >>> '\100' '@' This is Python's way of escaping characters using octal numbers. >>> chr(int('100', 8)) '@' How to avoid this? Well, if you wanted the literal backslash, you'll need to escape it properly: >>> print(re.sub('(/)word(/)', r'\1\\1000\2', test)) /my/\1000/whats/wrong >>> If you didn't want the backslash, then why on earth did you put it there? You have to be careful with backslashes, they bite ;-) Anyway, you can simply do the formatting after the match. >>> re.sub('(/)word(/)', r'\1%d\2', test) % 1000 '/my/1000/whats/wrong' >>> Or work with match objects to construct the resulting string by hand. - Thomas From nfdisco at gmail.com Wed Aug 18 14:24:41 2010 From: nfdisco at gmail.com (ernest) Date: Wed, 18 Aug 2010 11:24:41 -0700 (PDT) Subject: expression in an if statement Message-ID: Hi, In this code: if set(a).union(b) == set(a): pass Does Python compute set(a) twice? Thanks in advance. Ernest From __peter__ at web.de Wed Aug 18 14:34:17 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Aug 2010 20:34:17 +0200 Subject: expression in an if statement References: Message-ID: ernest wrote: > In this code: > > if set(a).union(b) == set(a): pass > > Does Python compute set(a) twice? >>> a = "abc" >>> b = "def" >>> _set = set >>> def set(x): ... print "computing set(%r)" % x ... return _set(x) ... >>> if set(a).union(b) == set(a): pass ... computing set('abc') computing set('abc') So yes, set(a) is computed twice. Peter From cbrown at cbrownsystems.com Wed Aug 18 14:40:57 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Wed, 18 Aug 2010 11:40:57 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: On Aug 18, 10:52?am, Baba wrote: > Hi Chas > > Thanks for that and i agree on your last remark :) > > re the number of required consecutive passes required: > > The number of required consecutive passes is equal to the smallest > number because after that you can get any amount of nuggets by just > adding the smallest nugget pack to some other number. > > This is only true if gcd(a,b,c)=1. > > Thanks to all for the help in getting to the bottom of the exercise. I > have truly enjoyed this and most importantly i have learned some new > things. Hadn't really done any mathematics in a long time and only > starting programming so this was good to get up to speed. > > kind regards to everyone! > Baba Happy to be of service! Cheers - Chas From blog at rivadpm.com Wed Aug 18 14:49:11 2010 From: blog at rivadpm.com (Alex McDonald) Date: Wed, 18 Aug 2010 11:49:11 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> Message-ID: On 18 Aug, 11:09, spinoza1111 wrote: > On Aug 18, 1:21?am, Standish P wrote: > > > This you might want to take this to the Forth people because they are > > marketing their language as a cure for all that plagues programming > > today. > > No, they're not. That I agree with. > Stack based languages have seen better days and Forth > (and the SL/1 language I supported with compilers at Bell-Northern > Research) were last in fashion in the 1970s. Processors seldom could > multitask, so it wasn't recognized that the stack could be a > performance bottleneck, where stack operations cannot be pipelined or > executed in parallel. > > John Hennessy of Stanford and MIPS made the stack must die case at ACM > ASPLOS in 1987. Niklaus Wirth was also at this conference at which I > was a fly on the wall, maintaining that the stack was good for > reliability and verifiability of software. > > Forth had a snowball's chance because it forces ordinary programmers > to think in Reverse Polish notation and is for the above reasons hard > to pipeline, although of course it can be pipelined. I really don't understand much of what you're saying here; Forth can be implemented on processors that have several hardware assisted stacks, 1 stack or even no stack at all. Multitasking? Why's that a problem? And why is it hard to pipeline? Are you thinking of a specific processor? From python at mrabarnett.plus.com Wed Aug 18 14:50:20 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 19:50:20 +0100 Subject: Using re.sub with %s In-Reply-To: <201008182021.35465.thomas@jollybox.de> References: <4C6C1A47.9020907@reelfx.com> <201008182021.35465.thomas@jollybox.de> Message-ID: <4C6C2B6C.7010709@mrabarnett.plus.com> Thomas Jollans wrote: > On Wednesday 18 August 2010, it occurred to Brandon Harris to exclaim: >> Having trouble using %s with re.sub >> >> test = '/my/word/whats/wrong' >> re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) >> >> return is /my/@0/whats/wrong >> > > This has nothing to do with %, of course: > >>>> re.sub('(/)word(/)', r'\1\%d\2'%1000, test) > '/my/@0/whats/wrong' >>>> re.sub('(/)word(/)', r'\1\1000\2', test) > '/my/@0/whats/wrong' > > let's see if we can get rid of that zero: > >>>> re.sub('(/)word(/)', r'\1\100\2', test) > '/my/@/whats/wrong' > > so '\100' appears to be getting replaced with '@'. Why? > >>>> '\100' > '@' > > This is Python's way of escaping characters using octal numbers. > >>>> chr(int('100', 8)) > '@' > > How to avoid this? Well, if you wanted the literal backslash, you'll need to > escape it properly: > >>>> print(re.sub('(/)word(/)', r'\1\\1000\2', test)) > /my/\1000/whats/wrong > > If you didn't want the backslash, then why on earth did you put it there? You > have to be careful with backslashes, they bite ;-) > > Anyway, you can simply do the formatting after the match. > >>>> re.sub('(/)word(/)', r'\1%d\2', test) % 1000 > '/my/1000/whats/wrong' > > Or work with match objects to construct the resulting string by hand. > You can stop group references which are followed by digits from turning into octal escapes in the replacement template by using \g instead: >>> print r'\1%s' % '00' \100 >>> print r'\g<1>%s' % '00' \g<1>00 From jjposner at optimum.net Wed Aug 18 14:50:32 2010 From: jjposner at optimum.net (John Posner) Date: Wed, 18 Aug 2010 14:50:32 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: <4C6C2B78.40606@optimum.net> On 8/18/2010 1:38 PM, cbrown at cbrownsystems.com wrote: >>> To go the other way, if d = 1, then there exists integers (not >>> neccessarily positive) such that >> >>> a*x + b*y + c*z = 1 That fact is non-trivial, although the proof isn't *too* hard [1]. I found it interesting to demonstrate the simpler case (a*x + b*y = 1) by "instrumenting" the classic Python implementation of Euclid's Algorithm: def show_gcd(a,b): """ find GCD of two integers, showing intermediate steps in both remainder and linear-combination forms """ while b: if a%b > 0: rem_form = "%d == %d*(%d), rem %d" % (a, b, a/b, a%b) equ_form = "%d == %d*(1) + %d*(-%d)" % (a%b, a, b, a/b) print "%3d %3d %-30s %s" % (a,b, rem_form, equ_form) a,b = b, a%b print "\nGCD is", a >>> show_gcd(124, 39) 124 39 124 == 39*(3), rem 7 7 == 124*(1) + 39*(-3) 39 7 39 == 7*(5), rem 4 4 == 39*(1) + 7*(-5) 7 4 7 == 4*(1), rem 3 3 == 7*(1) + 4*(-1) 4 3 4 == 3*(1), rem 1 1 == 4*(1) + 3*(-1) Performing successive substitutions, bottom to top, using the equations in the right-hand column: 1 == 4*(1) + 3*(-1) == 4*(1) + (7*(1) + 4*(-1))*(-1) == 4*(2) + 7*(-1) == (39*(1) + 7*(-5))*(2) + 7*(-1) == 39*(2) + 7*(-11) == 39*(2) + (124*(1) + 39*(-3))*(-11) == 39*(35) + 124*(-11) What could be simpler! :-) -John [1] http://math453fall2008.wikidot.com/lecture-3 ("GCD as a linear combonation" [sic]) From python at mrabarnett.plus.com Wed Aug 18 15:02:09 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 20:02:09 +0100 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: <4C6C2E31.30304@mrabarnett.plus.com> Andrew Evans wrote: > Hello yes > > This line doesn't seem to want to accept a list for some strange reason > > > story.append(Paragraph(str(result_list), para)) > From the documentation it appears that you need to pass a string. You're just passing the result of str(result_list), which isn't giving you what you want: >>> result_list = ['hello', 'world'] >>> print str(result_list) ['hello', 'world'] But what do you want? Do you just want to concatenate the entries into a single string (assuming they're all strings)? >>> print "".join(result_list) helloworld Or with some kind of separator between them? >>> print " ".join(result_list) hello world From randrange at gmail.com Wed Aug 18 15:17:24 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 12:17:24 -0700 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: Hello ty for the fast replies This is the string I am using for the PDF I was able to create new lines using the HTML "br" tag which is what I wanted a method to create new lines search_str="Position: (%d) - Keyword: (%s) - Domain (%s)

" % (idx+1, target_keyword, session.target_domain) result_list.append(search_str) however it maintains these characters in the text of the generated PDF [' ', ' '] with the string in between those I just want to be able to out put the string with no extra characters I assume these characters are there because its a list .............. >From the documentation it appears that you need to pass a string. You're just passing the result of str(result_list), which isn't giving you what you want: -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Aug 18 15:17:29 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Aug 2010 15:17:29 -0400 Subject: Python 2.7 support for PyWin32 In-Reply-To: References: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Message-ID: On 8/18/2010 8:33 AM, Mark Lawrence wrote: > On 18/08/2010 12:54, paulo.jpinto at gmail.com wrote: >> Hi everyone, >> >> does anyone know when PyWin is going to support Python 2.7? >> >> I tried to look for information, but to no avail. >> >> Thanks in advance, >> Paulo > > It was created on 2009-07-08!!! See:- > > http://sourceforge.net/projects/pywin32/files/pywin32/ Considering that that is months before the first alpha release and a year before the final of 2.7, truly amazing. -- Terry Jan Reedy From python at mrabarnett.plus.com Wed Aug 18 15:28:38 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 20:28:38 +0100 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: <4C6C3466.4060305@mrabarnett.plus.com> Andrew Evans wrote: > Hello ty for the fast replies > > This is the string I am using for the PDF I was able to create new lines > using the HTML "br" tag which is what I wanted a method to create new lines > > search_str="Position: (%d) - Keyword: (%s) - Domain (%s)

" % > (idx+1, target_keyword, session.target_domain) > result_list.append(search_str) > > however it maintains these characters in the text of the generated PDF > > [' > ', ' > '] with the string in between those > > I just want to be able to out put the string with no extra characters I > assume these characters are there because its a list > As I said, if you just want to join a list of strings into one string, then use "".join(result_list): story.append(Paragraph("".join(result_list), para)) From erather at forth.com Wed Aug 18 15:30:40 2010 From: erather at forth.com (Elizabeth D Rather) Date: Wed, 18 Aug 2010 09:30:40 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> Message-ID: On 8/18/10 12:09 AM, spinoza1111 wrote: > On Aug 18, 1:21 am, Standish P wrote: >>> Garbage collection doesn't use a stack. It uses a "heap", which is in >>> the abstract a collection of memory blocks of different lengths, >>> divided into two lists, generally represented as linked lists: >> >>> 1. A list of blocks that are free and may be used to store new data >> >>> 2. A list of blocks that are in use, or haven't been freed (yet) >> >> Is this all that a heap is or is there more to it ? I have been >> looking for simple but complete explanation of heap for a while and >> not gotten to it. I think I am looking for a stack allocation on the >> same pattern. In a disk, a file is fragmented in many contiguous >> blocks and is accessed automatically. Stacks (at least as far as Forth uses them) and heaps are fundamentally different things. ... >>> However, data structures of variable size, or data structures that >>> merely take up a lot of space, don't play nice with others on the >>> stack, so, we place their address on the stack and store them in >>> another place, which was named the heap, probably, as a sort of >>> witticism. In Forth, they go in "data space", which might or might not be in the dictionary, and is almost never in a dynamically managed heap; certainly not on a stack. ... > > No, they're not. Stack based languages have seen better days and Forth > (and the SL/1 language I supported with compilers at Bell-Northern > Research) were last in fashion in the 1970s. Processors seldom could > multitask, so it wasn't recognized that the stack could be a > performance bottleneck, where stack operations cannot be pipelined or > executed in parallel. Lol. Forth supported multitasking on every processor it was implemented on in the 70's, with blazing speed compared to competitive techniques. I have never seen stack operations to be a bottleneck. ... > Forth had a snowball's chance because it forces ordinary programmers > to think in Reverse Polish notation and is for the above reasons hard > to pipeline, although of course it can be pipelined. Mostly it had a "snowball's chance" because it was never picked up by the CS gurus who, AFAIK, never really took a serious look at it. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From aahz at pythoncraft.com Wed Aug 18 15:32:59 2010 From: aahz at pythoncraft.com (Aahz) Date: 18 Aug 2010 12:32:59 -0700 Subject: scipy / stats : quantiles using sample weights from survey data References: <94bb6313-1b09-4eeb-9969-07d76048a361@m35g2000prn.googlegroups.com> Message-ID: In article <94bb6313-1b09-4eeb-9969-07d76048a361 at m35g2000prn.googlegroups.com>, Christopher Barrington-Leigh wrote: > >There is a function scipy.stats.mstats.mquantiles that returns >quantiles for a vector of data. >But my data should not be uniformly weighted in an estimate of the >distribution, since they are from a survey and come with estimated >sampling weights based on the stratification used in sampling. > >Is there a routine to calculate these quantiles taking into account >the survey weights? I can find nothing, so maybe you have had the >same problem and written something. You should ask on the scipy mailing list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From aahz at pythoncraft.com Wed Aug 18 15:38:08 2010 From: aahz at pythoncraft.com (Aahz) Date: 18 Aug 2010 12:38:08 -0700 Subject: assigning variables from list data References: Message-ID: In article , Chris Hare wrote: > >cursor.execute('select * from net where NetNumber > 0') Unless your table is guaranteed to never change layout, I suggest that instead listing fields is a Good Idea: cursor.execute('select netNumber, netType, .... from net where NetNumber > 0') Then the tuple unpack suggested by other posters will never fail. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From cbrown at cbrownsystems.com Wed Aug 18 16:02:23 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Wed, 18 Aug 2010 13:02:23 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> <4C6C2B78.40606@optimum.net> Message-ID: <2c14d0e6-04fd-457e-a581-bfb4740d9c27@t20g2000yqa.googlegroups.com> On Aug 18, 11:50?am, John Posner wrote: > On 8/18/2010 1:38 PM, cbr... at cbrownsystems.com wrote: > > >>> To go the other way, if d = 1, then there exists integers (not > >>> neccessarily positive) such that > > >>> a*x + b*y + c*z = 1 > > That fact is non-trivial, although the proof isn't *too* hard [1]. I > found it interesting to demonstrate the simpler case (a*x + b*y = 1)... And to get the more general case, if we write (a,b) for gcd of and b, we can think of the "," as a binary operator that you can show is associative: ((a,b), c) = (a, (b,c)) = (a, b, c) and so a proof that exists x,y with a*x + b*y = (a,b) can then be extended to a proof for an arbitrary number of elements. (Oddly, "," is also distributive over itself: ((a,b), c) = ((a,c), (b,c))...) Cheers - Chas From nobody at nowhere.com Wed Aug 18 16:03:19 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 18 Aug 2010 21:03:19 +0100 Subject: when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray' References: Message-ID: On Wed, 18 Aug 2010 05:56:27 -0700, Duim wrote: > Although I'm sure somewhere this issue is discussed in this (great) > group, I didn't know the proper search words for it (although I > tried). > > I'm using python (2.6) scientifically mostly, and created a simple > class to store time series (my 'Signal' class). > I need this class to have a possibility to get multiplied by an array, > but pre and post multiplication have different mathematical outcomes > ( basically A* B != B*A ) . > > Post multiplication by an array works fine defining __mul__ in the > Signal class, but pre multiplication does not. It keeps trying to > multiply all elements separately instead to send this array to my > __rmul__ function. > > How can I fix this without the need for a separate > 'multiplysignal(A,B)' function? Make Signal a subclass of numpy.ndarray. If one operand is a subclass of the other, its __rmul__ will be preferred to the parent's __mul__. In the absence of a subclass-superclass relationship, the LHS's __mul__ is preferred to the RHS's __rmul__, so the RHS's __rmul__ is only called if the LHS lacks a __mul__ method or if the method refuses its argument (returns NotImplemented). Likewise for other "reflected" methods. From ringemup at gmail.com Wed Aug 18 16:12:47 2010 From: ringemup at gmail.com (Nan) Date: Wed, 18 Aug 2010 13:12:47 -0700 (PDT) Subject: subprocess.Popen calling httpd reload never finishes References: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Message-ID: <3e1dc02b-2cf8-4c9d-bb61-6c38faa38b45@d8g2000yqf.googlegroups.com> On Aug 18, 12:37?pm, Albert Hopkins wrote: > On Wed, 2010-08-18 at 06:58 -0700, Nan wrote: > > Ah, I'd been told that there would be no conflict, and that this was > > just reloading the configuration, not restarting Apache. > > > I do need the web app to instruct Apache to reload because just before > > this it's creating new VirtualHosts that need to be recognized. ?Is > > there a better way to do this (e.g. to say "start doing this once I'm > > finished")? > > > I'm getting a status code and output from the call before the Django > > script stops executing... Is there a way to stop waiting for the > > process to complete once I have those? > > I have a wireless router with a built in web server. ?Sometimes it needs > to "reload" it's config. ?Basically what it's doing is rebooting the > entire router (I can see this if I'm actuall watching the router). ?All > it is doing, I'm pretty sure, is calling some program that forks another > process and then exits the main program. ?The forked process then > reboots the router. ?Meanwhile before that happens the web server sends > a response. Basically in the response it sends an HTTP Refresh with x > number of seconds. ?Presumably x is longer than the time it requires for > the router to reboot. ?The router reboots, the browser refreshes and > viola. > > You probably need to so something similar in that your request calls a > program that forks off and restarts apaches. ?It should probably not do > so immediately so that your request has time to send a response with a > refresh header (but that shouldn't take long). ?After a second or so, > apache will have restarted and the browser will have refreshed. > > so (untested): > > def reload(request): > ? ? subprocess.call(['my_apache_reloader']) # this should fork and exit > ? ? response = HttpResponse() > ? ? response['Refresh']='3; url=%s' % reverse(home) # chk back in 3 secs > ? ? return response > > BTW There is a Django mailing list where this might be more appropriate > to discuss. > > -a Sadly, questions about subprocess spawning on the Django lists seem to get referred back to the Python lists when they get an answer at all. You've been very helpful, though, so thank you. I think I'll have to mark in the database when the server needs restarting, and run a cron job to check that and reload Apache from a non-Apache process. It will mean delayed creation of the Virtual Hosts and no immediate feedback to indicate success or failure, but it doesn't look like there's much alternative. From python at rcn.com Wed Aug 18 16:16:48 2010 From: python at rcn.com (Raymond Hettinger) Date: Wed, 18 Aug 2010 20:16:48 GMT Subject: q.join() is probably the wrong method for you References: Message-ID: <2010818161635usenet@eggheadcafe.com> The join() method is all about waiting for all the tasks to be done. If you don't care whether the tasks have actually finished, you can periodically poll the unfinished task count: stop = time() + timeout while q.unfinished_tasks and time() < stop: sleep(1) This loop will exist either when the tasks are done or when the timeout period has elapsed. Raymond > On Thursday, June 17, 2010 5:52 PM pacopyc wrote: > Hi, I am trying to work with threads and I need your help. This is > code: > > from threading import Thread > from Queue import Queue > import time > import random > > def test_fun (k,q,t): > time.sleep(t) > print "hello world from thread " + str(q.get()) + " (sleep time = > " + str(t) + " sec.)" > q.task_done() > > queue = Queue() > for i in range (1,10): > queue.put(i) > for j in range(queue.qsize()): > num = random.randint(1,30) > worker = Thread(target=test_fun, args=(j,queue,num)) > worker.setDaemon(True) > worker.start() > queue.join() > > > Execution: > > hello world from thread 1 (sleep time = 5 sec.) > hello world from thread 2 (sleep time = 5 sec.) > hello world from thread 3 (sleep time = 6 sec.) > hello world from thread 4 (sleep time = 8 sec.) > hello world from thread 5 (sleep time = 10 sec.) > hello world from thread 6 (sleep time = 13 sec.) > hello world from thread 7 (sleep time = 18 sec.) > hello world from thread 8 (sleep time = 19 sec.) > hello world from thread 9 (sleep time = 20 sec.) > > Some questions for you: > > 1) Why order is always the same (thread 1, thread 2, thread 3 .... > thread 9) and also seconds are always increasing? I do not understand. > 2) I'd like to decide a max time for each thread. If max time = 7 sec. > I want to print only threads with sleep time <= 7 sec. How can I do? > Can you modify my code? > > Thank you very much >> On Thursday, June 17, 2010 7:04 PM MRAB wrote: >> pacopyc wrote: >> >> 1) >> >> First it puts the numbers 1..9 into 'queue', then it starts 9 threads, >> giving each a number 'num'. >> >> Each thread waits for 'num' seconds ('t' in the thread). >> >> The thread with the lowest value of 'num' wakes first, gets the first >> entry from 'queue' (the value 1), and therefore prints "thread 1". >> >> The thread with the second-lowest value of 'num' wakes next, gets the >> second entry from 'queue' (the value 2), and therefore prints "thread >> 2". >> >> And so on. >> >> 2) >> >> If a thread is given a value of 'num' of more than a maximum, that >> thread should not print its output, but it should still get the entry >> from the queue (assuming that you want it to still behave the same >> otherwise). >>> On Friday, June 18, 2010 5:45 PM pacopyc wrote: >>> =3D >>> . >>> >>> Ok, the problem is that I want fix a time max for each thread. For >>> example run 10 threads (each can terminate its work in 10 sec. max >>> fixed time) and wait them. If they finish its work in < 10 sec. (for >>> example 2 sec.) very good ... go on immediately (do not wait >>> unnecessary time), but if a thread use more than 10 sec. stop wait (I >>> kill it) .... when all threads have finished their work or when they >>> have used all their available time (10 sec.) the program must go on >>> (do not wait). >>>> On Friday, June 18, 2010 6:27 PM MRAB wrote: >>>> pacopyc wrote: >>>> [snip] >>>> >>>> it is not possible to kill a thread. If you want a thread to have a >>>> maximum time, the thread must check occasionally how long it has been >>>> running and terminate if necessary. >>>> >>>> Another programming language (Java) originally had the ability to kill >>>> threads, but that was later deprecated because it caused problems due to >>>> not knowing what the thread was doing when it was killed (it might have >>>> been in the middle of updating something at the time, for example, >>>> leaving the system in an inconsistent state). >>>>> On Friday, June 18, 2010 6:58 PM pacopyc wrote: >>>>> Ok, I understand. But is possible fix max wait time (for example 60 >>>>> sec.) in main thread and check queue for task done and at the same >>>>> time the remaining time. When all task have done or wait time has >>>>> expired main thread go on. Is it possible? Can you write code? >>>>> Thank you very much. >>>>>> On Friday, June 18, 2010 7:45 PM MRAB wrote: >>>>>> pacopyc wrote: >>>>>> >>>>>> The documentation says that queue.join() cannot have a timeout, so you >>>>>> might have to think of another way to achieve the same effect. >>>>>> >>>>>> You could, for example, have a results queue into which a thread puts >>>>>> something to indicate when it has finished, and then use the .get method >>>>>> on it in the main thread (the .get method can have a timeout). >>>>>> Submitted via EggHeadCafe - Software Developer Portal of Choice >>>>>> Custom Favorites Web Site with MongoDb and NoRM >>>>>> http://www.eggheadcafe.com/tutorials/aspnet/7fbc7a01-5d30-4cd3-b373-51d4a0e1afa8/custom-favorites-web-site-with-mongodb-and-norm.aspx From no.email at nospam.invalid Wed Aug 18 16:32:30 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 18 Aug 2010 13:32:30 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> Message-ID: <7xwrrnmzkx.fsf@ruckus.brouhaha.com> Elizabeth D Rather writes: >> Processors seldom could multitask, so it wasn't recognized that the >> stack could be a performance bottleneck > Lol. Forth supported multitasking on every processor it was > implemented on in the 70's, with blazing speed compared to competitive > techniques. I have never seen stack operations to be a bottleneck. I think "multitasking" in that post refers to superscalar execution, which wasn't done in the 1970's except on supercomputers. That the stack is a bottleneck is the precise reason that optimizing Forth compilers do complicated flow analysis to translate stack operations into register operations. From andrei.avk at gmail.com Wed Aug 18 16:56:22 2010 From: andrei.avk at gmail.com (AK) Date: Wed, 18 Aug 2010 16:56:22 -0400 Subject: Python "why" questions In-Reply-To: <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> Message-ID: <4C6C48F6.3040309@gmail.com> On 08/17/2010 10:15 PM, Russ P. wrote: > On Aug 7, 5:54 am, "D'Arcy J.M. Cain" wrote: > >> Would said beginner also be surprised that a newborn baby is zero years >> old or would it be more natural to call them a one year old? Zero >> based counting is perfectly natural. > > You're confusing continuous and discrete variables. Time is a > continuous variable, but a list index is discrete. > > Take a look at any numbered list, such as the top ten football teams > or the top ten software companies. Have you ever seen such a list > start with zero? If so, where? I sure haven't. > > When I studied linear algebra way back, vector and matrix indices also > always started with one, and I assume they still do. > > The convention of starting with zero may have had some slight > performance advantage in the early days of computing, but the huge > potential for error that it introduced made it a poor choice in the > long run, at least for high-level languages. I have to agree, there's innumerable number of examples where sequential number of an item in a series is counted starting with one. Second loaf of bread; third day of vacation, first cup of tea today, first gray hair, 50th anniversary, 2nd century AD, and approximately a gazillion other examples. Contrast this with _one_ example that was repeated in this thread of there being ground floor, 1st floor, 2nd, and so on. However! Consider that ground floor is kind of different from the other floors. It's the floor that's not built up over ground, but is already there -- in case of the most primitive dwelling, you can put some sawdust over the ground, put a few boards overhead and it's a "home", although probably not a "house". But does it really have what can be officially called a "floor"? On a more practical angle, ground floors usually have the lobby, receptionists, storefronts and stores, etc; while 1st floor and up are business/residential. I think different numbering from pretty much all other things out there gives you a hint that the ground floor is a different animal. -andrei From andrei.avk at gmail.com Wed Aug 18 17:01:20 2010 From: andrei.avk at gmail.com (AK) Date: Wed, 18 Aug 2010 17:01:20 -0400 Subject: Python "why" questions In-Reply-To: <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> Message-ID: <4C6C4A20.8080208@gmail.com> On 08/17/2010 10:15 PM, Russ P. wrote: > On Aug 7, 5:54 am, "D'Arcy J.M. Cain" wrote: > >> Would said beginner also be surprised that a newborn baby is zero years >> old or would it be more natural to call them a one year old? Zero >> based counting is perfectly natural. > > You're confusing continuous and discrete variables. Time is a > continuous variable, but a list index is discrete. > > Take a look at any numbered list, such as the top ten football teams > or the top ten software companies. Have you ever seen such a list > start with zero? If so, where? I sure haven't. > > When I studied linear algebra way back, vector and matrix indices also > always started with one, and I assume they still do. > > The convention of starting with zero may have had some slight > performance advantage in the early days of computing, but the huge > potential for error that it introduced made it a poor choice in the > long run, at least for high-level languages. Besides that, the way things are now, it's almost an Abbot & Costello routine: - How many folders are there? - 5 - Ok, give me the fourth one. - Here. - No, that's the last one! - That's what you said! - No, I said, fourth one! - That's what I did! - How many are there in all? - I already said, five! - You gave me the last one!! - Just like you said - fourth!!!! From nagle at animats.com Wed Aug 18 17:14:15 2010 From: nagle at animats.com (John Nagle) Date: Wed, 18 Aug 2010 14:14:15 -0700 Subject: expression in an if statement In-Reply-To: References: Message-ID: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> On 8/18/2010 11:24 AM, ernest wrote: > Hi, > > In this code: > > if set(a).union(b) == set(a): pass > > Does Python compute set(a) twice? CPython does. Shed Skin might optimize. Don't know about Iron Python. John Nagle From nagle at animats.com Wed Aug 18 17:21:15 2010 From: nagle at animats.com (John Nagle) Date: Wed, 18 Aug 2010 14:21:15 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <7xwrrnmzkx.fsf@ruckus.brouhaha.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <7xwrrnmzkx.fsf@ruckus.brouhaha.com> Message-ID: <4c6c4ec8$0$1623$742ec2ed@news.sonic.net> On 8/18/2010 1:32 PM, Paul Rubin wrote: > Elizabeth D Rather writes: >>> Processors seldom could multitask, so it wasn't recognized that the >>> stack could be a performance bottleneck >> Lol. Forth supported multitasking on every processor it was >> implemented on in the 70's, with blazing speed compared to competitive >> techniques. I have never seen stack operations to be a bottleneck. > > I think "multitasking" in that post refers to superscalar execution, > which wasn't done in the 1970's except on supercomputers. That the > stack is a bottleneck is the precise reason that optimizing Forth > compilers do complicated flow analysis to translate stack operations > into register operations. Some small FORTH machines had dedicated stack hardware. On each CPU cycle, the CPU could do one stack access, one main memory access, and one return stack access. This was before cacheing; those CPUs were slow relative to their memory, so a non-cached one-instruction-per-clock machine made sense. In the superscalar era, there's not much of an advantage to avoiding stack accesses. x86 superscalar machines have many registers not visible to the program, as the fastest level of cache. In practice, the top of the stack is usually in CPU registers. The "huge number of programmer-visible register" machines like SPARCs turned out to be a dead end. So did making all the instructions the same width; it makes the CPU simpler, but not faster, and it bulks up the program by 2x or so. John Nagle From russ.paielli at gmail.com Wed Aug 18 17:47:08 2010 From: russ.paielli at gmail.com (Russ P.) Date: Wed, 18 Aug 2010 14:47:08 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> Message-ID: <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> On Aug 18, 2:01?pm, AK wrote: > On 08/17/2010 10:15 PM, Russ P. wrote: > > > > > On Aug 7, 5:54 am, "D'Arcy J.M. Cain" ?wrote: > > >> Would said beginner also be surprised that a newborn baby is zero years > >> old or would it be more natural to call them a one year old? ?Zero > >> based counting is perfectly natural. > > > You're confusing continuous and discrete variables. Time is a > > continuous variable, but a list index is discrete. > > > Take a look at any numbered list, such as the top ten football teams > > or the top ten software companies. Have you ever seen such a list > > start with zero? If so, where? I sure haven't. > > > When I studied linear algebra way back, vector and matrix indices also > > always started with one, and I assume they still do. > > > The convention of starting with zero may have had some slight > > performance advantage in the early days of computing, but the huge > > potential for error that it introduced made it a poor choice in the > > long run, at least for high-level languages. > > Besides that, the way things are now, it's almost an Abbot & Costello > routine: > > - How many folders are there? > - 5 > - Ok, give me the fourth one. > - Here. > - No, that's the last one! > - That's what you said! > - No, I said, fourth one! > - That's what I did! > - How many are there in all? > - I already said, five! > - You gave me the last one!! > - Just like you said - fourth!!!! Yes, it's confusing. Which element of a list is the "first" element? Wait, "first" is sometimes abbreviated as "1st". So is the 1st element the 0 element or the 1 element? I honestly don't know. Is the top team in the league the number 1 team -- or the number 0 team? I have yet to hear anyone call the best team the number 0 team! Unfortunately, we're stuck with this goofy numbering system in many languages. Fortunately, the trend is away from explicit indexing and toward "for" loops when possible. From cmpython at gmail.com Wed Aug 18 18:07:20 2010 From: cmpython at gmail.com (CM) Date: Wed, 18 Aug 2010 15:07:20 -0700 (PDT) Subject: exception handling with sqlite db errors References: <2a47b306-45d1-474a-9f8e-5b71eba629c9@p11g2000prf.googlegroups.com> Message-ID: On Aug 12, 3:31?pm, a... at pythoncraft.com (Aahz) wrote: > In article <2a47b306-45d1-474a-9f8e-5b71eba62... at p11g2000prf.googlegroups.com>, > > CM? wrote: > > >Maybe it's not much of an issue, but I think it would be a shame if > >occasional hangs/crashes could be caused by these (rare?) database > >conflicts if there is a good approach for avoiding them. ?I guess I > >could put every last write to the db in a try/except block but I > >thought there should be a more general solution, since that will > >require many such exceptions and seems inelegant. > > Wrap all your uses of sqlite into a function that does the try/except; > you only write the code once, then. ?As you progress, you can also > change the code to retry operations. ?Here's some ugly code I wrote on > top of SQLObject: > > from sqlobject.dbconnection import registerConnection > from sqlobject.sqlite.sqliteconnection import SQLiteConnection > > class RetrySQLiteConnection(SQLiteConnection): > ? ? """ > ? ? Because SQLite is not really concurrent, having multiple processes > ? ? read/write can result in locked DB failures. ?In addition, SQLObject > ? ? doesn't properly protect operations in transations, so you can get > ? ? spurious DB errors claiming that the DB is corrupt because of > ? ? foreign key integrity failures. > > ? ? This subclass retries DatabaseError and OperationalError > ? ? exceptions. > ? ? """ > ? ? MAX_RETRIES = 4 > ? ? SAFE_DB_ERROR = [ > ? ? ? ? 'database disk image is malformed', > ? ? ? ? 'file is encrypted or is not a database', > ? ? ? ? ] > > ? ? def _safe_db_error(self,exception): > ? ? ? ? err = str(exception).lower() > ? ? ? ? for safe_err in self.SAFE_DB_ERROR: > ? ? ? ? ? ? if safe_err in err: > ? ? ? ? ? ? ? ? return True > ? ? ? ? return False > > ? ? def _check_integrity(self): > ? ? ? ? conn = self.getConnection() > ? ? ? ? try: > ? ? ? ? ? ? i = 0 > ? ? ? ? ? ? while True: > ? ? ? ? ? ? ? ? i += 1 > ? ? ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? ? ? cursor = conn.cursor() > ? ? ? ? ? ? ? ? ? ? query = "pragma integrity_check" > ? ? ? ? ? ? ? ? ? ? SQLiteConnection._executeRetry(self, conn, cursor, query) > ? ? ? ? ? ? ? ? ? ? result = cursor.fetchall() > ? ? ? ? ? ? ? ? ? ? if result == [('ok',)]: > ? ? ? ? ? ? ? ? ? ? ? ? return True > ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? logging.error("Bad integrity result: %s", result) > ? ? ? ? ? ? ? ? ? ? ? ? return False > ? ? ? ? ? ? ? ? except DatabaseError, e: > ? ? ? ? ? ? ? ? ? ? if i < self.MAX_RETRIES: > ? ? ? ? ? ? ? ? ? ? ? ? logging.info('integrity_check, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? ? ? time.sleep(2) > ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? logging.error('integrity_check, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? finally: > ? ? ? ? ? ? self.releaseConnection(conn) > > ? ? def _executeRetry(self, conn, cursor, query): > ? ? ? ? i = 0 > ? ? ? ? while True: > ? ? ? ? ? ? i += 1 > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? return SQLiteConnection._executeRetry(self, conn, cursor, query) > ? ? ? ? ? ? except OperationalError, e: > ? ? ? ? ? ? ? ? if i < self.MAX_RETRIES: > ? ? ? ? ? ? ? ? ? ? logging.warn('OperationalError, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? time.sleep(10) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? logging.error('OperationalError, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? except DatabaseError, e: > ? ? ? ? ? ? ? ? if e.__class__ is not DatabaseError: > ? ? ? ? ? ? ? ? ? ? # Don't retry e.g. IntegrityError > ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? ? ? if not self._safe_db_error(e): > ? ? ? ? ? ? ? ? ? ? # Only retry specific errors > ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? ? ? if not self._check_integrity(): > ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? ? ? if i < self.MAX_RETRIES: > ? ? ? ? ? ? ? ? ? ? logging.warn('DatabaseError, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? time.sleep(0.5) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? logging.error('DatabaseError, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? raise > > def conn_builder(): > ? ? return RetrySQLiteConnection > > registerConnection(['retrysqlite'], conn_builder) > > def init(): > ? ? dbpath = os.path.join(common.getSyncDataPath(), app.dbname) > ? ? connection_string = "retrysqlite:" + dbpath > ? ? global _connection > ? ? _connection = connectionForURI(connection_string) > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "...if I were on life-support, I'd rather have it run by a Gameboy than a > Windows box." ?--Cliff Wells Thanks, Aahz, I'll try to implement something along these lines. Che From breamoreboy at yahoo.co.uk Wed Aug 18 18:07:29 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 18 Aug 2010 23:07:29 +0100 Subject: Python "why" questions In-Reply-To: <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> Message-ID: On 18/08/2010 22:47, Russ P. wrote: > On Aug 18, 2:01 pm, AK wrote: >> On 08/17/2010 10:15 PM, Russ P. wrote: >> >> >> >>> On Aug 7, 5:54 am, "D'Arcy J.M. Cain" wrote: >> >>>> Would said beginner also be surprised that a newborn baby is zero years >>>> old or would it be more natural to call them a one year old? Zero >>>> based counting is perfectly natural. >> >>> You're confusing continuous and discrete variables. Time is a >>> continuous variable, but a list index is discrete. >> >>> Take a look at any numbered list, such as the top ten football teams >>> or the top ten software companies. Have you ever seen such a list >>> start with zero? If so, where? I sure haven't. >> >>> When I studied linear algebra way back, vector and matrix indices also >>> always started with one, and I assume they still do. >> >>> The convention of starting with zero may have had some slight >>> performance advantage in the early days of computing, but the huge >>> potential for error that it introduced made it a poor choice in the >>> long run, at least for high-level languages. >> >> Besides that, the way things are now, it's almost an Abbot& Costello >> routine: >> >> - How many folders are there? >> - 5 >> - Ok, give me the fourth one. >> - Here. >> - No, that's the last one! >> - That's what you said! >> - No, I said, fourth one! >> - That's what I did! >> - How many are there in all? >> - I already said, five! >> - You gave me the last one!! >> - Just like you said - fourth!!!! > > Yes, it's confusing. Which element of a list is the "first" element? > Wait, "first" is sometimes abbreviated as "1st". So is the 1st element > the 0 element or the 1 element? I honestly don't know. > > Is the top team in the league the number 1 team -- or the number 0 > team? I have yet to hear anyone call the best team the number 0 team! > > Unfortunately, we're stuck with this goofy numbering system in many > languages. Fortunately, the trend is away from explicit indexing and > toward "for" loops when possible. > Bring back Coral 66, all is forgiven. http://www.xgc.com/manuals/xgc-c66-rm/x357.html Cheers. Mark Lawrence. From thomas at jollybox.de Wed Aug 18 18:12:31 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 19 Aug 2010 00:12:31 +0200 Subject: expression in an if statement In-Reply-To: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> Message-ID: <201008190012.32074.thomas@jollybox.de> On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: > On 8/18/2010 11:24 AM, ernest wrote: > > Hi, > > > > In this code: > > > > if set(a).union(b) == set(a): pass > > > > Does Python compute set(a) twice? > > CPython does. Shed Skin might optimize. Don't know > about Iron Python. I doubt any actual Python implementation optimizes this -- how could it? The object "set" is clearly being called twice, and it happens to be called with the object "a" as a sole argument twice. What if "set" has side effects? A compiler could only exclude this possibility if it knew exactly what "set" will be at run time, which it can't. I expect that "set" and "a" have to be looked up twice, actually: "set(a).union(b)" might rebind either one of them. This would be considered a very rude and inappropriate thing to do, but Python usually guarantees to allow bad taste and behaviour. I might be wrong on some points here, but this is what I expect the expression (set(a).union(b) == set(a)) has to do, in any conforming implementation of Python. Please correct me if I'm wrong. 1. find out which object "set" refers to 2. find out which object "a" refers to 3. call (set) with the single positional argument (a), no keyword arguments 4. get the attribute "union" of the return value of [3] 5. find out which object "b" refers to 6. call (.union) with the single positional argument (b). 7. look up __eq__ in the __class__ of the return value of [6] 8. find out which object "set" refers to 9. find out which object "a" refers to 10. call (set) with the single positional argument (a), no keyword arguments 11. call [7] with two positional arguments: the return values [6] & [10] I'm not 100% sure if there are any guarantees as to when (5) is taken care of -- what would happen if set(a) or even set(a).__getattr__ changed the global "b"? My list there is obviously referring to Python 3.x, so there is no __cmp__ to worry about. From randrange at gmail.com Wed Aug 18 19:35:23 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 16:35:23 -0700 Subject: Unsupported Format Character '&' (0x26) Message-ID: I get an error message "Unsupported Format Character '&' (0x26)" I narrowed it down to these two variables any idea how to fix it? SEARCH_URL_0 = " http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)&fr=sfp&fr2=&iscqry= " NEXT_PAGE_0 = " http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)&fr=sfp&xargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2E&pstart=%(start)&b=11 " Not sure why its doing it the value in parenthesis should work %(query) etc Any ideas cheeers -------------- next part -------------- An HTML attachment was scrubbed... URL: From dikermail at gmail.com Wed Aug 18 19:43:31 2010 From: dikermail at gmail.com (Dmitriy Sergeevich) Date: Wed, 18 Aug 2010 16:43:31 -0700 (PDT) Subject: Top world brands shop Message-ID: http://groups.google.com/group/dikermail From randrange at gmail.com Wed Aug 18 19:55:20 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 16:55:20 -0700 Subject: Unsupported Format Character '&' (0x26) In-Reply-To: References: Message-ID: nvm I got it by adding s and d respectively after each value eg %(query)s thank you all On Wed, Aug 18, 2010 at 4:35 PM, Andrew Evans wrote: > I get an error message "Unsupported Format Character '&' (0x26)" I narrowed > it down to these two variables > > any idea how to fix it? > > SEARCH_URL_0 = " > http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)&fr=sfp&fr2=&iscqry= > " > NEXT_PAGE_0 = " > http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)&fr=sfp&xargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2E&pstart=%(start)&b=11 > " > > > > Not sure why its doing it the value in parenthesis should work %(query) etc > > Any ideas cheeers > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stndshp at gmail.com Wed Aug 18 20:13:22 2010 From: stndshp at gmail.com (Standish P) Date: Wed, 18 Aug 2010 17:13:22 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> Message-ID: <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> On Aug 18, 12:30?pm, Elizabeth D Rather wrote: > On 8/18/10 12:09 AM, spinoza1111 wrote: > > > On Aug 18, 1:21 am, Standish P ?wrote: > >>> Garbage collection doesn't use a stack. It uses a "heap", which is in > >>> the abstract a collection of memory blocks of different lengths, > >>> divided into two lists, generally represented as linked lists: > > >>> 1. ?A list of blocks that are free and may be used to store new data > > >>> 2. ?A list of blocks that are in use, or haven't been freed (yet) > > >> Is this all that a heap is or is there more to it ? I have been > >> looking for simple but complete explanation of heap for a while and > >> not gotten to it. I think I am looking for a stack allocation on the > >> same pattern. In a disk, a file is fragmented in many contiguous > >> blocks and is accessed automatically. > > Stacks (at least as far as Forth uses them) and heaps are fundamentally > different things. > > ... > > >>> However, data structures of variable size, or data structures that > >>> merely take up a lot of space, don't play nice with others on the > >>> stack, so, we place their address on the stack and store them in > >>> another place, which was named the heap, probably, as a sort of > >>> witticism. > > In Forth, they go in "data space", which might or might not be in the > dictionary, and is almost never in a dynamically managed heap; certainly > not on a stack. > ... > > > > > No, they're not. Stack based languages have seen better days and Forth > > (and the SL/1 language I supported with compilers at Bell-Northern > > Research) were last in fashion in the 1970s. Processors seldom could > > multitask, so it wasn't recognized that the stack could be a > > performance bottleneck, where stack operations cannot be pipelined or > > executed in parallel. > > Lol. ?Forth supported multitasking on every processor it was implemented > on in the 70's, with blazing speed compared to competitive techniques. > I have never seen stack operations to be a bottleneck. > > > > Forth had a snowball's chance because it forces ordinary programmers > > to think in Reverse Polish notation and is for the above reasons hard > > to pipeline, although of course it can be pipelined. > > Mostly it had a "snowball's chance" because it was never picked up by > the CS gurus who, AFAIK, never really took a serious look at it. Its quite possible that the criticism is unfair, but dont you think that in part some responsibility must be borne by your organization in not doing a good job of education ? I have looked at this book you authored in the past few weeks and found a link for your convenience now. This is entitled Advanced ..... http://www.amazon.com/Forth-Application-Techniques-5th-Notebook/dp/1419685767/ref=sr_1_1?ie=UTF8&s=books&qid=1282175842&sr=8-1#reader_1419685767 Show me on what page does it explain how Forth implements dynamic binding or lexical binding and takes care of the scope of definition of the "nouns" ? Provide me with a link, if you kindly would, that can take me to a tutorial of Forth internals or discusses this issue. > Cheers, > Elizabeth She is quite humble. Take a look at this page, http://www.forth.com/resources/evolution/index.html She is currently the number 1 in the forth world and if there was a nobel prize in forth, it would go to these three. Authors Elizabeth D. Rather FORTH, Inc. 5959 W. Century Blvd. Suite 700 Los Angeles, CA 90045 Elizabeth Rather is the co-founder of FORTH, Inc. and is a leading expert in the Forth programming language. Elizabeth was a colleague of Chuck Moore back when he worked at NRAO in the early 1970s. During his development of Forth, she became the second ever Forth programmer. Since then, she has become a leading expert in the language and one of its main proponents. Elizabeth was the chair of the ANSI Technical Committee that produced the ANSI Standard for Forth (1994). She is an author of several books on Forth and gives regular training seminars on its usage. Donald R. Colburn c/o Digital Media Magic 14712 Westbury Rd. Rockville, MD 20853 Don Colburn was one of the earliest Forth users. He was one of the founders of the Forth Interest Group, and contributed to the development of the first public-domain figForth. Subsequently, he founded Creative Solutions, Inc. (CSI), which introduced MacForth? in 1984. MacForth was the first programming language capable of running on the Macintosh when it was first introduced. Don was a member of the ANSI Technical Committee that produced the ANSI Standard for Forth (1994). He died in 2009. Charles H. Moore Computer Cowboys 40 Cedar Lane P.O. Box 127 Sierra City, CA 96125 Chuck Moore is Chairman and CTO of Green Arrays, Inc. He co-founded FORTH, Inc., in 1971 and went on to develop a Forth-based chip (RTX2000) in the mid 1980s, derivatives of which are still being used widely by NASA. At Computer Cowboys, Mr. Moore designed the Sh-Boom microprocessor and then co-founded iTv, an Internet Appliance manufacturer. During the 1990s, he used his own CAD software to design several custom VLSI chips, including the F21 processor with a network interface. More recently, he invented colorForth and ported his VLSI design tools to it. Moore served as CTO for IntellaSys during development of the S40 multi-computer chip. From stndshp at gmail.com Wed Aug 18 20:23:02 2010 From: stndshp at gmail.com (Standish P) Date: Wed, 18 Aug 2010 17:23:02 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On Aug 17, 6:38?pm, John Passaniti wrote: > You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > lists are constructed with pair of pointers called a "cons cell". > That is the most primitive component that makes up a list. ?Forth has > no such thing; in Forth, the dictionary (which is traditionally, but > not necessarily a list) is a data structure that links to the previous > word with a pointer. ? Would you show me a picture, ascii art or whatever for Forth ? I know what lisp lists look like so I dont need that for comparison. Forth must have a convention and a standard or preferred practice for its dicts. However, let me tell you that in postscript the dictionaries can be nested inside other dictionaries and any such hiearchical structure is a nested associative list, which is what linked list, nested dictionaries, nested tables are. > This is in fact one of the nice things about > Lisp; because all lists are created out of the same primitive cons > cell, you can consistently process any list in the system. ?In Forth, > any lists (such as the dictionary, if it is a list) are specific to > their purpose and have to be treated individually. > > I don't know what you mean by "nested-dictionaries." ?There is no such > thing in Forth. ?Dictionaries don't nest. ?You can create wordlists, > but each wordlist is flat. ?When most people think of a nested > dictionary, they would think of a structure that would allow any > arbitrary level of nesting, not a string of flat wordlists. From kst-u at mib.org Wed Aug 18 20:38:24 2010 From: kst-u at mib.org (Keith Thompson) Date: Wed, 18 Aug 2010 17:38:24 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> Message-ID: Standish P writes: > On Aug 18, 12:30?pm, Elizabeth D Rather wrote: [...] >> Mostly it had a "snowball's chance" because it was never picked up by >> the CS gurus who, AFAIK, never really took a serious look at it. > > Its quite possible that the criticism is unfair, but dont you think > that in part some responsibility must be borne by your organization in > not doing a good job of education ? [snip] > Show me on what page does it explain how Forth implements dynamic > binding or lexical binding and takes care of the scope of definition > of the "nouns" ? [...] Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, or comp.lang.python. Please trim the Newsgroups line. -- Keith Thompson (The_Other_Keith) kst-u at mib.org Nokia "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" From margieroginski at gmail.com Wed Aug 18 21:20:12 2010 From: margieroginski at gmail.com (Margie Roginski) Date: Wed, 18 Aug 2010 18:20:12 -0700 (PDT) Subject: How to see intermediate fail results from unittest as tests are running? Message-ID: Hi, I am using unittest in a fairly basic way, where I have a single file that simply defines a class that inherits from unittest.TestCase and then within that class I have a bunch of methods that start with "test". Within that file, at the bottom I have: if __name__ == "__main__": unittest.main() This works fine and it runs all of the testxx() methods in my file. As it runs it prints if the tests passed or failed, but if they fail, it does not print the details of the assert that made them fail. It collects this info up and prints it all at the end. Ok - my question: Is there any way to get unittest to print the details of the assert that made a test fail, as the tests are running? IE, after a test fails, I would like to see why, rather than waiting until all the tests are done. I've searched the doc and even looked at the code, and it seems the answer is no, but I'm just wondering if I'm missing something. Thanks! Margie From dan at tombstonezero.net Wed Aug 18 21:50:04 2010 From: dan at tombstonezero.net (Dan Sommers) Date: Thu, 19 Aug 2010 01:50:04 +0000 (UTC) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4C6C48F6.3040309@gmail.com> Message-ID: On Wed, 18 Aug 2010 16:56:22 -0400, AK wrote: > Contrast this with _one_ example that was repeated in this thread of > there being ground floor, 1st floor, 2nd, and so on. However! Consider > that ground floor is kind of different from the other floors. It's the > floor that's not built up over ground, but is already there -- in case > of the most primitive dwelling, you can put some sawdust over the > ground, put a few boards overhead and it's a "home", although probably > not a "house". But does it really have what can be officially called a > "floor"? That's the perfect example, although perhaps for an [apparently] unintended reason : I think that the notion of a qualitatively different "ground floor" is European, or at least that's the way I remember it from my high school French class way back in the late 1970s. In the U.S., when you walk into a building (even a very tall commercial building), that's the first floor, and when you go up a level, that's the second floor, and all the room/suite/office numbers are two hundred and something. I also seem to recall that some European buildings have a mezzanine floor between the ground floor and the floor whose reference number is 1, but again, high school was a long time ago. Dan From steve-REMOVE-THIS at cybersource.com.au Wed Aug 18 22:47:28 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 02:47:28 GMT Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> <4c69c715$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c6c9b3f$0$28637$c3e8da3@news.astraweb.com> On Wed, 18 Aug 2010 16:03:58 +0200, Frederic Rentsch wrote: > On Mon, 2010-08-16 at 23:17 +0000, Steven D'Aprano wrote: >> On Mon, 16 Aug 2010 20:40:52 +0200, Frederic Rentsch wrote: >> >> > How about >> > >> >>>> [obj for obj in dataList if obj.number == 100] >> > >> > That should create a list of all objects whose .number is 100. No >> > need to cycle through a loop. >> >> What do you think the list comprehension does, if not cycle through a >> loop? >> >> >> -- >> Steven > > What I think is that list comprehensions cycle through a loop a lot > faster than a coded loop (for n in ...:). I think measurement beats intuition: [steve at wow-wow ~]$ python -m timeit '[str(i) for i in xrange(100000)]' 10 loops, best of 3: 84 msec per loop [steve at wow-wow ~]$ python -m timeit 'L=[] > for i in xrange(100000): > L.append(str(i)) > ' 10 loops, best of 3: 105 msec per loop But wait... we're not comparing apples with apples. There's an extra name lookup in the for-loop that the list comp doesn't have. We can fix that: [steve at wow-wow ~]$ python -m timeit 'L=[]; append = L.append for i in xrange(100000): append(str(i)) ' 10 loops, best of 3: 86.7 msec per loop The difference between 84 and 86 msec is essentially measurement error. Hell, the difference between 84 and 104 msec is not terribly significant either. > As at the time of my post only > coded loops had been proposed and the OP was concerned about speed, I > thought I'd propose a list comprehension. Yes, but the OP was concerned with asymptotic speed (big-oh notation), and both a for-loop and a list-comp are both O(N). Frankly, I think the OP doesn't really know what he wants, other than premature optimization. It's amazing how popular that is :) -- Steven From steve-REMOVE-THIS at cybersource.com.au Wed Aug 18 22:58:12 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 02:58:12 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> Message-ID: <4c6c9dc4$0$28637$c3e8da3@news.astraweb.com> On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote: > Is the top team in the league the number 1 team -- or the number 0 team? > I have yet to hear anyone call the best team the number 0 team! Why is the top team the one with the lowest number? > Unfortunately, we're stuck with this goofy numbering system in many > languages. Fortunately, the trend is away from explicit indexing and > toward "for" loops when possible. Agreed on the second sentence there, but not on the first. There's nothing "goofy" about indexing items from 0. Yes, it does lead to slight more difficulty when discussing which item you want in *human* languages, but not in *programming* languages. The nth item is always the nth item. The only difference is whether n starts at 0 or 1, and frankly, if you (generic you, not you personally) can't learn which to use, you have no business pretending to be a programmer. -- Steven From erather at forth.com Wed Aug 18 23:05:24 2010 From: erather at forth.com (Elizabeth D Rather) Date: Wed, 18 Aug 2010 17:05:24 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On 8/18/10 2:23 PM, Standish P wrote: > On Aug 17, 6:38 pm, John Passaniti wrote: > >> You asked if Forth "borrowed" lists from Lisp. It did not. In Lisp, >> lists are constructed with pair of pointers called a "cons cell". >> That is the most primitive component that makes up a list. Forth has >> no such thing; in Forth, the dictionary (which is traditionally, but >> not necessarily a list) is a data structure that links to the previous >> word with a pointer. > > Would you show me a picture, ascii art or whatever for Forth ? I know > what lisp lists look like so I dont need that for comparison. Forth > must have a convention and a standard or preferred practice for its > dicts. However, let me tell you that in postscript the dictionaries > can be nested inside other dictionaries and any such hiearchical > structure is a nested associative list, which is what linked list, > nested dictionaries, nested tables are. You indicated that you have a copy of Forth Application Techniques. Sections 8.1 and 8.2 cover this topic, with some drawings. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From python.list at tim.thechases.com Wed Aug 18 23:19:14 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 18 Aug 2010 22:19:14 -0500 Subject: Simple Problem but tough for me if i want it in linear time In-Reply-To: <4c6c9b3f$0$28637$c3e8da3@news.astraweb.com> References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> <4c69c715$0$11100$c3e8da3@news.astraweb.com> <4c6c9b3f$0$28637$c3e8da3@news.astraweb.com> Message-ID: <4C6CA2B2.5010406@tim.thechases.com> On 08/18/10 21:47, Steven D'Aprano wrote: > Frankly, I think the OP doesn't really know what he wants, other than > premature optimization. It's amazing how popular that is :) You see, the trick to prematurely optimizing is to have a good algorithm for prematurely optimizing...the real question them becomes "How can I optimize my premature-optimization algorithms to O(1) instead of O(newsgroup)?" :-) -tkc PS: I'm not positive, but O(newsgroup) may asymptotically approach O(log n) if the question is well formed, but O(2^n) if flaming, indentation/line-length preferences, the meaning of OOP, SQL-parameter escaping, McNugget combinations, or suggestions that Python is "just a scripting language" are involved... From dan.kluev at gmail.com Thu Aug 19 00:29:20 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Thu, 19 Aug 2010 15:29:20 +1100 Subject: expression in an if statement In-Reply-To: <201008190012.32074.thomas@jollybox.de> References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> <201008190012.32074.thomas@jollybox.de> Message-ID: On Thu, Aug 19, 2010 at 9:12 AM, Thomas Jollans wrote: > I doubt any actual Python implementation optimizes this -- how could it? > The > object "set" is clearly being called twice, and it happens to be called > with > the object "a" as a sole argument twice. What if "set" has side effects? A > compiler could only exclude this possibility if it knew exactly what "set" > will be at run time, which it can't. > > I expect that "set" and "a" have to be looked up twice, actually: > "set(a).union(b)" might rebind either one of them. This would be considered > a > very rude and inappropriate thing to do, but Python usually guarantees to > allow bad taste and behaviour. > > Yep. >>> def test(): ... a = [1] ... b = [1] ... if set(a).union(b) == set(a): pass ... >>> dis.dis(test) 2 0 LOAD_CONST 1 (1) 3 BUILD_LIST 1 6 STORE_FAST 0 (a) 3 9 LOAD_CONST 1 (1) 12 BUILD_LIST 1 15 STORE_FAST 1 (b) 4 18 LOAD_GLOBAL 0 (set) 21 LOAD_FAST 0 (a) 24 CALL_FUNCTION 1 27 LOAD_ATTR 1 (union) 30 LOAD_FAST 1 (b) 33 CALL_FUNCTION 1 36 LOAD_GLOBAL 0 (set) 39 LOAD_FAST 0 (a) 42 CALL_FUNCTION 1 45 COMPARE_OP 2 (==) 48 JUMP_IF_FALSE 4 (to 55) 51 POP_TOP 52 JUMP_FORWARD 1 (to 56) >> 55 POP_TOP >> 56 LOAD_CONST 0 (None) 59 RETURN_VALUE > I might be wrong on some points here, but this is what I expect the > expression > (set(a).union(b) == set(a)) has to do, in any conforming implementation of > Python. Please correct me if I'm wrong. > You can use dis module to let Python do compiling and explaining for you -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From russ.paielli at gmail.com Thu Aug 19 00:55:30 2010 From: russ.paielli at gmail.com (Russ P.) Date: Wed, 18 Aug 2010 21:55:30 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> <4c6c9dc4$0$28637$c3e8da3@news.astraweb.com> Message-ID: On Aug 18, 7:58?pm, Steven D'Aprano wrote: > On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote: > > Is the top team in the league the number 1 team -- or the number 0 team? > > I have yet to hear anyone call the best team the number 0 team! > > Why is the top team the one with the lowest number? How could it be otherwise? What is the highest number? Here's a couple of things I'd like to see just once before I die: 1. The winner of the championship game chanting, "We're number zero! We're number zero! 2. The loser of the championship game chanting, "We're number one! We're number one! > > > Unfortunately, we're stuck with this goofy numbering system in many > > languages. Fortunately, the trend is away from explicit indexing and > > toward "for" loops when possible. > > Agreed on the second sentence there, but not on the first. There's > nothing "goofy" about indexing items from 0. Yes, it does lead to slight > more difficulty when discussing which item you want in *human* languages, > but not in *programming* languages. The nth item is always the nth item. > The only difference is whether n starts at 0 or 1, and frankly, if you > (generic you, not you personally) can't learn which to use, you have no > business pretending to be a programmer. Maybe "goofy" was too derogatory, but I think you are rationalizing a bad decision, at least for high-level languages. I don't think programming languages should always mimic human languages, but this is one case where there is no advantage to doing otherwise. Why do you think "off by one" errors are so common? Because the darn indexing convention is off by one! And I'd still like to know if the "1st" element of aList is aList[0] or aList[1]. From abhijeet.thatte at gmail.com Thu Aug 19 00:59:07 2010 From: abhijeet.thatte at gmail.com (Abhijeet) Date: Wed, 18 Aug 2010 21:59:07 -0700 Subject: Need to import stuff In-Reply-To: References: Message-ID: <4C6CBA1B.2040701@gmail.com> Hi, Used imp. It worked. Thanks Daniel Kluev wrote: > > On Wed, Aug 18, 2010 at 9:40 AM, abhijeet thatte > > wrote: > > Hi, > > Thanks for the reply. But I guess it does not support nested file > paths. > If user gives 'abcd' then I need to import "//*Do/Stuff/abcd*/". > Out of which only /"abcd" is taken run time. Do and Stuff are fixed. / > /I got an error "/ImportError: Import by filename is not > supported.". Any solution?? > > > For complex importing, you can use imp module, > http://docs.python.org/library/imp.html > > Like this: > module_desc = imp.find_module(name, [base_path]) > module = imp.load_module(full_name, *module_desc) > > -- > With best regards, > Daniel Kluev > From ldo at geek-central.gen.new_zealand Thu Aug 19 01:05:44 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 19 Aug 2010 17:05:44 +1200 Subject: 79 chars or more? References: Message-ID: In message , BartC wrote: > (I tend to use 60x100 now, sometimes even wider; editing using 25x80 now > is like doing keyhole surgery...) And yet some people still think sticking to fewer columns is a good idea. From magguru.bangarayya at gmail.com Thu Aug 19 01:06:32 2010 From: magguru.bangarayya at gmail.com (Hot sex) Date: Wed, 18 Aug 2010 22:06:32 -0700 (PDT) Subject: Simple hack to get $5000 to your Paypal account Message-ID: <7238a8e3-e107-47cb-8914-bb993ef81079@i18g2000pro.googlegroups.com> Simple hack to get $5000 to your Paypal account At http://simplelivevideos.tk i have hidden the Paypal Form link in an image. in that website on Right Side below search box, click on image and enter your name and Paypal ID. From anthra.norell at bluewin.ch Thu Aug 19 02:40:08 2010 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Thu, 19 Aug 2010 08:40:08 +0200 Subject: expression in an if statement In-Reply-To: <201008190012.32074.thomas@jollybox.de> References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> <201008190012.32074.thomas@jollybox.de> Message-ID: <1282200008.2386.23.camel@hatchbox-one> On Thu, 2010-08-19 at 00:12 +0200, Thomas Jollans wrote: > On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: > > On 8/18/2010 11:24 AM, ernest wrote: > > > Hi, > > > > > > In this code: > > > > > > if set(a).union(b) == set(a): pass > > > > > > Does Python compute set(a) twice? > > > > CPython does. Shed Skin might optimize. Don't know > > about Iron Python. > > I doubt any actual Python implementation optimizes this -- how could it? And why should it if a programmer uses its facilities inefficiently. I would write >>> if set(a).issuperset (b): pass Frederic From nikos.the.gr33k at gmail.com Thu Aug 19 02:55:38 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Wed, 18 Aug 2010 23:55:38 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6BA2C4.4000309@gmail.com> Message-ID: I would expect that: "nikos" is a string, while, ("nikos") is a single element tuple. ["nikos"] is a single element list. That way we wouldn't be needing comma seperators. I just don't like it when "nikos" and ("nikos") is the same thing exactly. Parentheses are to be used to define a tuple and square brackets to define a list. Also i want to ask whats the difference between 'nikos', "nikos" and '''nikos''' for Python and whats the best way to use to enclose a string. ================================== if in my example instead of | cursor.execute('''SELECT host, hits, date FROM visitors WHERE | page=%s ORDER BY date DESC''', (page,) ) i use | cursor.execute('''SELECT host, hits, date FROM visitors WHERE | page=%s ORDER BY date DESC''', page) instead which i tend to like more, would there i have a problem? Also how how this part here page=%s doesn't need to be written as page='%s' which is the way i used to have it written with myssql string substitution? ========================================== And last but not least :-) is that http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors" =============================== don't reproduce the problem of actual deleting my data. I don't care losing it! I just want to see that happening with my own eyes! but if you try it you get an error. Maybe die to whitespace in the value of the page? How to write that propetly? Thank again fellows for ALL your help! From nikos.the.gr33k at gmail.com Thu Aug 19 03:10:00 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Thu, 19 Aug 2010 00:10:00 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6BA2C4.4000309@gmail.com> Message-ID: On 18 ???, 12:50, Cameron Simpson wrote: > > ("nikos",) is a single element tuple. > ["nikos"] is a single element list. > ["nikos",] is also a single element list, just written like the tuple. It makes more sense if i: "nikos" is just a string ("nikos") is a single element tuple ["nikos"] is also a single element list After all () used to define tuples and [] usedd to define lists. Why commas? Also is there a difference between 'nikos' or "nikos" or '''nikos''' ? What's and why best to use to enclose strings? =========================== Why in mysql string substitution example i have to use page='%s' and in the comma way(automatic mysql converetion i dont need the single quotes page=%s ? What is the diff? =========================== Why http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors" don't reproduce the problem of actual deleting my data to demonstrate the wrongness of string substitution in mysql queries? I don't care losing my data! The page is there to helpe me learn python and mysql. I just want to see that happening with my own eyes! Thanks again fols for all your precious help and explanations. From __peter__ at web.de Thu Aug 19 03:41:02 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 09:41:02 +0200 Subject: How to see intermediate fail results from unittest as tests are running? References: Message-ID: Margie Roginski wrote: > I am using unittest in a fairly basic way, where I have a single file > that simply defines a class that inherits from unittest.TestCase and > then within that class I have a bunch of methods that start with > "test". Within that file, at the bottom I have: > > if __name__ == "__main__": > unittest.main() > > This works fine and it runs all of the testxx() methods in my file. > As it runs it prints if the tests passed or failed, but if they fail, > it does not print the details of the assert that made them fail. It > collects this info up and prints it all at the end. > > Ok - my question: Is there any way to get unittest to print the > details of the assert that made a test fail, as the tests are > running? IE, after a test fails, I would like to see why, rather than > waiting until all the tests are done. Not exactly what you're asking for, but 2.7 has grown a --failfast option that tells unittest to stop on the first failure. For older Python versions you can use nose nosetests -x myscript.py at http://somethingaboutorange.com/mrl/projects/nose/0.11.2/ or the unittest backport at http://pypi.python.org/pypi/unittest2 Peter From forever.arihant at gmail.com Thu Aug 19 03:47:34 2010 From: forever.arihant at gmail.com (arihant nahata) Date: Thu, 19 Aug 2010 13:17:34 +0530 Subject: OpenCV_Problem In-Reply-To: References: <201008151914.34334.rami.chowdhury@gmail.com> Message-ID: > There is no file named _cv.dll file in the directory that you mentioned > what to do now.??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve-REMOVE-THIS at cybersource.com.au Thu Aug 19 03:52:30 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 07:52:30 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> <4c6c9dc4$0$28637$c3e8da3@news.astraweb.com> Message-ID: <4c6ce2be$0$11111$c3e8da3@news.astraweb.com> On Wed, 18 Aug 2010 21:55:30 -0700, Russ P. wrote: > On Aug 18, 7:58?pm, Steven D'Aprano T... at cybersource.com.au> wrote: >> On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote: >> > Is the top team in the league the number 1 team -- or the number 0 >> > team? I have yet to hear anyone call the best team the number 0 team! >> >> Why is the top team the one with the lowest number? > > How could it be otherwise? What is the highest number? If there are N teams, then the highest number is obviously N (if counting from 1) or N-1 (if from 0). In other words... why do we rank sporting teams Best to Worst rather than the other way around? [...] > Maybe "goofy" was too derogatory, but I think you are rationalizing a > bad decision, at least for high-level languages. I don't think > programming languages should always mimic human languages, but this is > one case where there is no advantage to doing otherwise. > > Why do you think "off by one" errors are so common? Because the darn > indexing convention is off by one! But you have that exactly backwards. Counting from 0 leads to fewer off by one errors for many tasks. (Of course, avoiding indexing in favour of iteration leads to even fewer off by one errors.) Anyway, in a feeble attempt to move this discussion somewhere -- anywhere! -- else: http://c2.com/cgi/wiki?FencePostError http://c2.com/cgi/wiki?WhyNumberingShouldStartAtZero http://c2.com/cgi/wiki?WhyNumberingShouldStartAtOne http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/zero and of course: http://xkcd.com/163/ -- Steven From stndshp at gmail.com Thu Aug 19 03:56:35 2010 From: stndshp at gmail.com (Standish P) Date: Thu, 19 Aug 2010 00:56:35 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> Message-ID: <8a12e419-447b-475d-9ec2-216f2d97c3cb@v41g2000yqv.googlegroups.com> On Aug 18, 5:38?pm, Keith Thompson wrote: > Standish P writes: > > On Aug 18, 12:30?pm, Elizabeth D Rather wrote: > [...] > >> Mostly it had a "snowball's chance" because it was never picked up by > >> the CS gurus who, AFAIK, never really took a serious look at it. > > > Its quite possible that the criticism is unfair, but dont you think > > that in part some responsibility must be borne by your organization in > > not doing a good job of education ? > [snip] > > Show me on what page does it explain how Forth implements dynamic > > binding or lexical binding and takes care of the scope of definition > > of the "nouns" ? > > [...] > > Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, > or comp.lang.python. ?Please trim the Newsgroups line. provide a rigorous proof that people are more interested in the nauseating nude pictures that you post of your mother in the newsgroups than in the subject of forth implementation. as a matter of fact a lot of people in various language groups are interested in implementation aspects and the languages borrow ideas from each other. now, get away from my thread and take away your odious posts which positively cause me nausea and vomiting. we will soon find out the game of stacks. > -- > Keith Thompson (The_Other_Keith) ks... at mib.org ? > Nokia > "We must do something. ?This is something. ?Therefore, we must do this." > ? ? -- Antony Jay and Jonathan Lynn, "Yes Minister" From mahaboobnisha at gmail.com Thu Aug 19 04:08:40 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Thu, 19 Aug 2010 01:08:40 -0700 (PDT) Subject: comp.lang.python Message-ID: www.127760.blogspot.com From a.j.romanista at gmail.com Thu Aug 19 04:29:51 2010 From: a.j.romanista at gmail.com (ata.jaf) Date: Thu, 19 Aug 2010 01:29:51 -0700 (PDT) Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> Message-ID: <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> On Aug 17, 11:55?pm, Thomas Jollans wrote: > On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > > > I am developing a little program in Mac with wxPython. > > But I have problems with the characters that are not in ASCII. Like > > some special characters in French or Turkish. > > So I am looking for a way to solve this. Like an encoding standard > > that supports all languages. Or some other way. > > Anything that supports all of Unicode will do. Like UTF-8. If your text is > mostly Latin, then just go for UTF-8, if you use other alphabets extensively, > you might want to consider UTF-16, which might the use a little less space. OK, I used UTF-8. I write a line of strings in the source code and I want my program to show that as an output on GUI. And this line of strings includes a character like "?". But I see that in GUI this character is replaced with another strange characters. I mean it doesn't work. And when I try to use UTF-16, I get an syntax error that declares "UTF-16 stream does not start with BOM". From jak at isp2dial.com Thu Aug 19 04:31:34 2010 From: jak at isp2dial.com (John Kelly) Date: Thu, 19 Aug 2010 08:31:34 +0000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> <8a12e419-447b-475d-9ec2-216f2d97c3cb@v41g2000yqv.googlegroups.com> Message-ID: On Thu, 19 Aug 2010 00:56:35 -0700 (PDT), Standish P wrote: >On Aug 18, 5:38?pm, Keith Thompson wrote: >> Standish P writes: >> > Show me on what page does it explain how Forth implements dynamic >> > binding or lexical binding and takes care of the scope of definition >> > of the "nouns" ? >> Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, >> or comp.lang.python. ?Please trim the Newsgroups line. >fact a lot of people in various language groups are interested in >implementation aspects and the languages borrow ideas from each other. Standish sounds like Spinoza in disguise. Nevertheless, ngs like c.l.c need more diversity. Standards minutia is boring. -- Web mail, POP3, and SMTP http://www.beewyz.com/freeaccounts.php From steve-REMOVE-THIS at cybersource.com.au Thu Aug 19 04:48:06 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 08:48:06 GMT Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: <4c6cefc6$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote: > On Aug 17, 11:55?pm, Thomas Jollans wrote: >> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: >> >> > I am developing a little program in Mac with wxPython. But I have >> > problems with the characters that are not in ASCII. Like some special >> > characters in French or Turkish. So I am looking for a way to solve >> > this. Like an encoding standard that supports all languages. Or some >> > other way. >> >> Anything that supports all of Unicode will do. Like UTF-8. If your text >> is mostly Latin, then just go for UTF-8, if you use other alphabets >> extensively, you might want to consider UTF-16, which might the use a >> little less space. > > OK, I used UTF-8. > I write a line of strings in the source code Do you have a source code encoding line at the start of your script? http://www.python.org/dev/peps/pep-0263/ > and I want my program to > show that as an output on GUI. And this line of strings includes a > character like "?". But I see that in GUI this character is replaced > with another strange characters. I mean it doesn't work. And when I try > to use UTF-16, I get an syntax error that declares "UTF-16 stream does > not start with BOM". What GUI are you using? Please COPY AND PASTE (do not retype) the EXACT error message you get, including the entire traceback. -- Steven From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 19 04:53:57 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 19 Aug 2010 10:53:57 +0200 Subject: Pop return from stack? In-Reply-To: <4c673375$0$11100$c3e8da3@news.astraweb.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c673375$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c6cf114$0$3325$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > > Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in > Python, even VB in Python, but this is the first time I've meet some one > who wants to write assembler in Python :) > +1 QOTW From martin at v.loewis.de Thu Aug 19 04:55:54 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Thu, 19 Aug 2010 10:55:54 +0200 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: <4C6CF19A.2060703@v.loewis.de> > I write a line of strings in the source code and I want my program to > show that as an output on GUI. And this line of strings includes a > character like "?". Make sure you use Unicode literals in your source code, i.e. u"?". HTH, Martin From bauketilma at gmail.com Thu Aug 19 04:56:02 2010 From: bauketilma at gmail.com (Duim) Date: Thu, 19 Aug 2010 01:56:02 -0700 (PDT) Subject: when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray' References: Message-ID: On Aug 18, 10:03?pm, Nobody wrote: > On Wed, 18 Aug 2010 05:56:27 -0700, Duim wrote: > > Although I'm sure somewhere this issue is discussed in this (great) > > group, I didn't know the proper search words for it (although I > > tried). > > > I'm using python (2.6) scientifically mostly, and created a simple > > class to store time series (my 'Signal' class). > > I need this class to have a possibility to get multiplied by an array, > > but pre and post multiplication have different mathematical outcomes > > ( basically A* B != B*A ) . > > > Post multiplication by an array works fine defining __mul__ in the > > Signal class, but pre multiplication does not. It keeps trying to > > multiply all elements separately instead to send this array to my > > __rmul__ function. > > > How can I fix this without the need for a separate > > 'multiplysignal(A,B)' function? > > Make Signal a subclass of numpy.ndarray. If one operand is a subclass of > the other, its __rmul__ will be preferred to the parent's __mul__. > > In the absence of a subclass-superclass relationship, the LHS's __mul__ is > preferred to the RHS's __rmul__, so the RHS's __rmul__ is only called if > the LHS lacks a __mul__ method or if the method refuses its argument > (returns NotImplemented). > > Likewise for other "reflected" methods. Great, many thanks. It seems to work well. For others looking into the same issue: http://www.scipy.org/Subclasses From iamforufriends at gmail.com Thu Aug 19 05:29:22 2010 From: iamforufriends at gmail.com (only adults no kids plzzz) Date: Thu, 19 Aug 2010 02:29:22 -0700 (PDT) Subject: adults only... no kida please. wanna meet me, sex with me. come...... Message-ID: <4f19162c-c645-430d-b3f8-d099caa783b1@h17g2000pri.googlegroups.com> adults only... no kida please. wanna meet me, sex with me. come...... just click.... start.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From fetchinson at googlemail.com Thu Aug 19 06:25:17 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 19 Aug 2010 12:25:17 +0200 Subject: path to data files Message-ID: If a python module requires a data file to run how would I reference this data file in the source in a way that does not depend on whether the module is installed system-wide, installed in $HOME/.local or is just placed in a directory from where the interpreter is fired up? I'd like to always keep the python source and the data file in the same directory, be it /usr/lib/python2.6/site-packages, $HOME/.local/lib/python2.6/site-packages or /arbitrary/path/to/somewhere. If the data file is called 'foo' and I simply do open('foo') in the python source file this will not work if they are both installed either system-wide or locally. More precisely if the module is called 'foo.py', data file called 'foo', they are both in /usr/lib/python2.6/site-packages and if foo.py I have open('foo') I'll get a file not found error. Any ideas? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From dan.kluev at gmail.com Thu Aug 19 06:32:49 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Thu, 19 Aug 2010 21:32:49 +1100 Subject: path to data files In-Reply-To: References: Message-ID: On Thu, Aug 19, 2010 at 9:25 PM, Daniel Fetchinson < fetchinson at googlemail.com> wrote: > If a python module requires a data file to run how would I reference > this data file in the source in a way that does not depend on whether > the module is installed system-wide, installed in $HOME/.local or is > just placed in a directory from where the interpreter is fired up? I'd > like to always keep the python source and the data file in the same > directory, be it /usr/lib/python2.6/site-packages, > $HOME/.local/lib/python2.6/site-packages or > /arbitrary/path/to/somewhere. > open(os.path.join(os.path.dirname(__file__), 'foo')) -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From spinoza1111 at yahoo.com Thu Aug 19 07:14:42 2010 From: spinoza1111 at yahoo.com (spinoza1111) Date: Thu, 19 Aug 2010 04:14:42 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: On Aug 18, 1:44?am, James Kanze wrote: > On Aug 17, 6:21 pm, Standish P wrote: > > > > Garbage collection doesn't use a stack. It uses a "heap", > > > which is in the abstract a collection of memory blocks of > > > different lengths, divided into two lists, generally > > > represented as linked lists: > > > 1. ?A list of blocks that are free and may be used to store > > > new data > > > 2. ?A list of blocks that are in use, or haven't been freed (yet) > > Is this all that a heap is or is there more to it ? > > There are many different ways to implement a heap. ?The above is > not a good one, and I doubt that it's really used anywhere. Actually, that's the only way to implement a heap in the abstract. Forest and trees, mate. Mathematically a heap is a block of storage, a list of free blocks and a list of allocated blocks. All the rest is detail for the little techies to normally, get wrong. The confusion between scientific and technical progress is a mirror of the (far more serious) confusion between scientific progress and ethical advance. Sure, when you free a block it is a good idea to see if you can join it with its neighbors to get the biggest "bang for the buck". This, again, is a detail relative to the grand plan which gives only techies a hard-on, because the way scientific is confused with technical progress is, in Foucault's terms, capillary. Part of ethical regression is the overemphasis on efficiency and metaphors taken from America's genocidal first use of nuclear weapons. > > > I have been looking for simple but complete explanation of > > heap for a while and not gotten to it. > > Complete in what sense? ?The basic principle of how to use it is > simple. ?As for how to implement it, there are many different > algorithms that can be used. Correct, for a change. > > > I think I am looking for a stack allocation on the same > > pattern. > > Stack allocation is far, far simpler (usually). And very different. > > > In a disk, a file is fragmented in many contiguous blocks and > > is accessed automatically. > > At the system level, the same thing holds for memory, and the > actual physical memory is "fragmented" into contiguous blocks, > each the size of a page. ?The MMU (hardware) makes this > transparent to user programs, however. > > > > There is no way you could do memory management of all but the most > > > trivial and fixed-length data chunks using a stack. > > The length isn't the issue. ?The order of allocation and freeing > is. ?(For many specific uses, stack based allocators can and > have been used, but they don't work for generally allocation.) > > -- > James Kanze From fetchinson at googlemail.com Thu Aug 19 07:18:15 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 19 Aug 2010 13:18:15 +0200 Subject: path to data files In-Reply-To: References: Message-ID: >> If a python module requires a data file to run how would I reference >> this data file in the source in a way that does not depend on whether >> the module is installed system-wide, installed in $HOME/.local or is >> just placed in a directory from where the interpreter is fired up? I'd >> like to always keep the python source and the data file in the same >> directory, be it /usr/lib/python2.6/site-packages, >> $HOME/.local/lib/python2.6/site-packages or >> /arbitrary/path/to/somewhere. >> > > open(os.path.join(os.path.dirname(__file__), 'foo')) Thanks a lot! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From python.list at tim.thechases.com Thu Aug 19 07:32:55 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Aug 2010 06:32:55 -0500 Subject: String substitution VS proper mysql escaping In-Reply-To: References: <4C6BA2C4.4000309@gmail.com> Message-ID: <4C6D1667.7090904@tim.thechases.com> On 08/19/10 02:10, ????? wrote: >> ("nikos",) is a single element tuple. >> ["nikos"] is a single element list. >> ["nikos",] is also a single element list, just written like the tuple. > > It makes more sense if i: > > "nikos" is just a string > ("nikos") is a single element tuple > ["nikos"] is also a single element list > > After all () used to define tuples and [] usedd to define lists. Why > commas? You have to look at the other side: what *else* they're used for. Python also uses () to override order of operations (and to call functions, but that's contextually different) which can occur in the same context as tuples, while [] are used only within contexts where they can be disambiguated. Going back to one of the originals example posted in this thread: (1) + (2) do you think this should yield (1, 2) or 3? It would be crazy if evaluation of (3*14) + (7*21) was reduced, treated as "(42) + (147)" and then reduced to "(42,147)" instead of 189. So Python needs a way to express that you *explicitly* mean "this is one of those rare one-element tuples, not an order of operations prioritization": (1,) + (2,) to return "(1,2)" > Also is there a difference between 'nikos' or "nikos" or '''nikos''' ? > What's and why best to use to enclose strings? Internally, there's no difference other than how easily you can include " or ' characters in your string. Thus you might write: with_dquote = 'He said "Hello"' with_apos = "It's 2:00am" with_both1 = """She said "Don't touch me" to her boss""" with_both2 = '''She said "Don't touch me" to her boss''' You can also prefix any of them with "r" such as file_path = r"c:\path\to\file.txt" file_path = r'c:\path\to\file.txt file_path = r"""c:\path\to\file.txt""" file_path = r'''c:\path\to\file.txt''' to alter how "\" are treated. Otherwise, if it doesn't make a difference, I tend to use C-ish conventions of using " for strings and ' for single characters: if 'w' in "hello world": but the important/kind thing is to be internally consistent to make your own life easier. :) -tkc From __peter__ at web.de Thu Aug 19 07:35:01 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 13:35:01 +0200 Subject: Unsupported Format Character '&' (0x26) References: Message-ID: Andrew Evans wrote: > On Wed, Aug 18, 2010 at 4:35 PM, Andrew Evans wrote: > >> I get an error message "Unsupported Format Character '&' (0x26)" I >> narrowed it down to these two variables >> >> any idea how to fix it? >> >> SEARCH_URL_0 = "http://search.yahoo.com/search...?p=%(query)..." > nvm I got it by adding s and d respectively after each value eg %(query)s If you want to handle this reliably have a look at urllib.urlencode(). Peter From sschwarzer at sschwarzer.net Thu Aug 19 07:41:11 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 19 Aug 2010 13:41:11 +0200 Subject: String substitution VS proper mysql escaping In-Reply-To: References: <4C6BA2C4.4000309@gmail.com> Message-ID: <4C6D1857.1070307@sschwarzer.net> Hi ?????, On 2010-08-19 09:10, ????? wrote: > On 18 ???, 12:50, Cameron Simpson wrote: >> >> ("nikos",) is a single element tuple. >> ["nikos"] is a single element list. >> ["nikos",] is also a single element list, just written like the tuple. > > It makes more sense if i: > > "nikos" is just a string > ("nikos") is a single element tuple > ["nikos"] is also a single element list > > After all () used to define tuples and [] usedd to define lists. Why > commas? Because parentheses are also used to group expressions. For example, >>> 2 * (1+2) 6 If it were as you would like, the result would have been (3, 3) So because inside parentheses already denotes an expression you have to add a comma to distinguish a one-element tuple from an expression. Stefan From agidak at gmail.com Thu Aug 19 08:22:23 2010 From: agidak at gmail.com (Agida Kerimova) Date: Thu, 19 Aug 2010 17:22:23 +0500 Subject: How do I make python test.py work without a syntax error msg? Message-ID: I am new to programming/python and have been having some difficulties getting started. I can't seem to run scripts without a syntax error msg. When I drag the file to the IDLE launcher or run the module it works, but when I actually type it I get an error msg. I've been told that the path to python executable is missing or that i have to specify the path but im not sure how to do this. I read some articles online but they are not very clear. A lot of the articles talk about doing this on windows but i have a mac. Also when I type python at the prompt it starts. Can someone please let me know what Im doing wrong or give me some advice? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.gonnerman at newcenturycomputers.net Thu Aug 19 08:30:03 2010 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 19 Aug 2010 07:30:03 -0500 Subject: [Python] Unsupported Format Character '&' (0x26) In-Reply-To: References: Message-ID: <4C6D23CB.70805@newcenturycomputers.net> On 08/18/2010 06:35 PM, Andrew Evans wrote: > I get an error message "Unsupported Format Character '&' (0x26)" I > narrowed it down to these two variables > > any idea how to fix it? > > SEARCH_URL_0 = > "http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)&fr=sfp&fr2=&iscqry= > " > NEXT_PAGE_0 = > "http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)&fr=sfp&xargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2E&pstart=%(start)&b=11 > " > Not %(query) Should be %(query)s The 's' means "string." -- Chris. From alain at dpt-info.u-strasbg.fr Thu Aug 19 08:30:34 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 19 Aug 2010 14:30:34 +0200 Subject: path to data files References: Message-ID: <87wrrm9445.fsf@dpt-info.u-strasbg.fr> Daniel Fetchinson writes: > If a python module requires a data file to run how would I reference > this data file in the source in a way that does not depend on whether > the module is installed system-wide, installed in $HOME/.local or is > just placed in a directory from where the interpreter is fired up? sys.path[0] is supposed to contain the script's directory. -- Alain. From smirnoffs at gmail.com Thu Aug 19 08:53:30 2010 From: smirnoffs at gmail.com (Sergey Smirnov) Date: Thu, 19 Aug 2010 15:53:30 +0300 Subject: How do I make python test.py work without a syntax error msg? In-Reply-To: References: Message-ID: *when I actually * *type it I get an error msg* Did you type python commands in a bash console? In case you did, you should run python interactive console instead. Just type python in terminal window and than you'll be able interactively run statements. If you have your script saved in a file, for instance, script.py, to run it on your Mac you should type: $ python script.py It would be easier to understand you if you'll post errors messages here. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anton at mips.complang.tuwien.ac.at Thu Aug 19 09:45:07 2010 From: anton at mips.complang.tuwien.ac.at (Anton Ertl) Date: Thu, 19 Aug 2010 13:45:07 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <7xwrrnmzkx.fsf@ruckus.brouhaha.com> <4c6c4ec8$0$1623$742ec2ed@news.sonic.net> Message-ID: <2010Aug19.154507@mips.complang.tuwien.ac.at> John Nagle writes: > In the superscalar era, there's not much of an advantage to avoiding >stack accesses. Apart from 4stack, I am not aware of a superscalar stack machine (and 4stack is more of an LIW than a superscalar). OTOH, if by stack accesses you mean memory accesses through the stack pointer on a register machine, then evidence contradicts your claim. E.g., if we can keep one or two more of Gforth's VM's registers in real registers rather than on the stack of an IA32 CPU, we see significant speedups (like a factor of 2). >x86 superscalar machines have many registers not >visible to the program, as the fastest level of cache. They have a data cache for memory accesses (about 3 cycles load-to-use latency on current CPUs for these architectures), and they have rename registers (not visible to programmers) that don't cache memory. They also have a store buffer with store-to-load forwarding, but that still has no better load-to-use latency. >In practice, >the top of the stack is usually in CPU registers. Only if the Forth system is written that way. > The "huge number >of programmer-visible register" machines like SPARCs turned out to be >a dead end. Really? Architectures with 32 programmer-visible registers like SPARC (but, unlike SPARC, without register windows) are quite successful in embedded systems (e.g., MIPS, SPARC). >So did making all the instructions the same width; it >makes the CPU simpler, but not faster, and it bulks up the program >by 2x or so. In the beginning it also made the CPU faster. As for the bulk, here's some data from <2007Dec11.202937 at mips.complang.tuwien.ac.at>; it's the text (code) size of /usr/bin/dpkg in a specific version of the dpkg package: .text section 98132 dpkg_1.14.12_hurd-i386.deb 230024 dpkg_1.14.12_m68k.deb 249572 dpkg_1.14.12_amd64.deb 254984 dpkg_1.14.12_arm.deb 263596 dpkg_1.14.12_i386.deb 271832 dpkg_1.14.12_s390.deb 277576 dpkg_1.14.12_sparc.deb 295124 dpkg_1.14.12_hppa.deb 320032 dpkg_1.14.12_powerpc.deb 351968 dpkg_1.14.12_alpha.deb 361872 dpkg_1.14.12_mipsel.deb 371584 dpkg_1.14.12_mips.deb 615200 dpkg_1.14.12_ia64.deb Sticking with the Linux packages (i.e., not the Hurd one), the range in code size increase over the i386 code is 0.97 (ARM) to 1.41 (MIPS) for the classical architectures with fixed-size instructions (RISCs). Only the IA64 has a code size increase by a factor of 2.33. Note that code size is not everything that's in a program binary, and the rest should be unaffected by whether the instructions are fixed-size or variable-sized, so the overall effect on the binary will be smaller. - anton -- M. Anton Ertl http://www.complang.tuwien.ac.at/anton/home.html comp.lang.forth FAQs: http://www.complang.tuwien.ac.at/forth/faq/toc.html New standard: http://www.forth200x.org/forth200x.html EuroForth 2010: http://www.euroforth.org/ef10/ From benjamin.kaplan at case.edu Thu Aug 19 10:08:28 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 19 Aug 2010 10:08:28 -0400 Subject: How do I make python test.py work without a syntax error msg? In-Reply-To: References: Message-ID: On Thu, Aug 19, 2010 at 8:22 AM, Agida Kerimova wrote: > I am new to programming/python and have been having some difficulties > getting started. I can't seem to run scripts without a syntax error msg. > When I drag the file to the IDLE launcher or run the module it works, but > when I actually type it I get an error msg. I've been told ?that the path to > python executable is missing or that i have to specify the path but im not > sure how to do this. I read some articles online but they are not very > clear. A lot of the articles talk about doing this on windows but i have a > mac. Also when I type python at the prompt it starts. Can someone please let > me know what Im doing wrong or give me some advice? > Thanks! > -- Are you trying to run ./test.py? If so, make sure you use a shebang line. The Unix shell doesn't care about those silly little things called file extensions- that's just part of the file name, after all. Any executed file will use the shell (bash on OS X) unless you specify otherwise. Add the following line to the top of the file: #!/usr/bin/env python Or, just call the Python interpreter directly python test.py From smirnoffs at gmail.com Thu Aug 19 10:15:19 2010 From: smirnoffs at gmail.com (Sergey Smirnov) Date: Thu, 19 Aug 2010 17:15:19 +0300 Subject: How do I make python test.py work without a syntax error msg? In-Reply-To: References: Message-ID: I see. Your script begins with a string: $ python test.py It's not a valid python code. Maybe you just copied this text to your script accidentally. Try to delete the first string. Can you send a few first strings of your script? On Thu, Aug 19, 2010 at 17:05, Agida Kerimova wrote: > this is what it looks like > > > On Thu, Aug 19, 2010 at 7:01 PM, Agida Kerimova wrote: > >> Hi, I don't know how to work in a non bash console... I typed python in a >> terminal window and all but it didn't work... >> >> >> >> >> >> >> On Thu, Aug 19, 2010 at 5:53 PM, Sergey Smirnov wrote: >> >>> *when I actually * >>> >>> *type it I get an error msg* >>> >>> Did you type python commands in a bash console? In case you did, you >>> should run python interactive console instead. Just type python in terminal >>> window and than you'll be able interactively run statements. >>> >>> If you have your script saved in a file, for instance, script.py, to run >>> it on your Mac you should type: >>> $ python script.py >>> >>> It would be easier to understand you if you'll post errors messages here. >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwutzke at web.de Thu Aug 19 10:21:56 2010 From: kwutzke at web.de (Karsten Wutzke) Date: Thu, 19 Aug 2010 07:21:56 -0700 (PDT) Subject: Contains/equals Message-ID: Hello, I have an object which has a list of other complex objects. How do I best achieve a complex "contains" comparison based on the object's class? In Java terms, I'm looking for an equivalent to equals(Object) in Python. Does a similar thing exist? Directions appreciated. Karsten From kara at kara-moon.com Thu Aug 19 10:27:34 2010 From: kara at kara-moon.com (Rony) Date: Thu, 19 Aug 2010 07:27:34 -0700 (PDT) Subject: Creating a PYD file Message-ID: Is a PYD file created from Pyrex faster in execution then a PYD file created from python source ? Tia Rony From invalid at invalid.invalid Thu Aug 19 10:42:06 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 19 Aug 2010 14:42:06 +0000 (UTC) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> <4c6c9dc4$0$28637$c3e8da3@news.astraweb.com> Message-ID: On 2010-08-19, Russ P. wrote: > And I'd still like to know if the "1st" element of aList is aList[0] > or aList[1]. aList[0] -- Grant Edwards grant.b.edwards Yow! I'm definitely not at in Omaha! gmail.com From downaold at gmail.com Thu Aug 19 10:42:32 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 19 Aug 2010 16:42:32 +0200 Subject: 79 chars or more? In-Reply-To: <4C6BA05C.2000906@sequans.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <20100817114256.d960549b.darcy@druid.net> <4C6BA05C.2000906@sequans.com> Message-ID: <18620C4D-A6F9-4248-ADF7-5CE3EDDE4491@gmail.com> Dear Jean-Michel, On Aug 18, 2010, at 10:57 AM, Jean-Michel Pichavant wrote: > At least, if you still want to stick with 79 chars, do something like > > text = find(response, 'MPNExpirationDate', ).text > self.expiration_date = translate_date(text,'%Y-%m-%d', '%m%d%Y') I don't necessarily like this example *so* much. I have no real problem with it, and maybe would write it myself sometimes, but I'm curious what people think of the following reasoning. I think that, for optimal readability, variable names should reflect the role if the function/class/module of the variable they refer to. If you stick to this convention, a function can normally be read very easily by just scanning through the left part of assignment statements. In your case, it looks like text would better be called expiration_text, or something like that. But what I would like better, is: self.expiration_date = translate_date( text = find(response, 'MPNExpirationDate', ).text, format1 = '%Y-%m-%d', # I don't know the argument name format2 = '%m%d%Y', # ... and of this one neither ) Moreover, the 'text = ...'-like statement, that are only used in the one statement after it, often interrupt a (more) logical sequence of variable assignments, and make your program a bit less readable. Cheers, Roald From __peter__ at web.de Thu Aug 19 10:47:46 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 16:47:46 +0200 Subject: Contains/equals References: Message-ID: Karsten Wutzke wrote: > I have an object which has a list of other complex objects. How do I > best achieve a complex "contains" comparison based on the object's > class? In Java terms, I'm looking for an equivalent to equals(Object) > in Python. Does a similar thing exist? Directions appreciated. I can't infer from your question whether you already know about __contains__(). So there: >>> class Cornucopia: ... def __contains__(self, other): ... return True ... >>> c = Cornucopia() >>> 42 in c True >>> "cherry pie" in c True >>> c in c True From kwutzke at web.de Thu Aug 19 10:53:32 2010 From: kwutzke at web.de (Karsten Wutzke) Date: Thu, 19 Aug 2010 07:53:32 -0700 (PDT) Subject: Contains/equals References: Message-ID: <8b1f1392-9d94-46cf-bd1b-5b041d0cb508@f42g2000yqn.googlegroups.com> On Aug 19, 4:47?pm, Peter Otten <__pete... at web.de> wrote: > Karsten Wutzke wrote: > > I have an object which has a list of other complex objects. How do I > > best achieve a complex "contains" comparison based on the object's > > class? In Java terms, I'm looking for an equivalent to equals(Object) > > in Python. Does a similar thing exist? Directions appreciated. > > I can't infer from your question whether you already know about > __contains__(). So there: > > >>> class Cornucopia: > > ... ? ? def __contains__(self, other): > ... ? ? ? ? ? ? return True > ...>>> c = Cornucopia() > >>> 42 in c > True > >>> "cherry pie" in c > True > >>> c in c > > True Whoops that easy... Thanks! Karsten From mehgcap at gmail.com Thu Aug 19 11:00:03 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 19 Aug 2010 11:00:03 -0400 Subject: Contains/equals In-Reply-To: References: Message-ID: On 8/19/10, Peter Otten <__peter__ at web.de> wrote: > Karsten Wutzke wrote: > >> I have an object which has a list of other complex objects. How do I >> best achieve a complex "contains" comparison based on the object's >> class? In Java terms, I'm looking for an equivalent to equals(Object) >> in Python. Does a similar thing exist? Directions appreciated. > > I can't infer from your question whether you already know about > __contains__(). So there: > >>>> class Cornucopia: > ... def __contains__(self, other): > ... return True > ... >>>> c = Cornucopia() >>>> 42 in c > True >>>> "cherry pie" in c > True >>>> c in c > True You may also want to use the double equals operator; in Java, one thing I wish I could do is String s="abc"; String t="def"; if(s==t)... In Python, as I understand it, you can define this behavior. class c(object): def __init__(self, a=1, b=2): self.a=a; self.b=b def __eq__(self, obj): if self.a==obj.a and self.b==obj.b: return True return False You can now say: obj1=c() obj2=c() print(obj1==obj2) #prints True > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From cri at tiac.net Thu Aug 19 11:25:51 2010 From: cri at tiac.net (Richard Harter) Date: Thu, 19 Aug 2010 15:25:51 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> <518b97c6-78ad-4ce9-9967-c7f72ea74109@5g2000yqz.googlegroups.com> Message-ID: <4c6d356f.608280081@text.giganews.com> On Wed, 18 Aug 2010 01:39:09 -0700 (PDT), Nick Keighley wrote: >On 17 Aug, 18:34, Standish P wrote: >> How are these heaps being implemented ? Is there some illustrative >> code or a book showing how to implement these heaps in C for example ? > >any book of algorithms I'd have thought > >http://en.wikipedia.org/wiki/Dynamic_memory_allocation >http://www.flounder.com/inside_storage_allocation.htm > >I've no idea how good either of these is The wikipedia page is worthless. The flounder page has substantial meat, but the layout and organization is a mess. A quick google search didn't turn up much that was general - most articles are about implementations in specific environments. From lists at cheimes.de Thu Aug 19 11:27:05 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 19 Aug 2010 17:27:05 +0200 Subject: Contains/equals In-Reply-To: References: Message-ID: Am 19.08.2010 17:00, schrieb Alex Hall: > In Python, as I understand it, you can define this behavior. > > class c(object): > def __init__(self, a=1, b=2): > self.a=a; self.b=b > > def __eq__(self, obj): > if self.a==obj.a and self.b==obj.b: return True > return False Yes, but you have to return NotImplemented when your type doesn't know how to handle the other type. class C(object): def __eq__(self, other): if not isinstance(other, C): return NotImplemented return self.a == other.a Christian From nikos.the.gr33k at gmail.com Thu Aug 19 11:42:02 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Thu, 19 Aug 2010 18:42:02 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D1667.7090904@tim.thechases.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> Message-ID: <4C6D50CA.5060604@gmail.com> ???? 19/8/2010 2:32 ??, ?/? Tim Chase ??????: > So Python needs a way to express that you *explicitly* mean "this is > one of those rare one-element tuples, not an order of operations > prioritization": > > (1,) + (2,) > to return "(1,2)" Yes i can see the difference now!! I just had to look at the big picture here! There is no other way of seperating this for that. > You can also prefix any of them with "r" such as > > file_path = r"c:\path\to\file.txt" > file_path = r'c:\path\to\file.txt > file_path = r"""c:\path\to\file.txt""" > file_path = r'''c:\path\to\file.txt''' 'r' is to avoid escaping backslashes only or other special charcaters as well? As for the string i noticed that if i'am to mix single quotes and double quotes(any number of them not just always pairs) and backslashes and other special stuff in them then i'm best off using 3-sinlge-quotes like name='''My name is "Nikos" and i'am from Thessaloniki\Greece''' The above example can only be written by using 3-single quoting right? Not by pairs of single or double quotes, correct? And i dont have to use the 'r' in fornt of it too. ======================= Also if you please comment on my mysql string substitution example i've posted in my previous post just to make it work. I want it to be able to delete my data but it fails when i try to http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors" please try it yourself, i dont mind lossign the data i just want to see if this mysql in jection can actually work. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Thu Aug 19 11:44:29 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Thu, 19 Aug 2010 18:44:29 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D1667.7090904@tim.thechases.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> Message-ID: <4C6D515D.2020304@gmail.com> ???? 19/8/2010 2:32 ??, ?/? Tim Chase ??????: > (1,) + (2,) > > to return "(1,2)" This is actually joining two single element tuples (1,) and (2, ) to a new bigger tuple of two elements, correct? From margieroginski at gmail.com Thu Aug 19 11:45:52 2010 From: margieroginski at gmail.com (Margie Roginski) Date: Thu, 19 Aug 2010 08:45:52 -0700 (PDT) Subject: How to see intermediate fail results from unittest as tests are running? References: Message-ID: <7cc5e61e-604e-4b10-87f0-4104296ca909@v41g2000yqv.googlegroups.com> On Aug 19, 12:41?am, Peter Otten <__pete... at web.de> wrote: > Margie Roginski wrote: > > I am using unittest in a fairly basic way, where I have a single file > > that simply defines a class that inherits from unittest.TestCase and > > then within that class I have a bunch of methods that start with > > "test". ?Within that file, at the bottom I have: > > > if __name__ == "__main__": > > ? ? unittest.main() > > > This works fine and it runs all of the testxx() methods in my file. > > As it runs it prints if the tests passed or failed, but if they fail, > > it does not print the details of the assert that made them fail. ?It > > collects this info up and prints it all at the end. > > > Ok - my question: Is there any way to get unittest to print the > > details of the assert that made a test fail, as the tests are > > running? ?IE, after a test fails, I would like to see why, rather than > > waiting until all the tests are done. > > Not exactly what you're asking for, but 2.7 has grown a --failfast option > that tells unittest to stop on the first failure. For older Python versions > you can use nose > > nosetests -x myscript.py > > athttp://somethingaboutorange.com/mrl/projects/nose/0.11.2/ > or the unittest backport athttp://pypi.python.org/pypi/unittest2 > > Peter Thanks for the pointers, I will give those a try. Margie From vicente.soler at gmail.com Thu Aug 19 11:55:09 2010 From: vicente.soler at gmail.com (vsoler) Date: Thu, 19 Aug 2010 08:55:09 -0700 (PDT) Subject: Reading the access attributes of directories in Windows Message-ID: Hello everyone! I need to read, for each of the directories in a shared file server unit, who has access to the directories and what type of access privileges. This is something that I can easily do interactively in my Windows Document Explorer by right clicking a single directory, clicking on Properties, then on Security. There I can see the Users and Group of Users that have access to the selected directory, as well as the type of access to that directory (Read/Write/eXecute etc.) Since I have to prepare a new access scheme, I first need to read what the current situation is. I've been looking in the "os" library, and found the "os.chmod" method but I am not sure that it is going to give me what I need. Should I also used library "stat"? So far I have not been able to find my way to the solution of this problem. Googling the web, I have seen that some examples provive some kind of information but using codes (755 or 0577) that I shoud translate to some form of understandable text messages. I think that my problem consists of finding the correct library/method to get the solution. Can anybody help? Thank you Using Python 3.1 on Windows Vista From python.list at tim.thechases.com Thu Aug 19 11:58:07 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Aug 2010 10:58:07 -0500 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D50CA.5060604@gmail.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> <4C6D50CA.5060604@gmail.com> Message-ID: <4C6D548F.2050303@tim.thechases.com> On 08/19/10 10:42, Nik Gr wrote: >> You can also prefix any of them with "r" such as >> >> file_path = r"c:\path\to\file.txt" >> file_path = r'c:\path\to\file.txt >> file_path = r"""c:\path\to\file.txt""" >> file_path = r'''c:\path\to\file.txt''' > > 'r' is to avoid escaping backslashes only or other special charcaters as > well? Yes, just backslashes. > As for the string i noticed that if i'am to mix single quotes and double > quotes(any number of them not just always pairs) > and backslashes and other special stuff in them then i'm best off using > 3-sinlge-quotes like > > name='''My name is "Nikos" and i'am from Thessaloniki\Greece''' > > The above example can only be written by using 3-single quoting right? > Not by pairs of single or double quotes, correct? It can be written as a non-3-quote string, you just have to escape the inner quotes (single & double) and the backslash to be seen: name = 'My name is Nikos and I\'m from Thessaloniki\\Greece' name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece" > And i dont have to use the 'r' in fornt of it too. Using the 'r' in front would make it much more challenging, because it would prevent the backslashes from being seen as escaping. :) >> (1,) + (2,) >> >> to return "(1,2)" > > This is actually joining two single element tuples (1,) and (2, ) to a > new bigger tuple of two elements, correct? Correct. > Also if you please comment on my mysql string substitution example i've > posted in my previous post just to make it work. There's a number of variables which can impact the exact string that would need to be passed, so it's not a trivial thing to do. You may or may not be un-escaping HTML entities in the GET parameters ("%20" -> a space, etc), and I don't have a readily available way to duplicate your environment, so testing becomes a bit harder. Hopefully others on the list can give you a hand on breaking your code. -tkc From chris at simplistix.co.uk Thu Aug 19 11:58:30 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 19 Aug 2010 16:58:30 +0100 Subject: bug? context managers vs ImportErrors Message-ID: <4C6D54A6.4060107@simplistix.co.uk> Hi All, Am I right in thinking this is a bug: class MyContextManager: def __enter__(self): pass def __exit__(self,t,e,tb): print type(t),t print type(e),e with MyContextManager(): import foo.bar.baz ...when executed, gives me: No module named foo.bar.baz Why is 'e' ending up as a string rather than the ImportError object? This is with Python 2.6.5 if that makes a difference... Chris From info at egenix.com Thu Aug 19 11:59:29 2010 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 19 Aug 2010 17:59:29 +0200 Subject: ANN: eGenix mxODBC - Python ODBC Database Interface 3.1.0 Message-ID: <4C6D54E1.1090606@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC - Python ODBC Database Interface Version 3.1.0 mxODBC is our commercially supported Python extension providing ODBC database connectivity to Python applications on Windows, Mac OS X, Unix and BSD platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-3.1.0-GA.html ________________________________________________________________________ INTRODUCTION mxODBC provides an easy-to-use, high-performance, reliable and robust Python interface to ODBC compatible databases such as MS SQL Server, MS Access, Oracle Database, IBM DB2 and Informix , Sybase ASE and Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many more: http://www.egenix.com/products/python/mxODBC/ The "eGenix mxODBC - Python ODBC Database Interface" product is a commercial extension to our open-source eGenix mx Base Distribution: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ NEWS The new mxODBC 3.1.0 release comes with many new features and supports more ODBC drivers, manager and platforms than ever before. Release Highlights ------------------ * We've added Python 2.7 support and builds for all platforms. * mxODBC 3.1 adds native support for the Windows 64-bit platforms as well as the Mac OS X 10.6 (Snow Leopard) 64-bit builds of Python. * mxODBC now fully supports the Oracle Instant Client ODBC driver. * We have updated the support for the latest IBM DB2 9.7 ODBC drivers and enhanced compatibility of mxODBC with the MS SQL Server Native Client ODBC driver on Windows and the Sybase ASE 15 ODBC drivers on Unix. * mxODBC 3.1 adds support for large-scale data warehouse databases Netezza and Teradata. * In addition to the Windows, Mac OS X, iODBC and unixODBC ODBC driver managers, we now also include support for the DataDirect ODBC manager. * The 64-bit support on Unix platforms was updated to support the new unixODBC 2.3.0 version. * We've improved the documentation on how to connect to various popular databases and now include many tips & tricks for each database/driver. * The Python 2.7 memoryview object is now supported as binary data container. * We have simplified handling of database warnings using a new customizable .warningformat attribute. * The catalog methods now accept both Unicode and 8-bit strings as parameters. * You can now select whether to use ANSI (8-bit) or Unicode ODBC APIs in the ODBC drivers, removing unnecessary data conversions and enhancing ODBC driver compatibility. For the full set of changes please check the mxODBC change log: http://www.egenix.com/products/python/mxODBC/changelog.html Feature Highlights ------------------ * Python Database API 2.0 Compliance: the mxODBC API is fully Python DB-API 2.0 compatible and implements a large number of powerful extensions. * Support for all popular ODBC Drivers: mxODBC includes adjustments and work-arounds to support MS SQL Server Native Client, MS SQL Server ODBC Driver, FreeTDS ODBC Driver, Oracle Instant Client ODBC Driver, IBM DB2 ODBC Driver, Sybase ASE ODBC Driver, Netezza ODBC Driver, Teradata ODBC Driver, PostgreSQL ODBC Driver, MySQL ODBC Driver, .MaxDB ODBC Driver as well as the ODBC driver sets of EasySoft, DataDirect, OpenLink, Actual Technologies. * Support for all popular ODBC Driver Managers: mxODBC comes with subpackages for the native Windows and Mac OS X ODBC managers, as well as the ODBC managers unixODBC, iODBC and DataDirect, which are commonly used on Unix systems. * Stable, robust and reliable:the mxODBC API has been in active production use for more than 10 years. * Full Python Support: mxODBC works with Python 2.3, 2.4, 2.5, 2.6 and 2.7. * Full 64-bit Support: mxODBC runs on the following 64-bit platforms: Windows, Linux, FreeBSD and Mac OS X. For the full set of features mxODBC has to offer, please see: http://www.egenix.com/products/python/mxODBC/#Features New mxODBC Editions ------------------- Due to popular demand, we have extended the set of available mxODBC editions and included a new low-cost standard edition. mxODBC is now available in thesethree editions: * The low-cost Standard Edition which provides data connectivity to a selected set of database backends. * The Professional Edition, which gives full access to all mxODBC features. * The Product Development Edition, which allows including mxODBC in applications you develop. At the same time we have simplified our license terms to clarify the situation on multi-core and virtual machines. In most cases, you no longer need to purchase more than one license per processor or virtual machine, scaling down the overall license costs significantly compared to earlier mxODBC releases. For a complete overview of the new editions, please see the product page. http://www.egenix.com/products/python/mxODBC/#mxODBCEditions ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/mxODBC/ In order to use the eGenix mxODBC package you will first need to install the eGenix mx Base package: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ UPGRADING Users are encouraged to upgrade to this latest mxODBC release to benefit from the new features and updated ODBC driver support. We have taken special care, not to introduce backwards incompatible changes, making the upgrade experience as smooth as possible. Customers who have purchased mxODBC 2.0, 2.1 or 3.0 licenses can upgrade their licenses using the mxODBC Professional Edition Upgrade License. If you want to try the new release before purchace, you can request 30-day evaluation licenses by visiting our web-site http://www.egenix.com/products/python/mxODBC/#Evaluation or by writing to sales at egenix.com, stating your name (or the name of the company) and the number of eval licenses that you need. _______________________________________________________________________ SUPPORT Commercial support for this product is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. _______________________________________________________________________ INFORMATION About Python (http://www.python.org/): Python is an object-oriented Open Source programming language which runs on all modern platforms. By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for today's IT challenges. About eGenix (http://www.egenix.com/): eGenix is a software project, consulting and product company focusing on expert services and professional quality products for companies, Python users and developers. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 19 2010) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From kst-u at mib.org Thu Aug 19 12:00:52 2010 From: kst-u at mib.org (Keith Thompson) Date: Thu, 19 Aug 2010 09:00:52 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> <8a12e419-447b-475d-9ec2-216f2d97c3cb@v41g2000yqv.googlegroups.com> Message-ID: Standish P writes: > On Aug 18, 5:38?pm, Keith Thompson wrote: [...] >> Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, >> or comp.lang.python. ?Please trim the Newsgroups line. > > provide a rigorous proof that people are more interested in the > nauseating nude pictures that you post of your mother in the > newsgroups than in the subject of forth implementation. [snip] *plonk* -- Keith Thompson (The_Other_Keith) kst-u at mib.org Nokia "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" From jbbrown at sunflower.kuicr.kyoto-u.ac.jp Thu Aug 19 12:07:53 2010 From: jbbrown at sunflower.kuicr.kyoto-u.ac.jp (J.B. Brown) Date: Fri, 20 Aug 2010 01:07:53 +0900 Subject: Python "why" questions In-Reply-To: <4C5EF1DF.3090007@mrabarnett.plus.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> Message-ID: 2010/8/9 MRAB : > Default User wrote: >> >> Not to prolong a good "food fight", but IIRC, many years ago in QBasic, >> one could choose >> >> OPTION BASE 0 >> >> or >> >> OPTION BASE 1 >> When I wrote my own C++ 2-D matrix class, I wrote a member function which did exactly this - allow you to specify the initial index value. Then users of my class (mainly my research lab coworkers) could specify whichever behavior they wanted. In terms of providing readable code and removing beginning programmer confusion, why not extend python lists by using something similar to (but not necessarily identical to) the C++ STL containers: C++ int myX[ ] = { 1,2,3,4,5 }; std::vector vectorX( myX, &myX[ sizeof( myX ) - 1 ] ); std::cout << vectorX.begin() << std::endl; std::cout << vectorX.end() << std::endl; Python x = [ 1 , 2 , 3 , 4 , 5 ] print x.first() print x.last() , where the first and last behavior of python is to return a deep copy of the object, and not a pointer. It seems that this would avoid complaints about the 0/1 issue. Of course, the problem is the behavior of: myList = [ myObject1, myObject2, myObject3, ... , myObjectLast ] print myList.first() + 5 , in which one will conceptually might want to get the 6th item in a list, though if first() is defined to return the object, then we get the returned object plus 5, if such behavior is defined to exist. I completely acknowledge that the behavior is not well defined, and that is why I am not proposing this as a final implementation, but rather as a concept and motivation. For those who don't like Python's 0-based indexing, why not just build a wrapper type which features an item() method that handles the internal conversion from 1 to 0 as the starting index? Better yet, include a method which sets/specifies the 0/1 behavior, and have item() reference the 0/1 setting to obtain the proper offset. Just a thought. J.B. Brown Kyoto University From randrange at gmail.com Thu Aug 19 12:34:08 2010 From: randrange at gmail.com (Andrew Evans) Date: Thu, 19 Aug 2010 09:34:08 -0700 Subject: Python module Code returns empty list any ideas how to fix Message-ID: Hello I am trying to modify Python xgoogle module to use yahoo I have hit a road block where I receive no error messages the code I use to test just returns an empty list. and I don't know how to trouble shoot it the module code is here http://pastebin.com/iTibRs1R and the code I am using to test is this import re from urlparse import urlparse from xyahoo.search import YahooSearch, SearchError gs = YahooSearch("quick and dirty") print gs gs.results_per_page = 50 results = gs.get_results() print results for res in results: print res.title.encode("utf8") print res.desc.encode("utf8") print res.url.encode("utf8") Any idea how to fix the module *cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Thu Aug 19 13:18:19 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 19 Aug 2010 17:18:19 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> Message-ID: <8d57arFph0U1@mid.individual.net> On 2010-08-19, J.B. Brown wrote: > When I wrote my own C++ 2-D matrix class, I wrote a member > function which did exactly this - allow you to specify the > initial index value. Then users of my class (mainly my research > lab coworkers) could specify whichever behavior they wanted. I did something similar in a library that needs to read "positions" from the specification for a fixed-length fields plain text database. The printed specs for these document types often start counting character positions at 1, but not universally. > For those who don't like Python's 0-based indexing, why not > just build a wrapper type which features an item() method that > handles the internal conversion from 1 to 0 as the starting > index? Better yet, include a method which sets/specifies the > 0/1 behavior, and have item() reference the 0/1 setting to > obtain the proper offset. Because they know deep down they wouldn't win anything. -- Neil Cerutti From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 13:38:50 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 17:38:50 GMT Subject: bug? context managers vs ImportErrors References: Message-ID: <4c6d6c29$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 16:58:30 +0100, Chris Withers wrote: > Hi All, > > Am I right in thinking this is a bug: > > class MyContextManager: > > def __enter__(self): > pass > > def __exit__(self,t,e,tb): > print type(t),t > print type(e),e > > > with MyContextManager(): > import foo.bar.baz > > ...when executed, gives me: > > > No module named foo.bar.baz > > Why is 'e' ending up as a string rather than the ImportError object? Because e is the exception value, not an exception instance. In other words, if you call t(e) you will get the instance you're expecting. See the docs: http://docs.python.org/library/stdtypes.html#contextmanager.__exit__ The three arguments exc_type, exc_value, exc_tb are the same three arguments you can pass to the raise statement: http://docs.python.org/reference/simple_stmts.html#the-raise-statement (BTW, I'm not suggesting you should do that from inside the __exit__ method.) So, no, this is not a bug. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 13:42:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 17:42:37 GMT Subject: Contains/equals References: Message-ID: <4c6d6d0c$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote: > def __eq__(self, obj): > if self.a==obj.a and self.b==obj.b: return True > return False That would be the same as: def __eq__(self, obj): return self.a==obj.a and self.b==obj.b -- Steven From ethan at stoneleaf.us Thu Aug 19 13:44:19 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 19 Aug 2010 10:44:19 -0700 Subject: bug? context managers vs ImportErrors In-Reply-To: <4C6D54A6.4060107@simplistix.co.uk> References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: <4C6D6D73.9050206@stoneleaf.us> Chris Withers wrote: > Hi All, > > Am I right in thinking this is a bug: > > class MyContextManager: > > def __enter__(self): > pass > > def __exit__(self,t,e,tb): > print type(t),t > print type(e),e > > > with MyContextManager(): > import foo.bar.baz > > ...when executed, gives me: > > > No module named foo.bar.baz > > Why is 'e' ending up as a string rather than the ImportError object? > > This is with Python 2.6.5 if that makes a difference... I don't have an answer, just some more examples across different versions/exceptions: class MyContextManager: def __enter__(self): pass def __exit__(self,t,e,tb): print ('--------') print (type(t),t) print (type(e),e) return True with MyContextManager(): import foo.bar.baz with MyContextManager(): 1/0 with MyContextManager(): not_here() c:\temp>\python25\python test.py [0] -------- (, ) (, 'No module named bar.baz') -------- (, ) (, 'integer division or modulo by zero') -------- (, ) (, "name 'not_here' is not defined") c:\temp>\python26\python test.py [0] -------- (, ) (, 'No module named bar.baz') -------- (, ) (, 'integer division or modulo by zero') -------- (, ) (, "name 'not_here' is not defined") c:\temp>\python27\python test.py [0] -------- (, ) (, ImportError('No module named bar.baz',)) -------- (, ) (, ZeroDivisionError('integer division or modulo by zero',)) -------- (, ) (, NameError("name 'not_here' is not defined",)) c:\temp>\python31\python test.py -------- invalid syntax (foo.py, line 3) -------- int division or modulo by zero -------- name 'not_here' is not defined As an aside, does anyone know why the 2.x versions are printing the [0] as the first line? 3.1 does not. From russ.paielli at gmail.com Thu Aug 19 14:03:53 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 11:03:53 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> Message-ID: <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> On Aug 19, 9:07?am, "J.B. Brown" wrote: > 2010/8/9 MRAB : > > > Default User wrote: > > >> Not to prolong a good "food fight", but IIRC, many years ago in QBasic, > >> one could choose > > >> OPTION BASE 0 > > >> or > > >> OPTION BASE 1 > > When I wrote my own C++ 2-D matrix class, I wrote a member function > which did exactly this - allow you to specify the initial index value. > Then users of my class (mainly my research lab coworkers) could > specify whichever behavior they wanted. > > In terms of providing readable code and removing beginning programmer > confusion, why not extend python lists by using something similar to > (but not necessarily identical to) ?the C++ STL containers: > > C++ > int myX[ ] ?= { 1,2,3,4,5 }; > std::vector vectorX( myX, &myX[ ?sizeof( myX ) - 1 ] ); > std::cout << vectorX.begin() << std::endl; > std::cout << vectorX.end() << std::endl; > > Python > x = [ 1 , 2 , 3 , 4 , 5 ] > print x.first() > print x.last() ? ?, Many years ago I wrote a fairly comprehensive vector/matrix class in C+ +. (It was an exercise to learn the intricacies of C++, and I also really needed it.) I used a system of offset pointers to realize indexing that starts with 1. Years later, after I had quit using it, I decided that I should have just bit the bullet and let the indexing start with zero for simplicity. I believe that zero-based indexing is a mistake, but attempts to fix it require additional boilerplate that is prone to error and inefficiency. Short of a major language overhaul, we are essentially stuck with zero-based indexing. But that doesn't mean we should pretend that it was the right choice. For those who insist that zero-based indexing is a good idea, why you suppose mathematical vector/matrix notation has never used that convention? I have studied and used linear algebra extensively, and I have yet to see a single case of vector or matrix notation with zero- based indexing in a textbook or a technical paper. Also, mathematical summation is traditionally shown as "1 to N", not "0 to N-1". Are mathematicians just too simple-minded and unsophisticated to understand the value of zero-based indexing? Or have you perhaps been mislead? From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 14:04:49 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 18:04:49 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> Message-ID: <4c6d7241$0$11111$c3e8da3@news.astraweb.com> On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote: > The convention of starting with zero may have had some slight > performance advantage in the early days of computing, but the huge > potential for error that it introduced made it a poor choice in the long > run, at least for high-level languages. People keep saying this, but it's actually the opposite. Signpost errors and off-by-one errors are more common in languages that count from one. A simple example: Using zero-based indexing, suppose you want to indent the string "spam" so it starts at column 4. How many spaces to you prepend? 0123456789 spam Answer: 4. Nice and easy and almost impossible to get wrong. To indent to position n, prepend n spaces. Now consider one-based indexing, where the string starts at column 5: 1234567890 spam Answer: 5-1 = 4. People are remarkably bad at remembering to subtract the 1, hence the off-by-one errors. Zero-based counting doesn't entirely eliminate off-by-one errors, but the combination of that plus half-open on the right intervals reduces them as much as possible. The intuitive one-based closed interval notation used in many natural languages is terrible for encouraging off-by-one errors. Quick: how many days are there between Friday 20th September and Friday 27th September inclusive? If you said seven, you fail. One-based counting is the product of human intuition. Zero-based counting is the product of human reason. -- Steven From __peter__ at web.de Thu Aug 19 14:08:13 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 20:08:13 +0200 Subject: bug? context managers vs ImportErrors References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: Ethan Furman wrote: > Chris Withers wrote: >> Hi All, >> >> Am I right in thinking this is a bug: >> >> class MyContextManager: >> >> def __enter__(self): >> pass >> >> def __exit__(self,t,e,tb): >> print type(t),t >> print type(e),e >> >> >> with MyContextManager(): >> import foo.bar.baz >> >> ...when executed, gives me: >> >> >> No module named foo.bar.baz >> >> Why is 'e' ending up as a string rather than the ImportError object? >> >> This is with Python 2.6.5 if that makes a difference... > > I don't have an answer, just some more examples across different > versions/exceptions: > > > class MyContextManager: > def __enter__(self): > pass > def __exit__(self,t,e,tb): > print ('--------') > print (type(t),t) > print (type(e),e) > return True > > with MyContextManager(): > import foo.bar.baz > with MyContextManager(): > 1/0 > with MyContextManager(): > not_here() > > > > c:\temp>\python25\python test.py > [0] > -------- > (, ) > (, 'No module named bar.baz') > -------- > (, ) > (, 'integer division or modulo by zero') > -------- > (, ) > (, "name 'not_here' is not defined") > > c:\temp>\python26\python test.py > [0] > -------- > (, ) > (, 'No module named bar.baz') > -------- > (, ) > (, 'integer division or modulo by zero') > -------- > (, ) > (, "name 'not_here' is not defined") > > c:\temp>\python27\python test.py > [0] > -------- > (, ) > (, ImportError('No module named bar.baz',)) > -------- > (, ) > (, ZeroDivisionError('integer > division or modulo by zero',)) > -------- > (, ) > (, NameError("name 'not_here' is not > defined",)) > > c:\temp>\python31\python test.py > -------- > > invalid syntax (foo.py, line 3) > -------- > > int division or modulo by zero > -------- > > name 'not_here' is not defined > > > > As an aside, does anyone know why the 2.x versions are printing the [0] > as the first line? 3.1 does not. If reading the error messages carefully doesn't help scroll down for a hint;) Look into foo.py From dodo_do_not_wake_up at yahoo.fr Thu Aug 19 14:25:41 2010 From: dodo_do_not_wake_up at yahoo.fr (Dodo) Date: Thu, 19 Aug 2010 20:25:41 +0200 Subject: Django 1.2.1 - stuck with CSRF verification Message-ID: Hi all, I followed the tutorial but at page 4 I can't get rid of CSRF errors, even though I followed everything in this page : http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ Any idea? Dorian From ethan at stoneleaf.us Thu Aug 19 14:25:54 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 19 Aug 2010 11:25:54 -0700 Subject: bug? context managers vs ImportErrors In-Reply-To: References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: <4C6D7732.5070203@stoneleaf.us> Peter Otten wrote: > Ethan Furman wrote: >> As an aside, does anyone know why the 2.x versions are printing the [0] >> as the first line? 3.1 does not. > > If reading the error messages carefully doesn't help scroll down for a > hint;) > . > . > . > Look into foo.py AH hahahahahahah. That's what I get for being in a hurry. Thanks for catching that, Peter! ~Ethan~ From russ.paielli at gmail.com Thu Aug 19 14:27:18 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 11:27:18 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: On Aug 19, 11:04?am, Steven D'Aprano wrote: > On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote: > > The convention of starting with zero may have had some slight > > performance advantage in the early days of computing, but the huge > > potential for error that it introduced made it a poor choice in the long > > run, at least for high-level languages. > > People keep saying this, but it's actually the opposite. Signpost errors > and off-by-one errors are more common in languages that count from one. > > A simple example: Using zero-based indexing, suppose you want to indent > the string "spam" so it starts at column 4. How many spaces to you > prepend? > > 0123456789 > ? ? spam > > Answer: 4. Nice and easy and almost impossible to get wrong. To indent to > position n, prepend n spaces. > > Now consider one-based indexing, where the string starts at column 5: > > 1234567890 > ? ? spam > > Answer: 5-1 = 4. People are remarkably bad at remembering to subtract the > 1, hence the off-by-one errors. > > Zero-based counting doesn't entirely eliminate off-by-one errors, but the > combination of that plus half-open on the right intervals reduces them as > much as possible. > > The intuitive one-based closed interval notation used in many natural > languages is terrible for encouraging off-by-one errors. Quick: how many > days are there between Friday 20th September and Friday 27th September > inclusive? If you said seven, you fail. The error mode you refer to is much less common than the typical off- by-one error mode. In the far more common error mode, zero-based indexing is far more error prone. > One-based counting is the product of human intuition. Zero-based counting > is the product of human reason. I suggest you take that up with mathematicians, who have used one- based indexing all along. That's why it was used in Fortran and Matlab, among other more mathematical and numerically oriented and languages. From russ.paielli at gmail.com Thu Aug 19 14:39:05 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 11:39:05 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: <40cea402-30ac-472c-ab1e-27e2050ec25b@y11g2000yqm.googlegroups.com> I just checked, and Mathematica uses one-based indexing. Apparently they want their notation to look mathematical. From thomas at jollybox.de Thu Aug 19 14:40:50 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 19 Aug 2010 20:40:50 +0200 Subject: Django 1.2.1 - stuck with CSRF verification In-Reply-To: References: Message-ID: <201008192040.50998.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to Dodo to exclaim: > Hi all, > I followed the tutorial but at page 4 I can't get rid of CSRF errors, > even though I followed everything in this page : > http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ > what kind of errors? Any exception tracebacks you can show us maybe? From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 14:42:45 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 18:42:45 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> Message-ID: <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote: > For those who insist that zero-based indexing is a good idea, why you > suppose mathematical vector/matrix notation has never used that > convention? I have studied and used linear algebra extensively, and I > have yet to see a single case of vector or matrix notation with zero- > based indexing in a textbook or a technical paper. Also, mathematical > summation is traditionally shown as "1 to N", not "0 to N-1". In my experience, it's more likely to be "0 to N" than either of the above, thus combining the worst of both notations. > Are > mathematicians just too simple-minded and unsophisticated to understand > the value of zero-based indexing? No, mathematicians are addicted to tradition. Unlike computer scientists, who create new languages with radically different notation and syntax at the drop of a hat, mathematicians almost never change existing notation. Sometimes they *add* new notation, but more often they just re-use old notation in a new context. E.g. if you see (5, 8), does that mean a coordinate pair, a two-tuple, an open interval, or something else? Additionally, mathematical notation isn't chosen for its ability to encourage or discourage errors. It seems often to be chosen arbitrarily, or for convenience, but mostly out of tradition and convention. Why do we use "x" for "unknown"? Why do we use i for an integer value, but not r for a real or c for a complex value? Mathematicians are awfully lazy -- laziness is one of the cardinal virtues of the mathematician, as it is of programmers -- but they value brevity and conciseness over notation that improves readability and robustness. That's why they (e.g.) they use implicit multiplication, a plethora of "line noise" symbols that would boggle even Perl programmers, and two-dimensional syntax where the meaning of tokens depends on where they are written relative to some other token. (E.g. subscript, superscript, and related forms.) There is one slightly mainstream language that uses mathematical notation: APL. The result isn't pretty. -- Steven From thomas at jollybox.de Thu Aug 19 14:47:10 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 19 Aug 2010 20:47:10 +0200 Subject: Creating a PYD file In-Reply-To: References: Message-ID: <201008192047.10460.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to Rony to exclaim: > Is a PYD file created from Pyrex faster in execution then a PYD file > created from python source ? How do you plan to create an extension module (*.so, *.pyd on Windows) from Python source then? From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 14:47:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 18:47:26 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <40cea402-30ac-472c-ab1e-27e2050ec25b@y11g2000yqm.googlegroups.com> Message-ID: <4c6d7c3e$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:39:05 -0700, Russ P. wrote: > I just checked, and Mathematica uses one-based indexing. Apparently they > want their notation to look mathematical. Well duh. It's called MATHematica, not PROGematica. -- Steven From nikos.the.gr33k at gmail.com Thu Aug 19 14:50:53 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Thu, 19 Aug 2010 21:50:53 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D548F.2050303@tim.thechases.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> <4C6D50CA.5060604@gmail.com> <4C6D548F.2050303@tim.thechases.com> Message-ID: <4C6D7D0D.7040703@gmail.com> ???? 19/8/2010 6:58 ??, ?/? Tim Chase ??????: > It can be written as a non-3-quote string, you just have to escape the > inner quotes (single & double) and the backslash to be seen: > > name = 'My name is "Nikos" and I\'m from Thessaloniki\\Greece' > name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece" > So if i enclose the string in double quotes the inner double quotes have to be escaped while if i enclose the string in single quotes the inner single quotes have to be escaped. But in 3-single-quoting thing became easier since i don't have to escape all kind of quotes right? just the backslashes. >> And i dont have to use the 'r' in fornt of it too. > > Using the 'r' in front would make it much more challenging, because it > would prevent the backslashes from being seen as escaping. :) So the best way to write the above assignment statement would be: name = r'''My name is "Nikos" and I'm from Thessaloniki\Greece''' It cannot get any easier that that can it? :) ''' ''' helps avoid escaping all kind of quotes! 'r' avoid escaping backslashes! ============================= Why does the page variable which is actually a string needs to be a tuple or a list and not just as a string which is what it actually is? I have a strong desire to use it like this: cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page ) opposed to tuple. Would i might facing a problem? Of what? MySQLdb instead of give the whole value to the placeholder to give just a single char? Also do i need 3-single-quoting here as well or it can be written qith signle/double quotes? What appleis to strings apply to mysql queries as well? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu Aug 19 14:53:36 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Aug 2010 13:53:36 -0500 Subject: Contains/equals In-Reply-To: <4c6d6d0c$0$11111$c3e8da3@news.astraweb.com> References: <4c6d6d0c$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4C6D7DB0.1030304@tim.thechases.com> On 08/19/10 12:42, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote: > >> def __eq__(self, obj): >> if self.a==obj.a and self.b==obj.b: return True >> return False > > That would be the same as: > > def __eq__(self, obj): > return self.a==obj.a and self.b==obj.b Or, if you have lots of attributes and 2.5+ def __eq__(self, other): return all( getattr(self, attr) == getattr(other, attr) for attr in ['a', 'b', 'c', ...] ) or even something like def __eq__(self, other): return all( getattr(self, attr) == getattr(other, attr) for attr in dir(self) if not attr.startswith("__") and not attr.endswith("__") ) -tkc From mail at timgolden.me.uk Thu Aug 19 14:55:38 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 19 Aug 2010 19:55:38 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: <4C6D7E2A.9010703@timgolden.me.uk> On 19/08/2010 4:55 PM, vsoler wrote: > I need to read, for each of the directories in a shared file server > unit, who has access to the directories and what type of access > privileges. > > This is something that I can easily do interactively in my Windows > Document Explorer by right clicking a single directory, clicking on > Properties, then on Security. > > There I can see the Users and Group of Users that have access to the > selected directory, as well as the type of access to that directory > (Read/Write/eXecute etc.) Here you have one of those occasions when the Windows GUI does a very good job of presenting a simplified but perfectly usable interface layer on top of a moderately complex security scheme. It's not as easy as you think. > I've been looking in the "os" library, and found the "os.chmod" method > but I am not sure that it is going to give me what I need. Should I > also used library "stat"? No. Both of these are basically doing a best-endeavours job of mapping certain Windows attributes to some Posix equivalent. They're essentially useless for anything beyond the most trivial tasks. Have a read here which will at least put you on the path of knowing what terminology you need to search for: http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html and if you're interested, this is the kind of thing my winsys package is reasonably good at: http://timgolden.me.uk/python/winsys/security.html#module-security TJG From russ.paielli at gmail.com Thu Aug 19 14:57:53 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 11:57:53 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> Message-ID: <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> On Aug 19, 11:42?am, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote: > > For those who insist that zero-based indexing is a good idea, why you > > suppose mathematical vector/matrix notation has never used that > > convention? I have studied and used linear algebra extensively, and I > > have yet to see a single case of vector or matrix notation with zero- > > based indexing in a textbook or a technical paper. Also, mathematical > > summation is traditionally shown as "1 to N", not "0 to N-1". > > In my experience, it's more likely to be "0 to N" than either of the > above, thus combining the worst of both notations. > > > Are > > mathematicians just too simple-minded and unsophisticated to understand > > the value of zero-based indexing? > > No, mathematicians are addicted to tradition. That is probably true. But computer languages are addicted to more than tradition. They're addicted to compatibility and familiarity. I don't know where zero-based indexing started, but I know that C used it very early, probably for some minuscule performance advantage. When C++ came along, it tried to be somewhat compatible with C, so it continued using zero-based indexing. Then Java was loosely modeled after C++, so the convention continued. Python was written in C, so zero-based indexing was "natural." So the whole thing is based on a decision by some guy who was writing a language for operating systems, not mathematics or application programming. > Unlike computer scientists, who create new languages with radically > different notation and syntax at the drop of a hat, mathematicians almost > never change existing notation. Sometimes they *add* new notation, but > more often they just re-use old notation in a new context. E.g. if you > see (5, 8), does that mean a coordinate pair, a two-tuple, an open > interval, or something else? > > Additionally, mathematical notation isn't chosen for its ability to > encourage or discourage errors. It seems often to be chosen arbitrarily, > or for convenience, but mostly out of tradition and convention. Why do we > use "x" for "unknown"? Why do we use i for an integer value, but not r > for a real or c for a complex value? > > Mathematicians are awfully lazy -- laziness is one of the cardinal > virtues of the mathematician, as it is of programmers -- but they value > brevity and conciseness over notation that improves readability and > robustness. That's why they (e.g.) they use implicit multiplication, a > plethora of "line noise" symbols that would boggle even Perl programmers, > and two-dimensional syntax where the meaning of tokens depends on where > they are written relative to some other token. (E.g. subscript, > superscript, and related forms.) > > There is one slightly mainstream language that uses mathematical > notation: APL. The result isn't pretty. As I wrote above, the use of zero-based indexing in C++, Java, and Python are all simply based on the fact that C used it. I wouldn't have guessed that APL is a "mainstream" language. As I wrote in recent posts, Fortran, Matlab, and Mathematica all used one- based indexing. Maybe Basic too, but I haven't checked. From russ.paielli at gmail.com Thu Aug 19 15:13:06 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 12:13:06 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> Message-ID: <8c9a626e-cf15-4b42-bfbc-e32622777b4b@l14g2000yql.googlegroups.com> Yes, apparently Basic uses one-based indexing too. As for Ada, apparently, the programmer needs to explicitly define the index range for every array. Weird. But I get the impression that one- based indexing is used much more than zero-based indexing. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 15:13:50 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 19:13:50 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c6d826e$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:27:18 -0700, Russ P. wrote: [...] >> Zero-based counting doesn't entirely eliminate off-by-one errors, but >> the combination of that plus half-open on the right intervals reduces >> them as much as possible. >> >> The intuitive one-based closed interval notation used in many natural >> languages is terrible for encouraging off-by-one errors. Quick: how >> many days are there between Friday 20th September and Friday 27th >> September inclusive? If you said seven, you fail. > > The error mode you refer to is much less common than the typical off- > by-one error mode. In the far more common error mode, zero-based > indexing is far more error prone. So you say, and yet you don't give any examples of this "far more common" error mode. >> One-based counting is the product of human intuition. Zero-based >> counting is the product of human reason. > > I suggest you take that up with mathematicians, who have used one- based > indexing all along. That's why it was used in Fortran and Matlab, among > other more mathematical and numerically oriented and languages. Mathematics is an ancient art that values tradition and convention. It doesn't matter how hard it was to come up with a proof, or how difficult to verify it. Mathematicians value logical correctness and some undefinable sense of elegance over how easy it is to verify, the readability of the notation, resistance to errors, and the ability of mediocre mathematicians to make useful contributions. Mathematical notation and conventions are not, by any stretch of the imagination, designed to reduce errors. Mathematicians consider it a good thing that they are still mostly using the same notation invented by (say) Leibniz. Programming language design is a young art that values reliability and ease of use over tradition. While correctness of the code is important, equally important (if not more so) is readability, resistance to errors, and the ability of mediocre programmers to write code that works. Or at least code that can be hammered into working by slightly less mediocre programmers. Maintenance of code is usually more difficult than writing it in the first place, and consequently languages often are designed specifically to reduce errors rather than to use the exact same notation than Grace Hopper or Charles Babbage used. While businesses are conservative in which languages they choose, language designers are not conservative in the design features they come up with. That there has been a gradual (although as yet incomplete) convergence towards zero-based indexing in languages aimed at programmers, and one-based indexing in languages aimed at non- programmers, tells you everything you need to know. -- Steven From andrei.avk at gmail.com Thu Aug 19 15:18:23 2010 From: andrei.avk at gmail.com (AK) Date: Thu, 19 Aug 2010 15:18:23 -0400 Subject: Python "why" questions In-Reply-To: <4c6d7241$0$11111$c3e8da3@news.astraweb.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4C6D837F.3010803@gmail.com> On 08/19/2010 02:04 PM, Steven D'Aprano wrote: > On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote: > >> The convention of starting with zero may have had some slight >> performance advantage in the early days of computing, but the huge >> potential for error that it introduced made it a poor choice in the long >> run, at least for high-level languages. > > People keep saying this, but it's actually the opposite. Signpost errors > and off-by-one errors are more common in languages that count from one. > > A simple example: Using zero-based indexing, suppose you want to indent > the string "spam" so it starts at column 4. How many spaces to you > prepend? > > 0123456789 > spam Doesn't it start at column 5 as shown? Anyway, it's far more common, I think, to iterate over a sequence and say "my list is 12 items long. I need to check if I'm on 12th item and do something special. Doh, I mean, 11th item." In my view, this is far, far more common, especially for people new to programming, and isn't one of Python mottos "programming for everybody"? In other words, starting with 0 leads to implicit error every time you simply pause and think "at which item am I now and how many items have I got so far?" which are the two most basic questions involved in iteration. I'm not saying that 1-th indexing is necessarily better in programming than 0-th indexing, all things considered. It's an arguable question, it depends on what kind of operations are more common, and I can't know this for everyone. I am saying that it is much more natural for people new to programming and outside of programming to count from 1, and I imagine the reason for this is simply that it's most useful in vast majority of real usage people deal with. It's just annoying that people bring up, for example, ground floor/ first floor as proof that both are equally natural. (I don't mean you, I know you said you agree that 1-th indexing is more intuitive). -ak From lists at cheimes.de Thu Aug 19 15:20:50 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 19 Aug 2010 21:20:50 +0200 Subject: Contains/equals In-Reply-To: <4C6D7DB0.1030304@tim.thechases.com> References: <4c6d6d0c$0$11111$c3e8da3@news.astraweb.com> <4C6D7DB0.1030304@tim.thechases.com> Message-ID: Am 19.08.2010 20:53, schrieb Tim Chase: > On 08/19/10 12:42, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote: >> >>> def __eq__(self, obj): >>> if self.a==obj.a and self.b==obj.b: return True >>> return False >> >> That would be the same as: >> >> def __eq__(self, obj): >> return self.a==obj.a and self.b==obj.b > > Or, if you have lots of attributes and 2.5+ > > def __eq__(self, other): > return all( > getattr(self, attr) == getattr(other, attr) > for attr in ['a', 'b', 'c', ...] > ) > > or even something like > > def __eq__(self, other): > return all( > getattr(self, attr) == getattr(other, attr) > for attr in dir(self) > if not attr.startswith("__") and not attr.endswith("__") > ) > or simpler if you don't take slots and class attributes into account. def __eq__(self, other): return self.__dict__ == other.__dict__ Christian From russ.paielli at gmail.com Thu Aug 19 15:25:50 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 12:25:50 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> Message-ID: <9015ea75-e67c-46d2-b5ce-b9745aab1317@x25g2000yqj.googlegroups.com> On Aug 19, 12:13?pm, Steven D'Aprano While businesses are conservative in which languages they choose, > language designers are not conservative in the design features they come > up with. That there has been a gradual (although as yet incomplete) > convergence towards zero-based indexing in languages aimed at > programmers, and one-based indexing in languages aimed at non- > programmers, tells you everything you need to know. I beg to differ. I remember reading Bjarne Stroustrup's rationale for adopting all sorts of junk from C that he really didn't want, just to make C++ reasonably compatible with it. Had he not done that, C++ probably would have died on the vine. I'm sure the same was true of Java and Python too. In any case, I need to drop this discussion and move on. Mr. D'Aprano, I usually find your posts enlightening and amusing, but in this case just don't seem to be converging. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 15:32:41 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 19:32:41 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> Message-ID: <4c6d86d9$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:57:53 -0700, Russ P. wrote: > I don't > know where zero-based indexing started, but I know that C used it very > early, probably for some minuscule performance advantage. In C, zero based indexing was used because it made pointer arithmetic elegant and reduced bugs. > When C++ came > along, it tried to be somewhat compatible with C, so it continued using > zero-based indexing. And because a feature that isn't broken doesn't need to be "fixed". > Then Java was loosely modeled after C++, so the > convention continued. Python was written in C, so zero-based indexing > was "natural." So the whole thing is based on a decision by some guy who > was writing a language for operating systems, not mathematics or > application programming. Python is vastly different from C. It has just as many similarities to Pascal as C, which uses 1-based indexing. No surprise there -- Python, like both Pascal and C, is a member of the Algol family of languages. It is interesting to see that Nicholas Wirth's first language, Pascal, used one-based indexing, and his latest, Oberon, uses zero-based. Say what you like about Wirth, but he's not influenced by the desire to be like C. Oberon uses the same zero-based half-open on the right indexing as Python: VAR a: ARRAY 10 OF INTEGER; creates an array a[0]...a[9]. If Wirth has moved to the Python convention, it is because it *works*, not because he's trying to ape C. Not all languages are based on Algol. Languages derived from Lisp also start array indexing at 0. So does Forth. So that's at least three significantly different language families which have independently converged on zero-based indexing. [...] > I wouldn't have guessed that APL is a "mainstream" language. I said "slightly". It was surprisingly popular in it's time, and there are still multiple APL compilers and interpreters for Windows, Linux and Mac. -- Steven From kara at kara-moon.com Thu Aug 19 15:41:30 2010 From: kara at kara-moon.com (Rony) Date: Thu, 19 Aug 2010 12:41:30 -0700 (PDT) Subject: Creating a PYD file References: Message-ID: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> Sorry that was a typo... The question actually is, is a PYD file created from C faster then a PYD file from Pyrex ? I know it will depend on how it is written, but let's imagine a tiny example, like (Pseudo code) result = arg1 + arg2 return result Tia Rony On 19 ao?t, 20:47, Thomas Jollans wrote: > On Thursday 19 August 2010, it occurred to Rony to exclaim: > > > Is a PYD file created from Pyrex faster in execution then a PYD file > > created from python source ? > > How do you plan to create an extension module (*.so, *.pyd on Windows) from > Python source then? From python at mrabarnett.plus.com Thu Aug 19 15:43:51 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Aug 2010 20:43:51 +0100 Subject: Python "why" questions In-Reply-To: <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> Message-ID: <4C6D8977.2030700@mrabarnett.plus.com> Russ P. wrote: > On Aug 19, 11:42 am, Steven D'Aprano cybersource.com.au> wrote: >> On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote: >>> For those who insist that zero-based indexing is a good idea, why you >>> suppose mathematical vector/matrix notation has never used that >>> convention? I have studied and used linear algebra extensively, and I >>> have yet to see a single case of vector or matrix notation with zero- >>> based indexing in a textbook or a technical paper. Also, mathematical >>> summation is traditionally shown as "1 to N", not "0 to N-1". >> In my experience, it's more likely to be "0 to N" than either of the >> above, thus combining the worst of both notations. >> >>> Are >>> mathematicians just too simple-minded and unsophisticated to understand >>> the value of zero-based indexing? >> No, mathematicians are addicted to tradition. > > That is probably true. But computer languages are addicted to more > than tradition. They're addicted to compatibility and familiarity. I > don't know where zero-based indexing started, but I know that C used > it very early, probably for some minuscule performance advantage. When > C++ came along, it tried to be somewhat compatible with C, so it > continued using zero-based indexing. Then Java was loosely modeled > after C++, so the convention continued. Python was written in C, so > zero-based indexing was "natural." So the whole thing is based on a > decision by some guy who was writing a language for operating systems, > not mathematics or application programming. > [snip] C was derived ultimately from BCPL. In C array indexing is syntactic sugar for pointer arithmetic with dereferencing, so: p[i] means the same as: *(p + i) BCPL, IIRC, didn't use the familiar indexing syntax. !p was the equivalent of *p and p!i was short for !(p + i), the equivalent of p[i]. From python at mrabarnett.plus.com Thu Aug 19 15:49:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Aug 2010 20:49:32 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D7D0D.7040703@gmail.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> <4C6D50CA.5060604@gmail.com> <4C6D548F.2050303@tim.thechases.com> <4C6D7D0D.7040703@gmail.com> Message-ID: <4C6D8ACC.2050108@mrabarnett.plus.com> Nik Gr wrote: [snip] > Why does the page variable which is actually a string needs to be a > tuple or a list and not just as a string which is what it actually is? > I have a strong desire to use it like this: > > cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page ) > > opposed to tuple. Would i might facing a problem? Of what? MySQLdb > instead of give the whole value to the placeholder to give just a single > char? When there's more than one value you provide a tuple. It's makes sense from the point of view of consistency that you also provide a tuple when there's only one value. > Also do i need 3-single-quoting here as well or it can be written qith > signle/double quotes? > What appleis to strings apply to mysql queries as well? > It's just a normal string literal. From lists at cheimes.de Thu Aug 19 15:50:24 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 19 Aug 2010 21:50:24 +0200 Subject: bug? context managers vs ImportErrors In-Reply-To: <4C6D54A6.4060107@simplistix.co.uk> References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: > Why is 'e' ending up as a string rather than the ImportError object? > > This is with Python 2.6.5 if that makes a difference... It's a known bug in Python 2.6 and earlier. See http://docs.python.org/whatsnew/2.7.html#porting-to-python-2-7 Due to a bug in Python 2.6, the exc_value parameter to __exit__() methods was often the string representation of the exception, not an instance. This was fixed in 2.7, so exc_value will be an instance as expected. (Fixed by Florent Xicluna; issue 7853.) From info at wingware.com Thu Aug 19 15:54:26 2010 From: info at wingware.com (Wingware) Date: Thu, 19 Aug 2010 15:54:26 -0400 Subject: Wing IDE 3.2.10 released Message-ID: <4C6D8BF2.7040009@wingware.com> Hi, Wingware has released version 3.2.10 of Wing IDE, an integrated development environment designed specifically for the Python programming language. This release includes the following improvements: * Several vi mode fixes and other key binding enhancements * Copy from selected text in Exceptions tool and Testing tool * Fix Perforce support to run client command in project directory * Fix debug attach to remote host * Don't output XML when debugging unit tests * About 20 other bug fixes (see CHANGELOG.txt for details) See the change log at http://wingware.com/pub/wingide/3.2.10/CHANGELOG.txt for details of other recent changes. *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product. Wing IDE 101 can be used free of charge. Wing IDE Pro 3.2.10 http://wingware.com/downloads/wingide/3.2 Wing IDE Personal 3.2.10 http://wingware.com/downloads/wingide-personal/3.2 Wing IDE 101 3.2.10 http://wingware.com/downloads/wingide-101/3.2 *About Wing IDE* Wing IDE is an integrated development environment designed specifically for the Python programming language. It provides powerful editing, testing, and debugging features that help reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE can be used to develop Python code for web, GUI, and embedded scripting applications. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. Version 3.2 of Wing IDE Professional includes the following major features: * Professional quality code editor with vi, emacs, and other keyboard personalities * Code intelligence for Python: Auto-completion, call tips, goto-definition, error indicators, smart indent and re-wrapping, and source navigation * Advanced multi-threaded debugger with graphical UI, command line interaction, conditional breakpoints, data value tool tips over code, watch tool, and externally launched and remote debugging * Powerful search and replace options including keyboard driven and graphical UIs, multi-file, wild card, and regular expression search and replace * Version control integration for Subversion, CVS, Bazaar, git, Mercurial, and Perforce * Integrated unit testing for the unittest, nose, and doctest frameworks * Many other features including project manager, bookmarks, code snippets, OS command integration, indentation manager, PyLint integration, and perspectives * Extremely configurable and may be extended with Python scripts Please refer to the feature list at http://wingware.com/wingide/features for a detailed listing of features by product level. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE supports Python versions 2.0.x through 3.1.x and Stackless Python. For more information, see http://wingware.com/products *Purchasing and Upgrading* Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Version 2.x licenses cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- Wingware | Python IDE The Intelligent Development Environment for Python Programmers www.wingware.com From python at mrabarnett.plus.com Thu Aug 19 15:55:09 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Aug 2010 20:55:09 +0100 Subject: Python "why" questions In-Reply-To: <8c9a626e-cf15-4b42-bfbc-e32622777b4b@l14g2000yql.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> <8c9a626e-cf15-4b42-bfbc-e32622777b4b@l14g2000yql.googlegroups.com> Message-ID: <4C6D8C1D.3080203@mrabarnett.plus.com> Russ P. wrote: > Yes, apparently Basic uses one-based indexing too. > For arrays, yes and no. Traditionally, DIM A(10) has 11 elements, starting at 0, although it might depend on the version of Basic. For strings, yes. > As for Ada, apparently, the programmer needs to explicitly define the > index range for every array. Weird. But I get the impression that one- > based indexing is used much more than zero-based indexing. From ericjvandervelden at gmail.com Thu Aug 19 15:57:04 2010 From: ericjvandervelden at gmail.com (Eric J. Van der Velden) Date: Thu, 19 Aug 2010 12:57:04 -0700 (PDT) Subject: tkinter Message-ID: Hello, I have python2.7 .I have compiled tcl en tk and installed them in my home directory, say /home/eric/tcl and /home/eric/tk . I have edited $ vi Modules/Setup ... _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ -L/home/eric/tcl/lib \ -L/home/eric/tk/lib \ -I/home/eric/tcl/include \ -I/home/eric/tcl/include \ -I/usr/include \ -ltcl8.6 -ltk8.6 \ -L/usr/lib \ -lX11 But setup.py does self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) When I pdb setup.py I see (Pdb) p inc_dirs ['/home/eric/Unix/Python/Python-2.7-install/include', '.', 'Include', './Include', '/usr/local/include', '/home/eric/Unix/Python/Python-2.7- install/include/python2.7', '/usr/include'] (Pdb) p lib_dirs ['/home/eric/Unix/Python/Python-2.7-install/lib', '/usr/local/lib', '/ lib64', '/usr/lib64', '/lib', '/usr/lib'] So no tcl or tk libraries or header files. Is my Modules/Setup not OK? Thanks, Eric J. From debatem1 at gmail.com Thu Aug 19 16:12:13 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 19 Aug 2010 13:12:13 -0700 Subject: Python "why" questions In-Reply-To: <4c6d86d9$0$11111$c3e8da3@news.astraweb.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> <4c6d86d9$0$11111$c3e8da3@news.astraweb.com> Message-ID: On Thu, Aug 19, 2010 at 12:32 PM, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 11:57:53 -0700, Russ P. wrote: > >> I don't >> know where zero-based indexing started, but I know that C used it very >> early, probably for some minuscule performance advantage. > > In C, zero based indexing was used because it made pointer arithmetic > elegant and reduced bugs. That's because in C, an array 'index' is not an ordinal, but a distance. Distances are easier to work with if you are comparing indices and performing arithmetic on them, while ordinals are easier to work with for straightforward I'd-like-this-element-please. I'm personally glad that Python uses the former. Geremy Condra From vicente.soler at gmail.com Thu Aug 19 16:17:40 2010 From: vicente.soler at gmail.com (vsoler) Date: Thu, 19 Aug 2010 13:17:40 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: Message-ID: On Aug 19, 8:55?pm, Tim Golden wrote: > On 19/08/2010 4:55 PM, vsoler wrote: > > > I need to read, for each of the directories in a shared file server > > unit, who has access to the directories and what type of access > > privileges. > > > This is something that I can easily do interactively in my Windows > > Document Explorer by right clicking a single directory, clicking on > > Properties, then on Security. > > > There I can see the Users and Group of Users that have access to the > > selected directory, as well as the type of access to that directory > > (Read/Write/eXecute etc.) > > Here you have one of those occasions when the Windows GUI does > a very good job of presenting a simplified but perfectly usable > interface layer on top of a moderately complex security scheme. > > It's not as easy as you think. > > > I've been looking in the "os" library, and found the "os.chmod" method > > but I am not sure that it is going to give me what I need. Should I > > also used library "stat"? > > No. Both of these are basically doing a best-endeavours job of mapping > certain Windows attributes to some Posix equivalent. They're essentially > useless for anything beyond the most trivial tasks. > > Have a read here which will at least put you on the path of knowing > what terminology you need to search for: > > ? ?http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html > ? ?http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.... > > and if you're interested, this is the kind of thing my winsys > package is reasonably good at: > > ? ?http://timgolden.me.uk/python/winsys/security.html#module-security > > TJG Thank you very much, Tim, for your answer. It looks as though it is going to suit my needs. Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and 2.6. File WinSys-0.4.zip should be for the same versions of Python, probably. What about your WinSys-0.5beta.win32.exe file? is it for python 3? I currently have python 3 in my pc. Do I need to install a previous version of python? Thank you for your help Vicente Soler From dodo_do_not_wake_up at yahoo.fr Thu Aug 19 16:36:04 2010 From: dodo_do_not_wake_up at yahoo.fr (Dodo) Date: Thu, 19 Aug 2010 22:36:04 +0200 Subject: Django 1.2.1 - stuck with CSRF verification In-Reply-To: References: Message-ID: Le 19/08/2010 20:40, Thomas Jollans a ?crit : > On Thursday 19 August 2010, it occurred to Dodo to exclaim: >> Hi all, >> I followed the tutorial but at page 4 I can't get rid of CSRF errors, >> even though I followed everything in this page : >> http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ >> > > what kind of errors? Any exception tracebacks you can show us maybe? Well I fill the form, submit via POST then : Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: No CSRF or session cookie. From nagle at animats.com Thu Aug 19 16:50:43 2010 From: nagle at animats.com (John Nagle) Date: Thu, 19 Aug 2010 13:50:43 -0700 Subject: String substitution VS proper mysql escaping In-Reply-To: References: <4C6BA2C4.4000309@gmail.com> Message-ID: <4c6d991f$0$1661$742ec2ed@news.sonic.net> On 8/18/2010 2:50 AM, Cameron Simpson wrote: > On 18Aug2010 12:07, Nik Gr wrote: > | ???? 18/8/2010 7:31 ??, ?/? Cameron Simpson ??????: > |>On 17Aug2010 20:15, ????? wrote: > |>| =============================== > |>| cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = > |>| '%s' ORDER BY date DESC ''' % (page) ) > |>| =============================== > |>| > |>| Someone told me NOT to do string substitution ("%") on SQL statements > |>| and to let MySQLdb do it > |>| for me, with proper escaping like the following > |>| > |>| =============================== > |>| cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s > |>| ORDER BY date DESC''', (page,)) > |>| =============================== > |>| > |>| The difference is that if some external source can control "page", > |>| and > |>| they put in a value like > |>| 100 ; DELETE FROM visitors; SELECT * FROM visitors > |>| i will be losing my database table data. > |> > |>That other difference is that the mysql dialect support knows how to > |>correctly escape a string for insertion into an SQL statement. You may > |>not, or may forget to pre-escape the string, etc. Using the MySQLdb > |>stuff do it for you is reliable and robust. > | > | Can you please tell me what escaping means by giving me an example > | of what is escaped and whats isn't? > > In your plain substitution example above: > > cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = > '%s' ORDER BY date DESC ''' % (page) ) > > Supposing page is the string "100". This will produce the SQL statement: > > SELECT host, hits, date FROM visitors WHERE page = '100' ORDER BY date DESC > > which looks ok. But suppose page was the string: > > bill o'reilly > > Then your SQL statement looks like this: > > SELECT host, hits, date FROM visitors WHERE page = 'bill o'reilly' ORDER BY date DESC > > To the SQL engine this looks like the string "bill o" followed by an SQL > instruction named "reilly", and then the opening quote for another string. > Invalid SQL. > > The procedure used to avoid this problem (to insert an _arbitrary_ > string into the SQL statement) is to "escape" problematic characters in > strings when placing them into SQL statements. In this case, the quote > character in the string is the SQL "end string" character. Therefore the > string must be modified in the SQL statement to be correctly expressed. > > IIRC, SQL uses the quote doubling convention for strings, so this: > > SELECT host, hits, date FROM visitors WHERE page = 'bill o''reilly' ORDER BY date DESC > > is how one would write the literal SQL for that. > > The MySQLdb library will do this and a host of other equivalent things > automatically and correctly and consistently when you pass page as a > parameter to the execute() method, needing no special attention or > detailed syntactic knowledge on your part when you write your program. Right. There's much mystery about this, but it's really simple. All MySQLdb is doing for cursor.execute(sqlstring, values) is quotedstr = sqlstring % map(MySQLdb.escape_string, values) cursor.execute(quotedstr) It just applies "MySQLdb.escape_string to each arg. If PHP did that, we'd have far fewer "SQL injection attacks". Most programs shouldn't use "MySQLdb.escape", and should let the built-in call do it. It's useful, though, if you're constructing a data file for LOAD DATA to do a bulk database load. The same escaping works for LOAD DATA INFILE with the default input format. John Nagle From tjreedy at udel.edu Thu Aug 19 16:57:52 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Aug 2010 16:57:52 -0400 Subject: Creating a PYD file In-Reply-To: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> References: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> Message-ID: On 8/19/2010 3:41 PM, Rony wrote: > is a PYD file created from C faster then a PYD file from Pyrex ? Since a .pyd file from Pyrex is also from C, the question is ill-posed. It is equivalent to "Does the C code generated by Pyrex compile to faster or slower machine code than the C code generated by some other person or program?". Leaving compiler variations aside, the answer depend on the proficiency of the other source in relation to the particular function being computed. Perhaps you already answered this... > I know it will depend on how it is written, depending on what you meant by 'it'. To be fair, the two code have to have exactly the same input/output relationships, including exception raising. -- Terry Jan Reedy From mail at timgolden.me.uk Thu Aug 19 16:59:04 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 19 Aug 2010 21:59:04 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: <4C6D9B18.6070308@timgolden.me.uk> On 19/08/2010 9:17 PM, vsoler wrote: > On Aug 19, 8:55 pm, Tim Golden wrote: >> On 19/08/2010 4:55 PM, vsoler wrote: >> >>> I need to read, for each of the directories in a shared file server >>> unit, who has access to the directories and what type of access >>> privileges. >> >>> This is something that I can easily do interactively in my Windows >>> Document Explorer by right clicking a single directory, clicking on >>> Properties, then on Security. >> >>> There I can see the Users and Group of Users that have access to the >>> selected directory, as well as the type of access to that directory >>> (Read/Write/eXecute etc.) >> >> Here you have one of those occasions when the Windows GUI does >> a very good job of presenting a simplified but perfectly usable >> interface layer on top of a moderately complex security scheme. >> >> It's not as easy as you think. >> >>> I've been looking in the "os" library, and found the "os.chmod" method >>> but I am not sure that it is going to give me what I need. Should I >>> also used library "stat"? >> >> No. Both of these are basically doing a best-endeavours job of mapping >> certain Windows attributes to some Posix equivalent. They're essentially >> useless for anything beyond the most trivial tasks. >> >> Have a read here which will at least put you on the path of knowing >> what terminology you need to search for: >> >> http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html >> http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.... >> >> and if you're interested, this is the kind of thing my winsys >> package is reasonably good at: >> >> http://timgolden.me.uk/python/winsys/security.html#module-security >> >> TJG > > Thank you very much, Tim, for your answer. > > It looks as though it is going to suit my needs. > > Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and > 2.6. > File WinSys-0.4.zip should be for the same versions of Python, > probably. > What about your WinSys-0.5beta.win32.exe file? is it for python 3? > > I currently have python 3 in my pc. Do I need to install a previous > version of python? > > Thank you for your help > > Vicente Soler I have a subversion branch for Python 3. If you have subversion access, try: http://winsys.googlecode.com/svn/branches/py3k and do the python setup.py install dance. If you can't get that working, let me know and I'll publish an installer somewhere. TJG From raoulbia at gmail.com Thu Aug 19 17:12:44 2010 From: raoulbia at gmail.com (Baba) Date: Thu, 19 Aug 2010 14:12:44 -0700 (PDT) Subject: Iterative vs. Recursive coding Message-ID: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Level: Beginner exercise source: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf I am looking at the first problem in the above assignment. The assignemnt deals, amongst others, with the ideas of iterative vs. recursive coding approaches and i was wondering what are the advantages of each and how to best chose between both options? I had a go at the first part of the exercise and it seems that i can handle it. However i think my Recursive version can be improved. By the way, is my code actually proper recursive code? part 1 iterative approach: from string import * def countSubStringMatch(target,key): counter=0 fsi=0 #fsi=find string index while fsi Message-ID: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> On Aug 19, 10:59?pm, Tim Golden wrote: > On 19/08/2010 9:17 PM, vsoler wrote: > > > > > On Aug 19, 8:55 pm, Tim Golden ?wrote: > >> On 19/08/2010 4:55 PM, vsoler wrote: > > >>> I need to read, for each of the directories in a shared file server > >>> unit, who has access to the directories and what type of access > >>> privileges. > > >>> This is something that I can easily do interactively in my Windows > >>> Document Explorer by right clicking a single directory, clicking on > >>> Properties, then on Security. > > >>> There I can see the Users and Group of Users that have access to the > >>> selected directory, as well as the type of access to that directory > >>> (Read/Write/eXecute etc.) > > >> Here you have one of those occasions when the Windows GUI does > >> a very good job of presenting a simplified but perfectly usable > >> interface layer on top of a moderately complex security scheme. > > >> It's not as easy as you think. > > >>> I've been looking in the "os" library, and found the "os.chmod" method > >>> but I am not sure that it is going to give me what I need. Should I > >>> also used library "stat"? > > >> No. Both of these are basically doing a best-endeavours job of mapping > >> certain Windows attributes to some Posix equivalent. They're essentially > >> useless for anything beyond the most trivial tasks. > > >> Have a read here which will at least put you on the path of knowing > >> what terminology you need to search for: > > >> ? ?http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html > >> ? ?http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.... > > >> and if you're interested, this is the kind of thing my winsys > >> package is reasonably good at: > > >> ? ?http://timgolden.me.uk/python/winsys/security.html#module-security > > >> TJG > > > Thank you very much, Tim, for your answer. > > > It looks as though it is going to suit my needs. > > > Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and > > 2.6. > > File WinSys-0.4.zip should be for the same versions of Python, > > probably. > > What about your WinSys-0.5beta.win32.exe file? is it for python 3? > > > I currently have python 3 in my pc. Do I need to install a previous > > version of python? > > > Thank you for your help > > > Vicente Soler > > I have a subversion branch for Python 3. If you have subversion > access, try: > > ? ?http://winsys.googlecode.com/svn/branches/py3k > > and do the python setup.py install dance. > > If you can't get that working, let me know and I'll publish > an installer somewhere. > > TJG I currently do not have subversion access in my PC. I could try to install a free copy of it. But it you could ptovide an installer, it certainly would do things easier. Please let me know if it is possible. Vicente Soler From chris at simplistix.co.uk Thu Aug 19 17:25:56 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 19 Aug 2010 22:25:56 +0100 Subject: bug? context managers vs ImportErrors In-Reply-To: References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: <4C6DA164.4000608@simplistix.co.uk> Christian Heimes wrote: >> Why is 'e' ending up as a string rather than the ImportError object? >> >> This is with Python 2.6.5 if that makes a difference... > > It's a known bug in Python 2.6 and earlier. See > http://docs.python.org/whatsnew/2.7.html#porting-to-python-2-7 When was it introduced? I've been relying on the value being an exception a lot in 2.5, and only hit problems in 2.6 with ImportError, everything else seems fine, which doesn't agree with Florent's statements in #7853... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From emile at fenx.com Thu Aug 19 17:31:14 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Aug 2010 14:31:14 -0700 Subject: Reading the access attributes of directories in Windows In-Reply-To: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> Message-ID: On 8/19/2010 2:17 PM vsoler said... > On Aug 19, 10:59 pm, Tim Golden wrote: >> I have a subversion branch for Python 3. If you have subversion >> access, try: >> >> http://winsys.googlecode.com/svn/branches/py3k >> >> and do the python setup.py install dance. >> >> If you can't get that working, let me know and I'll publish >> an installer somewhere. >> >> TJG > > I currently do not have subversion access in my PC. I could try to > install a free copy of it. I like this one for windows... http://tortoisesvn.net/downloads Emile From benjamin at python.org Thu Aug 19 17:33:11 2010 From: benjamin at python.org (Benjamin Peterson) Date: Thu, 19 Aug 2010 21:33:11 +0000 (UTC) Subject: bug? context managers vs ImportErrors References: <4C6D54A6.4060107@simplistix.co.uk> <4C6DA164.4000608@simplistix.co.uk> Message-ID: Chris Withers simplistix.co.uk> writes: > When was it introduced? It depends on how the exception was raised. From thomas at jollybox.de Thu Aug 19 17:41:36 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 19 Aug 2010 23:41:36 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <201008192341.36445.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to Baba to exclaim: > def countSubStringMatchRecursive(target,key): > counter=0 > fsi=0 #fsi=find string index > if len(key)==len(target): #base case > if key==target: > counter+=1 > elif len(key) while fsi fsi=target.find(key,fsi) > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > else: > print 'key is longer than target...' > > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcat > atgc") This is not recursive. In fact, it's exactly the same approach as the first one, plus a bit of an if statement. Take another good look at the definition of "recursion" I'm sure you were given. To sum it up: "iterate": use a loop. and again. and again. and again. and again. and aga.... "recurse": consider. recurse. This is another good one: http://mytechquest.com/blog/wp-content/uploads/2010/05/From-a-Programming-Book.jpg - Thomas PS: If you think you're thinking, then you're really only thinking that you're thinking. Or are you? From python at mrabarnett.plus.com Thu Aug 19 17:45:53 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Aug 2010 22:45:53 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4C6DA611.5090300@mrabarnett.plus.com> Baba wrote: > Level: Beginner > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf > > I am looking at the first problem in the above assignment. The > assignemnt deals, amongst others, with the ideas of iterative vs. > recursive coding approaches and i was wondering what are the > advantages of each and how to best chose between both options? > > I had a go at the first part of the exercise and it seems that i can > handle it. However i think my Recursive version can be improved. By > the way, is my code actually proper recursive code? > > part 1 iterative approach: > > from string import * > def countSubStringMatch(target,key): > counter=0 > fsi=0 #fsi=find string index > while fsi fsi=target.find(key,fsi) > #print fsi > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatch("atgacatgcacaagtatgcat","zzz") > > > part 2 recursive approach: > > > def countSubStringMatchRecursive(target,key): > counter=0 > fsi=0 #fsi=find string index > if len(key)==len(target): #base case > if key==target: > counter+=1 > elif len(key) while fsi fsi=target.find(key,fsi) > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > else: > print 'key is longer than target...' > > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcatatgc") > 'countSubStringMatchRecursive' isn't recursive at all. From dan.kluev at gmail.com Thu Aug 19 17:48:33 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Fri, 20 Aug 2010 08:48:33 +1100 Subject: Iterative vs. Recursive coding In-Reply-To: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 8:12 AM, Baba wrote: > Level: Beginner > > exercise source: > > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf > > I am looking at the first problem in the above assignment. The > assignemnt deals, amongst others, with the ideas of iterative vs. > recursive coding approaches and i was wondering what are the > advantages of each and how to best chose between both options? > > With Python, I'd avoid using recursions unless it is absolutely needed / much simpler than iteration and depth is known in advance, and not exceeds the limit. Reason is that Python does not optimize recursion calls, and even tail recursions get own stack frame on each call. It is more expensive than iteration and risks to exceed max recursion depth. part 2 recursive approach: > > > def countSubStringMatchRecursive(target,key): > counter=0 > fsi=0 #fsi=find string index > if len(key)==len(target): #base case > if key==target: > counter+=1 > elif len(key) while fsi fsi=target.find(key,fsi) > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > else: > print 'key is longer than target...' > > print '%s is %d times in the target string' %(key,counter) > > > countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcatatgc") > Maybe I'm missing something, but this one seems to be iterative too. Recursive is one which calls itself, like def countSubString(haystack, needle): def checkMatch(haystack, needle): if not needle: return True elif not haystack: return False elif haystack[0] == needle[0]: return checkMatch(haystack[1:], needle[1:]) else: return False return len(filter(bool, map(lambda i: checkMatch(haystack[i:], needle), range(len(haystack))))) Where checkMatch would be called recursively to match needle over particular part of haystack. -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Thu Aug 19 17:53:16 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Thu, 19 Aug 2010 23:53:16 +0200 Subject: Creating a PYD file In-Reply-To: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> References: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> Message-ID: > (Pseudo code) > > result = arg1 + arg2 > return result For this code, the manually-written version will most likely be faster than the Pyrex-generated one. This is, most likely, because the manually-written version will assume a specific data type for the arguments (e.g. int), which Pyrex will not. As a consequence, the manually-written version will be more restricted than the Pyrex one, and most likely, that will be acceptable in your application. Theoretically speaking. Regards, Martin From martin at address-in-sig.invalid Thu Aug 19 18:00:16 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Thu, 19 Aug 2010 22:00:16 +0000 (UTC) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: On Thu, 19 Aug 2010 14:12:44 -0700, Baba wrote: > Level: Beginner > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer- science/6-00-introduction-to-computer-science-and-programming-fall-2008/ assignments/pset3.pdf > > I am looking at the first problem in the above assignment. The > assignemnt deals, amongst others, with the ideas of iterative vs. > recursive coding approaches and i was wondering what are the advantages > of each and how to best chose between both options? > > I had a go at the first part of the exercise and it seems that i can > handle it. However i think my Recursive version can be improved. By the > way, is my code actually proper recursive code? > No, it isn't. By way of a hint, here are two versions of the classic example of recursion: calculating factorials. Recursion can be quite a trick to get your mind round at first, so compare the two and follow through their operation step by step... ------------------------------------------------- def i_factorial(n): "Iterative factorial calculation" f = 1; for n in range(1, n+1): f = f * n return f def r_factorial(n): "Recursive factorial calculation" if (n > 1): return n * r_factorial(n - 1) else: return 1 print i_factorial.__doc__ for n in range(1,10): print "%d! = %d" % (n, i_factorial(n)) print r_factorial.__doc__ for n in range(1,10): print "%d! = %d" % (n, r_factorial(n)) ----------------------------------------- In case you're wondering "print i_factorial.__doc__" prints the docstring out of the i_factorial subroutine. You probably haven't covered that yet, but run it and see. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From thomas at jollybox.de Thu Aug 19 18:04:29 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 20 Aug 2010 00:04:29 +0200 Subject: Reading the access attributes of directories in Windows In-Reply-To: <4C6D7E2A.9010703@timgolden.me.uk> References: <4C6D7E2A.9010703@timgolden.me.uk> Message-ID: <201008200004.30289.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to Tim Golden to exclaim: > On 19/08/2010 4:55 PM, vsoler wrote: > > I've been looking in the "os" library, and found the "os.chmod" method > > but I am not sure that it is going to give me what I need. Should I > > also used library "stat"? > > No. Both of these are basically doing a best-endeavours job of mapping > certain Windows attributes to some Posix equivalent. They're essentially > useless for anything beyond the most trivial tasks. This brings up an interesting, but probably quite complicated question: is it reasonable to try to express Windows permissions using full POSIX ACLs (not the traditional UNIX mode, the full-featured complex beast that most users know nothing about and that many file systems don't enable by default) -- or is it, maybe, possible to express the Windows permissions model as a subset of POSIX ACL? I'm no expert either, but the basic idea is that you replace the traditional UNIX model with one where not only does every file have an owner and an owning group, and r/w/x permission bits for owner, group, and "the rest", but you can also specify permissions for arbitrary users and groups, in addition to the standard set. I'm leaving out all the details, of course, first and foremost those I don't know about myself, but that's essentially it. Do Windows NT permissions do anything more? Or, apart from the "executable" bit, anything less, for that matter? Just asking. Maybe there are some experts around. - Thomas From davea at ieee.org Thu Aug 19 18:15:15 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 19 Aug 2010 18:15:15 -0400 Subject: Iterative vs. Recursive coding In-Reply-To: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4C6DACF3.3010103@ieee.org> Baba wrote: > Level: Beginner > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf > > I am looking at the first problem in the above assignment. The > assignemnt deals, amongst others, with the ideas of iterative vs. > recursive coding approaches and i was wondering what are the > advantages of each and how to best chose between both options? > > I had a go at the first part of the exercise and it seems that i can > handle it. However i think my Recursive version can be improved. By > the way, is my code actually proper recursive code? > > part 1 iterative approach: > > from string import * > def countSubStringMatch(target,key): > counter=0 > fsi=0 #fsi=find string index > while fsi fsi=target.find(key,fsi) > #print fsi > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatch("atgacatgcacaagtatgcat","zzz") > > > part 2 recursive approach: > > > def countSubStringMatchRecursive(target,key): > counter=0 > fsi=0 #fsi=find string index > if len(key)==len(target): #base case > if key==target: > counter+=1 > elif len(key) while fsi fsi=target.find(key,fsi) > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > else: > print 'key is longer than target...' > > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcatatgc") > > > tnx > Baba > > A function that doesn't call itself (directly or indirectly) isn't recursive. So you don't have any recursion here. An example of recursion might be where your function simply compares the key to the beginning of the target, then calls itself with a substring of the target ( target[1:] ) Don't forget to return 0 if the target is smaller than the key. And take the print out of the recursive function. Write a separate function that does that, after calling the worker function. DaveA From nobody at nowhere.com Thu Aug 19 18:40:15 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 19 Aug 2010 23:40:15 +0100 Subject: path to data files References: <87wrrm9445.fsf@dpt-info.u-strasbg.fr> Message-ID: On Thu, 19 Aug 2010 14:30:34 +0200, Alain Ketterlin wrote: >> If a python module requires a data file to run how would I reference >> this data file in the source in a way that does not depend on whether >> the module is installed system-wide, installed in $HOME/.local or is >> just placed in a directory from where the interpreter is fired up? > > sys.path[0] is supposed to contain the script's directory. One caveat: if you use wxPython, wxversion.select() pushes the directory containing the selected version at the front of sys.path, so that a subsequent "import wx" will import the correct version. It's possible that other functions may do likewise, so if you're relying upon sys.path[0] to find the script's directory, it's a good idea to make a copy of sys.path[0] before importing any modules (other than sys). From python at mrabarnett.plus.com Thu Aug 19 19:04:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 20 Aug 2010 00:04:26 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: <201008192341.36445.thomas@jollybox.de> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <201008192341.36445.thomas@jollybox.de> Message-ID: <4C6DB87A.5040100@mrabarnett.plus.com> Thomas Jollans wrote: [snip] > "iterate": use a loop. and again. and again. and again. and again. and aga.... > > "recurse": consider. recurse. > > This is another good one: > > http://mytechquest.com/blog/wp-content/uploads/2010/05/From-a-Programming-Book.jpg > The definition for recursion looks a lot like that for infinite loop. Perhaps because it's tail-recursive? From nobody at nowhere.com Thu Aug 19 19:08:03 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 20 Aug 2010 00:08:03 +0100 Subject: Reading the access attributes of directories in Windows References: <4C6D7E2A.9010703@timgolden.me.uk> Message-ID: On Fri, 20 Aug 2010 00:04:29 +0200, Thomas Jollans wrote: > This brings up an interesting, but probably quite complicated question: is it > reasonable to try to express Windows permissions using full POSIX ACLs > Do Windows NT permissions do anything more? Or, apart from the > "executable" bit, anything less, for that matter? 1. There are far more permission types than just "rwx". Specifically: For files: Execute File Read Data Write Data Append Data For folders: Traverse Folder List Folder Create Files Create Folders Delete Subfolders and Files For both: Full Control Read Attributes Read Extended Attributes Write Attributes Write Extended Attributes Delete Read Permissions Change Permissions Take Ownership Note that files/folders have a distinct "Delete" permission, as well as the "Delete Subfolders and Files" permission on the parent folder. Unix lacks the "Append Data" permission for files, and the "Create Files", "Create Folders" and "Delete Subfolders and Files" correspond to having write permission on a directory. On Unix, you can read permissions (and attributes if the filesystem has them) for any file which you can "reach" (i.e. have "x" permission on all ancestor directories). You can only change permissions (and some attributes) if you own the file, and only root can change ownership (and change some attributes). 2. Permissions can be inherited from the "parent object" (which isn't necessarily the parent folder). If you change a permission on the parent object, it automatically affects any file or folder which inherits the permission. 3. The owner can be either a user or a group. 4. On Windows, a file cannot be "given away" either by its owner or an administrator. You can grant the "Take Ownership" permission, but the recipient still has to explicitly change the ownership. From tundra at tundraware.com Thu Aug 19 19:27:11 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 19 Aug 2010 18:27:11 -0500 Subject: Using String Methods In Jump Tables Message-ID: Problem: Given tuples in the form (key, string), use 'key' to determine what string method to apply to the string: key operation ----------------------- l lower() u upper() t title() ... Commentary: Easy, right? Well ... except that I would really, really like to avoid cascading ifs or eval based solutions. I'd like to implement this as a jump table dictionary: jt = { 'l' : lower_function reference, 'u' : upper_function reference, ... } So I could then do this: string = jt[key](string) But There's A Problem: I tried to do this: jt = {'l', "".lower, 'u', "".upper, ... } You can get away with this because all string objects appear to point to common method objects. That is,: id("a".lower) == id("b".lower) HOWEVER, you cannot then do this: string = jt[key](string) Why? Because the methods of a string, while common to all strings *do not accept an arg*. They are implemented to "know" about the string instance they "belong to" (that contains them). (Forgive me here, I am probably not using some of the OO arcana properly...) I realize that the string module has many of the same functions that are found as methods on strings. But it doesn't have all of them - the .title() method is notably absent. If this were not the case, I could happily do things like 'l' : string.lower and my approach would work fine. Even if I could use the string module, I'd still be curious though: How do you get a reference to a method found in one object instance, but actually apply it to another instance of the same class? I'm guessing this may involve fiddling with some of the internal __ variables, but I'm not quite sure where to go next. As I said, I know I could do this as a set of cascading ifs or even as an eval, but I'm loathe to use such approaches. I like jump tables as a structural construct because they are easy to understand and maintain. I also realize that what I'm asking may be violating some deeply held notion of OO purity, but, well, now I'm just curious if there is a way to do this ... ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From nfdisco at gmail.com Thu Aug 19 19:39:10 2010 From: nfdisco at gmail.com (ernest) Date: Thu, 19 Aug 2010 16:39:10 -0700 (PDT) Subject: expression in an if statement References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> <201008190012.32074.thomas@jollybox.de> Message-ID: <8c31eb1c-bf5e-4774-aec0-5fca14547482@j18g2000yqd.googlegroups.com> On 19 Ago, 08:40, Frederic Rentsch wrote: > On Thu, 2010-08-19 at 00:12 +0200, Thomas Jollans wrote: > > On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: > > > On 8/18/2010 11:24 AM, ernest wrote: > > > > Hi, > > > > > In this code: > > > > > if set(a).union(b) == set(a): pass > > > > > Does Python compute set(a) twice? > > > > ? ? CPython does. ?Shed Skin might optimize. ?Don't know > > > about Iron Python. > > > I doubt any actual Python implementation optimizes this -- how could it? > > And why should it if a programmer uses its facilities inefficiently. I > would write > > >>> if set(a).issuperset (b): pass > > Frederic Yes, maybe the example is silly, but situations like this arise frequently and it's good to know. Thanks for the answers. Ernest From clp2 at rebertia.com Thu Aug 19 19:41:27 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 19 Aug 2010 16:41:27 -0700 Subject: Using String Methods In Jump Tables In-Reply-To: References: Message-ID: On Thu, Aug 19, 2010 at 4:27 PM, Tim Daneliuk wrote: > Problem: > > ?Given tuples in the form (key, string), use 'key' to determine > ?what string method to apply to the string: > > ? ?key ? ? ? ? ? operation > ? ?----------------------- > > ? ? l ? ? ? ? ? ?lower() > ? ? u ? ? ? ? ? ?upper() > ? ? t ? ? ? ? ? ?title() > ? ? ... > > Commentary: > > ? Easy, right? ?Well ... except that I would really, really like > ? to avoid cascading ifs or eval based solutions. ?I'd like to implement > ? this as a jump table dictionary: > > ? ? jt = { 'l' : lower_function reference, > ? ? ? ? ? ?'u' : upper_function reference, > ? ? ? ? ? ? ... > ? ? ? ? ?} > > ? So I could then do this: > > ? ? string = jt[key](string) > > But There's A Problem: > > ? I tried to do this: > > ? ? jt = {'l', "".lower, > ? ? ? ? ? 'u', "".upper, > ? ? ? ? ? ... > ? ? ? ? ?} > > ? You can get away with this because all string objects appear to point to common > ? method objects. ?That is,: id("a".lower) == id("b".lower) > > ? HOWEVER, you cannot then do this: > > ? ? string = jt[key](string) > > ? Why? ?Because the methods of a string, while common to all strings > ? *do not accept an arg*. ?They are implemented to "know" about the > ? string instance they "belong to" (that contains them). Right; by looking the method up on an instance you get a "bound" method that is "bound" to the instance you got it from and already has self filled-in. > (Forgive me here, I am probably not using some of the OO arcana properly...) > > > ? How do you get a reference to a method found in one object instance, but > ? actually apply it to another instance of the same class? ?I'm guessing this may > ? involve fiddling with some of the internal __ variables, but I'm not > ? quite sure where to go next. You must access the method from the class rather than the instance; this produces an "unbound" method that is not bound to a specific instance and does not have self already filled-in. In your dictionary, replace "".lower with str.lower, and so on for the other methods. Cheers, Chris -- http://blog.rebertia.com From doulos05 at gmail.com Thu Aug 19 19:42:50 2010 From: doulos05 at gmail.com (JonathanB) Date: Thu, 19 Aug 2010 16:42:50 -0700 (PDT) Subject: extra rows in a CSV module output when viewed in excel 2007 References: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> Message-ID: <8e0e7501-ffd7-4faa-ada8-1a6c097d01f3@f6g2000pro.googlegroups.com> On Aug 13, 3:52?pm, alex23 wrote: > On Aug 13, 4:22?pm, JonathanB wrote: > > > ? ? ? ? writer = csv.writer(open(output, 'w'), dialect='excel') > > I think - not able to test atm - that if you open the file in 'wb' > mode instead it should be fine. changed that to writer = csv.writer(open(output,'wb'),dialect='excel') Now I get this error: TypeError: must be bytes or buffer, not str I'm using Python 3.1, maybe that changes things? From python at mrabarnett.plus.com Thu Aug 19 20:10:29 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 20 Aug 2010 01:10:29 +0100 Subject: extra rows in a CSV module output when viewed in excel 2007 In-Reply-To: <8e0e7501-ffd7-4faa-ada8-1a6c097d01f3@f6g2000pro.googlegroups.com> References: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> <8e0e7501-ffd7-4faa-ada8-1a6c097d01f3@f6g2000pro.googlegroups.com> Message-ID: <4C6DC7F5.5000300@mrabarnett.plus.com> JonathanB wrote: > On Aug 13, 3:52 pm, alex23 wrote: >> On Aug 13, 4:22 pm, JonathanB wrote: >> >>> writer = csv.writer(open(output, 'w'), dialect='excel') >> I think - not able to test atm - that if you open the file in 'wb' >> mode instead it should be fine. > > changed that to > writer = csv.writer(open(output,'wb'),dialect='excel') > > Now I get this error: > > TypeError: must be bytes or buffer, not str > > I'm using Python 3.1, maybe that changes things? You want to open the file in text mode, but not write Windows line endings (CRLF) for each newline: writer = csv.writer(open(output, 'w', newline=''), dialect='excel') From doulos05 at gmail.com Thu Aug 19 20:15:47 2010 From: doulos05 at gmail.com (JonathanB) Date: Thu, 19 Aug 2010 17:15:47 -0700 (PDT) Subject: extra rows in a CSV module output when viewed in excel 2007 References: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> <8e0e7501-ffd7-4faa-ada8-1a6c097d01f3@f6g2000pro.googlegroups.com> Message-ID: On Aug 20, 9:10?am, MRAB wrote: > JonathanB wrote: > > On Aug 13, 3:52 pm, alex23 wrote: > >> On Aug 13, 4:22 pm, JonathanB wrote: > > >>> ? ? ? ? writer = csv.writer(open(output, 'w'), dialect='excel') > >> I think - not able to test atm - that if you open the file in 'wb' > >> mode instead it should be fine. > > > changed that to > > writer = csv.writer(open(output,'wb'),dialect='excel') > > > Now I get this error: > > > TypeError: must be bytes or buffer, not str > > > I'm using Python 3.1, maybe that changes things? > > You want to open the file in text mode, but not write Windows line > endings (CRLF) for each newline: > > ? ? ?writer = csv.writer(open(output, 'w', newline=''), dialect='excel') That was it! Thank you, I knew it was something stupid. It's been so long (6 months) since I coded, I forgot about how Windows/Mac mangle line endings. From cri at tiac.net Thu Aug 19 20:18:29 2010 From: cri at tiac.net (Richard Harter) Date: Fri, 20 Aug 2010 00:18:29 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: <4c6d56b0.616794210@text.giganews.com> On Thu, 19 Aug 2010 04:14:42 -0700 (PDT), spinoza1111 wrote: >On Aug 18, 1:44=A0am, James Kanze wrote: >> On Aug 17, 6:21 pm, Standish P wrote: >> >> > > Garbage collection doesn't use a stack. It uses a "heap", >> > > which is in the abstract a collection of memory blocks of >> > > different lengths, divided into two lists, generally >> > > represented as linked lists: >> > > 1. =A0A list of blocks that are free and may be used to store >> > > new data >> > > 2. =A0A list of blocks that are in use, or haven't been freed (yet) >> > Is this all that a heap is or is there more to it ? >> >> There are many different ways to implement a heap. =A0The above is >> not a good one, and I doubt that it's really used anywhere. > >Actually, that's the only way to implement a heap in the abstract. >Forest and trees, mate. Mathematically a heap is a block of storage, a >list of free blocks and a list of allocated blocks. All the rest is >detail for the little techies to normally, get wrong. The confusion >between scientific and technical progress is a mirror of the (far more >serious) confusion between scientific progress and ethical advance. > >Sure, when you free a block it is a good idea to see if you can join >it with its neighbors to get the biggest "bang for the buck". [snip] I appreciate your desire to provide a "mathematical" definition but the one you gave won't quite do. Your definition does not specify what is meant by a block. The notion of defining a heap as a list of free list and a list of allocated blocks is unfortunate. Neither a free list nor a list of allocated blocks is of the essence. It isn't easy to give a good definition of a heap (in the sense of a storage heap) but here is a shot at it. A heap is a data structure consisting of a pair (H,B) of substructures, operations (split,join), and attribute A where: H is a set of sequentially addressable elements. That is, the elements form a sequence, each element has an integer associated with it (its address) and the difference between the addresses of successive elements is a constant, w. Let h_i be the address of the initial element of H and h_f be the address of the final element of H. B is a set of integers such that (1) each element b of B is an address of an element of H, and (2) h_i and h_f are elements of B. From this definition we can define the successor succ(b) of each element (h_f has no successor) and we can order B if we wish. Given the construction of succ on B we can define block(b) as the set of elements in H such that their addresses a satisfy b <= a < succ(a) It is trivial to prove that the blocks of B divide H into disjoint subsets that cover H. The attribute A is defined for elements of B. A(b) may have either of two values - free and inuse. A block b is said to be free if A(b) = free and in use if A(b) = inuse. An address, h, of H is said to be free if A(largest address b in B that is <= h) = free and in use otherwise. Now for the two operations: The join operator operates on all free elements of b except h_f. It removes the successor of an element of b. The effect is to set succ(b) := succ(succ(b)). The split operator operates on all free element addresses in H that are not element addresses in B. Let s be the argument for split. Split adds s to B. The effect of split is to find the largest address b in B that is smaller than s, set succ(s) := succ(b) and succ(b) := s. Note that the successor changes implicitly follow from the definitions of H, B, split, and join. The above definition covers defining a storage heap. It establishes what blocks are, what the sequence of blocks is, and how to alter the sequence of blocks. The important thing here is that free lists/allocated lists are not basic abstractions; rather they are derived concepts based on the primitive concept of a block and the operations performed on a set of blocks. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 20:23:57 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2010 00:23:57 GMT Subject: Using String Methods In Jump Tables References: Message-ID: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: > Problem: > > Given tuples in the form (key, string), use 'key' to determine what > string method to apply to the string: >>> table = {'l': str.lower, 'u': str.upper} >>> table['u']('hello world') 'HELLO WORLD' [...] > As I said, I know I could do this as a set of cascading ifs or even as > an eval, but I'm loathe to use such approaches. I like jump tables as a > structural construct because they are easy to understand and maintain. I > also realize that what I'm asking may be violating some deeply held > notion of OO purity, but, well, now I'm just curious if there is a way > to do this This is Python, not some "pure" OO language. We have functional programming constructs, procedural constructs, and probably other programming models as well. Screw the deeply held notion of OO purity :) But seriously, Python's object model includes bound and unbound methods precisely so you can do this sort of thing, and the above table-based approach is very common and recommended as an alternative to case/switch statements. It's a very common Pythonic idiom, so never fear that people will stone you for using it. The only thing that is a bit unusual is that you call it a jump table. In my experience, "Jump Table" is used for low-level languages where the table values are memory addresses. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 20:26:45 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2010 00:26:45 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: > Recursion can be quite a trick to get your mind round at first Really? Do people actually find the *concept* of recursion to be tricky? If I remember correctly, my puzzlement about recursion lasted about 15 seconds. I remember thinking "How does the function foo know that there is a function foo when foo doesn't fully exist yet?", but once I accepted the fact that it just does it all just seemed obvious. Getting recursion *right* is sometimes tricky, but the idea itself isn't. But then, I grew up watching Doctor Who, and had no problem with the idea that the TARDIS could materialise *inside itself*. And from a very early age, I was familiar with a particular brand of Advocaat liquor where the label on the bottle contained a picture of a rooster holding a bottom of Advocaat, whose label contained a picture of a rooster holding a bottle of Advocaat, whose label contained a picture of a rooster holding a bottle, whose label ... well, you can see where that is going. -- Steven From tundra at tundraware.com Thu Aug 19 20:51:33 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 19 Aug 2010 19:51:33 -0500 Subject: Using String Methods In Jump Tables In-Reply-To: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: On 8/19/2010 7:23 PM, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: > >> Problem: >> >> Given tuples in the form (key, string), use 'key' to determine what >> string method to apply to the string: > >>>> table = {'l': str.lower, 'u': str.upper} >>>> table['u']('hello world') > 'HELLO WORLD' > Aha! That's just what I was looking for. > > [...] >> As I said, I know I could do this as a set of cascading ifs or even as >> an eval, but I'm loathe to use such approaches. I like jump tables as a >> structural construct because they are easy to understand and maintain. I >> also realize that what I'm asking may be violating some deeply held >> notion of OO purity, but, well, now I'm just curious if there is a way >> to do this > > This is Python, not some "pure" OO language. We have functional > programming constructs, procedural constructs, and probably other > programming models as well. Screw the deeply held notion of OO purity :) Yeah, I've never been much impressed with the OO purists. One of the best speeches on the subject I ever saw was by David Korn (of ksh fame) who did a presentation at USENIX one year called "Objecting To Objects". He documented an attempt to write a compiler using purely OO constructs and the many rings of hell that ensued. > > But seriously, Python's object model includes bound and unbound methods > precisely so you can do this sort of thing, and the above table-based > approach is very common and recommended as an alternative to case/switch > statements. It's a very common Pythonic idiom, so never fear that people > will stone you for using it. +1 > > The only thing that is a bit unusual is that you call it a jump table. In > my experience, "Jump Table" is used for low-level languages where the > table values are memory addresses. > > Yeah ... those old assembler memories never quite fade do they. I dunno what you might call this. A Function Dispatch Table perhaps? Thanks to both you and Chris for setting me straight :) -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From tundra at tundraware.com Thu Aug 19 20:52:29 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 19 Aug 2010 19:52:29 -0500 Subject: Using String Methods In Jump Tables In-Reply-To: References: Message-ID: On 8/19/2010 6:41 PM, Chris Rebert wrote: > >> >> How do you get a reference to a method found in one object instance, but >> actually apply it to another instance of the same class? I'm guessing this may >> involve fiddling with some of the internal __ variables, but I'm not >> quite sure where to go next. > > You must access the method from the class rather than the instance; > this produces an "unbound" method that is not bound to a specific > instance and does not have self already filled-in. > In your dictionary, replace "".lower with str.lower, and so on for the > other methods. > > Cheers, > Chris > -- > http://blog.rebertia.com Thanks Chris - just what I needed ... -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From ahleniusm at gmail.com Thu Aug 19 22:02:57 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Thu, 19 Aug 2010 19:02:57 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? Message-ID: Hi, I am relatively new to doing serious work in python. I am using it to access a large number of log files. Some of the logs get corrupted and I need to detect that when processing them. This code seems to work for quite a few of the logs (all same structure) It also correctly identifies some corrupt logs but then it identifies others as being corrupt when they are not. example error msg from below code: Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' Exception: CRC check\ failed 0x8967e931 != 0x4e5f1036L When I manually examine the supposed corrupt log file and use "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " on it, it opens just fine. Is there anything wrong with how I am using this module? (extra code removed for clarity) if tarfile.is_tarfile( file ): try: xf = tarfile.open( file, "r:gz" ) for locFile in xf: logfile = xf.extractfile( locFile ) validFileFlag = True # iterate through each log file, grab the first and the last lines lines = iter( logfile ) firstLine = lines.next() for nextLine in lines: .... continue logfile.close() ... xf.close() except Exception, e: validFileFlag = False msg = "\nCould not open the log file: " + repr(file) + " Exception: " + str(e) + "\n" else: validFileFlag = False lTime = extractFileNameTime( file ) msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive \n" print msg From ldo at geek-central.gen.new_zealand Thu Aug 19 23:09:39 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 20 Aug 2010 15:09:39 +1200 Subject: 79 chars or more? References: Message-ID: In message , Terry Reedy wrote: > A reason not mentioned much is that some people have trouble following > packed lines that are too much longer. Wide-page textbooks routinely put > text in two columns for easier reading. But even 79 columns is too wide for them. So what? From ldo at geek-central.gen.new_zealand Thu Aug 19 23:15:56 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 20 Aug 2010 15:15:56 +1200 Subject: path to data files References: Message-ID: In message , Daniel Fetchinson wrote: > If a python module requires a data file to run how would I reference > this data file in the source in a way that does not depend on whether > the module is installed system-wide, installed in $HOME/.local or is > just placed in a directory from where the interpreter is fired up? You may want to look at the XDG Base Directory Specification . There is a python- xdg module which implements this. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 23:49:05 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2010 03:49:05 GMT Subject: 79 chars or more? References: Message-ID: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 15:09:39 +1200, Lawrence D'Oliveiro wrote: > In message , Terry > Reedy wrote: > >> A reason not mentioned much is that some people have trouble following >> packed lines that are too much longer. Wide-page textbooks routinely >> put text in two columns for easier reading. > > But even 79 columns is too wide for them. So what? I think you're wrong. I just opened a random text book at a random page, and the first line I counted had 84 columns of text. ("Data Structures and Program Design", 2nd Edition, by Robert L Kruse.) Of course source code is written in a monospaced typeface, which is a little wider and consequently fewer characters per page. The book uses right-justified comments, making it easy to count that the maximum line- width used for source code is 79 columns. Most lines are *much* shorter. Excluding comments, the longest line of code I spotted was 64 columns, with a typical line being more like 40 columns. -- Steven From nagle at animats.com Fri Aug 20 00:53:55 2010 From: nagle at animats.com (John Nagle) Date: Thu, 19 Aug 2010 21:53:55 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4c6e0a5e$0$1647$742ec2ed@news.sonic.net> On 8/19/2010 2:41 PM, Thomas Jollans wrote: > On Thursday 19 August 2010, it occurred to Baba to exclaim: > This is not recursive. In fact, it's exactly the same approach as > the first one, plus a bit of an if statement. Right. The original poster seems to be getting their ideas from "http://stackoverflow.com/questions/2308696/substring-recursive-algorithm-not-working" which is a rather confused article, or http://talkbinary.com/programming/c/c-recursion-palindrome/ which really has a recursive, although inefficient, example. If you're really interested in this area, read up on the Boyer-Moore Fast String Search Algorithm, which is the fast way to do this for long strings. For Python, a quick solution is def countSubStringMatch(target, key) : esckey = re.sub(r'(\W)',r'\\\1',key) # put \ escapes into key cnt = len(re.findall(esckey, target)) # find all key and count print('%s is %d times in the target string' %(key,cnt)) >>> countSubStringMatch("atgacatgcacaagtatgcat","ca") ca is 4 times in the target string Enjoy. John Nagle From jrmy.lnrd at gmail.com Fri Aug 20 01:13:18 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Thu, 19 Aug 2010 22:13:18 -0700 (PDT) Subject: Assert statements in python 3.1 Message-ID: This is more of a curiosity question then anything else... I was just wondering why in version 3 of python assertions weren't converted to use parenthesis, since print was. I am just asking because it seems the following line of code would seem more readable as a function: assert 2 + 2 == 5, "Only for very large values of 2." From cs at zip.com.au Fri Aug 20 01:22:43 2010 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 20 Aug 2010 15:22:43 +1000 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D7D0D.7040703@gmail.com> References: <4C6D7D0D.7040703@gmail.com> Message-ID: <20100820052243.GA23046@cskk.homeip.net> On 19Aug2010 21:50, Nik Gr wrote: | ???? 19/8/2010 6:58 ??, ?/? Tim Chase ??????: | >It can be written as a non-3-quote string, you just have to escape | >the inner quotes (single & double) and the backslash to be seen: | > | > name = 'My name is "Nikos" and I\'m from Thessaloniki\\Greece' | > name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece" | | So if i enclose the string in double quotes the inner double quotes | have to be escaped while | if i enclose the string in single quotes the inner single quotes | have to be escaped. | | But in 3-single-quoting thing became easier since i don't have to | escape all kind of quotes right? just the backslashes. Well, unless you have the misfortune to want three single quotes in a row inside your 3-single-quoting string... [...snip...] | Why does the page variable which is actually a string needs to be a | tuple or a list and not just as a string which is what it actually | is? With regard to the "%" operator, it considers the string on the left to be a format string with multiple %blah things in it to replace. The thing on the right is a sequence of items to place into the format string. So the thing on the right is _supposed_ to | I have a strong desire to use it like this: | cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page ) | opposed to tuple. Hmm. This isn't the python "%" format operator at all. This is the database API's .execute() method. If it expects its second argument to be a sequence of parameters (which is does) then you need to supply a sequence of parameters. It is that simple! In you usage above you're supplying "page" instead of "(page,)". The latter matches the .execute() method's requirements. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ The fabs of the future will be pressrooms. - overhead by WIRED at the Intelligent Printing conference Oct2006 From nagle at animats.com Fri Aug 20 02:03:03 2010 From: nagle at animats.com (John Nagle) Date: Thu, 19 Aug 2010 23:03:03 -0700 Subject: expression in an if statement In-Reply-To: References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> Message-ID: <4c6e1a93$0$1658$742ec2ed@news.sonic.net> On 8/18/2010 3:12 PM, Thomas Jollans wrote: > On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: >> On 8/18/2010 11:24 AM, ernest wrote: >>> Hi, >>> >>> In this code: >>> >>> if set(a).union(b) == set(a): pass >>> >>> Does Python compute set(a) twice? >> >> CPython does. Shed Skin might optimize. Don't know >> about Iron Python. > > I doubt any actual Python implementation optimizes this -- how could it? The > object "set" is clearly being called twice, and it happens to be called with > the object "a" as a sole argument twice. What if "set" has side effects? A > compiler could only exclude this possibility if it knew exactly what "set" > will be at run time, which it can't. That just reflects the rather lame state of Python implementations. For some other languages, there are JIT compilers that can optimize such things. If you rebind a function at run time, the compiled code has to be invalidated and recompiled with the new binding. The HotSpot Java JIT compiler did this. See http://books.google.com/books?id=GBISkhhrHh8C&pg=PA786&lpg=PA786&dq=JIT+compiler+rebinding&source=bl&ots=GhZa3XbrNu&sig=OVBOnu0vwlVN_B1QC6jc2ltHk_w&hl=en&ei=IhluTLCXOIymsQOW6vy1Cw&sa=X&oi=book_result&ct=result&resnum=9&ved=0CDsQ6AEwCA#v=onepage&q&f=false It's really tough to get this right. There's a huge overhead in either performance or complexity for allowing rebinding of functions during execution. It's also a feature very seldom used after program startup. I was talking to the Facebook guys doing the compiler for PHP, and they said that it was a huge win for them that PHP doesn't allow dynamically replacing a function. John Nagle From nikos.the.gr33k at gmail.com Fri Aug 20 02:04:16 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Fri, 20 Aug 2010 09:04:16 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <20100820052243.GA23046@cskk.homeip.net> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> Message-ID: <4C6E1AE0.1000604@gmail.com> ???? 20/8/2010 8:22 ??, ?/? Cameron Simpson ??????: > [...snip...] > | Why does the page variable which is actually a string needs to be a > | tuple or a list and not just as a string which is what it actually > | is? > > With regard to the "%" operator, it considers the string on the left to > be a format string with multiple %blah things in it to replace. The > thing on the right is a sequence of items to place into the format > string. > I didn't undersatnd. > So the thing on the right is_supposed_ to > | I have a strong desire to use it like this: > | cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page ) > | opposed to tuple. > > Hmm. This isn't the python "%" format operator at all. > This is the database API's .execute() method. > If it expects its second argument to be a sequence of parameters > (which is does) then you need to supply a sequence of parameters. > It is that simple! > > In you usage above you're supplying "page" instead of "(page,)". > The latter matches the .execute() method's requirements. I don't follow either. From Kai.Borgolte at gmx.de Fri Aug 20 03:09:16 2010 From: Kai.Borgolte at gmx.de (Kai Borgolte) Date: Fri, 20 Aug 2010 09:09:16 +0200 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: Russ P. wrote: >> A simple example: Using zero-based indexing, suppose you want to indent >> the string "spam" so it starts at column 4. How many spaces to you >> prepend? No, you won't want to indent a string so it starts at column 4. You simply want to indent the string by four spaces. Like in PEP 8: /Use 4 spaces per indentation level./ > 0123456789 > ? ? spam And of course your text editor will number the columns beginning with one, so the string starts at column 5. 123456789 ? ? spam -- Kai Borgolte, Bonn From stndshp at gmail.com Fri Aug 20 03:13:04 2010 From: stndshp at gmail.com (Standish P) Date: Fri, 20 Aug 2010 00:13:04 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> <518b97c6-78ad-4ce9-9967-c7f72ea74109@5g2000yqz.googlegroups.com> <4c6d356f.608280081@text.giganews.com> Message-ID: <8f5c181f-9333-468c-b44c-9d54672d06e1@f42g2000yqn.googlegroups.com> On Aug 19, 8:25?am, c... at tiac.net (Richard Harter) wrote: > On Wed, 18 Aug 2010 01:39:09 -0700 (PDT), Nick Keighley > > wrote: > >On 17 Aug, 18:34, Standish P wrote: > >> How are these heaps being implemented ? Is there some illustrative > >> code or a book showing how to implement these heaps in C for example ? > >any book of algorithms I'd have thought > >http://en.wikipedia.org/wiki/Dynamic_memory_allocation > >http://www.flounder.com/inside_storage_allocation.htm > >I've no idea how good either of these is > The wikipedia page is worthless. ?The flounder page has > substantial meat, but the layout and organization is a mess. ?A > quick google search didn't turn up much that was general - most > articles are about implementations in specific environments. I second your assessment. What we have is blind leading the blind. "Keith Thompson" A CORPORATE MINDER - with multiple accounts - on a Crusade to limit discussions of useful nature on the usenet, must be giving anti-education, pro- illiteracy corporatists (who did much of studies and development on TAX-PAYER MONEY, maybe from now on we should fund Indian/Chinese/ Vietnamese/Russian/Cuban companies that have a tradition of sharing knowledge from the socialist value system) ,lots of joy because that means more market for their "user-friendly" , "thought-killing" products and high priced courses. You will see how consistently, she gives short replies, that have ZILCH educational contents, compared to the volume of details they boast on their websites they claim know. From Kai.Borgolte at gmx.de Fri Aug 20 03:21:25 2010 From: Kai.Borgolte at gmx.de (Kai Borgolte) Date: Fri, 20 Aug 2010 09:21:25 +0200 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: Sorry about my previous posting with wrong references, this one should be better. Steven D'Aprano wrote: >A simple example: Using zero-based indexing, suppose you want to indent >the string "spam" so it starts at column 4. How many spaces to you >prepend? No, you won't want to indent a string so it starts at column 4. You simply want to indent the string by four spaces. Like in PEP 8: /Use 4 spaces per indentation level./ >0123456789 > spam And of course your text editor will number the columns beginning with one, so the string starts at column 5. 123456789 ? ? spam -- Kai Borgolte, Bonn From dickinsm at gmail.com Fri Aug 20 03:27:14 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 20 Aug 2010 00:27:14 -0700 (PDT) Subject: Assert statements in python 3.1 References: Message-ID: On Aug 20, 6:13?am, genxtech wrote: > This is more of a curiosity question then anything else... ?I was just > wondering why in version 3 of python assertions weren't converted to > use parenthesis, since print was. > > I am just asking because it seems the following line of code would > seem more readable as a function: > ? ?assert 2 + 2 == 5, "Only for very large values of 2." Well, part of the idea of asserts is that when you're running with optimizations turned on (python -O), asserts should be disabled. But if assert were a normal function then in assert(expensive_check) the argument expensive_check would be evaluated both with 'python' and with 'python -O'. -- Mark From mail at timgolden.me.uk Fri Aug 20 03:36:12 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Aug 2010 08:36:12 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> Message-ID: <4C6E306C.20101@timgolden.me.uk> > I currently do not have subversion access in my PC. I could try to > install a free copy of it. But it you could ptovide an installer, it > certainly would do things easier. Please let me know if it is > possible. Vicente, can you just confirm that you received the installer I sent offlist? I'll try to put winsys on PyPI with installers; just haven't got round to it yes :) TJG From news1234 at free.fr Fri Aug 20 03:47:30 2010 From: news1234 at free.fr (News123) Date: Fri, 20 Aug 2010 09:47:30 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c6e3313$0$16599$426a74cc@news.free.fr> On 08/20/2010 02:26 AM, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: > >> Recursion can be quite a trick to get your mind round at first > > Really? Do people actually find the *concept* of recursion to be tricky? Is this a sincere surprise or are you just boasting? > > If I remember correctly, my puzzlement about recursion lasted about 15 > seconds. I remember thinking "How does the function foo know that there > is a function foo when foo doesn't fully exist yet?", but once I accepted > the fact that it just does it all just seemed obvious. Getting recursion > *right* is sometimes tricky, but the idea itself isn't. Well there's two things where I remember, that at least quite some people in our class (at least the ones who didn't do maths or programming in their spare time) had problems with. This were recursion and Mathematical induction. (quite the same though) The fact, that you didn't have the issue doens't mean it's easy for others. From kara at kara-moon.com Fri Aug 20 04:16:56 2010 From: kara at kara-moon.com (Rony) Date: Fri, 20 Aug 2010 01:16:56 -0700 (PDT) Subject: A question to experienced Pythoneers Message-ID: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Here's the story : I've been hired by a company as a consultant to reorganise there development department. The actual situation is : The manager of the development has been fired, main reason (what they told me) is that they have big big troubles in keeping deadlines ! For there last product, for which they estimated 3 man years of development they had 9 months extra effort, and the product was delivered a year to late. I basicaly have 'carte blanche' :) One of my plans is to introduce Python as development tool. They mostly develop back-office software, and at the moment they do it all in C with MFC. Another new requirement they have, is that the new product should run on Win & Mac. So, my strategie would be : - Use Python and wxpython for the GUI - Develop critical routines in Pyrex or in C and make PYD's from it which will be imported by the main Python programm. - Distribute with py2exe on Win & py2app for Mac. What do you think of this ? Another point of attention is that the software isn't Open Source, it is a commercial package. So protection of sources is important. Now I know that anything can be decompiled, even C. The only question is, how hard is it and how much effort must someone do to decompile and retro engineer code to understand it. I think by putting all program logic in Pyd files that I would be quite secure ? On a side note : Is it harder to decompile PYD files then PYC files ? I allready had a meeting with the developpers and did a presentation of python with wxwindow, mostly with an open source project where I contribute to the development. They didn't see any big problems to learn Python fast and they allready know C. All opinions, advice here is welcome :) Tia Rony From martin.braun at kit.edu Fri Aug 20 04:23:08 2010 From: martin.braun at kit.edu (Martin Braun) Date: Fri, 20 Aug 2010 10:23:08 +0200 Subject: Python "why" questions In-Reply-To: <4c6d826e$0$11111$c3e8da3@news.astraweb.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> Message-ID: <20100820082308.GA3258@int.uni-karlsruhe.de> On Thu, Aug 19, 2010 at 07:13:50PM +0000, Steven D'Aprano wrote: > Mathematics is an ancient art that values tradition and convention. It > doesn't matter how hard it was to come up with a proof, or how difficult > to verify it. Mathematicians value logical correctness and some > undefinable sense of elegance over how easy it is to verify, the > readability of the notation, resistance to errors, and the ability of > mediocre mathematicians to make useful contributions. Mathematical > notation and conventions are not, by any stretch of the imagination, > designed to reduce errors. Mathematicians consider it a good thing that > they are still mostly using the same notation invented by (say) Leibniz. Another thing worth mentioning (I guess here is a good a place as any other) is the fact that programming and mathematics are still pretty different things, despite how much we programmers would like to think ourselves as some kind of mathematician. Fields-medal winners are not likely to be writing database applications in their spare time, or to save up money for blackboards and pencils. But mathematics is a wide field, and one area I'm very familiar in is signal processing, which has taken a lot of mathematics to make our algorithms work. In fact, of all electrical engineering disciplines, signal processing is probably the most mathematical. I find this thread extremely interesting, but what surprised me that everyone seems to agree that mathematics is 1-based, but we Pythoneers should stick to zero-based. I disagree. To make sure I'm not going crazy, I took the top five books lying on my desk, which were the DSP book by Oppenheim/Schafer, two books by Stephen M. Kay (Spectral Estimation and Estimation Theory) and the Channel Coding book by Lin & Costello. This is isn't pure mathematics (as in proving the Goldbach conjecture), but nevertheless, this is serious mathematics and, surprise, they most exclusively use zero-based notation. You probably don't have those books in grabbing distance, so here's some examples for zero-based stuff: - The definition of the FFT and one-sided z-transform (practically everywhere I've seen) - Time indices for time-discrete signals usually start at 0 for causal signals, same goes for filters (impulse responses) - Vector representation of polynomials - The Levinson-Durbin recursion algorithm is way more readable with zero-based indices (step 0 is an initialisation step) - Even most matrices used in the context for coding use zero-based indexing (i.e., the left-most column is column zero). I would like to add that dealing with linear algebra in GF2 is a bit different from handling complex signals as in the previous examples, so this is something to consider. I realize a lot of this has it's root in the application, e.g. shift-registers (index 0 means it's run through 0 shift registers). But it's been adopted for the mathematics because it's useful there as well (e.g. because x^0 = 1 for any non-zero value of x). Both mathematics and programming have two kinds of iterations: where index matters, and where it doesn't (why not iterate 'apple', 'banana', 'cherry' etc.). In practically all cases I deal with where the index matters, zero-based suits me better. The one-based indexing Matlab uses drives me crazy, and that's specifically designed for engineers. Martin -- Karlsruhe Institute of Technology (KIT) Communications Engineering Lab (CEL) Dipl.-Ing. Martin Braun Research Associate Kaiserstra?e 12 Building 05.01 76131 Karlsruhe Phone: +49 721 608-3790 Fax: +49 721 608-6071 www.cel.kit.edu KIT -- University of the State of Baden-W?rttemberg and National Laboratory of the Helmholtz Association -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From navkirats at gmail.com Fri Aug 20 04:24:30 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 20 Aug 2010 13:54:30 +0530 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6e3313$0$16599$426a74cc@news.free.fr> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> Message-ID: On 20-Aug-2010, at 1:17 PM, News123 wrote: > On 08/20/2010 02:26 AM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be tricky? > Is this a sincere surprise or are you just boasting? >> >> If I remember correctly, my puzzlement about recursion lasted about 15 >> seconds. I remember thinking "How does the function foo know that there >> is a function foo when foo doesn't fully exist yet?", but once I accepted >> the fact that it just does it all just seemed obvious. Getting recursion >> *right* is sometimes tricky, but the idea itself isn't. > > Well there's two things where I remember, that at least quite some > people in our class (at least the ones who didn't do maths or > programming in their spare time) had problems with. > > This were recursion and Mathematical induction. (quite the same though) > > The fact, that you didn't have the issue doens't mean it's easy for others. > > > > -- > http://mail.python.org/mailman/listinfo/python-list Well I guess why you did not have a problem understanding recursion is because you took for granted that it is the way it is. Most people, like me, try to reason why something is the way it is ! Hence, the delay in understanding the concept fully. From debatem1 at gmail.com Fri Aug 20 04:30:45 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 20 Aug 2010 01:30:45 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6e3313$0$16599$426a74cc@news.free.fr> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> Message-ID: On Fri, Aug 20, 2010 at 12:47 AM, News123 wrote: > On 08/20/2010 02:26 AM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be tricky? > Is this a sincere surprise or are you just boasting? I think his point is that the confusion is on how to do it right, not the concept of it. Geremy Condra From debatem1 at gmail.com Fri Aug 20 05:25:07 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 20 Aug 2010 02:25:07 -0700 Subject: A question to experienced Pythoneers In-Reply-To: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 1:16 AM, Rony wrote: > Here's the story : > I've been hired by a company as a consultant to reorganise there > development department. > The actual situation is : > The manager of the development has been fired, main reason (what they > told me) is that they have big big troubles in keeping deadlines ! For > there last product, for which they estimated 3 man years of > development they had 9 months extra effort, and the product was > delivered a year to late. > > I basicaly have 'carte blanche' :) > > One of my plans is to introduce Python as development tool. > They mostly develop back-office software, and at the moment they do it > all in C with MFC. > Another new requirement they have, is that the new product should run > on Win & Mac. > > So, my strategie would be : > - Use Python and wxpython for the GUI > - Develop critical routines in Pyrex or in C and make PYD's from it > which will be imported by the main Python programm. > - Distribute with py2exe on Win & py2app for Mac. > > What do you think of this ? > Another point of attention is that the software isn't Open Source, it > is a commercial package. So protection of sources is important. > Now I know that anything can be decompiled, even C. The only question > is, how hard is it and how much effort must someone do to decompile > and retro engineer code to understand it. > I think by putting all program logic in Pyd files that I would be > quite secure ? > On a side note : Is it harder to decompile PYD files then PYC files ? > > I allready had a meeting with the developpers and did a presentation > of python with wxwindow, mostly with an open source project where I > contribute to the development. They didn't see any big problems to > learn Python fast and they allready know C. > > All opinions, advice here is welcome :) 1) Don't take this the wrong way, but get in the habit of using proper grammar and spelling. Especially as a consultant. It will make the job of convincing people to take you seriously that much easier. 2) Use the tools at hand. If your developers don't know Python, you could wind up wasting a lot of talent turning a top-notch C developer into a bottom-tier Python developer, assuming you don't lose them altogether. 3) Don't rewrite critical code in a new language unless you have somebody who really knows what the hell they're doing. All you've done is turn programming's usual first-order ignorance into a much harder second-order problem. 4) Don't fool yourself into thinking that your code can't be decompiled. Odds are your code isn't worth decompiling, but it isn't hard, and a surprising number of people have the requisite skills. It certainly isn't 'secure'. Also- in my experience when people say 'I don't see a problem' to a consultant, what they really mean is 'I don't think you'll be around long enough for this to be a problem for me', but you may have the tools to deal with that. Happy hunting, Geremy Condra From kara at kara-moon.com Fri Aug 20 05:31:20 2010 From: kara at kara-moon.com (Rony) Date: Fri, 20 Aug 2010 02:31:20 -0700 (PDT) Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: <1664f7f2-fa30-4c12-b5a8-d095bed41e2c@5g2000yqz.googlegroups.com> On Aug 20, 11:25?am, geremy condra wrote: > 1) Don't take this the wrong way, but get in the habit of using proper > grammar and spelling. Especially as a consultant. It will make the job > of convincing people to take you seriously that much easier. I don't take it the wrong way but have an answer :) I'm French and doing my best to write understandable English... Thank you for your answers. > Also- in my experience when people say 'I don't see a problem' to a > consultant, what they really mean is 'I don't think you'll be around > long enough for this to be a problem for me', but you may have the > tools to deal with that. > I'll keep this in mind Thank you Rony From davea at ieee.org Fri Aug 20 06:34:27 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 20 Aug 2010 06:34:27 -0400 Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? In-Reply-To: References: Message-ID: <4C6E5A33.3020801@ieee.org> m_ahlenius wrote: > Hi, > > I am relatively new to doing serious work in python. I am using it to > access a large number of log files. Some of the logs get corrupted > and I need to detect that when processing them. This code seems to > work for quite a few of the logs (all same structure) It also > correctly identifies some corrupt logs but then it identifies others > as being corrupt when they are not. > > example error msg from below code: > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > Exception: CRC check\ > failed 0x8967e931 != 0x4e5f1036L > > When I manually examine the supposed corrupt log file and use > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " on it, it opens > just fine. > > Is there anything wrong with how I am using this module? (extra code > removed for clarity) > > if tarfile.is_tarfile( file ): > try: > xf = tarfile.open( file, "r:gz" ) > for locFile in xf: > logfile = xf.extractfile( locFile ) > validFileFlag = True > # iterate through each log file, grab the first and > the last lines > lines = iter( logfile ) > firstLine = lines.next() > for nextLine in lines: > .... > continue > > logfile.close() > ... > xf.close() > except Exception, e: > validFileFlag = False > msg = "\nCould not open the log file: " + repr(file) + " > Exception: " + str(e) + "\n" > else: > validFileFlag = False > lTime = extractFileNameTime( file ) > msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive > \n" > print msg > > I haven't used tarfile, but this feels like a problem with the Win/Unix line endings. I'm going to assume you're running on Windows, which could trigger the problem I'm going to describe. You use 'file' to hold something, but don't show us what. In fact, it's a lousy name, since it's already a Python builtin. But if it's holding fileobj, that you've separately opened, then you need to change that open to use mode 'rb' The problem, if I've guessed right, is that occasionally you'll accidentally encounter a 0d0a sequence in the middle of the (binary) compressed data. If you're on Windows, and use the default 'r' mode, it'll be changed into a 0a byte. Thus corrupting the checksum, and eventually the contents. DaveA From ldo at geek-central.gen.new_zealand Fri Aug 20 07:11:06 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 20 Aug 2010 23:11:06 +1200 Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: In message <8d1b76b7-1ba3-49c5-97cf-dc38370502ae at y11g2000yqm.googlegroups.com>, Rony wrote: > The manager of the development has been fired, main reason (what they > told me) is that they have big big troubles in keeping deadlines ! For > there last product, for which they estimated 3 man years of > development they had 9 months extra effort, and the product was > delivered a year to late. From ahleniusm at gmail.com Fri Aug 20 07:57:36 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 04:57:36 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: Message-ID: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> On Aug 20, 5:34?am, Dave Angel wrote: > m_ahlenius wrote: > > Hi, > > > I am relatively new to doing serious work in python. ?I am using it to > > access a large number of log files. ?Some of the logs get corrupted > > and I need to detect that when processing them. ?This code seems to > > work for quite a few of the logs (all same structure) ?It also > > correctly identifies some corrupt logs but then it identifies others > > as being corrupt when they are not. > > > example error msg from below code: > > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > > Exception: CRC check\ > > ?failed 0x8967e931 != 0x4e5f1036L > > > When I manually examine the supposed corrupt log file and use > > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " ?on it, it opens > > just fine. > > > Is there anything wrong with how I am using this module? ?(extra code > > removed for clarity) > > > ?if tarfile.is_tarfile( file ): > > ? ? ? ? try: > > ? ? ? ? ? ? xf = tarfile.open( file, "r:gz" ) > > ? ? ? ? ? ? for locFile in xf: > > ? ? ? ? ? ? ? ? logfile = xf.extractfile( locFile ) > > ? ? ? ? ? ? ? ? validFileFlag = True > > ? ? ? ? ? ? ? ? # iterate through each log file, grab the first and > > the last lines > > ? ? ? ? ? ? ? ? lines = iter( logfile ) > > ? ? ? ? ? ? ? ? firstLine = lines.next() > > ? ? ? ? ? ? ? ? for nextLine in lines: > > ? ? ? ? ? ? ? ? ? ? .... > > ? ? ? ? ? ? ? ? ? ? ? ? continue > > > ? ? ? ? ? ? ? ? logfile.close() > > ? ? ? ? ? ? ? ? ?... > > ? ? ? ? ? ? xf.close() > > ? ? ? ? except Exception, e: > > ? ? ? ? ? ? validFileFlag = False > > ? ? ? ? ? ? msg = "\nCould not open the log file: " + repr(file) + " > > Exception: " + str(e) + "\n" > > ?else: > > ? ? ? ? validFileFlag = False > > ? ? ? ? lTime = extractFileNameTime( file ) > > ? ? ? ? msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive > > \n" > > ? ? ? ? print msg > > I haven't used tarfile, but this feels like a problem with the Win/Unix > line endings. ?I'm going to assume you're running on Windows, which > could trigger the problem I'm going to describe. > > You use 'file' to hold something, but don't show us what. ?In fact, it's > a lousy name, since it's already a Python builtin. ?But if it's holding ? > fileobj, that you've separately opened, then you need to change that > open to use mode 'rb' > > The problem, if I've guessed right, is that occasionally you'll > accidentally encounter a 0d0a sequence in the middle of the (binary) > compressed data. ?If you're on Windows, and use the default 'r' mode, > it'll be changed into a 0a byte. ?Thus corrupting the checksum, and > eventually the contents. > > DaveA Hi, thanks for the comments - I'll change the variable name. I am running this on linux so don't think its a Windows issue. So if that's the case is the 0d0a still an issue? 'mark From rami.chowdhury at gmail.com Fri Aug 20 07:58:50 2010 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 20 Aug 2010 17:58:50 +0600 Subject: OpenCV_Problem In-Reply-To: References: <201008151914.34334.rami.chowdhury@gmail.com> Message-ID: On Thu, Aug 19, 2010 at 13:47, arihant nahata wrote: > I m new to python and openCV. i installed openCV and python and copied the necessary folder. and even appended the sys.path. but then too the same error. > > from opencv import cv > > File "C:\Python26\lib\site-packages\opencv\__init__.py", line 74, in > > > from cv import * > File "C:\Python26\lib\site-packages\opencv\cv.py", line 25, in > > _cv = swig_import_helper() > File "C:\Python26\lib\site-packages\opencv\cv.py", line 21, in > swig_import_helper > _mod = imp.load_module('_cv', fp, pathname, description) > ImportError: DLL load failed: The specified module could not be found. > > can you help me with this?? [next message] > This is what i have, > > >>> print sys.path > > ['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', > 'C:\\Python27\ > \lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', > 'C:\\Python27 > ', 'C:\\Python27\\lib\\site-packages', > 'C:\\OpenCV2.0\\Python2.6\\Lib\\site-pack > ages'] [next message] >> There is no file named _cv.dll file in the directory that you mentioned > what to do now.??? Well, we've established that the '_cv' module really isn't present. Which makes me wonder if the OpenCV installation went correctly, or if you've added the right paths. However, as I'm not an OpenCV expert, I don't know where to look next. If no one on the Python mailing list can help, you could also try the OpenCV mailing list: http://tech.groups.yahoo.com/group/OpenCV/ HTH, Rami -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From rami.chowdhury at merton.oxon.org Fri Aug 20 08:07:30 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Fri, 20 Aug 2010 18:07:30 +0600 Subject: A question to experienced Pythoneers In-Reply-To: References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 15:25, geremy condra wrote: > On Fri, Aug 20, 2010 at 1:16 AM, Rony wrote: >> Here's the story : >> I've been hired by a company as a consultant to reorganise there >> development department. [snip] >> One of my plans is to introduce Python as development tool. >> They mostly develop back-office software, and at the moment they do it >> all in C with MFC. >> Another new requirement they have, is that the new product should run >> on Win & Mac. [snip] > 2) Use the tools at hand. If your developers don't know Python, you > could wind up wasting a lot of talent turning a top-notch C developer > into a bottom-tier Python developer, assuming you don't lose them > altogether. > > 3) Don't rewrite critical code in a new language unless you have > somebody who really knows what the hell they're doing. All you've done > is turn programming's usual first-order ignorance into a much harder > second-order problem. +1 to both of these, personally. If the developers are used to C and MFC, but you need to make the product run on the Mac as well, have you considered C / C++ GUI frameworks like GTK, WxWidgets, or Qt? Porting your GUI to those might be a better use of time than porting the software to Python... -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From roy at panix.com Fri Aug 20 08:44:42 2010 From: roy at panix.com (Roy Smith) Date: Fri, 20 Aug 2010 08:44:42 -0400 Subject: 79 chars or more? References: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> Message-ID: In article <4c6dfb31$0$11111$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > Of course source code is written in a monospaced typeface, which is a > little wider and consequently fewer characters per page. There was a fling a while ago with typesetting code in proportional spaced type. I think some of the "Effective C++" series from Addison-Wesley did that. Yuck. From malcolm.mclean5 at btinternet.com Fri Aug 20 08:53:43 2010 From: malcolm.mclean5 at btinternet.com (Malcolm McLean) Date: Fri, 20 Aug 2010 05:53:43 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: <03cfab6b-0d69-458b-8d89-fb1a705c5836@y11g2000yqm.googlegroups.com> On Aug 19, 2:14?pm, spinoza1111 wrote: > All the rest [how to implement heaps] is > detail for the little techies to normally, get wrong. > That's a fundamental feature of structured programming. If we maintain the interface malloc(), realloc(), and free(), then we could have a fairly simple or a fairly complicated scheme, and the user doesn't care or need to know. The problem is that a lot of techniques we can use to speed up memory management, such as allocating from a stack, can't be used with this interface. Designing good interfaces is hard. From neilc at norwich.edu Fri Aug 20 09:10:54 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 20 Aug 2010 13:10:54 GMT Subject: 79 chars or more? References: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> Message-ID: <8d7d6uFpvvU1@mid.individual.net> On 2010-08-20, Roy Smith wrote: > In article <4c6dfb31$0$11111$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: > >> Of course source code is written in a monospaced typeface, which is a >> little wider and consequently fewer characters per page. > > There was a fling a while ago with typesetting code in > proportional spaced type. I think some of the "Effective C++" > series from Addison-Wesley did that. Yuck. It's probably influenced by The C++ Programming Language. Stroustrup likes it. -- Neil Cerutti From ahleniusm at gmail.com Fri Aug 20 09:23:57 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 06:23:57 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: On Aug 20, 6:57?am, m_ahlenius wrote: > On Aug 20, 5:34?am, Dave Angel wrote: > > > > > > > m_ahlenius wrote: > > > Hi, > > > > I am relatively new to doing serious work in python. ?I am using it to > > > access a large number of log files. ?Some of the logs get corrupted > > > and I need to detect that when processing them. ?This code seems to > > > work for quite a few of the logs (all same structure) ?It also > > > correctly identifies some corrupt logs but then it identifies others > > > as being corrupt when they are not. > > > > example error msg from below code: > > > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > > > Exception: CRC check\ > > > ?failed 0x8967e931 != 0x4e5f1036L > > > > When I manually examine the supposed corrupt log file and use > > > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " ?on it, it opens > > > just fine. > > > > Is there anything wrong with how I am using this module? ?(extra code > > > removed for clarity) > > > > ?if tarfile.is_tarfile( file ): > > > ? ? ? ? try: > > > ? ? ? ? ? ? xf = tarfile.open( file, "r:gz" ) > > > ? ? ? ? ? ? for locFile in xf: > > > ? ? ? ? ? ? ? ? logfile = xf.extractfile( locFile ) > > > ? ? ? ? ? ? ? ? validFileFlag = True > > > ? ? ? ? ? ? ? ? # iterate through each log file, grab the first and > > > the last lines > > > ? ? ? ? ? ? ? ? lines = iter( logfile ) > > > ? ? ? ? ? ? ? ? firstLine = lines.next() > > > ? ? ? ? ? ? ? ? for nextLine in lines: > > > ? ? ? ? ? ? ? ? ? ? .... > > > ? ? ? ? ? ? ? ? ? ? ? ? continue > > > > ? ? ? ? ? ? ? ? logfile.close() > > > ? ? ? ? ? ? ? ? ?... > > > ? ? ? ? ? ? xf.close() > > > ? ? ? ? except Exception, e: > > > ? ? ? ? ? ? validFileFlag = False > > > ? ? ? ? ? ? msg = "\nCould not open the log file: " + repr(file) + " > > > Exception: " + str(e) + "\n" > > > ?else: > > > ? ? ? ? validFileFlag = False > > > ? ? ? ? lTime = extractFileNameTime( file ) > > > ? ? ? ? msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive > > > \n" > > > ? ? ? ? print msg > > > I haven't used tarfile, but this feels like a problem with the Win/Unix > > line endings. ?I'm going to assume you're running on Windows, which > > could trigger the problem I'm going to describe. > > > You use 'file' to hold something, but don't show us what. ?In fact, it's > > a lousy name, since it's already a Python builtin. ?But if it's holding ? > > fileobj, that you've separately opened, then you need to change that > > open to use mode 'rb' > > > The problem, if I've guessed right, is that occasionally you'll > > accidentally encounter a 0d0a sequence in the middle of the (binary) > > compressed data. ?If you're on Windows, and use the default 'r' mode, > > it'll be changed into a 0a byte. ?Thus corrupting the checksum, and > > eventually the contents. > > > DaveA > > Hi, > > thanks for the comments - I'll change the variable name. > > I am running this on linux so don't think its a Windows issue. ?So if > that's the case > is the 0d0a still an issue? > > 'mark Oh and what's stored currently in The file var us just the unopened pathname to the Target file I want to open From nt_mahmood at yahoo.com Fri Aug 20 09:43:20 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Fri, 20 Aug 2010 06:43:20 -0700 (PDT) Subject: Get authentication error while using 'smtplib' Message-ID: <13714.16636.qm@web50005.mail.re2.yahoo.com> I have this script to send an email via SMTP: import smtplib smtpserver = 'smtp.server.com' AUTHREQUIRED = 1# if you need to use SMTP AUTH set to 1 smtpuser = "username"# for SMTP AUTH, set SMTP username here smtppass = "password"# for SMTP AUTH, set SMTP password here RECIPIENTS ='recipient at server.com' SENDER = 'sender at server.com' mssg = open('filename.txt', 'r').read() session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: ?? session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) After running the script I get this error: ? Traceback (most recent call last): ? File "my_mail.py", line 14, in ??? session.login(smtpuser, smtppass) ? File "/usr/lib/python2.6/smtplib.py", line 589, in login ??? raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, '5.7.0 Error: authentication failed: authentication failure') However there is no problem with my user/pass because I can login to my mail account. Thanks for any idea.? // Naderan *Mahmood;? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sschwarzer at sschwarzer.net Fri Aug 20 09:55:51 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 20 Aug 2010 15:55:51 +0200 Subject: A question to experienced Pythoneers In-Reply-To: References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: <4C6E8967.40408@sschwarzer.net> Hi Lawrence, On 2010-08-20 13:11, Lawrence D'Oliveiro wrote: > In message > <8d1b76b7-1ba3-49c5-97cf-dc38370502ae at y11g2000yqm.googlegroups.com>, Rony > wrote: > >> The manager of the development has been fired, main reason (what they >> told me) is that they have big big troubles in keeping deadlines ! For >> there last product, for which they estimated 3 man years of >> development they had 9 months extra effort, and the product was >> delivered a year to late. > > I can't get the page; all I get is an error message: """ Not Found The requested message, i4ku71$fdg$1 at lust.ihug.co.nz, could not be found. """ Can you please give a part of the message to search for or even better, an URL that works? :-) Thanks, Stefan From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 20 09:56:17 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Aug 2010 15:56:17 +0200 Subject: 79 chars or more? In-Reply-To: <4C6A9C72.4040708@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <4c6e8980$0$692$426a74cc@news.free.fr> Stefan Schwarzer a ?crit : > Hi Neil, > > On 2010-08-17 14:42, Neil Cerutti wrote: (snip) >> Looking through my code, the split-up lines almost always include >> string literals or elimination of meaningless temporary >> variables, e.g.: >> >> self.expiration_date = translate_date(find(response, >> 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') > > I'd probably reformat this to > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', '%m%d%Y') > > or even > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') make this : self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y' ) I just HATE closing parens on the same line when the args don't fit on one single line. Significant indentation only solves one single issue when it comes to coding conventions war !-) From neilc at norwich.edu Fri Aug 20 10:00:49 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 20 Aug 2010 14:00:49 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4c6e8980$0$692$426a74cc@news.free.fr> Message-ID: <8d7g4gFa0nU1@mid.individual.net> On 2010-08-20, Bruno Desthuilliers wrote: > make this : > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y' > ) > > I just HATE closing parens on the same line when the args don't > fit on one single line. It's been interesting to see my code scrutinized like this. Thanks all. As a result of the discussion, I changed translate_date to trans_date_from_to to make the order of arguments clear. find is just a small wrapper around Element.find calls, inserting the namespace. -- Neil Cerutti From davea at ieee.org Fri Aug 20 10:10:13 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 20 Aug 2010 10:10:13 -0400 Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? In-Reply-To: References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: <4C6E8CC5.6060308@ieee.org> m_ahlenius wrote: > On Aug 20, 6:57 am, m_ahlenius wrote: > >> On Aug 20, 5:34 am, Dave Angel wrote: >> >> >> >> >> >> >>> m_ahlenius wrote: >>> >>>> Hi, >>>> >>>> I am relatively new to doing serious work in python. I am using it to >>>> access a large number of log files. Some of the logs get corrupted >>>> and I need to detect that when processing them. This code seems to >>>> work for quite a few of the logs (all same structure) It also >>>> correctly identifies some corrupt logs but then it identifies others >>>> as being corrupt when they are not. >>>> >>>> example error msg from below code: >>>> >>>> Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' >>>> Exception: CRC check\ >>>> failed 0x8967e931 !=x4e5f1036L >>>> >>>> When I manually examine the supposed corrupt log file and use >>>> "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " on it, it opens >>>> just fine. >>>> >>>> Is there anything wrong with how I am using this module? (extra code >>>> removed for clarity) >>>> >>>> if tarfile.is_tarfile( file ): >>>> try: >>>> xf =arfile.open( file, "r:gz" ) >>>> for locFile in xf: >>>> logfile =f.extractfile( locFile ) >>>> validFileFlag =rue >>>> # iterate through each log file, grab the first and >>>> the last lines >>>> lines =ter( logfile ) >>>> firstLine =ines.next() >>>> for nextLine in lines: >>>> .... >>>> continue >>>> >>>> logfile.close() >>>> ... >>>> xf.close() >>>> except Exception, e: >>>> validFileFlag =alse >>>> msg =\nCould not open the log file: " + repr(file) + " >>>> Exception: " + str(e) + "\n" >>>> else: >>>> validFileFlag =alse >>>> lTime =xtractFileNameTime( file ) >>>> msg =>>>>>>> Warning " + file + " is NOT a valid tar archive >>>> \n" >>>> print msg >>>> >>> I haven't used tarfile, but this feels like a problem with the Win/Unix >>> line endings. I'm going to assume you're running on Windows, which >>> could trigger the problem I'm going to describe. >>> >>> You use 'file' to hold something, but don't show us what. In fact, it's >>> a lousy name, since it's already a Python builtin. But if it's holding >>> fileobj, that you've separately opened, then you need to change that >>> open to use mode 'rb' >>> >>> The problem, if I've guessed right, is that occasionally you'll >>> accidentally encounter a 0d0a sequence in the middle of the (binary) >>> compressed data. If you're on Windows, and use the default 'r' mode, >>> it'll be changed into a 0a byte. Thus corrupting the checksum, and >>> eventually the contents. >>> >>> DaveA >>> >> Hi, >> >> thanks for the comments - I'll change the variable name. >> >> I am running this on linux so don't think its a Windows issue. So if >> that's the case >> is the 0d0a still an issue? >> >> 'mark >> > > Oh and what's stored currently in > The file var us just the unopened pathname to the > Target file I want to open > > > No, on Linux, there should be no such problem. And I have to assume that if you pass the filename as a string, the library would use 'rb' anyway. It's just if you pass a fileobj, AND are on Windows. Sorry I wasted your time, but nobody else had answered, and I hoped it might help. DaveA From sschwarzer at sschwarzer.net Fri Aug 20 10:10:16 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 20 Aug 2010 16:10:16 +0200 Subject: A question to experienced Pythoneers In-Reply-To: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: <4C6E8CC8.2090603@sschwarzer.net> Hi Rony, On 2010-08-20 10:16, Rony wrote: > Here's the story : > I've been hired by a company as a consultant to reorganise there > development department. > The actual situation is : > The manager of the development has been fired, main reason (what they > told me) is that they have big big troubles in keeping deadlines ! For > there last product, for which they estimated 3 man years of > development they had 9 months extra effort, and the product was > delivered a year to late. I guess the most important issue will be to find out what was wrong with the development process and fix the problems, i. e. don't repeat them. Keep in mind that "what was wrong" can mean any number of reasons. Until you haven't dealt with this, thinking about changing the programming language in my opinion makes little sense. > I basicaly have 'carte blanche' :) Um, yes ... with the corresponding responsibilities and risks. :-) > So, my strategie would be : > - Use Python and wxpython for the GUI > - Develop critical routines in Pyrex or in C and make PYD's from it > which will be imported by the main Python programm. > - Distribute with py2exe on Win & py2app for Mac. You plan to change a process (and people) used to developing with C to developing with Python and the associated tools. For a developer experienced with both C and Python, using the latter usually will result in faster development. On the other hand, switching to a tool you (i. e. an individual developer) never used before adds some risk (-> uncertainty in effort estimation). If the project you're dealing with now is based on the project you mentioned above, you better not start from scratch in a different language. Very likely the existing code will have subtle though important fixes for subtle problems which were encountered during development. If you start from scratch you risk losing these fixes and having to re-discover the problems and fixes which can take a lot of time. Even if you have all programmers of the old team available, it's risky because they might have forgotten the parts of the code or they may no longer be around when you're about to implement the functionality of these critical parts of the code. If you haven't already, I recommend to read these books: Steve McConnell Rapid Development http://www.amazon.com/x/dp/0072850604/ Tom DeMarco, Timothy Lister Waltzing With Bears: Managing Risk on Software Projects http://www.amazon.com/x/dp/0932633609/ Stefan From __peter__ at web.de Fri Aug 20 10:25:42 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Aug 2010 16:25:42 +0200 Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: m_ahlenius wrote: > On Aug 20, 6:57 am, m_ahlenius wrote: >> On Aug 20, 5:34 am, Dave Angel wrote: >> >> >> >> >> >> > m_ahlenius wrote: >> > > Hi, >> >> > > I am relatively new to doing serious work in python. I am using it >> > > to access a large number of log files. Some of the logs get >> > > corrupted and I need to detect that when processing them. This code >> > > seems to work for quite a few of the logs (all same structure) It >> > > also correctly identifies some corrupt logs but then it identifies >> > > others as being corrupt when they are not. >> >> > > example error msg from below code: >> >> > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' >> > > Exception: CRC check\ >> > > failed 0x8967e931 != 0x4e5f1036L >> >> > > When I manually examine the supposed corrupt log file and use >> > > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " on it, it opens >> > > just fine. >> >> > > Is there anything wrong with how I am using this module? (extra code >> > > removed for clarity) >> >> > > if tarfile.is_tarfile( file ): >> > > try: >> > > xf = tarfile.open( file, "r:gz" ) >> > > for locFile in xf: >> > > logfile = xf.extractfile( locFile ) >> > > validFileFlag = True >> > > # iterate through each log file, grab the first and >> > > the last lines >> > > lines = iter( logfile ) >> > > firstLine = lines.next() >> > > for nextLine in lines: >> > > .... >> > > continue >> >> > > logfile.close() >> > > ... >> > > xf.close() >> > > except Exception, e: >> > > validFileFlag = False >> > > msg = "\nCould not open the log file: " + repr(file) + " >> > > Exception: " + str(e) + "\n" >> > > else: >> > > validFileFlag = False >> > > lTime = extractFileNameTime( file ) >> > > msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive >> > > \n" >> > > print msg >> >> > I haven't used tarfile, but this feels like a problem with the Win/Unix >> > line endings. I'm going to assume you're running on Windows, which >> > could trigger the problem I'm going to describe. >> >> > You use 'file' to hold something, but don't show us what. In fact, >> > it's a lousy name, since it's already a Python builtin. But if it's >> > holding fileobj, that you've separately opened, then you need to change >> > that open to use mode 'rb' >> >> > The problem, if I've guessed right, is that occasionally you'll >> > accidentally encounter a 0d0a sequence in the middle of the (binary) >> > compressed data. If you're on Windows, and use the default 'r' mode, >> > it'll be changed into a 0a byte. Thus corrupting the checksum, and >> > eventually the contents. >> >> > DaveA >> >> Hi, >> >> thanks for the comments - I'll change the variable name. >> >> I am running this on linux so don't think its a Windows issue. So if >> that's the case >> is the 0d0a still an issue? >> >> 'mark > > Oh and what's stored currently in > The file var us just the unopened pathname to the > Target file I want to open Random questions: What python version are you using? If you have other python versions around, do they exhibit the same problem? If you extract and compress your data using the external tool, does the resulting file make problems in Python, too? If so, can you reduce data size and put a small demo online for others to experiment with? Peter From vicente.soler at gmail.com Fri Aug 20 10:26:49 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 07:26:49 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> Message-ID: <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> On Aug 20, 9:36?am, Tim Golden wrote: > > I currently do not have subversion access in my PC. I could try to > > install a free copy of it. But it you could ptovide an installer, it > > certainly would do things easier. Please let me know if it is > > possible. > > Vicente, can you just confirm that you received the installer I > sent offlist? I'll try to put winsys on PyPI with installers; > just haven't got round to it yes :) > > TJG Tim, I just downloaded it, and am going to install it right away. From kara at kara-moon.com Fri Aug 20 10:31:54 2010 From: kara at kara-moon.com (Rony) Date: Fri, 20 Aug 2010 07:31:54 -0700 (PDT) Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> <4C6E8CC8.2090603@sschwarzer.net> Message-ID: <8d6f1093-c585-4374-a843-2e452aebafa5@i13g2000yqd.googlegroups.com> It looks like I forgot to specify that the product is a totaly new product build from scratch, not an upgrade from an existing product. Interesting answers ! Rony From vicente.soler at gmail.com Fri Aug 20 10:45:22 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 07:45:22 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> Message-ID: <3d972531-6b5b-470f-a446-5c897731fc8b@z10g2000yqb.googlegroups.com> On Aug 20, 9:36?am, Tim Golden wrote: > > I currently do not have subversion access in my PC. I could try to > > install a free copy of it. But it you could ptovide an installer, it > > certainly would do things easier. Please let me know if it is > > possible. > > Vicente, can you just confirm that you received the installer I > sent offlist? I'll try to put winsys on PyPI with installers; > just haven't got round to it yes :) > > TJG Tim, I just downloaded it, and am going to install it right away. From vicente.soler at gmail.com Fri Aug 20 10:49:04 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 07:49:04 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> Message-ID: <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> On Aug 20, 4:26?pm, vsoler wrote: > On Aug 20, 9:36?am, Tim Golden wrote: > > > > I currently do not have subversion access in my PC. I could try to > > > install a free copy of it. But it you could ptovide an installer, it > > > certainly would do things easier. Please let me know if it is > > > possible. > > > Vicente, can you just confirm that you received the installer I > > sent offlist? I'll try to put winsys on PyPI with installers; > > just haven't got round to it yes :) > > > TJG > > Tim, > > I just downloaded it, and am going to install it right away. Tim, It works!!! or at least, should I say, it runs!!! wonderful. Now, would it be possible to have a hint/suggestion as to some lines that I should include in my script? I find this exercice very interesting. Thank you for your help. Vicente Soler From a.j.romanista at gmail.com Fri Aug 20 11:02:30 2010 From: a.j.romanista at gmail.com (ata.jaf) Date: Fri, 20 Aug 2010 08:02:30 -0700 (PDT) Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> <4c6cefc6$0$11111$c3e8da3@news.astraweb.com> Message-ID: <31e9a229-9422-42d4-ab51-14cd4aaf62af@z10g2000yqb.googlegroups.com> On Aug 19, 11:48?am, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote: > > On Aug 17, 11:55?pm, Thomas Jollans wrote: > >> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > > >> > I am developing a little program in Mac with wxPython. But I have > >> > problems with the characters that are not in ASCII. Like some special > >> > characters in French or Turkish. So I am looking for a way to solve > >> > this. Like an encoding standard that supports all languages. Or some > >> > other way. > > >> Anything that supports all of Unicode will do. Like UTF-8. If your text > >> is mostly Latin, then just go for UTF-8, if you use other alphabets > >> extensively, you might want to consider UTF-16, which might the use a > >> little less space. > > > OK, I used UTF-8. > > I write a line of strings in the source code > > Do you have a source code encoding line at the start of your script? > > http://www.python.org/dev/peps/pep-0263/ > > > and I want my program to > > show that as an output on GUI. And this line of strings includes a > > character like "?". But I see that in GUI this character is replaced > > with another strange characters. I mean it doesn't work. And when I try > > to use UTF-16, I get an syntax error that declares "UTF-16 stream does > > not start with BOM". > > What GUI are you using? > > Please COPY AND PASTE (do not retype) the EXACT error message you get, > including the entire traceback. > > -- > Steven Yes I have a source code encoding line. Here it is: # -*- coding: utf_16 -*- I am using WxPython. And the error that I get about using utf-16 is:\ Traceback (most recent call last): File "", line 1, in File "z.py", line 2 SyntaxError: UTF-16 stream does not start with BOM From mail at timgolden.me.uk Fri Aug 20 11:10:51 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Aug 2010 16:10:51 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: <4C6E9AFB.1070508@timgolden.me.uk> On 20/08/2010 15:49, vsoler wrote: > On Aug 20, 4:26 pm, vsoler wrote: >> On Aug 20, 9:36 am, Tim Golden wrote: >> >>>> I currently do not have subversion access in my PC. I could try to >>>> install a free copy of it. But it you could ptovide an installer, it >>>> certainly would do things easier. Please let me know if it is >>>> possible. >> >>> Vicente, can you just confirm that you received the installer I >>> sent offlist? I'll try to put winsys on PyPI with installers; >>> just haven't got round to it yes :) >> >>> TJG >> >> Tim, >> >> I just downloaded it, and am going to install it right away. > > Tim, > > It works!!! or at least, should I say, it runs!!! wonderful. > > Now, would it be possible to have a hint/suggestion as to some lines > that I should include in my script? Depends what, exactly, you want your script to do :) The simplest way to get an ad-hoc look at what permissions are applied to a file is: import os, sys from winsys import fs # # Just using sys.executable as a file I know will exist; # obviously you put your own file name in there... # fs.file (sys.executable).security ().dump () To get that in the more compact but more esoteric MS SDDL format: import os, sys from winsys import fs print (fs.file (sys.executable).security ()) To decode the permission bit-strings to vaguely meaningful names: import os, sys from winsys import fs dacl = fs.file (sys.executable).security ().dacl for permission in dacl: print (d.trustee, " (Inherited )" if d.inherited else "") for name in fs.FILE_ACCESS.names_from_value (d.access): print (" ", name) TJG From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 20 11:16:14 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Aug 2010 17:16:14 +0200 Subject: A question to experienced Pythoneers In-Reply-To: <8d6f1093-c585-4374-a843-2e452aebafa5@i13g2000yqd.googlegroups.com> References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> <4C6E8CC8.2090603@sschwarzer.net> <8d6f1093-c585-4374-a843-2e452aebafa5@i13g2000yqd.googlegroups.com> Message-ID: <4c6e9c3c$0$411$426a74cc@news.free.fr> Rony a ?crit : > It looks like I forgot to specify that the product is a totaly new > product build from scratch, not an upgrade from an existing product. Still the advice to first find out what went wrong with the previous project is a very sensible one. Technical problems do exist, but from experience they rarely are the main source of failure. From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 20 11:23:23 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Aug 2010 17:23:23 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c6e9de9$0$23142$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: > >> Recursion can be quite a trick to get your mind round at first > > Really? Do people actually find the *concept* of recursion to be tricky? > I onced worked in a shop (Win32 desktop / accouting applications mainly) where I was the only guy that could actually understand recursion. FWIW, I also was the only guy around that understood "hairy" (lol) concepts like callback functions, FSM, polymorphism, hashtables, linked lists, ADTs, algorithm complexity etc... Needless to say, I didn't last long !-) From enleverLesX_XXmcX at XmclavXeauX.com.invalid Fri Aug 20 11:34:56 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Fri, 20 Aug 2010 17:34:56 +0200 Subject: Iterative vs. Recursive coding References: <4c6e9de9$0$23142$426a74cc@news.free.fr> Message-ID: <4c6ea0a9$0$5403$ba4acef3@reader.news.orange.fr> Salut ! C'est cela, la solitude du programmeur g?nial... @-salutations -- Michel Claveau From aahz at pythoncraft.com Fri Aug 20 11:41:00 2010 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2010 08:41:00 -0700 Subject: urllib "quote" problem References: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> Message-ID: In article <4c5eef7f$0$1609$742ec2ed at news.sonic.net>, John Nagle wrote: > > This looks like code that will do the wrong thing in >Python 2.6 for characters in the range 128-255. Those are >illegal in type "str", but this code is constructing such >values with "chr". WDYM "illegal"? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 20 11:45:09 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Aug 2010 17:45:09 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6ea0a9$0$5403$ba4acef3@reader.news.orange.fr> References: <4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6ea0a9$0$5403$ba4acef3@reader.news.orange.fr> Message-ID: <4c6ea303$0$23154$426a34cc@news.free.fr> Michel Claveau - MVP a ?crit : > Salut ! > > C'est cela, la solitude du programmeur g?nial... > > @-salutations Moi aussi je t'aime, Michel !-) From aahz at pythoncraft.com Fri Aug 20 11:45:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2010 08:45:44 -0700 Subject: requirements in writing an email/rss/usenet client? References: Message-ID: In article , George Oliver wrote: > >I'd like to know what to consider when writing an email/rss/usenet >client. Apologies for such a broad question, but I've never attempted >a project of this scope and I'm currently feeling out the >requirements. About the only advice I can give you to such a broad question is the aphorism "Be strict about what you send; be generous about what you receive". IOW, follow the standards very very carefully in sending messages but be very very lenient with what you accept (just make sure you don't crash). Overall, you probably will get discouraged eventually, so I suggest that you try to have as much fun as possible along the way. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From aahz at pythoncraft.com Fri Aug 20 11:53:34 2010 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2010 08:53:34 -0700 Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: In article <8d1b76b7-1ba3-49c5-97cf-dc38370502ae at y11g2000yqm.googlegroups.com>, Rony wrote: > >The manager of the development has been fired, main reason (what they >told me) is that they have big big troubles in keeping deadlines ! For >there last product, for which they estimated 3 man years of >development they had 9 months extra effort, and the product was >delivered a year to late. Keep in mind that the real problem may have been that upper management forced a completely unrealistic deadline. They may also have had difficulty translating "development effort" into Real World Timing [tm]. (For example, when I tell my boss that something will take three days of development effort, I also make clear that between support and production issues that I need to help with, not to mention meetings, mentoring other people on my team, etc -- those three days will almost inevitably expand into six business days BEST CASE.) Try to have some quiet, off-campus discussions with developers to gather information. NOTE VERY CAREFULLY: if you promise to keep a conversation private, KEEP THE PROMISE. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From vicente.soler at gmail.com Fri Aug 20 12:00:56 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 09:00:56 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: <1f6b049b-6bdc-4305-9389-5142dbd44e4e@s9g2000yqd.googlegroups.com> On Aug 20, 5:10?pm, Tim Golden wrote: > On 20/08/2010 15:49, vsoler wrote: > > > > > On Aug 20, 4:26 pm, vsoler ?wrote: > >> On Aug 20, 9:36 am, Tim Golden ?wrote: > > >>>> I currently do not have subversion access in my PC. I could try to > >>>> install a free copy of it. But it you could ptovide an installer, it > >>>> certainly would do things easier. Please let me know if it is > >>>> possible. > > >>> Vicente, can you just confirm that you received the installer I > >>> sent offlist? I'll try to put winsys on PyPI with installers; > >>> just haven't got round to it yes :) > > >>> TJG > > >> Tim, > > >> I just downloaded it, and am going to install it right away. > > > Tim, > > > It works!!! or at least, should I say, it runs!!! wonderful. > > > Now, would it be possible to have a hint/suggestion as to some lines > > that I should include in my script? > > Depends what, exactly, you want your script to do :) > > The simplest way to get an ad-hoc look at what permissions are applied to > a file is: > > > import os, sys > from winsys import fs > > # > # Just using sys.executable as a file I know will exist; > # obviously you put your own file name in there... > # > fs.file (sys.executable).security ().dump () > > > > To get that in the more compact but more esoteric MS SDDL format: > > > import os, sys > from winsys import fs > > print (fs.file (sys.executable).security ()) > > > > To decode the permission bit-strings to vaguely meaningful > names: > > > import os, sys > from winsys import fs > > dacl = fs.file (sys.executable).security ().dacl > for permission in dacl: > ? ?print (d.trustee, " (Inherited )" if d.inherited else "") > ? ?for name in fs.FILE_ACCESS.names_from_value (d.access): > ? ? ?print (" ?", name) > > > > TJG Tim, in your last piece of code, the definition of "d" is missing. missed anything when copying? Vicente Soler From rami.chowdhury at merton.oxon.org Fri Aug 20 12:07:21 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Fri, 20 Aug 2010 22:07:21 +0600 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: <31e9a229-9422-42d4-ab51-14cd4aaf62af@z10g2000yqb.googlegroups.com> References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> <4c6cefc6$0$11111$c3e8da3@news.astraweb.com> <31e9a229-9422-42d4-ab51-14cd4aaf62af@z10g2000yqb.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 21:02, ata.jaf wrote: > On Aug 19, 11:48?am, Steven D'Aprano T... at cybersource.com.au> wrote: >> On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote: >> > On Aug 17, 11:55?pm, Thomas Jollans wrote: >> >> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: >> >> >> > I am developing a little program in Mac with wxPython. But I have >> >> > problems with the characters that are not in ASCII. Like some special >> >> > characters in French or Turkish. So I am looking for a way to solve >> >> > this. Like an encoding standard that supports all languages. Or some >> >> > other way. >> >> >> Anything that supports all of Unicode will do. Like UTF-8. If your text >> >> is mostly Latin, then just go for UTF-8, if you use other alphabets >> >> extensively, you might want to consider UTF-16, which might the use a >> >> little less space. >> >> > OK, I used UTF-8. >> > I write a line of strings in the source code >> >> Do you have a source code encoding line at the start of your script? >> >> http://www.python.org/dev/peps/pep-0263/ >> > > Yes I have a source code encoding line. > Here it is: > > # -*- coding: utf_16 -*- > > I am using WxPython. > > And the error that I get about using utf-16 is:\ > > Traceback (most recent call last): > ?File "", line 1, in > ?File "z.py", line 2 > SyntaxError: UTF-16 stream does not start with BOM Which encoding are you saving your script in? Very few of the text editors I've used save to UTF-16 by default. -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From vicente.soler at gmail.com Fri Aug 20 12:10:23 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 09:10:23 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: On Aug 20, 5:10?pm, Tim Golden wrote: > On 20/08/2010 15:49, vsoler wrote: > > > > > On Aug 20, 4:26 pm, vsoler ?wrote: > >> On Aug 20, 9:36 am, Tim Golden ?wrote: > > >>>> I currently do not have subversion access in my PC. I could try to > >>>> install a free copy of it. But it you could ptovide an installer, it > >>>> certainly would do things easier. Please let me know if it is > >>>> possible. > > >>> Vicente, can you just confirm that you received the installer I > >>> sent offlist? I'll try to put winsys on PyPI with installers; > >>> just haven't got round to it yes :) > > >>> TJG > > >> Tim, > > >> I just downloaded it, and am going to install it right away. > > > Tim, > > > It works!!! or at least, should I say, it runs!!! wonderful. > > > Now, would it be possible to have a hint/suggestion as to some lines > > that I should include in my script? > > Depends what, exactly, you want your script to do :) > > The simplest way to get an ad-hoc look at what permissions are applied to > a file is: > > > import os, sys > from winsys import fs > > # > # Just using sys.executable as a file I know will exist; > # obviously you put your own file name in there... > # > fs.file (sys.executable).security ().dump () > > > > To get that in the more compact but more esoteric MS SDDL format: > > > import os, sys > from winsys import fs > > print (fs.file (sys.executable).security ()) > > > > To decode the permission bit-strings to vaguely meaningful > names: > > > import os, sys > from winsys import fs > > dacl = fs.file (sys.executable).security ().dacl > for permission in dacl: > ? ?print (d.trustee, " (Inherited )" if d.inherited else "") > ? ?for name in fs.FILE_ACCESS.names_from_value (d.access): > ? ? ?print (" ?", name) > > > > TJG it seems as though the definition of "d" is missing in your last piece of code From ahleniusm at gmail.com Fri Aug 20 12:27:52 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 09:27:52 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: On Aug 20, 9:10?am, Dave Angel wrote: > m_ahlenius wrote: > > On Aug 20, 6:57 am, m_ahlenius wrote: > > >> On Aug 20, 5:34 am, Dave Angel wrote: > > >>> m_ahlenius wrote: > > >>>> Hi, > > >>>> I am relatively new to doing serious work in python. ?I am using it to > >>>> access a large number of log files. ?Some of the logs get corrupted > >>>> and I need to detect that when processing them. ?This code seems to > >>>> work for quite a few of the logs (all same structure) ?It also > >>>> correctly identifies some corrupt logs but then it identifies others > >>>> as being corrupt when they are not. > > >>>> example error msg from below code: > > >>>> Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > >>>> Exception: CRC check\ > >>>> ?failed 0x8967e931 !=x4e5f1036L > > >>>> When I manually examine the supposed corrupt log file and use > >>>> "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " ?on it, it opens > >>>> just fine. > > >>>> Is there anything wrong with how I am using this module? ?(extra code > >>>> removed for clarity) > > >>>> ?if tarfile.is_tarfile( file ): > >>>> ? ? ? ? try: > >>>> ? ? ? ? ? ? xf =arfile.open( file, "r:gz" ) > >>>> ? ? ? ? ? ? for locFile in xf: > >>>> ? ? ? ? ? ? ? ? logfile =f.extractfile( locFile ) > >>>> ? ? ? ? ? ? ? ? validFileFlag =rue > >>>> ? ? ? ? ? ? ? ? # iterate through each log file, grab the first and > >>>> the last lines > >>>> ? ? ? ? ? ? ? ? lines =ter( logfile ) > >>>> ? ? ? ? ? ? ? ? firstLine =ines.next() > >>>> ? ? ? ? ? ? ? ? for nextLine in lines: > >>>> ? ? ? ? ? ? ? ? ? ? .... > >>>> ? ? ? ? ? ? ? ? ? ? ? ? continue > > >>>> ? ? ? ? ? ? ? ? logfile.close() > >>>> ? ? ? ? ? ? ? ? ?... > >>>> ? ? ? ? ? ? xf.close() > >>>> ? ? ? ? except Exception, e: > >>>> ? ? ? ? ? ? validFileFlag =alse > >>>> ? ? ? ? ? ? msg =\nCould not open the log file: " + repr(file) + " > >>>> Exception: " + str(e) + "\n" > >>>> ?else: > >>>> ? ? ? ? validFileFlag =alse > >>>> ? ? ? ? lTime =xtractFileNameTime( file ) > >>>> ? ? ? ? msg =>>>>>>> Warning " + file + " is NOT a valid tar archive > >>>> \n" > >>>> ? ? ? ? print msg > > >>> I haven't used tarfile, but this feels like a problem with the Win/Unix > >>> line endings. ?I'm going to assume you're running on Windows, which > >>> could trigger the problem I'm going to describe. > > >>> You use 'file' to hold something, but don't show us what. ?In fact, it's > >>> a lousy name, since it's already a Python builtin. ?But if it's holding ? > >>> fileobj, that you've separately opened, then you need to change that > >>> open to use mode 'rb' > > >>> The problem, if I've guessed right, is that occasionally you'll > >>> accidentally encounter a 0d0a sequence in the middle of the (binary) > >>> compressed data. ?If you're on Windows, and use the default 'r' mode, > >>> it'll be changed into a 0a byte. ?Thus corrupting the checksum, and > >>> eventually the contents. > > >>> DaveA > > >> Hi, > > >> thanks for the comments - I'll change the variable name. > > >> I am running this on linux so don't think its a Windows issue. ?So if > >> that's the case > >> is the 0d0a still an issue? > > >> 'mark > > > Oh and what's stored currently in > > The file var us just the unopened pathname to the > > Target file I want to open > > No, on Linux, there should be no such problem. ?And I have to assume > that if you pass the filename as a string, the library would use 'rb' > anyway. ?It's just if you pass a fileobj, ?AND are on Windows. > > Sorry I wasted your time, but nobody else had answered, and I hoped it > might help. > > DaveA Hi Dave thanks for responding - you were not wasting my time but helping me to be aware of other potential issues. Appreciate it much. Its just weird that it works for most files and even finds corrupt ones, but some of the ones it marks as corrupt seem to be OK. thanks 'mark From nagle at animats.com Fri Aug 20 12:34:58 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 09:34:58 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6e3313$0$16599$426a74cc@news.free.fr> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> Message-ID: <4c6eaead$0$1638$742ec2ed@news.sonic.net> On 8/20/2010 12:47 AM, News123 wrote: > On 08/20/2010 02:26 AM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be tricky? > Is this a sincere surprise or are you just boasting? >> >> If I remember correctly, my puzzlement about recursion lasted about 15 >> seconds. I remember thinking "How does the function foo know that there >> is a function foo when foo doesn't fully exist yet?", but once I accepted >> the fact that it just does it all just seemed obvious. Getting recursion >> *right* is sometimes tricky, but the idea itself isn't. If you think about what the implementation has to do, it's quite complicated. Which objects are copied, and which are merely referenced? Is the recursion going to result in control being inside the same object instance twice? Is the recursion a closure? Is tail recursion possible, and does your language implement it? Python does not do tail recursion, so using recursion where iteration could do the job is generally a bad idea. Scheme, on the other hand, always does tail recursion where possible. Python does have generators, and I recently wrote a recursive generator for a production application. I needed to descend a specialized directory tree structure (the one used by the US Securities and Exchange Commission to store filings) and retrieve the last N days of filings. So I have a recursive generator that returns directory after directory, descending into the directories for years and quarters as necessary. The calling function stops calling the generator when it has found the information it needs, which happens before the generator runs out. That's a real-life use case for such a construct, and led to much shorter code than a non-recursive implementation. John Nagle From ahleniusm at gmail.com Fri Aug 20 12:44:29 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 09:44:29 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: <19aa141c-1ae9-47ed-bf4b-9af0b0de0396@u26g2000yqu.googlegroups.com> On Aug 20, 9:25?am, Peter Otten <__pete... at web.de> wrote: > m_ahlenius wrote: > > On Aug 20, 6:57 am, m_ahlenius wrote: > >> On Aug 20, 5:34 am, Dave Angel wrote: > > >> > m_ahlenius wrote: > >> > > Hi, > > >> > > I am relatively new to doing serious work in python. ?I am using it > >> > > to access a large number of log files. ?Some of the logs get > >> > > corrupted and I need to detect that when processing them. ?This code > >> > > seems to work for quite a few of the logs (all same structure) ?It > >> > > also correctly identifies some corrupt logs but then it identifies > >> > > others as being corrupt when they are not. > > >> > > example error msg from below code: > > >> > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > >> > > Exception: CRC check\ > >> > > failed 0x8967e931 != 0x4e5f1036L > > >> > > When I manually examine the supposed corrupt log file and use > >> > > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " ?on it, it opens > >> > > just fine. > > >> > > Is there anything wrong with how I am using this module? ?(extra code > >> > > removed for clarity) > > >> > > if tarfile.is_tarfile( file ): > >> > > try: > >> > > xf = tarfile.open( file, "r:gz" ) > >> > > for locFile in xf: > >> > > logfile = xf.extractfile( locFile ) > >> > > validFileFlag = True > >> > > # iterate through each log file, grab the first and > >> > > the last lines > >> > > lines = iter( logfile ) > >> > > firstLine = lines.next() > >> > > for nextLine in lines: > >> > > .... > >> > > continue > > >> > > logfile.close() > >> > > ... > >> > > xf.close() > >> > > except Exception, e: > >> > > validFileFlag = False > >> > > msg = "\nCould not open the log file: " + repr(file) + " > >> > > Exception: " + str(e) + "\n" > >> > > else: > >> > > validFileFlag = False > >> > > lTime = extractFileNameTime( file ) > >> > > msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive > >> > > \n" > >> > > print msg > > >> > I haven't used tarfile, but this feels like a problem with the Win/Unix > >> > line endings. ?I'm going to assume you're running on Windows, which > >> > could trigger the problem I'm going to describe. > > >> > You use 'file' to hold something, but don't show us what. ?In fact, > >> > it's a lousy name, since it's already a Python builtin. ?But if it's > >> > holding fileobj, that you've separately opened, then you need to change > >> > that open to use mode 'rb' > > >> > The problem, if I've guessed right, is that occasionally you'll > >> > accidentally encounter a 0d0a sequence in the middle of the (binary) > >> > compressed data. ?If you're on Windows, and use the default 'r' mode, > >> > it'll be changed into a 0a byte. ?Thus corrupting the checksum, and > >> > eventually the contents. > > >> > DaveA > > >> Hi, > > >> thanks for the comments - I'll change the variable name. > > >> I am running this on linux so don't think its a Windows issue. ?So if > >> that's the case > >> is the 0d0a still an issue? > > >> 'mark > > > Oh and what's stored currently in > > The file var us just the unopened pathname to the > > Target file I want to open > > Random questions: > > What python version are you using? > If you have other python versions around, do they exhibit the same problem? > If you extract and compress your data using the external tool, does the > resulting file make problems in Python, too? > If so, can you reduce data size and put a small demo online for others to > experiment with? > > Peter Hi, I am using Python 2.6.5. Unfortunately I don't have other versions installed so its hard to test with a different version. As for the log compression, its a bit hard to test. Right now I may process 100+ of these logs per night, and will get maybe 5 which are reported as corrupt (typically a bad CRC) and 2 which it reported as a bad tar archive. This morning I checked each of the 7 reported problem files by manually opening them with "tar -xzvof" and they were all indeed corrupt. Sign. Unfortunately due to the nature of our business, I can't post the data files online, I hope you can understand. But I really appreciate your suggestions. The thing that gets me is that it seems to work just fine for most files, but then not others. Labeling normal files as corrupt hurts us as we then skip getting any log data from those files. appreciate all your help. 'mark From neilc at norwich.edu Fri Aug 20 13:09:43 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 20 Aug 2010 17:09:43 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> Message-ID: <8d7r6nFe1nU1@mid.individual.net> On 2010-08-20, John Nagle wrote: > Python does not do tail recursion, so using recursion where > iteration could do the job is generally a bad idea. Scheme, on > the other hand, always does tail recursion where possible. A tail-recursive function is usually easy to convert to a loop-style iteration. However, Scheme does tail-call optimization, I believe, which is slightly more general. -- Neil Cerutti From thomas at jollybox.de Fri Aug 20 13:41:44 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 20 Aug 2010 19:41:44 +0200 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: <201008201941.45601.thomas@jollybox.de> On Friday 20 August 2010, it occurred to Nobody to exclaim: > Unix lacks the "Append Data" permission for files, and the "Create Files", > "Create Folders" and "Delete Subfolders and Files" correspond to having > write permission on a directory. How does append differ from write? If you have appending permissions, but not writing ones, is it impossible to seek? Or is there a more complex "block" that bites you when you seek to before the old end of file and try writing there? Thank you for the insights, "Nobody". Makes me wonder whether SELinux makes changes in this area, and if so, how far-reaching they are. > On Unix, you can read permissions (and attributes if the filesystem has > them) for any file which you can "reach" (i.e. have "x" permission on all > ancestor directories). You can only change permissions (and some > attributes) if you own the file, and only root can change ownership (and > change some attributes). > > 2. Permissions can be inherited from the "parent object" (which isn't > necessarily the parent folder). If you change a permission on the parent > object, it automatically affects any file or folder which inherits the > permission. > > 3. The owner can be either a user or a group. What about both? > 4. On Windows, a file cannot be "given away" either by its owner or an > administrator. You can grant the "Take Ownership" permission, but > the recipient still has to explicitly change the ownership. Really? So the operating system actually places restrictions on what the administrator can do? Or is there a fine distinction here between administrator-accounts in general and the NT "Administrator" account that at least some versions of Windows (xp home edition springs to mind) appear to try to hide as best they can ? Well, this is probably just my UNIX conditioning, expecting a single all-powerful super-user, shining through here -- but it does seam strange to have a super- user that is not omnipotent. From mail at timgolden.me.uk Fri Aug 20 13:42:08 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Aug 2010 18:42:08 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: <4C6EBE70.2040308@timgolden.me.uk> On 20/08/2010 5:10 PM, vsoler wrote: > On Aug 20, 5:10 pm, Tim Golden wrote: >> To decode the permission bit-strings to vaguely meaningful >> names: >> >> >> import os, sys >> from winsys import fs >> >> dacl = fs.file (sys.executable).security ().dacl >> for permission in dacl: >> print (d.trustee, " (Inherited )" if d.inherited else "") >> for name in fs.FILE_ACCESS.names_from_value (d.access): >> print (" ", name) >> >> >> >> TJG > > it seems as though the definition of "d" is missing in your last piece > of code Whoops, changed tack mid-thingy. Try: dacl = ... for d in dacl: # .. as before From __peter__ at web.de Fri Aug 20 13:55:54 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Aug 2010 19:55:54 +0200 Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> <19aa141c-1ae9-47ed-bf4b-9af0b0de0396@u26g2000yqu.googlegroups.com> Message-ID: m_ahlenius wrote: > I am using Python 2.6.5. > > Unfortunately I don't have other versions installed so its hard to > test with a different version. > > As for the log compression, its a bit hard to test. Right now I may > process 100+ of these logs per night, and will get maybe 5 which are > reported as corrupt (typically a bad CRC) and 2 which it reported as a > bad tar archive. This morning I checked each of the 7 reported > problem files by manually opening them with "tar -xzvof" and they were > all indeed corrupt. Sign. So many corrupted files? I'd say you have to address the problem with your infrastructure first. > Unfortunately due to the nature of our business, I can't post the data > files online, I hope you can understand. But I really appreciate your > suggestions. > > The thing that gets me is that it seems to work just fine for most > files, but then not others. Labeling normal files as corrupt hurts us > as we then skip getting any log data from those files. > > appreciate all your help. I've written an autocorruption script, import sys import subprocess import tarfile def process(source, dest, data): for pos in range(len(data)): for bit in range(8): new_data = data[:pos] + chr(ord(data[pos]) ^ (1< <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> Message-ID: <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> On Aug 20, 1:23?am, Martin Braun wrote: > I find this thread extremely interesting, but what surprised me that > everyone seems to agree that mathematics is 1-based, but we Pythoneers > should stick to zero-based. I disagree. To make sure I'm not going > crazy, I took the top five books lying on my desk, which were the DSP > book by Oppenheim/Schafer, two books by Stephen M. Kay (Spectral > Estimation and Estimation Theory) and the Channel Coding book by Lin & > Costello. This is isn't pure mathematics (as in proving the Goldbach > conjecture), but nevertheless, this is serious mathematics and, > surprise, they most exclusively use zero-based notation. > You probably don't have those books in grabbing distance, so here's some > examples for zero-based stuff: That's interesting, but I think zero-based indexing is rare in the literature of mathematics, applied math, science and engineering. All the literature I've ever seen that uses vectors and matrices is one- based, and that includes text books and technical papers. It all boils down to personal preference, but I just find it strange that we would not try to make programming as consistent as possible with notational conventions in the literature. If I try to implement some algorithm I find in a technical book or paper, why should I have to mentally offset every index by one? That's very error prone, and I have more important things to think about. Then again, I don't do that very often, so maybe it's not a big deal. The zero-based indexing just seemed wrong to me when I first saw it. I'm used to it by now, but it still doesn't seem quite right to me. It's almost right -- but it's off by one. I still have a habit of taking the "1" element when I really want the "0" element. Most programmers probably never use vectors and matrices, so they don't care about the inconsistency with standard mathematical notation. And yes, I understand that zero-based indexing can be slightly more efficient. That's why I think it's appropriate for low-level languages such as C. However, I think one-based indexing is more appropriate for high-level languages. From znarus at telia.com Fri Aug 20 14:09:36 2010 From: znarus at telia.com (M B) Date: Fri, 20 Aug 2010 20:09:36 +0200 Subject: scope of variable Message-ID: <1282327776.2942.3.camel@pex-desktop> Hi, I try to learn python. I don't understand this: (running in idle) >>> dept=0 >>> def mud(): print dept >>> mud() 0 >>> def mud(): dept+=1 print dept >>> mud() Traceback (most recent call last): File "", line 1, in mud() File "", line 2, in mud dept+=1 UnboundLocalError: local variable 'dept' referenced before assignment >>> Regards MB From debatem1 at gmail.com Fri Aug 20 14:19:46 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 20 Aug 2010 11:19:46 -0700 Subject: Python "why" questions In-Reply-To: <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 11:01 AM, Russ P. wrote: > On Aug 20, 1:23?am, Martin Braun wrote: > >> I find this thread extremely interesting, but what surprised me that >> everyone seems to agree that mathematics is 1-based, but we Pythoneers >> should stick to zero-based. I disagree. To make sure I'm not going >> crazy, I took the top five books lying on my desk, which were the DSP >> book by Oppenheim/Schafer, two books by Stephen M. Kay (Spectral >> Estimation and Estimation Theory) and the Channel Coding book by Lin & >> Costello. This is isn't pure mathematics (as in proving the Goldbach >> conjecture), but nevertheless, this is serious mathematics and, >> surprise, they most exclusively use zero-based notation. >> You probably don't have those books in grabbing distance, so here's some >> examples for zero-based stuff: > > That's interesting, but I think zero-based indexing is rare in the > literature of mathematics, applied math, science and engineering. All > the literature I've ever seen that uses vectors and matrices is one- > based, and that includes text books and technical papers. Not sure what you read, but for me (mostly number theory, numerical analysis, and abstract algebra) zero-based indexing is quite common. > It all boils down to personal preference, but I just find it strange > that we would not try to make programming as consistent as possible > with notational conventions in the literature. If I try to implement > some algorithm I find in a technical book or paper, why should I have > to mentally offset every index by one? That's very error prone, and I > have more important things to think about. Then again, I don't do that > very often, so maybe it's not a big deal. Ever read code by a mathematician? It's usually (obviously not always) a nightmare. I'm glad we break with convention, particularly when that convention is things like one-letter variables and 'reuse' of notation. Geremy Condra From clp2 at rebertia.com Fri Aug 20 14:25:05 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 20 Aug 2010 11:25:05 -0700 Subject: scope of variable In-Reply-To: <1282327776.2942.3.camel@pex-desktop> References: <1282327776.2942.3.camel@pex-desktop> Message-ID: On Fri, Aug 20, 2010 at 11:09 AM, M B wrote: > Hi, > I try to learn python. > I don't understand this: >>>> dept=0 >>>> def mud(): > ? ? ? ?dept+=1 > ? ? ? ?print dept > >>>> mud() > Traceback (most recent call last): > ?File "", line 1, in > ? ?mud() > ?File "", line 2, in mud > ? ?dept+=1 > UnboundLocalError: local variable 'dept' referenced before assignment http://www.mail-archive.com/python-list at python.org/msg75263.html Cheers, Chris -- Google is your friend http://blog.rebertia.com From kara at kara-moon.com Fri Aug 20 14:33:19 2010 From: kara at kara-moon.com (Rony) Date: Fri, 20 Aug 2010 11:33:19 -0700 (PDT) Subject: scope of variable References: <1282327776.2942.3.camel@pex-desktop> Message-ID: <3ad95d6c-9011-4c07-8a93-38efbdaa5eca@c10g2000yqi.googlegroups.com> On Aug 20, 8:25?pm, Chris Rebert wrote: > On Fri, Aug 20, 2010 at 11:09 AM, M B wrote: > > Hi, > > I try to learn python. > > I don't understand this: > > >>>> dept=0 > > >>>> def mud(): > > ? ? ? ?dept+=1 > > ? ? ? ?print dept > > >>>> mud() > > Traceback (most recent call last): > > ?File "", line 1, in > > ? ?mud() > > ?File "", line 2, in mud > > ? ?dept+=1 > > UnboundLocalError: local variable 'dept' referenced before assignment Just put a global dept at the start of your function and it will work Rony From martin at address-in-sig.invalid Fri Aug 20 14:34:16 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Fri, 20 Aug 2010 18:34:16 +0000 (UTC) Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> <4C6E8CC8.2090603@sschwarzer.net> <8d6f1093-c585-4374-a843-2e452aebafa5@i13g2000yqd.googlegroups.com> <4c6e9c3c$0$411$426a74cc@news.free.fr> Message-ID: On Fri, 20 Aug 2010 17:16:14 +0200, Bruno Desthuilliers wrote: > Rony a ?crit : >> It looks like I forgot to specify that the product is a totaly new >> product build from scratch, not an upgrade from an existing product. > > > Still the advice to first find out what went wrong with the previous > project is a very sensible one. Technical problems do exist, but from > experience they rarely are the main source of failure. > And be sure to look into the estimation and costing methods the company is using. IOW are you sure whether design/build/test phases are overrunning a sensible estimate or if the initial costing and estimation is underestimating the project size? -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From nagle at animats.com Fri Aug 20 14:50:39 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 11:50:39 -0700 Subject: urllib "quote" problem In-Reply-To: References: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> Message-ID: <4c6ece79$0$1583$742ec2ed@news.sonic.net> On 8/20/2010 8:41 AM, Aahz wrote: > In article<4c5eef7f$0$1609$742ec2ed at news.sonic.net>, > John Nagle wrote: >> >> This looks like code that will do the wrong thing in >> Python 2.6 for characters in the range 128-255. Those are >> illegal in type "str", but this code is constructing such >> values with "chr". > > WDYM "illegal"? Type "str" in Python 2.6 is ASCII, 0..127. John Nagle From nagle at animats.com Fri Aug 20 14:54:36 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 11:54:36 -0700 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> <4c6cefc6$0$11111$c3e8da3@news.astraweb.com> <31e9a229-9422-42d4-ab51-14cd4aaf62af@z10g2000yqb.googlegroups.com> Message-ID: <4c6ecf67$0$1639$742ec2ed@news.sonic.net> On 8/20/2010 9:07 AM, Rami Chowdhury wrote: > On Fri, Aug 20, 2010 at 21:02, ata.jaf wrote: >> On Aug 19, 11:48 am, Steven D'Aprano> T... at cybersource.com.au> wrote: >>> On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote: >>>> On Aug 17, 11:55 pm, Thomas Jollans wrote: >> Yes I have a source code encoding line. >> Here it is: >> >> # -*- coding: utf_16 -*- Try "utf_8". >> >> I am using WxPython. >> >> And the error that I get about using utf-16 is:\ >> >> Traceback (most recent call last): >> File "", line 1, in >> File "z.py", line 2 >> SyntaxError: UTF-16 stream does not start with BOM > > Which encoding are you saving your script in? Very few of the text > editors I've used save to UTF-16 by default. Most editors that will do Unicode save files as "utf-8". Try that. John Nagle From thomas at jollybox.de Fri Aug 20 15:04:55 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 20 Aug 2010 21:04:55 +0200 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: <201008202104.55683.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to ata.jaf to exclaim: > On Aug 17, 11:55 pm, Thomas Jollans wrote: > > On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > > > I am developing a little program in Mac with wxPython. > > > But I have problems with the characters that are not in ASCII. Like > > > some special characters in French or Turkish. > > > So I am looking for a way to solve this. Like an encoding standard > > > that supports all languages. Or some other way. > > > > Anything that supports all of Unicode will do. Like UTF-8. If your text > > is mostly Latin, then just go for UTF-8, if you use other alphabets > > extensively, you might want to consider UTF-16, which might the use a > > little less space. > > OK, I used UTF-8. > I write a line of strings in the source code and I want my program to > show that as an output on GUI. And this line of strings includes a > character like "?". But I see that in GUI this character is replaced > with another strange characters. I mean it doesn't work. > And when I try to use UTF-16, I get an syntax error that declares > "UTF-16 stream does not start with BOM". I get the feeling you're not actually using the encoding you say you're using, or not telling every program involved what you're doing. 1. Save the file in the correct encoding. Either tell your text editor to use a specific encoding (UTF-8 would be a good choice), or find out what encoding your text editor is using and use that encoding during the rest of the process. 2. Tell Python which encoding you're using. The coding: line will do the trick, *provided* you don't lie, and the encoding your specify in the file is actually the encoding you're using to store the file on disk. 3. Instruct your GUI library to do the right thing. If you use unicode strings (either by using Python 3 or by using the u"K?se" syntax in Python 2), that should be enough, otherwise, if you're using byte strings, which you shouldn't be doing in this case, you might have to tell the library what you're doing, or use the customary encoding. (For GTK+, this is UTF-8. For other libraries, it might be Latin-1, or system-dependent) From robert.kern at gmail.com Fri Aug 20 15:09:58 2010 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 20 Aug 2010 14:09:58 -0500 Subject: urllib "quote" problem In-Reply-To: <4c6ece79$0$1583$742ec2ed@news.sonic.net> References: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> <4c6ece79$0$1583$742ec2ed@news.sonic.net> Message-ID: On 8/20/10 1:50 PM, John Nagle wrote: > On 8/20/2010 8:41 AM, Aahz wrote: >> In article<4c5eef7f$0$1609$742ec2ed at news.sonic.net>, >> John Nagle wrote: >>> >>> This looks like code that will do the wrong thing in >>> Python 2.6 for characters in the range 128-255. Those are >>> illegal in type "str", but this code is constructing such >>> values with "chr". >> >> WDYM "illegal"? > > Type "str" in Python 2.6 is ASCII, 0..127. In Python 2.6, type "str" is comprised of bytes 0..255, not ASCII characters. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From jkrukoff at ltgc.com Fri Aug 20 15:10:13 2010 From: jkrukoff at ltgc.com (John Krukoff) Date: Fri, 20 Aug 2010 13:10:13 -0600 Subject: [ANN]VTD-XML 2.9 In-Reply-To: <61aedbd9-1fa4-4f37-926e-f57512948a9d@q21g2000prm.googlegroups.com> References: <61aedbd9-1fa4-4f37-926e-f57512948a9d@q21g2000prm.googlegroups.com> Message-ID: <1282331413.3695.1.camel@localhost> On Thu, 2010-08-19 at 17:40 -0700, dontcare wrote: > VTD-XML 2.9, the next generation XML Processing API for SOA and Cloud > computing, has been released. Please visit https://sourceforge.net/projects/vtd-xml/files/ > to download the latest version. > > * Strict Conformance > # VTD-XML now fully conforms to XML namespace 1.0 spec > * Performance Improvement > # Significantly improved parsing performance for small XML files > * Expand Core VTD-XML API > # Adds getPrefixString(), and toNormalizedString2() > * Cutting/Splitting > # Adds getSiblingElementFragment() > * A number of bug fixes and code enhancement including: > # Fixes a bug for reading very large XML documents on some > platforms > # Fixes a bug in parsing processing instruction > # Fixes a bug in outputAndReparse() So, correct me if I'm wrong, but it doesn't look like this project even has a python version. So, why is it on the python-announce list? -- John Krukoff Land Title Guarantee Company jkrukoff at ltgc.com From python at mrabarnett.plus.com Fri Aug 20 15:13:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 20 Aug 2010 20:13:52 +0100 Subject: urllib "quote" problem In-Reply-To: <4c6ece79$0$1583$742ec2ed@news.sonic.net> References: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> <4c6ece79$0$1583$742ec2ed@news.sonic.net> Message-ID: <4C6ED3F0.9030001@mrabarnett.plus.com> John Nagle wrote: > On 8/20/2010 8:41 AM, Aahz wrote: >> In article<4c5eef7f$0$1609$742ec2ed at news.sonic.net>, >> John Nagle wrote: >>> >>> This looks like code that will do the wrong thing in >>> Python 2.6 for characters in the range 128-255. Those are >>> illegal in type "str", but this code is constructing such >>> values with "chr". >> >> WDYM "illegal"? > > Type "str" in Python 2.6 is ASCII, 0..127. > Actually 'str' in Python 2.6 is bytestring, or ASCII + other characters, by which I mean that the other characters aren't affected by .lower, etc. From burton at userful.com Fri Aug 20 15:19:08 2010 From: burton at userful.com (Burton Samograd) Date: Fri, 20 Aug 2010 13:19:08 -0600 Subject: scope of variable References: <1282327776.2942.3.camel@pex-desktop> Message-ID: M B writes: > Hi, >>>> dept=0 >>>> def mud(): > print dept > > >>>> mud() > 0 >>>> def mud(): > dept+=1 > print dept You should add a global statement or else python thinks a variable used is a local: >>> def mud(): global dept dept+=1 print dept -- Burton Samograd From russ.paielli at gmail.com Fri Aug 20 15:31:36 2010 From: russ.paielli at gmail.com (Russ P.) Date: Fri, 20 Aug 2010 12:31:36 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> Message-ID: <6ec14625-0f5e-4f43-b889-150e8add8b1e@a36g2000yqc.googlegroups.com> On Aug 20, 11:19?am, geremy condra wrote: > Not sure what you read, but for me (mostly number theory, numerical > analysis, and abstract algebra) zero-based indexing is quite common. My background is in aerospace control engineering. I am certainly not familiar with the literature in pure mathematics, but I assume that the math textbooks I used on college used standard mathematical notation. If one-based indexing is becoming more common in the literature, I'll bet that is only because it is so widely used in computer programming -- not because the writers decided independently that it is a better notation. But that's just a guess on my part. From tom.browder at gmail.com Fri Aug 20 15:32:54 2010 From: tom.browder at gmail.com (Tom Browder) Date: Fri, 20 Aug 2010 14:32:54 -0500 Subject: How to Customize the New 2.7 ArgumentParser Library Class (module argparse)? Message-ID: I have converted from OptionParser to ArgumentParser (new in version 2.7) to great advantage, and I think it's a great improvement! But now I want to customize the help formatting just a bit. The documentation is sketchy here, but I started by subclassing ArgumentParser and attempted to redefine format_usage, but after looking at the detailed instructions with pydoc I see "the API of the formatter objects is still considered an implementation detail." I take that to mean I should abandon such efforts at the moment. So, using the defined class as is, and following instructions in the online docs, I have been able to get my output to look like this: ==============> $ test_argparser.py -h usage: test_argparser.py [options] A program to manipulate user programs. optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -s, --show Show a list of user post-processing programs. Version 2010-08-20.01 <============== To beautify things I would like to change two strings which are auto-generated by the standard parser: 1. change "usage:" to "Usage:" # capitalize 'usage' 2. change "optional arguments:" to "Optional arguments:" # capitalize 'Optional' Does anyone know how to do it without modifying source code? Thanks, -Tom Thomas M. Browder, Jr. Niceville, Florida USA From thomas at jollybox.de Fri Aug 20 15:36:31 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 20 Aug 2010 21:36:31 +0200 Subject: How to convert bytearray into integer? In-Reply-To: <38b3c3b4-5a06-4fe1-9e5f-7194142a3606@f20g2000pro.googlegroups.com> References: <38b3c3b4-5a06-4fe1-9e5f-7194142a3606@f20g2000pro.googlegroups.com> Message-ID: <201008202136.31591.thomas@jollybox.de> On Tuesday 17 August 2010, it occurred to Jacky to exclaim: > On Aug 17, 3:38 am, Thomas Jollans wrote: > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > it's hard to image why socket object provides the interface: > > > socket.recv_from(buf[, num_bytes[, flags]]) but forget the more > > > generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]]) > > > > Well, that's what pointer arithmetic (in C) or slices (in Python) are > > for! There's an argument to be made for sticking close to the > > traditional (originally C) interface here - it's familiar. > > Hi Thomas, - I'm not quite follow you. It will be great if you could > show me some code no this part... When I originally wrote that, I didn't check the Python docs, I just had a quick look at the manual page. This is the signature of the BSD-socket recv function: (recv(2)) ssize_t recv(int sockfd, void *buf, size_t len, int flags); so, to receive data into a buffer, you pass it the buffer pointer. len = recv(sock, buf, full_len, 0); To receive more data into another buffer, you pass it a pointer further on: len = recv(sock, buf+len, full_len-len, 0); /* or, this might be clearer, but it's 100% the same: */ len = recv(sock, & buf[len], full_len-len, 0); Now, in Python. I assume you were referring to socket.recv_into: socket.recv_into(buffer[, nbytes[, flags]]) It's hard to imagine why this method exists at all. I think the recv method is perfectly adequate: buf = bytearray() buf[:] = sock.recv(full_len) # then: lngth = len(buf) buf[lngth:] = sock.recv(full_len - lngth) But still, nothing's stopping us from using recv_into: # create a buffer large enough. Oh this is so C... buf = bytearray([0]) * full_len lngth = sock.recv_into(buf, length_of_first_bit) # okay, now let's fill the rest ! sock.recv_into(memoryview(buf)[lngth:]) In C, you can point your pointers where ever you want. In Python, you can point your memoryview at buffers in any way you like, but there tend to be better ways of doing things. Cheers, Thomas From znarus at telia.com Fri Aug 20 15:56:52 2010 From: znarus at telia.com (M B) Date: Fri, 20 Aug 2010 21:56:52 +0200 Subject: scope of variable In-Reply-To: References: <1282327776.2942.3.camel@pex-desktop> Message-ID: <1282334212.1887.6.camel@pex-desktop> fre 2010-08-20 klockan 13:19 -0600 skrev Burton Samograd: > M B writes: > > > Hi, > >>>> dept=0 > >>>> def mud(): > > print dept > > > > > >>>> mud() > > 0 > >>>> def mud(): > > dept+=1 > > print dept > > You should add a global statement or else python thinks a variable used > is a local: > > >>> def mud(): > global dept > dept+=1 > print dept > > -- > Burton Samograd > Ok. Thanks for the answers. :) I was a bit puzzled of the fact that I could read but not assign to a global variable. From debatem1 at gmail.com Fri Aug 20 16:07:38 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 20 Aug 2010 13:07:38 -0700 Subject: Python "why" questions In-Reply-To: <6ec14625-0f5e-4f43-b889-150e8add8b1e@a36g2000yqc.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <6ec14625-0f5e-4f43-b889-150e8add8b1e@a36g2000yqc.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 12:31 PM, Russ P. wrote: > On Aug 20, 11:19?am, geremy condra wrote: > >> Not sure what you read, but for me (mostly number theory, numerical >> analysis, and abstract algebra) zero-based indexing is quite common. > > My background is in aerospace control engineering. I am certainly not > familiar with the literature in pure mathematics, but I assume that > the math textbooks I used on college used standard mathematical > notation. > > If one-based indexing is becoming more common in the literature, I'll > bet that is only because it is so widely used in computer programming > -- not because the writers decided independently that it is a better > notation. But that's just a guess on my part. I can't speak for the motivation for selecting that notation, but I'm not sure it matters anyway- if the rationale for a switch is to become consistent with mathematical notation and the 0-based indexing is becoming a common notation in that field then we achieve consistency by standing still. Geremy Condra From john at castleamber.com Fri Aug 20 16:17:22 2010 From: john at castleamber.com (John Bokma) Date: Fri, 20 Aug 2010 15:17:22 -0500 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> Message-ID: <8739u9ninh.fsf@castleamber.com> John Nagle writes: > Python does not do tail recursion, so using recursion > where iteration could do the job is generally a bad idea. Scheme, on > the other hand, always does tail recursion where possible. I think you mean tail recursion optimization / elimination. Python does tail recursion: >>> def x(n): ... if n == 10: return ... print n ... x(n + 1) ... >>> x(1) 1 2 3 4 5 6 7 8 9 -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From __peter__ at web.de Fri Aug 20 16:19:42 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Aug 2010 22:19:42 +0200 Subject: How to Customize the New 2.7 ArgumentParser Library Class (module argparse)? References: Message-ID: Tom Browder wrote: > I have converted from OptionParser to ArgumentParser (new in version > 2.7) to great advantage, and I think it's a great improvement! But > now I want to customize the help formatting just a bit. > > The documentation is sketchy here, but I started by subclassing > ArgumentParser and attempted to redefine format_usage, but after > looking at the detailed instructions with pydoc I see "the API of the > formatter objects is still considered an implementation detail." > > I take that to mean I should abandon such efforts at the moment. > > So, using the defined class as is, and following instructions in the > online docs, I have been able to get my output to look like this: > > ==============> > $ test_argparser.py -h > usage: test_argparser.py [options] > > A program to manipulate user programs. > > optional arguments: > -h, --help Show this help message and exit. > -v, --version Show program's version number and exit. > -s, --show Show a list of user post-processing programs. > > Version 2010-08-20.01 > <============== > > To beautify things I would like to change two strings which are > auto-generated by the standard parser: > > 1. change "usage:" > > to "Usage:" # capitalize 'usage' > > 2. change "optional arguments:" > > to "Optional arguments:" # capitalize 'Optional' > > Does anyone know how to do it without modifying source code? You can use internationalization via http://docs.python.org/library/gettext.html or take a shortcut: $ cat tmp.py lookup = { "usage: ": "Usage: ", "optional arguments": "Optional arguments"} def gettext(s): return lookup.get(s, s) import argparse argparse._ = gettext if __name__ == "__main__": p = argparse.ArgumentParser() p.parse_args() $ python tmp.py -h Usage: tmp.py [-h] Optional arguments: -h, --help show this help message and exit Peter From hughaguilar96 at yahoo.com Fri Aug 20 18:51:44 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Fri, 20 Aug 2010 15:51:44 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> On Aug 18, 6:23?pm, Standish P wrote: > On Aug 17, 6:38?pm, John Passaniti wrote: > > > You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > > lists are constructed with pair of pointers called a "cons cell". > > That is the most primitive component that makes up a list. ?Forth has > > no such thing; in Forth, the dictionary (which is traditionally, but > > not necessarily a list) is a data structure that links to the previous > > word with a pointer. ? > > Would you show me a picture, ascii art or whatever for Forth ? I know > what lisp lists look like so I dont need that for comparison. Forth > must have a convention and a standard or preferred practice for its > dicts. However, let me tell you that in postscript the dictionaries > can be nested inside other dictionaries and any such hiearchical > structure is a nested associative list, which is what linked list, > nested dictionaries, nested tables are. You can see an example of lists in my novice package (in the list.4th file): http://www.forth.org/novice.html Also in there is symtab, which is a data structure intended to be used for symbol tables (dictionaries). Almost nobody uses linked lists for the dictionary anymore (the FIG compilers of the 1970s did, but they are obsolete). I must say, I've read through this entire thread and I didn't understand *anything* that *anybody* was saying (especially the OP). I really recommend that people spend a lot more time writing code, and a lot less time with all of this pseudo-intellectual nonsense. This whole thread (and most of what I see on C.L.F. these days) reminds me of the "dialectic method" of the early Middle Ages --- a lot of talk and no substance. Write some programs! Are we not programmers? From vicente.soler at gmail.com Fri Aug 20 18:54:47 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 15:54:47 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> On Aug 20, 7:42?pm, Tim Golden wrote: > On 20/08/2010 5:10 PM, vsoler wrote: > > > > > On Aug 20, 5:10 pm, Tim Golden ?wrote: > >> To decode the permission bit-strings to vaguely meaningful > >> names: > > >> > >> import os, sys > >> from winsys import fs > > >> dacl = fs.file (sys.executable).security ().dacl > >> for permission in dacl: > >> ? ? print (d.trustee, " (Inherited )" if d.inherited else "") > >> ? ? for name in fs.FILE_ACCESS.names_from_value (d.access): > >> ? ? ? print (" ?", name) > > >> > > >> TJG > > > it seems as though the definition of "d" is missing in your last piece > > of code > > Whoops, changed tack mid-thingy. Try: > > dacl = ... > for d in dacl: > ? ?# .. as before Tim, I'am testing your library. I am mainly interested in knowing the access attributes of directories in the local(C:\) or shared unit(W:\) of my system. Using your script with 'c:\\' I get an error message saying... 'file exists but it is a directory' and I cannot go any further. Of course, the problem is that I am using "fs.file" when I should be using something different. Reading the doc I have found that I should be using os.walk(...), which works, but then I cannot use fs.file Could you please give me a hint as to what metghod I should be using? Thank you Vicente Soler From hughaguilar96 at yahoo.com Fri Aug 20 19:04:44 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Fri, 20 Aug 2010 16:04:44 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> Message-ID: <56ef1e79-7a94-45a7-b854-43b48ed96af8@m1g2000yqo.googlegroups.com> On Aug 18, 6:13?pm, Standish P wrote: > > Mostly it had a "snowball's chance" because it was never picked up by > > the CS gurus who, AFAIK, never really took a serious look at it. > > Its quite possible that the criticism is unfair, but dont you think > that in part some responsibility must be borne by your organization in > not doing a good job of education ? > ... > She is quite humble. Take a look at this page, > > http://www.forth.com/resources/evolution/index.html That is actually pretty humorous; she managed to describe herself as a "leading expert" twice in a single short paragraph. LOL See! I do have a sense of humor! http://groups.google.com/group/comp.lang.forth/browse_thread/thread/4c4dba9135bcf03e/8086ee13095bf78c From ben+python at benfinney.id.au Fri Aug 20 19:17:11 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 21 Aug 2010 09:17:11 +1000 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> Message-ID: <8762z4swlk.fsf@benfinney.id.au> Steven D'Aprano writes: > On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: > > > Recursion can be quite a trick to get your mind round at first > > Really? Do people actually find the *concept* of recursion to be > tricky? Evidently so. It's folk wisdom that some adults find recursion an easy concept, and those people will find programming significantly easier; and the majority of people have a great deal of difficulty with recursion and so find programming correspondingly difficult. There is evidence that the phenomenon is at least significant and measurable . There is all manner of speculation as to what might cause this divide in capability, but precious little scientific research has been done on the differences between such people AFAICT. -- \ ?Two possibilities exist: Either we are alone in the Universe | `\ or we are not. Both are equally terrifying.? ?Arthur C. Clarke, | _o__) 1999 | Ben Finney From mailtome200420032002 at gmail.com Fri Aug 20 19:21:15 2010 From: mailtome200420032002 at gmail.com (aj) Date: Fri, 20 Aug 2010 16:21:15 -0700 (PDT) Subject: make install DESTDIR Message-ID: I am trying to install python with make install DESTDIR=/home/blah ./python -E ./setup.py install \ --prefix=/ \ --install-scripts=//bin \ --install-platlib=//lib/python2.6/lib-dynload \ --root=//home/blah running install running build running build_ext INFO: Can't locate Tcl/Tk libs and/or headers Failed to find the necessary bits to build these modules: _tkinter bsddb185 dl imageop sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. running build_scripts running install_lib creating /lib/python2.6 error: could not create '/lib/python2.6': Permission denied make: *** [sharedinstall] Error 1 From raoulbia at gmail.com Fri Aug 20 19:22:44 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 20 Aug 2010 16:22:44 -0700 (PDT) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: Hi Martin Thanks for your post. This basic but fundamental computation is a great example when trying to understand the concept of recursion for the first time. Also thanks to John for the stackoverflow link where i found a very good summarised definition completing some of the posts left here. For future readers of this post who want to learn to programm (just like myself) let me re-state the basics i have learned now: - a procedure is said to be recursive when it contains a statement that calls itself - there must be a condition where the recursion has to stop otherwise the routine will continue to call itself infinitely. This is called the Base Case - every time the procedure calls itself the memory gradually fills up with the copies until the whole thing winds down again as the "return" statements start being executed. - the above point means that a recursive approach is expensive on resources so in the practical world it should be avoided. (Thanks John for giving me a real life example where recursion is recommended) For the purposes of learning programming i think it's a must to understand Recursion so thanks all for your help! Ok so now i hope you all agree that my code is also correct :) def r_countSubStringMatch(target,key): counter=0 if len(key) References: Message-ID: <201008210139.47901.thomas@jollybox.de> On Saturday 21 August 2010, it occurred to aj to exclaim: > I am trying to install python with make install DESTDIR=/home/blah > > --prefix=/ ... > creating /lib/python2.6 > error: could not create '/lib/python2.6': Permission denied > make: *** [sharedinstall] Error 1 Obviously, the flags you specified didn't have the effect you intended. --prefix=$HOME should do the trick. From raoulbia at gmail.com Fri Aug 20 19:42:26 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 20 Aug 2010 16:42:26 -0700 (PDT) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: On Aug 19, 11:00?pm, Martin Gregorie wrote: > By way of a hint, here are two versions of the classic example of > recursion: calculating factorials. Recursion can be quite a trick to get > your mind round at first, so compare the two and follow through their > operation step by step... Hi Martin Thanks for your post. This basic but fundamental computation (calculating factorials) is a great example when trying to understand the concept of recursion for the first time. Also thanks to John for the stackoverflow link where i found a very good summarised definition completing some of the posts left here. For future readers of this post who want to learn to programm (just like myself) let me re-state the basics i have learned now: - a procedure is said to be recursive when it contains a statement that calls itself - there must be a condition where the recursion has to stop otherwise the routine will continue to call itself infinitely. This is called the Base Case - every time the procedure calls itself the memory gradually fills up with the copies until the whole thing winds down again as the "return" statements start being executed. - the above point means that a recursive approach is expensive on resources so in the practical world it should be avoided. (Thanks John for giving me a real life example where recursion is recommended) For the purposes of learning programming i think it's a must to understand Recursion so thanks all for your help! Ok so now i hope you all agree that my code is also correct :) def r_countSubStringMatch(target,key): counter=0 if len(key) References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <201008210159.46825.thomas@jollybox.de> On Saturday 21 August 2010, it occurred to Baba to exclaim: > - every time the procedure calls itself the memory gradually fills up > with the copies until the whole thing winds down again > as the "return" statements start being executed. > - the above point means that a recursive approach is expensive on > resources so in the practical world it should be avoided. > (Thanks John for giving me a real life example where recursion is > recommended) This is only partly true. In most programming languages "typical" today, this is true: each recursion is a normal function call which allocates space on the stack. Thus, the maximum recursion depth is severely limited. However, in most functional programming languages, recursion is recognized as a highly expressive, powerful, and idiomatic tool that can often be optimized. Languages like haskell or scheme compile tail-end recursive functions in a manner that is just as efficient as a loop would have been. In general, if you could rewrite a recursive scheme function to use a loop, then a decent scheme compiler will be able to "do it for you" behind the scenes. From greg.ewing at canterbury.ac.nz Fri Aug 20 20:17:09 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 12:17:09 +1200 Subject: Python "why" questions In-Reply-To: References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: <8d8jnkFoitU1@mid.individual.net> Lawrence D'Oliveiro wrote: > That is not some kind of ordinal numbering of the terms, that is the power > of the variable involved. It's both. Convention is to make the power and the index of the coefficent the same, because it would be pointlessly confusing to do anything else. -- Greg From martin at address-in-sig.invalid Fri Aug 20 20:24:18 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Sat, 21 Aug 2010 00:24:18 +0000 (UTC) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: On Fri, 20 Aug 2010 16:22:44 -0700, Baba wrote: > For the purposes of learning programming i think it's a must to > understand Recursion so thanks all for your help! > That depends on the language and/or hardware. COBOL wouldn't understand recursion if hit on the head with a recursion brick and early computer hardware (those without a stack) made it VERY hard work. If you don't follow this, look at the CODASYL language specification for COBOL or the hardware design of ICL 1900 or IBM System/360 mainframes (which are still the heart of the financial world) and work out how to implement a recursive function for any of them. Its not easy but it can be done. > Ok so now i hope you all agree that my code is also correct :) > Yes: it runs and does what I'd expect. A good result. A basic skill for a programmer is to understand the specification for a piece of code and write test cases. This is a set of inputs (both expected/sensible and totally out of order) and the expected outputs from each set of inputs. Then you write the code and run it against the test cases to show that it does what the specification requires. Never bullshit yourself or anybody else about this conformance to spec: either you screwed up or, hopefully less often, the designer wrote an ambiguous or plain wrong requirement. Either way, the problem must be resolved and the code be made to do what is wanted. while (results don't match the spec): Rince, wash, repeat. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From greg.ewing at canterbury.ac.nz Fri Aug 20 20:26:19 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 12:26:19 +1200 Subject: Python "why" questions In-Reply-To: References: <8crequF9tpU1@mid.individual.net> Message-ID: <8d8k8vFs2qU1@mid.individual.net> Martin Gregorie wrote: > On Mon, 16 Aug 2010 12:33:51 +1200, Gregory Ewing wrote: > > >>Ian Kelly wrote: >> >>>On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie >>> wrote: >> >>>> real sample[-500:750]; >> >>>Ugh, no. The ability to change the minimum index is evil. >> >>Not always; it can have its uses, particularly when you're using the >>array as a mapping rather than a collection. >> > > Say you have intensity data captured from an X-ray goniometer from 160 > degrees to 30 degrees at 0.01 degree resolution. Which is most evil of > the following? > > 1) real intensity[16000:3000] > for i from lwb intensity to upb intensity > plot(i/100, intensity[i]); > > 2) double angle[13000]; > double intensity[13000]; > for (int i = 0; i < 13000; i++) > plot(angle[i], intensity[i]); > > 3) struct > { > double angle; > double intensity > } measurement; > measurement m[13000]; > for (int i = 0; i < 13000; i++) > plot(m[i].angle, m[i].intensity); > > 4) double intensity[13000]; > for (int i = 0; i < 13000; i++) > plot((16000 - i)/100, intensity[i]) > > To my mind (1) is much clearer to read and far less error-prone to write, > while zero-based indexing forces you to use code like (2), (3) or (4), > all of which obscure rather than clarify what the program is doing. This might be true if the only thing you ever do with your indices is use them to iterate over the array. However, if you need to do any arithmetic with them, you may find yourself thinking again. Also, in Python you wouldn't write iteration loops that way in the first place. You would write things such as for x, y in zip(angle, intensity): plot(x, y) which avoids dealing with indexes altogether. The only time you really need to use indexes in Python is when you want to do arithmetic with them, or take slices, both of which turn out to be less confusing most of the time with 0-based indexing. -- Greg From greg.ewing at canterbury.ac.nz Fri Aug 20 20:27:52 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 12:27:52 +1200 Subject: Python "why" questions In-Reply-To: References: <8crequF9tpU1@mid.individual.net> Message-ID: <8d8kbmFs2qU2@mid.individual.net> Robert Kern wrote: > On 8/16/10 9:29 PM, Roy Smith wrote: > >> In article, >> Lawrence D'Oliveiro wrote: >> >>> In message, Roy Smith wrote: >>> >>>> 5) real intensity[160.0 : 30.0 : 0.01] >>> >>> How many elements in that array? >>> >> c) neither of the above. More specifically, 13,001 (if I counted >> correctly). > > 13000, actually. Floating point is a bitch. Or 12999.9999999 if you're unlucky. Floating point is a *real* bitch! -- Greg From greg.ewing at canterbury.ac.nz Fri Aug 20 20:29:53 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 12:29:53 +1200 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> Message-ID: <8d8kffFs2qU3@mid.individual.net> J.B. Brown wrote: > Then users of my class (mainly my research lab coworkers) could > specify whichever behavior they wanted. > > In terms of providing readable code and removing beginning programmer > confusion, But having some arrays indexed from 0 and others from 1 can be a recipe for confusion in its own right. -- Greg From mailtome200420032002 at gmail.com Fri Aug 20 21:12:16 2010 From: mailtome200420032002 at gmail.com (aj) Date: Fri, 20 Aug 2010 18:12:16 -0700 (PDT) Subject: make install DESTDIR References: Message-ID: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> On Aug 20, 4:39?pm, Thomas Jollans wrote: > On Saturday 21 August 2010, it occurred to aj to exclaim: > > > I am trying to install python with make install DESTDIR=/home/blah > > > ? ? ? ? ? ? ? ? --prefix=/ > > ... > > > creating /lib/python2.6 > > error: could not create '/lib/python2.6': Permission denied > > make: *** [sharedinstall] Error 1 > > Obviously, the flags you specified didn't have the effect you intended. > > ? --prefix=$HOME > > should do the trick. The whole point of DESTDIR is that it should be prepended to all installed paths, but the binaries should not contain any references to it.DESTDIR is commonly used by packagers, for example, to allow installation without superuser privileges. From greg.ewing at canterbury.ac.nz Fri Aug 20 21:22:35 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 13:22:35 +1200 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> Message-ID: <8d8nicFc1dU1@mid.individual.net> Martin Braun wrote: > Another thing worth mentioning (I guess here is a good a place as any > other) is the fact that programming and mathematics are still pretty > different things, despite how much we programmers would like to think > ourselves as some kind of mathematician. Although when it comes to indexing, mathematics and programming have remarkably similar issues. I've seen mathematics texts that made a poor choice of index base and ended up with formulas confusingly littered with plus and minus ones, or where I've had to scratch my head a few times and look back to find out whether a particular index was meant to start from 0 or 1. Also it doesn't help that the sigma notation lends itself more to closed than half-open intervals, which can lead to a Hobson's choice between i-1 in the formulas and n-1 in the summation range. -- Greg From greg.ewing at canterbury.ac.nz Fri Aug 20 21:29:59 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 13:29:59 +1200 Subject: Python "why" questions In-Reply-To: <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> Message-ID: <8d8o08Fe34U1@mid.individual.net> Russ P. wrote: > It all boils down to personal preference, but I just find it strange > that we would not try to make programming as consistent as possible > with notational conventions in the literature. It doesn't matter how much mathematical convention you quote, your assertion that 1-based indexing is better won't convince me, because it flies in the face of my own personal experience. > The zero-based indexing just seemed wrong to me when I first saw it. > I'm used to it by now, but it still doesn't seem quite right to me. > It's almost right -- but it's off by one. I still have a habit of > taking the "1" element when I really want the "0" element. That may be because you haven't fully adopted 0-based indexing into your thinking. You're trying to think in terms of 1-based indexes and convert to 0-based when you code. If you think in 0-based indexes in the first place, many things become simpler. -- Greg From greg.ewing at canterbury.ac.nz Fri Aug 20 21:41:10 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 13:41:10 +1200 Subject: Pop return from stack? In-Reply-To: References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: <8d8ol4FgdpU1@mid.individual.net> bvdp wrote: > The whole problem I was having is that I was trying to tie a small > application (an helper to the main application) to use a bit of the > existing code as a pseudo-library. This is precisely the reason that it's a bad idea to directly terminate the program from somewhere deep inside the code. It makes it hard to re-use the code in another context. It's much better to raise an exception containing an appropriate error message, catch it at the top level of the application and print the message and exit there. Then you can easily re-use any of the code in a context where it's not appropriate to have it exit out from under you. -- Greg From me+list/python at ixokai.io Fri Aug 20 22:13:52 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Fri, 20 Aug 2010 19:13:52 -0700 Subject: Simple Python Sandbox In-Reply-To: <20100816140142.GB22789@localhost> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4C67586C.3020107@ixokai.io> <20100816140142.GB22789@localhost> Message-ID: <4C6F3660.4000901@ixokai.io> On 8/16/10 7:01 AM, Roland Koebler wrote: > On Sat, Aug 14, 2010 at 08:01:00PM -0700, Stephen Hansen wrote: >>> As you can see, black listing isn't the best approach here. >> >> But I have a two pronged strategy: the black list is only half of the >> equation. One, I'm blacklisting all the meta functions out of builtins. > But blacklists are *never* secure. Sorry, but you should fully understand > this before even thinking about more detailed security. And whitelists are never secure, either. There is no such thing as perfectly secure, no. But that is not a goal that I've set for this at all. There's more secure, less secure, more likely to provide a vector for attack, less likely to provide a vector for attack. Every security precaution does end up having a cost: every one weakens the resulting environment or makes something someone wants to do legitimately more hard. Security is always a trade off. The goal is "secure enough" -- and what 'enough' is is going to vary a lot depending on different people's needs. If I were in a situation where I'm executing arbitrary code gathered off of the 'net, that'd be a very different demand and I'd be a lot more keen on finding a perfect sand box (and thus would simply not use Python). That isn't the case here; my relatively untrusted users are uniquely and specifically identifyable and trackable, their interface to the system is logged and actions recorded. There's no money involved in this system, nor possibility that someone could use it to get higher tier access on the parent machine: if someone gets through the sandbox, it'll be a nuisance, hurt some people's enjoyment, harm a community, but really-- it should be able to be fixed pretty rapidly, and then that person utterly locked out. I just want a sandbox that is good enough that it'd be really hard for someone to do that. That's all. Minimize how many times I have to go fix up something. :) > Why are you blacklisting the "known-bad" functions instead of whitelising > the allowed ones?? Because that would annoy some of the other users, who think the status quo isn't really all that bad and that I'm paranoid :) Me, I'm going to go farther on my own installation and kill import entirely, and do a sort of require() which returns a special proxied version of an imported module only if its on a pre-allowed white-list, and even then each individual member of said module will have to be white-listed specifically, too. But in general, I just want a better sandbox that starts things off without getting in anyone's way to do totally legitimate sorts of things. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From ahleniusm at gmail.com Fri Aug 20 23:07:00 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 20:07:00 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> <19aa141c-1ae9-47ed-bf4b-9af0b0de0396@u26g2000yqu.googlegroups.com> Message-ID: <5bf10ba0-cb79-46e4-8cef-a8579e905d58@x42g2000yqx.googlegroups.com> On Aug 20, 12:55?pm, Peter Otten <__pete... at web.de> wrote: > m_ahlenius wrote: > > I am using Python 2.6.5. > > > Unfortunately I don't have other versions installed so its hard to > > test with a different version. > > > As for the log compression, its a bit hard to test. ?Right now I may > > process 100+ of these logs per night, and will get maybe 5 which are > > reported as corrupt (typically a bad CRC) and 2 which it reported as a > > bad tar archive. ?This morning I checked each of the 7 reported > > problem files by manually opening them with "tar -xzvof" and they were > > all indeed corrupt. Sign. > > So many corrupted files? I'd say you have to address the problem with your > infrastructure first. > > > Unfortunately due to the nature of our business, I can't post the data > > files online, I hope you can understand. ?But I really appreciate your > > suggestions. > > > The thing that gets me is that it seems to work just fine for most > > files, but then not others. ?Labeling normal files as corrupt hurts us > > as we then skip getting any log data from those files. > > > appreciate all your help. > > I've written an autocorruption script, > > import sys > import subprocess > import tarfile > > def process(source, dest, data): > ? ? for pos in range(len(data)): > ? ? ? ? for bit in range(8): > ? ? ? ? ? ? new_data = data[:pos] + chr(ord(data[pos]) ^ (1< data[pos+1:] > ? ? ? ? ? ? assert len(data) == len(new_data) > ? ? ? ? ? ? out = open(dest, "w") > ? ? ? ? ? ? out.write(new_data) > ? ? ? ? ? ? out.close() > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? t = tarfile.open(dest) > ? ? ? ? ? ? ? ? for f in t: > ? ? ? ? ? ? ? ? ? ? t.extractfile(f) > ? ? ? ? ? ? except Exception, e: > ? ? ? ? ? ? ? ? if 0 == subprocess.call(["tar", "-xf", dest]): > ? ? ? ? ? ? ? ? ? ? return pos, bit > > if __name__ == "__main__": > ? ? source, dest = sys.argv[1:] > ? ? data = open(source).read() > ? ? print process(source, dest, data) > > and I can indeed construct an archive that is rejected by tarfile, but not > by tar. My working hypothesis is that the python library is a bit stricter > in what it accepts... > > Peter Thanks - that's cool. A friend of mine was suggesting that he's seen similar behaviour when he uses Perl on these types of files when the OS (Unix) has not finished writing them. We have an rsync process which sync's our servers for these files and then come down somewhat randomly. So its conceivable I think that this process could be trying to open a file as its being written. I know it sounds like a stretch but my guess is that its a possibility. I could verify that with the timestamps of the errors in my log and the mod time on the original file. 'mark From john.passaniti at gmail.com Fri Aug 20 23:10:19 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Fri, 20 Aug 2010 20:10:19 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: On Aug 20, 6:51?pm, Hugh Aguilar wrote: > You can see an example of lists in my novice package (in the list.4th > file):http://www.forth.org/novice.html > Also in there is symtab, which is a data structure intended to be used > for symbol tables (dictionaries). Almost nobody uses linked lists for > the dictionary anymore (the FIG compilers of the 1970s did, but they > are obsolete). Thanks for pointing this out, Hugh. After reading the code in your novice package and symtab, I am confused: With code of that caliber and the obvious stunning intellect behind it, why hasn't everyone adapted your awesome symtab for symbol tables instead? Any why hasn't there been an effort to translate symtab into other languages so users outside of Forth can also experience the sheer speed and hyper- efficient use of memory and CPU? Let me say I find it refreshing that a great programmer like yourself doesn't bother with stupid fads like testing algorithms against large data sets and measuring performance relative to competitive algorithms. That's all academic nonsense. The only test and measurement anyone needs are the comments at the top of symtab where you state your algorithm is better. You clearly wouldn't have written that if it wasn't true. > Write some programs! Are we not programmers? Amen! All this academic talk is useless. Who cares about things like the big-O notation for program complexity. Can't people just *look* at code and see how complex it is?! And take things like the years of wasted effort computer scientists have put into taking data structures (like hashes and various kinds of trees) and extending them along various problem domains and requirements. Real programmers don't waste their time with learning that junk. What good did any of that ever do anyone?! Thanks Hugh for a refreshing stance on what it means to be a programmer. From ldo at geek-central.gen.new_zealand Fri Aug 20 23:19:22 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 21 Aug 2010 15:19:22 +1200 Subject: 79 chars or more? References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> Message-ID: In message , Jean-Michel Pichavant wrote: > Saying that, if one intend to distribute its code, he should stick to 80 > chars per line. Why? From rowlett at pcnetinc.com Sat Aug 21 00:07:50 2010 From: rowlett at pcnetinc.com (Richard Owlett) Date: Fri, 20 Aug 2010 23:07:50 -0500 Subject: OI VEY, I AGREE -was once [Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?] In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: John Passaniti wrote: > On Aug 20, 6:51 pm, Hugh Aguilar wrote: >> You can see an example of lists in my novice package (in the list.4th >> file):http://www.forth.org/novice.html >> Also in there is symtab, which is a data structure intended to be used >> for symbol tables (dictionaries). Almost nobody uses linked lists for >> the dictionary anymore (the FIG compilers of the 1970s did, but they >> are obsolete). > > Thanks for pointing this out, Hugh. After reading the code in your > novice package and symtab, I am confused: With code of that caliber > and the obvious stunning intellect behind it, why hasn't everyone > adapted your awesome symtab for symbol tables instead? Any why hasn't > there been an effort to translate symtab into other languages so users > outside of Forth can also experience the sheer speed and hyper- > efficient use of memory and CPU? Let me say I find it refreshing that > a great programmer like yourself doesn't bother with stupid fads like > testing algorithms against large data sets and measuring performance > relative to competitive algorithms. That's all academic nonsense. > The only test and measurement anyone needs are the comments at the top > of symtab where you state your algorithm is better. You clearly > wouldn't have written that if it wasn't true. > >> Write some programs! Are we not programmers? > > Amen! All this academic talk is useless. Who cares about things like > the big-O notation for program complexity. Can't people just *look* > at code and see how complex it is?! And take things like the years of > wasted effort computer scientists have put into taking data structures > (like hashes and various kinds of trees) and extending them along > various problem domains and requirements. Real programmers don't > waste their time with learning that junk. What good did any of that > ever do anyone?! > > Thanks Hugh for a refreshing stance on what it means to be a > programmer. > Never thought I I'd agree wholeheartedly with very verbose John. Hugh, you are complete idiot! (and other less complementary ...) From stndshp at gmail.com Sat Aug 21 01:36:18 2010 From: stndshp at gmail.com (Standish P) Date: Fri, 20 Aug 2010 22:36:18 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: <00b9244e-7339-45b0-b38b-9c9854286345@l6g2000yqb.googlegroups.com> On Aug 18, 8:05?pm, Elizabeth D Rather wrote: > On 8/18/10 2:23 PM, Standish P wrote: > > > On Aug 17, 6:38 pm, John Passaniti ?wrote: > > >> You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > >> lists are constructed with pair of pointers called a "cons cell". > >> That is the most primitive component that makes up a list. ?Forth has > >> no such thing; in Forth, the dictionary (which is traditionally, but > >> not necessarily a list) is a data structure that links to the previous > >> word with a pointer. > > > Would you show me a picture, ascii art or whatever for Forth ? I know > > what lisp lists look like so I dont need that for comparison. Forth > > must have a convention and a standard or preferred practice for its > > dicts. However, let me tell you that in postscript the dictionaries > > can be nested inside other dictionaries and any such hiearchical > > structure is a nested associative list, which is what linked list, > > nested dictionaries, nested tables are. > > You indicated that you have a copy of Forth Application Techniques. > Sections 8.1 and 8.2 cover this topic, with some drawings. Can someone send me a scan copy of sec 8.1 to 8.2 within the exemption in the copyright law for my personal study and evaluation of the book only. I have only looked at the book cover on forth site and its table of contents on amazon. why elase would I ask where it is if I had a copy and would go directly to index assuming it has a good indexing. Alternative, a link to an open source of explanation would be requested. From stndshp at gmail.com Sat Aug 21 01:42:18 2010 From: stndshp at gmail.com (Standish P) Date: Fri, 20 Aug 2010 22:42:18 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: On Aug 20, 3:51?pm, Hugh Aguilar wrote: > On Aug 18, 6:23?pm, Standish P wrote: > > > > > > > On Aug 17, 6:38?pm, John Passaniti wrote: > > > > You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > > > lists are constructed with pair of pointers called a "cons cell". > > > That is the most primitive component that makes up a list. ?Forth has > > > no such thing; in Forth, the dictionary (which is traditionally, but > > > not necessarily a list) is a data structure that links to the previous > > > word with a pointer. ? > > > Would you show me a picture, ascii art or whatever for Forth ? I know > > what lisp lists look like so I dont need that for comparison. Forth > > must have a convention and a standard or preferred practice for its > > dicts. However, let me tell you that in postscript the dictionaries > > can be nested inside other dictionaries and any such hiearchical > > structure is a nested associative list, which is what linked list, > > nested dictionaries, nested tables are. > > You can see an example of lists in my novice package (in the list.4th > file):http://www.forth.org/novice.html > Also in there is symtab, which is a data structure intended to be used > for symbol tables (dictionaries). Almost nobody uses linked lists for > the dictionary anymore (the FIG compilers of the 1970s did, but they > are obsolete). > > I must say, I've read through this entire thread and I didn't > understand *anything* that *anybody* was saying (especially the OP). You didnt understand anything because no one explained anything coherently. Admittedly, I am asking a question that would be thought provoking to those who claim to be "experts" but these experts are actually very stingy and mean business people, most certainly worse than Bill Gates, only it did not occur to them his ideas and at the right time. > I really recommend that people spend a lot more time writing code, and a > lot less time with all of this pseudo-intellectual nonsense. You have to have a concept to write code. > This > whole thread (and most of what I see on C.L.F. these days) reminds me > of the "dialectic method" of the early Middle Ages --- a lot of talk > and no substance. > > Write some programs! Are we not programmers?- Hide quoted text - > > - Show quoted text - From mail at timgolden.me.uk Sat Aug 21 02:10:53 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 21 Aug 2010 07:10:53 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: <4C6F6DED.6080202@timgolden.me.uk> On 20/08/2010 11:54 PM, vsoler wrote: > I'am testing your library. I am mainly interested in knowing the > access attributes of directories in the local(C:\) or shared unit(W:\) > of my system. > > Using your script with 'c:\\' I get an error message saying... 'file > exists but it is a directory' and I cannot go any further. > > Of course, the problem is that I am using "fs.file" when I should be > using something different. Either use fs.dir (if you know it's a directory) or fs.entry (if it could be a file or a directory; the code will dispatch to the right one). If you only want the directories immediately some directory, you could do this: from winsys import fs, security root = fs.file (sys.executable).path # or fs.dir ("w:/") etc. for d in root.dirs (ignore_access_errors=True): print (d, "=>", d.security ()) # or whatever If you want to walk the tree of directories looking at permissions, then: import os, sys from winsys import fs root = fs.file (sys.executable).path for dirpath, _, _ in root.walk (): print (dirpath, "=>", dirpath.security ()) > Reading the doc I have found that I should be using os.walk(...), > which works, but then I cannot use fs.file In fact, even if you did for some reason use os.walk, you can easily wrap the returned filenames using fs.entry: import os, sys from winsys import fs root = os.path.dirname (sys.executable) for dirpath, filenames, dirnames in os.walk (root): print (dirpath, "=>", fs.entry (dirpath).security ()) TKG From nagle at animats.com Sat Aug 21 02:37:12 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 23:37:12 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: <8739u9ninh.fsf@castleamber.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> Message-ID: <4c6f7413$0$1631$742ec2ed@news.sonic.net> On 8/20/2010 1:17 PM, John Bokma wrote: > John Nagle writes: > >> Python does not do tail recursion, so using recursion >> where iteration could do the job is generally a bad idea. Scheme, on >> the other hand, always does tail recursion where possible. > > I think you mean tail recursion optimization / elimination. > Python does tail recursion: Not very well. def cnt(n) : if n > 0 : cnt(n-1) This will work for up to cnt(998), but at cnt(999), CPython reports "RuntimeError: maximum recursion depth exceeded." Yes, you can increase the recursion depth, but that case shouldn't be compiled to recursion at all. John Nagle From nagle at animats.com Sat Aug 21 02:40:53 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 23:40:53 -0700 Subject: scope of variable In-Reply-To: References: <1282327776.2942.3.camel@pex-desktop> Message-ID: <4c6f74ef$0$1631$742ec2ed@news.sonic.net> On 8/20/2010 12:56 PM, M B wrote: > fre 2010-08-20 klockan 13:19 -0600 skrev Burton Samograd: >> M B writes: >> >>> Hi, >>>>>> dept=0 >>>>>> def mud(): >>> print dept >>> >>> >>>>>> mud() >>> 0 >>>>>> def mud(): >>> dept+=1 >>> print dept >> >> You should add a global statement or else python thinks a variable used >> is a local: >> >>>>> def mud(): >> global dept >> dept+=1 >> print dept >> >> -- >> Burton Samograd >> > Ok. Thanks for the answers. :) I was a bit puzzled of > the fact that I could read but not assign to a global variable. If you assign before a read, you create a local variable. If you read only, you get a global access. If you do a read before an assignment, you get an error message. John Nagle From wuwei23 at gmail.com Sat Aug 21 02:40:59 2010 From: wuwei23 at gmail.com (alex23) Date: Fri, 20 Aug 2010 23:40:59 -0700 (PDT) Subject: expression in an if statement References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> <4c6e1a93$0$1658$742ec2ed@news.sonic.net> Message-ID: <95be46b5-cfa8-49df-9b77-28e62f766168@h40g2000pro.googlegroups.com> John Nagle wrote: > I was talking to the Facebook guys doing the compiler for PHP, and they > said that it was a huge win for them that PHP doesn't allow dynamically > replacing a function. I'm not sure if I call all that effort for a 50% speed increase a win. PyPy is seeing speed increases of up to 15 times that of CPython 2.6.2 without reducing the flexibility of the language at all. From erather at forth.com Sat Aug 21 03:39:58 2010 From: erather at forth.com (Elizabeth D Rather) Date: Fri, 20 Aug 2010 21:39:58 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: On 8/20/10 7:42 PM, Standish P wrote: ... >Admittedly, I am asking a question that would be thought > provoking to those who claim to be "experts" but these experts are > actually very stingy and mean business people, most certainly worse > than Bill Gates, only it did not occur to them his ideas and at the > right time. The problem as I see it is that you're asking complex questions in a forum that, at best, supports simple answers. The information you're looking for exists, on the net, free. There are free pdfs of manuals on Forth available with program downloads from FORTH, Inc., MPE, Gforth, and other sources, as well as some inexpensive books. But you have to be willing to make the investment to download and read them, because the answers to your questions are not simple one-liners that you can get from newsgroups, and the folks in newsgroups are not prepared to host computer science seminars -- many of us are working programmers, engineers, and project managers who have limited time to spend here. If you're willing to invest your time enough to investigate some of these sources, and still have questions, we'll be happy to try to help. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 04:30:53 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 08:30:53 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> Message-ID: <4c6f8ebc$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 09:47:30 +0200, News123 wrote: > On 08/20/2010 02:26 AM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be >> tricky? > Is this a sincere surprise or are you just boasting? Why would it be boasting? I didn't say that at the age of seven I independently invented a COBOL compiler that supported recursion. *That* would be boasting. (It would also be a lie -- at the age of seven, I don't think I even knew about the existence of computers.) Boasting about understanding the idea of recursion is kind of like boasting about the putting my hands in the correct glove nine times out of ten. [...] > The fact, that you didn't have the issue doens't mean it's easy for > others. Apparently not. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 04:31:25 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 08:31:25 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e9de9$0$23142$426a74cc@news.free.fr> Message-ID: <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: > Steven D'Aprano a ?crit : >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be >> tricky? >> >> > I onced worked in a shop (Win32 desktop / accouting applications mainly) > where I was the only guy that could actually understand recursion. FWIW, > I also was the only guy around that understood "hairy" (lol) concepts > like callback functions, FSM, FSM? Flying Spaghetti Monster? > polymorphism, hashtables, linked lists, > ADTs, algorithm complexity etc... Was there anything they *did* understand, or did they just bang on the keyboard at random until the code compiled? *wink* > Needless to say, I didn't last long !-) And rightly so :) -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 04:33:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 08:33:26 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> Message-ID: <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: > Most programmers probably never use vectors and matrices, so they don't > care about the inconsistency with standard mathematical notation. Perhaps you should ask the numpy programmers what they think about that. Vectors and matrices are just arrays, and the suggestion that most programmers don't use arrays (or array-like objects like lists) is ludicrous. > And yes, I understand that zero-based indexing can be slightly more > efficient. That's why I think it's appropriate for low-level languages > such as C. However, I think one-based indexing is more appropriate for > high-level languages. Only if your aim is to reduce the learning curve for newbies and non- programmers, at the expense of making it easier for them to produce buggy code. That's a defensible choice. I'm a great fan of Apple's Hypercard from the late 80s and early 90s, and it used one-based indexing, as well as English-like syntax like: put char 2 of the third word of it into the last field You don't need to know a thing about the language to guess what that does, and you'd probably be right. It would have been inappropriate for Hypercard to use zero-based indexing, because it was aimed at giving non- programmers a shallow learning curve and syntax that looks like natural language. There is room in the world for programming languages aimed at non- programmers (although HC is an extreme case), but not all languages should prefer the intuition of non-programmers over other values. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 04:54:19 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 08:54:19 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c6f943a$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 09:21:25 +0200, Kai Borgolte wrote: > Sorry about my previous posting with wrong references, this one should > be better. > > Steven D'Aprano wrote: > >>A simple example: Using zero-based indexing, suppose you want to indent >>the string "spam" so it starts at column 4. How many spaces to you >>prepend? As AK pointed out, I totally messed up the example by talking about column 4 then giving an example of column 5. Sigh. 0123456789 spam > No, you won't want to indent a string so it starts at column 4. You > simply want to indent the string by four spaces. Like in PEP 8: > > /Use 4 spaces per indentation level./ I don't see what PEP 8 has to do with anything here. Code is not the only thing that needs indenting, and 4 was just a mere example chosen at random. I might be pretty-printing a table of numbers, I might be drawing a text-based maze, I could be writing a function to left-fill strings with some arbitrary character, e.g left-fill with asterisks: 01234567 ****spam Besides, PEP 8 is merely a coding standard, not a law of nature. Some people might choose other coding standards, such as two-space indents, eight-spaces, or even (gasp! horror!) tabs. > And of course your text editor will number the columns beginning with > one, so the string starts at column 5. Ah, text editors. I'm glad you mention that... My text editor of choice is kwrite, which suits me fine, but it has one obnoxious, painful design choice. It indexes characters from one, so when I have the cursor at the left-hand margin and haven't typed anything, it says I'm at position 1. Consequently, if I want to know how many characters are in a line (and you'd be amazed how frequently I need to do this!), I can't just glance at the cursor position, I have to remember to subtract one from whatever the cursor position says. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 05:03:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 09:03:42 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4c6f966e$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 16:42:26 -0700, Baba wrote: > For future readers of this post who want to learn to programm (just like > myself) let me re-state the basics i have learned now: I would disagree in part with nearly all of these. > - a procedure is said to be recursive when it contains a statement that > calls itself Not necessarily. A function can be indirectly recursive -- function f can call function g which calls function h which calls function f. This is still recursion, even though f doesn't contain a statement which calls itself. > - there must be a condition where the recursion has to stop otherwise > the routine will continue to call itself infinitely. > This is called the Base Case I agree with this, although I've never heard the name "Base Case" before. > - every time the procedure calls itself the memory gradually fills up > with the copies until the whole thing winds down again > as the "return" statements start being executed. That's so vague as to be almost meaningless. I think what you are talking about is one specific part of memory, the calling stack, which fills up with arguments needed to call the function, and then empties as the recursive calls return. However, there is an import class of recursive calls where a sufficiently smart compiler can avoid this cost, essentially turning recursion into iteration automatically, speeding up recursion drastically. > - the above point means that a recursive approach is expensive on > resources so in the practical world it should be avoided. True-ish for the first part of the sentence, absolutely false for the second. Recursion can be slower and more memory consuming than iteration under some circumstances, although this depends on the specific way that recursion is used, not the mere fact that recursion happens. A single recursive call is no more expensive than any other function call. Also, as mentioned, some compilers can optimize tail-call recursion to make it as fast and efficient as iteration. (However, Python doesn't do this.) In the real world, avoiding recursion also has costs. Your function may be bigger, more complicated, need more memory, possibly manage its own stack. None of these things happen for free. Whether a specific recursive function is better than a specific iterative function depends on the details of what that function does and what arguments you call it with. If your recursive function is likely to use only a few recursive calls, there is no need to complicate matters by re-writing it iteratively. There's no need to avoid recursion just because it is recursive. Also, recursion together with memoisation can be extremely fast and efficient, at some cost of memory. For example, the typical recursive version of factorisation: def fact(n): if n <= 1: return 1 return n*fact(n-1) can be made much, much faster by giving it a simple cache: def fact(n): try: cache = fact.cache except AttributeError: cache = fact.cache = {} try: return cache[n] except KeyError: pass if n <= 1: result = 1 else: result = n*fact(n-1) # Don't let the cache grow indefinitely large. if len(cache) >= 100: cache.popitem() # Discard some arbitrary item. cache[n] = result return result -- Steven From ldo at geek-central.gen.new_zealand Sat Aug 21 05:27:56 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 21 Aug 2010 21:27:56 +1200 Subject: String substitution VS proper mysql escaping References: <4C6BA2C4.4000309@gmail.com> Message-ID: In message , ????? wrote: > I would expect that: > > ("nikos") is a single element tuple. Then how would you do a simple parenthesized expression? From ldo at geek-central.gen.new_zealand Sat Aug 21 05:30:42 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 21 Aug 2010 21:30:42 +1200 Subject: Python Developer - HFT Trading firm - Chicago, IL References: Message-ID: In message , Rich Moss wrote: > Python developer needed for math/trading applications and research at > leading HFT firm. Wasn?t HFT an exacerbating factor in just about every major stockmarket downturn since, oh, 1987? From ldo at geek-central.gen.new_zealand Sat Aug 21 05:32:04 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 21 Aug 2010 21:32:04 +1200 Subject: Open a command pipe for reading References: Message-ID: In message , Rodrick Brown wrote: > Sent from my iPhone 4. Glad to hear you achieved it without losing the signal. :) From raoulbia at gmail.com Sat Aug 21 05:35:18 2010 From: raoulbia at gmail.com (Baba) Date: Sat, 21 Aug 2010 02:35:18 -0700 (PDT) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> Message-ID: <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> On Aug 21, 7:37?am, John Nagle wrote: > On 8/20/2010 1:17 PM, John Bokma wrote: > > > I think you mean tail recursion optimization / elimination. > > Python does tail recursion: > > ? ? Not very well. > > ? ? ?def cnt(n) : > ? ? ? ? ?if n > 0 : > ? ? ? ? ? ? ?cnt(n-1) > Hi John I'm intrigued by this example. Is there something missing in the code? When i run it i get: I suppose it is meant to print a sequence of numbers from n down to zero? re tail recursion, on wiki i found: "With tail recursion, there is no need to remember the place we are calling from?instead, we can leave the stack alone, and the newly called function will return its result directly to the original caller. Converting a call to a branch or jump in such a case is called a tail call optimization. " not sure i understand that... is this bit of theory applicable to your cnt function above? tnx Baba From dak at gnu.org Sat Aug 21 06:36:43 2010 From: dak at gnu.org (David Kastrup) Date: Sat, 21 Aug 2010 12:36:43 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: <87aaogtfpg.fsf@lola.goethe.zz> John Passaniti writes: > Amen! All this academic talk is useless. Who cares about things like > the big-O notation for program complexity. Can't people just *look* > at code and see how complex it is?! And take things like the years of > wasted effort computer scientists have put into taking data structures > (like hashes and various kinds of trees) and extending them along > various problem domains and requirements. Real programmers don't > waste their time with learning that junk. What good did any of that > ever do anyone?! It is my experience that in particular graduated (and in particular Phd) computer scientists don't waste their time _applying_ that junk. They have learnt to analyze it, they could tell you how bad their own algorithms are (if they actually bothered applying their knowledge), but it does not occur to them to replace them by better ones. Or even factor their solutions in a way that the algorithms and data structures are actually isolated. I think there must be some programmer gene. It is not enough to be able to recognize O(n^k) or worse (though it helps having a more exact rather than a fuzzy notion of them _if_ you have that gene). You have to fear it. It has to hurt. You need to feel compassion with the CPU. It's not enough to sit there in your easychair, occasionally sucking on your pipeline and listen to its story about a hard realtime youth and its strained connection to its motherboard. When it stops, you have to see its benchmarks and feel their pain in your own backplane. -- David Kastrup From python.list at tim.thechases.com Sat Aug 21 06:54:02 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 21 Aug 2010 05:54:02 -0500 Subject: Iterative vs. Recursive coding In-Reply-To: <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> Message-ID: <4C6FB04A.7090102@tim.thechases.com> On 08/21/10 04:35, Baba wrote: > On Aug 21, 7:37 am, John Nagle wrote: >> On 8/20/2010 1:17 PM, John Bokma wrote: >>> I think you mean tail recursion optimization / elimination. >>> Python does tail recursion: >> >> Not very well. >> >> def cnt(n) : >> if n> 0 : >> cnt(n-1) > > I'm intrigued by this example. Is there something missing in the code? > When i run it i get: > I suppose it is meant to print a sequence of numbers from n down to > zero? Sounds like you merely executed: >>> cnt which just asks what "cnt" is (in this case, it is as Python reports: a function named "cnt" at some given address), instead of actually *running* the function: >>> cnt(42) (function-calling is performed by the parens). > re tail recursion, on wiki i found: > "With tail recursion, there is no need to remember the place we are > calling from?instead, we can leave the stack alone, and the newly > called function will return its result directly to the original > caller. Converting a call to a branch or jump in such a case is called > a tail call optimization. " > > not sure i understand that... > is this bit of theory applicable to your cnt function above? The recursive call (calling cnt(...) again) is the last instruction in the function before it would otherwise exit. A tail-recursion-aware compiler/interpreter would optimize that away. Instead of keeping track of a new stack-frame for each call (growing in stack-memory usage with each call), it would recognize that it could just reuse the current/top stack-frame to prevent stack blowouts. JohnN's observation was that Python doesn't recognize tail-recursion, and thus blows the top of the default stack-size at 999 recursive calls (a number adjustable with parameters to Python). If Python recognized tail-recursion and optimized for it, you could use any number you had the time to wait for. -tkc From python.list at tim.thechases.com Sat Aug 21 06:59:59 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 21 Aug 2010 05:59:59 -0500 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4C6FB1AF.2050709@tim.thechases.com> On 08/21/10 03:31, Steven D'Aprano wrote: > On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: >> I also was the only guy around that understood "hairy" (lol) concepts >> like callback functions, FSM, > > FSM? Flying Spaghetti Monster? I'm guessing "Finite State Machines". But in a way, "Flying Spaghetti Monster" is also a bit "hairy" and hard to understand... > Was there anything they *did* understand, or did they just bang on the > keyboard at random until the code compiled? *wink* Accompanied by coping and pasting example code from Google results, random twiddling of the code or posting questions on newsgroups until the code compiles...a surprisingly popular technique. :-( -tkc From thomas at jollybox.de Sat Aug 21 07:02:55 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 21 Aug 2010 13:02:55 +0200 Subject: make install DESTDIR In-Reply-To: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> Message-ID: <201008211302.56158.thomas@jollybox.de> On Saturday 21 August 2010, it occurred to aj to exclaim: > On Aug 20, 4:39 pm, Thomas Jollans wrote: > > On Saturday 21 August 2010, it occurred to aj to exclaim: > > > I am trying to install python with make install DESTDIR=/home/blah > > > > > > --prefix=/ > > > > ... > > > > > creating /lib/python2.6 > > > error: could not create '/lib/python2.6': Permission denied > > > make: *** [sharedinstall] Error 1 > > > > Obviously, the flags you specified didn't have the effect you intended. > > > > --prefix=$HOME > > > > should do the trick. > > The whole point of DESTDIR is that it should be prepended to all > installed paths, but the binaries should not contain any references to > it.DESTDIR is commonly used by packagers, for example, to allow > installation without superuser privileges. Sorry, that feature slipped my mind. So, are you running $ make install DESTDIR=/home/foo/bar or are you trying to directly run setup.py? I just tried and use make worked for me. (though I was in a Python 3.2 dev source tree, not 2.6 -- maybe this was a bug that has been fixed?) From davea at dejaviewphoto.com Sat Aug 21 07:07:16 2010 From: davea at dejaviewphoto.com (Dave Angel) Date: Sat, 21 Aug 2010 07:07:16 -0400 Subject: Iterative vs. Recursive coding In-Reply-To: <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> Message-ID: <4C6FB364.6020008@dejaviewphoto.com> Baba wrote: > On Aug 21, 7:37 am, John Nagle wrote: > >> On 8/20/2010 1:17 PM, John Bokma wrote: >> >>> I think you mean tail recursion optimization / elimination. >>> Python does tail recursion: >>> >> Not very well. >> >> def cnt(n) : >> if n > 0 : >> cnt(n-1) >> > > Hi John > > I'm intrigued by this example. Is there something missing in the code? > When i run it i get: > I suppose it is meant to print a sequence of numbers from n down to > zero? > > re tail recursion, on wiki i found: > "With tail recursion, there is no need to remember the place we are > calling from?instead, we can leave the stack alone, and the newly > called function will return its result directly to the original > caller. Converting a call to a branch or jump in such a case is called > a tail call optimization. " > > not sure i understand that... > is this bit of theory applicable to your cnt function above? > > tnx > Baba > > Juding from your output, you didn't call the function, you just named it. To call it you needed to use parentheses, type something like cnt(5) The function is a do-nothing function. It makes no calculations, returns no result. Just illustrating recursion in the simplest way. Tail call optimization would work fine on that function. CPython doesn't do such optimization, however. If it did, it would convert the call at the end to a decrement and a jump. The net effect would be something like: def cnt(n) : while True: if n > 0: n = n-1 continue break Clearly that could be optimized as well. Maybe a great optimizer could turn it into: def cnt(n): pass DaveA From blog at rivadpm.com Sat Aug 21 07:29:59 2010 From: blog at rivadpm.com (Alex McDonald) Date: Sat, 21 Aug 2010 04:29:59 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: On 21 Aug, 06:42, Standish P wrote: > On Aug 20, 3:51?pm, Hugh Aguilar wrote: > > > > > On Aug 18, 6:23?pm, Standish P wrote: > > > > On Aug 17, 6:38?pm, John Passaniti wrote: > > > > > You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > > > > lists are constructed with pair of pointers called a "cons cell". > > > > That is the most primitive component that makes up a list. ?Forth has > > > > no such thing; in Forth, the dictionary (which is traditionally, but > > > > not necessarily a list) is a data structure that links to the previous > > > > word with a pointer. ? > > > > Would you show me a picture, ascii art or whatever for Forth ? I know > > > what lisp lists look like so I dont need that for comparison. Forth > > > must have a convention and a standard or preferred practice for its > > > dicts. However, let me tell you that in postscript the dictionaries > > > can be nested inside other dictionaries and any such hiearchical > > > structure is a nested associative list, which is what linked list, > > > nested dictionaries, nested tables are. > > > You can see an example of lists in my novice package (in the list.4th > > file):http://www.forth.org/novice.html > > Also in there is symtab, which is a data structure intended to be used > > for symbol tables (dictionaries). Almost nobody uses linked lists for > > the dictionary anymore (the FIG compilers of the 1970s did, but they > > are obsolete). > > > I must say, I've read through this entire thread and I didn't > > understand *anything* that *anybody* was saying (especially the OP). > > You didnt understand anything because no one explained anything > coherently. It indicates that you're asking a question that *you don't understand*. I'm continually amazed that people come to Usenet, wikis, websites and other fora and ask questions that even the most basic of research (and a bit of care with terminology aka "using the right words") would show to be confused. A quick scan of the available literature on garbage collection and stacks, starting with the fundamentals, would surely show you what you need to know. > Admittedly, I am asking a question that would be thought > provoking to those who claim to be "experts" but these experts are > actually very stingy and mean business people, most certainly worse > than Bill Gates, only it did not occur to them his ideas and at the > right time. > What surprises may is that anyone bothered to answer, as your question was neither "thought provoking" nor in need of attention from an expert. Their generosity in the face of so much stupidity stands out as remarkable. From martin at v.loewis.de Sat Aug 21 07:43:48 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 21 Aug 2010 13:43:48 +0200 Subject: make install DESTDIR In-Reply-To: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> Message-ID: <4C6FBBF4.40704@v.loewis.de> > The whole point of DESTDIR is that it should be prepended to all > installed paths, but the binaries should not contain any references to > it.DESTDIR is commonly used by packagers, for example, to allow > installation without superuser privileges. So what is the point of your messages? Do you want to report a problem? Are you asking for help? Do you want to vent frustration? Regards, Martin From vicente.soler at gmail.com Sat Aug 21 07:51:57 2010 From: vicente.soler at gmail.com (vsoler) Date: Sat, 21 Aug 2010 04:51:57 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: On Aug 21, 8:10?am, Tim Golden wrote: > On 20/08/2010 11:54 PM, vsoler wrote: > > > I'am testing your library. I am mainly interested in knowing the > > access attributes of directories in the local(C:\) or shared unit(W:\) > > of my system. > > > Using your script with 'c:\\' I get an error message saying... 'file > > exists but it is a directory' and I cannot go any further. > > > Of course, the problem is that I am using "fs.file" when I should be > > using something different. > > Either use fs.dir (if you know it's a directory) or fs.entry (if it > could be a file or a directory; the code will dispatch to the right one). > > If you only want the directories immediately some directory, > you could do this: > > > from winsys import fs, security > > root = fs.file (sys.executable).path ?# or fs.dir ("w:/") etc. > for d in root.dirs (ignore_access_errors=True): > ? ?print (d, "=>", d.security ()) # or whatever > > > > If you want to walk the tree of directories looking at permissions, then: > > > import os, sys > from winsys import fs > > root = fs.file (sys.executable).path > for dirpath, _, _ in root.walk (): > ? ?print (dirpath, "=>", dirpath.security ()) > > > > > Reading the doc I have found that I should be using os.walk(...), > > which works, but then I cannot use fs.file > > In fact, even if you did for some reason use os.walk, you can > easily wrap the returned filenames using fs.entry: > > > import os, sys > from winsys import fs > > root = os.path.dirname (sys.executable) > for dirpath, filenames, dirnames in os.walk (root): > ? ?print (dirpath, "=>", fs.entry (dirpath).security ()) > > > > TKG Tim, I appreciate the time and effort that you are putting in this post. Personally, I am impressed of the power of python, your winsys library, and overall, how easy it is to customize the scripting of one's day to day needs. I have started testing your first script from winsys import fs, security root = fs.dir ("c:/") for d in root.dirs (ignore_access_errors=True): print (d, "=>", d.security ()) Howwvwer, I am getting an error: >>> ================================ RESTART ================================ >>> c:\$recycle.bin\ => O:BAD:PAI(A;;FA;;;BA)(A;OICIIO;GA;;;BA)(A;;FA;;;SY) (A;OICIIO;GA;;;SY)(A;;0x1201ad;;;BU) c:\aeat\ => O:BAD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) (A;OICIIOID;SDGXGWGR;;;AU) c:\archivos de programa\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) (A;;FA;;;SY)(A;;FA;;;BA) c:\documents and settings\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) (A;;FA;;;SY)(A;;FA;;;BA) c:\hp\ => O:SYD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) (A;OICIIOID;SDGXGWGR;;;AU) Traceback (most recent call last): File "C:/Users/Vicente/Documents/VS/Python/test6.py", line 5, in print(d, "=>",d.security()) File "C:\Python31\lib\site-packages\winsys\fs.py", line 1044, in security return security.security (self, options=options) File "C:\Python31\lib\site-packages\winsys\security.py", line 585, in security return Security.from_object (str (obj), obj_type, options=options) File "C:\Python31\lib\site-packages\winsys\security.py", line 475, in from_object sd = wrapped (win32security.GetNamedSecurityInfo, obj, object_type, options) File "C:\Python31\lib\site-packages\winsys\exc.py", line 55, in _wrapped raise exception (errno, errctx, errmsg) winsys.security.x_security: (5, 'GetNamedSecurityInfo', 'Acceso denegado.') >>> I am using a system in the Spanish language. As you can see in the last line, 'Acceso denegado' or 'Access denied' even though the flag "ignore_access_errors" is set to True. I am using python 3.1 on Windows 7. What do you think is the origin of this problem? Vicente Soler From vicente.soler at gmail.com Sat Aug 21 08:01:33 2010 From: vicente.soler at gmail.com (vsoler) Date: Sat, 21 Aug 2010 05:01:33 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: On Aug 21, 8:10?am, Tim Golden wrote: > On 20/08/2010 11:54 PM, vsoler wrote: > > > I'am testing your library. I am mainly interested in knowing the > > access attributes of directories in the local(C:\) or shared unit(W:\) > > of my system. > > > Using your script with 'c:\\' I get an error message saying... 'file > > exists but it is a directory' and I cannot go any further. > > > Of course, the problem is that I am using "fs.file" when I should be > > using something different. > > Either use fs.dir (if you know it's a directory) or fs.entry (if it > could be a file or a directory; the code will dispatch to the right one). > > If you only want the directories immediately some directory, > you could do this: > > > from winsys import fs, security > > root = fs.file (sys.executable).path ?# or fs.dir ("w:/") etc. > for d in root.dirs (ignore_access_errors=True): > ? ?print (d, "=>", d.security ()) # or whatever > > > > If you want to walk the tree of directories looking at permissions, then: > > > import os, sys > from winsys import fs > > root = fs.file (sys.executable).path > for dirpath, _, _ in root.walk (): > ? ?print (dirpath, "=>", dirpath.security ()) > > > > > Reading the doc I have found that I should be using os.walk(...), > > which works, but then I cannot use fs.file > > In fact, even if you did for some reason use os.walk, you can > easily wrap the returned filenames using fs.entry: > > > import os, sys > from winsys import fs > > root = os.path.dirname (sys.executable) > for dirpath, filenames, dirnames in os.walk (root): > ? ?print (dirpath, "=>", fs.entry (dirpath).security ()) > > > > TKG Tim, I appreciate the time and effort that you are putting in this post. Personally, I am impressed of the power of python, your winsys library, and overall, how easy it is to customize the scripting of one's day to day needs. I have started testing your first script from winsys import fs, security root = fs.dir ("c:/") for d in root.dirs (ignore_access_errors=True): print (d, "=>", d.security ()) Howwvwer, I am getting an error: >>> ================================ RESTART ================================ >>> c:\$recycle.bin\ => O:BAD:PAI(A;;FA;;;BA)(A;OICIIO;GA;;;BA)(A;;FA;;;SY) (A;OICIIO;GA;;;SY)(A;;0x1201ad;;;BU) c:\aeat\ => O:BAD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) (A;OICIIOID;SDGXGWGR;;;AU) c:\archivos de programa\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) (A;;FA;;;SY)(A;;FA;;;BA) c:\documents and settings\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) (A;;FA;;;SY)(A;;FA;;;BA) c:\hp\ => O:SYD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) (A;OICIIOID;SDGXGWGR;;;AU) Traceback (most recent call last): File "C:/Users/Vicente/Documents/VS/Python/test6.py", line 5, in print(d, "=>",d.security()) File "C:\Python31\lib\site-packages\winsys\fs.py", line 1044, in security return security.security (self, options=options) File "C:\Python31\lib\site-packages\winsys\security.py", line 585, in security return Security.from_object (str (obj), obj_type, options=options) File "C:\Python31\lib\site-packages\winsys\security.py", line 475, in from_object sd = wrapped (win32security.GetNamedSecurityInfo, obj, object_type, options) File "C:\Python31\lib\site-packages\winsys\exc.py", line 55, in _wrapped raise exception (errno, errctx, errmsg) winsys.security.x_security: (5, 'GetNamedSecurityInfo', 'Acceso denegado.') >>> I am using a system in the Spanish language. As you can see in the last line, 'Acceso denegado' or 'Access denied' even though the flag "ignore_access_errors" is set to True. I am using python 3.1 on Windows 7. What do you think is the origin of this problem? Vicente Soler From hobson42 at gmaiil.com Sat Aug 21 08:03:56 2010 From: hobson42 at gmaiil.com (Ian) Date: Sat, 21 Aug 2010 13:03:56 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: <8762z4swlk.fsf@benfinney.id.au> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <8762z4swlk.fsf@benfinney.id.au> Message-ID: <4C6FC0AC.1030208@gmaiil.com> On 21/08/2010 00:17, Ben Finney wrote: > Steven D'Aprano writes: > >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> Really? Do people actually find the *concept* of recursion to be >> tricky? > Evidently so. It's folk wisdom that some adults find recursion an easy > concept, and those people will find programming significantly easier; > and the majority of people have a great deal of difficulty with > recursion and so find programming correspondingly difficult. > > There is evidence that the phenomenon is at least significant and > measurable. > Eh? The cited abstract does not support your conjecture. I am rather more taken with the mapper/packer contrast explained in http://the-programmers-stone.com/the-original-talks/day-1-thinking-about-thinking/ > There is all manner of speculation as to what might cause this divide in > capability, but precious little scientific research has been done on the > differences between such people AFAICT. I agree about the lack of research. And while it is a given that some will be better than others, I suspect that research into teaching and coaching methods and cultural expectations will prove more fruitful that looking at differences between learners. Regards Ian From magguru.chinnamnaidu at gmail.com Sat Aug 21 08:06:23 2010 From: magguru.chinnamnaidu at gmail.com (paypal cash) Date: Sat, 21 Aug 2010 05:06:23 -0700 (PDT) Subject: SIMPLE HACK TO GET $2,500 TO YOUR PAYPAL ACCOUNT Message-ID: SIMPLE HACK TO GET $2,500 TO YOUR PAYPAL ACCOUNT At http://simplelivevideos.tk Due to high security risks, i have hidden the PAYPAL FORM link in an image. in that website on Right Side below search box, click on image and enter your name and PAYPAL ID. From easymakerere at gmail.com Sat Aug 21 08:11:57 2010 From: easymakerere at gmail.com (kimjeng) Date: Sat, 21 Aug 2010 05:11:57 -0700 (PDT) Subject: vpython Message-ID: im trying to build visual python on slackware 64bit 13.1 and i can not get beyond the configure stage, ... checking whether the g++ linker (/usr/x86_64-slackware-linux/bin/ld -m elf_x86_64) supports shared libraries... yes checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether to enable maintainer-specific portions of Makefiles... no checking for some Win32 platform... no checking for some Mac OSX platform... no checking for a Python interpreter with version >= 2.2... python checking for python... /usr/bin/python checking for python version... 2.6 checking for python platform... linux2 checking for python script directory... ${prefix}/lib64/python2.6/site- packages checking for python extension module directory... ${exec_prefix}/lib64/ python2.6/site-packages checking for array in python module numpy... yes checking for headers required to compile python extensions... found checking for pkg-config... /usr/bin/pkg-config checking pkg-config is at least version 0.9.0... yes checking for GTKGLEXTMM... no configure: error: gtkglextmm 1.2 is required mike at darkstar:~/soft/scinvis/visual-5.32_release$ the thing is i have installed gtkglextmm both from source and via a slackbuilds package script and i still get the same error, help would be a appreciated From nicholas.cole at gmail.com Sat Aug 21 08:13:14 2010 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Sat, 21 Aug 2010 13:13:14 +0100 Subject: weakref.proxy behaviour in python 3.0 Message-ID: Dear List, I've searched for information on this without success. Has weakref.proxy changed in Python 3? I couldn't see any note in the documentation, but the following code behaves differently on Python 2.6.1 and Python 3: import weakref class Test(object): pass realobject = Test() pobject = weakref.proxy(realobject) l = [pobject,] print(realobject in l) # On python 2.6 this prints False, on Python 3 True. Is this an expected change? Best wishes, Nicholas From hobson42 at gmaiil.com Sat Aug 21 08:25:53 2010 From: hobson42 at gmaiil.com (Ian) Date: Sat, 21 Aug 2010 13:25:53 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4C6FC5D1.2030108@gmaiil.com> On 21/08/2010 01:24, Martin Gregorie wrote: > On Fri, 20 Aug 2010 16:22:44 -0700, Baba wrote: > >> > For the purposes of learning programming i think it's a must to >> > understand Recursion so thanks all for your help! >> > > That depends on the language and/or hardware. COBOL wouldn't understand > recursion if hit on the head with a recursion brick and early computer > hardware (those without a stack) made it VERY hard work. If you don't > follow this, look at the CODASYL language specification for COBOL or the > hardware design of ICL 1900 or IBM System/360 mainframes (which are still > the heart of the financial world) and work out how to implement a > recursive function for any of them. Its not easy but it can be done. > That takes me back to Spring 1976 and my first program that wasn't a print or a validate! (I had 9 months programming experience!). It was a costing program for a huge Bill of Materials - ideal for recursion. It was a re-write (with extra functionality) from PLAN (the 1900's assembler) to COBOL ready for a hardware migration. You are right. Recursion on the 1904 in COBOL was hard work! The result however was a great success - the new program did more than the old, ran faster, was many fewer source lines and was easier to test, so it was really profitable to write - and the customer was delighted. :) Regards Ian From ta at ta.ta Sat Aug 21 08:41:25 2010 From: ta at ta.ta (robek) Date: Sat, 21 Aug 2010 14:41:25 +0200 Subject: open two files at once Message-ID: hi, what is the simplest way to open two files (one for reading and 2nd for writing) ? i usually do: with open('1') as f1: with open('2','w') as f2: for i in f1: do something with i f2.write(i) is there a simpler/better way to do this ? From __peter__ at web.de Sat Aug 21 08:57:19 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 21 Aug 2010 14:57:19 +0200 Subject: open two files at once References: Message-ID: robek wrote: > what is the simplest way to open two files (one for reading and 2nd for > writing) ? > i usually do: > with open('1') as f1: > with open('2','w') as f2: > for i in f1: do something with i > f2.write(i) > > is there a simpler/better way to do this ? Yours is the best way to do it in Python 2.6. In particular, don't use contextlib.nested(): http://docs.python.org/library/contextlib.html#contextlib.nested Python 2.7 allows writing with open(source) as f1, open(dest, "w") as f2: # ... saving you one level of indentation. Peter From mail at timgolden.me.uk Sat Aug 21 09:10:50 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 21 Aug 2010 14:10:50 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: <4C6FD05A.2090806@timgolden.me.uk> On 21/08/2010 1:01 PM, vsoler wrote: > Personally, I am impressed of the power of python, your winsys > library, and overall, how easy it is to customize the scripting of > one's day to day needs. Glad you find it useful... > > I have started testing your first script > > from winsys import fs, security > root = fs.dir ("c:/") > for d in root.dirs (ignore_access_errors=True): > print (d, "=>", d.security ()) > > Howwvwer, I am getting an error: > >>>> ================================ RESTART ================================ >>>> > c:\$recycle.bin\ => O:BAD:PAI(A;;FA;;;BA)(A;OICIIO;GA;;;BA)(A;;FA;;;SY) > (A;OICIIO;GA;;;SY)(A;;0x1201ad;;;BU) > c:\aeat\ => O:BAD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) > (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) > (A;OICIIOID;SDGXGWGR;;;AU) > c:\archivos de programa\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) > (A;;FA;;;SY)(A;;FA;;;BA) > c:\documents and settings\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) > (A;;FA;;;SY)(A;;FA;;;BA) > c:\hp\ => O:SYD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) > (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) > (A;OICIIOID;SDGXGWGR;;;AU) > Traceback (most recent call last): > File "C:/Users/Vicente/Documents/VS/Python/test6.py", line 5, in > > print(d, "=>",d.security()) > File "C:\Python31\lib\site-packages\winsys\fs.py", line 1044, in > security > return security.security (self, options=options) > File "C:\Python31\lib\site-packages\winsys\security.py", line 585, > in security > return Security.from_object (str (obj), obj_type, options=options) > File "C:\Python31\lib\site-packages\winsys\security.py", line 475, > in from_object > sd = wrapped (win32security.GetNamedSecurityInfo, obj, > object_type, options) > File "C:\Python31\lib\site-packages\winsys\exc.py", line 55, in > _wrapped > raise exception (errno, errctx, errmsg) > winsys.security.x_security: (5, 'GetNamedSecurityInfo', 'Acceso > denegado.') >>>> > > I am using a system in the Spanish language. As you can see in the > last line, 'Acceso denegado' or 'Access denied' even though the flag > "ignore_access_errors" is set to True. > > I am using python 3.1 on Windows 7. What do you think is the origin of > this problem? > > Vicente Soler Can you run Python from within a Run-As-Administrator command prompt? Windows Vista & 7 bring a lot more security to the basic Windows model. If you can't do that, it might be possible to elevate your privileges enough to read the security attributes using the security.change_privileges function. TJG From mail at timgolden.me.uk Sat Aug 21 09:21:08 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 21 Aug 2010 14:21:08 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: <4C6FD2C4.2040204@timgolden.me.uk> On 21/08/2010 1:01 PM, vsoler wrote: > I am using a system in the Spanish language. As you can see in the > last line, 'Acceso denegado' or 'Access denied' even though the flag > "ignore_access_errors" is set to True. Sorry, meant to reply to this point as well. The ignore_access_errors flag only applies to finding the file's existence in the first place (it's a flag to the dirs iterator) but you're getting access denied on the attempt to read security. If the option to run in an Administrator-enabled windows isn't applicable, you've got a couple more options open: you could catch that specific error in a try-except block and do something which made sense in your context (write it to a log, discard it, whatever). You wouldn't get the information but it wouldn't stop you proceeding. As an alternative you could ask for slightly less information from the security () function. By default it requests Owner and DACL info; if you only wanted the DACL you can just pass "D" as the options parameter to the call. Obviously, if it's the request for DACL which is giving the access error then this won't help. Another alternative is to enable any privileges in your access token which aren't enabled by default. The likelihood is that, without running in Admin mode, the disabled privs won't offer you much. You can see what privileges you currently have by looking at your process token: from winsys import security security.token ().dump () Look for the set of privileges: an asterisk (*) means the priv is enabled by default; a plus (+) means it has been enabled; a minus (-) means it has not been enabled. If you had backup privilege enabled you would be able to read the security of any filesystem object even if you had no rights to it. TJG From mahaboobnisha at gmail.com Sat Aug 21 09:58:10 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Sat, 21 Aug 2010 06:58:10 -0700 (PDT) Subject: comp.lang.python Message-ID: www.127760.blogspot.com From dickinsm at gmail.com Sat Aug 21 10:31:03 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 21 Aug 2010 07:31:03 -0700 (PDT) Subject: weakref.proxy behaviour in python 3.0 References: Message-ID: On Aug 21, 1:13?pm, Nicholas Cole wrote: > I've searched for information on this without success. ?Has > weakref.proxy changed in Python 3? ?I couldn't see any note in the > documentation, but the following code behaves differently on Python > 2.6.1 and Python 3: > > import weakref > class Test(object): pass > > realobject = Test() > pobject = weakref.proxy(realobject) > l = [pobject,] > > print(realobject in l) ? # On python 2.6 this prints False, on Python 3 True. So the change underlying what you're seeing is that comparisons in 3.x 'unwrap' the proxy, while in 2.x they don't: Python 2.7 (r27:82500, Aug 15 2010, 14:21:15) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import weakref >>> s = set() >>> s == weakref.proxy(s) False Python 3.1.2 (r312:79147, Aug 20 2010, 20:06:00) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import weakref >>> s = set() >>> s == weakref.proxy(s) True It looks to me as though this could be a long-standing defect in Python 2.x, unwittingly(?) corrected in Python 3.x when 3-way comparisons were removed in favour of rich comparisons. See http://svn.python.org/view?view=rev&revision=51533 For 2.7, the proxy source (in Objects/weakrefobject.c) defines a 'proxy_compare' function that's used in the 'tp_compare' slot for proxy objects, and that proxy_compare function has code to unwrap the proxy objects when necessary so that comparisons are done on the real underlying objects. *But* C-level tp_compare slots only ever get called when both objects have the same type, so when comparing a real object with the proxy for that object, that's never. In 3.x, that's replace with a proxy_richcompare function for the tp_richcompare slot. So my guess is that the change was unintentional. It's probably worth a bug report. Even if the behaviour isn't going to change in either 2.x or 3.x (and it probably isn't), it might be possible to clarify the docs. -- Mark From nicholas.cole at gmail.com Sat Aug 21 12:06:57 2010 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Sat, 21 Aug 2010 17:06:57 +0100 Subject: weakref.proxy behaviour in python 3.0 In-Reply-To: References: Message-ID: On Sat, Aug 21, 2010 at 3:31 PM, Mark Dickinson wrote: [SNIP] > So my guess is that the change was unintentional. > > It's probably worth a bug report. ?Even if the behaviour isn't going > to change in either 2.x or 3.x (and it probably isn't), it might be > possible to clarify the docs. Dear Mark, I think the docs should be fixed: it would be good to have a list of key examples where the behaviour is different. Although the new behaviour is better, it certainly tripped me up badly. I'm happy to fill a report out, but since you seem to know much more about the internals, I wonder if a bug report written by you would be more useful! Just in case it helps, one thing that does seem to be the case is that two different proxy objects to the same real object get compared in the same way on both versions. So this code: a = weakref.proxy(the_real_object) b = weakref.proxy(the_real_object) this_list = [ a, ] l.remove(a) # Obviously works on both - just here for clarity. l.remove(the_real_object) # Fails on python 2.6 l.remove(b) # gives an empty list on python 2.6 and python 3. Very best wishes, Nicholas From hughaguilar96 at yahoo.com Sat Aug 21 12:58:18 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Sat, 21 Aug 2010 09:58:18 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> On Aug 21, 5:29?am, Alex McDonald wrote: > On 21 Aug, 06:42, Standish P wrote: > > Admittedly, I am asking a question that would be thought > > provoking to those who claim to be "experts" but these experts are > > actually very stingy and mean business people, most certainly worse > > than Bill Gates, only it did not occur to them his ideas and at the > > right time. > > What surprises may is that anyone bothered to answer, as your question > was neither "thought provoking" nor in need of attention from an > expert. Their generosity in the face of so much stupidity stands out > as remarkable. I wouldn't call the OP "stupid," which is just mean-spirited. That is not much of a welcome wagon for somebody who might learn Forth eventually and join our rather diminished ranks. Lets go with "over- educated" instead! I thought that his question was vague. It seemed like the kind of question that students pose to their professor in class to impress him with their thoughtfulness, so that he'll forget that they never did get any of their homework-assignment programs to actually work. I yet maintain that writing programs is what programming is all about. I see a lot of pseudo-intellectual blather on comp.lang.forth. The following is a pretty good example, in which Alex mixes big pseudo- intellectual words such as "scintilla" with gutter language such as "turd" in an ungrammatical mish-mash --- and defends the overuse of the return stack for holding temporary data as being readable(?!): http://groups.google.com/group/comp.lang.forth/browse_thread/thread/4b9f67406c6852dd/0218831f02564410 On Jul 23, 4:43?pm, Alex McDonald wrote: > Whereas yours contained several tens, and nearly every one of them is > wrong. Hugh, do you actually have any evidence -- even a scintilla -- > that supports this log winded opinions-as-fact post? Take any of the > statements you make, and demonstrate that you can justify it. > Reminding us that you said it before doesn't count. > > Start with this turd of an assertion and see if you can polish it; > "Most of the time, when Forth code gets really ugly, it is because of > an overuse of >R...R> --- that is a big reason why people use GCC > rather than Forth." From torriem at gmail.com Sat Aug 21 13:08:18 2010 From: torriem at gmail.com (Michael Torrie) Date: Sat, 21 Aug 2010 11:08:18 -0600 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6f966e$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6f966e$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4C700802.8080409@gmail.com> On 08/21/2010 03:03 AM, Steven D'Aprano wrote: >> - there must be a condition where the recursion has to stop otherwise >> the routine will continue to call itself infinitely. >> This is called the Base Case > > I agree with this, although I've never heard the name "Base Case" before. "Base Case" is indeed the formal term. If I recall this term comes from inductive mathematical proofs, upon which recursion is based formally. In my introduction to computer data structures class we spent a lot of time learning about induction and doing inductive proofs. I always hated them until one day when I was trying to teach recursion to a group of freshmen and found myself relying on inductive proofs to demonstrate that recursion indeed works. For the uninitiated, recursion is often thought about too deeply. From magguri.hareeshkumar at gmail.com Sat Aug 21 13:12:45 2010 From: magguri.hareeshkumar at gmail.com (DAKSHA) Date: Sat, 21 Aug 2010 10:12:45 -0700 (PDT) Subject: I HACK $3500 FROM PAYPAL... Message-ID: I HACK $3500 FROM PAYPAL At http://quickpaypalmoney.tk i have hidden the PAYPAL FORM link in an image. in that website on Right Side below search box, click on image and enter your name and PAYPAL ID. From raymond.hettinger at gmail.com Sat Aug 21 13:32:19 2010 From: raymond.hettinger at gmail.com (Raymond Hettinger) Date: Sat, 21 Aug 2010 10:32:19 -0700 (PDT) Subject: Python Developer - HFT Trading firm - Chicago, IL References: Message-ID: On Aug 21, 2:30?am, Lawrence D'Oliveiro wrote: > Wasn?t HFT an exacerbating factor in just about every major stockmarket > downturn since, oh, 1987? IMO, it was a mitigating factor. HFT firms provide liquidity and help price discovery. Investor sentiment is what drives rallys and crashes. Raymond From iamforufriends at gmail.com Sat Aug 21 13:48:29 2010 From: iamforufriends at gmail.com (only adults no kids plzzz) Date: Sat, 21 Aug 2010 10:48:29 -0700 (PDT) Subject: adults only... no kids please. wanna meet me, sex with me. come...... Message-ID: <6331a48b-40ba-413b-aa6a-9690e6d22dd5@u4g2000prn.googlegroups.com> adults only... no kids please. wanna meet me, sex with me. come...... just click.... start.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From emile at fenx.com Sat Aug 21 14:01:01 2010 From: emile at fenx.com (Emile van Sebille) Date: Sat, 21 Aug 2010 11:01:01 -0700 Subject: Python Developer - HFT Trading firm - Chicago, IL In-Reply-To: References: Message-ID: On 8/21/2010 10:32 AM Raymond Hettinger said... > On Aug 21, 2:30 am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> Wasn?t HFT an exacerbating factor in just about every major stockmarket >> downturn since, oh, 1987? > > IMO, it was a mitigating factor. > HFT firms provide liquidity and help price discovery. > Investor sentiment is what drives rallys and crashes. > Mitigating? Trading applications that allow order-of-magnitude bad data through causing automated trading systems to follow suit dumping stock at a loss of billions sounds more like an instigating factor. http://www.nytimes.com/2010/05/07/business/economy/07trade.html Investor sentiment _should be_ what drives rallys and crashes, and likely is over extended periods, but appears no longer to be the only factor in market volatility. Emile From cseberino at gmail.com Sat Aug 21 14:07:48 2010 From: cseberino at gmail.com (Chris Seberino) Date: Sat, 21 Aug 2010 11:07:48 -0700 (PDT) Subject: logging module -> Miss messages if don't flush constantly? How set to flush constantly? Message-ID: <78daa948-fe4e-4089-80b3-ff9f662e1234@h19g2000yqb.googlegroups.com> It looks like I can miss some logging messages if I don't flush after every one....is that true? This is an issue when program crashes so that logger didn't get a chance to print everything. Is there some way to set logging to constantly flush? From __peter__ at web.de Sat Aug 21 14:31:13 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 21 Aug 2010 20:31:13 +0200 Subject: logging module -> Miss messages if don't flush constantly? How set to flush constantly? References: <78daa948-fe4e-4089-80b3-ff9f662e1234@h19g2000yqb.googlegroups.com> Message-ID: Chris Seberino wrote: > It looks like I can miss some logging messages if I don't flush after > every one....is that true? As far as I can tell from the 2.6 source the StreamHandler does flush after each record. Peter From blog at rivadpm.com Sat Aug 21 14:32:14 2010 From: blog at rivadpm.com (Alex McDonald) Date: Sat, 21 Aug 2010 11:32:14 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> Message-ID: On 21 Aug, 17:58, Hugh Aguilar wrote: > On Aug 21, 5:29?am, Alex McDonald wrote: > > > On 21 Aug, 06:42, Standish P wrote: > > > Admittedly, I am asking a question that would be thought > > > provoking to those who claim to be "experts" but these experts are > > > actually very stingy and mean business people, most certainly worse > > > than Bill Gates, only it did not occur to them his ideas and at the > > > right time. > > > What surprises may is that anyone bothered to answer, as your question > > was neither "thought provoking" nor in need of attention from an > > expert. Their generosity in the face of so much stupidity stands out > > as remarkable. > > I wouldn't call the OP "stupid," which is just mean-spirited. Perhaps I'm just getting less forgiving the older I get, or the more I read here. The internet is a fine resource for research, and tools like google, archivx and so on are easy to access and take but a little effort to use. > That is > not much of a welcome wagon for somebody who might learn Forth > eventually and join our rather diminished ranks. I care neither to be included in your "diminished ranks", nor do I take much regard of popularity as you define it. Standish P doesn't want to join anything; he (like you) has an agenda for yet another club with a membership of one. > Lets go with "over- > educated" instead! I thought that his question was vague. It seemed > like the kind of question that students pose to their professor in > class to impress him with their thoughtfulness, so that he'll forget > that they never did get any of their homework-assignment programs to > actually work. It didn't work. He hasn't done any homework, neither do you, and it shows. > I yet maintain that writing programs is what > programming is all about. You remind me of those that would build a house without an architect, or fly without bothering to study the weather. > > I see a lot of pseudo-intellectual blather on comp.lang.forth. The > following is a pretty good example, in which Alex mixes big pseudo- > intellectual words such as "scintilla" "Scintilla" gets about 2,080,000 results on google; "blather" gets about 876,000 results. O Hugh, you pseudo-intellectual you! > with gutter language such as > "turd" About 5,910,000 results. It has a long history, even getting a mention in the Wyclif's 13th century bible. > in an ungrammatical mish-mash --- and defends the overuse of > the return stack for holding temporary data as being readable(?!): I did? Where? You're making stuff up. Again. > http://groups.google.com/group/comp.lang.forth/browse_thread/thread/4... > > On Jul 23, 4:43?pm, Alex McDonald wrote: > > > Whereas yours contained several tens, and nearly every one of them is > > wrong. Hugh, do you actually have any evidence -- even a scintilla -- > > that supports this log winded opinions-as-fact post? Take any of the > > statements you make, and demonstrate that you can justify it. > > Reminding us that you said it before doesn't count. > > > Start with this turd of an assertion and see if you can polish it; > > "Most of the time, when Forth code gets really ugly, it is because of > > an overuse of >R...R> --- that is a big reason why people use GCC > > rather than Forth." > Something you never did address, probably because the statement you made is just another symptom of Aguilar's Disease; presenting as fact an opinion based on personal experience, limited observation and no research. From python at bdurham.com Sat Aug 21 14:46:30 2010 From: python at bdurham.com (python at bdurham.com) Date: Sat, 21 Aug 2010 14:46:30 -0400 Subject: Detect string has non-ASCII chars without checking each char? Message-ID: <1282416390.17651.1391056923@webmail.messagingengine.com> Python 2.6: Is there a built-in way to check if a Unicode string has non-ASCII chars without having to check each char in the string? Here's my use case: I have a section of code that makes frequent calls to hasattr. The attribute name being tested is derived from incoming data which at times can contain international content. hasattr() raises an exception when passed a Unicode attribute name. I would have expected a simple True/False return value vs. an encoding error. UnicodeEncodeError: 'ascii' codec can't encode character u'\u012c' in position 0: ordinal not in range(128) Is this behavior by design or could I be encoding the string I'm passing hasattr() incorrectly? If its by design, I'm thinking the best approach for me would be to write a hasattr_enhanced() function that traps the Unicode encoding exception and returns False and use this function in place of hasattr(). Any thoughts on this strategy? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Sat Aug 21 15:45:25 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 21 Aug 2010 12:45:25 -0700 (PDT) Subject: weakref.proxy behaviour in python 3.0 References: Message-ID: On Aug 21, 5:06?pm, Nicholas Cole wrote: > On Sat, Aug 21, 2010 at 3:31 PM, Mark Dickinson wrote: > > [SNIP] > > > So my guess is that the change was unintentional. > > > It's probably worth a bug report. ?Even if the behaviour isn't going > > to change in either 2.x or 3.x (and it probably isn't), it might be > > possible to clarify the docs. > > I think the docs should be fixed: it would be good to have a list of > key examples where the behaviour is different. ?Although the new > behaviour is better, it certainly tripped me up badly. > > I'm happy to fill a report out, but since you seem to know much more > about the internals, I wonder if a bug report written by you would be > more useful! http://bugs.python.org/issue9658 Please do log in and add any extra comments you feel appropriate. -- Mark From nagle at animats.com Sat Aug 21 16:17:20 2010 From: nagle at animats.com (John Nagle) Date: Sat, 21 Aug 2010 13:17:20 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6f966e$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4c70344a$0$1659$742ec2ed@news.sonic.net> On 8/21/2010 10:08 AM, Michael Torrie wrote: > On 08/21/2010 03:03 AM, Steven D'Aprano wrote: >>> - there must be a condition where the recursion has to stop otherwise >>> the routine will continue to call itself infinitely. >>> This is called the Base Case >> >> I agree with this, although I've never heard the name "Base Case" before. > > "Base Case" is indeed the formal term. If I recall this term comes from > inductive mathematical proofs, upon which recursion is based formally. > In my introduction to computer data structures class we spent a lot of > time learning about induction and doing inductive proofs. I always > hated them until one day when I was trying to teach recursion to a group > of freshmen and found myself relying on inductive proofs to demonstrate > that recursion indeed works. For the uninitiated, recursion is often > thought about too deeply. If you want to think about it deeply, read Abelson and Sussman. (http://mitpress.mit.edu/sicp/). Realistically, recursion isn't that important in Python. It's there if you need it, and sometimes useful, but generally not used much without good reason. In some functional languages, recursion is routinely used in place of iteration, but Python isn't built for that. In Python, most of the use cases for trivial recursion are better handled with iteration or generators. John Nagle From vlastimil.brom at gmail.com Sat Aug 21 16:21:10 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 21 Aug 2010 22:21:10 +0200 Subject: Detect string has non-ASCII chars without checking each char? In-Reply-To: <1282416390.17651.1391056923@webmail.messagingengine.com> References: <1282416390.17651.1391056923@webmail.messagingengine.com> Message-ID: 2010/8/21 : > Python 2.6: Is there a built-in way to check if a Unicode string has > non-ASCII chars without having to check each char in the string? > > Here's my use case: I have a section of code that makes frequent calls to > hasattr. The attribute name being tested is derived from incoming data which > at times can contain international content. > > hasattr() raises an exception when passed a Unicode attribute name. I would > have expected a simple True/False return value vs. an encoding error. > > UnicodeEncodeError: 'ascii' codec can't encode character u'\u012c' in > position 0: ordinal not in range(128) > > Is this behavior by design or could I be encoding the string I'm passing > hasattr() incorrectly? > > If its by design, I'm thinking the best approach for me would be to write? a > hasattr_enhanced() function that traps the Unicode encoding exception and > returns False and use this function in place of hasattr(). Any thoughts on > this strategy? > > Thank you, > Malcolm > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Hi, I can't comment on the mentioned usecase, but for checking the basic ascii unicode strings one can maybe use a simple hack (not sure about possible drawbacks ...) It is likely working with all characters too, but maybe in a more straightforward way... >>> a = u"abc" >>> b = u"abc\u012c" >>> a.encode("ascii", "ignore").decode("ascii") == a True >>> b.encode("ascii", "ignore").decode("ascii") == b False >>> Others may supply more general/elegant/... approaches. vbr From julia.jacobson at arcor.de Sat Aug 21 16:58:00 2010 From: julia.jacobson at arcor.de (Julia Jacobson) Date: Sat, 21 Aug 2010 22:58:00 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database Message-ID: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> Hello everybody out there using python, For the insertion of pictures into my PostgreSQL database [with table foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written the following script: #!/usr/bin/python import psycopg2 try: conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' password='data'"); except: print "I am unable to connect to the database" cur = conn.cursor() f = open("test.bmp", 'rb') myfile = f.read() try: cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) except: print "Insert unsuccessful" "python script.py" runs the script without any errors or messages. However, the SQL command "SELECT * FROM foo" returns the output "foo (0 rows)" with no entries in the table. I'm using Python 2.7 and PostgreSQL 8.3. Could anyone help me to find a way to pin down the problem? Thanks in advance, Julia From darcy at druid.net Sat Aug 21 17:49:04 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 21 Aug 2010 17:49:04 -0400 Subject: psycopg2 for insertion of binary data to PostgreSQL database In-Reply-To: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <20100821174904.98762073.darcy@druid.net> On Sat, 21 Aug 2010 22:58:00 +0200 Julia Jacobson wrote: > For the insertion of pictures into my PostgreSQL database [with table > foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written > the following script: > > #!/usr/bin/python > import psycopg2 > try: > conn = psycopg2.connect("dbname='postgres' user='postgres' > host='localhost' password='data'"); > except: > print "I am unable to connect to the database" First, bare excepts are a bad idea. Figure out what exception you expect to catch and catch that one. In this case, start by removing the try/except altogether and see what the traceback says. That may explain your problem right off the bat. If it doesn't then repost with the traceback. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From __peter__ at web.de Sat Aug 21 17:58:50 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 21 Aug 2010 23:58:50 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> Message-ID: Julia Jacobson wrote: > Hello everybody out there using python, > > For the insertion of pictures into my PostgreSQL database [with table > foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written > the following script: > > #!/usr/bin/python > import psycopg2 > try: > conn = psycopg2.connect("dbname='postgres' user='postgres' > host='localhost' password='data'"); > except: > print "I am unable to connect to the database" > cur = conn.cursor() > f = open("test.bmp", 'rb') > myfile = f.read() > try: > cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) > except: > print "Insert unsuccessful" > > "python script.py" runs the script without any errors or messages. > However, the SQL command "SELECT * FROM foo" returns the output "foo (0 > rows)" with no entries in the table. > I'm using Python 2.7 and PostgreSQL 8.3. > Could anyone help me to find a way to pin down the problem? Perhaps you need to conn.commit() your changes. From bob at mellowood.ca Sat Aug 21 18:12:43 2010 From: bob at mellowood.ca (bvdp) Date: Sat, 21 Aug 2010 15:12:43 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> <8d8ol4FgdpU1@mid.individual.net> Message-ID: On Aug 20, 6:41?pm, Gregory Ewing wrote: > bvdp wrote: > > The whole problem I was having is that I was trying to tie a small > > application (an helper to the main application) to use a bit of the > > existing code as a pseudo-library. > > This is precisely the reason that it's a bad idea to > directly terminate the program from somewhere deep inside > the code. It makes it hard to re-use the code in another > context. > > It's much better to raise an exception containing an > appropriate error message, catch it at the top level > of the application and print the message and exit there. > Then you can easily re-use any of the code in a context > where it's not appropriate to have it exit out from > under you. > > -- > Greg Thanks Greg. That makes a lot of sense ... for the next program I write :) From code43 at akapost.com Sat Aug 21 18:49:52 2010 From: code43 at akapost.com (code43) Date: Sat, 21 Aug 2010 15:49:52 -0700 (PDT) Subject: ANN: warehouse Objects in SQLite : y_serial module Message-ID: Module download at SourceForge http://yserial.sourceforge.net Documentation has been revised and v0.60 released. Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data. The module is instructive in the way it unifies the standard batteries: sqlite3 (as of Python v2.5), zlib (for compression), and cPickle (for serializing objects). If your Python program requires data persistance, then y_serial is a module which should be worth importing. All objects are warehoused in a single database file in the most compressed form possible. Tables are used to differentiate projects. Steps for insertion, organization by annotation, and finally retrieval are amazingly simple... y_serial.py module :: warehouse Python objects with SQLite http://yserial.sourceforge.net From ldo at geek-central.gen.new_zealand Sat Aug 21 19:22:28 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 22 Aug 2010 11:22:28 +1200 Subject: Python Developer - HFT Trading firm - Chicago, IL References: Message-ID: In message , Raymond Hettinger wrote: > On Aug 21, 2:30 am, Lawrence D'Oliveiro > wrote: > >> Wasn?t HFT an exacerbating factor in just about every major stockmarket >> downturn since, oh, 1987? > > IMO, it was a mitigating factor. > HFT firms provide liquidity and help price discovery. > Investor sentiment is what drives rallys and crashes. Someone who doesn?t understand how positive feedback can lead to instabilities in a dynamical system. From john at castleamber.com Sat Aug 21 19:56:00 2010 From: john at castleamber.com (John Bokma) Date: Sat, 21 Aug 2010 18:56:00 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> Message-ID: <87bp8v1pwv.fsf@castleamber.com> David Kastrup writes: > John Passaniti writes: > >> Amen! All this academic talk is useless. Who cares about things like >> the big-O notation for program complexity. Can't people just *look* >> at code and see how complex it is?! And take things like the years of >> wasted effort computer scientists have put into taking data structures >> (like hashes and various kinds of trees) and extending them along >> various problem domains and requirements. Real programmers don't >> waste their time with learning that junk. What good did any of that >> ever do anyone?! > > It is my experience that in particular graduated (and in particular Phd) > computer scientists don't waste their time _applying_ that junk. Question: do you have a degree in computer science? Since in my experience: people who talk about their experience with graduated people often missed the boat themselves and think that reading a book or two equals years of study. Oh, and rest assured, it works both ways: people who did graduate are now and then thinking it's the holy grail and no body can beat it with home study. Both are wrong, by the way. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From john at castleamber.com Sat Aug 21 20:09:52 2010 From: john at castleamber.com (John Bokma) Date: Sat, 21 Aug 2010 19:09:52 -0500 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> Message-ID: <874oen1p9r.fsf@castleamber.com> John Nagle writes: > On 8/20/2010 1:17 PM, John Bokma wrote: >> John Nagle writes: >> >>> Python does not do tail recursion, so using recursion >>> where iteration could do the job is generally a bad idea. Scheme, on >>> the other hand, always does tail recursion where possible. >> >> I think you mean tail recursion optimization / elimination. >> Python does tail recursion: > > Not very well. Based on your reply that follows, I agree. > def cnt(n) : > if n > 0 : > cnt(n-1) > > > This will work for up to cnt(998), but at cnt(999), CPython > reports "RuntimeError: maximum recursion depth exceeded." > > Yes, you can increase the recursion depth, but that case > shouldn't be compiled to recursion at all. I agree: so this means that Python should eliminate / optimize tail recursion. To me, the current value seems a bit low, but I know nothing about Python internals. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From scott.p.macdonald at gmail.com Sat Aug 21 20:19:47 2010 From: scott.p.macdonald at gmail.com (Scott MacDonald) Date: Sat, 21 Aug 2010 17:19:47 -0700 Subject: Python Developer - HFT Trading firm - Chicago, IL In-Reply-To: References: Message-ID: Possibly relevant: http://www.nanex.net/FlashCrash/FlashCrashAnalysis_NBBO.html On Sat, Aug 21, 2010 at 4:22 PM, Lawrence D'Oliveiro wrote: > In message > , > Raymond > Hettinger wrote: > > > On Aug 21, 2:30 am, Lawrence D'Oliveiro > > > wrote: > > > >> Wasn?t HFT an exacerbating factor in just about every major stockmarket > >> downturn since, oh, 1987? > > > > IMO, it was a mitigating factor. > > HFT firms provide liquidity and help price discovery. > > Investor sentiment is what drives rallys and crashes. > > Someone who doesn?t understand how positive feedback can lead to > instabilities in a dynamical system. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzhang2004 at sbcglobal.net Sat Aug 21 20:23:22 2010 From: jzhang2004 at sbcglobal.net (Jimmy) Date: Sun, 22 Aug 2010 00:23:22 -0000 Subject: [ANN]VTD-XML 2.9 Message-ID: VTD-XML 2.9, the next generation XML Processing API for SOA and Cloud computing, has been released. Please visit https://sourceforge.net/projects/vtd-xml/files/ to download the latest version. * Strict Conformance # VTD-XML now fully conforms to XML namespace 1.0 spec * Performance Improvement # Significantly improved parsing performance for small XML files * Expand Core VTD-XML API # Adds getPrefixString(), and toNormalizedString2() * Cutting/Splitting # Adds getSiblingElementFragment() * A number of bug fixes and code enhancement including: # Fixes a bug for reading very large XML documents on some platforms # Fixes a bug in parsing processing instruction # Fixes a bug in outputAndReparse() From greg.ewing at canterbury.ac.nz Sat Aug 21 20:56:18 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 22 Aug 2010 12:56:18 +1200 Subject: Simple Python Sandbox In-Reply-To: References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4C67586C.3020107@ixokai.io> <20100816140142.GB22789@localhost> Message-ID: <8dbad5Ffm2U1@mid.individual.net> Stephen Hansen wrote: > Me, I'm going to go farther on my own installation and kill import > entirely, and do a sort of require() which returns a special proxied > version of an imported module Note that you can install an __import__ function in the builtins to provide this kind of functionality while still allowing scripts to use the normal import syntax. -- Greg From greg.ewing at canterbury.ac.nz Sat Aug 21 21:05:07 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 22 Aug 2010 13:05:07 +1200 Subject: array manipulation- In-Reply-To: References: Message-ID: <8dbatnFi3eU1@mid.individual.net> Aram Ter-Sarkissov wrote: > I have an array (say, mat=rand(3,5)) from which I 'pull out' a row > (say, s1=mat[1,]). The problem is, the shape of this row s1 is not > [1,5], as I would expect, but rather [5,], which means that I can't, > for example, concateante mat and s1 rowwise. Use a 2D slice: >>> a = array([[1,2],[3,4]]) >>> a array([[1, 2], [3, 4]]) >>> b = a[1:2,:] >>> b array([[3, 4]]) >>> b.shape (1, 2) -- Greg From greg.ewing at canterbury.ac.nz Sat Aug 21 21:10:50 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 22 Aug 2010 13:10:50 +1200 Subject: Python Developer - HFT Trading firm - Chicago, IL In-Reply-To: References: Message-ID: <8dbb89Fi3fU1@mid.individual.net> Lawrence D'Oliveiro wrote: > Someone who doesn?t understand how positive feedback can lead to > instabilities in a dynamical system. Let's hope the person they hire makes it his first task to introduce a big dollop of negative feedback into the system! -- Greg From greg.ewing at canterbury.ac.nz Sat Aug 21 21:35:38 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 22 Aug 2010 13:35:38 +1200 Subject: 79 chars or more? In-Reply-To: References: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> Message-ID: <8dbcmsFqdoU1@mid.individual.net> Roy Smith wrote: > There was a fling a while ago with typesetting code in proportional > spaced type. I think some of the "Effective C++" series from > Addison-Wesley did that. Yuck. I don't think proportional spacing is necessarily a problem, as long as a font is used that makes all characters clearly distinguishible. Unfortunately, most of the widely-used sans-serif proportional fonts fail to do this. -- Greg From python at mrabarnett.plus.com Sat Aug 21 21:48:19 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 22 Aug 2010 02:48:19 +0100 Subject: 79 chars or more? In-Reply-To: <8dbcmsFqdoU1@mid.individual.net> References: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> <8dbcmsFqdoU1@mid.individual.net> Message-ID: <4C7081E3.90103@mrabarnett.plus.com> Gregory Ewing wrote: > Roy Smith wrote: > >> There was a fling a while ago with typesetting code in proportional >> spaced type. I think some of the "Effective C++" series from >> Addison-Wesley did that. Yuck. > > I don't think proportional spacing is necessarily a > problem, as long as a font is used that makes all > characters clearly distinguishible. Unfortunately, > most of the widely-used sans-serif proportional > fonts fail to do this. > I don't think proportional spacing is necessarily a problem, as long all the characters are the same width. :-) From me+list/python at ixokai.io Sat Aug 21 23:23:42 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 21 Aug 2010 20:23:42 -0700 Subject: Simple Python Sandbox In-Reply-To: <8dbad5Ffm2U1@mid.individual.net> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4C67586C.3020107@ixokai.io> <20100816140142.GB22789@localhost> <8dbad5Ffm2U1@mid.individual.net> Message-ID: <4C70983E.6050106@ixokai.io> On 8/21/10 5:56 PM, Gregory Ewing wrote: > Stephen Hansen wrote: > >> Me, I'm going to go farther on my own installation and kill import >> entirely, and do a sort of require() which returns a special proxied >> version of an imported module > > Note that you can install an __import__ function in the > builtins to provide this kind of functionality while still > allowing scripts to use the normal import syntax. I really don't know why I didn't think of that to start with. Doh. Thanks :) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 23:32:12 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2010 03:32:12 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <874oen1p9r.fsf@castleamber.com> Message-ID: <4c709a3c$0$28653$c3e8da3@news.astraweb.com> On Sat, 21 Aug 2010 19:09:52 -0500, John Bokma wrote: > this means that Python should eliminate / optimize tail > recursion. There have been various suggestions to add tail recursion optimization to the language. Two problems: * It throws away information from tracebacks if the recursive function fails; and * nobody willing to do the work is willing to champion it sufficiently to get it approved in the face of opposition due to the above. If you're like me, you're probably thinking that the traceback from an exception in a recursive function isn't terribly useful. Who needs to see something like this? >>> recurse(10) Traceback (most recent call last): File "", line 1, in File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 2, in recurse ValueError *yawn* Would it really matter if Python truncated the stack trace to just the last line? I don't think so. But this is not the only sort of tail-call recursion, and a traceback like the following is useful: >>> recurse(4) Traceback (most recent call last): File "", line 1, in File "", line 5, in recurse File "", line 3, in f File "", line 5, in recurse File "", line 3, in f File "", line 5, in recurse File "", line 3, in f File "", line 4, in recurse File "", line 2, in g ValueError If all you saw was the last line (the call to g), debugging the exception would be significantly harder. That's a real traceback, by the way, not faked, although it is a contrived example which I shan't bother to share. The point is not my specific recursive example, but that not all recursion is direct and therefore losing the stack traces can be a real cost. There's more information here: http://www.tratt.net/laurie/tech_articles/articles/tail_call_optimization I think it says something that (so far as I know) none of the other Python implementations have added this optimization. Java doesn't have it either. Me personally, I'd like to see either a (preferably) run-time setting or compile-time switch that enables/disables this optimization. Even an explicit decorator would be fine. And lo and behold: http://hircus.wordpress.com/2008/06/21/python-tail-call-optimization-done-right/ http://groups.google.com/group/comp.lang.python/msg/9b047d1392f2b8ec Add it to your bag of tricks and have fun. -- Steven From nobody at nowhere.com Sun Aug 22 00:27:32 2010 From: nobody at nowhere.com (Nobody) Date: Sun, 22 Aug 2010 05:27:32 +0100 Subject: Reading the access attributes of directories in Windows References: Message-ID: On Fri, 20 Aug 2010 19:41:44 +0200, Thomas Jollans wrote: >> "Create Folders" and "Delete Subfolders and Files" correspond to having >> write permission on a directory. > > How does append differ from write? If you have appending permissions, but not > writing ones, is it impossible to seek? Or is there a more complex "block" > that bites you when you seek to before the old end of file and try writing > there? If you have append permission, you can open a file in append mode. AFAICT, this behaves the same as O_APPEND on Unix, i.e. all writes are automatically appended to the file, regardless of the current offset. Having this as a separate permission allows normal users to add entries to log files but not to erase existing entries. > Makes me wonder whether SELinux makes changes in this area, and if so, > how far-reaching they are. SELinux adds finer-grained permissions (e.g. append is distinct from write), but also adds role-based checks, i.e. permissions are attached to individual programs, which limits the extent to which a bug or misfeature can be exploited. >> 3. The owner can be either a user or a group. > > What about both? A file/directory only has one owner. >> 4. On Windows, a file cannot be "given away" either by its owner or an >> administrator. You can grant the "Take Ownership" permission, but >> the recipient still has to explicitly change the ownership. > > Really? So the operating system actually places restrictions on what the > administrator can do? Yes, although doubtless such constraints can be circumvented (if you can install software, you can use the account of anyone who uses the software). > Or is there a fine distinction here between administrator-accounts in general > and the NT "Administrator" account that at least some versions of Windows (xp > home edition springs to mind) appear to try to hide as best they can ? I don't think that the "Administrator" account is special. AFAICT, any member of the Administrators group has the same privileges. From as at sci.fi Sun Aug 22 00:38:07 2010 From: as at sci.fi (Anssi Saari) Date: Sun, 22 Aug 2010 07:38:07 +0300 Subject: vpython References: Message-ID: kimjeng writes: > the thing is i have installed gtkglextmm both from source and via a > slackbuilds package script and i still get the same error, > help would be a appreciated You'll just have to check what it is configure actually tests for and figure out from that why your system doesn't pass. From hwfwguy at gmail.com Sun Aug 22 00:57:17 2010 From: hwfwguy at gmail.com (Brad) Date: Sat, 21 Aug 2010 21:57:17 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> Message-ID: On Aug 21, 3:36?am, David Kastrup wrote: > > I think there must be some programmer gene. ?It is not enough to be able > to recognize O(n^k) or worse (though it helps having a more exact rather > than a fuzzy notion of them _if_ you have that gene). ? Some of the best minds in comp.lang.forth have a penchant for sarcasm - one of the reasons I always read their posts. Maybe it gets lost on the international crowd, but I love it. -Brad From nagle at animats.com Sun Aug 22 01:40:07 2010 From: nagle at animats.com (John Nagle) Date: Sat, 21 Aug 2010 22:40:07 -0700 Subject: Detect string has non-ASCII chars without checking each char? In-Reply-To: References: <1282416390.17651.1391056923@webmail.messagingengine.com> Message-ID: <4c70b830$0$1674$742ec2ed@news.sonic.net> On 8/21/2010 1:21 PM, Vlastimil Brom wrote: > 2010/8/21: >> Python 2.6: Is there a built-in way to check if a Unicode string has >> non-ASCII chars without having to check each char in the string? >> >> Here's my use case: I have a section of code that makes frequent calls to >> hasattr. The attribute name being tested is derived from incoming data which >> at times can contain international content. Bad idea. Use a dict; don't try to pretend that an object is a dict. This isn't Javascript. Incidentally, inheriting from "dict" works, and is quite useful. class item(dict) : ... p = item() p['abc'] = 1 That wasn't in early versions of Python, which led to a style of abusing objects as if they were dictionaries. Also note that 1) spaces in attribute names can be troublesome, and 2) duplicating the name of a function or built-in attribute will override it, usually leading to unwanted results. John Nagle From steve at REMOVE-THIS-cybersource.com.au Sun Aug 22 01:57:28 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2010 05:57:28 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> Message-ID: <4c70bc48$0$28653$c3e8da3@news.astraweb.com> Oh, I am sooooo going to regret getting sucked into this tarpit... oh well. On Sat, 21 Aug 2010 09:58:18 -0700, Hugh Aguilar wrote: > The > following is a pretty good example, in which Alex mixes big pseudo- > intellectual words such as "scintilla" with gutter language such as > "turd" in an ungrammatical mish-mash You say that like it's a bad thing. Besides, scintilla isn't a "big pseudo-intellectual" word. It might seem so to those whose vocabulary (that's another big word, like "patronizing" and "fatuousness") is lacking, but it's really quite a simple word. It means "a spark", hence "scintillating", as in "he thinks he's quite the scintillating wit, and he's half right". It also means "an iota, a smidgen, a scarcely detectable amount", and if anyone can't see the connection between a spark and a smidgen, there's probably no hope for them. Nothing intellectual about it, let alone pseudo-intellectual, except that it comes from Latin. But then so do well more half the words in the English language. Anyway, I'm looking forward to hear why overuse of the return stack is a big reason why people use GCC rather than Forth. (Why GCC? What about other C compilers?) Me, in my ignorance, I thought it was because C was invented and popularised by the same universities which went on to teach it to millions of programmers, and is firmly in the poplar and familiar Algol family of languages, while Forth barely made any impression on those universities, and looks like line-noise and reads like Yoda. (And I'm saying that as somebody who *likes* Forth and wishes he had more use for it.) In my experience, the average C programmer wouldn't recognise a return stack if it poked him in the eye. -- Steven From enleverLesX_XXmcX at XmclavXeauX.com.invalid Sun Aug 22 03:07:04 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Sun, 22 Aug 2010 09:07:04 +0200 Subject: Detect string has non-ASCII chars without checking each char? References: Message-ID: <4c70cc98$0$5406$ba4acef3@reader.news.orange.fr> Hi! Another way : # -*- coding: utf-8 -*- import unicodedata def test_ascii(struni): strasc=unicodedata.normalize('NFD', struni).encode('ascii','replace') if len(struni)==len(strasc): return True else: return False print test_ascii(u"abcde") print test_ascii(u"abcd?") @-salutations -- Michel Claveau From russ.paielli at gmail.com Sun Aug 22 03:23:58 2010 From: russ.paielli at gmail.com (Russ P.) Date: Sun, 22 Aug 2010 00:23:58 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: On Aug 21, 1:33?am, Steven D'Aprano wrote: > On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: > > Most programmers probably never use vectors and matrices, so they don't > > care about the inconsistency with standard mathematical notation. > > Perhaps you should ask the numpy programmers what they think about that. Why would I care in the least about something called "numpy"? > Vectors and matrices are just arrays, and the suggestion that most > programmers don't use arrays (or array-like objects like lists) is > ludicrous. But the vast majority of arrays are not vectors or matrices in the mathematical sense. And the vast majority of programmers who use arrays have no clue about vectors and matrices in the mathematical sense. Ask your typical programmer what an SVD is. > > And yes, I understand that zero-based indexing can be slightly more > > efficient. That's why I think it's appropriate for low-level languages > > such as C. However, I think one-based indexing is more appropriate for > > high-level languages. > > Only if your aim is to reduce the learning curve for newbies and non- > programmers, at the expense of making it easier for them to produce buggy > code. If you're suggesting that one-based indexing makes it easier to produce buggy code, I think you must be smoking something. > That's a defensible choice. I'm a great fan of Apple's Hypercard from the > late 80s and early 90s, and it used one-based indexing, as well as > English-like syntax like: Python is a high level language, and high-level languages have many features that make it easier for newbies as well as experienced programmers at the expense of extreme efficiency. But the array indexing in Python is a throwback to C: it is zero-based and uses square brackets. Say what you will, but both of those aspects just seem wrong and awkward to me. However, I've switched from Python to Scala, so I really don't care. You guys can have it. From nikos.the.gr33k at gmail.com Sun Aug 22 03:27:57 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 22 Aug 2010 00:27:57 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> Message-ID: On 16 ???, 14:31, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > # initializecookie > >cookie=Cookie.SimpleCookie() > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > mycookie =cookie.get('visitor') > > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > > yandex|13448|spider|crawl)', host ) is None: > > ? ? blabla... > > ======================== > > > I checked and Chrome has acookienames visitor with a value ofnikos > > within. > > So, i have to ask why the if fails? > > Maybe it's because != != == Iwant ti if code block to be executed only if the browser cookie names visitor fetched doesnt cotnain the vbalue of 'nikos' Is there somethign wrong with the way i wrote it? From clp2 at rebertia.com Sun Aug 22 03:47:23 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 22 Aug 2010 00:47:23 -0700 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: On Sun, Aug 22, 2010 at 12:23 AM, Russ P. wrote: > On Aug 21, 1:33?am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: >> > Most programmers probably never use vectors and matrices, so they don't >> > care about the inconsistency with standard mathematical notation. >> >> Perhaps you should ask the numpy programmers what they think about that. > > Why would I care in the least about something called "numpy"? Because it's a popular matrix math package for Python. Its users are thus a subset of programmers which by definition don't fall into the "most programmers" group you describe. Cheers, Chris -- Google is your friend! http://blog.rebertia.com From dirknbr at gmail.com Sun Aug 22 04:01:55 2010 From: dirknbr at gmail.com (Dirk Nachbar) Date: Sun, 22 Aug 2010 01:01:55 -0700 (PDT) Subject: freq function Message-ID: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> Here is a function which takes any list and creates a freq table, which can be printed unsorted, sorted by cases or items. It's supposed to mirror the proc freq in SAS. Dirk def freq(seq,order='unsorted',prin=True): #order can be unsorted, cases, items freq={} for s in seq: if s in freq: freq[s]+=1 else: freq[s]=1 if prin==True: print 'Items=',len(seq),'Cases=',len(freq) print '------------------------' if order=='unsorted': for k in freq.keys(): print k,freq[k],float(freq[k])/len(seq) elif order=='cases': #http://blog.client9.com/2007/11/sorting-python-dict-by- value.html freq2=sorted(freq.iteritems(), key=lambda (k,v): (v,k),reverse=True) for f in freq2: print f[0],f[1],float(f[1])/len(seq) elif order=='items': for k in sorted(freq.iterkeys()): print k,freq[k],float(freq[k])/len(seq) print '------------------------' return freq #test import random rand=[] for i in range(10000): rand.append(str(int(100*random.random()))) fr=freq(rand) fr2=freq(rand,order='items') fr2=freq(rand,order='cases') From anand.shashwat at gmail.com Sun Aug 22 04:16:56 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 22 Aug 2010 13:46:56 +0530 Subject: freq function In-Reply-To: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> References: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> Message-ID: On Sun, Aug 22, 2010 at 1:31 PM, Dirk Nachbar wrote: > Here is a function which takes any list and creates a freq table, > which can be printed unsorted, sorted by cases or items. It's supposed > to mirror the proc freq in SAS. > > Dirk > > def freq(seq,order='unsorted',prin=True): > #order can be unsorted, cases, items > > freq={} > for s in seq: > if s in freq: > freq[s]+=1 > else: > freq[s]=1 > The above code can be replaced with this: freq = {} for s in seqn: freq[s] = freq.get(s,0) + 1 > if prin==True: > print 'Items=',len(seq),'Cases=',len(freq) > print '------------------------' > if order=='unsorted': > for k in freq.keys(): > print k,freq[k],float(freq[k])/len(seq) > elif order=='cases': > #http://blog.client9.com/2007/11/sorting-python-dict-by- > value.html > freq2=sorted(freq.iteritems(), key=lambda (k,v): > (v,k),reverse=True) > for f in freq2: > print f[0],f[1],float(f[1])/len(seq) > elif order=='items': > for k in sorted(freq.iterkeys()): > print k,freq[k],float(freq[k])/len(seq) > print '------------------------' > return freq > > #test > > import random > > rand=[] > for i in range(10000): > rand.append(str(int(100*random.random()))) > > fr=freq(rand) > fr2=freq(rand,order='items') > fr2=freq(rand,order='cases') > -- > I feel the code you wrote is bloated a bit. You shall definately give another try to improvise it. > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 22 04:34:33 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 22 Aug 2010 01:34:33 -0700 Subject: freq function In-Reply-To: References: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> Message-ID: On Sun, Aug 22, 2010 at 1:16 AM, Shashwat Anand wrote: > On Sun, Aug 22, 2010 at 1:31 PM, Dirk Nachbar wrote: >> Here is a function which takes any list and creates a freq table, >> which can be printed unsorted, sorted by cases or items. It's supposed >> to mirror the proc freq in SAS. >> >> Dirk >> >> ? ?freq={} >> ? ?for s in seq: >> ? ? ? ?if s in freq: >> ? ? ? ? ? ?freq[s]+=1 >> ? ? ? ?else: >> ? ? ? ? ? ?freq[s]=1 > > The above code can be replaced with this: > ?freq = {} > ?for s in seq: > ?? ? ? ? ?freq[s] = freq.get(s,0) + 1 Which can be further replaced by: from collections import Counter freq = Counter(seq) Using collections.defaultdict is another possibility if one doesn't have Python 2.7. Cheers, Chris -- It really bothers me that Counter isn't a proper Bag. http://blog.rebertia.com From nt_mahmood at yahoo.com Sun Aug 22 04:52:44 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 01:52:44 -0700 (PDT) Subject: Running python script before user login Message-ID: <702221.56174.qm@web50003.mail.re2.yahoo.com> I have wrote a python script and want to run it before user login. To do that, I have added it to the ubuntu startup file (init.d). However it seems that the script doesn't work. I want to know does python modules work before user login? // Naderan *Mahmood; -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 22 04:58:45 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 22 Aug 2010 01:58:45 -0700 Subject: Running python script before user login In-Reply-To: <702221.56174.qm@web50003.mail.re2.yahoo.com> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> Message-ID: On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > I have wrote a python script and want to run it before user login. To do > that, I have added it to the ubuntu startup file (init.d). However it seems > that the script doesn't work. Specify exactly how it's not working. Cheers, Chris -- More details = Better assistance From awilter at ebi.ac.uk Sun Aug 22 05:05:22 2010 From: awilter at ebi.ac.uk (Alan Wilter Sousa da Silva) Date: Sun, 22 Aug 2010 10:05:22 +0100 Subject: how to use xdrlib Message-ID: Hi there, I am trying to understand how xdrlib works as I want to read files in this format. The problem is I don't much about xdr (although I read http://docs.python.org/library/xdrlib.html and RFC 1832). Another problem is I don't know how the file I want to read was encoded. So when I do something like: import xdrlib f = open('file.xdr').read() data = xdrlib.Unpacker(f) Then, I don't know which "unpack_*" to use. If I use, repr(data.unpack_string()) sometimes it returns something meaningful like: "'Ryckaert-Bell.'" but other times, '\x00\x00\x00\x04Bond\x00\x00\x00\x05Angle\x00\x00\x00\x00\x00\x00\x0bProper Dih.\x00' if not a error. Well, as you see, I am a bit lost here and any hint would be very appreciated. Thanks in advance, Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From nt_mahmood at yahoo.com Sun Aug 22 05:13:14 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 02:13:14 -0700 (PDT) Subject: Running python script before user login In-Reply-To: References: <702221.56174.qm@web50003.mail.re2.yahoo.com> Message-ID: <782406.32409.qm@web50008.mail.re2.yahoo.com> >Specify exactly how it's not working. I have wrote a script to send my ip address to an email address. It does work when I am login (python sendip.py). I then followed the procedure in https://help.ubuntu.com/community/RcLocalHowto. However after restart, no email is sent. // Naderan *Mahmood; ________________________________ From: Chris Rebert To: Mahmood Naderan Cc: python mailing list Sent: Sun, August 22, 2010 1:28:45 PM Subject: Re: Running python script before user login On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > I have wrote a python script and want to run it before user login. To do > that, I have added it to the ubuntu startup file (init.d). However it seems > that the script doesn't work. Specify exactly how it's not working. Cheers, Chris -- More details = Better assistance -------------- next part -------------- An HTML attachment was scrubbed... URL: From wxjmfauth at gmail.com Sun Aug 22 05:17:09 2010 From: wxjmfauth at gmail.com (jmfauth) Date: Sun, 22 Aug 2010 02:17:09 -0700 (PDT) Subject: Wrong unichr docstring in 2.7 Message-ID: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> I think there is a small point here. >>> sys.version 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] >>> print unichr.__doc__ unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. >>> # but >>> unichr(0x10fff) Traceback (most recent call last): File "", line 1, in ValueError: unichr() arg not in range(0x10000) (narrow Python build) Note: I find 0x0 <= i <= 0xffff more logical than 0 <= i <= 0xffff (orange-apple comparaison) Ditto, for Python 2.6.5 Regards, jmf From ashish.satapathy2009 at gmail.com Sun Aug 22 05:51:05 2010 From: ashish.satapathy2009 at gmail.com (bapi) Date: Sun, 22 Aug 2010 02:51:05 -0700 (PDT) Subject: CodeSnipr Learning can be simple!! Message-ID: Hi, All the group members right at here, we people recently lunched a website CodeSnipr based on Computer language like (PHP, RUBBY, HTML, CSS, MYSQL, JQURY, IPHONE DEVELOPMENT, JAVASCRIPT, C++,.NET,XML,C# etc.). CodeSnipr will provide you access to user generated tutorials. Here you can post your code snippet and learn from other's snippet. We believe learning can be simple. We want your feedback about this tutorial please visit to join this : http://www.codesnipr.com/. From thomas at jollybox.de Sun Aug 22 06:25:19 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 22 Aug 2010 12:25:19 +0200 Subject: Wrong unichr docstring in 2.7 In-Reply-To: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> References: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> Message-ID: <201008221225.20614.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to jmfauth to exclaim: > I think there is a small point here. > > >>> sys.version > > 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] > > >>> print unichr.__doc__ > > unichr(i) -> Unicode character > > Return a Unicode string of one character with ordinal i; 0 <= i <= > 0x10ffff. > > >>> # but > >>> unichr(0x10fff) > > Traceback (most recent call last): > File "", line 1, in > ValueError: unichr() arg not in range(0x10000) (narrow Python > build) This is very tricky ground. I consider the behaviour of unichr() to be wrong here. The user shouldn't have to care much about UTF-16 and the difference between wide and narrow Py_UNICODDE builds. In fact, in Python 3.1, this behaviour has changed: on a narrow Python 3 build, chr(0x10fff) == '\ud803\udfff' == '\U00010fff'. Now, the Python 2 behaviour can't be fixed [1] -- it was specified in PEP 261 [2], which means it was pretty much set in stone. Then, it was deemed more important for unichr() to always return a length-one string that for it to work with wide characters. And then add pretty half-arsed utf-16 support... The doc string could be changed for narrow Python builds. I myself don't think docstrings should change depending on build options like this -- it could be amended to document the different behaviours here. Note that the docs [3] already include this information. If you want to, feel free to report a bug at http://bugs.python.org/ > Note: > > I find > 0x0 <= i <= 0xffff > more logical than > 0 <= i <= 0xffff > > (orange-apple comparaison) Would a zero by any other name not look as small? Honestly, I myself find it nonsensical to qualify 0 by specifying a base, unless you go all the way and represent the full uint16_t by saying 0x0000 <= i <= 0xffff - Thomas [1] http://bugs.python.org/issue1057588 [2] http://www.python.org/dev/peps/pep-0261/ [3] http://docs.python.org/library/functions.html#unichr From davea at ieee.org Sun Aug 22 06:39:35 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 22 Aug 2010 06:39:35 -0400 Subject: Wrong unichr docstring in 2.7 In-Reply-To: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> References: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> Message-ID: <4C70FE67.3050209@ieee.org> jmfauth wrote: > I think there is a small point here. > > >>>> sys.version >>>> > 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] > >>>> print unichr.__doc__ >>>> > unichr(i) -> Unicode character > > Return a Unicode string of one character with ordinal i; 0 <= i <= > 0x10ffff. > >>>> # but >>>> unichr(0x10fff) >>>> > Traceback (most recent call last): > File "", line 1, in > ValueError: unichr() arg not in range(0x10000) (narrow Python > build) > > Note: > > I find > 0x0 <= i <= 0xffff > more logical than > 0 <= i <= 0xffff > > (orange-apple comparaison) > > Ditto, for Python 2.6.5 > > Regards, > jmf > > > There are two variants that CPython can be compiled for, 16 bit Unicode and 32 bit. By default, the Windows implementation uses 16 bits, and the Linux one uses 32. I believe you can rebuild your version if you have access to an appropriate version MSC compiler, but I haven't any direct experience. At any rate, the bug here is that the docstring doesn't get patched to match the compile switches for your particular build of CPython. DaveA From thomas at jollybox.de Sun Aug 22 06:41:55 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 22 Aug 2010 12:41:55 +0200 Subject: how to use xdrlib In-Reply-To: References: Message-ID: <201008221241.56612.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to Alan Wilter Sousa da Silva to exclaim: > Hi there, > > I am trying to understand how xdrlib works as I want to read files in this > format. The problem is I don't much about xdr (although I read > http://docs.python.org/library/xdrlib.html and RFC 1832). > > Another problem is I don't know how the file I want to read was encoded. > > So when I do something like: > > import xdrlib > > f = open('file.xdr').read() > data = xdrlib.Unpacker(f) > > Then, I don't know which "unpack_*" to use. If you actually have read RFC 1832, then this surprises me: as far as I can see, and I have only skimmed the RFC so I may be wrong, it includes no way to specify the type of a piece of data -- you have to know what you're reading. > > If I use, > > repr(data.unpack_string()) > > sometimes it returns something meaningful like: > > "'Ryckaert-Bell.'" This happens when the data was actually a string -- so you correctly used unpack_string > > but other times, > > '\x00\x00\x00\x04Bond\x00\x00\x00\x05Angle\x00\x00\x00\x00\x00\x00\x0bPrope > r Dih.\x00' Here, you read data that was not originally a string as if it were one. What the xdrlib module did is: it read four bytes. Probably 00 00 00 24. And it interpreted these to be the length of the string you're trying to read. Actually, you probably should have read an int first. After that, you could have called unpack_string, which would have read in 00 00 00 04 -- aha, a four-long string -- and then read another four bytes, the actual string: "Bond". Similarly, "Angle" has length 0x00000005, it's followed by padding unto 4-byte margins, followed by the length of "Proper Dih.", which happens to be 0x0000000b. > > if not a error. That might happen if the number xdrlib interprets as the string length is larger than the length of the rest of the file. > > Well, as you see, I am a bit lost here and any hint would be very > appreciated. Basically, you have to know which file format you're dealing with, and use the right unpack functions in the correct order for the specific file you're dealing with. So you need some documentation for the file format you're using -- XDR (like Microsoft's StructuredStorage, or even XML) doesn't as of itself make any claims about the nature or structure of the data it holds. Cheers, - Thomas From thomas at jollybox.de Sun Aug 22 06:47:57 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 22 Aug 2010 12:47:57 +0200 Subject: Running python script before user login In-Reply-To: <782406.32409.qm@web50008.mail.re2.yahoo.com> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> <782406.32409.qm@web50008.mail.re2.yahoo.com> Message-ID: <201008221247.58158.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > >Specify exactly how it's not working. > > I have wrote a script to send my ip address to an email address. It does > work when I am login (python sendip.py). I then followed the procedure in > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > email is sent. The first step would be to make sure your init script is actually running. Add some simple command that you know will not fail, and where you can see easily that it worked. Say, you could use #!/bin/sh date > /home/[USER]/Desktop/created_during_boot.txt as an init script. Then you could see that, if the file was created on your desktop, that the script is running at all. When you know that, THEN you can start to worry about Python (I think Ubuntu probably doesn't bring up the network before NetworkManager does this after login. So you might just not be able to send e-mail before login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > ________________________________ > From: Chris Rebert > To: Mahmood Naderan > Cc: python mailing list > Sent: Sun, August 22, 2010 1:28:45 PM > Subject: Re: Running python script before user login > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > > I have wrote a python script and want to run it before user login. To do > > that, I have added it to the ubuntu startup file (init.d). However it > > seems that the script doesn't work. > > Specify exactly how it's not working. > > Cheers, > Chris > -- > More details = Better assistance From sjmachin at lexicon.net Sun Aug 22 06:57:04 2010 From: sjmachin at lexicon.net (John Machin) Date: Sun, 22 Aug 2010 03:57:04 -0700 (PDT) Subject: Detect string has non-ASCII chars without checking each char? References: <4c70cc98$0$5406$ba4acef3@reader.news.orange.fr> Message-ID: On Aug 22, 5:07?pm, "Michel Claveau - MVP" wrote: > Hi! > > Another way : > > ? # -*- coding: utf-8 -*- > > ? import unicodedata > > ? def test_ascii(struni): > ? ? ? strasc=unicodedata.normalize('NFD', struni).encode('ascii','replace') > ? ? ? if len(struni)==len(strasc): > ? ? ? ? ?return True > ? ? ? else: > ? ? ? ? ?return False > > ? print test_ascii(u"abcde") > ? print test_ascii(u"abcd?") -1 Try your code with u"abcd\xa1" ... it says it's ASCII. Suggestions: test_ascii = lambda s: len(s.decode('ascii', 'ignore')) == len(s) or test_ascii = lambda s: all(c < u'\x80' for c in s) or use try/except Also: if a == b: return True else: return False is a horribly bloated way of writing return a == b From inhahe at gmail.com Sun Aug 22 08:23:19 2010 From: inhahe at gmail.com (inhahe) Date: Sun, 22 Aug 2010 05:23:19 -0700 (PDT) Subject: trying to use sdl_pango with python Message-ID: <417e139c-2032-4793-8b23-88433d99c9de@i31g2000yqm.googlegroups.com> i'm new to ctypes. can someone help me use sdl_pango with python? here's the documentation: http://sdlpango.sourceforge.net/ here's my code: ----------------------------------------------------- import pygame from ctypes import * import win32api MATRIX_TRANSPARENT_BACK_WHITE_LETTER = c_char_p("\xFF\xFF\0\0\xFF\xFF \0\0\xFF\xFF\0\0\0\xFF\0\0") margin_x = margin_y = 10 def sdlwrite(rtext, width, height=None): context = sdlpango.SDLPango_CreateContext() sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) sdlpango.SDLPango_SetMinimumSize(context, width, height) sdlpango.SDLPango_SetMarkup(context, rtext, -1) w = sdlpango.SDLPango_GetLayoutWidth(context) h = sdlpango.SDLPango_GetLayoutHeight(context) surface = sdl.SDL_CreateRGBSurface(sdlpango.SDL_SWSURFACE, w + margin_x, h + margin_y, 32, 255 << (8*3), 255 << (8*2), 255 << (8*1), 255) sp = POINTER(surface) sdlpango.SDLPango_Draw(context, ps, margin_x, margin_y) sdl.SDL_FreeSurface(ps) return context def surfwrite(rtext, width, height=None): sdlcontext = sdlwrite(rtext, width, height) print 'sdlcontext:', sdlcontext #scr = pygame.set_mode() #rloss, gloss, bloss, aloss = scr. sdlpango = windll.LoadLibrary(r"C:\projects\soundshop\pango-1.18.3\bin \sdl_pango.dll") sdl = windll.LoadLibrary(r"sdl.dll") #sdlpango.SDLPango_SetDefaultColor.argtypes = [c_void_p, c_char_p] #sdlpango.SDLPango_SetMinimumSize.argtypes = [c_void_p, c_int, c_int] #sdlpango.SDLPango_SetMarkup.argtypes = [c_void_p, c_char_p, c_int] #sdlpango.SDLPango_GetLayoutWidth.argtypes = [c_void_p] #sdlpango.SDLPango_GetLayoutHeight.argtypes = [c_void_p] #sdl.SDL_CreateRGBSurface.argtypes = [c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint] #sdlpango.SDLPango_Draw.argtypes = [c_void_p, c_uint, c_int, c_int] #sdl.SDL_FreeSurface.argtypes = [c_void_p] sdlpango.SDLPango_SetDefaultColor.argtypes = [c_uint, c_uint] sdlpango.SDLPango_SetMinimumSize.argtypes = [c_uint, c_int, c_int] sdlpango.SDLPango_SetMarkup.argtypes = [c_uint, c_char_p, c_int] sdlpango.SDLPango_GetLayoutWidth.argtypes = [c_uint] sdlpango.SDLPango_GetLayoutHeight.argtypes = [c_uint] sdl.SDL_CreateRGBSurface.argtypes = [c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint] sdlpango.SDLPango_Draw.argtypes = [c_uint, c_uint, c_int, c_int] sdl.SDL_FreeSurface.argtypes = [c_uint] surfwrite("hello", 640) ----------------------------------------------------- here's the .h file that i got MATRIX_TRANSPARENT_BACK_WHITE_LETTER from. http://sdlpango.sourceforge.net/_s_d_l___pango_8h-source.html ----------------------------------------------------- here's my error: Traceback (most recent call last): File "C:\projects\soundshop\sdlpango.py", line 54, in surfwrite("hello", 640) File "C:\projects\soundshop\sdlpango.py", line 25, in surfwrite sdlcontext = sdlwrite(rtext, width, height) File "C:\projects\soundshop\sdlpango.py", line 13, in sdlwrite sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) ctypes.ArgumentError: argument 2: : wrong type ----------------------------------------------------- i've tried other things, like using c_char_p instead for MATRIX_TRANSPARENT_BACK_WHITE_LETTER, but the only other result i can manage to get is this: C:\projects\soundshop>sdlpango.py Traceback (most recent call last): File "C:\projects\soundshop\sdlpango.py", line 52, in surfwrite("hello", 640) File "C:\projects\soundshop\sdlpango.py", line 25, in surfwrite sdlcontext = sdlwrite(rtext, width, height) File "C:\projects\soundshop\sdlpango.py", line 13, in sdlwrite sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) ValueError: Procedure probably called with too many arguments (8 bytes in excess) ----------------------------------------------------- thx for any help. From __peter__ at web.de Sun Aug 22 08:29:31 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Aug 2010 14:29:31 +0200 Subject: freq function References: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> Message-ID: Dirk Nachbar wrote: > Here is a function which takes any list and creates a freq table, > which can be printed unsorted, sorted by cases or items. It's supposed > to mirror the proc freq in SAS. > > Dirk > > def freq(seq,order='unsorted',prin=True): > #order can be unsorted, cases, items > > freq={} > for s in seq: > if s in freq: > freq[s]+=1 > else: > freq[s]=1 > if prin==True: > print 'Items=',len(seq),'Cases=',len(freq) > print '------------------------' > if order=='unsorted': > for k in freq.keys(): > print k,freq[k],float(freq[k])/len(seq) > elif order=='cases': > #http://blog.client9.com/2007/11/sorting-python-dict-by- > value.html > freq2=sorted(freq.iteritems(), key=lambda (k,v): > (v,k),reverse=True) Sorting in two steps gives a slightly better result when there are items with equal keys. Compare >>> freq = {"a": 2, "b": 1, "c": 1, "d": 2} >>> sorted(freq.iteritems(), key=lambda (k, v): (v, k), reverse=True) [('d', 2), ('a', 2), ('c', 1), ('b', 1)] with >>> freq2 = sorted(freq.iteritems(), key=lambda (k, v): k) >>> freq2.sort(key=lambda (k, v): v, reverse=True) >>> freq2 [('a', 2), ('d', 2), ('b', 1), ('c', 1)] Here the keys within groups of equal frequency are in normal instead of reversed order. From nt_mahmood at yahoo.com Sun Aug 22 09:13:27 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 06:13:27 -0700 (PDT) Subject: Running python script before user login In-Reply-To: <201008221247.58158.thomas@jollybox.de> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> <782406.32409.qm@web50008.mail.re2.yahoo.com> <201008221247.58158.thomas@jollybox.de> Message-ID: <587949.10318.qm@web50005.mail.re2.yahoo.com> I am trying to execute this script before login: ? #!/bin/sh? date > /home/mahmood/dateatboot.txt echo "In local file" /usr/bin/python2.6 /home/mahmood/sendip.py echo "python script finished" after restart, dateatboot.txt was created shows that the script was executed. In the python file, I have this: ?import smtplib, commands, os, datetime # find IP address and write to file print 'I am in python file' f = open('.ip.txt', 'w') f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) f.close() ... ? After boot there is no .ip.txt file. ? // Naderan *Mahmood; ________________________________ From: Thomas Jollans To: python-list at python.org Sent: Sun, August 22, 2010 3:17:57 PM Subject: Re: Running python script before user login On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > >Specify exactly how it's not working. > > I have wrote a script to send my ip address to an email address. It does > work when I am login (python sendip.py). I then followed the procedure in > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > email is sent. The first step would be to make sure your init script is actually running. Add some simple command that you know will not fail, and where you can see easily that it worked. Say, you could use #!/bin/sh date > /home/[USER]/Desktop/created_during_boot.txt as an init script. Then you could see that, if the file was created on your desktop, that the script is running at all. When you know that, THEN you can start to worry about Python (I think Ubuntu probably doesn't bring up the network before NetworkManager does this after login. So you might just not be able to send e-mail before login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > ________________________________ > From: Chris Rebert > To: Mahmood Naderan > Cc: python mailing list > Sent: Sun, August 22, 2010 1:28:45 PM > Subject: Re: Running python script before user login > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > > I have wrote a python script and want to run it before user login. To do > > that, I have added it to the ubuntu startup file (init.d). However it > > seems that the script doesn't work. > > Specify exactly how it's not working. > > Cheers, > Chris > -- > More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollybox.de Sun Aug 22 09:20:00 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 22 Aug 2010 15:20:00 +0200 Subject: Running python script before user login In-Reply-To: <587949.10318.qm@web50005.mail.re2.yahoo.com> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> <201008221247.58158.thomas@jollybox.de> <587949.10318.qm@web50005.mail.re2.yahoo.com> Message-ID: <201008221520.01115.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > I am trying to execute this script before login: > > #!/bin/sh > date > /home/mahmood/dateatboot.txt > echo "In local file" > /usr/bin/python2.6 /home/mahmood/sendip.py > echo "python script finished" > after restart, dateatboot.txt was created shows that the script was > executed. In the python file, I have this: > import smtplib, commands, os, datetime > # find IP address and write to file > print 'I am in python file' > f = open('.ip.txt', 'w') > f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) > f.close() > ... > > After boot there is no .ip.txt file. Where are you looking? Do you actually know in which working directory your script is being executed? How about something like this: #!/bin/sh cd /home/mahmood/ python sendip.py >sendip.log 2>&1 ... this will write Python's output to a log file. If there is an exception, you'd be able to see it. > > > // Naderan *Mahmood; > > > > > ________________________________ > From: Thomas Jollans > To: python-list at python.org > Sent: Sun, August 22, 2010 3:17:57 PM > Subject: Re: Running python script before user login > > On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > > >Specify exactly how it's not working. > > > > I have wrote a script to send my ip address to an email address. It does > > work when I am login (python sendip.py). I then followed the procedure in > > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > > email is sent. > > The first step would be to make sure your init script is actually running. > Add some simple command that you know will not fail, and where you can see > easily that it worked. Say, you could use > > #!/bin/sh > > date > /home/[USER]/Desktop/created_during_boot.txt > > as an init script. Then you could see that, if the file was created on your > desktop, that the script is running at all. When you know that, THEN you > can start to worry about Python > > (I think Ubuntu probably doesn't bring up the network before NetworkManager > does this after login. So you might just not be able to send e-mail before > login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > > > > > > ________________________________ > > From: Chris Rebert > > To: Mahmood Naderan > > Cc: python mailing list > > Sent: Sun, August 22, 2010 1:28:45 PM > > Subject: Re: Running python script before user login > > > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan > > wrote: > > > I have wrote a python script and want to run it before user login. To > > > do that, I have added it to the ubuntu startup file (init.d). However > > > it seems that the script doesn't work. > > > > Specify exactly how it's not working. > > > > Cheers, > > Chris > > -- > > More details = Better assistance From nt_mahmood at yahoo.com Sun Aug 22 09:45:57 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 06:45:57 -0700 (PDT) Subject: Running python script before user login In-Reply-To: <201008221520.01115.thomas@jollybox.de> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> <201008221247.58158.thomas@jollybox.de> <587949.10318.qm@web50005.mail.re2.yahoo.com> <201008221520.01115.thomas@jollybox.de> Message-ID: <767562.18819.qm@web50007.mail.re2.yahoo.com> It seems that changing the directory before python command is mandatory: #!/bin/sh cd /home/mahmood/ python sendip.py? ? I am now able to receive the IP address right after boot and before login page. Thank you // Naderan *Mahmood; ________________________________ From: Thomas Jollans To: python-list at python.org Sent: Sun, August 22, 2010 5:50:00 PM Subject: Re: Running python script before user login On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > I am trying to execute this script before login: >? > #!/bin/sh > date > /home/mahmood/dateatboot.txt > echo "In local file" > /usr/bin/python2.6 /home/mahmood/sendip.py > echo "python script finished" > after restart, dateatboot.txt was created shows that the script was > executed. In the python file, I have this: >? import smtplib, commands, os, datetime > # find IP address and write to file > print 'I am in python file' > f = open('.ip.txt', 'w') > f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) > f.close() > ... >? > After boot there is no .ip.txt file. Where are you looking? Do you actually know in which working directory your script is being executed? How about something like this: #!/bin/sh cd /home/mahmood/ python sendip.py >sendip.log 2>&1 ... this will write Python's output to a log file. If there is an exception, you'd be able to see it. > >? > // Naderan *Mahmood; > > > > > ________________________________ > From: Thomas Jollans > To: python-list at python.org > Sent: Sun, August 22, 2010 3:17:57 PM > Subject: Re: Running python script before user login > > On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > > >Specify exactly how it's not working. > > > > I have wrote a script to send my ip address to an email address. It does > > work when I am login (python sendip.py). I then followed the procedure in > > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > > email is sent. > > The first step would be to make sure your init script is actually running. > Add some simple command that you know will not fail, and where you can see > easily that it worked. Say, you could use > > #!/bin/sh > > date > /home/[USER]/Desktop/created_during_boot.txt > > as an init script. Then you could see that, if the file was created on your > desktop, that the script is running at all. When you know that, THEN you > can start to worry about Python > > (I think Ubuntu probably doesn't bring up the network before NetworkManager > does this after login. So you might just not be able to send e-mail before > login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > > > > > > ________________________________ > > From: Chris Rebert > > To: Mahmood Naderan > > Cc: python mailing list > > Sent: Sun, August 22, 2010 1:28:45 PM > > Subject: Re: Running python script before user login > > > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan > > wrote: > > > I have wrote a python script and want to run it before user login. To > > > do that, I have added it to the ubuntu startup file (init.d). However > > > it seems that the script doesn't work. > > > > Specify exactly how it's not working. > > > > Cheers, > > Chris > > -- > > More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Sun Aug 22 10:06:54 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 22 Aug 2010 14:06:54 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: <8dcp7uFvpgU1@mid.individual.net> On 2010-08-21, Steven D'Aprano wrote: > There is room in the world for programming languages aimed at > non- programmers (although HC is an extreme case), but not all > languages should prefer the intuition of non-programmers over > other values. Extremer: Inform 7. -- Neil Cerutti From wxjmfauth at gmail.com Sun Aug 22 10:12:21 2010 From: wxjmfauth at gmail.com (jmfauth) Date: Sun, 22 Aug 2010 07:12:21 -0700 (PDT) Subject: Wrong unichr docstring in 2.7 References: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> Message-ID: Short comments: 1) I'm aware Python can be built in "ucs2" or "ucs4" mode. It remains that the unichr doc string does not seem correct. 2) 0x0 versus 0 Do not take this too seriously. Sure the value of 0x0 and 0 are equal, but the "unit" sounds strange. Eg. If a is a length, I would not express a as beeing 0 mm <= a <= 999 m (or 0 in <= a <= 999 ft) but 0 m <= a <= 999 m . I agree a notation like 0x0000 <= i <= 0xffff is even the best. 3) Of course, the Python 3 behaviour (chr() instead of unichr()) is correct. jmf From jhullu at gmail.com Sun Aug 22 10:29:54 2010 From: jhullu at gmail.com (Jacques HULLU) Date: Sun, 22 Aug 2010 16:29:54 +0200 Subject: windows hook to catch WM_CREATE Message-ID: Hello all, I'm looking for a method, lib, ... to create a windows hook to catch WM_CREATE message in python 2.6? For keyboard and mouse I use pyHook. any idea ? -- Jacques -------------- next part -------------- An HTML attachment was scrubbed... URL: From enleverLesX_XXmcX at XmclavXeauX.com.invalid Sun Aug 22 11:10:26 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Sun, 22 Aug 2010 17:10:26 +0200 Subject: Detect string has non-ASCII chars without checking each char? References: Message-ID: <4c713de4$0$5428$ba4acef3@reader.news.orange.fr> Re ! > Try your code with u"abcd\xa1" ... it says it's ASCII. Ah? in my computer, it say "False" @-salutations -- MCi From dak at gnu.org Sun Aug 22 11:22:51 2010 From: dak at gnu.org (David Kastrup) Date: Sun, 22 Aug 2010 17:22:51 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> Message-ID: <87k4nir7sk.fsf@lola.goethe.zz> John Bokma writes: > David Kastrup writes: > >> John Passaniti writes: >> >>> Amen! All this academic talk is useless. Who cares about things like >>> the big-O notation for program complexity. Can't people just *look* >>> at code and see how complex it is?! And take things like the years of >>> wasted effort computer scientists have put into taking data structures >>> (like hashes and various kinds of trees) and extending them along >>> various problem domains and requirements. Real programmers don't >>> waste their time with learning that junk. What good did any of that >>> ever do anyone?! >> >> It is my experience that in particular graduated (and in particular Phd) >> computer scientists don't waste their time _applying_ that junk. > > Question: do you have a degree in computer science? > > Since in my experience: people who talk about their experience with > graduated people often missed the boat themselves and think that reading > a book or two equals years of study. I have a degree in electrical engineering. But that's similarly irrelevant. I have a rather thorough background with computers (started with punched cards), get along with about a dozen assembly languages and quite a few other higher level languages. I've had to write the BIOS for my first computer and a number of other stuff and did digital picture enhancement on DOS computers with EMM (programming 80387 assembly language and using a variant of Hartley transforms). I have rewritten digital map processing code from scratch that has been designed and optimized by graduated computer scientists (including one PhD) to a degree where it ran twice as fast as originally, at the cost of occasional crashes and utter unmaintainability. Twice as fast meaning somewhat less than a day of calculation time for medium size data sets (a few 100000 of data points, on something like a 25MHz 68020 or something). So I knew the problem was not likely to be easy. Took me more than a week. After getting the thing to compile and fixing the first few crashing conditions, I got stuck in debugging. The thing just terminated after about 2 minutes of runtime without an apparent reason. I spent almost two more days trying to find the problem before bothering to even check the output. The program just finished regularly. That has not particularly helped my respect towards CS majors and PhDs in the function of programmers (and to be honest: their education is not intended to make them good programmers, but to enable them to _lead_ good programmers). That does not mean that I am incapable of analyzing, say quicksort and mergesort, and come up with something reasonably close to a closed form for average, min, and max comparisons (well, unless a close approximation is good enough, you have to sum about lg n terms which is near instantaneous, with a real closed form mostly available when n is special, like a power of 2). And I know how to work with more modern computer plagues, like the need for cache coherency. So in short, I have a somewhat related scientific education, but I can work the required math. And I can work the computers. > Oh, and rest assured, it works both ways: people who did graduate are > now and then thinking it's the holy grail and no body can beat it with > home study. > > Both are wrong, by the way. Depends. In my personal opinion, living close to the iron and being sharp enough can make a lot of a difference. Donald Knuth never studied computer science. He more or less founded it. As a programmer, he is too much artist and too little engineer for my taste: you can't take his proverbial masterpiece "TeX" apart without the pieces crumbling. He won't write inefficient programs: he has the respective gene and the knowledge to apply it. But the stuff he wrote is not well maintainable and reusable. Of course, he has no need for reuse if he can rewrite as fast as applying an interface. -- David Kastrup From roy at panix.com Sun Aug 22 12:14:03 2010 From: roy at panix.com (Roy Smith) Date: Sun, 22 Aug 2010 12:14:03 -0400 Subject: Organizing unit test? Message-ID: Over the years, I've tried different styles of organizing unit tests. I used to create a test directory and put all my tests there. I would maintain a one-to-one correspondence between production source and test source, i.e. the test code for foo.py would be in test/foo.py. More recently, I've taken to having foo.py and test_foo.py in the same directory. My latest experiment is to just put both the production code and the test code in the same file, ending with if __name__ == '__main__': unittest.main() So, if I import the file, I get the production code as a module, and if I run it from the command line, it runs the tests. This makes the file messier, but it makes the directory structure cleaner and (I think) makes the whole thing easier to edit. Any of these work. I'm just curious what organizations other people have used and what the plusses and minuses ended up being. From nt_mahmood at yahoo.com Sun Aug 22 13:05:56 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 10:05:56 -0700 (PDT) Subject: Get authentication error while using 'smtplib' In-Reply-To: <13714.16636.qm@web50005.mail.re2.yahoo.com> References: <13714.16636.qm@web50005.mail.re2.yahoo.com> Message-ID: <11570.47722.qm@web50007.mail.re2.yahoo.com> Well, login plain did the job: ? session = smtplib.SMTP(smtpserver) session.ehlo() session.esmtp_features["auth"] = "LOGIN PLAIN"if AUTHREQUIRED: ?? session.login(smtpuser, smtppass) ? // Naderan *Mahmood; ________________________________ From: Mahmood Naderan To: python mailing list Sent: Fri, August 20, 2010 6:13:20 PM Subject: Get authentication error while using 'smtplib' I have this script to send an email via SMTP: import smtplib smtpserver = 'smtp.server.com' AUTHREQUIRED = 1# if you need to use SMTP AUTH set to 1 smtpuser = "username"# for SMTP AUTH, set SMTP username here smtppass = "password"# for SMTP AUTH, set SMTP password here RECIPIENTS ='recipient at server.com' SENDER = 'sender at server.com' mssg = open('filename.txt', 'r').read() session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: ?? session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) After running the script I get this error: ? Traceback (most recent call last): ? File "my_mail.py", line 14, in ??? session.login(smtpuser, smtppass) ? File "/usr/lib/python2.6/smtplib.py", line 589, in login ??? raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, '5.7.0 Error: authentication failed: authentication failure') However there is no problem with my user/pass because I can login to my mail account. Thanks for any idea.? // Naderan *Mahmood;? -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Sun Aug 22 13:32:51 2010 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 22 Aug 2010 19:32:51 +0200 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <874oen1p9r.fsf@castleamber.com> <4c709a3c$0$28653$c3e8da3@news.astraweb.com> Message-ID: <87mxse1rjw.fsf@busola.homelinux.net> Steven D'Aprano writes: > * It throws away information from tracebacks if the recursive function > fails; and [...] > If you're like me, you're probably thinking that the traceback from an > exception in a recursive function isn't terribly useful. Agreed. On the other hand, a full-fledged tail recursion optimization might throw away more than that. For tail recursion elimination to work for those used to it, it needs to also handle the case of mutually recursive tail calls. The obvious way is by eliminating *all* tail calls, not just recursive ones. Tail call optimization, as opposed to tail recursion optimization, means that code such as: def f(n): return g(n + 5) is executed by a conceptual "jump" from the body of f to the body of g, regardless of whether recursion is involved at any point in the call chain. Now, if invocation of g() fails, the stack trace will show no sign of f() having been invoked. On the other hand, if f() invocation remains stored on the stack, mutually recursive functions will overflow it. Python being dynamic, I would expect it to be impossible to determine at compile-time whether a tail call will ultimately lead to a recursive invocation. From raoulbia at gmail.com Sun Aug 22 13:50:47 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 22 Aug 2010 10:50:47 -0700 (PDT) Subject: comparing tuples Message-ID: <880a20dd-7a1f-467a-a215-e36dd0108d0e@i13g2000yqd.googlegroups.com> level: beginners I was trying to write simple code that compares 2 tuples and returns any element in the second tuple that is not in the first tuple. def tuples(t1, t2): result = [] for b in t2: for a in t1: if b == a: break else: result=result+[b,] return result print tuples([0,5,6], [0,5,6,3,7]) the code works but i was surprised by the following: my understanding was that an ELSE clause is part of an IF statement. Therefore it comes at the same indentation as the IF statement. However the above example only works if the ELSE clause is positioned under the second FOR loop. As if it was an ELSE clause without an IF statement....!? Why/How does this work? tnx Baba From gandalf at shopzeus.com Sun Aug 22 14:07:48 2010 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Sun, 22 Aug 2010 20:07:48 +0200 Subject: Sphinx cross reference question Message-ID: <4C716774.5090207@shopzeus.com> In my shopzeus.db.pivot.convert.py file, in the run() method of my Data2Facts class, I can write this into the docstring: class Data2Facts(threading.Thread): # code here... def prepare(self,*args): # code here... # more code here def run(self): """ Start data conversion. You need to call :meth:`prepare` before starting the conversion with :meth:`run`. """ # more code here... This works perfectly - it places cross links in the HTML documentation. I have another file where I'm writting a tutorial for my Data2Facts class. It is not the API, but I would like to make references to the API. So I can do this: The :meth:`shopzeus.db.pivot.convert.Data2Facts.prepare` method is used for blablabla.... However, I do not want to write "shopzeus.db.pivot.convert." every time. I want to make this my current module for cross-referencing. So I tried this: .. :currentmodule:: shopzeus.db.pivot.convert The :meth:`Data2Facts.prepare` method is used for blablabla.... But it does not work! It is displayed in bold, but there is no link. The sphinx build command does not give me any warnings about invalid references. What am I doing wrong? Thanks, Laszlo From python.list at tim.thechases.com Sun Aug 22 14:12:00 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 22 Aug 2010 13:12:00 -0500 Subject: comparing tuples In-Reply-To: <880a20dd-7a1f-467a-a215-e36dd0108d0e@i13g2000yqd.googlegroups.com> References: <880a20dd-7a1f-467a-a215-e36dd0108d0e@i13g2000yqd.googlegroups.com> Message-ID: <4C716870.7010609@tim.thechases.com> On 08/22/10 12:50, Baba wrote: > level: beginners > > I was trying to write simple code that compares 2 tuples and returns > any element in the second tuple that is not in the first tuple. > > def tuples(t1, t2): > result = [] > for b in t2: > for a in t1: > if b == a: > break > else: > result=result+[b,] > return result > > print tuples([0,5,6], [0,5,6,3,7]) > > > the code works but i was surprised by the following: my understanding > was that an ELSE clause is part of an IF statement. Therefore it comes > at the same indentation as the IF statement. The ELSE clause can be used either with an IF (as you know) or with a FOR loop, which is interpreted as "if this loop reached the end naturally instead of exiting via a BREAK statement, execute this block of code". If you reach the end of t1 without having found a value (and then issuing a "break"), then the current value of t2 (b) should be appended to the result. That said, unless order matters, I'd just use sets: def tuples(t1, t2): return list(set(t2)-set(t1)) which should have better performance characteristics for large inputs. -tkc From john at castleamber.com Sun Aug 22 14:12:36 2010 From: john at castleamber.com (John Bokma) Date: Sun, 22 Aug 2010 13:12:36 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> Message-ID: <878w3yikiz.fsf@castleamber.com> David Kastrup writes: > John Bokma writes: > >> David Kastrup writes: >> >>> John Passaniti writes: >>> >>>> Amen! All this academic talk is useless. Who cares about things like >>>> the big-O notation for program complexity. Can't people just *look* >>>> at code and see how complex it is?! And take things like the years of >>>> wasted effort computer scientists have put into taking data structures >>>> (like hashes and various kinds of trees) and extending them along >>>> various problem domains and requirements. Real programmers don't >>>> waste their time with learning that junk. What good did any of that >>>> ever do anyone?! >>> >>> It is my experience that in particular graduated (and in particular Phd) >>> computer scientists don't waste their time _applying_ that junk. >> >> Question: do you have a degree in computer science? >> >> Since in my experience: people who talk about their experience with >> graduated people often missed the boat themselves and think that reading >> a book or two equals years of study. > > I have a degree in electrical engineering. But that's similarly > irrelevant. Nah, it's not: your attitude towards people with a degree in computer science agrees with what I wrote. > That has not particularly helped my respect towards CS majors and PhDs > in the function of programmers (and to be honest: their education is not > intended to make them good programmers, but to enable them to _lead_ > good programmers). I disagree. > That does not mean that I am incapable of analyzing, say quicksort and > mergesort, Oh, that's what I was not implying. I am convinced that quite some people who do self-study can end up with better understanding of things than people who do it for a degree. I have done both: I already was programming in several languages before I was studying CS. And my experience is that a formal study in CS can't compare to home study unless you're really good and have the time and drive to read formal books written on CS. And my experience is that most self-educaters don't have that time. On the other hand: some people I knew during my studies had no problem at all with introducing countless memory leaks in small programs (and turning off compiler warnings, because it gave so much noise...) > Donald Knuth never studied computer science. Yes, yes, and Albert Einstein worked at an office. Those people are very rare. But my experience (see for plenty of examples: Slashdot) is that quite some people who don't have a degree think that all that formal education is just some paper pushing and doesn't count. While some of those who do have the paper think they know it all. Those people who are right in either group are a minority in my experience. As for electrical engineering: done that (BSc) and one of my class mates managed to connect a transformer the wrong way around.... twice. Yet he had the highest mark in our class. So in short: yes, self-study can make you good at something. But self-study IMO is not in general a replacement for a degree. Someone who can become great after self-study would excel at a formal study and learn more. Study works best if there is competition and if there are challenges. I still study a lot at home, but I do miss the challenges and competition. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From john at castleamber.com Sun Aug 22 14:18:36 2010 From: john at castleamber.com (John Bokma) Date: Sun, 22 Aug 2010 13:18:36 -0500 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <874oen1p9r.fsf@castleamber.com> <4c709a3c$0$28653$c3e8da3@news.astraweb.com> Message-ID: <874oemik8z.fsf@castleamber.com> Steven D'Aprano writes: > On Sat, 21 Aug 2010 19:09:52 -0500, John Bokma wrote: > >> this means that Python should eliminate / optimize tail >> recursion. > > There have been various suggestions to add tail recursion optimization to > the language. Two problems: [snip] > But this is not the only sort of tail-call recursion, and a traceback > like the following is useful: > > >>>> recurse(4) > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in recurse > File "", line 3, in f > File "", line 5, in recurse > File "", line 3, in f > File "", line 5, in recurse > File "", line 3, in f > File "", line 4, in recurse > File "", line 2, in g > ValueError > > > If all you saw was the last line (the call to g), debugging the exception > would be significantly harder. Yup, agreed, good example. > Me personally, I'd like to see either a (preferably) run-time setting or > compile-time switch that enables/disables this optimization. Even an > explicit decorator would be fine. And lo and behold: > > http://hircus.wordpress.com/2008/06/21/python-tail-call-optimization-done-right/ > http://groups.google.com/group/comp.lang.python/msg/9b047d1392f2b8ec > > > Add it to your bag of tricks and have fun. Thanks for the links. And yes, I will add this to my bag of tricks (aka local wiki with notes ;-) ). -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From russ.paielli at gmail.com Sun Aug 22 14:36:35 2010 From: russ.paielli at gmail.com (Russ P.) Date: Sun, 22 Aug 2010 11:36:35 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: On Aug 22, 12:47?am, Chris Rebert wrote: > On Sun, Aug 22, 2010 at 12:23 AM, Russ P. wrote: > > On Aug 21, 1:33?am, Steven D'Aprano > cybersource.com.au> wrote: > >> On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: > >> > Most programmers probably never use vectors and matrices, so they don't > >> > care about the inconsistency with standard mathematical notation. > > >> Perhaps you should ask the numpy programmers what they think about that. > > > Why would I care in the least about something called "numpy"? > > Because it's a popular matrix math package for Python. Its users are > thus a subset of programmers which by definition don't fall into the > "most programmers" group you describe. Yes, I know what numpy is, and I'm sure it's great. I was just taking a light-hearted jab at the name. From raoulbia at gmail.com Sun Aug 22 15:03:04 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 22 Aug 2010 12:03:04 -0700 (PDT) Subject: comparing tuples References: <880a20dd-7a1f-467a-a215-e36dd0108d0e@i13g2000yqd.googlegroups.com> Message-ID: On Aug 22, 7:12?pm, Tim Chase wrote: > On 08/22/10 12:50, Baba wrote: > > > > > level: beginners > > > I was trying to write simple code that compares 2 tuples and returns > > any element in the second tuple that is not in the first tuple. > > > def tuples(t1, t2): > > ? ? ?result = [] > > ? ? ?for b in t2: > > ? ? ? ? ?for a in t1: > > ? ? ? ? ? ? ?if b == a: > > ? ? ? ? ? ? ? ? ?break > > ? ? ? ? ?else: > > ? ? ? ? ? ? ?result=result+[b,] > > ? ? ?return result > > > print tuples([0,5,6], [0,5,6,3,7]) > > > the code works but i was surprised by the following: my understanding > > was that an ELSE clause is part of an IF statement. Therefore it comes > > at the same indentation as the IF statement. > > The ELSE clause can be used either with an IF (as you know) or > with a FOR loop, which is interpreted as "if this loop reached > the end naturally instead of exiting via a BREAK statement, > execute this block of code". > > If you reach the end of t1 without having found a value (and then > issuing a "break"), then the current value of t2 (b) should be > appended to the result. > > That said, unless order matters, I'd just use sets: > > ? ?def tuples(t1, t2): > ? ? ?return list(set(t2)-set(t1)) > > which should have better performance characteristics for large > inputs. > > -tkc Thanks Tim! From nagle at animats.com Sun Aug 22 15:36:22 2010 From: nagle at animats.com (John Nagle) Date: Sun, 22 Aug 2010 12:36:22 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: <4c709a3c$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <874oen1p9r.fsf@castleamber.com> <4c709a3c$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4c717c2f$0$1602$742ec2ed@news.sonic.net> On 8/21/2010 8:32 PM, Steven D'Aprano wrote: > On Sat, 21 Aug 2010 19:09:52 -0500, John Bokma wrote: > >> this means that Python should eliminate / optimize tail >> recursion. > > There have been various suggestions to add tail recursion optimization to > the language. Two problems: > > > * It throws away information from tracebacks if the recursive function > fails; and > > * nobody willing to do the work is willing to champion it sufficiently to > get it approved in the face of opposition due to the above. I would rank tail recursion way down on the list of things which make CPython slow. (Unladen Swallow seems to have stalled. Last quarterly release, October 2009. Last wiki update, May 2010. Last issue advanced to "started" state, Feb. 2010. There are still code checkins, so somebody is still working, but little visible progress. They did get a JIT working, but discovered that the performance improvement was very slight. They wanted at least 5x; they got 1x to 2x at best.) John Nagle From julia.jacobson at arcor.de Sun Aug 22 15:53:51 2010 From: julia.jacobson at arcor.de (Julia Jacobson) Date: Sun, 22 Aug 2010 21:53:51 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database In-Reply-To: References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> Thanks a lot, this was the solution. It would be greate, if you could also show me a way to extract the inserted binary object from the table on the server to a file on a client. > Peter Otten wrote: >> Julia Jacobson wrote: >> >> Hello everybody out there using python, >> >> For the insertion of pictures into my PostgreSQL database [with table >> foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written >> the following script: >> >> #!/usr/bin/python >> import psycopg2 >> try: >> conn = psycopg2.connect("dbname='postgres' user='postgres' >> host='localhost' password='data'"); >> except: >> print "I am unable to connect to the database" >> cur = conn.cursor() >> f = open("test.bmp", 'rb') >> myfile = f.read() >> try: >> cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) >> except: >> print "Insert unsuccessful" >> >> "python script.py" runs the script without any errors or messages. >> However, the SQL command "SELECT * FROM foo" returns the output "foo (0 >> rows)" with no entries in the table. >> I'm using Python 2.7 and PostgreSQL 8.3. >> Could anyone help me to find a way to pin down the problem? > > Perhaps you need to conn.commit() your changes. From 1001nuits at gmail.com Sun Aug 22 17:40:55 2010 From: 1001nuits at gmail.com (1001nuits) Date: Sun, 22 Aug 2010 23:40:55 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> Message-ID: Le Sun, 22 Aug 2010 20:12:36 +0200, John Bokma a ?crit: > David Kastrup writes: > >> John Bokma writes: >> >>> David Kastrup writes: >>> >>>> John Passaniti writes: >>>> >>>>> Amen! All this academic talk is useless. Who cares about things >>>>> like >>>>> the big-O notation for program complexity. Can't people just *look* >>>>> at code and see how complex it is?! And take things like the years >>>>> of >>>>> wasted effort computer scientists have put into taking data >>>>> structures >>>>> (like hashes and various kinds of trees) and extending them along >>>>> various problem domains and requirements. Real programmers don't >>>>> waste their time with learning that junk. What good did any of that >>>>> ever do anyone?! >>>> >>>> It is my experience that in particular graduated (and in particular >>>> Phd) >>>> computer scientists don't waste their time _applying_ that junk. >>> >>> Question: do you have a degree in computer science? >>> >>> Since in my experience: people who talk about their experience with >>> graduated people often missed the boat themselves and think that >>> reading >>> a book or two equals years of study. >> >> I have a degree in electrical engineering. But that's similarly >> irrelevant. > > Nah, it's not: your attitude towards people with a degree in computer > science agrees with what I wrote. > >> That has not particularly helped my respect towards CS majors and PhDs >> in the function of programmers (and to be honest: their education is not >> intended to make them good programmers, but to enable them to _lead_ >> good programmers). > > I disagree. > >> That does not mean that I am incapable of analyzing, say quicksort and >> mergesort, > > Oh, that's what I was not implying. I am convinced that quite some > people who do self-study can end up with better understanding of things > than people who do it for a degree. I have done both: I already was > programming in several languages before I was studying CS. And my > experience is that a formal study in CS can't compare to home study > unless you're really good and have the time and drive to read formal > books written on CS. And my experience is that most self-educaters don't > have that time. > > On the other hand: some people I knew during my studies had no problem > at all with introducing countless memory leaks in small programs (and > turning off compiler warnings, because it gave so much noise...) > >> Donald Knuth never studied computer science. > > Yes, yes, and Albert Einstein worked at an office. > > Those people are very rare. > > But my experience (see for plenty of examples: Slashdot) is that quite > some people who don't have a degree think that all that formal education > is just some paper pushing and doesn't count. While some of those who do > have the paper think they know it all. Those people who are right in > either group are a minority in my experience. > > As for electrical engineering: done that (BSc) and one of my class mates > managed to connect a transformer the wrong way around.... twice. Yet he > had the highest mark in our class. > > So in short: yes, self-study can make you good at something. But > self-study IMO is not in general a replacement for a degree. Someone who > can become great after self-study would excel at a formal study and > learn more. Study works best if there is competition and if there are > challenges. I still study a lot at home, but I do miss the challenges > and competition. > Hi all, I quite agree with the fact that self learning is not enough. Another thing you learn in studying in University is the fact that you can be wrong, which is quite difficult to accept for self taught people. When you work in groups, you are bound to admit that you don't have the best solution all the time. To my experience, self-taught people I worked with had tremendous difficulties to accept that they were wrong, that their design was badly done, that their code was badly written or strangely designed. Because self teaching was done with a lot of efforts, in particular to figure out complex problems on their own. Most of the time, the self learned people are attached to the things they learned by themselves and have difficulties to envisage that being right of wrong is often not an issue provided the group comes to the best option. They often live contradiction as a personal offense while it is just work, you know. That's another interest of the degree, confrontation with other people that have the same background. And letting the things learned at the place they should be and not in the affective area. 1001 -- Utilisant le logiciel de courrier r?volutionnaire d'Opera : http://www.opera.com/mail/ From thomas at jollybox.de Sun Aug 22 18:04:07 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 23 Aug 2010 00:04:07 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database In-Reply-To: <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <201008230004.07741.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to Julia Jacobson to exclaim: > Thanks a lot, this was the solution. > It would be greate, if you could also show me a way to extract the > inserted binary object from the table on the server to a file on a client. Probably something along the lines of: * execute an appropriate SELECT query * get the record you're interested in * open a file for writing * f.write(data) * f.close() and other clean-up code > > > Peter Otten wrote: > >> Julia Jacobson wrote: > >> > >> Hello everybody out there using python, > >> > >> For the insertion of pictures into my PostgreSQL database [with table > >> foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written > >> the following script: > >> > >> #!/usr/bin/python > >> import psycopg2 > >> > >> try: > >> conn = psycopg2.connect("dbname='postgres' user='postgres' > >> > >> host='localhost' password='data'"); > >> > >> except: > >> print "I am unable to connect to the database" > >> > >> cur = conn.cursor() > >> f = open("test.bmp", 'rb') > >> myfile = f.read() > >> > >> try: > >> cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) > >> > >> except: > >> print "Insert unsuccessful" > >> > >> "python script.py" runs the script without any errors or messages. > >> However, the SQL command "SELECT * FROM foo" returns the output "foo (0 > >> rows)" with no entries in the table. > >> I'm using Python 2.7 and PostgreSQL 8.3. > >> Could anyone help me to find a way to pin down the problem? > > > > Perhaps you need to conn.commit() your changes. From sjmachin at lexicon.net Sun Aug 22 18:13:57 2010 From: sjmachin at lexicon.net (John Machin) Date: Sun, 22 Aug 2010 15:13:57 -0700 (PDT) Subject: Detect string has non-ASCII chars without checking each char? References: <4c713de4$0$5428$ba4acef3@reader.news.orange.fr> Message-ID: <32a05d75-01ff-4171-a2e4-bfbb90f67a61@i18g2000pro.googlegroups.com> On Aug 23, 1:10?am, "Michel Claveau - MVP" wrote: > Re ! > > > Try your code with u"abcd\xa1" ... it says it's ASCII. > > Ah? ?in my computer, it say "False" Perhaps your computer has a problem. Mine does this with both Python 2.7 and Python 2.3 (which introduced the unicodedata.normalize function): >>> import unicodedata >>> t1 = u"abcd\xa1" >>> t2 = unicodedata.normalize('NFD', t1) >>> t3 = t2.encode('ascii', 'replace') >>> [t1, t2, t3] [u'abcd\xa1', u'abcd\xa1', 'abcd?'] >>> map(len, _) [5, 5, 5] >>> From stef.mientki at gmail.com Sun Aug 22 19:12:41 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 23 Aug 2010 01:12:41 +0200 Subject: webbrowser module in Ubuntu 10, how to prevent forking ? Message-ID: <4C71AEE9.3000007@gmail.com> hello, I've an application where I need the rendering of webpages. The application is developed under windows where I can use IE-ActiveX component. To make the application platform independent I use the webbrowser module. (btw are there better options under wxPython ?) previously this worked quit well under (older versions) Ubuntu. But now every time I show a page through webbrowser I get a question about forking child or parent. Is there a way to prevent this question ? thanks, Stef Mientki From greg.ewing at canterbury.ac.nz Sun Aug 22 19:37:18 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 23 Aug 2010 11:37:18 +1200 Subject: expression in an if statement In-Reply-To: References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> Message-ID: <8ddq51FckaU1@mid.individual.net> Thomas Jollans wrote: > What if "set" has side effects? A > compiler could only exclude this possibility if it knew exactly what "set" > will be at run time, And also that 'a' remains bound to the same object, and that object or anything reachable from it is not mutated in any way that could affect the result of set(a). That's quite a lot of information for an optimiser to deduce, particularly in a language as dynamic as Python. -- Greg From psdasilva.nospam at netcabonospam.pt Sun Aug 22 22:49:56 2010 From: psdasilva.nospam at netcabonospam.pt (Paulo da Silva) Date: Mon, 23 Aug 2010 03:49:56 +0100 Subject: What is a class method? Message-ID: <4c71e1d7$0$1846$a729d347@news.telepac.pt> I understand the concept of a static method. However I don't know what is a class method. Would anybody pls. explain me? class C: @classmethod def ... ... Thanks From prologic at shortcircuit.net.au Sun Aug 22 23:30:19 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 23 Aug 2010 13:30:19 +1000 Subject: What is a class method? In-Reply-To: <4c71e1d7$0$1846$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> Message-ID: On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva wrote: > I understand the concept of a static method. > However I don't know what is a class method. > Would anybody pls. explain me? Please read this first: http://docs.python.org/library/functions.html#classmethod Then ask us questions :) cheers James -- -- James Mills -- -- "Problems are solved by method" From psdasilva.nospam at netcabonospam.pt Sun Aug 22 23:53:35 2010 From: psdasilva.nospam at netcabonospam.pt (Paulo da Silva) Date: Mon, 23 Aug 2010 04:53:35 +0100 Subject: What is a class method? In-Reply-To: References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> Message-ID: <4c71f0c1$0$1861$a729d347@news.telepac.pt> Em 23-08-2010 04:30, James Mills escreveu: > On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva > wrote: >> I understand the concept of a static method. >> However I don't know what is a class method. >> Would anybody pls. explain me? > > Please read this first: > http://docs.python.org/library/functions.html#classmethod > > Then ask us questions :) I did it before posting ... The "explanation" is not very clear. It is more like "how to use it". Thanks anyway. From prologic at shortcircuit.net.au Mon Aug 23 00:16:42 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 23 Aug 2010 14:16:42 +1000 Subject: What is a class method? In-Reply-To: <4c71f0c1$0$1861$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: On Mon, Aug 23, 2010 at 1:53 PM, Paulo da Silva wrote: > I did it before posting ... > The "explanation" is not very clear. It is more like "how to use it". Without going into the semantics of languages basically the differences are quite clear: @classmethod is a decorator that warps a function with passes the class as it's first argument. @staticmethod (much like C++/Java) is also a decorator that wraps a function but does not pass a class or instance as it's first argument. I won't go into the use-cases as I don't use static or class methods myself personally in any of my work (yet). cheers James -- -- James Mills -- -- "Problems are solved by method" From ian.g.kelly at gmail.com Mon Aug 23 01:16:45 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 22 Aug 2010 23:16:45 -0600 Subject: What is a class method? In-Reply-To: <4c71f0c1$0$1861$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: On Sun, Aug 22, 2010 at 9:53 PM, Paulo da Silva wrote: > Em 23-08-2010 04:30, James Mills escreveu: >> On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva >> wrote: >>> I understand the concept of a static method. >>> However I don't know what is a class method. >>> Would anybody pls. explain me? >> >> Please read this first: >> http://docs.python.org/library/functions.html#classmethod >> >> Then ask us questions :) > > I did it before posting ... > The "explanation" is not very clear. It is more like "how to use it". Consider this: class A(object): @staticmethod def new(): return A() class B(A): pass versus this: class C(object): @classmethod def new(cls): return cls() class D(C): pass B.new() will return a new instance of A, not B. D.new() will return a new instance of D. Does this answer your question? From tjreedy at udel.edu Mon Aug 23 01:26:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Aug 2010 01:26:07 -0400 Subject: What is a class method? In-Reply-To: <4c71f0c1$0$1861$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: On 8/22/2010 11:53 PM, Paulo da Silva wrote: >> Please read this first: >> http://docs.python.org/library/functions.html#classmethod >> >> Then ask us questions :) > > I did it before posting ... When you ask a question, it help people answer if they know what you have already tried and failed with ;-) > The "explanation" is not very clear. It is more like "how to use it". A function accessed as a class attribute is normal treated as an instance function/method -- with an instance of the class as the first argument. A class method takes the class as the first argument. A 'staticmethod' is a function that takes neither as the first argument and, with one esoteric exception, does not need to be a class attribute but is for convenience. -- Terry Jan Reedy From nagle at animats.com Mon Aug 23 02:24:59 2010 From: nagle at animats.com (John Nagle) Date: Sun, 22 Aug 2010 23:24:59 -0700 Subject: What is a class method? In-Reply-To: References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: <4c721434$0$1668$742ec2ed@news.sonic.net> On 8/22/2010 9:16 PM, James Mills wrote: > On Mon, Aug 23, 2010 at 1:53 PM, Paulo da Silva > wrote: >> I did it before posting ... >> The "explanation" is not very clear. It is more like "how to use it". > > Without going into the semantics of languages basically the > differences are quite clear: > > @classmethod is a decorator that warps a function with > passes the class as it's first argument. > > @staticmethod (much like C++/Java) is also a decorator that > wraps a function but does not pass a class or instance as > it's first argument. That reads like something the C++ standards revision committee would dream up as they add unnecessary template gimmicks to the language. John Nagle From julia.jacobson at arcor.de Mon Aug 23 03:37:13 2010 From: julia.jacobson at arcor.de (Julia Jacobson) Date: Mon, 23 Aug 2010 09:37:13 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database In-Reply-To: References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4c722526$0$6875$9b4e6d93@newsspool2.arcor-online.net> How can I assign the result of a SQL query to a variable? The following code snippet doesn't work: query_result=cur.execute("SELECT column_name FROM table_name WHERE my_variable = 'my_value'",) > Thomas Jollans wrote: > > * get the record you're interested in From __peter__ at web.de Mon Aug 23 04:13:36 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Aug 2010 10:13:36 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> <4c722526$0$6875$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Julia Jacobson wrote: > How can I assign the result of a SQL query to a variable? > The following code snippet doesn't work: > query_result=cur.execute("SELECT column_name FROM table_name WHERE > my_variable = 'my_value'",) To retrieve an image from a table "images" by its name you could do (untested): name = "image001.jpg" row = cur.execute("select image from images where name = %s", (name,)).fetchone() if row is None: raise ValueError("no image %r found" % name) image = row[0] From sschwarzer at sschwarzer.net Mon Aug 23 04:15:56 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 23 Aug 2010 10:15:56 +0200 Subject: Open a command pipe for reading In-Reply-To: References: Message-ID: <4C722E3C.5010206@sschwarzer.net> Hi Rodrick, On 2010-08-17 18:40, Rodrick Brown wrote: > I have a fairly large file 1-2GB in size that I need to > process line by line but I first need to convert the file > to text using a 3rd party tool that prints the records > also line by line. > > I've tried using Popen to do this with no luck. I'm trying > to simulate > > /bin/foo myfile.dat Is foo the 3rd-party conversion tool you've mentioned? It would be good to have a bit more context, e. g. an actual snippet from your code. > And as the records are being printed do some calculations. > > pipe = Popen(exttool,shell=True,stdout=PIPE).stdout > > for data in pipe.readlines(): > print data, > > This operation blocks forever I'm guessing it's trying to > process the entire file at once. If you use `readlines` on a file object it reads the whole file at once and returns a list of the lines (including line end characters, by the way). What you probably want is for line in pipe: print line, which reads and prints the file contents line by line. Stefan From ldo at geek-central.gen.new_zealand Mon Aug 23 04:34:48 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 23 Aug 2010 20:34:48 +1200 Subject: Python Developer - HFT Trading firm - Chicago, IL References: <8dbb89Fi3fU1@mid.individual.net> Message-ID: In message <8dbb89Fi3fU1 at mid.individual.net>, Gregory Ewing wrote: > Lawrence D'Oliveiro wrote: > >> Someone who doesn?t understand how positive feedback can lead to >> instabilities in a dynamical system. > > Let's hope the person they hire makes it his first task > to introduce a big dollop of negative feedback into the > system! Actually the normal way to prevent instabilities is to add damping to leak the energy away. In an economic system, that?s generally called ?Government regulation?. From graemeglass at gmail.com Mon Aug 23 04:42:23 2010 From: graemeglass at gmail.com (Graeme Glass) Date: Mon, 23 Aug 2010 01:42:23 -0700 (PDT) Subject: psycopg2 for insertion of binary data to PostgreSQL database References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> <4c722526$0$6875$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Aug 23, 9:37?am, Julia Jacobson wrote: > How can I assign the result of a SQL query to a variable? > The following code snippet doesn't work: > query_result=cur.execute("SELECT column_name FROM table_name WHERE > my_variable = 'my_value'",) > > ?> Thomas Jollans wrote: > > > > > * get the record you're interested in You need to go and fetch the data now. query_result.fetchone() Take a look at the docs here, on how to fetch one vs many rows (fetchmany) http://initd.org/psycopg/docs/cursor.html#cursor.fetchone hth, Graeme From pDOTpagel at wzw.tum.de Mon Aug 23 05:03:35 2010 From: pDOTpagel at wzw.tum.de (Philipp Pagel) Date: Mon, 23 Aug 2010 09:03:35 +0000 (UTC) Subject: Creating a PYD file References: Message-ID: Rony wrote: > Is a PYD file created from Pyrex faster in execution then a PYD file > created from python source ? What do you mean? An African or European swallow? Of course it depends on your choice of algorithm, programmer ability.familarity with the respective langugage, ... cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://webclu.bio.wzw.tum.de/~pagel/ From easymakerere at gmail.com Mon Aug 23 05:08:50 2010 From: easymakerere at gmail.com (kimjeng) Date: Mon, 23 Aug 2010 02:08:50 -0700 (PDT) Subject: vpython References: Message-ID: On Aug 22, 7:38?am, Anssi Saari wrote: > kimjeng writes: > > the thing is i have installed gtkglextmm both from source and via a > > slackbuilds package script and i still get the same error, > > help would be a appreciated > > You'll just have to check what it is configure actually tests for and > figure out from that why your system doesn't pass. thanks here's something i noticed ... Package gtkglextmm-1.2 was not found in the pkg-config search path. Perhaps you should add the directory containing `gtkglextmm-1.2.pc' to the PKG_CONFIG_PATH environment variable No package 'gtkglextmm-1.2' found ... the configure script is looking for gtkglextmm-1.2.pc , a file that does not exist, what i do have is gtkglext-1.0.pc , im wondering why i have the 1.0. version while i built the 1.2. source , plus the 'mm' in the name is missing from the name of my .pc files thanks From jhullu at gmail.com Mon Aug 23 06:15:46 2010 From: jhullu at gmail.com (jacquesh) Date: Mon, 23 Aug 2010 03:15:46 -0700 (PDT) Subject: Global Hook for Window Creation and Destruction Message-ID: hello, I'm looking for a sample using a Global Hook for Window Creation and Destruction in python 2.6 in win32 env... I've found some samples in c# or delphi but nothing in python. I'll try to catch any WM_CREATE events, like pyHook do to catch event from keyboard and mouse... any idea ? thx From oss.elmar at googlemail.com Mon Aug 23 06:24:50 2010 From: oss.elmar at googlemail.com (Elmar Hinz) Date: Mon, 23 Aug 2010 12:24:50 +0200 Subject: Gentoo, Cygwin: Import Error time, cStringIO, Permission denied Message-ID: Hello all, I freshly subscribed to this list, because I search a solution for a very special problem. Is this the appropriate list? Context ====== I try if it is possible to bootstrap Gentoo Prefix, upon the Cygwin compatibility layer on Windows. Gentoo Prefix is not a virtual machine but a bundle of Gentoo programs compiled into a nonstandard directory on a host OS. IT is similar to Cygwin itself, but compiled from sources. I try to compile Prefix into Cygwin on Windows. This involves compiling python. The gentoo management tool "emerge" is done in python. However I am not a Python programmer myself, so I have some difficulties to understand what is going on. Problem ====== After compiling pyhton I run into errors when I start to use it in form of emerge. It says something like this in the logger module: Import Error sys, os, types, time, string, cStringIO, traceback. Permission denied. I researched the web. One discssion told to try it on the pyhton shell. I did the same. Only "time" and "cStringIO" are not imported. Looking into the compiled sources i find cStringIO.dll and time.dll. Both have the permissions 755. Hence permission to run them should be given. Is it a path problem? Are environment variables wrong? I would expect in that case python would complain "Modules not found" instead of "Permission denied". I am at the end of my wits now. Al From stefan_ml at behnel.de Mon Aug 23 06:34:45 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 23 Aug 2010 12:34:45 +0200 Subject: Creating a PYD file In-Reply-To: <201008192047.10460.thomas@jollybox.de> References: <201008192047.10460.thomas@jollybox.de> Message-ID: Thomas Jollans, 19.08.2010 20:47: > On Thursday 19 August 2010, it occurred to Rony to exclaim: >> Is a PYD file created from Pyrex faster in execution then a PYD file >> created from python source ? > > How do you plan to create an extension module (*.so, *.pyd on Windows) from > Python source then? You can try to compile it using Cython. Stefan From oss.elmar at googlemail.com Mon Aug 23 06:41:48 2010 From: oss.elmar at googlemail.com (Elmar Hinz) Date: Mon, 23 Aug 2010 12:41:48 +0200 Subject: Gentoo, Cygwin: Import Error time, cStringIO, Permission denied In-Reply-To: References: Message-ID: > Problem > ====== > > After compiling pyhton I run into errors when I start to use it in > form of emerge. It says something like this in the logger module: > > Import Error sys, os, types, time, string, cStringIO, traceback. > Permission denied. > > I researched the web. One discssion told to try it on the pyhton > shell. I did the same. Only "time" and "cStringIO" are not imported. > > Looking into the compiled sources i find cStringIO.dll and time.dll. > Both have the permissions 755. Hence permission to run them should be > given. > I tried something different. I tried to run emerge with Cygwins precompiled python. In this case I get a related but different error: fatal error - unable to map \\?\F:\cygwin\lib\pyhton2.6\lib-dynload\time.dll to same address as parent: 0x330000 != 0x3A0000 What does this mean? Is there a naming conflict between pythons time.dll and a time.dll of the windows system? Al From mail at johnohagan.com Mon Aug 23 06:47:56 2010 From: mail at johnohagan.com (John O'Hagan) Date: Mon, 23 Aug 2010 10:47:56 +0000 Subject: Helper classes design question Message-ID: <201008231047.57128.mail@johnohagan.com> I want to know the best way to organise a bunch of functions designed to operate on instances of a given class without cluttering the class itself with a bunch of unrelated methods. What I've done is make what I think are called helper classes, each of which are initialized with an instance of the main class and has methods which are all of the same type (insofar as they return a boolean, or modify the object in place, or whatever). I'm not sure if I'm on the right track here design-wise. Maybe this could be better done with inheritance (not my forte), but my first thought is that no, the helper classes (if that's what they are) are not actually a type of the main class, but are auxiliary to it. Here's what I've done: I have a class MySequence which is initialized with a number sequence (in a list), which has a bunch of methods which deal with various (musical) properties of the sequence. Toy example: class MySequence(object): """MySequence, a representation musical sequences as numbers. Its methods return various characteristics of the sequence.""" def __init__(self, sequence): self.pitches = sequence[:] def pcset(self): """Example method: The pitch class set derived from the sequence""" return sorted(list(set([ i % 12 for i in self.pitches]))) A generator function spits out MySequence objects, and I want to filter them (i.e. reject those which do not meet certain criteria) and then be able to modify them in various ways. For that I have two classes; toy examples: class SeqTest(object): """SeqTest, initialized with a MySequence object. Its methods return the boolean result of tests against the Sequence object.""" def __init__(self, myseq_obj): self.seq = myseq_obj def degrees(self, degrees): """Example method: Test for certain members, passed as list""" return all(i in self.seq.pcset() for i in degrees) class SeqMod(object): """A SeqMod object's methods modify in place the MySequence object with which it is initialized """ def __init__(self, myseq_obj): self.seq = myseq_obj def rotate(self, num): """Example method: Rotate pitches by n steps""" self.seq.pitches = self.seq.pitches[-num:] + self.seq.pitches[:-num] And here is a toy version of how I'm using them with the generator: def seq_factory(generator_func, test_opts, mod_opts): """Yields Sequence objects, filtered and modified. Opts are dictionaries.""" for sequence in generator_func: seq = MySequence(sequence) tester = SeqTest(seq) if any (not getattr(tester, opt)(value) for opt, value in test_opts.items()): continue modifier = SeqMod(seq) for opt, value in mod_opts.items(): getattr(modifier, opt)(value) yield seq Used, say, like this: generator_func = (range(n, n+5) for n in range(5)) test_opts = {'degrees': [5,7]} mod_opts = {'rotate': 3} for i in seq_factory(generator_func, test_opts, mod_opts): print i.pitches Which yields: [5, 6, 7, 3, 4] [6, 7, 8, 4, 5] It actually works well, so there's no real problem apart from wanting to know if this is a good way to do what I want. Thanks for any wise words, John From stefan_ml at behnel.de Mon Aug 23 07:02:01 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 23 Aug 2010 13:02:01 +0200 Subject: Creating a PYD file In-Reply-To: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> References: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> Message-ID: Rony, 19.08.2010 21:41: > The question actually is, is a PYD file created from C faster then a > PYD file from Pyrex ? Most likely, yes. However, when comparing to Cython instead of Pyrex, the answer really depends on your code. Cython cannot be faster than the equivalent C code, simply because it generates C code. However, if the Python call overhead matters (e.g. in thin wrappers around simple C functions), Cython easily wins because it uses various tweaks that you simply wouldn't write in your own C code. If the overhead can be ignored, hand tuned C code wins often but not always, with the obvious drawback of being much harder to write and much longer in lines of code. Generally speaking, if you can avoid it, don't write the extension in C. You'll have your Cython code hand optimised long before your C code is even close to running. And in the long run, the maintenance cost will always be the dominating factor anyway. Stefan From __peter__ at web.de Mon Aug 23 07:33:07 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Aug 2010 13:33:07 +0200 Subject: Helper classes design question References: Message-ID: John O'Hagan wrote: > I want to know the best way to organise a bunch of functions designed to > operate on instances of a given class without cluttering the class itself > with a bunch of unrelated methods. > > What I've done is make what I think are called helper classes, each of > which are initialized with an instance of the main class and has methods > which are all of the same type (insofar as they return a boolean, or > modify the object in place, or whatever). > > I'm not sure if I'm on the right track here design-wise. Maybe this could > be better done with inheritance (not my forte), but my first thought is > that no, the helper classes (if that's what they are) are not actually a > type of the main class, but are auxiliary to it. > > Here's what I've done: > > I have a class MySequence which is initialized with a number sequence (in > a list), which has a bunch of methods which deal with various (musical) > properties of the sequence. Toy example: > > class MySequence(object): > """MySequence, a representation musical sequences as numbers. > Its methods return various characteristics of the sequence.""" > def __init__(self, sequence): > self.pitches = sequence[:] > def pcset(self): > """Example method: The pitch class set > derived from the sequence""" > return sorted(list(set([ i % 12 for i in self.pitches]))) > > A generator function spits out MySequence objects, and I want to filter > them (i.e. reject those which do not meet certain criteria) and then be > able to modify them in various ways. For that I have two classes; toy > examples: > > class SeqTest(object): > """SeqTest, initialized with a MySequence object. Its methods > return the boolean result of tests against the Sequence object.""" > def __init__(self, myseq_obj): > self.seq = myseq_obj > def degrees(self, degrees): > """Example method: Test for certain members, passed as list""" > return all(i in self.seq.pcset() for i in degrees) > > class SeqMod(object): > """A SeqMod object's methods modify in place > the MySequence object with which it is initialized """ > def __init__(self, myseq_obj): > self.seq = myseq_obj > def rotate(self, num): > """Example method: Rotate pitches by n steps""" > self.seq.pitches = self.seq.pitches[-num:] + > self.seq.pitches[:-num] > > > And here is a toy version of how I'm using them with the generator: > > def seq_factory(generator_func, test_opts, mod_opts): > """Yields Sequence objects, filtered and modified. > Opts are dictionaries.""" > for sequence in generator_func: > seq = MySequence(sequence) > tester = SeqTest(seq) > if any (not getattr(tester, opt)(value) > for opt, value in test_opts.items()): > continue > modifier = SeqMod(seq) > for opt, value in mod_opts.items(): > getattr(modifier, opt)(value) > yield seq > > > Used, say, like this: > > generator_func = (range(n, n+5) for n in range(5)) > test_opts = {'degrees': [5,7]} > mod_opts = {'rotate': 3} > > for i in seq_factory(generator_func, test_opts, mod_opts): > print i.pitches > > Which yields: > > [5, 6, 7, 3, 4] > [6, 7, 8, 4, 5] > > It actually works well, so there's no real problem apart from wanting to > know if this is a good way to do what I want. > > Thanks for any wise words, As far as I can see the SeqMod and SeqTest classes don't keep any state apart from the sequence instance. Therefore functions instead of methods would do as well: from functools import partial class MySequence(object): def __init__(self, sequence): self.pitches = sequence[:] def pcset(self): return sorted(list(set([ i % 12 for i in self.pitches]))) def degrees(seq, degrees): return all(i in seq.pcset() for i in degrees) def rotate(seq, num): seq.pitches = seq.pitches[-num:] + seq.pitches[:-num] def seq_factory(sequences, tests, modifications): for seq in sequences: if all(test(seq) for test in tests): for modify in modifications: modify(seq) yield seq sequences = (MySequence(range(n, n+5)) for n in range(5)) tests = [ partial(degrees, degrees=[5,7]), # ... ] modifications = [ partial(rotate, num=3), # ... ] for i in seq_factory(sequences, tests, modifications): print i.pitches When you see that your module becomes too messy move the testing and modifying functions into separate modules that are part of the same package. Peter From oss.elmar at googlemail.com Mon Aug 23 07:37:44 2010 From: oss.elmar at googlemail.com (Elmar Hinz) Date: Mon, 23 Aug 2010 13:37:44 +0200 Subject: SOLVED: Gentoo, Cygwin: Import Error time, cStringIO, Permission denied Message-ID: I seem to talk to myself. So for the archives: This is no python thingy. It is a windows/cygwin one. The second error message brings good search results in the web. Search for: "cygwin, dll to same address as parent, rebaseall" Al From madhusoodan.shanbhag at gmail.com Mon Aug 23 07:50:01 2010 From: madhusoodan.shanbhag at gmail.com (Madhusoodan) Date: Mon, 23 Aug 2010 04:50:01 -0700 (PDT) Subject: DDE Module for Python 3.1.2 Message-ID: Hi Members, I am learning python 3.1.2 on windows XP. I wanted to do experiments on importing real time data from QuoteCenter with DDE. After searching relevant module, I found dde module only for Python 2.6, but not for 3.1.2. Kindly guide me if there is any other way I can communicate with DDE server for requesting data with Python 3.X. Thanks and Regards madhusoodan From parvini_navid at yahoo.com Mon Aug 23 08:00:02 2010 From: parvini_navid at yahoo.com (Navid Parvini) Date: Mon, 23 Aug 2010 05:00:02 -0700 (PDT) Subject: import a module in a destructor of a class Message-ID: <157673.25880.qm@web51006.mail.re2.yahoo.com> Dear All, I have a python module named "book.py" I want to import it in a destructor of a class. class Excel: ? ??? def __init__( self, ... ): ??????????? . . . ??? def __del__( self ): ????????? import book but I got error. Would you please help me? Can I import a module in a destructor? Thank you in advance. Regards, Navid -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Aug 23 08:02:01 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 23 Aug 2010 14:02:01 +0200 Subject: DDE Module for Python 3.1.2 In-Reply-To: References: Message-ID: Madhusoodan, 23.08.2010 13:50: > I am learning python 3.1.2 on windows XP. I wanted to do experiments > on importing real time data from QuoteCenter with DDE. What's DDE here? > After searching > relevant module, I found dde module only for Python 2.6, but not for > 3.1.2. Could you provide a link to the module, so that we know what module you are actually talking about? Also, if the project that provides the module has a mailing list, you might want to ask there. Stefan From mail at timgolden.me.uk Mon Aug 23 08:12:02 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 23 Aug 2010 13:12:02 +0100 Subject: DDE Module for Python 3.1.2 In-Reply-To: References: Message-ID: <4C726592.7010406@timgolden.me.uk> On 23/08/2010 13:02, Stefan Behnel wrote: > Madhusoodan, 23.08.2010 13:50: >> I am learning python 3.1.2 on windows XP. I wanted to do experiments >> on importing real time data from QuoteCenter with DDE. > > What's DDE here? It'll be Microsoft's Dynamic Data Exchange : http://msdn.microsoft.com/en-us/library/ms648711%28VS.85%29.aspx Didn't know anyone was still using it explicitly. > > >> After searching >> relevant module, I found dde module only for Python 2.6, but not for >> 3.1.2. > > Could you provide a link to the module, so that we know what module you > are actually talking about? I expect that'll be the dde module in the pywin32 packages: http://pywin32.cvs.sourceforge.net/viewvc/pywin32/pywin32/win32/Demos/dde/ I haven't run any tests against it, but it imports ok on my 3.1.2 instance (albeit after importing win32ui) TJG From clp2 at rebertia.com Mon Aug 23 08:33:58 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 23 Aug 2010 05:33:58 -0700 Subject: import a module in a destructor of a class In-Reply-To: <157673.25880.qm@web51006.mail.re2.yahoo.com> References: <157673.25880.qm@web51006.mail.re2.yahoo.com> Message-ID: On Mon, Aug 23, 2010 at 5:00 AM, Navid Parvini wrote: > Dear All, > > I have a python module named "book.py" I want to import it in a destructor of a class. > > class Excel: > > ??? def __init__( self, ... ): > ??????????? . . . > > ??? def __del__( self ): > ????????? import book > > but I got error. And the exact error message and exception traceback were...? Cheers, Chris -- Vagueness makes questions harder to answer. http://blog.rebertia.com From __peter__ at web.de Mon Aug 23 08:41:57 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Aug 2010 14:41:57 +0200 Subject: import a module in a destructor of a class References: <157673.25880.qm@web51006.mail.re2.yahoo.com> Message-ID: Navid Parvini wrote: > I have a python module named "book.py" I want to import it in a destructor > of a class. Why would you do that? > class Excel: > > def __init__( self, ... ): > . . . > > def __del__( self ): > import book > > but I got error. Would you please help me? Can I import a module in a > destructor? > > Thank you in advance. You may be able to avoid the ImportError by moving the instance from the global scope into a function, e. g. instead of e = Excel() # work with e do def main(): e = Excel() # work with e main() but the more appropriate answer is likely: Don't use __del__() at all. Peter From chris at simplistix.co.uk Mon Aug 23 09:10:29 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 23 Aug 2010 14:10:29 +0100 Subject: Sphinx cross reference question In-Reply-To: <4C716774.5090207@shopzeus.com> References: <4C716774.5090207@shopzeus.com> Message-ID: <4C727345.8010500@simplistix.co.uk> Laszlo Nagy wrote: > > In my shopzeus.db.pivot.convert.py file, in the run() method of my > Data2Facts class, I can write this into the docstring: ...you may have more joy asking about this on the Sphinx list: http://groups.google.com/group/sphinx-dev cheers, Chris From chris at simplistix.co.uk Mon Aug 23 09:16:14 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 23 Aug 2010 14:16:14 +0100 Subject: nested subparsers with argparse Message-ID: <4C72749E.1000706@simplistix.co.uk> Hi All, I'm looking to build a script that has command line options as follows: ./myscript.py command subcommand [options] I can do up to the command [options] bit with add_subparsers in argparse, but how do I then add a second level of subparsers? cheers, Chris From a.j.romanista at gmail.com Mon Aug 23 09:34:26 2010 From: a.j.romanista at gmail.com (Ata Jafari) Date: Mon, 23 Aug 2010 06:34:26 -0700 (PDT) Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: On Aug 20, 10:04?pm, Thomas Jollans wrote: > On Thursday 19 August 2010, it occurred to ata.jaf to exclaim: > > > > > On Aug 17, 11:55 pm, Thomas Jollans wrote: > > > On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > > > > I am developing a little program in Mac with wxPython. > > > > But I have problems with the characters that are not in ASCII. Like > > > > some special characters in French or Turkish. > > > > So I am looking for a way to solve this. Like an encoding standard > > > > that supports all languages. Or some other way. > > > > Anything that supports all of Unicode will do. Like UTF-8. If your text > > > is mostly Latin, then just go for UTF-8, if you use other alphabets > > > extensively, you might want to consider UTF-16, which might the use a > > > little less space. > > > OK, I used UTF-8. > > I write a line of strings in the source code and I want my program to > > show that as an output on GUI. And this line of strings includes a > > character like "?". But I see that in GUI this character is replaced > > with another strange characters. I mean it doesn't work. > > And when I try to use UTF-16, I get an syntax error that declares > > "UTF-16 stream does not start with BOM". > > I get the feeling you're not actually using the encoding you say you're using, > or not telling every program involved what you're doing. > > 1. Save the file in the correct encoding. Either tell your text editor to use > a specific encoding (UTF-8 would be a good choice), or find out what encoding > your text editor is using and use that encoding during the rest of the > process. > > 2. Tell Python which encoding you're using. The coding: line will do the > trick, *provided* you don't lie, and the encoding your specify in the file is > actually the encoding you're using to store the file on disk. > > 3. Instruct your GUI library to do the right thing. If you use unicode strings > (either by using Python 3 or by using the u"K?se" syntax in Python 2), that > should be enough, otherwise, if you're using byte strings, which you shouldn't > be doing in this case, you might have to tell the library what you're doing, > or use the customary encoding. (For GTK+, this is UTF-8. For other libraries, > it might be Latin-1, or system-dependent) Finally I did it. I was doing some stupid mistakes. Thanks alot. Ata From fmanley at gmail.com Mon Aug 23 09:45:04 2010 From: fmanley at gmail.com (Frederick Manley) Date: Mon, 23 Aug 2010 09:45:04 -0400 Subject: IDLE will not startup after upgrading Python on Mac OS X Message-ID: I have snow leopard and a brand new mac book pro. After running python from x11, I saw that I had python 2.5.1 installed on this laptop, so went to python.org to download Python 2.7, as I was "strongly encouraged" to do on the website. The problem is that Mac doesn't come with a text editor for writing programs. TextEdit won't allow you to save files with the ".py" extension. So IDLE is really my only choice. The only problem is, whenever I start it up (I've tried starting it from the Terminal and double clicking the icon) I get the following message: "Idle's subprocess cannot make connection. Either Idle can't start a subprocess or a personal firewall is blocking the connection." Searching various programming forums came up with similar problems users have had in windows, but I couldn't find any information on how to fix this problem on a mac with OSX. Please help. Thanks, Fred -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Mon Aug 23 09:55:31 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 23 Aug 2010 06:55:31 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: On Aug 21, 8:10?am, Tim Golden wrote: > On 20/08/2010 11:54 PM, vsoler wrote: > > > I'am testing your library. I am mainly interested in knowing the > > access attributes of directories in the local(C:\) or shared unit(W:\) > > of my system. > > > Using your script with 'c:\\' I get an error message saying... 'file > > exists but it is a directory' and I cannot go any further. > > > Of course, the problem is that I am using "fs.file" when I should be > > using something different. > > Either use fs.dir (if you know it's a directory) or fs.entry (if it > could be a file or a directory; the code will dispatch to the right one). > > If you only want the directories immediately some directory, > you could do this: > > > from winsys import fs, security > > root = fs.file (sys.executable).path ?# or fs.dir ("w:/") etc. > for d in root.dirs (ignore_access_errors=True): > ? ?print (d, "=>", d.security ()) # or whatever > > > > If you want to walk the tree of directories looking at permissions, then: > > > import os, sys > from winsys import fs > > root = fs.file (sys.executable).path > for dirpath, _, _ in root.walk (): > ? ?print (dirpath, "=>", dirpath.security ()) > > > > > Reading the doc I have found that I should be using os.walk(...), > > which works, but then I cannot use fs.file > > In fact, even if you did for some reason use os.walk, you can > easily wrap the returned filenames using fs.entry: > > > import os, sys > from winsys import fs > > root = os.path.dirname (sys.executable) > for dirpath, filenames, dirnames in os.walk (root): > ? ?print (dirpath, "=>", fs.entry (dirpath).security ()) > > > > TKG Tim, One of your scripts still does not work on my system: ==> If you want to walk the tree of directories looking at permissions, then: import os, sys from winsys import fs root = fs.file (sys.executable).path for dirpath, _, _ in root.walk (): print (dirpath, "=>", dirpath.security ()) However, I get the following error: Traceback (most recent call last): File "C:/Local/test4.py", line 5, in root = fs.file (r'W:\FRIB\ELPR\$DATA\DPT-FINANZAS').path File "C:\Program Files\Python31\lib\site-packages\winsys\fs.py", line 1775, in file raise x_fs (None, "file", "%s exists but is a directory" % filepath) winsys.fs.x_fs: (None, 'file', 'W:\\FRIB\\ELPR\\$DATA\\DPT-FINANZAS exists but is a directory') That is, I am interested in looking for directories, but the problem is that the path is a directory. I'm sure there must be some way to get around this problem. Thank you Vicente Soler From dsdale24 at gmail.com Mon Aug 23 09:58:16 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Mon, 23 Aug 2010 06:58:16 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X Message-ID: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> The following script runs without problems on Ubuntu and Windows 7. h5py is a package wrapping the hdf5 library (http://code.google.com/p/ h5py/): from multiprocessing import Pool import h5py def update(i): print i def f(i): "hello foo" return i*i if __name__ == '__main__': pool = Pool() for i in range(10): pool.apply_async(f, [i], callback=update) pool.close() pool.join() On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to comment out the as-yet unused h5py import, otherwise I get a traceback: Exception in thread Thread-1: Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/threading.py", line 532, in __bootstrap_inner self.run() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/threading.py", line 484, in run self.__target(*self.__args, **self.__kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/multiprocessing/pool.py", line 226, in _handle_tasks put(task) PicklingError: Can't pickle : attribute lookup __builtin__.function failed I've searched that pickle error and found some references to pickling a lambda, but I don't think that is the issue. There are no lambdas in the h5py module, and the script runs fine on windows and linux. I need access to both multiprocessing and h5py objects in the same module, so I can register a callback that saves the results to an hdf5 file. Are there any suggestions as to what could be the problem, or suggestions on how I can track it down? Thanks, Darren From mahaboobnisha at gmail.com Mon Aug 23 09:59:01 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Mon, 23 Aug 2010 06:59:01 -0700 (PDT) Subject: comp.lang.python Message-ID: <190fadcc-250d-454a-a0a5-62dd98829e24@u31g2000pru.googlegroups.com> www.127760.blogspot.com From benjamin.kaplan at case.edu Mon Aug 23 10:05:36 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 23 Aug 2010 10:05:36 -0400 Subject: IDLE will not startup after upgrading Python on Mac OS X In-Reply-To: References: Message-ID: On Mon, Aug 23, 2010 at 9:45 AM, Frederick Manley wrote: > I have snow leopard and a brand new mac book pro. ?After running python from > x11, I saw that I had python 2.5.1 installed on this laptop, That should be 2.6.1 if you're on Snow Leopard. Also, why were you running Python from an xterm? Just use Terminal.app. > so went to > python.org to download Python 2.7, as I was "strongly encouraged" to do on > the website. > The problem is that Mac doesn't come with a text editor for writing > programs. ?TextEdit won't allow you to save files with the ".py" extension. Yes it will. You just have to turn it to plain text mode first. It's in the format menu. Then, just add the .py extension to the file name when you go to save it. You'll get an annoying little "do you want to use .py or .txt" message box. > ?So IDLE is really my only choice. Vim and emacs are both installed on the machine. Or you can install MacVim. Or whatever GUI version of Emacs there is. Or you can install TextMate if you don't want to learn those. Or you can install XCode or Eclipse+PyDev if you want an IDE. Or Eric or Komodo Edit. Or any of a dozen others. >The only problem is, whenever I start it > up (I've tried starting it from the Terminal and double clicking the icon) I > get the following message: > "Idle's subprocess cannot make connection. ?Either Idle can't start a > subprocess or a personal firewall is blocking the connection." > Searching various programming forums came up with similar problems users > have had in windows, but I couldn't find any information on how to fix this > problem on a mac with OSX. ?Please help. >From the title, this may be relevant, but I'm not sure because I'm having trouble accessing the bug tracker right now. http://bugs.python.org/issue9227 Also, this one: http://bugs.python.org/issue9620 > Thanks, > Fred > -- > http://mail.python.org/mailman/listinfo/python-list > > From mail at timgolden.me.uk Mon Aug 23 10:07:03 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 23 Aug 2010 15:07:03 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: <4C728087.3080500@timgolden.me.uk> On 23/08/2010 14:55, vsoler wrote: > On Aug 21, 8:10 am, Tim Golden wrote: >> On 20/08/2010 11:54 PM, vsoler wrote: >> >>> I'am testing your library. I am mainly interested in knowing the >>> access attributes of directories in the local(C:\) or shared unit(W:\) >>> of my system. >> >>> Using your script with 'c:\\' I get an error message saying... 'file >>> exists but it is a directory' and I cannot go any further. >> >>> Of course, the problem is that I am using "fs.file" when I should be >>> using something different. >> >> Either use fs.dir (if you know it's a directory) or fs.entry (if it >> could be a file or a directory; the code will dispatch to the right one). >> >> If you only want the directories immediately some directory, >> you could do this: >> >> >> from winsys import fs, security >> >> root = fs.file (sys.executable).path # or fs.dir ("w:/") etc. >> for d in root.dirs (ignore_access_errors=True): >> print (d, "=>", d.security ()) # or whatever >> >> >> >> If you want to walk the tree of directories looking at permissions, then: >> >> >> import os, sys >> from winsys import fs >> >> root = fs.file (sys.executable).path >> for dirpath, _, _ in root.walk (): >> print (dirpath, "=>", dirpath.security ()) >> >> >> >>> Reading the doc I have found that I should be using os.walk(...), >>> which works, but then I cannot use fs.file >> >> In fact, even if you did for some reason use os.walk, you can >> easily wrap the returned filenames using fs.entry: >> >> >> import os, sys >> from winsys import fs >> >> root = os.path.dirname (sys.executable) >> for dirpath, filenames, dirnames in os.walk (root): >> print (dirpath, "=>", fs.entry (dirpath).security ()) >> >> >> >> TKG > > Tim, > > One of your scripts still does not work on my system: > > > ==> If you want to walk the tree of directories looking at > permissions, then: > > > import os, sys > from winsys import fs > > root = fs.file (sys.executable).path > for dirpath, _, _ in root.walk (): > print (dirpath, "=>", dirpath.security ()) > > > However, I get the following error: > > Traceback (most recent call last): > File "C:/Local/test4.py", line 5, in > root = fs.file (r'W:\FRIB\ELPR\$DATA\DPT-FINANZAS').path > File "C:\Program Files\Python31\lib\site-packages\winsys\fs.py", > line 1775, in file > raise x_fs (None, "file", "%s exists but is a directory" % > filepath) > winsys.fs.x_fs: (None, 'file', 'W:\\FRIB\\ELPR\\$DATA\\DPT-FINANZAS > exists but is a directory') > > That is, I am interested in looking for directories, but the problem > is that the path is a directory. > > I'm sure there must be some way to get around this problem. Replace fs.file by fs.entry: the latter detects automatically whether it's looking at a file or at a directory. I used fs.file in my example because I *know&* what sys.executable must be a file (python.exe). In your case, either use fs.dir if you know it's a directory or fs.entry if it could be either. (Obviously fs.entry must do some work to determine which it is, so you can optimise slightly by specifying fs.dir / fs.file) TJG From chris at simplistix.co.uk Mon Aug 23 10:19:30 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 23 Aug 2010 15:19:30 +0100 Subject: nested subparsers with argparse In-Reply-To: <4C72749E.1000706@simplistix.co.uk> References: <4C72749E.1000706@simplistix.co.uk> Message-ID: <4C728372.4020504@simplistix.co.uk> Chris Withers wrote: > Hi All, > > I'm looking to build a script that has command line options as follows: > > ./myscript.py command subcommand [options] > > I can do up to the command [options] bit with add_subparsers in > argparse, but how do I then add a second level of subparsers? Answering my own question, here's what worked for me: """ from argparse import ArgumentParser from mock import Mock m = Mock() parser = ArgumentParser() subparsers = parser.add_subparsers() agroup = subparsers.add_parser('a') command = subparsers.add_parser('b') command.set_defaults(func=m.b) subparsers = agroup.add_subparsers() command = subparsers.add_parser('aa') command.set_defaults(func=m.a.a) command = subparsers.add_parser('ab') command.set_defaults(func=m.a.b) options = parser.parse_args() options.func(options) print m.method_calls """ If there's anything I could have done better, please let me know! Chris From __peter__ at web.de Mon Aug 23 10:21:44 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Aug 2010 16:21:44 +0200 Subject: nested subparsers with argparse References: Message-ID: Chris Withers wrote: > I'm looking to build a script that has command line options as follows: > > ./myscript.py command subcommand [options] > > I can do up to the command [options] bit with add_subparsers in > argparse, but how do I then add a second level of subparsers? It looks like subparsers behave like the toplevel parsers -- you can invoke add_subparsers() on them, too. From burton at userful.com Mon Aug 23 11:09:24 2010 From: burton at userful.com (Burton Samograd) Date: Mon, 23 Aug 2010 09:09:24 -0600 Subject: vpython References: Message-ID: kimjeng writes: > On Aug 22, 7:38?am, Anssi Saari wrote: >> kimjeng writes: >> > the thing is i have installed gtkglextmm both from source and via a >> > slackbuilds package script and i still get the same error, >> > help would be a appreciated >> >> You'll just have to check what it is configure actually tests for and >> figure out from that why your system doesn't pass. > > thanks > here's something i noticed > > ... > Package gtkglextmm-1.2 was not found in the pkg-config search path. > Perhaps you should add the directory containing `gtkglextmm-1.2.pc' > to the PKG_CONFIG_PATH environment variable > No package 'gtkglextmm-1.2' found > ... > > the configure script is looking for gtkglextmm-1.2.pc , a file that > does not exist, what i do have is gtkglext-1.0.pc , im wondering why > i have the 1.0. version while i built the 1.2. source , plus the 'mm' > in the name is missing from the name of my .pc files > thanks The mm in the name is for a C++ binding for the library. Make sure you install both gtkglext and gtkglextmm packages. -- Burton From joncle at googlemail.com Mon Aug 23 11:35:11 2010 From: joncle at googlemail.com (Jon Clements) Date: Mon, 23 Aug 2010 08:35:11 -0700 (PDT) Subject: Using String Methods In Jump Tables References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: On 20 Aug, 01:51, Tim Daneliuk wrote: > On 8/19/2010 7:23 PM, Steven D'Aprano wrote: > > > On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: > > >> Problem: > > >> ? Given tuples in the form (key, string), use 'key' to determine what > >> ? string method to apply to the string: > > >>>> table = {'l': str.lower, 'u': str.upper} > >>>> table['u']('hello world') > > 'HELLO WORLD' > > Aha! ?That's just what I was looking for. > > > > > [...] > >> As I said, I know I could do this as a set of cascading ifs or even as > >> an eval, but I'm loathe to use such approaches. I like jump tables as a > >> structural construct because they are easy to understand and maintain. I > >> also realize that what I'm asking may be violating some deeply held > >> notion of OO purity, but, well, now I'm just curious if there is a way > >> to do this > > > This is Python, not some "pure" OO language. We have functional > > programming constructs, procedural constructs, and probably other > > programming models as well. Screw the deeply held notion of OO purity :) > > Yeah, I've never been much impressed with the OO purists. ?One of > the best speeches on the subject I ever saw was by David Korn (of > ksh fame) who did a presentation at USENIX one year called "Objecting > To Objects". ?He documented an attempt to write a compiler using > purely OO constructs and the many rings of hell that ensued. ? > > > > > But seriously, Python's object model includes bound and unbound methods > > precisely so you can do this sort of thing, and the above table-based > > approach is very common and recommended as an alternative to case/switch > > statements. It's a very common Pythonic idiom, so never fear that people > > will stone you for using it. > > +1 > > > > > The only thing that is a bit unusual is that you call it a jump table. In > > my experience, "Jump Table" is used for low-level languages where the > > table values are memory addresses. > > Yeah ... those old assembler memories never quite fade do they. > I dunno what you might call this. ?A Function Dispatch Table > perhaps? > > Thanks to both you and Chris for setting me straight :) > > -- > ------------------------------------------------------------------------ > Tim Daneliuk > tun... at tundraware.com Another more generic option would be to use methodcaller from the operator module. Just my 2p, Jon. From tundra at tundraware.com Mon Aug 23 11:57:08 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 23 Aug 2010 10:57:08 -0500 Subject: Using String Methods In Jump Tables In-Reply-To: References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: On 8/23/2010 10:35 AM, Jon Clements wrote: > On 20 Aug, 01:51, Tim Daneliuk wrote: >> On 8/19/2010 7:23 PM, Steven D'Aprano wrote: >> >>> On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: >> >>>> Problem: >> >>>> Given tuples in the form (key, string), use 'key' to determine what >>>> string method to apply to the string: >> >>>>>> table = {'l': str.lower, 'u': str.upper} >>>>>> table['u']('hello world') >>> 'HELLO WORLD' >> >> Aha! That's just what I was looking for. >> >> >> >>> [...] >>>> As I said, I know I could do this as a set of cascading ifs or even as >>>> an eval, but I'm loathe to use such approaches. I like jump tables as a >>>> structural construct because they are easy to understand and maintain. I >>>> also realize that what I'm asking may be violating some deeply held >>>> notion of OO purity, but, well, now I'm just curious if there is a way >>>> to do this >> >>> This is Python, not some "pure" OO language. We have functional >>> programming constructs, procedural constructs, and probably other >>> programming models as well. Screw the deeply held notion of OO purity :) >> >> Yeah, I've never been much impressed with the OO purists. One of >> the best speeches on the subject I ever saw was by David Korn (of >> ksh fame) who did a presentation at USENIX one year called "Objecting >> To Objects". He documented an attempt to write a compiler using >> purely OO constructs and the many rings of hell that ensued. >> >> >> >>> But seriously, Python's object model includes bound and unbound methods >>> precisely so you can do this sort of thing, and the above table-based >>> approach is very common and recommended as an alternative to case/switch >>> statements. It's a very common Pythonic idiom, so never fear that people >>> will stone you for using it. >> >> +1 >> >> >> >>> The only thing that is a bit unusual is that you call it a jump table. In >>> my experience, "Jump Table" is used for low-level languages where the >>> table values are memory addresses. >> >> Yeah ... those old assembler memories never quite fade do they. >> I dunno what you might call this. A Function Dispatch Table >> perhaps? >> >> Thanks to both you and Chris for setting me straight :) >> >> -- >> ------------------------------------------------------------------------ >> Tim Daneliuk >> tun... at tundraware.com > > Another more generic option would be to use methodcaller from the > operator module. > > Just my 2p, > > Jon. Could you say a bit more about just why you prefer this approach? Clearly, it *is* more generic, but in looking it over, it seems that methodcaller is less readable and intuitive ... at least to my eyes ... -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From psdasilva.nospam at netcabonospam.pt Mon Aug 23 12:07:48 2010 From: psdasilva.nospam at netcabonospam.pt (Paulo da Silva) Date: Mon, 23 Aug 2010 17:07:48 +0100 Subject: What is a class method? In-Reply-To: References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: <4c729cd7$0$18263$a729d347@news.telepac.pt> Em 23-08-2010 06:16, Ian Kelly escreveu: > On Sun, Aug 22, 2010 at 9:53 PM, Paulo da Silva > wrote: >> Em 23-08-2010 04:30, James Mills escreveu: >>> On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva >>> wrote: >>>> I understand the concept of a static method. >>>> However I don't know what is a class method. >>>> Would anybody pls. explain me? >>> >>> Please read this first: >>> http://docs.python.org/library/functions.html#classmethod >>> >>> Then ask us questions :) >> >> I did it before posting ... >> The "explanation" is not very clear. It is more like "how to use it". > > Consider this: > > class A(object): > @staticmethod > def new(): > return A() > > class B(A): > pass > > versus this: > > class C(object): > @classmethod > def new(cls): > return cls() > > class D(C): > pass > > B.new() will return a new instance of A, not B. D.new() will return a > new instance of D. > > Does this answer your question? Yes. Thank you very much. From denisg640 at gmail.com Mon Aug 23 12:31:11 2010 From: denisg640 at gmail.com (Denis Gomes) Date: Mon, 23 Aug 2010 12:31:11 -0400 Subject: What is a class method? In-Reply-To: <4c721434$0$1668$742ec2ed@news.sonic.net> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> <4c721434$0$1668$742ec2ed@news.sonic.net> Message-ID: John, I agree with you and I also think the definition given on the official python site is somewhat confusing, at least for an engineer like myself. But I'll take a stab at explaning it using what I know thus far. I think to understand what a class method is you have to first understand what a class variable is. Take this code snippet for example. class foo(object): x=10 def __init__(self): self.x=20 In this example if you create an instance of foo and call it f. You can access the instance attribute x by using f.x or you can access the class variable using the notation foo.x. These two will give you two different results. Now lets do something a bit more interesting. Say you have the following snippet. class foo(object): x=0 def __init__(self): self.x=10 foo.x+=1 >>>f=foo() >>>g=goo() >>>f.x 10 >>>g.x 10 >>>foo.x 2 What happened here is that the class variable foo.x is used to keep a count of the total number of instances created. So we see that a class variable can be looked at as what "connects" the two instances in a way, so that data can be shared between instances of the same class. This defintion may very well only apply to this case, but I think the mechanics is fundamentally the same. Keeping this in mind, lets make the jump to class methods. When an instance of a class is created, the methods are just functions that "work on" the attributes (the variables). Similarly, a class method is a method that works on a class variable. For example, class foo(object): x=10 def __init__(self): self.x=20 @classmethod def change(self): self.x=15 >>>f=foo() >>>f.x 20 >>>foo.x 10 >>>f.change() >>>f.x 20 >>>foo.x 15 So this is my explanation for what a classmethod is. Hope it helps. Good luck. Denis On Mon, Aug 23, 2010 at 2:24 AM, John Nagle wrote: > On 8/22/2010 9:16 PM, James Mills wrote: > >> On Mon, Aug 23, 2010 at 1:53 PM, Paulo da Silva >> >> wrote: >> >>> I did it before posting ... >>> >>> The "explanation" is not very clear. It is more like "how to use it". >>> >> >> Without going into the semantics of languages basically the >> differences are quite clear: >> >> @classmethod is a decorator that warps a function with >> passes the class as it's first argument. >> >> @staticmethod (much like C++/Java) is also a decorator that >> wraps a function but does not pass a class or instance as >> it's first argument. >> > > That reads like something the C++ standards revision committee > would dream up as they add unnecessary template gimmicks to the > language. > > John Nagle > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Aug 23 13:10:00 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Aug 2010 13:10:00 -0400 Subject: IDLE will not startup after upgrading Python on Mac OS X In-Reply-To: References: Message-ID: On 8/23/2010 10:05 AM, Benjamin Kaplan wrote: >> From the title, this may be relevant, but I'm not sure because I'm > having trouble accessing the bug tracker right now. > http://bugs.python.org/issue9227 > > Also, this one: > http://bugs.python.org/issue9620 Tracker is still down (site maintainers have been informed). I believe one of those may have helpful info when it is back up. -- Terry Jan Reedy From thomas at jollybox.de Mon Aug 23 13:22:46 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 23 Aug 2010 19:22:46 +0200 Subject: Helper classes design question In-Reply-To: <201008231047.57128.mail@johnohagan.com> References: <201008231047.57128.mail@johnohagan.com> Message-ID: <201008231922.46898.thomas@jollybox.de> On Monday 23 August 2010, it occurred to John O'Hagan to exclaim: > I want to know the best way to organise a bunch of functions designed to > operate on instances of a given class without cluttering the class itself > with a bunch of unrelated methods. > > What I've done is make what I think are called helper classes, each of > which are initialized with an instance of the main class and has methods > which are all of the same type (insofar as they return a boolean, or > modify the object in place, or whatever). > > I'm not sure if I'm on the right track here design-wise. Maybe this could > be better done with inheritance (not my forte), but my first thought is > that no, the helper classes (if that's what they are) are not actually a > type of the main class, but are auxiliary to it. You could try using mixins. I don't know how well this fits with the problem at hand, but what you'd do is this: Instead of thinking of the bits you're writing as helper classes, think of them as more or less isolated pieces of the functionality you'd like the final object to have. You can implement these independently, operating on self instead of on self.seq or something like that. Have a look at the abc module (abstract base classes) for a nifty way to prevent instantiation of these classes. If the functionality you're implementing only makes sense for a sequence, or for a sequence with certain characteristics, you can define an ABC that represents/specifies those characteristics and inherit from that. Or maybe not. Then, you have a bunch of largely independent classes providing isolated pieces of functionality, which you can then combine into one class by inheriting from ALL of them, and implementing the missing methods, like a constructor. Let's draw a graph: MySuperDuperCoolSequenceThing / / \ \ Filtered Rotated Tap \ \ / / \ | AbstractSequence KitchenSink \ / object I hope you understood at least a bit of my ramblings. Cheers, Thomas From Sang-Ho.Yun at jpl.nasa.gov Mon Aug 23 13:37:03 2010 From: Sang-Ho.Yun at jpl.nasa.gov (Sang-Ho Yun) Date: Mon, 23 Aug 2010 10:37:03 -0700 Subject: Save/load like matlab? Message-ID: I wonder if there is a way to save and load all python variables just like matlab does, so I can build a code step by step by loading previous states. I am handling a python processing code for very large files and multiple processing steps. Each time I find a bug, I have to run the whole thing again, which is time consuming. Thank you, Sang-Ho From leon at dcs.shef.ac.uk Mon Aug 23 13:38:02 2010 From: leon at dcs.shef.ac.uk (Leon Derczynski) Date: Mon, 23 Aug 2010 10:38:02 -0700 (PDT) Subject: Discarding STDERR generated during subprocess.popen Message-ID: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> Hi, I would like to run an external program, and discard anything written to stderr during its execution, capturing only stdout. My code currently looks like: def blaheta_tag(filename): blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/' process = subprocess.Popen([blaheta_dir + 'exec/funcTag', blaheta_dir + 'data/', filename], cwd=blaheta_dir, stdout=subprocess.PIPE) process.wait() return process.communicate()[0] This returns stdout, and stderr ends up printing to the console. How can I disregard anything sent to stderr such that it doesn't appear on the console? Thanks From tjreedy at udel.edu Mon Aug 23 13:41:02 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Aug 2010 13:41:02 -0400 Subject: Using String Methods In Jump Tables In-Reply-To: References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: On 8/23/2010 11:57 AM, Tim Daneliuk wrote: > On 8/23/2010 10:35 AM, Jon Clements wrote: >> Another more generic option would be to use methodcaller from the >> operator module. > Could you say a bit more about just why you prefer this approach? > Clearly, it *is* more generic, but in looking it over, it seems that > methodcaller is less readable and intuitive ... at least to my eyes ... He did not say 'preferable', only more generic, as you agree, and the generic solution, buried away in operator, is a good thing to know about. The OP wanted to convert (methodname, string) pairs to a call of methodname on strings. Since there is only one class, str, involved, mapping methodname to str.methodname works. If, for instance, the OP instead had to map (methodname, bytes_or_string) to a call, a not unreasonable generalization, str.methodname does not work (with bytes) but methodcaller(methodname) will, with bytes or string. >>> methodcaller('upper')(b'abc') b'ABC' >>> methodcaller('upper')('abc') 'ABC' -- Terry Jan Reedy From mailtome200420032002 at gmail.com Mon Aug 23 13:43:56 2010 From: mailtome200420032002 at gmail.com (aj) Date: Mon, 23 Aug 2010 10:43:56 -0700 (PDT) Subject: make install DESTDIR References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> Message-ID: <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> Thanks for reply Thomas. I am running make install DESTDIR=/home/foo/ bar. Martin- Asking for help :) On Aug 21, 4:43?am, "Martin v. Loewis" wrote: > > The whole point of DESTDIR is that it should be prepended to all > > installed paths, but the binaries should not contain any references to > > it.DESTDIR is commonly used by packagers, for example, to allow > > installation without superuser privileges. > > So what is the point of your messages? Do you want to report a problem? > Are you asking for help? Do you want to vent frustration? > > Regards, > Martin From thomas at jollybox.de Mon Aug 23 13:53:40 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 23 Aug 2010 19:53:40 +0200 Subject: Discarding STDERR generated during subprocess.popen In-Reply-To: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> References: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> Message-ID: <201008231953.41180.thomas@jollybox.de> On Monday 23 August 2010, it occurred to Leon Derczynski to exclaim: > Hi, > > I would like to run an external program, and discard anything written > to stderr during its execution, capturing only stdout. My code > currently looks like: > > def blaheta_tag(filename): > blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/' > process = subprocess.Popen([blaheta_dir + 'exec/funcTag', > blaheta_dir + 'data/', filename], cwd=blaheta_dir, > stdout=subprocess.PIPE) > process.wait() > return process.communicate()[0] > > This returns stdout, and stderr ends up printing to the console. How > can I disregard anything sent to stderr such that it doesn't appear on > the console? Read it into a pipe as well, and then ignore. Or, if you're targeting only UNIX-like systems, open /dev/null for writing and redirect the output there. From dan.kluev at gmail.com Mon Aug 23 14:16:43 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Tue, 24 Aug 2010 05:16:43 +1100 Subject: Discarding STDERR generated during subprocess.popen In-Reply-To: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> References: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> Message-ID: On Tue, Aug 24, 2010 at 4:38 AM, Leon Derczynski wrote: > Hi, > > I would like to run an external program, and discard anything written > to stderr during its execution, capturing only stdout. My code > currently looks like: > > def blaheta_tag(filename): > blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/' > process = subprocess.Popen([blaheta_dir + 'exec/funcTag', > blaheta_dir + 'data/', filename], cwd=blaheta_dir, > stdout=subprocess.PIPE) > process.wait() > return process.communicate()[0] > > This returns stdout, and stderr ends up printing to the console. How > can I disregard anything sent to stderr such that it doesn't appear on > the console? > Just add `stderr=subprocess.PIPE` keyword in the Popen call. -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.koda at gmail.com Mon Aug 23 14:22:21 2010 From: python.koda at gmail.com (Alban Nona) Date: Mon, 23 Aug 2010 14:22:21 -0400 Subject: Replace multiple lines in a txt file. Message-ID: Hi everybody, I would like to know if its possible to modify a list of entry that is define into a list and replace it by another list ? I try this piece of code, but Im pretty sure I messed something: http://pastebin.com/HfdkGeB3 Any help appreciated, Thank you :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From empwanted at cox.net Mon Aug 23 14:45:58 2010 From: empwanted at cox.net (empwanted at cox.net) Date: Mon, 23 Aug 2010 11:45:58 -0700 Subject: Start up company is looking for an experianced Django web developer . Message-ID: <20100823144558.AUPWA.560488.imail@fed1rmwml40> Hi Everyone, Our company is looking for an experienced full time Django programmer to work with our development team on a contract basis. We are a start up that is developing a large web application with extensive database interfaces. We are based in the US so living in the US is a plus. The existing application is partially completed using Django, Centos 5, Postgresql 8.4, SVN, and Jquery. This contract position could lead to a full time position with our new company. If you?ve got expert skills in Django, HTML, Jquery, CSS and overall web development and design, we?d like to hear from you. If you are interested please send your resume or work experience to empwanted at cox.net Please include your expected hourly or weekly rate. Accepted applicants will be required to sign a non-disclosure agreement. From emile at fenx.com Mon Aug 23 15:13:15 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 23 Aug 2010 12:13:15 -0700 Subject: Replace multiple lines in a txt file. In-Reply-To: References: Message-ID: On 8/23/2010 11:22 AM Alban Nona said... > Hi everybody, > > I would like to know if its possible to modify a list of entry that is > define into a list and replace it by another list ? > I try this piece of code, but Im pretty sure I messed something: > > http://pastebin.com/HfdkGeB3 > > The code you posted references variables not defined within the snippet, so it's hard to guess what may be wrong. Emile From jyoung79 at kc.rr.com Mon Aug 23 15:15:44 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Mon, 23 Aug 2010 19:15:44 +0000 Subject: Working with PDFs? Message-ID: <20100823191544.DVI43.197922.root@cdptpa-web24-z02> > writes: >> - Pull out text from each PDF page (to search for specific words) >> - Combine separate pdf documents into one document >> - Add bookmarks (with destination settings) > PDF Shuffler is a Python app which does PDF merging and splitting very > well. I don't think it does anything else, though, but maybe that's > where your code comes in? Thank you Anssi, MRAB, Terry and Geremy for your replies. I've been researching the apps you have recommended. Just curious if anyone has used pyPdf? While testing this, it seems to work pretty well for combining pdf files (seems to keep the annotation notes nicely also) and pulling out the text contents. I'm not sure I'm going to be able to find anything that can add bookmarks though. If you have used pyPdf, would you mind sharing your thoughts about it? Thanks. Jay From emile at fenx.com Mon Aug 23 15:18:00 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 23 Aug 2010 12:18:00 -0700 Subject: Replace multiple lines in a txt file. In-Reply-To: References: Message-ID: On 8/23/2010 12:13 PM Emile van Sebille said... > On 8/23/2010 11:22 AM Alban Nona said... >> Hi everybody, >> >> I would like to know if its possible to modify a list of entry that is >> define into a list and replace it by another list ? >> I try this piece of code, but Im pretty sure I messed something: >> >> http://pastebin.com/HfdkGeB3 >> >> > > The code you posted references variables not defined within the snippet, > so it's hard to guess what may be wrong. > > Emile > One thing stands out -- fopen = open(_path).read() for passe in _passeFettel: fopen.write(re.sub(passe, _fileFettel) fopen contains the data read from _path and certainly has no write method. Emile From fetchinson at googlemail.com Mon Aug 23 15:44:00 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 23 Aug 2010 21:44:00 +0200 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: > I wonder if there is a way to save and load all python variables just like > matlab does, so I can build a code step by step by loading previous states. > > I am handling a python processing code for very large files and multiple > processing steps. Each time I find a bug, I have to run the whole thing > again, which is time consuming. Perhaps pickle is the thing you are looking for? http://docs.python.org/library/pickle.html HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From stef.mientki at gmail.com Mon Aug 23 15:54:37 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 23 Aug 2010 21:54:37 +0200 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: <4C72D1FD.1020009@gmail.com> On 23-08-2010 21:44, Daniel Fetchinson wrote: >> I wonder if there is a way to save and load all python variables just like >> matlab does, so I can build a code step by step by loading previous states. >> >> I am handling a python processing code for very large files and multiple >> processing steps. Each time I find a bug, I have to run the whole thing >> again, which is time consuming. > Perhaps pickle is the thing you are looking for? > > http://docs.python.org/library/pickle.html or even cpickle which is lot faster cheers, Stef > HTH, > Daniel > > From debatem1 at gmail.com Mon Aug 23 15:58:43 2010 From: debatem1 at gmail.com (geremy condra) Date: Mon, 23 Aug 2010 12:58:43 -0700 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On Mon, Aug 23, 2010 at 10:37 AM, Sang-Ho Yun wrote: > I wonder if there is a way to save and load all python variables just like > matlab does, so I can build a code step by step by loading previous states. > > I am handling a python processing code for very large files and multiple > processing steps. Each time I find a bug, I have to run the whole thing > again, which is time consuming. > > Thank you, > Sang-Ho You may also be interested in Sage if you're trying to do Matlab-like things in Python. http://www.sagemath.org/ Geremy Condra From joncle at googlemail.com Mon Aug 23 16:08:25 2010 From: joncle at googlemail.com (Jon Clements) Date: Mon, 23 Aug 2010 13:08:25 -0700 (PDT) Subject: Using String Methods In Jump Tables References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: <5c99a604-f64c-49db-88f6-762175aa8532@5g2000yqz.googlegroups.com> On 23 Aug, 16:57, Tim Daneliuk wrote: > On 8/23/2010 10:35 AM, Jon Clements wrote: > > > > > On 20 Aug, 01:51, Tim Daneliuk wrote: > >> On 8/19/2010 7:23 PM, Steven D'Aprano wrote: > > >>> On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: > > >>>> Problem: > > >>>> ? Given tuples in the form (key, string), use 'key' to determine what > >>>> ? string method to apply to the string: > > >>>>>> table = {'l': str.lower, 'u': str.upper} > >>>>>> table['u']('hello world') > >>> 'HELLO WORLD' > > >> Aha! ?That's just what I was looking for. > > >>> [...] > >>>> As I said, I know I could do this as a set of cascading ifs or even as > >>>> an eval, but I'm loathe to use such approaches. I like jump tables as a > >>>> structural construct because they are easy to understand and maintain. I > >>>> also realize that what I'm asking may be violating some deeply held > >>>> notion of OO purity, but, well, now I'm just curious if there is a way > >>>> to do this > > >>> This is Python, not some "pure" OO language. We have functional > >>> programming constructs, procedural constructs, and probably other > >>> programming models as well. Screw the deeply held notion of OO purity :) > > >> Yeah, I've never been much impressed with the OO purists. ?One of > >> the best speeches on the subject I ever saw was by David Korn (of > >> ksh fame) who did a presentation at USENIX one year called "Objecting > >> To Objects". ?He documented an attempt to write a compiler using > >> purely OO constructs and the many rings of hell that ensued. ? > > >>> But seriously, Python's object model includes bound and unbound methods > >>> precisely so you can do this sort of thing, and the above table-based > >>> approach is very common and recommended as an alternative to case/switch > >>> statements. It's a very common Pythonic idiom, so never fear that people > >>> will stone you for using it. > > >> +1 > > >>> The only thing that is a bit unusual is that you call it a jump table. In > >>> my experience, "Jump Table" is used for low-level languages where the > >>> table values are memory addresses. > > >> Yeah ... those old assembler memories never quite fade do they. > >> I dunno what you might call this. ?A Function Dispatch Table > >> perhaps? > > >> Thanks to both you and Chris for setting me straight :) > > >> -- > >> ------------------------------------------------------------------------ > >> Tim Daneliuk > >> tun... at tundraware.com > > > Another more generic option would be to use methodcaller from the > > operator module. > > > Just my 2p, > > > Jon. > > Could you say a bit more about just why you prefer this approach? > Clearly, it *is* more generic, but in looking it over, it seems that > methodcaller is less readable and intuitive ... at least to my eyes ... In addition to Terry's informative response... Using methodcaller allows you to 'preserve' Python's duck-typing as well as any over-ridden methods in subclasses. In your example, this is probably overkill as you're only dealing with one class: but Terry did provide a nice example of when it could fail. Another (convoluted) example: class mystr(str): def lower(self): return self.upper() >>> s = mystr('abc') >>> s.lower() 'ABC' >>> lower = methodcaller('lower') >>> lower(s) 'ABC' >>> str.lower(s) 'abc' ^^^ Most likely incorrect It also adds a further bit of flexibility (which can be emulated with functools.partial admittedly): split_tab = methodcaller('split', '\t') split_comma = methodcaller('split', ',') ... etc ... Cheers, Jon. From robert.kern at gmail.com Mon Aug 23 16:18:08 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 23 Aug 2010 15:18:08 -0500 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On 8/23/10 12:37 PM, Sang-Ho Yun wrote: > I wonder if there is a way to save and load all python variables just like > matlab does, so I can build a code step by step by loading previous states. > > I am handling a python processing code for very large files and multiple > processing steps. Each time I find a bug, I have to run the whole thing > again, which is time consuming. Test each piece of code in isolation from the rest rather than relying on a complete run to test everything in one go. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nad at acm.org Mon Aug 23 16:20:17 2010 From: nad at acm.org (Ned Deily) Date: Mon, 23 Aug 2010 13:20:17 -0700 Subject: IDLE will not startup after upgrading Python on Mac OS X References: Message-ID: In article , Benjamin Kaplan wrote: > On Mon, Aug 23, 2010 at 9:45 AM, Frederick Manley wrote: > > so went to > > python.org to download Python 2.7, as I was "strongly encouraged" to do on > > the website. [...] > >The only problem is, whenever I start it > > up (I've tried starting it from the Terminal and double clicking the icon) I > > get the following message: > > "Idle's subprocess cannot make connection. ?Either Idle can't start a > > subprocess or a personal firewall is blocking the connection." > > Searching various programming forums came up with similar problems users > > have had in windows, but I couldn't find any information on how to fix this > > problem on a mac with OSX. ?Please help. > >From the title, this may be relevant, but I'm not sure because I'm > having trouble accessing the bug tracker right now. > http://bugs.python.org/issue9227 Yes, you are undoubtedly running into Issue9227. This is a known problem with IDLE and Tkinter on OS X 10.6 when using the python.org 2.7 installer "for OS X 10.5 and later". Until a replacement installer is made available, the simplest workaround is to just re-install 2.7 using the 32-bit OS X installer "for OS X 10.3 and later" (available here http://www.python.org/download/releases/2.7/). -- Ned Deily, nad at acm.org From f1crazed at gmail.com Mon Aug 23 16:43:58 2010 From: f1crazed at gmail.com (f1crazed) Date: Mon, 23 Aug 2010 13:43:58 -0700 (PDT) Subject: Installing pymssql Message-ID: <7e155e4e-ca2e-41c0-b838-0dfba5acc93f@h40g2000pro.googlegroups.com> Hello, I am new to the python world. I'm trying the install the pymssql package and have been unsuccessful. I am running Win7 x64. Here is the output I get when I try to build the pymssql package: running build running build_ext cythoning _mssql.pyx to _mssql.c building '_mssql' extension creating build creating build\temp.win-amd64-2.6 creating build\temp.win-amd64-2.6\Release C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN \amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Iwin32\free tds\include -IC:\Python26\include -IC:\Python26\PC /Tc_mssql.c /Fobuild \temp.win-amd64-2.6\Release\_mssql.obj -DMSDBLIB _mssql.c _mssql.c(643) : warning C4244: 'function' : conversion from 'Py_ssize_t' to 'long', possible loss of data _mssql.c(663) : warning C4244: 'function' : conversion from 'Py_ssize_t' to 'long', possible loss of data _mssql.c(685) : warning C4244: 'function' : conversion from 'Py_ssize_t' to 'long', possible loss of data _mssql.c(712) : warning C4244: 'function' : conversion from 'Py_ssize_t' to 'long', possible loss of data _mssql.c(6192) : warning C4244: '=' : conversion from 'Py_ssize_t' to 'int', possible loss of data _mssql.c(9967) : warning C4267: '=' : conversion from 'size_t' to 'int', possible loss of data c:\pythonmods\pymssql-1.9.908\_mssql.c(4652) : warning C4700: uninitialized local variable '__pyx_v_dbcol' used creating build\lib.win-amd64-2.6 C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN \amd64\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:win32\fre etds\lib /LIBPATH:C:\Python26\libs /LIBPATH:C:\Python26\PCbuild\amd64 msvcrt.lib kernel32.lib user32.lib gdi32.lib winsp ool.lib ws2_32.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libTDS. lib dblib.lib /EXPORT:init_mssql build\temp.win-amd64-2.6\Release \_mssql.obj /OUT:build\lib.win-amd64-2.6\_mssql.pyd /IM PLIB:build\temp.win-amd64-2.6\Release\_mssql.lib /MANIFESTFILE:build \temp.win-amd64-2.6\Release\_mssql.pyd.manifest _mssql.obj : warning LNK4197: export 'init_mssql' specified multiple times; using first specification Creating library build\temp.win-amd64-2.6\Release\_mssql.lib and object build\temp.win-amd64-2.6\Release\_mssql.exp _mssql.obj : error LNK2019: unresolved external symbol dbsqlexec referenced in function __pyx_f_6_mssql_db_sqlexec _mssql.obj : error LNK2019: unresolved external symbol dbadata referenced in function __pyx_f_6_mssql_get_data _mssql.obj : error LNK2019: unresolved external symbol dbdata referenced in function __pyx_f_6_mssql_get_data _mssql.obj : error LNK2019: unresolved external symbol dbalttype referenced in function __pyx_f_6_mssql_get_type _mssql.obj : error LNK2019: unresolved external symbol dbcoltype referenced in function __pyx_f_6_mssql_get_type _mssql.obj : error LNK2019: unresolved external symbol dbadlen referenced in function __pyx_f_6_mssql_get_length _mssql.obj : error LNK2019: unresolved external symbol dbdatlen referenced in function __pyx_f_6_mssql_get_length _mssql.obj : error LNK2019: unresolved external symbol dbcancel referenced in function __pyx_f_6_mssql_db_cancel _mssql.obj : error LNK2019: unresolved external symbol dbtds referenced in function __pyx_pf_6_mssql_15MSSQLConnection_1 1tds_version___get__ _mssql.obj : error LNK2019: unresolved external symbol dbclose referenced in function __pyx_pf_6_mssql_15MSSQLConnection _close _mssql.obj : error LNK2019: unresolved external symbol dbuse referenced in function __pyx_pf_6_mssql_15MSSQLConnection_s elect_db _mssql.obj : error LNK2019: unresolved external symbol dbgetmaxprocs referenced in function __pyx_pf_6_mssql_get_max_con nections _mssql.obj : error LNK2019: unresolved external symbol dbcount referenced in function __pyx_f_6_mssql_15MSSQLConnection_ execute_scalar _mssql.obj : error LNK2019: unresolved external symbol dbnextrow referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_execute_scalar _mssql.obj : error LNK2019: unresolved external symbol dbsettime referenced in function __pyx_pf_6_mssql_15MSSQLConnecti on_13query_timeout___set__ _mssql.obj : error LNK2019: unresolved external symbol dbcmd referenced in function __pyx_pf_6_mssql_15MSSQLConnection__ _init__ _mssql.obj : error LNK2019: unresolved external symbol dbloginfree referenced in function __pyx_pf_6_mssql_15MSSQLConnec tion___init__ _mssql.obj : error LNK2019: unresolved external symbol tdsdbopen referenced in function __pyx_pf_6_mssql_15MSSQLConnecti on___init__ _mssql.obj : error LNK2019: unresolved external symbol dbsetlogintime referenced in function __pyx_pf_6_mssql_15MSSQLCon nection___init__ _mssql.obj : error LNK2019: unresolved external symbol dbsetlname referenced in function __pyx_pf_6_mssql_15MSSQLConnect ion___init__ _mssql.obj : error LNK2019: unresolved external symbol dblogin referenced in function __pyx_pf_6_mssql_15MSSQLConnection ___init__ _mssql.obj : error LNK2019: unresolved external symbol dbdatecrack referenced in function __pyx_f_6_mssql_15MSSQLConnect ion_convert_db_value _mssql.obj : error LNK2019: unresolved external symbol dbconvert referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_convert_db_value _mssql.obj : error LNK2019: unresolved external symbol dbresults referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_execute_non_query _mssql.obj : error LNK2019: unresolved external symbol dbrpcinit referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure___init__ _mssql.obj : error LNK2019: unresolved external symbol dbrpcparam referenced in function __pyx_pf_6_mssql_20MSSQLStoredP rocedure_bind _mssql.obj : error LNK2019: unresolved external symbol dbretstatus referenced in function __pyx_pf_6_mssql_20MSSQLStored Procedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbretdata referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbretlen referenced in function __pyx_pf_6_mssql_20MSSQLStoredPro cedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbretname referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbrettype referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbnumrets referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbsqlok referenced in function __pyx_pf_6_mssql_20MSSQLStoredProc edure_execute _mssql.obj : error LNK2019: unresolved external symbol dbrpcsend referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbsetmaxprocs referenced in function __pyx_pf_6_mssql_set_max_con nections _mssql.obj : error LNK2019: unresolved external symbol dbmsghandle referenced in function __pyx_f_6_mssql_init_mssql _mssql.obj : error LNK2019: unresolved external symbol dberrhandle referenced in function __pyx_f_6_mssql_init_mssql _mssql.obj : error LNK2019: unresolved external symbol dbinit referenced in function __pyx_f_6_mssql_init_mssql _mssql.obj : error LNK2019: unresolved external symbol dbcolname referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_get_result _mssql.obj : error LNK2019: unresolved external symbol dbnumcols referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_get_result build\lib.win-amd64-2.6\_mssql.pyd : fatal error LNK1120: 40 unresolved externals error: command '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC \BIN\amd64\link.exe"' failed with exit status 1120 I know this might be a bit much to chew on but I have been trying to figure this out for a while know and I cannot figure this one out. Thanks in advance for the help! -JD From almar.klein at gmail.com Mon Aug 23 16:47:54 2010 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 23 Aug 2010 22:47:54 +0200 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On 23 August 2010 19:37, Sang-Ho Yun wrote: > I wonder if there is a way to save and load all python variables just like > matlab does, so I can build a code step by step by loading previous states. > > I am handling a python processing code for very large files and multiple > processing steps. Each time I find a bug, I have to run the whole thing > again, which is time consuming. > > Thank you, > Sang-Ho > > -- > http://mail.python.org/mailman/listinfo/python-list > A year ago or so I designed a simple file format that could do that and is also human readable (binary data is compressed and then base64 encoded). I use it extensively to store experiment data for my research and also for configuration files for two open source projects that I own: http://code.google.com/p/ssdf/ Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Mon Aug 23 17:22:17 2010 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 23 Aug 2010 23:22:17 +0200 Subject: Using String Methods In Jump Tables References: Message-ID: <87fwy510ty.fsf@busola.homelinux.net> Tim Daneliuk writes: > You can get away with this because all string objects appear to point to common > method objects. That is,: id("a".lower) == id("b".lower) A side note: your use of `id' has misled you. id(X)==id(Y) is not a perfect substitue for the X is Y. :) "a".lower and "b".lower obviously cannot be the same object, because in that case, how could they behave differently when called? >>> "a".lower() 'a' >>> "b".lower() # this should also return 'a' if "b".lower is the # same object 'b' Yet, id("a".lower) == id("b".lower) evaluates as True. What happens is, when the expression id("a".lower) == id("b.lower") is evaluated, each of the bound method objects created with subexpressions "a".lower" and "b".lower is referenced and thrown away as soon as "id" is called (i.e. pretty much immediately), so the two never exist at the same time. By the time "b".lower needs to be created, "a".lower is freshly deceased, and the memory it used to occupy is ready for use, and waiting at the top of the freelist. If CPython happened to use a different allocation/garbage collection strategy and failed to reuse the same memory address immediately, your code would just (happen to) work. From martin at v.loewis.de Mon Aug 23 17:23:09 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 23 Aug 2010 23:23:09 +0200 Subject: make install DESTDIR In-Reply-To: <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> Message-ID: <4C72E6BD.1020204@v.loewis.de> > Martin- Asking for help :) Ok. Please try the patch below. If this works, please make a bug report. Regards, Martin Index: Lib/distutils/util.py =================================================================== --- Lib/distutils/util.py (Revision 84197) +++ Lib/distutils/util.py (Arbeitskopie) @@ -220,7 +220,7 @@ if not os.path.isabs(pathname): return os.path.join(new_root, pathname) else: - return os.path.join(new_root, pathname[1:]) + return os.path.join(new_root, pathname.lstrip('/')) elif os.name == 'nt': (drive, path) = os.path.splitdrive(pathname) From robert.kern at gmail.com Mon Aug 23 17:33:54 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 23 Aug 2010 16:33:54 -0500 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On 8/23/10 3:18 PM, Robert Kern wrote: > On 8/23/10 12:37 PM, Sang-Ho Yun wrote: >> I wonder if there is a way to save and load all python variables just like >> matlab does, so I can build a code step by step by loading previous states. >> >> I am handling a python processing code for very large files and multiple >> processing steps. Each time I find a bug, I have to run the whole thing >> again, which is time consuming. > > Test each piece of code in isolation from the rest rather than relying on a > complete run to test everything in one go. Having said that, you will want to take a look into using joblib to structure your larger runs: http://pypi.python.org/pypi/joblib -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ben+python at benfinney.id.au Mon Aug 23 17:38:53 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 24 Aug 2010 07:38:53 +1000 Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: <87zkwdovpu.fsf@benfinney.id.au> Ata Jafari writes: > Finally I did it. > I was doing some stupid mistakes. > Thanks alot. For the benefit of future readers of this thread, could you please describe what the errors were and how you discovered them? Also what the eventual solution was. -- \ ?When I get new information, I change my position. What, sir, | `\ do you do with new information?? ?John Maynard Keynes | _o__) | Ben Finney From ben+python at benfinney.id.au Mon Aug 23 17:56:42 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 24 Aug 2010 07:56:42 +1000 Subject: Start up company is looking for an experianced Django web developer . References: Message-ID: <87vd71ouw5.fsf@benfinney.id.au> writes: > Our company is looking for an experienced full time Django programmer [?] Please don't use the Python forum for this. Instead, post it to the Python Jobs Board . > Accepted applicants will be required to sign a non-disclosure agreement. I would strongly recommend that IT workers not sign such agreements. Instead, both parties can rely on existing law (which already heavily favours the employer), and don't sign away more of your rights just to get a job. -- \ ?I am amazed, O Wall, that you have not collapsed and fallen, | `\ since you must bear the tedious stupidities of so many | _o__) scrawlers.? ?anonymous graffiti, Pompeii, 79 CE | Ben Finney From thomas at jollybox.de Mon Aug 23 17:57:06 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 23 Aug 2010 23:57:06 +0200 Subject: Installing pymssql In-Reply-To: <7e155e4e-ca2e-41c0-b838-0dfba5acc93f@h40g2000pro.googlegroups.com> References: <7e155e4e-ca2e-41c0-b838-0dfba5acc93f@h40g2000pro.googlegroups.com> Message-ID: <201008232357.07258.thomas@jollybox.de> On Monday 23 August 2010, it occurred to f1crazed to exclaim: > Hello, > > I am new to the python world. I'm trying the install the pymssql > package and have been unsuccessful. I am running Win7 x64. Here is > the output I get when I try to build the pymssql package: > > [snip: missing symbols 64 bit blah] This appears to be a known bug: http://code.google.com/p/pymssql/issues/detail?id=11 There is a comment by the reporter: " This is likely because the 'freetds.zip' included in the source distribution only has 32-bit libraries (lib/libTDS.lib). " Assuming this analysis is correct, maybe you can find (or, more likely, create) a 64-bit build of libTDS and use that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Mon Aug 23 18:15:26 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 23 Aug 2010 15:15:26 -0700 (PDT) Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation Message-ID: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> I started learning python with ver 2.6. Then I switched to 3.1 after uninstalling the previous version. Now I find that many of the code snippets that I would need are written for py 2.6. Sometimes the automatic converter 2to3 doesn't help, because it is not able to complete its objective and request manual "tuning" from the user. This is to tell you that I would like to have both versions running on my PC. I am using Windows 7 at home, and Windows Vista in the office. Right now, the two versions are installed on the PC I have at home. If I go to the directory C:\python26 or C:\python31 and I type "python", the correct version of python is launched. I need the pywin32 extensions in either case. I was about to feel happy that everything worked when I found that I cannot change the file associations. If I want to work with py 3.1, I want that a double click on a *.py file launches python 3.1, and not 2.6. On the other hand, when I pan to work with py 2.6 I want that a double click on a*.py file launches python 3.1. I keep source files (*.py) for either version in different directories. I tried to change file associations, first manually, in a CMD window. But the system was responding "access denied" even when I used an Administrator account (I was using FTYPE python.file="C: \Python26\python.exe" "%1" %*). So I directed my efforts towards the Control Panel. But here I got lost. I am not able to find the python file associations (I can find others, but not python's). Perhaps I am focussing my efforts in the wrong direction, but I am not aware of any alternative one. Perhaps you can help me. Thank you Vicente Soler From martin at v.loewis.de Mon Aug 23 18:55:30 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 24 Aug 2010 00:55:30 +0200 Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation In-Reply-To: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> Message-ID: <4C72FC62.1050908@v.loewis.de> > I tried to change file associations, first manually, in a CMD window. > But the system was responding "access denied" even when I used an > Administrator account (I was using FTYPE python.file="C: > \Python26\python.exe" "%1" %*). That works, in principle. Put that command into py26.bat, then, in Explorer, Run As Administrator. Make sure to double-escape the percent signs. Alternatively, you can also write a program that writes to HKEY_CURRENT_USER; that would take precedence over HKEY_LOCAL_MACHINE. Regards, Martin From vicente.soler at gmail.com Mon Aug 23 19:08:17 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 23 Aug 2010 16:08:17 -0700 (PDT) Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> <4C72FC62.1050908@v.loewis.de> Message-ID: <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> On 24 ago, 00:55, "Martin v. Loewis" wrote: > > I tried to change file associations, first manually, in a CMD window. > > But the system was responding "access denied" even when I used an > > Administrator account (I was using FTYPE python.file="C: > > \Python26\python.exe" "%1" %*). > > That works, in principle. Put that command into py26.bat, then, in > Explorer, Run As Administrator. Make sure to double-escape the percent > signs. > > Alternatively, you can also write a program that writes to > HKEY_CURRENT_USER; that would take precedence over HKEY_LOCAL_MACHINE. > > Regards, > Martin When I am logged-in in a session as an administrator, the BAT file on the Desktop, and I double-click on it, it does not work. However, if instead of double-clicking on the BAT file, I enter the Explorer and I run the BAT file as administrator, then something seems to start working. Excellent! When you say to double-escape the percent signs, do you mean that in my BAT file I should write... FTYPE python.file="C:\Python26\python.exe" "%%1" %%* and the inverted commas around %%*, are they not necessary? Vicente Soler From martin at v.loewis.de Mon Aug 23 19:33:21 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 24 Aug 2010 01:33:21 +0200 Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation In-Reply-To: <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> <4C72FC62.1050908@v.loewis.de> <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> Message-ID: <4C730541.7040507@v.loewis.de> > When I am logged-in in a session as an administrator, the BAT file on > the Desktop, and I double-click on it, it does not work. This is not what I meant. Instead, right-click on the BAT file, and select "run as administrator". > When you say to double-escape the percent signs, do you mean that in > my BAT file I should write... > > FTYPE python.file="C:\Python26\python.exe" "%%1" %%* > > and the inverted commas around %%*, are they not necessary? No, I don't think so. Regards, Martin From vicente.soler at gmail.com Mon Aug 23 19:41:13 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 23 Aug 2010 16:41:13 -0700 (PDT) Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> <4C72FC62.1050908@v.loewis.de> <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> <4C730541.7040507@v.loewis.de> Message-ID: <3d85d8f5-8ce0-470f-b6ec-c86c452a335b@a36g2000yqc.googlegroups.com> On Aug 24, 1:33?am, "Martin v. Loewis" wrote: > > When I am logged-in in a session as an administrator, the BAT file on > > the Desktop, and I double-click on it, it does not work. > > This is not what I meant. Instead, right-click on the BAT file, > and select "run as administrator". > > > When you say to double-escape the percent signs, do you mean that in > > my BAT file I should write... > > > ? ? FTYPE python.file="C:\Python26\python.exe" "%%1" %%* > > > and the inverted commas around %%*, are they not necessary? > > No, I don't think so. > > Regards, > Martin Martin (or anybody else), The problem with FTYPE is solved. However, after having switched to py 3.1 with the help of the BAT script (which only changes FTYPE) I have another problem. (Just for reference, here is my batch file) @ECHO OFF ECHO ************************************************ ECHO Cambia a Python 3.1 ECHO ************************************************ ECHO * ECHO FTYPES: ECHO * ECHO .py=Python.File ECHO .pyc=Python.CompiledFile ECHO .pyo=Python.CompiledFile ECHO .pys=pysFile ECHO .pyw=Python.NoConFile ECHO * ECHO ************************************************ ECHO * FTYPE python.file="C:\Python31\python.exe" "%%1" %%* FTYPE python.compiledfile="C:\Python31\python.exe" "%%1" %%* FTYPE python.NoConFile="C:\Python31\pythonw.exe" "%%1" %%* ECHO * Pause @ECHO ON The problem is that, if I am on top of a .py file, and, with the mouse, I click on the right button, then I click on "Edit with IDLE", I get the 2.6 system, not the 3.1 one (which was supposed to be the correct one after the change). My question is: are there any other changes that I should do in order to fully switch from one version to another? Thank you in advance. Vicente Soler From hughaguilar96 at yahoo.com Mon Aug 23 20:00:55 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Mon, 23 Aug 2010 17:00:55 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> Message-ID: <80befec3-be41-4166-8487-9a147131c7b9@s9g2000yqd.googlegroups.com> On Aug 21, 12:32?pm, Alex McDonald wrote: > "Scintilla" gets about 2,080,000 results on google; "blather" gets > about 876,000 results. O Hugh, you pseudo-intellectual you! > > > with gutter language such as > > "turd" > > About 5,910,000 results. It has a long history, even getting a mention > in the Wyclif's 13th century bible. You looked up "blather" and "turd" on google *AND* you are not a pseudo-intellectual??? That is funny! I don't consider myself to be a pseudo-intellectual. I don't have any education however, so a pseudo-intellectual is the only kind of intellectual that I could be. From python at mrabarnett.plus.com Mon Aug 23 20:16:56 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 24 Aug 2010 01:16:56 +0100 Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation In-Reply-To: <4C730541.7040507@v.loewis.de> References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> <4C72FC62.1050908@v.loewis.de> <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> <4C730541.7040507@v.loewis.de> Message-ID: <4C730F78.9050502@mrabarnett.plus.com> Martin v. Loewis wrote: >> When I am logged-in in a session as an administrator, the BAT file on >> the Desktop, and I double-click on it, it does not work. > > This is not what I meant. Instead, right-click on the BAT file, > and select "run as administrator". > >> When you say to double-escape the percent signs, do you mean that in >> my BAT file I should write... >> >> FTYPE python.file="C:\Python26\python.exe" "%%1" %%* >> >> and the inverted commas around %%*, are they not necessary? > > No, I don't think so. > %1 is the placeholder for parameter 1, which you do want quoted. %* is the placeholder for all the remaining parameters, which you don't want quoted as single string. From hughaguilar96 at yahoo.com Mon Aug 23 20:26:46 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Mon, 23 Aug 2010 17:26:46 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> Message-ID: <009e2df0-6299-442d-aedf-e0e2e704d6c1@g17g2000yqe.googlegroups.com> On Aug 22, 3:40?pm, 1001nuits <1001nu... at gmail.com> wrote: > Another thing you learn in studying in University is the fact that you can ? > be wrong, which is quite difficult to accept for self taught people. Yet another thing you learn in studying in University, is the art of apple polishing! LOL If a person has graduated from college, it is not clear what if anything he has learned of a technical nature --- but it can be assumed that he has learned to be a head-bobber (someone who habitually bobs his head up and down in agreement when the boss is speaking) and has learned to readily admit to being wrong when pressured (when the boss looks at him without smiling for more than two seconds). These are the traits that bosses want in an employee --- that prove the employee to be "trainable." BTW, has anybody actually looked at my software? http://www.forth.org/novice.html All this pseudo-intellectual nonsense (including this post) is getting boring. Why don't we try discussing software for a while? I wrote that slide-rule program as a showcase of Forth. I've been thinking of porting it over to another language, possibly C. Maybe one of you C experts could write the C program though, as a comparison --- to show how much better C is than Forth. You can demonstrate that my code was badly written and strangely designed --- with a concrete example, rather than just a lot hand-waving and chest-thumping. From bblais at bryant.edu Mon Aug 23 21:18:01 2010 From: bblais at bryant.edu (Brian Blais) Date: Mon, 23 Aug 2010 21:18:01 -0400 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On Aug 23, 2010, at 16:47 , Almar Klein wrote: > A year ago or so I designed a simple file format that could do that > and is also human readable (binary data is compressed and then > base64 encoded). I use it extensively to store experiment data for > my research and also for configuration files for two open source > projects that I own: > http://code.google.com/p/ssdf/ > this is fantastic! what a great format! I've been looking for something like this for quite some time. thanks! bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais http://bblais.blogspot.com/ From mailtome200420032002 at gmail.com Mon Aug 23 21:26:05 2010 From: mailtome200420032002 at gmail.com (aj) Date: Mon, 23 Aug 2010 18:26:05 -0700 (PDT) Subject: make install DESTDIR References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> <4C72E6BD.1020204@v.loewis.de> Message-ID: On Aug 23, 2:23?pm, "Martin v. Loewis" wrote: > > Martin- Asking for help :) > > Ok. Please try the patch below. > > If this works, please make a bug report. > > Regards, > Martin > > Index: Lib/distutils/util.py > =================================================================== > --- Lib/distutils/util.py ? ? ? (Revision 84197) > +++ Lib/distutils/util.py ? ? ? (Arbeitskopie) > @@ -220,7 +220,7 @@ > ? ? ? ? ?if not os.path.isabs(pathname): > ? ? ? ? ? ? ?return os.path.join(new_root, pathname) > ? ? ? ? ?else: > - ? ? ? ? ? ?return os.path.join(new_root, pathname[1:]) > + ? ? ? ? ? ?return os.path.join(new_root, pathname.lstrip('/')) > > ? ? ?elif os.name == 'nt': > ? ? ? ? ?(drive, path) = os.path.splitdrive(pathname) Thanks Martin. That seems to work. I will file a bug report. Also, can you describe what the problem was? From nanothermite911fbibustards at gmail.com Mon Aug 23 22:30:52 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Mon, 23 Aug 2010 19:30:52 -0700 (PDT) Subject: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From nanothermite911fbibustards at gmail.com Mon Aug 23 22:39:05 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Mon, 23 Aug 2010 19:39:05 -0700 (PDT) Subject: Iran's self-defense options 'limitless' - against the YANQUI and KHAZAR Bustards - Brilliant ANALYSIS References: Message-ID: Iran's self-defense options 'limitless' - against the YANQUI and KHAZAR Bustards - Brilliant ANALYSIS Iran's self-defense options 'limitless' Tue Aug 24, 2010 12:9AM President Mahmoud AhmadinejadIran's President Mahmoud Ahmadinejad says no military action is expected to be taken against the Islamic Republic since enemies are aware of Iran's reaction. "Iran is not concerned by a prospective military attack by any country, although it is always prepared to defend itself," Ahmadinejad said in an interview with Qatar's al-Sharq and the Peninsula newspapers on Monday. "Enemies know well that Iran is an invincible fortress and I do not believe the US masters of the Zionists will allow the regime [in Tel Aviv] to take any measures against Iran," noted the Iranian chief executive. Asked about Iran's options in the case it is attacked, Ahmadinejad said, "Iran has limitless options which extends to all parts of the world." Commenting on the Israeli threats against Iran's sovereignty over the county's nuclear enrichment program, the Iranian president pointed out that "Israel is too weak to stage a military strike against Iran, but if it attacks, it will receive a devastating response, which will make it regret its aggression." He also dismissed the idea that Arab countries' soil would be used to launch attacks on Iran, saying that the "leaders of these countries are more prudent than that.? Ahmadinejad further downplayed US military might in its current wars in the Middle East region and rejected the speculations that an imminent war against Iran was the cause of the US troops' withdrawal from Iraq. GHN/MGH ============ BRILLIANT ANALYSIS http://www.tehrantimes.com/index_View.asp?code=225469 View Rate : 1531 # News Code : TTime- 225469 Print Date : Tuesday, August 24, 2010 ?Iran will stand beside any country threatened in region? Ahmadinejad: Israel lacks courage to attack Iran TEHRAN ? Iranian President Mahmoud Ahmadinejad says that Iran will stand beside any country in the region that is threatened. ?Iran will stand on the side of any country in the region which comes under pressure or is threatened,? Ahmadinejad said in an interview with Arabic satellite television network Al Jazeera aired on Sunday. He also said he doesn?t think the threats by the United States and Israel to attack Iran are ?serious?. ?Israel does not have the courage to do it? I do not think the threat is serious.? Ahmadinejad also stated that Israel is ?too weak? to attack the Islamic Republic. The Iranian president said that any military adventure by the Zionist regime targeting Iran would receive a ?crushing? response that would make Israel regret the decision. He went on to say that Persian Gulf states are ?too smart? to allow the U.S. to use bases on their territory for a strike on Iran. ?We regard the Persian Gulf countries as brothers and friends. They are smarter than that.? In the interview, the president also said he does not fear an attack by the U.S. because it could not even defeat a small army in Iraq. ?There are no logical reasons for the United States to carry out such an act,? President Ahmadinejad told Al Jazeera. ?Do you believe an army that has been defeated by a small army in Iraq can enter into a war with a large and well trained army like the Iranian army?? he asked, referring to the insurgents in Iraq. Iran will only ?look to the views of wise people? in the U.S. and not to those whose minds are obsessed with ?hatred and animosity?, the president said when asked about former U.S. ambassador to the UN John Bolton?s remarks, which had apparently encouraged Israel to attack the Bushehr plant before its start-up. Washington has no real motive to attack Iran and would not benefit from hostilities, he added. ?The friendship of Iran is much better than its hostility,? he said. He went on to say that Iran is working to produce nuclear fuel independently ?because receiving it from an outside source is conditioned on diplomatic criteria.? To prevent Iran from using the Bushehr reactor to produce plutonium, inspectors from the International Atomic Energy Agency and Russia, which built the power plant, are making sure Iran returns the fuel rods it receives after they are spent. ?There is a difference between those who produce and those who buy. We must make sure our nuclear power plant continues to operate. We do not trust the West, despite our good relations with Russia,? Ahmadinejad said. ?We need 20 power plants like the one in Bushehr,? he added. From wuwei23 at gmail.com Mon Aug 23 22:46:51 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 23 Aug 2010 19:46:51 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: "Russ P." wrote: > However, I've switched from Python to > Scala, so I really don't care. Really? Your endless whining in this thread would seem to indicate otherwise. From nobody at nowhere.com Mon Aug 23 22:53:40 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 24 Aug 2010 03:53:40 +0100 Subject: Discarding STDERR generated during subprocess.popen References: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> Message-ID: On Mon, 23 Aug 2010 10:38:02 -0700, Leon Derczynski wrote: > I would like to run an external program, and discard anything written > to stderr during its execution, capturing only stdout. My code > currently looks like: > > def blaheta_tag(filename): > blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/' > process = subprocess.Popen([blaheta_dir + 'exec/funcTag', > blaheta_dir + 'data/', filename], cwd=blaheta_dir, > stdout=subprocess.PIPE) > process.wait() > return process.communicate()[0] > > This returns stdout, and stderr ends up printing to the console. How > can I disregard anything sent to stderr such that it doesn't appear on > the console? Either: 1. Add "stderr=subprocess.PIPE" to the Popen() call. The communicate() method will read both stdout and stderr, and you just ignore stderr. 2. Redirect stderr to the null device: nul_f = open(os.devnull, 'w') process = subprocess.Popen(..., stderr = nul_f) nul_f.close() return process.communicate()[0] [os.devnull will be "/dev/null" on Unix, "nul" on Windows.] BTW: you shouldn't call process.wait() here. The communicate() method will call the wait() method when it receives EOF. If you call wait(), and the process tries to write more than a buffer's worth of output (the exact figure is platform-specific), your script will deadlock. The child process will block waiting for the script to consume its output, while the script will block waiting for the child process to terminate. From smallpox911 at gmail.com Mon Aug 23 23:02:02 2010 From: smallpox911 at gmail.com (small Pox) Date: Mon, 23 Aug 2010 20:02:02 -0700 (PDT) Subject: YANQUI cry babies concerned that Iran has achieved parity in DRONES and against the massive AIRCRAFT carriers which are like SITTING DUCKS. A nation needs AIRCRAFT carriers to venture out for IMPERIALISTIC assaults but cant go out on speed boats. References: Message-ID: <7211b12b-86fe-4a27-8b4b-674dec101fef@v41g2000yqv.googlegroups.com> YANQUI cry babies concerned that Iran has achieved parity in DRONES and against the massive AIRCRAFT carriers which are like SITTING DUCKS. A nation needs AIRCRAFT carriers to venture out for IMPERIALISTIC assaults but cant go out on speed boats. Yet the NUMEROUS fast boats can sink the AIRCRAFT carrier and make it a SAILING COFFIN. http://www.google.com/hostednews/afp/article/ALeqM5gYlBmnQz28otk-w_hvx1pZ5C= bl0w US concerned about Iran's assault boats, drone (AFP) =96 5 hours ago WASHINGTON =97 The United States voiced concern Monday over Iran's unveiling of new assault boats and an aerial drone, but said Iran's arms buildup will backfire as its neighbors gang up against it. Iran began mass-producing two high-speed variants of missile-launching assault boats on Monday, a day after Iranian President Mahmoud Ahmadinejad revealed a home-built bomber drone. "This is... something that is of concern to us and... concern to Iran's neighbors," State Department spokesman Philip Crowley told reporters. He said that while every country had the right to provide for its self- defense, the United States takes into account "systems that can potentially... threaten particular countries or peace and stability in the region." Faced with "the growth of Iran's capabilities over a number of years, we've stepped up our military cooperation with other countries in the region," Crowley said. "This is one of the reasons why... we believe that if Iran continues on the path that it's on... (it) might find itself less secure because you'll have countries in the region that join together to offset Iran's growing capabilities." He added that the United States is still open to "constructive dialogue" with Iran to answer questions it and the world community have about its nuclear program, which Washington fears is aimed at building a bomb. "But in the meantime, we will work with other countries to try to do everything that we can to maintain peace and stability in the region," Crowley said. Copyright =A9 2010 AFP. All rights reserved From russ.paielli at gmail.com Tue Aug 24 00:06:09 2010 From: russ.paielli at gmail.com (Russ P.) Date: Mon, 23 Aug 2010 21:06:09 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: <2938d973-9011-46d7-bcdb-bbd2827ee42d@v35g2000prn.googlegroups.com> On Aug 23, 7:46?pm, alex23 wrote: > "Russ P." wrote: > > However, I've switched from Python to > > Scala, so I really don't care. > > Really? Your endless whining in this thread would seem to indicate > otherwise. Yes, I guess I care some, but not much. I still use Python for some things, and I still have lots of "legacy" Python code that I still use. I just like to "whine" about zero-based indexing (but Scala is no different in that regard). It's my number one gripe. (My number zero gripe is semicolons after each statement -- but both Python and Scala got that one right, thank goodness.) From pahitezu at gmail.com Tue Aug 24 01:40:04 2010 From: pahitezu at gmail.com (pahi sharma) Date: Mon, 23 Aug 2010 22:40:04 -0700 (PDT) Subject: help in code Message-ID: I am new to python .I have a corpus which is written in Bengali and i want to read that file using python code.Can anyone help me in this matter. Thank You From martin at v.loewis.de Tue Aug 24 01:52:01 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 24 Aug 2010 07:52:01 +0200 Subject: make install DESTDIR In-Reply-To: References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> <4C72E6BD.1020204@v.loewis.de> Message-ID: <4C735E01.3050709@v.loewis.de> > Thanks Martin. That seems to work. I will file a bug report. Also, can > you describe what the problem was? If you have / as the prefix, you get two leading slashes, e.g. for //lib/python2.x. Any other prefix would have given you only a single slash: e.g. if it had been /usr, then you end up with /usr/lib/python2.x. Now, the code strips the first character to make it a relative path name (so that join can be used), which fails to work correctly if there are two leading slashes. HTH, Martin From steve-REMOVE-THIS at cybersource.com.au Tue Aug 24 03:15:08 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2010 07:15:08 GMT Subject: help in code References: Message-ID: <4c73717c$0$28639$c3e8da3@news.astraweb.com> On Mon, 23 Aug 2010 22:40:04 -0700, pahi sharma wrote: > I am new to python .I have a corpus which is written in Bengali and i > want to read that file using python code.Can anyone help me in this > matter. In Python 3, I believe this should work: f = open("filename", encoding="which-encoding-you-use") text = f.read() f.close() In Python 2, you probably need to do this: f = open("filename") bytes = f.read() text = bytes.decode('which-encoding-you-use') f.close() Hope this helps. -- Steven From steve-REMOVE-THIS at cybersource.com.au Tue Aug 24 03:23:31 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2010 07:23:31 GMT Subject: Helper classes design question References: <201008231047.57128.mail@johnohagan.com> Message-ID: <4c737373$0$28639$c3e8da3@news.astraweb.com> On Mon, 23 Aug 2010 19:22:46 +0200, Thomas Jollans wrote: > On Monday 23 August 2010, it occurred to John O'Hagan to exclaim: [...] >> I'm not sure if I'm on the right track here design-wise. Maybe this >> could be better done with inheritance (not my forte), but my first >> thought is that no, the helper classes (if that's what they are) are >> not actually a type of the main class, but are auxiliary to it. > > You could try using mixins. Without taking a position for or against mixins, I think it is only fair to point out that not everyone considers them a good design choice: Mixins considered harmful part 1 by Michele Simionato http://www.artima.com/weblogs/viewpost.jsp?thread=246341 And parts 2, 3, and 4: http://www.artima.com/weblogs/viewpost.jsp?thread=246483 http://www.artima.com/weblogs/viewpost.jsp?thread=254367 http://www.artima.com/weblogs/viewpost.jsp?thread=254507 -- Steven From kai.diefenbach at iqpp.de Tue Aug 24 03:54:37 2010 From: kai.diefenbach at iqpp.de (Kai Diefenbach) Date: Tue, 24 Aug 2010 09:54:37 +0200 Subject: ANN: LFC 1.0 Message-ID: Hi guys, today we released LFC 1.0. This is the first final release of LFC. LFC is a CMS based on Python, Django and jQuery. You can find the installer here: http://pypi.python.org/pypi/django-lfc/1.0. The installation is described here: http://packages.python.org/django-lfc/introduction/installation.html and should last just a few minutes. Its main features are: - Commenting - Cut/Copy?n Paste - Easy upload of images and files - Flexible Databases - Multilingual content - Pluggable - Role based per-object permissions - RSS Feeds - Search - Tagging - Time based publishing - Variable Templates - Variable Portlets - Variable Workflows - WYSIWYG-Editor You can find more information on following places: - Official Homepage: http://www.lfcproject.com/ - Documentation: http://packages.python.org/django-lfc - Download: http://pypi.python.org/pypi/django-lfc - Source Code: http://bitbucket.org/diefenbach/django-lfc - Google Group: http://groups.google.com/group/django-lfc - Twitter: http://twitter.com/lfcproject - IRC: irc://irc.freenode.net/django-lfc Any suggestions are highly appreciated. Thanks Kai From bill at supposedly.org Tue Aug 24 04:34:01 2010 From: bill at supposedly.org (Bill Green) Date: Tue, 24 Aug 2010 08:34:01 +0000 (UTC) Subject: curses KEY_* constants Message-ID: Hello, According to the documentation for the curses module, there are a number of constants defined for various special keys (such as KEY_DOWN, KEY_UP, KEY_BACKSPACE, etc.). However, these do not exist on my system (NetBSD 5). Looking at _cursesmodule.c, the code that sets up the KEY_ variables is #defined out on NetBSD (in initcurses() at line 2860 for Python 2.7). Does anyone know why this is so? Thanks. From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 24 04:40:14 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 24 Aug 2010 10:40:14 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4c73856e$0$8111$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: > >> Steven D'Aprano a ?crit : >>> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >>> >>>> Recursion can be quite a trick to get your mind round at first >>> Really? Do people actually find the *concept* of recursion to be >>> tricky? >>> >>> >> I onced worked in a shop (Win32 desktop / accouting applications mainly) >> where I was the only guy that could actually understand recursion. FWIW, >> I also was the only guy around that understood "hairy" (lol) concepts >> like callback functions, FSM, > > FSM? Flying Spaghetti Monster? Lol. Now this would at least be a pretty good description of the kind of code base these guys were used to !-) > >> polymorphism, hashtables, linked lists, >> ADTs, algorithm complexity etc... > > > Was there anything they *did* understand, Hmmm.... good question - but I didn't last long enough to find out. > or did they just bang on the > keyboard at random until the code compiled? *wink* Kind of, yes. From durumdara at gmail.com Tue Aug 24 05:21:00 2010 From: durumdara at gmail.com (durumdara) Date: Tue, 24 Aug 2010 02:21:00 -0700 (PDT) Subject: ftplib limitations? Message-ID: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> Hi! See this code: ---------------- import os, sys, ftplib from ftplib import FTP ftp = FTP() ftp.connect('ftp.anything.hu', 2121) ftp.login('?', '?') print ftp.getwelcome() ftp.set_pasv(False) ls = ftp.nlst() for s in ls: print "\nFilename:", '"%s"' % s, fsize = ftp.size(s) print "Size:", fsize print "..download:", d = {} d['buffer'] = [] d['size'] = 0 d['lastpercentp10'] = 0 def CallBack(Data): d['size'] = d['size'] + len(Data) d['buffer'].append(Data) percent = (d['size'] / float(fsize)) * 100 percentp10 = int(percent/10) if percentp10 > d['lastpercentp10']: d['lastpercentp10'] = percentp10 print str(percentp10 * 10) + "%", ftp.retrbinary("retr " + s, CallBack) print "" print "..downloaded, joining" dbuffer = "".join(d['buffer']) adir = os.path.abspath("b:\\_BACKUP_") newfilename = os.path.join(adir, s) print "..saving into", newfilename f = open(newfilename, "wb") f.write(dbuffer) f.close() print "..saved" print "..delete from the server" ftp.delete(s) print "..deleted" #sys.exit() print "\nFinished" ---------------- This code is login into a site, download and delete all files. I experienced some problem. The server is Windows and FileZilla, the client is Win7 and Python2.6. When I got a file with size 1 303 318 662 byte, python is halt on "retrbinary" line everytime. It down all of the file (100%) but the next line never reached. Some error I got, but this was in yesterday, I don't remember the text of the error. I want to ask that have Py2.6 some ftp limitations? I remembered that Zip have 2 GB limitation, the bigger size of the archive making infinite loop. May ftplib also have this, and this cause the problem... Or I need to add a "NOOP" command in Callback? Thanks for your help: dd From jeanmichel at sequans.com Tue Aug 24 05:29:21 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 24 Aug 2010 11:29:21 +0200 Subject: 79 chars or more? In-Reply-To: References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> Message-ID: <4C7390F1.8070401@sequans.com> Lawrence D'Oliveiro wrote: > In message > , Jean-Michel Pichavant > wrote: > > >> Saying that, if one intend to distribute its code, he should stick to 80 >> chars per line. >> > > Why? > Because some(many ?) people cannot deal with more than 80 chars, otherwise this rule would be pointless. JM From bill at supposedly.org Tue Aug 24 05:43:46 2010 From: bill at supposedly.org (Bill Green) Date: Tue, 24 Aug 2010 09:43:46 +0000 (UTC) Subject: curses KEY_* constants References: Message-ID: I perhaps should have mentioned I linked the Python curses module against ncurses rather than BSD curses. Perhaps NetBSD's curses doesn't support this feature, and that's why it's not included there. In any case, I removed the relevant #defines in _cursesmodule.c and got a Python that includes all the KEY_ constants in the curses module, but these constants (for the arrow keys at least) seem not to match the actual keycodes. From mark.leander at topicbranch.net Tue Aug 24 05:46:48 2010 From: mark.leander at topicbranch.net (Mark Leander) Date: Tue, 24 Aug 2010 09:46:48 +0000 (UTC) Subject: Save/load like matlab? References: Message-ID: Almar Klein gmail.com> writes: > A year ago or so I designed a simple file format that could do that and is also > human readable (binary data is compressed and then base64 encoded). I use it > extensively to store experiment data for my research and also for configuration > files for two open source projects that I own:http://code.google.com/p/ssdf/ That looks quite nice! Thank you for sharing! I see that at least in some case you use the generally unsafe eval() for parsing. For instance the following will consume CPU and memory for quite a while: >>> ssdf.loads(u'a = [0xffffffffffffffff**0xffffffffffffffff]') Regards Mark http://blog.topicbranch.net/2010/08/ssdf-simple-structured-data-format.html From bill at supposedly.org Tue Aug 24 06:01:16 2010 From: bill at supposedly.org (Bill Green) Date: Tue, 24 Aug 2010 10:01:16 +0000 (UTC) Subject: curses KEY_* constants References: Message-ID: On 2010-08-24, Bill Green wrote: > ... but these > constants (for the arrow keys at least) seem not to match the actual > keycodes. After looking at the documentation again I've realized I needed to enable keypad mode on the window for curses to catch the escape codes, and now everything's working. It seems to me that _cursesmodule.c should check at compile time to see if the platform is NetBSD AND ncurses isn't being used. Regards, Bill From ldo at geek-central.gen.new_zealand Tue Aug 24 06:13:26 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 24 Aug 2010 22:13:26 +1200 Subject: 79 chars or more? References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> Message-ID: In message , Jean-Michel Pichavant wrote: > Lawrence D'Oliveiro wrote: > >> In message >> , Jean-Michel >> Pichavant wrote: >> >>> Saying that, if one intend to distribute its code, he should stick to 80 >>> chars per line. >>> >> >> Why? >> > Because some(many ?) people cannot deal with more than 80 chars, > otherwise this rule would be pointless. So you assume the rule cannot be pointless? From ldo at geek-central.gen.new_zealand Tue Aug 24 06:16:40 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 24 Aug 2010 22:16:40 +1200 Subject: Reading the access attributes of directories in Windows References: <4C6D7E2A.9010703@timgolden.me.uk> Message-ID: In message , Nobody wrote: > 1. There are far more permission types than just "rwx". One thing Windows lacks is the ability to replace files that are currently open by another process. This is why Windows software updates require so many reboots. On Unix/Linux, you can replace the files, then restart the affected processes, instead of having to take them down for the entire duration of the update. This minimizes downtime. From ldo at geek-central.gen.new_zealand Tue Aug 24 06:21:29 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 24 Aug 2010 22:21:29 +1200 Subject: requirements in writing an email/rss/usenet client? References: Message-ID: In message , George Oliver wrote: > I currently use Thunderbird + Muttator, which is a nice setup; but, it > has some clunky parts, and I thought it might be simpler in the end to > start fresh than try to engage with what seems to be the massive-ness > of Thunderbird (of course, I may be disabused of this notion at some > point ;) ). I would advise you to use Thunderbird or some such MUA as a starting point. Why reinvent the wheel? From ldo at geek-central.gen.new_zealand Tue Aug 24 06:23:35 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 24 Aug 2010 22:23:35 +1200 Subject: Contains/equals References: Message-ID: In message , Alex Hall wrote: > def __eq__(self, obj): > if self.a==obj.a and self.b==obj.b: return True > return False Is there a ?Useless Use Of ...? award category for these ?if then return True; else return False? constructs? From eacheaby at gmail.com Tue Aug 24 06:28:17 2010 From: eacheaby at gmail.com (=?GB2312?B?t+fW0L6ist0=?=) Date: Tue, 24 Aug 2010 03:28:17 -0700 (PDT) Subject: sex-girl Message-ID: sex-girl http://bailong.0fees.net/ From almar.klein at gmail.com Tue Aug 24 07:13:03 2010 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 24 Aug 2010 13:13:03 +0200 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On 24 August 2010 11:46, Mark Leander wrote: > Almar Klein gmail.com> writes: > > A year ago or so I designed a simple file format that could do that and > is also > > human readable (binary data is compressed and then base64 encoded). I use > it > > extensively to store experiment data for my research and also for > configuration > > files for two open source projects that I own: > http://code.google.com/p/ssdf/ > > That looks quite nice! Thank you for sharing! > > I see that at least in some case you use the generally unsafe eval() for > parsing. > For instance the following will consume CPU and memory for quite a while: > > >>> ssdf.loads(u'a = [0xffffffffffffffff**0xffffffffffffffff]') > > I added an issue for this, will take a look at it. Thanks! Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Tue Aug 24 07:27:47 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 24 Aug 2010 13:27:47 +0200 Subject: What is a class method? In-Reply-To: <4c71f0c1$0$1861$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: <4C73ACB3.7090108@sequans.com> Paulo da Silva wrote: > Em 23-08-2010 04:30, James Mills escreveu: > >> On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva >> wrote: >> >>> I understand the concept of a static method. >>> However I don't know what is a class method. >>> Would anybody pls. explain me? >>> >> Please read this first: >> http://docs.python.org/library/functions.html#classmethod >> >> Then ask us questions :) >> > > I did it before posting ... > The "explanation" is not very clear. It is more like "how to use it". > > Thanks anyway. > A very naive approach: Instance methodes modify/use the instance. They requires a reference to the instance as first parameter (self) class Foo: def foo(self): print self.instanceAttribute Class methodes modify/use the class. They require a class as parameter (cls) class Foo: occurrences = 0 @classmethod def foo(cls): print "Number of %s occurrences : %s" % (cls.__name__, cls.occurrences) Static methods neither use a class nor an instance, thus require no parameter. In that case, the class acts like a namespace (<~>container): class Foo: @staticmethod def sayHello(): print "Hello" Foo.sayHello() Cheers, JM From jeanmichel at sequans.com Tue Aug 24 07:37:52 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 24 Aug 2010 13:37:52 +0200 Subject: Helper classes design question In-Reply-To: <201008231047.57128.mail@johnohagan.com> References: <201008231047.57128.mail@johnohagan.com> Message-ID: <4C73AF10.5010703@sequans.com> John O'Hagan wrote: > I want to know the best way to organise a bunch of functions designed to > operate on instances of a given class without cluttering the class itself with > a bunch of unrelated methods. > > What I've done is make what I think are called helper classes, each of which > are initialized with an instance of the main class and has methods which are > all of the same type (insofar as they return a boolean, or modify the object > in place, or whatever). > > I'm not sure if I'm on the right track here design-wise. Maybe this could be > better done with inheritance (not my forte), but my first thought is that no, > the helper classes (if that's what they are) are not actually a type of the > main class, but are auxiliary to it. > I've seen the following pattern in someone else code which was working pretty well: It was using composition instead of inheritance. When a method is not found in the 'main class', then it searches within all the registered helpers and automatically call the helper method if it exists. It was pretty much clever but has some drawbacks: - you have to handle collisions between helpers methods name - reading the code may become difficult because you're successfully calling methods that do not belong the the instance class. JM From mahaboobnisha at gmail.com Tue Aug 24 08:21:10 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Tue, 24 Aug 2010 05:21:10 -0700 (PDT) Subject: comp.lang.python Message-ID: <7413e35a-ca4c-4838-98c6-d97fc9c7832d@x18g2000pro.googlegroups.com> www.127760.blogspot.com From blog at rivadpm.com Tue Aug 24 08:59:19 2010 From: blog at rivadpm.com (Alex McDonald) Date: Tue, 24 Aug 2010 05:59:19 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> <80befec3-be41-4166-8487-9a147131c7b9@s9g2000yqd.googlegroups.com> Message-ID: <12c3d3b0-e433-4748-8b5f-5087e4f72a7a@l6g2000yqb.googlegroups.com> On 24 Aug, 01:00, Hugh Aguilar wrote: > On Aug 21, 12:32?pm, Alex McDonald wrote: > > > "Scintilla" gets about 2,080,000 results on google; "blather" gets > > about 876,000 results. O Hugh, you pseudo-intellectual you! > > > > with gutter language such as > > > "turd" > > > About 5,910,000 results. It has a long history, even getting a mention > > in the Wyclif's 13th century bible. > > You looked up "blather" and "turd" on google *AND* you are not a > pseudo-intellectual??? That is funny! > > I don't consider myself to be a pseudo-intellectual. I don't have any > education however, so a pseudo-intellectual is the only kind of > intellectual that I could be. I don't have any formal CS education, nor a degree in anything else. But that doesn't make me an anti-intellectual by instinct (the instinct would be jealousy, I guess), nor does it stop me from learning. Or using Google, something I'm sure you do too. We have a great degree of admiration and fondness for intellectuals in Europe; the French in particular hold them in very high regard. Perhaps disdain of learning and further education is peculiar to a certain section of American society, as the label "intellectual" (often, "liberal intellectual") appears to be used as a derogatory term. I have no idea what a pseudo-intellectual might be, but it's evident you mean it in much the same way. From tundra at tundraware.com Tue Aug 24 09:06:04 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Tue, 24 Aug 2010 08:06:04 -0500 Subject: Using String Methods In Jump Tables In-Reply-To: <87fwy510ty.fsf@busola.homelinux.net> References: <87fwy510ty.fsf@busola.homelinux.net> Message-ID: On 8/23/2010 4:22 PM, Hrvoje Niksic wrote: > Tim Daneliuk writes: > >> You can get away with this because all string objects appear to point to common >> method objects. That is,: id("a".lower) == id("b".lower) > > A side note: your use of `id' has misled you. id(X)==id(Y) is not a > perfect substitue for the X is Y. :) > > "a".lower and "b".lower obviously cannot be the same object, because in > that case, how could they behave differently when called? > >>>> "a".lower() > 'a' >>>> "b".lower() # this should also return 'a' if "b".lower is the > # same object > 'b' > > Yet, id("a".lower) == id("b".lower) evaluates as True. > > What happens is, when the expression id("a".lower) == id("b.lower") is > evaluated, each of the bound method objects created with subexpressions > "a".lower" and "b".lower is referenced and thrown away as soon as "id" > is called (i.e. pretty much immediately), so the two never exist at the > same time. By the time "b".lower needs to be created, "a".lower is > freshly deceased, and the memory it used to occupy is ready for use, and > waiting at the top of the freelist. > > If CPython happened to use a different allocation/garbage collection > strategy and failed to reuse the same memory address immediately, your > code would just (happen to) work. Thanks for the clarification. -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From hniksic at xemacs.org Tue Aug 24 09:16:12 2010 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 24 Aug 2010 15:16:12 +0200 Subject: Contains/equals References: Message-ID: <87d3t8w3qb.fsf@busola.homelinux.net> Lawrence D'Oliveiro writes: > In message , Alex Hall > wrote: > >> def __eq__(self, obj): >> if self.a==obj.a and self.b==obj.b: return True >> return False > > Is there a ?Useless Use Of ...? award category for these ?if then > return True; else return False? constructs? Well, remember that self.a == obj.a can return something other than bool, and the and operator will evaluate to either False or the last value. Maybe he doesn't want to propagate the non-bools out of his __eq__. :) what's-next-"useless-use-of-"useless-use-of...""-ly y'rs From funthyme at gmail.com Tue Aug 24 09:49:08 2010 From: funthyme at gmail.com (John Pinner) Date: Tue, 24 Aug 2010 06:49:08 -0700 (PDT) Subject: Using String Methods In Jump Tables References: Message-ID: <98f1a235-3ee8-44ee-b886-3fc8ec7e46cf@5g2000yqz.googlegroups.com> On Aug 20, 12:27?am, Tim Daneliuk wrote: > Problem: > > ? Given tuples in the form (key, string), use 'key' to determine > ? what string method to apply to the string: > > ? ? key ? ? ? ? ? operation > ? ? ----------------------- > > ? ? ?l ? ? ? ? ? ?lower() > ? ? ?u ? ? ? ? ? ?upper() > ? ? ?t ? ? ? ? ? ?title() > ? ? ?... > > Commentary: > > ? ?Easy, right? ?Well ... except that I would really, really like > ? ?to avoid cascading ifs or eval based solutions. ?I'd like to implement > ? ?this as a jump table dictionary: > > ? ? ?jt = { 'l' : lower_function reference, > ? ? ? ? ? ? 'u' : upper_function reference, > ? ? ? ? ? ? ?... > ? ? ? ? ? } > > ? ?So I could then do this: > > ? ? ?string = jt[key](string) > > But There's A Problem: > > ? ?I tried to do this: > > ? ? ?jt = {'l', "".lower, > ? ? ? ? ? ?'u', "".upper, > ? ? ? ? ? ?... > ? ? ? ? ? } > > ? ?You can get away with this because all string objects appear to point to common > ? ?method objects. ?That is,: id("a".lower) == id("b".lower) > > ? ?HOWEVER, you cannot then do this: > > ? ? ?string = jt[key](string) > > ? ?Why? ?Because the methods of a string, while common to all strings > ? ?*do not accept an arg*. ?They are implemented to "know" about the > ? ?string instance they "belong to" (that contains them). > > (Forgive me here, I am probably not using some of the OO arcana properly...) > > I realize that the string module has many of the same functions that > are found as methods on strings. ?But it doesn't have all of them - > the .title() method is notably absent. ?If this were not the case, > I could happily do things like 'l' : string.lower ?and my approach > would work fine. ? > > Even if I could use the string module, I'd still be curious though: > > ? ?How do you get a reference to a method found in one object instance, but > ? ?actually apply it to another instance of the same class? ?I'm guessing this may > ? ?involve fiddling with some of the internal __ variables, but I'm not > ? ?quite sure where to go next. > > As I said, I know I could do this as a set of cascading ifs or even as an > eval, but I'm loathe to use such approaches. I like jump tables as a > structural construct because they are easy to understand and maintain. I > also realize that what I'm asking may be violating some deeply held notion > of OO purity, but, well, now I'm just curious if there is a way to do this I think the solution to what you are asking for is to use getattr(), eg: >>> ops={'u':'upper','l':'lower'} >>> s='hello world' >>> getattr( s, ops['u'] )() 'HELLO WORLD' >>> For info on getattr() see: http://docs.python.org/library/functions.html#getattr or http://effbot.org/zone/python-getattr.htm Best wishes, John -- From sschwarzer at sschwarzer.net Tue Aug 24 10:29:12 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 24 Aug 2010 16:29:12 +0200 Subject: ftplib limitations? In-Reply-To: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> Message-ID: <4C73D738.9030501@sschwarzer.net> Hi durumdara, On 2010-08-24 11:21, durumdara wrote: > def CallBack(Data): > d['size'] = d['size'] + len(Data) > d['buffer'].append(Data) > percent = (d['size'] / float(fsize)) * 100 > percentp10 = int(percent/10) > if percentp10 > d['lastpercentp10']: > d['lastpercentp10'] = percentp10 > print str(percentp10 * 10) + "%", > > ftp.retrbinary("retr " + s, CallBack) > print "" > print "..downloaded, joining" > dbuffer = "".join(d['buffer']) > [...] > This code is login into a site, download and delete all files. > > I experienced some problem. > The server is Windows and FileZilla, the client is Win7 and Python2.6. > When I got a file with size 1 303 318 662 byte, python is halt on > "retrbinary" line everytime. So if I understand correctly, the script works well on smaller files but not on the large one? > It down all of the file (100%) but the next line never reached. _Which_ line is never reached? The `print` statement after the `retrbinary` call? > Some error I got, but this was in yesterday, I don't remember the text > of the error. Can't you reproduce the error by executing the script once more? Can you copy the file to another server and see if the problem shows up there, too? I can imagine the error message (a full traceback if possible) would help to say a bit more about the cause of the problem and maybe what to do about it. Stefan From aahz at pythoncraft.com Tue Aug 24 10:54:45 2010 From: aahz at pythoncraft.com (Aahz) Date: 24 Aug 2010 07:54:45 -0700 Subject: iter References: Message-ID: In article , Terry Reedy wrote: > >Changing a list while iterating through it is possible, sometimes >useful, but error prone, especially with insert or delete. Changing a >dict while iterating through it is prohibited since the iteration order >depends on the exact internal structure. That in turn depends on the >history of additions and deletions. Although I agree in general with your warning, you are factually incorrect about dicts: >>> d = {1:2, 3:4} >>> i = iter(d) >>> i.next() 1 >>> d[1] = 'foo' >>> d {1: 'foo', 3: 4} Essentially, the prohibition is against changing the *keys* of lists and dicts (where list keys are the indexes). So what you can't do is add or delete dict keys and changing the position or order of list elements is a Bad Idea. But changing dict or list values is fine as long as you're careful that's *all* you're doing. Python newcomers are best off simply avoiding any list/dict mutation during iteration. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From ian at ianhobson.co.uk Tue Aug 24 11:25:30 2010 From: ian at ianhobson.co.uk (Ian Hobson) Date: Tue, 24 Aug 2010 16:25:30 +0100 Subject: adodbapi help needed Message-ID: <4C73E46A.7050207@ianhobson.co.uk> Hi all, I am just starting to learn Python and I have a setup problem - I think. Python 3.1. I have a small test script that is not working as expected. Start script----------- # coding=utf8 import adodbapi connectString = ( "DRIVER={MySQL ODBC 5.1 Driver} ;" "SERVER=127.0.0.1;" "PORT=3306;" "DATABASE=moschatel;" "USER=Moschatel;" "PASSWORD=badger43time;" "OPTION=3;" ) # MySQL ODBC 5.1 Driver - version 5.01.06.00 is installed db = adodbapi.connect(connectString) ------------end script -------------- I get an error message that reads D:\websites\moschatel\sop\Printing>test.py Traceback (most recent call last): File "D:\websites\moschatel\sop\Printing\test.py", line 13, in db = adodbapi.connect(connectString) AttributeError: 'module' object has no attribute 'connect' Now, adodbapi is installed into D:\websites\moschatel\sop\Printing\adodbapi and contains file adodbapi.py, and line 279 reads def connect(connection_string, timeout=30): I expected that to be called. What have I missed? Regards Ian From aahz at pythoncraft.com Tue Aug 24 11:37:59 2010 From: aahz at pythoncraft.com (Aahz) Date: 24 Aug 2010 08:37:59 -0700 Subject: Python parsing XML file problem with SAX References: Message-ID: In article , Stefan Behnel wrote: >Christian Heimes, 10.08.2010 01:39: >> Am 10.08.2010 01:20, schrieb Aahz: >>> The docs say, "Parses an XML section into an element tree incrementally". >>> Sure sounds like it retains the entire parsed tree in RAM. Not good. >>> Again, how do you parse an XML file larger than your available memory >>> using something other than SAX? >> >> The document at >> http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ explains it >> one way. >> >> The iterparser approach is ingenious but it doesn't work for every XML >> format. Let's say you have a 10 GB XML file with one million >> tags. An iterparser doesn't load the entire document. Instead it >> iterates over the file and yields (for example) one million ElementTrees >> for each tag and its children. You can get the nice API of >> ElementTree with the memory efficiency of a SAX parser if you obey >> "Listing 4". > >In the very common case that you are interested in all children of the root >element, it's even enough to intercept on the specific tag name (lxml.etree >has an option for that, but an 'if' block will do just fine in ET) and just >".clear()" the child element at the end of the loop body. That results in >very fast and simple code, but will leave the tags in the tree while only >removing their content and attributes. Usually works well enough for >several ten thousand elements, especially when using cElementTree. Thanks to both of you! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From sumit.jha50 at gmail.com Tue Aug 24 11:49:44 2010 From: sumit.jha50 at gmail.com (sumit) Date: Tue, 24 Aug 2010 08:49:44 -0700 (PDT) Subject: easy n perfect earning Message-ID: hey guys try dis link n make account...click on view adds...click on every add n leave it 4 60sec n once cmpleted click on my account n u vl c tat u got $40.. http://www.fineptc.com/index.php?ref=sumit4u2010 ...must try...i hav experienced and its safe From nanothermite911fbibustards at gmail.com Tue Aug 24 12:11:06 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 09:11:06 -0700 (PDT) Subject: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: <1ececad8-7f6b-412f-9eba-61ac82e7ae4f@j8g2000yqd.googlegroups.com> CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From nanothermite911fbibustards at gmail.com Tue Aug 24 12:17:57 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 09:17:57 -0700 (PDT) Subject: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: CENSORSHIP by GOOGLE NSA BUSTARDS deleted my earlier post dated Mon, Aug 23, 2010 at 7:33 PM from google groups. but its archived in the mailing lists linked to the various newsgroups. CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From dak at gnu.org Tue Aug 24 12:24:17 2010 From: dak at gnu.org (David Kastrup) Date: Tue, 24 Aug 2010 18:24:17 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> Message-ID: <87bp8sou6m.fsf@lola.goethe.zz> John Bokma writes: > On the other hand: some people I knew during my studies had no problem > at all with introducing countless memory leaks in small programs (and > turning off compiler warnings, because it gave so much noise...) [...] > As for electrical engineering: done that (BSc) and one of my class > mates managed to connect a transformer the wrong way > around.... twice. Yet he had the highest mark in our class. Anybody worth his salt in his profession has a trail of broken things in his history. The faster it thinned out, the better he learned. The only reliable way never to break a thing is not to touch it in the first place. But that will not help you if it decides to break on its own. -- David Kastrup From tim.arnold at sas.com Tue Aug 24 12:32:31 2010 From: tim.arnold at sas.com (Tim Arnold) Date: Tue, 24 Aug 2010 12:32:31 -0400 Subject: Working with PDFs? References: Message-ID: wrote in message news:mailman.2465.1282591017.1673.python-list at python.org... >> writes: > >>> - Pull out text from each PDF page (to search for specific words) >>> - Combine separate pdf documents into one document >>> - Add bookmarks (with destination settings) > >> PDF Shuffler is a Python app which does PDF merging and splitting very >> well. I don't think it does anything else, though, but maybe that's >> where your code comes in? > > Thank you Anssi, MRAB, Terry and Geremy for your replies. I've been > researching the apps you have recommended. Just curious if anyone has > used pyPdf? While testing this, it seems to work pretty well for > combining pdf files (seems to keep the annotation notes nicely also) > and pulling out the text contents. I'm not sure I'm going to be able > to find anything that can add bookmarks though. If you have used pyPdf, > would you mind sharing your thoughts about it? > > Thanks. > > Jay Hi Jay, I use pyPdf and I seem to remember I had to patch it so it didn't crash when a PDF dictionary contained duplicate keys. (the part that holds the document properties I think). Anyway, I use the package to get info from that document properties dictionary, page count and etc for displaying a build report to users of a customized LaTeX system. So I'm using LaTeX to generate the PDFs and pyPDF to glean data about the pdfs after the builds. I'd like to be able to do more with it, like find out whether any fonts in the doc are not embedded for example. --Tim Arnold From richie8105 at gmail.com Tue Aug 24 12:33:11 2010 From: richie8105 at gmail.com (richie05 bal) Date: Tue, 24 Aug 2010 09:33:11 -0700 (PDT) Subject: seach for pattern based on string Message-ID: <6054e266-4730-411e-9a27-9b501e6086cd@j8g2000yqd.googlegroups.com> i am starting to learn python and I am stuck with query I want to generate with python File looks something like this TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, publishingCompanyId 7} TRACE: AddNewBookD {bookId 21, noofBooks 6577, authorId 42, publishingCompanyId 8} I want to first search for AddNewBookD if found store bookId, noofBooks, authorId and publishingCompanyId I know how to search for only AddNewBookD or find the pattern bookId 20, noofBooks 6576, authorId 41, publishingCompanyId 7 but I don't know how search one based on another. From emile at fenx.com Tue Aug 24 13:08:28 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 24 Aug 2010 10:08:28 -0700 Subject: adodbapi help needed In-Reply-To: <4C73E46A.7050207@ianhobson.co.uk> References: <4C73E46A.7050207@ianhobson.co.uk> Message-ID: On 8/24/2010 8:25 AM Ian Hobson said... > Hi all, > > I am just starting to learn Python and I have a setup problem - I think. > Python 3.1. > > > def connect(connection_string, timeout=30): > > I expected that to be called. > > What have I missed? > The current revision includes the caveat: This module source should run correctly in CPython versions 2.3 and later, or IronPython version 2.6 and later, or, after running through 2to3.py, CPython 3.0 or later. Does that help? Emile From dani.valverde at gmail.com Tue Aug 24 13:15:11 2010 From: dani.valverde at gmail.com (Dani Valverde) Date: Tue, 24 Aug 2010 19:15:11 +0200 Subject: Declare self.cursor Message-ID: <4C73FE1F.5000206@gmail.com> Hello! I am working on a GUI to connect to a MySQL database using MySQLdb (code in attached file). I define the cursor in lines 55-66 in the OnLogin function within the LoginDlg class. /db= MySQLdb.connect(host='localhost', user=Username , passwd=pwd, db='Ornithobase') self.cursor = db.cursor()/ When I try to use the cursor on another part of the code (EditUser class, line 176) /sql = 'select substring_index(CURRENT_USER(),"@",1)' login.cursor.execute(sql)/ I get this error: /AttributeError: 'LoginDlg' object has no attribute 'cursor'/ You can check the code for details, I think is better. Cheers! Dani -- Daniel Valverde Saub? c/Joan Maragall 37 4 2 17002 Girona Spain Tel?fon m?bil: +34651987662 e-mail: dani.valverde at gmail.com http://www.acrocephalus.net http://natupics.blogspot.com Si no ?s del tot necessari, no imprimeixis aquest missatge. Si ho fas utilitza paper 100% reciclat i blanquejat sense clor. D'aquesta manera ajudar?s a estalviar aigua, energia i recursos forestals. GR?CIES! Do not print this message unless it is absolutely necessary. If you must print it, please use 100% recycled paper whitened without chlorine. By doing so, you will save water, energy and forest resources. THANK YOU! -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: OrnithobaseGUI.txt URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: dani_valverde.vcf Type: text/x-vcard Size: 296 bytes Desc: not available URL: From mwilson at the-wire.com Tue Aug 24 13:39:23 2010 From: mwilson at the-wire.com (Mel) Date: Tue, 24 Aug 2010 13:39:23 -0400 Subject: Declare self.cursor References: Message-ID: Dani Valverde wrote: > Hello! > I am working on a GUI to connect to a MySQL database using MySQLdb (code > in attached file). I define the cursor in lines 55-66 in the OnLogin > function within the LoginDlg class. > > /db= MySQLdb.connect(host='localhost', user=Username , passwd=pwd, > db='Ornithobase') > self.cursor = db.cursor()/ > > When I try to use the cursor on another part of the code (EditUser > class, line 176) > > /sql = 'select substring_index(CURRENT_USER(),"@",1)' > login.cursor.execute(sql)/ > > I get this error: > > /AttributeError: 'LoginDlg' object has no attribute 'cursor'/ > > You can check the code for details, I think is better. Did you actually click the loginBtn? Mel. From astan.chee at al.com.au Tue Aug 24 15:18:52 2010 From: astan.chee at al.com.au (Astan Chee) Date: Wed, 25 Aug 2010 05:18:52 +1000 Subject: equivalent of source in python? Message-ID: <4C741B1C.3080405@al.com.au> Hi, I'm trying to convert my tcsh script to python and am stuck at one part, particularly the part of the script that looks like this: #!/bin/tcsh setenv LSFLOG /var/tmp/lsf_log source /etc/setup unalias cp umask 0 env >> ${AFLOG} What is the equivalent of doing this in python2.5? Thanks again From mailtome200420032002 at gmail.com Tue Aug 24 15:21:31 2010 From: mailtome200420032002 at gmail.com (aj) Date: Tue, 24 Aug 2010 12:21:31 -0700 (PDT) Subject: make install DESTDIR References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> <4C72E6BD.1020204@v.loewis.de> <4C735E01.3050709@v.loewis.de> Message-ID: On Aug 23, 10:52?pm, "Martin v. Loewis" wrote: > > Thanks Martin. That seems to work. I will file a bug report. Also, can > > you describe what the problem was? > > If you have / as the prefix, you get two leading slashes, e.g. for > //lib/python2.x. Any other prefix would have given you only a single > slash: e.g. if it had been /usr, then you end up with /usr/lib/python2.x. > > Now, the code strips the first character to make it a relative path name > (so that join can be used), which fails to work correctly if there are > two leading slashes. > > HTH, > Martin Thanks a lot for the help Martin. I have created http://bugs.python.org/issue9674 From dsdale24 at gmail.com Tue Aug 24 15:31:00 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Tue, 24 Aug 2010 12:31:00 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> Message-ID: <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> On Aug 23, 9:58?am, Darren Dale wrote: > The following script runs without problems on Ubuntu and Windows 7. > h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > h5py/): > > from multiprocessing import Pool > import h5py > > def update(i): > ? ? print i > > def f(i): > ? ? "hello foo" > ? ? return i*i > > if __name__ == '__main__': > ? ? pool = Pool() > ? ? for i in range(10): > ? ? ? ? pool.apply_async(f, [i], callback=update) > ? ? pool.close() > ? ? pool.join() > > On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > comment out the as-yet unused h5py import, otherwise I get a > traceback: > > Exception in thread Thread-1: > Traceback (most recent call last): > ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > lib/python2.6/threading.py", line 532, in __bootstrap_inner > ? ? self.run() > ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > lib/python2.6/threading.py", line 484, in run > ? ? self.__target(*self.__args, **self.__kwargs) > ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > lib/python2.6/multiprocessing/pool.py", line 226, in _handle_tasks > ? ? put(task) > PicklingError: Can't pickle : attribute lookup > __builtin__.function failed This is a really critical bug for me, but I'm not sure how to proceed. Can I file a bug report on the python bugtracker if the only code I can come up with to illustrate the problem requires a lame import of a third party module? From barry at python.org Tue Aug 24 15:31:46 2010 From: barry at python.org (Barry Warsaw) Date: Tue, 24 Aug 2010 15:31:46 -0400 Subject: Released: Python 2.6.6 Message-ID: <20100824153146.69874f04@heresy> Hello fellow Pythoneers and Pythonistas, I'm very happy to announce the release of Python 2.6.6. A truly impressive number of bugs have been fixed since Python 2.6.5. Source code and Windows installers for Python 2.6.6 are now available here: http://www.python.org/download/releases/2.6.6/ The full details of everything that's changed is available in the NEWS file: http://www.python.org/download/releases/2.6.6/NEWS.txt Python 2.6.6 marks the end of regular maintenance releases for the Python 2.6 series. From now until October 2013, only security related, source-only releases of Python 2.6 will be made available. After that date, Python 2.6 will no longer be supported, even for security bugs. My deepest appreciation go out to everyone who has helped contribute fixes great and small, and much testing and bug tracker gardening for Python 2.6.6. Enjoy, -Barry (on behalf of the Python development community) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: not available URL: From smallpox911 at gmail.com Tue Aug 24 15:36:28 2010 From: smallpox911 at gmail.com (small Pox) Date: Tue, 24 Aug 2010 12:36:28 -0700 (PDT) Subject: CRIMINAL YanQui MARINES BUSTARDS Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: CENSORSHIP by GOOGLE NSA BUSTARDS deleted my earlier post dated Mon, Aug 23, 2010 at 7:33 PM from google groups. but its archived in the mailing lists linked to the various newsgroups. CRIMINAL YanQui MARINES BUSTARDS Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From smallpox911 at gmail.com Tue Aug 24 15:38:00 2010 From: smallpox911 at gmail.com (small Pox) Date: Tue, 24 Aug 2010 12:38:00 -0700 (PDT) Subject: CRIMINAL YanQui MARINES BUSTARDS Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: <156f547e-c730-4e16-9790-0c0636ddf12d@f42g2000yqn.googlegroups.com> CENSORSHIP by GOOGLE NSA BUSTARDS deleted my earlier post dated Mon, Aug 23, 2010 at 7:33 PM from google groups. but its archived in the mailing lists linked to the various newsgroups. CRIMINAL YanQui MARINES BUSTARDS Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From steve.ferg.bitbucket at gmail.com Tue Aug 24 16:00:24 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Tue, 24 Aug 2010 13:00:24 -0700 (PDT) Subject: Help please! strange Tkinter behavior has me totally baffled. Message-ID: <6270b512-8b73-434d-83c3-ec5c60100eb1@w17g2000vbn.googlegroups.com> I have a short Python script that uses Tkinter to display an image. Here is the script =================================================================== import sys, os from Tkinter import * root = Tk() # A: create a global variable named "root" def showPicture(imageFilename): # global root #C: make root global root = Tk() # B: create a local variable named "root" imageFrame = Frame(root) imageFrame.pack() imageObject = PhotoImage(file=imageFilename) label = Label(imageFrame,image=imageObject) label.pack() root.mainloop() showPicture("python_and_check_logo.gif") =================================================================== The strange thing is that it crashes with this traceback... =================================================================== Traceback (most recent call last): File "easygui_test3.py", line 19, in showPicture("python_and_check_logo.gif") File "easygui_test3.py", line 14, in showPicture label = Label(imageFrame,image=imageObject) File "L:\FergLabstatPublic\Python26\lib\lib-tk\Tkinter.py", line 2474, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "L:\FergLabstatPublic\Python26\lib\lib-tk\Tkinter.py", line 1940, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "pyimage1" doesn't exist =================================================================== If I comment out either line A or line B, the script works fine. What I don't understand is why creating a global "root" variable and a local "root" variable causes the script to crash. Even more puzzling... if I uncomment line C, so that "root" in line B refers to a global "root" variable, the script still crashes. I'm totally baffled. Does anybody know what is going on here? -- Steve Ferg (I'm running Python 2.6 under Windows, but I get the same behavior under Solaris.) From news1234 at free.fr Tue Aug 24 16:01:19 2010 From: news1234 at free.fr (News123) Date: Tue, 24 Aug 2010 22:01:19 +0200 Subject: equivalent of source in python? In-Reply-To: References: Message-ID: <4c742513$0$9846$426a74cc@news.free.fr> On 08/24/2010 09:18 PM, Astan Chee wrote: > Hi, > I'm trying to convert my tcsh script to python and am stuck at one part, > particularly the part of the script that looks like this: > > #!/bin/tcsh > setenv LSFLOG /var/tmp/lsf_log > source /etc/setup > unalias cp > umask 0 > env >> ${AFLOG} > > What is the equivalent of doing this in python2.5? > Thanks again the equivalent would be exec(), but I'm not sure, that it is a good idea to try to make a word by word translation of a shell script into python. you could do exec( open("/etc/setup").read() ) but of course you had to translate /etc/setup to python. From steve.ferg.bitbucket at gmail.com Tue Aug 24 16:06:06 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Tue, 24 Aug 2010 13:06:06 -0700 (PDT) Subject: Questions, newbies, and community (was: python terminology on classes) References: <8e60e2db-205d-4b8b-9c19-1d46e2318cb8@h20g2000vbs.googlegroups.com> <87tyna2dc7.fsf_-_@benfinney.id.au> Message-ID: I stand corrected. I didn't know the background. Thanks for supplying the larger picture. :-) From sschwarzer at sschwarzer.net Tue Aug 24 16:12:06 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 24 Aug 2010 22:12:06 +0200 Subject: equivalent of source in python? In-Reply-To: References: Message-ID: <4C742796.8020904@sschwarzer.net> Hi Astan, On 2010-08-24 21:18, Astan Chee wrote: > I'm trying to convert my tcsh script to python and am stuck at one part, > particularly the part of the script that looks like this: > > #!/bin/tcsh > setenv LSFLOG /var/tmp/lsf_log > source /etc/setup > unalias cp > umask 0 > env >> ${AFLOG} > > What is the equivalent of doing this in python2.5? I guess it doesn't make sense to "translate" this to Python line by line. For example, you can't "source" shell code into a Python program. The above commands don't look as if they were the purpose of the program, but rather mostly some preparation/setup before solving the actual problem. Maybe it's more helpful to tell us what you want to achieve in the end and we might be able to make suggestions on that. How long is the shell script and what's your Python code so far? Stefan From clp2 at rebertia.com Tue Aug 24 16:28:42 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 24 Aug 2010 13:28:42 -0700 Subject: equivalent of source in python? In-Reply-To: <4C741B1C.3080405@al.com.au> References: <4C741B1C.3080405@al.com.au> Message-ID: On Tue, Aug 24, 2010 at 12:18 PM, Astan Chee wrote: > Hi, > I'm trying to convert my tcsh script to python and am stuck at one part, > particularly the part of the script that looks like this: > > #!/bin/tcsh > setenv LSFLOG /var/tmp/lsf_log > source /etc/setup > unalias cp > umask 0 > env >> ${AFLOG} > > What is the equivalent of doing this in python2.5? I agree with Stefan, but anyway, here's an approximate untested literal translation: import os import subprocess os.environ['LSFLOG'] = '/var/tmp/lsf_log' subprocess.check_call(['tcsh', '/etc/setup']) os.umask(0) out = open(os.environ['AFLOG'], 'a') subprocess.check_call(['env'], stdout=out) out.close() Cheers, Chris -- http://blog.rebertia.com From emile at fenx.com Tue Aug 24 16:32:26 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 24 Aug 2010 13:32:26 -0700 Subject: equivalent of source in python? In-Reply-To: <4C741B1C.3080405@al.com.au> References: <4C741B1C.3080405@al.com.au> Message-ID: On 8/24/2010 12:18 PM Astan Chee said... > Hi, > I'm trying to convert my tcsh script to python and am stuck at one part, > particularly the part of the script that looks like this: > > #!/bin/tcsh > setenv LSFLOG /var/tmp/lsf_log > source /etc/setup > unalias cp > umask 0 > env >> ${AFLOG} > > What is the equivalent of doing this in python2.5? > Thanks again source == import * Although that's generally considered non-pythonic. Emile From thomas at jollybox.de Tue Aug 24 16:32:29 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 24 Aug 2010 22:32:29 +0200 Subject: problem with simple multiprocessing script on OS X In-Reply-To: <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: <201008242232.29481.thomas@jollybox.de> On Tuesday 24 August 2010, it occurred to Darren Dale to exclaim: > On Aug 23, 9:58 am, Darren Dale wrote: > > The following script runs without problems on Ubuntu and Windows 7. > > h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > > h5py/): > > > > from multiprocessing import Pool > > import h5py > > > > def update(i): > > print i > > > > def f(i): > > "hello foo" > > return i*i > > > > if __name__ == '__main__': > > pool = Pool() > > for i in range(10): > > pool.apply_async(f, [i], callback=update) > > pool.close() > > pool.join() > > > > On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > > comment out the as-yet unused h5py import, otherwise I get a > > traceback: What on earth is h5py doing there? If what you're telling us is actually happening, and the code works 1:1 on Linux and Windows, but fails on OSX, and you're using the same versions of h5py and Python, then the h5py initialization code is not only enticing multiprocessing to try to pickle something other than usual, but it is also doing that due to some platform- dependent witchcraft, and I doubt there's very much separating the OSX versions from the Linux versions of anything involved. > This is a really critical bug for me, but I'm not sure how to proceed. > Can I file a bug report on the python bugtracker if the only code I > can come up with to illustrate the problem requires a lame import of a > third party module? I doubt this is an issue with Python. File a bug on the h5py tracker and see what they say. The people there might at least have some vague inkling of what may be going on. From thomas at jollybox.de Tue Aug 24 16:36:00 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 24 Aug 2010 22:36:00 +0200 Subject: equivalent of source in python? In-Reply-To: <4c742513$0$9846$426a74cc@news.free.fr> References: <4c742513$0$9846$426a74cc@news.free.fr> Message-ID: <201008242236.01193.thomas@jollybox.de> On Tuesday 24 August 2010, it occurred to News123 to exclaim: > On 08/24/2010 09:18 PM, Astan Chee wrote: > > Hi, > > I'm trying to convert my tcsh script to python and am stuck at one part, > > particularly the part of the script that looks like this: > > > > #!/bin/tcsh > > setenv LSFLOG /var/tmp/lsf_log > > source /etc/setup > > unalias cp > > umask 0 > > env >> ${AFLOG} > > > > What is the equivalent of doing this in python2.5? > > Thanks again > > the equivalent would be exec(), but I'm not sure, that it is a good idea > to try to make a > word by word translation of a shell script into python. > > > you could do > exec( open("/etc/setup").read() ) Rather use execfile here. Though you'd probably rather want to write a Python module and use it as such (you know, import). > > but of course you had to translate /etc/setup > > to python. From hobson42 at gmaiil.com Tue Aug 24 16:38:55 2010 From: hobson42 at gmaiil.com (Ian) Date: Tue, 24 Aug 2010 21:38:55 +0100 Subject: adodbapi help needed In-Reply-To: References: <4C73E46A.7050207@ianhobson.co.uk> Message-ID: <4C742DDF.7000608@gmaiil.com> On 24/08/2010 18:08, Emile van Sebille wrote: > On 8/24/2010 8:25 AM Ian Hobson said... >> Hi all, >> >> I am just starting to learn Python and I have a setup problem - I think. >> Python 3.1. >> > > > >> >> def connect(connection_string, timeout=30): >> >> I expected that to be called. >> >> What have I missed? >> > > > > The current revision includes the caveat: > > This module source should run correctly in CPython versions 2.3 and > later, or IronPython version 2.6 and later, or, after running through > 2to3.py, CPython 3.0 or later. > > Does that help? > > Emile > Thanks for the response Emile, I have also removed all my Python installations and started again - with same result. After installing Python3.1 and pywin32-214.win32-py3.1.exe (which includes adodbapi) I was getting System does not exist. I have run 2to3.py on adodbapi and I still get this trackback. D:\websites\moschatel\sop\Printing>test.py Traceback (most recent call last): File "D:\websites\moschatel\sop\Printing\test.py", line 16, in import adodbapi File "C:\Python31\lib\site-packages\adodbapi\__init__.py", line 1, in from .adodbapi import * File "C:\Python31\lib\site-packages\adodbapi\adodbapi.py", line 57, in from System import Activator, Type, DBNull, DateTime, Array, Byte ImportError: No module named System I suspect that is movement, not progress. :) Regards Ian From raymond.hettinger at gmail.com Tue Aug 24 16:40:11 2010 From: raymond.hettinger at gmail.com (Raymond Hettinger) Date: Tue, 24 Aug 2010 13:40:11 -0700 Subject: [Python-Dev] Released: Python 2.6.6 In-Reply-To: <20100824153146.69874f04@heresy> References: <20100824153146.69874f04@heresy> Message-ID: On Aug 24, 2010, at 12:31 PM, Barry Warsaw wrote: > Hello fellow Pythoneers and Pythonistas, > > I'm very happy to announce the release of Python 2.6.6. Thanks Barry :-) Raymond From ahleniusm at gmail.com Tue Aug 24 16:45:12 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Tue, 24 Aug 2010 13:45:12 -0700 (PDT) Subject: problem with strptime and time zone Message-ID: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> Hi, perhaps I missed this posted already somewhere. I am got a program which reads time stings from some devices which are providing the time zones. I have to take this into account when doing some epoch time calculations. When I run the following code with the time zone string set to 'GMT' it works ok. This works: myStrA = 'Sun Aug 22 19:03:06 GMT' gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') print "gTimeA = ",gTimeA --- But when its set to 'PDT' it fails. Any ideas? whereas this fails: myStrA = 'Sun Aug 22 19:03:06 PDT' gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') print "gTimeA = ",gTimeA ValueError: time data 'Sun Aug 22 19:03:06 PDT' does not match format '%a %b %d %H:%M:%S %Z' thank you, From astan.chee at al.com.au Tue Aug 24 16:50:32 2010 From: astan.chee at al.com.au (Astan Chee) Date: Wed, 25 Aug 2010 06:50:32 +1000 Subject: equivalent of source in python? In-Reply-To: References: <4C741B1C.3080405@al.com.au> Message-ID: <4C743098.5010304@al.com.au> Thanks for all the help. I think Chris's answer is the one I can use. I know its probably better to convert the /etc/setup file into python but it'll do for now. Also, the entire tsch script is just setting up env vars and such; various mvs and cps. Not really executing anything. Thanks again for the help. Chris Rebert wrote: > On Tue, Aug 24, 2010 at 12:18 PM, Astan Chee wrote: > >> Hi, >> I'm trying to convert my tcsh script to python and am stuck at one part, >> particularly the part of the script that looks like this: >> >> #!/bin/tcsh >> setenv LSFLOG /var/tmp/lsf_log >> source /etc/setup >> unalias cp >> umask 0 >> env >> ${AFLOG} >> >> What is the equivalent of doing this in python2.5? >> > > I agree with Stefan, but anyway, here's an approximate untested > literal translation: > > import os > import subprocess > > os.environ['LSFLOG'] = '/var/tmp/lsf_log' > subprocess.check_call(['tcsh', '/etc/setup']) > os.umask(0) > out = open(os.environ['AFLOG'], 'a') > subprocess.check_call(['env'], stdout=out) > out.close() > > Cheers, > Chris > -- > http://blog.rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 24 16:56:55 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 24 Aug 2010 22:56:55 +0200 Subject: Help please! strange Tkinter behavior has me totally baffled. References: <6270b512-8b73-434d-83c3-ec5c60100eb1@w17g2000vbn.googlegroups.com> Message-ID: Steve Ferg wrote: > I have a short Python script that uses Tkinter to display an image. > Here is the script > > =================================================================== > import sys, os > from Tkinter import * > root = Tk() # A: create a global variable named "root" > > def showPicture(imageFilename): > # global root #C: make root global > root = Tk() # B: create a local variable named "root" > > imageFrame = Frame(root) > imageFrame.pack() > > imageObject = PhotoImage(file=imageFilename) > > label = Label(imageFrame,image=imageObject) > label.pack() > > root.mainloop() > > showPicture("python_and_check_logo.gif") > =================================================================== > > The strange thing is that it crashes with this traceback... > > =================================================================== > > Traceback (most recent call last): > File "easygui_test3.py", line 19, in > showPicture("python_and_check_logo.gif") > File "easygui_test3.py", line 14, in showPicture > label = Label(imageFrame,image=imageObject) > File "L:\FergLabstatPublic\Python26\lib\lib-tk\Tkinter.py", line > 2474, in __init__ > Widget.__init__(self, master, 'label', cnf, kw) > File "L:\FergLabstatPublic\Python26\lib\lib-tk\Tkinter.py", line > 1940, in __init__ > (widgetName, self._w) + extra + self._options(cnf)) > _tkinter.TclError: image "pyimage1" doesn't exist > > =================================================================== > > If I comment out either line A or line B, the script works fine. > > What I don't understand is why creating a global "root" variable and a > local "root" variable causes the script to crash. > > Even more puzzling... if I uncomment line C, so that "root" in line B > refers to a global "root" variable, the script still crashes. > > I'm totally baffled. Does anybody know what is going on here? > > -- Steve Ferg > (I'm running Python 2.6 under Windows, but I get the same behavior > under Solaris.) Tkinter.Tk() creates a new Tcl interpreter. Are you sure you want that? The standard way to create an additional window is Tkinter.Toplevel(). The PhotoImage is created in the default (first) interpreter and then looked up in the Label's (second) interpreter. At least that's what I would infer from class Image: """Base class for images.""" _last_id = 0 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): self.name = None if not master: master = _default_root if not master: raise RuntimeError, 'Too early to create image' self.tk = master.tk in the Tkinter source which also makes it plausible that you can avoid the problem by specifying an explicit master def showPicture(imageFilename): root = Tk() # ... imageObject = PhotoImage(file=imageFilename, master=root) # ... Peter From nanothermite911fbibustards at gmail.com Tue Aug 24 17:01:14 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 14:01:14 -0700 (PDT) Subject: YANQUI cry babies concerned that Iran has achieved parity in DRONES and against the massive AIRCRAFT carriers which are like SITTING DUCKS. A nation needs AIRCRAFT carriers to venture out for IMPERIALISTIC assaults but cant go out on speed boats. References: <156f547e-c730-4e16-9790-0c0636ddf12d@f42g2000yqn.googlegroups.com> Message-ID: <5383f461-3549-4674-b490-e2183fcf4be9@v8g2000yqe.googlegroups.com> This was censored by google or removed by some KhazarJew/YanQui hacker. I am reposting from python list : YANQUI cry babies concerned that Iran has achieved parity in DRONES and against the massive AIRCRAFT carriers which are like SITTING DUCKS. A nation needs AIRCRAFT carriers to venture out for IMPERIALISTIC assaults but cant go out on speed boats. Yet the NUMEROUS fast boats can sink the AIRCRAFT carrier and make it a SAILING COFFIN. http://www.google.com/hostednews/afp/article/ALeqM5gYlBmnQz28otk-w_hvx1pZ5C= bl0w US concerned about Iran's assault boats, drone (AFP) =96 5 hours ago WASHINGTON =97 The United States voiced concern Monday over Iran's unveiling of new assault boats and an aerial drone, but said Iran's arms buildup will backfire as its neighbors gang up against it. Iran began mass-producing two high-speed variants of missile- launching assault boats on Monday, a day after Iranian President Mahmoud Ahmadinejad revealed a home-built bomber drone. "This is... something that is of concern to us and... concern to Iran's neighbors," State Department spokesman Philip Crowley told reporters. He said that while every country had the right to provide for its self- defense, the United States takes into account "systems that can potentially... threaten particular countries or peace and stability in the region." Faced with "the growth of Iran's capabilities over a number of years, we've stepped up our military cooperation with other countries in the region," Crowley said. "This is one of the reasons why... we believe that if Iran continues on the path that it's on... (it) might find itself less secure because you'll have countries in the region that join together to offset Iran's growing capabilities." He added that the United States is still open to "constructive dialogue" with Iran to answer questions it and the world community have about its nuclear program, which Washington fears is aimed at building a bomb. "But in the meantime, we will work with other countries to try to do everything that we can to maintain peace and stability in the region," Crowley said. Copyright =A9 2010 AFP. All rights reserved -- http://mail.python.org/mailman/listinfo/python-list > Asked by a Mexican reporter at the time of his arrest whether he > killed Lauterbach, Laurean replied, "I loved her." > > Laurean's lawyer said his client would appeal the decision. > > ///////////////////////////////////////////////////////////////// > > The MARINE BASTARD will probably claim INSANITY ........ > > ////////////////////// > The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE > is UNACCEPTABLE. > > ===== > > http://www.youtube.com/watch?v=lX18zUp6WPY > > http://www.youtube.com/watch?v=XQapkVCx1HI > > http://www.youtube.com/watch?v=tXJ-k-iOg0M > > Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? > Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did > you release the 5 dancing Israelis compromising the whole 911 > investigation ? If the Dubai Police can catch Mossad Murderers and put > the videos and Iranian Police can why cant you put the Pentagon > Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and > puting on INTERNATIONAL MEDIA a day after catching him without > TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did > you have to LIE about Dr Afiya Siddiqui and torture that Innocent > little mother of 3 and smashing the skull of her one child ? > > http://www.youtube.com/watch?v=DhMcii8smxkhttp://www.youtube.com/watch?v=0SZ2lxDJmdg > > There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian > courts. > > FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but > only because he was a white. They got away with MURDER of thousands of > Non-whites in all parts of the world. > > Daily 911 news :http://911blogger.com > > http://www.youtube.com/watch?v=tRfhUezbKLw > > http://www.youtube.com/watch?v=x7kGZ3XPEm4 > > http://www.youtube.com/watch?v=lX18zUp6WPY > > Conclusion : FBI bustards are RACIST and INcompetent. They could > neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they > cover them up - whichever was their actual goal or task. > > SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across > tbe board, esp the whites/jew on the top. > > FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and > UNPATRIOTIC Act > FBI bustards failed to prevent ROMAN POLANSKY from absconding to > europe and rapes. > FBI bustards failed to prevent OKLAHOMA From alex at moreati.org.uk Tue Aug 24 17:05:50 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 24 Aug 2010 14:05:50 -0700 (PDT) Subject: seach for pattern based on string References: <6054e266-4730-411e-9a27-9b501e6086cd@j8g2000yqd.googlegroups.com> Message-ID: On Aug 24, 5:33?pm, richie05 bal wrote: > i am starting to learn python and I am stuck with query I want to > generate with python > File looks something like this > TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, > publishingCompanyId 7} > TRACE: AddNewBookD {bookId 21, noofBooks 6577, authorId 42, > publishingCompanyId 8} > > I want to first search for AddNewBookD > if found > ? ?store bookId, noofBooks, authorId and publishingCompanyId > > I know how to search for only AddNewBookD or find the pattern bookId > 20, noofBooks 6576, authorId 41, publishingCompanyId 7 but I don't > know how search one based on another. Using a regular expression I would perform a match against each line. If the match fails, it will return None. If the match succeeds it returns a match object with which you can extract the values >>> import re >>> pattern = re.compile(r'TRACE: AddNewBookD \{bookId (\d+), noofBooks (\d+), authorId (\d+), publishingCompanyId (\d+)\}\s*') >>> s = '''TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, publishingCompanyId 7} ''' >>> pattern.match(s) <_sre.SRE_Match object at 0xa362f40> # If the match failed this would be None >>> m = pattern.match(s) >>> m.groups() ('20', '6576', '41', '7') >>> So your code to store the result would be inside an if m: block HTH, Alex From rowlett at pcnetinc.com Tue Aug 24 17:12:32 2010 From: rowlett at pcnetinc.com (Richard Owlett) Date: Tue, 24 Aug 2010 16:12:32 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <87bp8sou6m.fsf@lola.goethe.zz> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <87bp8sou6m.fsf@lola.goethe.zz> Message-ID: David Kastrup wrote: > John Bokma writes: > >> On the other hand: some people I knew during my studies had no problem >> at all with introducing countless memory leaks in small programs (and >> turning off compiler warnings, because it gave so much noise...) > > [...] > >> As for electrical engineering: done that (BSc) and one of my class >> mates managed to connect a transformer the wrong way >> around.... twice. Yet he had the highest mark in our class. > > Anybody worth his salt in his profession has a trail of broken things in > his history. The faster it thinned out, the better he learned. The > only reliable way never to break a thing is not to touch it in the first > place. But that will not help you if it decides to break on its own. > *LOL* !!! I remember the day a very senior field service engineer for a multi-national minicomputer mfg plugged 16k (or was it 32k) of core (back when a core was visible to naked eye ;) the wrong way into a backplane. After the smoke cleared ... snicker snicker. I also remember writing a failure report because someone installed a grounding strap 100 degrees out of orientation on a piece of multi kV switchgear.(don't recall nominal capacity, buck backup generator was rated for 1.5 MW continuous ;) P.S. failure was demonstrated as manufacturer's senior sales rep was demonstrating how easy it was to do maintenance on the system. There were times I had fun writing up inspection reports. From alex at moreati.org.uk Tue Aug 24 17:16:01 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 24 Aug 2010 14:16:01 -0700 (PDT) Subject: problem with strptime and time zone References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> Message-ID: <45faa241-620e-42c7-b524-949936f63610@f6g2000yqa.googlegroups.com> On Aug 24, 9:45?pm, m_ahlenius wrote: > > whereas this fails: > myStrA = 'Sun Aug 22 19:03:06 PDT' > gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') > print "gTimeA = ",gTimeA > > ValueError: time data 'Sun Aug 22 19:03:06 PDT' does not match format > '%a %b %d %H:%M:%S %Z' Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform- specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones). http://docs.python.org/library/time.html Dateutil has it's own timezone database, so should work reliably http://labix.org/python-dateutil From emile at fenx.com Tue Aug 24 17:17:22 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 24 Aug 2010 14:17:22 -0700 Subject: adodbapi help needed In-Reply-To: <4C742DDF.7000608@gmaiil.com> References: <4C73E46A.7050207@ianhobson.co.uk> <4C742DDF.7000608@gmaiil.com> Message-ID: On 8/24/2010 1:38 PM Ian said... > On 24/08/2010 18:08, Emile van Sebille wrote: >> On 8/24/2010 8:25 AM Ian Hobson said... >>> Hi all, >>> >>> I am just starting to learn Python and I have a setup problem - I think. >>> Python 3.1. >>> >> >> >> >>> >>> def connect(connection_string, timeout=30): >>> >>> I expected that to be called. >>> >>> What have I missed? >>> >> >> >> >> The current revision includes the caveat: >> >> This module source should run correctly in CPython versions 2.3 and >> later, or IronPython version 2.6 and later, or, after running through >> 2to3.py, CPython 3.0 or later. >> >> Does that help? >> >> Emile >> > Thanks for the response Emile, > > I have also removed all my Python installations and started again - with > same result. > After installing Python3.1 and pywin32-214.win32-py3.1.exe (which > includes adodbapi) > I was getting System does not exist. > > I have run 2to3.py on adodbapi and I still get this trackback. > > D:\websites\moschatel\sop\Printing>test.py > Traceback (most recent call last): > File "D:\websites\moschatel\sop\Printing\test.py", line 16, in > import adodbapi > File "C:\Python31\lib\site-packages\adodbapi\__init__.py", line 1, in > > > from .adodbapi import * > File "C:\Python31\lib\site-packages\adodbapi\adodbapi.py", line 57, in > > > from System import Activator, Type, DBNull, DateTime, Array, Byte > ImportError: No module named System > > I suspect that is movement, not progress. :) > In a windows environment 3.x and 2.x live side-by-side without issues. I haven't made the jump yet to using 3.x for production, but as the warning says "... should run correctly ..." I'd try next with activestate's 2.x version which should come with all the right bits and pieces, and particularly as you're just starting out using 2.x shouldn't matter much. HTH, Emile From clp2 at rebertia.com Tue Aug 24 17:23:31 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 24 Aug 2010 14:23:31 -0700 Subject: problem with strptime and time zone In-Reply-To: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> Message-ID: On Tue, Aug 24, 2010 at 1:45 PM, m_ahlenius wrote: > Hi, > > perhaps I missed this posted already somewhere. > > I am got a program which reads time stings from some devices which > are ?providing the time zones. ?I have to take this into account when > doing some epoch time calculations. > > When I run the following code with the time zone string set to 'GMT' > it works ok. > > This works: > > myStrA = 'Sun Aug 22 19:03:06 GMT' > > gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') > > print "gTimeA = ",gTimeA > > --- > > whereas this fails: > myStrA = 'Sun Aug 22 19:03:06 PDT' > gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') > print "gTimeA = ",gTimeA > > > ValueError: time data 'Sun Aug 22 19:03:06 PDT' does not match format > '%a %b %d %H:%M:%S %Z' > > But when its set to 'PDT' it fails. > > Any ideas? Read The Fine Manual. Quoth http://docs.python.org/library/time.html#time.strptime : """ time.strptime(string[, format]) [...] Support for the %Z directive is based on the values contained in time.tzname and whether time.daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones). """ Cheers, Chris -- http://blog.rebertia.com From benjamin.kaplan at case.edu Tue Aug 24 17:29:16 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 24 Aug 2010 17:29:16 -0400 Subject: problem with simple multiprocessing script on OS X In-Reply-To: <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: On Tue, Aug 24, 2010 at 3:31 PM, Darren Dale wrote: > On Aug 23, 9:58?am, Darren Dale wrote: >> The following script runs without problems on Ubuntu and Windows 7. >> h5py is a package wrapping the hdf5 library (http://code.google.com/p/ >> h5py/): >> >> from multiprocessing import Pool >> import h5py >> >> def update(i): >> ? ? print i >> >> def f(i): >> ? ? "hello foo" >> ? ? return i*i >> >> if __name__ == '__main__': >> ? ? pool = Pool() >> ? ? for i in range(10): >> ? ? ? ? pool.apply_async(f, [i], callback=update) >> ? ? pool.close() >> ? ? pool.join() >> >> On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to >> comment out the as-yet unused h5py import, otherwise I get a >> traceback: >> >> Exception in thread Thread-1: >> Traceback (most recent call last): >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ >> lib/python2.6/threading.py", line 532, in __bootstrap_inner >> ? ? self.run() >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ >> lib/python2.6/threading.py", line 484, in run >> ? ? self.__target(*self.__args, **self.__kwargs) >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ >> lib/python2.6/multiprocessing/pool.py", line 226, in _handle_tasks >> ? ? put(task) >> PicklingError: Can't pickle : attribute lookup >> __builtin__.function failed > > > This is a really critical bug for me, but I'm not sure how to proceed. > Can I file a bug report on the python bugtracker if the only code I > can come up with to illustrate the problem requires a lame import of a > third party module? > -- It's working fine for me, OS X 10.6.4, Python 2.6 and h5py from Macports. From nanothermite911fbibustards at gmail.com Tue Aug 24 17:46:43 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 14:46:43 -0700 (PDT) Subject: Iran's self-defense options 'limitless' - against the YANQUI and KHAZAR Bustards - Brilliant ANALYSIS References: <156f547e-c730-4e16-9790-0c0636ddf12d@f42g2000yqn.googlegroups.com> <5383f461-3549-4674-b490-e2183fcf4be9@v8g2000yqe.googlegroups.com> Message-ID: <896d73ff-13c0-4235-87df-51572c291305@j8g2000yqd.googlegroups.com> Iran's self-defense options 'limitless' - against the YANQUI and KHAZAR Bustards - Brilliant ANALYSIS Iran's self-defense options 'limitless' Tue Aug 24, 2010 12:9AM President Mahmoud AhmadinejadIran's President Mahmoud Ahmadinejad says no military action is expected to be taken against the Islamic Republic since enemies are aware of Iran's reaction. "Iran is not concerned by a prospective military attack by any country, although it is always prepared to defend itself," Ahmadinejad said in an interview with Qatar's al-Sharq and the Peninsula newspapers on Monday. "Enemies know well that Iran is an invincible fortress and I do not believe the US masters of the Zionists will allow the regime [in Tel Aviv] to take any measures against Iran," noted the Iranian chief executive. Asked about Iran's options in the case it is attacked, Ahmadinejad said, "Iran has limitless options which extends to all parts of the world." Commenting on the Israeli threats against Iran's sovereignty over the county's nuclear enrichment program, the Iranian president pointed out that "Israel is too weak to stage a military strike against Iran, but if it attacks, it will receive a devastating response, which will make it regret its aggression." He also dismissed the idea that Arab countries' soil would be used to launch attacks on Iran, saying that the "leaders of these countries are more prudent than that.? Ahmadinejad further downplayed US military might in its current wars in the Middle East region and rejected the speculations that an imminent war against Iran was the cause of the US troops' withdrawal from Iraq. GHN/MGH ============ BRILLIANT ANALYSIS http://www.tehrantimes.com/index_View.asp?code=225469 View Rate : 1531 # News Code : TTime- 225469 Print Date : Tuesday, August 24, 2010 ?Iran will stand beside any country threatened in region? Ahmadinejad: Israel lacks courage to attack Iran TEHRAN ? Iranian President Mahmoud Ahmadinejad says that Iran will stand beside any country in the region that is threatened. ?Iran will stand on the side of any country in the region which comes under pressure or is threatened,? Ahmadinejad said in an interview with Arabic satellite television network Al Jazeera aired on Sunday. He also said he doesn?t think the threats by the United States and Israel to attack Iran are ?serious?. ?Israel does not have the courage to do it? I do not think the threat is serious.? Ahmadinejad also stated that Israel is ?too weak? to attack the Islamic Republic. The Iranian president said that any military adventure by the Zionist regime targeting Iran would receive a ?crushing? response that would make Israel regret the decision. He went on to say that Persian Gulf states are ?too smart? to allow the U.S. to use bases on their territory for a strike on Iran. ?We regard the Persian Gulf countries as brothers and friends. They are smarter than that.? In the interview, the president also said he does not fear an attack by the U.S. because it could not even defeat a small army in Iraq. ?There are no logical reasons for the United States to carry out such an act,? President Ahmadinejad told Al Jazeera. ?Do you believe an army that has been defeated by a small army in Iraq can enter into a war with a large and well trained army like the Iranian army?? he asked, referring to the insurgents in Iraq. Iran will only ?look to the views of wise people? in the U.S. and not to those whose minds are obsessed with ?hatred and animosity?, the president said when asked about former U.S. ambassador to the UN John Bolton?s remarks, which had apparently encouraged Israel to attack the Bushehr plant before its start-up. Washington has no real motive to attack Iran and would not benefit from hostilities, he added. ?The friendship of Iran is much better than its hostility,? he said. He went on to say that Iran is working to produce nuclear fuel independently ?because receiving it from an outside source is conditioned on diplomatic criteria.? To prevent Iran from using the Bushehr reactor to produce plutonium, inspectors from the International Atomic Energy Agency and Russia, which built the power plant, are making sure Iran returns the fuel rods it receives after they are spent. ?There is a difference between those who produce and those who buy. We must make sure our nuclear power plant continues to operate. We do not trust the West, despite our good relations with Russia,? Ahmadinejad said. ?We need 20 power plants like the one in Bushehr,? he added. -- http://mail.python.org/mailman/listinfo/python-list From hughaguilar96 at yahoo.com Tue Aug 24 17:48:09 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 14:48:09 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: <91927894-a2b3-46df-801e-577f0e68e8be@l20g2000yqm.googlegroups.com> On Aug 21, 12:18?pm, ehr... at dk3uz.ampr.org (Edmund H. Ramm) wrote: > In <2d59bfaa-2aa5-4396-bd03-22200df8c... at x21g2000yqa.googlegroups.com> Hugh Aguilar writes: > > > [...] > > I really recommend that people spend a lot more time writing code, > > and a lot less time with all of this pseudo-intellectual nonsense. > > [...] > > ? ?I energetically second that! > -- > ? ? ? e-mail: dk3uz AT arrl DOT net ?| ?AMPRNET: dk... at db0hht.ampr.org > ? ? ? If replying to a Usenet article, please use above e-mail address. > ? ? ? ? ? ? ? ?Linux/m68k, the best U**x ever to hit an Atari! What open-source code have you posted publicly? BTW, why did you request that your post not be archived, and be removed in a few days? That doesn't seem very energetic. Also, now that I've responded to it, it will be archived forever. It is so rare that anybody agrees with me, I wanted to make a permanent record. :-) From nanothermite911fbibustards at gmail.com Tue Aug 24 17:48:48 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 14:48:48 -0700 (PDT) Subject: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM References: <156f547e-c730-4e16-9790-0c0636ddf12d@f42g2000yqn.googlegroups.com> <5383f461-3549-4674-b490-e2183fcf4be9@v8g2000yqe.googlegroups.com> <896d73ff-13c0-4235-87df-51572c291305@j8g2000yqd.googlegroups.com> Message-ID: <5c56cb90-b5ef-4584-83e1-e932db968f56@x21g2000yqa.googlegroups.com> CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list From john at castleamber.com Tue Aug 24 17:50:23 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 16:50:23 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <87bp8sou6m.fsf@lola.goethe.zz> Message-ID: <87pqx77k9s.fsf@castleamber.com> David Kastrup writes: > John Bokma writes: > >> On the other hand: some people I knew during my studies had no problem >> at all with introducing countless memory leaks in small programs (and >> turning off compiler warnings, because it gave so much noise...) > > [...] > >> As for electrical engineering: done that (BSc) and one of my class >> mates managed to connect a transformer the wrong way >> around.... twice. Yet he had the highest mark in our class. > > Anybody worth his salt in his profession has a trail of broken things in > his history. Sure. The long version is: he blew up his work when he connected the transformer wrong. He borrowed someone else's board and blew that one up as well. > The faster it thinned out, the better he learned. He he he, his internships went along similar lines. Maybe he loved to blow up things. > The only reliable way never to break a thing is not to touch it in the > first place. But that will not help you if it decides to break on its > own. I don't think transfomers connect themselfs in the wrong way ;-). I agree with that accidents do happen, but some people just manage to make accidents happen way above average. And in that case they might start to think if it's a good idea them touching things. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From hughaguilar96 at yahoo.com Tue Aug 24 18:05:20 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 15:05:20 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> Message-ID: <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> On Aug 22, 11:12?am, John Bokma wrote: > And my > experience is that a formal study in CS can't compare to home study > unless you're really good and have the time and drive to read formal > books written on CS. And my experience is that most self-educaters don't > have that time. I've read a lot of graduate-level CS books. I think most self-educated programmers have read more of these books than have 4-year degree students who were not required to in order to get their Bachelors degree and who were too busy during college to read anything that wasn't required. > On the other hand: some people I knew during my studies had no problem > at all with introducing countless memory leaks in small programs (and > turning off compiler warnings, because it gave so much noise...) I do this all the time. My slide-rule program, for example, has beau- coup memory leaks. When I have time to mess with the program I clean up these memory leaks, but it is not a big deal. The program just runs, generates the gcode and PostScript, and then it is done. I don't really worry about memory leaks except with programs that are run continuously and have a user-interface, because they can eventually run out of memory. The real problem here is that C, Forth and C++ lack automatic garbage collection. If I have a program in which I have to worry about memory leaks (as described above), I would be better off to ignore C, Forth and C++ and just use a language that supports garbage collection. Why should I waste my time carefully freeing up heap space? I will very likely not find everything but yet have a few memory leaks anyway. From rowlett at pcnetinc.com Tue Aug 24 18:17:13 2010 From: rowlett at pcnetinc.com (Richard Owlett) Date: Tue, 24 Aug 2010 17:17:13 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> Message-ID: Hugh Aguilar wrote: > [SNIP ;] > > The real problem here is that C, Forth and C++ lack automatic garbage > collection. If I have a program in which I have to worry about memory > leaks (as described above), I would be better off to ignore C, Forth > and C++ and just use a language that supports garbage collection. Why > should I waste my time carefully freeing up heap space? I will very > likely not find everything but yet have a few memory leaks anyway. IOW Hugh has surpassed GIGO to achieve AGG - *A*utomatic*G*arbage*G*eneration ;) From hughaguilar96 at yahoo.com Tue Aug 24 18:25:25 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 15:25:25 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <87bp8sou6m.fsf@lola.goethe.zz> Message-ID: <5a3360f9-3eaf-4694-963a-8f67b813eb17@t2g2000yqe.googlegroups.com> On Aug 24, 9:24?am, David Kastrup wrote: > Anybody worth his salt in his profession has a trail of broken things in > his history. When I was employed as a Forth programmer, I worked for two brothers. The younger one told me a funny story about when he was 13 or 14 years old. He bought a radio at a garage sale. The radio worked perfectly, except that it had no case. He was mighty proud of his radio and was admiring it, but he noticed that the tubes were dusty. That wouldn't do! Such a wonderful radio ought to look as good as it sounds! So he removed the tubes and cleaned them all off with a soft cloth. At this time it occurred to him that maybe he should have kept track of which sockets the tubes had come out of. He put the tubes back in so that they looked correct, but he couldn't be sure. Fortunately, his older brother who was in high school knew *everything* about electronics, or at least, that is what he claimed. So the boy gets his big brother and asks him. The brother says: "There is one way to know for sure if the tubes are in correctly or not --- plug the radio in." He plugs in the radio; it makes a crackling noise and begins to smoke. The boy desperately yanks the cord, but it is too late; his wonderful radio is toast. The older brother says: "Now you know!" From cs_bittin at msn.com Tue Aug 24 18:31:51 2010 From: cs_bittin at msn.com (Martin Jernberg) Date: Wed, 25 Aug 2010 00:31:51 +0200 Subject: [Python-Dev] Released: Python 2.6.6 In-Reply-To: References: <20100824153146.69874f04@heresy>, Message-ID: yay new python release :) > From: raymond.hettinger at gmail.com > Date: Tue, 24 Aug 2010 13:40:11 -0700 > To: barry at python.org > CC: python-announce-list at python.org; python-list at python.org; python-dev at python.org > Subject: Re: [Python-Dev] Released: Python 2.6.6 > > > On Aug 24, 2010, at 12:31 PM, Barry Warsaw wrote: > > > Hello fellow Pythoneers and Pythonistas, > > > > I'm very happy to announce the release of Python 2.6.6. > > Thanks Barry :-) > > > Raymond > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: http://mail.python.org/mailman/options/python-dev/cs_bittin%40msn.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Tue Aug 24 19:04:55 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 25 Aug 2010 11:04:55 +1200 Subject: Reading the access attributes of directories in Windows References: Message-ID: In message , Nobody wrote: > Having this as a separate permission allows normal users to add entries to > log files but not to erase existing entries. Unix/Linux systems can do this already. From nanothermite911fbibustards at gmail.com Tue Aug 24 19:37:32 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 16:37:32 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach Message-ID: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list From john at castleamber.com Tue Aug 24 19:53:26 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 18:53:26 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> Message-ID: <871v9n36vd.fsf@castleamber.com> Hugh Aguilar writes: > On Aug 22, 11:12?am, John Bokma wrote: > >> And my >> experience is that a formal study in CS can't compare to home study >> unless you're really good and have the time and drive to read formal >> books written on CS. And my experience is that most self-educaters don't >> have that time. > > I've read a lot of graduate-level CS books. I think most self-educated > programmers have read more of these books than have 4-year degree > students who were not required to in order to get their Bachelors > degree and who were too busy during college to read anything that > wasn't required. I doubt it. But this all comes back to what I earlier wrote: those with a CS degree think they are better than people without, and people without think they can achieve the same or better by just buying a few books and reading them. On top of that, most of the people I knew in my final year were very fanatic regarding CS: it was a hobby to them. During coffeebreaks we talked about approximation algorithms for TSPs for example. Not always, but it happened. I read plenty of books during my studies that were not on the list, as did other students I knew. If I recall correctly, you don't have a CS degree. I do, and I can tell you that your /guess/ (since that is all it is) is wrong. For most exams I've done one had not only to have read the entire book (often in a very short time), but also the hand-outs. And for quite some courses additional material was given during the course itself, so not attending all classes could result in a lower score. Reading additional books and papers helped. Sometimes reading a book by a different author could be a real eye opener (and the students I had contact with did exactly this). On top of that, often in class excercises were done, and with some courses I had to hand in home work (yikes). Also, most books are easy to read compared to CS papers. In my final two years I did several courses which solely consisted of reading a CS paper and giving a presentation on the subject in front of your classmates (and sometimes other interested people). Reading and understanding such a paper is one (and quite an effort). Teaching it in front of a (small) class within a few days is not easy, to say the least. We also had to attend several talks by guest speakers. I went to more than the required number, including a guest talk by Linus. When there was a break-through in proving Fermat's last theorem there was a talk, which I attended, like several other class mates. I am sure there are students who are there just to get a degree and to make money. But my class mates didn't fall into that category, or I have missed something. So yes, I am convinced that there are plenty of self-educated people who can code circles around me or plenty of other people with a CS degree. But IMO those people are very hard to find. Most people overestimate their skills, with or without a degree; I am sure I do. And it wouldn't surprise me if self-educated people do this more so. >> On the other hand: some people I knew during my studies had no problem >> at all with introducing countless memory leaks in small programs (and >> turning off compiler warnings, because it gave so much noise...) > > I do this all the time. My slide-rule program, for example, has beau- > coup memory leaks. When I have time to mess with the program I clean > up these memory leaks, but it is not a big deal. The program just > runs, generates the gcode and PostScript, and then it is done. I don't > really worry about memory leaks except with programs that are run > continuously and have a user-interface, because they can eventually > run out of memory. Oh boy, I think you just made my point for me... > The real problem here is that C, Forth and C++ lack automatic garbage > collection. If I have a program in which I have to worry about memory > leaks (as described above), I would be better off to ignore C, Forth > and C++ and just use a language that supports garbage collection. Several languages that support garbage collection still are able to leak memory when circular datastructures are used (for example). Also, allocating memory and never giving it back (by keeping a reference to it) can also be memory leaking. And the wrong form of optimization can result in a program using more memory than necessary. On top of that, you have to understand when the gc releases memory, and things like memory fragmentation. In short: you still have to use your head (on some occasions even more). > Why should I waste my time carefully freeing up heap space? I will > very likely not find everything but yet have a few memory leaks > anyway. Why should you waste time with carefully checking for other issues? In my experience, once you become sloppy with one aspect it's very easy to become sloppy with others as well. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From hughaguilar96 at yahoo.com Tue Aug 24 20:00:14 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 17:00:14 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> Message-ID: <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> On Aug 24, 4:17?pm, Richard Owlett wrote: > Hugh Aguilar wrote: > > [SNIP ;] > > > The real problem here is that C, Forth and C++ lack automatic garbage > > collection. If I have a program in which I have to worry about memory > > leaks (as described above), I would be better off to ignore C, Forth > > and C++ and just use a language that supports garbage collection. Why > > should I waste my time carefully freeing up heap space? I will very > > likely not find everything but yet have a few memory leaks anyway. > > IOW Hugh has surpassed GIGO to achieve AGG - > *A*utomatic*G*arbage*G*eneration ;) The C programmers reading this are likely wondering why I'm being attacked. The reason is that Elizabeth Rather has made it clear to everybody that this is what she wants: http://groups.google.com/group/comp.lang.forth/browse_thread/thread/c37b473ec4da66f1 Every Forth programmer who aspires to get a job at Forth Inc. is obliged to attack me. Attacking my software that I posted on the FIG site is preferred, but personal attacks work too. It is a loyalty test. From rowlett at pcnetinc.com Tue Aug 24 20:05:38 2010 From: rowlett at pcnetinc.com (Richard Owlett) Date: Tue, 24 Aug 2010 19:05:38 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> Message-ID: Hugh Aguilar wrote: > On Aug 24, 4:17 pm, Richard Owlett wrote: >> Hugh Aguilar wrote: >>> [SNIP ;] >> >>> The real problem here is that C, Forth and C++ lack automatic garbage >>> collection. If I have a program in which I have to worry about memory >>> leaks (as described above), I would be better off to ignore C, Forth >>> and C++ and just use a language that supports garbage collection. Why >>> should I waste my time carefully freeing up heap space? I will very >>> likely not find everything but yet have a few memory leaks anyway. >> >> IOW Hugh has surpassed GIGO to achieve AGG - >> *A*utomatic*G*arbage*G*eneration ;) > > The C programmers reading this are likely wondering why I'm being > attacked. The reason is that Elizabeth Rather has made it clear to > everybody that this is what she wants: > http://groups.google.com/group/comp.lang.forth/browse_thread/thread/c37b473ec4da66f1 > > Every Forth programmer who aspires to get a job at Forth Inc. is > obliged to attack me. Attacking my software that I posted on the FIG > site is preferred, but personal attacks work too. It is a loyalty > test. *SNICKER SNICKER LOL* I am not now, nor have been a professional programmer. I still recognize you. P.S. - ever read "The Emperor's New Clothes" From no.email at nospam.invalid Tue Aug 24 20:16:20 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 24 Aug 2010 17:16:20 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> Message-ID: <7xhbijo8bv.fsf@ruckus.brouhaha.com> Hugh Aguilar writes: > I've read a lot of graduate-level CS books. Reading CS books doesn't make you a computer scientist any more than listening to violin records makes you a violinist. Write out answers to all the exercises in those books, and get your answers to the more difficult ones checked by a professor, and you'll be getting somewhere. That's the point someone else was making about self-study: without someone checking your answers at first, it's easy to not learn to recogize your own mistakes. Anyway, as someone else once said, studying a subject like CS isn't done by reading. It's done by writing out answers to problem after problem. Unless you've been doing that, you haven't been studying. From john at castleamber.com Tue Aug 24 20:39:48 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 19:39:48 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> Message-ID: <87tymj1q5n.fsf@castleamber.com> Paul Rubin writes: > Hugh Aguilar writes: >> I've read a lot of graduate-level CS books. > > Reading CS books doesn't make you a computer scientist any more than > listening to violin records makes you a violinist. Write out answers to > all the exercises in those books, and get your answers to the more > difficult ones checked by a professor, and you'll be getting somewhere. > That's the point someone else was making about self-study: without > someone checking your answers at first, it's easy to not learn to > recogize your own mistakes. > > Anyway, as someone else once said, studying a subject like CS isn't done > by reading. It's done by writing out answers to problem after problem. > Unless you've been doing that, you haven't been studying. Yup. I would like to add the following three: 1) being able to teach to peers what you've read. As explained in a post I made: during several courses I took you got a paper from your teacher and had to teach in front of the class the next week. Those papers are quite hard to grasp on the first reading even if you know quite a bit of the topic. Understanding it enough to teach in front of a class and being able to handle the question round, in which the teacher participates, is quite a killer. 2) being able to program on paper / understand programs on paper. On several exams I had to write small programs on paper. The solutions had to compile (i.e. missing a ; for languages that required so was counted against you, or using optional ;). One exam was about OOP and several OO languages were taught, and hence on paper one had to provide solutions in C++, Objective-C, Object Pascal, Smalltalk, Eiffel, etc. No compiler(s) handy. And of course questions like: what's wrong with this piece of code and how should it be written. 3) being able to write papers and a thesis (or two) No explanation needed, quite some people have no problem reading the required books, passing the exams, but need quite some time to do this (and some give up on it). -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From hughaguilar96 at yahoo.com Tue Aug 24 21:05:18 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 18:05:18 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> Message-ID: <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> On Aug 24, 5:16?pm, Paul Rubin wrote: > Anyway, as someone else once said, studying a subject like CS isn't done > by reading. ?It's done by writing out answers to problem after problem. > Unless you've been doing that, you haven't been studying. What about using what I learned to write programs that work? Does that count for anything? If I don't have a professor to pat me on the back, will my programs stop working? That sounds more like magic than technology. From hughaguilar96 at yahoo.com Tue Aug 24 21:47:14 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 18:47:14 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> <4c70bc48$0$28653$c3e8da3@news.astraweb.com> Message-ID: On Aug 21, 10:57?pm, Steven D'Aprano wrote: > Anyway, I'm looking forward to hear why overuse of the return stack is a > big reason why people use GCC rather than Forth. (Why GCC? What about > other C compilers?) Me, in my ignorance, I thought it was because C was > invented and popularised by the same universities which went on to teach > it to millions of programmers, and is firmly in the poplar and familiar > Algol family of languages, while Forth barely made any impression on > those universities, and looks like line-noise and reads like Yoda. (And > I'm saying that as somebody who *likes* Forth and wishes he had more use > for it.) In my experience, the average C programmer wouldn't recognise a > return stack if it poked him in the eye. "The Empire Strikes Back" was a popular movie. I read an article ("The puppet like, I do not") criticizing the movie though. At one point, Luke asked why something was true that Yoda had told him, and Yoda replied: "There is no why!" The general idea is that the sudent (Luke) was supposed to blindly accept what the professor (Yoda) tells him. If he asks "why?," he gets yelled at. This is also the attitude that I find among college graduates. They just believe what their professors told them in college, and there is no why. This is essentially the argument being made above --- that C is taught in college and Forth is not, therefore C is good and Forth is bad --- THERE IS NO WHY! People who promote "idiomatic" programming are essentially trying to be Yoda. They want to criticize people even when those people's programs work. They are just faking up their own expertise --- many of them have never actually written a program that works themselves. The reason why I like programming is because there is an inherent anti- bullshit mechanism in programming. Your program either works or it doesn't. If your program doesn't work, then it doesn't matter if it is idiomatic, if you have a college degree, etc., etc.. That is the way I see it, anyway. This perspective doesn't hold for much on comp.lang.forth where we have people endlessly spouting blather *about* programming, without actually doing any programming themselves. This is why I don't take c.l.f. very seriously; people attack me all of the time and I don't really care --- I know that my programs work, which is what matters in the real world. (Pardon my use of the word "bullshit" above; there is no better term available.) From ahleniusm at gmail.com Tue Aug 24 22:07:52 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Tue, 24 Aug 2010 19:07:52 -0700 (PDT) Subject: problem with strptime and time zone References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> <45faa241-620e-42c7-b524-949936f63610@f6g2000yqa.googlegroups.com> Message-ID: On Aug 24, 4:16?pm, Alex Willmer wrote: > On Aug 24, 9:45?pm, m_ahlenius wrote: > > > > > whereas this fails: > > myStrA = 'Sun Aug 22 19:03:06 PDT' > > gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') > > print "gTimeA = ",gTimeA > > > ValueError: time data 'Sun Aug 22 19:03:06 PDT' does not match format > > '%a %b %d %H:%M:%S %Z' > > Support for the %Z directive is based on the values contained in > tzname and whether daylight is true. Because of this, it is platform- > specific except for recognizing UTC and GMT which are always known > (and are considered to be non-daylight savings timezones). > > http://docs.python.org/library/time.html > > Dateutil has it's own timezone database, so should work reliablyhttp://labix.org/python-dateutil Thanks much, I missed the directive settings. From john at castleamber.com Tue Aug 24 22:17:10 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 21:17:10 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> Message-ID: <87pqx71lnd.fsf@castleamber.com> Hugh Aguilar writes: > On Aug 24, 5:16?pm, Paul Rubin wrote: >> Anyway, as someone else once said, studying a subject like CS isn't done >> by reading. ?It's done by writing out answers to problem after problem. >> Unless you've been doing that, you haven't been studying. > > What about using what I learned to write programs that work? Does that > count for anything? Of course it does; but who's going to verify your program? > If I don't have a professor to pat me on the back, will my programs > stop working? That sounds more like magic than technology. I am sure you know what Paul means. As for patting on the back: you must make a hell of an effort to get that. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From john at castleamber.com Tue Aug 24 22:35:39 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 21:35:39 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> <4c70bc48$0$28653$c3e8da3@news.astraweb.com> Message-ID: <87lj7v1ksk.fsf@castleamber.com> Hugh Aguilar writes: > This is also the attitude that I find among college graduates. They > just believe what their professors told them in college, and there is > no why. Which college is that? It doesn't agree with my experiences. In CS quite a lot has to be proven with a formal proof, exactly the opposite from what you claim. And after some time students want to see the proof and certainly don't accept "there is no why!" unless it's a trivial thing. Maybe it's because your anecdote is an interpretation from a distance, not based on the actual experience? > This is essentially the argument being made above --- that C > is taught in college and Forth is not, therefore C is good and Forth > is bad --- THERE IS NO WHY! At an university which languages you see depend a lot on what your teachers use themselves. A language is just a verhicle to get you from a to b. What a good study should teach you is how to drive the verhicle without accidents and not that a red one is the best. From top of my head I've seen 20+ languages during my study at the University of Utrecht. Forth wasn't one of them, but I already knew about Forth before I went to the UU. On top of that I had written an extremely minimalistic Forth in Z80 assembly years before I went to the UU (based on the work of someone else). > People who promote "idiomatic" programming are essentially trying to > be Yoda. They want to criticize people even when those people's > programs work. "Works" doesn't mean that a program is good or what. There is a lot to say about a program that works, even one that works flawless. I do it all the time about my own programs. It's good to be critical about your own work. And if you're a teacher, it's good to provide positive feedback. > They are just faking up their own expertise --- Like you, you mean? You consider yourself quite the expert on how people educate and what they learn when educated in a formal environment. Without (if I recall correctly) only second hand information and guessing. > many of them have never actually written a program that works > themselves. Quite some part of CS can be done without writing a single line of code. > The reason why I like programming is because there is an inherent anti- > bullshit mechanism in programming. Your program either works or it > doesn't. Now can you provide a formal proof that it works, or do you just consider running the program a few times sufficient proof that "it works"? > If your program doesn't work, then it doesn't matter if it is > idiomatic, if you have a college degree, etc., etc.. That is the way I > see it, anyway. Well, you see it wrong. A program that doesn't work and is idiomatic is easier to make work and to verify by others that it works. A program that's the result of trial-and-error (that's what quite some people end up doing who are self-taught) is a pain in the ass (pardon my French) to maintain or to extend. > This perspective doesn't hold for much on > comp.lang.forth where we have people endlessly spouting blather > *about* programming, and you are different how? Also note that your post is crossposted to several other groups. > without actually doing any programming themselves. This is why I don't > take c.l.f. very seriously; people attack me all of the time and I > don't really care heh, hence all the replies you write, and mentioning it in this post. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From john at castleamber.com Tue Aug 24 22:38:57 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 21:38:57 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> <4c70bc48$0$28653$c3e8da3@news.astraweb.com> <87lj7v1ksk.fsf@castleamber.com> Message-ID: <87hbij1kn2.fsf@castleamber.com> John Bokma writes: > At an university which languages you see depend a lot on what your > teachers use themselves. A language is just a verhicle to get you from a > to b. Addendum: or to illustrate a concept (e.g. functional programming, oop) [..] > Like you, you mean? You consider yourself quite the expert on how people > educate and what they learn when educated in a formal > environment. Without (if I recall correctly) only second hand ^^^^^^^ Should've written "With", of course. > information and guessing. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From ghoetker at illinois.edu Tue Aug 24 22:49:42 2010 From: ghoetker at illinois.edu (ghoetker) Date: Tue, 24 Aug 2010 19:49:42 -0700 (PDT) Subject: Passing data between objects and calling all objects of a class in turn Message-ID: I'm a fairly new Python coder, learning along with my son (actually, hopefully a bit ahead of him...). We're stuck on something. As part of solving a backwards induction problem (purely as a learning experience, we are geeks), we are going to create N objects, each of the class "interview". We will first create the N_th interview, which will calculate, based on data we pass to it, its expected payoff value. We will then create interview N-1, which needs to know the expected payoff of interview N in order to determine a decision and then calculate its own expected payoff. We then create interview N-2, which needs to know the expected payoff of interview N-1, etc., until we reach interview 1. 1. How can we best (that is, most Pythonically) let interview N-1 know the expected value of interview N and so on. One way would be to define a variable "payoff_of_continuing" which gets set to the expected value of interview N and is passed to interview N-1 when is created. Interview N-1 then resets "payoff_of_continuing", which is passed to interview N-2 when it is created, etc. Is there a more Pythonic approach? 2. When we want to output the results of the analysis, how do we most Pythonically get each interview object in turn to report its identity, the result of its decision and its expected payoff (e.g., For interview 3, stop if you interview a good candidate. This interview's expected value is 2.5). I know how to do the reporting part (print....), it's the "getting each interview object in turn to..." part that I'm unsure about. We could have each interview report as it is created, but I'm wondering if the splitting it into "Create all the objects" and "Report the results from all the objects" is sensible. For one thing, it would allow compiling the results into a table, etc. I really appreciate any input. I'm a competent procedural programmer (albeit not primarily in Python), but a dabbler in object oriented programming (we've already done this problem procedurally, but want to try it again as OOP). Thank you!! From python at mrabarnett.plus.com Tue Aug 24 23:18:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 25 Aug 2010 04:18:52 +0100 Subject: Passing data between objects and calling all objects of a class in turn In-Reply-To: References: Message-ID: <4C748B9C.8040000@mrabarnett.plus.com> On 25/08/2010 03:49, ghoetker wrote: > I'm a fairly new Python coder, learning along with my son (actually, > hopefully a bit ahead of him...). We're stuck on something. > > As part of solving a backwards induction problem (purely as a learning > experience, we are geeks), we are going to create N objects, each of > the class "interview". We will first create the N_th interview, which > will calculate, based on data we pass to it, its expected payoff > value. We will then create interview N-1, which needs to know the > expected payoff of interview N in order to determine a decision and > then calculate its own expected payoff. We then create interview N-2, > which needs to know the expected payoff of interview N-1, etc., until > we reach interview 1. > > 1. How can we best (that is, most Pythonically) let interview N-1 > know the expected value of interview N and so on. One way would be to > define a variable "payoff_of_continuing" which gets set to the > expected value of interview N and is passed to interview N-1 when is > created. Interview N-1 then resets "payoff_of_continuing", which is > passed to interview N-2 when it is created, etc. Is there a more > Pythonic approach? > I hope you don't mean that "payoff_of_continuing" is a global variable which is set by the instance when it's created. The Pythonic way would be to create the instance and then ask it what it's payoff is so that you then know what to pass in when you create the next instance. > 2. When we want to output the results of the analysis, how do we most > Pythonically get each interview object in turn to report its identity, > the result of its decision and its expected payoff (e.g., For > interview 3, stop if you interview a good candidate. This interview's > expected value is 2.5). I know how to do the reporting part > (print....), it's the "getting each interview object in turn to..." > part that I'm unsure about. We could have each interview report as it > is created, but I'm wondering if the splitting it into "Create all the > objects" and "Report the results from all the objects" is sensible. > For one thing, it would allow compiling the results into a table, etc. > Put the objects into a list when you create them and then iterate through them, asking each to print its report. > I really appreciate any input. I'm a competent procedural programmer > (albeit not primarily in Python), but a dabbler in object oriented > programming (we've already done this problem procedurally, but want to > try it again as OOP). Thank you!! From magawake at gmail.com Tue Aug 24 23:19:50 2010 From: magawake at gmail.com (Mag Gam) Date: Tue, 24 Aug 2010 23:19:50 -0400 Subject: pypy Message-ID: Just curious if anyone had the chance to build pypy on a 64bit environment and to see if it really makes a huge difference in performance. Would like to hear some thoughts (or alternatives). From madhusoodan.shanbhag at gmail.com Tue Aug 24 23:39:31 2010 From: madhusoodan.shanbhag at gmail.com (Madhusoodan) Date: Tue, 24 Aug 2010 20:39:31 -0700 (PDT) Subject: DDE Module for Python 3.1.2 References: Message-ID: Respected Stefan and Tim, Thanks very much for help. I found DDE tutorial for 2.6 but was wondering why I can't do it in 3.X. Thanks Stefan for pywin32. I was not knowing this tool. Thanks again to both of you. Regards madhusoodan On Aug 23, 5:12?pm, Tim Golden wrote: > On 23/08/2010 13:02, Stefan Behnel wrote: > > > Madhusoodan, 23.08.2010 13:50: > >> I am learning python 3.1.2 on windows XP. I wanted to do experiments > >> on importing real time data from QuoteCenter with DDE. > > > What's DDE here? > > It'll be Microsoft's Dynamic Data Exchange : > > ? ?http://msdn.microsoft.com/en-us/library/ms648711%28VS.85%29.aspx > > Didn't know anyone was still using it explicitly. > > > > >> After searching > >> relevant module, I found dde module only for Python 2.6, but not for > >> 3.1.2. > > > Could you provide a link to the module, so that we know what module you > > are actually talking about? > > I expect that'll be the dde module in the pywin32 packages: > > http://pywin32.cvs.sourceforge.net/viewvc/pywin32/pywin32/win32/Demos... > > I haven't run any tests against it, but it imports ok on > my 3.1.2 instance (albeit after importing win32ui) > > TJG From ritchy_gato at hotmail.com Wed Aug 25 01:21:34 2010 From: ritchy_gato at hotmail.com (Ritchy lelis) Date: Tue, 24 Aug 2010 22:21:34 -0700 (PDT) Subject: How to implement a pipeline...??? Please help References: <5242b005-31b6-4a9c-afd9-6fbb82e28db7@l14g2000yql.googlegroups.com> <08ce00ca-f58e-4ff4-a95e-54f7a4d5071f@w30g2000yqw.googlegroups.com> Message-ID: On 11 Ago, 01:01, Ritchy lelis wrote: > On 7 Ago, 07:30, Dennis Lee Bieber wrote: > > > > > > > On Fri, 6 Aug 2010 16:47:58 -0700 (PDT), Ritchy lelis > > declaimed the following in > > gmane.comp.python.general: > > > > Guys i'm asking if it's possible for a generic function for a > > >pipeline, all the suggestions ideas are welcome. > > > ? ? ? ? I've not done metaclasses, so don't know if a metaclass would be of > > use... Since it appears one would have to have something that generates > > functions on the fly based upon inputs... > > > ? ? ? ? I look at details on what you are trying to create and see a > > series-parallel circuit architecture with clocked stages and delay lines > > for the summing of the outputs. That is, when the clock ticks, every > > stage in the unit does its processing and provides and output... On the > > next tick, those outputs become inputs to the subsequent stage and the > > process repeats > > > > Also if you have a specific solution for my problem I will be grateful > > > for it here. > > > ? ? ? ? I'm still blinking at the thought of doing analog to digital > > conversion in Python! I sure wouldn't hold out much hope of real-time > > signal processing. There is a reason ADC and DAC are done in hardware, > > even if the intermediate processing is with general purpose processors. > > > ? ? ? ? I'm also not sure I understand the > > > np.linspace(1,1, Inc)... > > > ? ? ? ? Looking up documentation implies you are trying to create a vector > > of "inc" length, evenly populated by values between 1 and 1... which > > means a vector of all 1s... Might it not be faster to just > > > ? ? ? ? v = [1] * inc > > > and pass v to some numpy method for conversion from Python list to numpy > > vector? > > > (the -1 to 1 at least makes sense) > > > ? ? ? ? Me? I'd probably create a class in which the __init__() takes a > > value specifying the number of stages. It would than create suitable > > lists to track values, some sort of counter (c), a Semaphore (s) > > [initialized at 0 -- ie, already acquired/block], ?a thread for EACH > > stage, and an Event (e) object > > > ? ? ? ? Each stage thread, initialized with its position in thepipeline. > > The threads perform an e.wait() call. They also, after the wait is > > released, perform an e.clear() call. As their processing, they each grab > > from thepipeline"input" list the current value for their position. > > After processing they update their position in the "output" list(s), > > they decrement the counter c (maybe put a lock around access to c). The > > thread that decrements c to 0 is responsible for "releasing" the > > semaphore. > > > ? ? ? ? The main code of the class instance is responsible for a loop that > > does: set up the "input" list based on current value of stage outputs, > > initialize c to the count of stages (minus 1?), e.set() to signal all > > stage threads to process the current conditions, s.acquire() to block > > until the last processed thread (by c hitting 0) does s.release(). It > > then collects the output lists, does whatever shifting is needed to > > prepare for the next cycle... > > > ? ? ? ? Actually, that "loop" may not be a loop so much as a method off the > > class like > > > ? ? ? ? digitalOutput = adcInstance.step(analogInput) > > > which is, itself, in a loop. > > > That is, something like... > > > myADC = ADC(stages=10) > > while True: > > ? ? ? ? voltage = getNextAnalogInput() > > ? ? ? ? digital = myADC.step(voltage) > > ? ? ? ? outputDigitalValue() > > > ? ? ? ? Obviously I've not taken the time to actually lay out all the > > instance lists needed for inputs and outputs, nor the code of threads > > (while one can create the first "stages-1" threads with a loop, the > > final stage needs a discrete creation) > > > ? ? ? ? When one finds that the threading solution is really slow (though > > understandable in terms of the hardware circuit -- one thread per stage > > makes the stages easy to code), THEN one might try to figure out how to > > implement an iterative version... I suspect using numpy would be the > > third optimization -- removing iteration by using parallel vector > > operations. > > -- > > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ > > Hi > > First of all i would like to thank you for your time and help. > > I appreciate your suggestions and they seems very good to me... The > only problem it's that i'm newbie at python programming, but still > interested to learn more and more... > > I already got a solution through harsh but it worked. at least I got > the wave form i wanted. > > Next i'm going to let you'll my solution here. It's rudimentary but it > work's. > > Seems very perceptible that's why i will not explain it right now but > if in case of doubt I will: > > PipelineFunction: > > from flash1b5 import flash1b5 > from flash1b5 import * > from flash2b import flash2b > from flash2b import * > import matplotlib.pyplot as plt > import numpy as np > from pylab import * > > if __name__ == "__main__": > > ? ? Inc = raw_input("Valor do Incrimento = ") > > ? ? Vref = np.linspace(1,1, Inc) > ? ? Vi = np.linspace(-1,1, Inc) > # ? ?x = np.linspace(-1,1, Inc) > # ? ?Vi = 1*sin(2*pi*(x-1/4)) > ? ? Cs = np.linspace(3e-12, 3e-12, Inc) > ? ? Cf = np.linspace(3e-12, 3e-12, Inc) > > ? ? f1 = flash1b5(Vi, Vref, Cs, Cf) > > ? ? Vin1 = f1[0] > ? ? Vt1 = f1[1] > ? ? Vd1 = f1[2]*256 > > ? ? f2 = flash1b5(Vt1, Vref, Cs, Cf) > > ? ? Vin2 = f2[0] > ? ? Vt2 = f2[1] > ? ? Vd2 = f2[2]*128 > > ? ? f3 = flash1b5(Vt2, Vref, Cs, Cf) > > ? ? Vin3 = f3[0] > ? ? Vt3 = f3[1] > ? ? Vd3 = f3[2]*64 > > ? ? f4 = flash1b5(Vt3, Vref, Cs, Cf) > > ? ? Vin4 = f4[0] > ? ? Vt4 = f4[1] > ? ? Vd4 = f4[2]*32 > > ? ? f5 = flash1b5(Vt4, Vref, Cs, Cf) > > ? ? Vin5 = f5[0] > ? ? Vt5 = f5[1] > ? ? Vd5 = f5[2]*16 > > ? ? f6 = flash1b5(Vt5, Vref, Cs, Cf) > > ? ? Vin6 = f6[0] > ? ? Vt6 = f6[1] > ? ? Vd6 = f6[2]*8 > > ? ? f7 = flash1b5(Vt6, Vref, Cs, Cf) > > ? ? Vin7 = f7[0] > ? ? Vt7 = f7[1] > ? ? Vd7 = f7[2]*4 > > ? ? f8 = flash1b5(Vt7, Vref, Cs, Cf) > > ? ? Vin8 = f8[0] > ? ? Vt8 = f8[1] > ? ? Vd8 = f8[2]*2 > > ? ? f2b = flash2b(Vt8, Vref) > > ? ? Vin2b = f2b[0] > ? ? Vd2b = f2b[1]*1 > > ? ? Vd = Vd1+Vd2+Vd3+Vd4+Vd5+Vd6+Vd7+Vd8+Vd2b > > ## ? ?print 'Vin = ',Vin > ## ? ?print 'Vt = ',Vt > ## ? ?print 'Vd = ',Vd > ## > # ? ?fig1 = figure(1,figsize=(8,5)) > # ? ?ax1 = fig1.add_subplot(211, autoscale_on=False, xlim=(-1,1), > ylim=(-1,1)) > # ? ?ax1.plot(Vin1, Vt4, lw=2, color='blue') > # ? ?grid (True); title('FLASH 1.5 BIT',fontsize = > 16);ylabel('Vout_Residuo') > ## > ## ? ?ax1.annotate('00', xy=(-0.5, 0.5)) > ## ? ?ax1.annotate('01', xy=(0.0, 0.5)) > ## ? ?ax1.annotate('11', xy=(0.5, 0.5)) > # > ## ? ?hold(True) > # > ? ? fig2 = figure(1,figsize=(8,5)) > ? ? ax2 = fig2.add_subplot(111, autoscale_on=True) > ? ? ax2.plot(Vin1, Vd, lw=2, color='red') > ? ? grid (True); xlabel('Vin');ylabel('Vout_Digital') > # > ## ? ?ax2.annotate('00 --> 0', xy=(-0.5, 0.1)) > ## ? ?ax2.annotate('01 --> 1', xy=(0.0, 1.1)) > ## ? ?ax2.annotate('11 --> 2', xy=(0.5, 2.1)) > ## > # > ? ? plt.show() > -------------------------------------------------------------------------- > > About the answer i got for my last post: > > ?1 - > ? ? v = [1] * inc > > > > > and pass v to some numpy method for conversion from Python list to numpy > > vector? > > Yes i agree with you, but at the time i made it i found that function > (Linspace) that could do what i was loking for and i didn't worry > about search for a better solution. but even if wanted to, i'm new at > the programming language and i don't know how to convert a list to a > vector in numpy. but still open for tips/tricks that could help me. > > 2 - > > > ? ? ? ? Me? I'd probably create a class in which the __init__() takes a > > value specifying the number of stages. It would than create suitable > > lists to track values, some sort of counter (c), a Semaphore (s) > > [initialized at 0 -- ie, already acquired/block], ?a thread for EACH > > stage, and an Event (e) object > > ? ? ? ? Each stage thread, initialized with its position in thepipeline. > > The threads perform an e.wait() call. They also, after the wait is > > released, perform an e.clear() call. As their processing, they each grab > > from thepipeline"input" list the current value for their position. > > After processing they update their position in the "output" list(s), > > they decrement the counter c (maybe put a lock around access to c). The > > thread that decrements c to 0 is responsible for "releasing" the > > semaphore > > I did understand your algorithm/idea and that's what i want to > implement here (you couldn't be more right). but i don't now how to > implement the funcs e.wait() call and e.clear() call. they already > exists? i have to create them? > > if I may, i would like to ask more help on this one please. I hope not > to be bothering you :( hi friend Dennis Lee Bieber I have watching your code sujestion and now i can understand more of what you have there.. I have made some chances into it, for my better understanding of your point of view and adapted for it to fits my needs... i would like to show you them but i need to now if you still interested in the challenge it self and also in helping me with your extraordinary tips. Can i count on your help? I hope so gratefully. I'll be waiting for a message so we can proceed. Cheers. From sschwarzer at sschwarzer.net Wed Aug 25 02:07:47 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 25 Aug 2010 08:07:47 +0200 Subject: ftplib limitations? In-Reply-To: <4C73D738.9030501@sschwarzer.net> References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> Message-ID: <4C74B333.5020206@sschwarzer.net> Hi durumdara, On 2010-08-24 16:29, Stefan Schwarzer wrote: >> I experienced some problem. >> The server is Windows and FileZilla, the client is Win7 and Python2.6. >> When I got a file with size 1 303 318 662 byte, python is halt on >> "retrbinary" line everytime. > > So if I understand correctly, the script works well on > smaller files but not on the large one? I just did an experiment in the interpreter which corresponds to this script: import ftplib of = open("large_file", "wb") def callback(data): of.write(data) ftp = ftplib.FTP("localhost", userid, passwd) ftp.retrbinary("RETR large_file", callback) of.close() ftp.close() The file is 2 GB in size and is fully transferred, without blocking or an error message. The status message from the server is '226-File successfully transferred\n226 31.760 seconds (measured here), 64.48 Mbytes per second', so this looks ok, too. I think your problem is related to the FTP server or its configuration. Have you been able to reproduce the problem? Stefan From pdwjfndjbdgfyg at gmail.com Wed Aug 25 02:30:13 2010 From: pdwjfndjbdgfyg at gmail.com (097) Date: Tue, 24 Aug 2010 23:30:13 -0700 (PDT) Subject: GAMES Message-ID: <823cf601-f0da-4621-9099-963f42963693@q21g2000prm.googlegroups.com> games GAME 1 http://freeonlingamesplay.blogspot.com/2010/08/game-1.html GAME 2 http://freeonlingamesplay.blogspot.com/2010/08/game-2.html GAME 3 http://freeonlingamesplay.blogspot.com/2010/08/game-3.html GAME 4 http://freeonlingamesplay.blogspot.com/2010/08/game-4.html GAME 5 http://freeonlingamesplay.blogspot.com/2010/08/game-5.html GAME 6 http://freeonlingamesplay.blogspot.com/2010/08/game-6.html GAME 7 http://freeonlingamesplay.blogspot.com/2010/08/game-7.html GAME 8 http://freeonlingamesplay.blogspot.com/2010/08/game-8.html GAME 9 http://freeonlingamesplay.blogspot.com/2010/08/game-9.html GAME 10 http://freeonlingamesplay.blogspot.com/2010/08/game-10.html From durumdara at gmail.com Wed Aug 25 03:43:01 2010 From: durumdara at gmail.com (durumdara) Date: Wed, 25 Aug 2010 00:43:01 -0700 (PDT) Subject: ftplib limitations? References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> Message-ID: Hi! > > So if I understand correctly, the script works well on > smaller files but not on the large one? Yes. 500-800 MB is ok. > 1 GB is not ok. > > > It down all of the file (100%) but the next line never reached. > > _Which_ line is never reached? The `print` statement after > the `retrbinary` call? Yes, the print. > > > Some error I got, but this was in yesterday, I don't remember the text > > of the error. > > Can't you reproduce the error by executing the script once > more? Can you copy the file to another server and see if the > problem shows up there, too? I got everytime, but I don't have another server to test it. > > I can imagine the error message (a full traceback if > possible) would help to say a bit more about the cause of > the problem and maybe what to do about it. This was: Filename: "Repositories 20100824_101805 (Teljes).zip" Size: 1530296127 ..download: 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% Traceback (most recent call last): File "C:\D\LocalBackup\ftpdown.py", line 31, in ftp.retrbinary("retr " + s, CallBack) File "C:\Python26\lib\ftplib.py", line 401, in retrbinary return self.voidresp() File "C:\Python26\lib\ftplib.py", line 223, in voidresp resp = self.getresp() File "C:\Python26\lib\ftplib.py", line 209, in getresp resp = self.getmultiline() File "C:\Python26\lib\ftplib.py", line 195, in getmultiline line = self.getline() File "C:\Python26\lib\ftplib.py", line 182, in getline line = self.file.readline() File "C:\Python26\lib\socket.py", line 406, in readline data = self._sock.recv(self._rbufsize) socket.error: [Errno 10054] A l?tez? kapcsolatot a t?voli ?llom?s k?nyszer?tette n bez?rta So this message is meaning that the remote station forced close the existing connection. Now I'm trying with saving the file into temporary file, not hold in memory. Thanks: dd From ldo at geek-central.gen.new_zealand Wed Aug 25 03:48:26 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 25 Aug 2010 19:48:26 +1200 Subject: problem with strptime and time zone References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> <45faa241-620e-42c7-b524-949936f63610@f6g2000yqa.googlegroups.com> Message-ID: In message <45faa241-620e-42c7-b524-949936f63610 at f6g2000yqa.googlegroups.com>, Alex Willmer wrote: > Dateutil has it's own timezone database ... I hate code which doesn?t just use /usr/share/zoneinfo. How many places do you need to patch every time somebody changes their daylight-saving rules? From metolone+gmane at gmail.com Wed Aug 25 03:57:44 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 25 Aug 2010 00:57:44 -0700 Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com><4C72FC62.1050908@v.loewis.de><8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com><4C730541.7040507@v.loewis.de> <3d85d8f5-8ce0-470f-b6ec-c86c452a335b@a36g2000yqc.googlegroups.com> Message-ID: > "vsoler" wrote in message > news:3d85d8f5-8ce0-470f-b6ec-c86c452a335b at a36g2000yqc.googlegroups.com... > On Aug 24, 1:33 am, "Martin v. Loewis" wrote: > > > When I am logged-in in a session as an administrator, the BAT file on > > > the Desktop, and I double-click on it, it does not work. > > > > This is not what I meant. Instead, right-click on the BAT file, > > and select "run as administrator". > > > > > When you say to double-escape the percent signs, do you mean that in > > > my BAT file I should write... > > > > > FTYPE python.file="C:\Python26\python.exe" "%%1" %%* > > > > > and the inverted commas around %%*, are they not necessary? > > > > No, I don't think so. > > > > Regards, > > Martin > > Martin (or anybody else), > > The problem with FTYPE is solved. > > However, after having switched to py 3.1 with the help of the BAT > script (which only changes FTYPE) I have another problem. > > (Just for reference, here is my batch file) > > @ECHO OFF > ECHO ************************************************ > ECHO Cambia a Python 3.1 > ECHO ************************************************ > ECHO * > ECHO FTYPES: > ECHO * > ECHO .py=Python.File > ECHO .pyc=Python.CompiledFile > ECHO .pyo=Python.CompiledFile > ECHO .pys=pysFile > ECHO .pyw=Python.NoConFile > ECHO * > ECHO ************************************************ > ECHO * > FTYPE python.file="C:\Python31\python.exe" "%%1" %%* > FTYPE python.compiledfile="C:\Python31\python.exe" "%%1" %%* > FTYPE python.NoConFile="C:\Python31\pythonw.exe" "%%1" %%* > ECHO * > Pause > @ECHO ON > > The problem is that, if I am on top of a .py file, and, with the > mouse, I click on the right button, then I click on "Edit with IDLE", > I get the 2.6 system, not the 3.1 one (which was supposed to be the > correct one after the change). > > My question is: are there any other changes that I should do in order > to fully switch from one version to another? Yes, and they are relatively easy to edit with a .reg file instead of a batch file. Below is just an example for type "Python.File" that adds "Open with Python3", "Edit with IDLE3", and "Open with Pythonwin3" commands to the right-click context menu of a .py file. The first 3 entries are the original Python26 entries. The last three were copied from them and modified to create the alternative context menus. You could also create two .reg files that toggle the original three entries between Python 2.6 and Python 3.1 if you want. -----------------------START------------------------ Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE\command] @="\"C:\\Python26\\pythonw.exe\" \"C:\\Python26\\Lib\\idlelib\\idle.pyw\" -n -e \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\Edit with Pythonwin\command] @="C:\\Python26\\Lib\\site-packages\\Pythonwin\\Pythonwin.exe /edit \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\open\command] @="\"C:\\Python26\\python.exe\" \"%1\" %*" [HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE3\command] @="\"C:\\Python31\\pythonw.exe\" \"C:\\Python31\\Lib\\idlelib\\idle.pyw\" -n -e \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\Edit with Pythonwin3\command] @="C:\\Python31\\Lib\\site-packages\\Pythonwin\\Pythonwin.exe /edit \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\Open with Python3\command] @="\"C:\\Python31\\python.exe\" \"%1\" %*" -------------------END--------------------------- -Mark From bartc at freeuk.com Wed Aug 25 04:22:41 2010 From: bartc at freeuk.com (BartC) Date: Wed, 25 Aug 2010 09:22:41 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com><4c6dcbc5$0$11111$c3e8da3@news.astraweb.com><4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> Message-ID: "Steven D'Aprano" wrote in message news:4c6f8edd$0$28653$c3e8da3 at news.astraweb.com... > On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: >> I onced worked in a shop (Win32 desktop / accouting applications mainly) >> where I was the only guy that could actually understand recursion. FWIW, >> I also was the only guy around that understood "hairy" (lol) concepts >> like callback functions, FSM, polymorphism, hashtables, linked lists, >> ADTs, algorithm complexity etc... > > > Was there anything they *did* understand, or did they just bang on the > keyboard at random until the code compiled? *wink* You underestimate how much programming (of applications) can be done without needing any of this stuff. >> Needless to say, I didn't last long !-) > > And rightly so :) I guess they wanted code that could be maintained by anybody. -- Bartc --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From durumdara at gmail.com Wed Aug 25 05:18:03 2010 From: durumdara at gmail.com (durumdara) Date: Wed, 25 Aug 2010 02:18:03 -0700 (PDT) Subject: ftplib limitations? References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74B333.5020206@sschwarzer.net> Message-ID: <8b5971fe-8561-4801-8605-5b9c1e186c84@f42g2000yqn.googlegroups.com> Hi! On aug. 25, 08:07, Stefan Schwarzer wrote: > > The file is 2 GB in size and is fully transferred, without > blocking or an error message. The status message from the > server is '226-File successfully transferred\n226 31.760 > seconds (measured here), 64.48 Mbytes per second', so this > looks ok, too. > > I think your problem is related to the FTP server or its > configuration. > > Have you been able to reproduce the problem? Yes. I tried with saving the file, but I also got this error. but: Total COmmander CAN download the file, and ncftpget also can download it without problem... Hmmmmm... :-( Thanks: dd From sschwarzer at sschwarzer.net Wed Aug 25 05:44:36 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 25 Aug 2010 11:44:36 +0200 Subject: ftplib limitations? In-Reply-To: References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> Message-ID: <4C74E604.6090208@sschwarzer.net> Hi durumdara, On 2010-08-25 09:43, durumdara wrote: >> I can imagine the error message (a full traceback if >> possible) would help to say a bit more about the cause of >> the problem and maybe what to do about it. > > This was: > > Filename: "Repositories 20100824_101805 (Teljes).zip" Size: 1530296127 > ..download: 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% > Traceback (most recent call last): > File "C:\D\LocalBackup\ftpdown.py", line 31, in > ftp.retrbinary("retr " + s, CallBack) > File "C:\Python26\lib\ftplib.py", line 401, in retrbinary > return self.voidresp() > File "C:\Python26\lib\ftplib.py", line 223, in voidresp > resp = self.getresp() > File "C:\Python26\lib\ftplib.py", line 209, in getresp > resp = self.getmultiline() > File "C:\Python26\lib\ftplib.py", line 195, in getmultiline > line = self.getline() > File "C:\Python26\lib\ftplib.py", line 182, in getline > line = self.file.readline() > File "C:\Python26\lib\socket.py", line 406, in readline > data = self._sock.recv(self._rbufsize) > socket.error: [Errno 10054] A l?tez? kapcsolatot a t?voli ?llom?s > k?nyszer?tette > n bez?rta > > So this message is meaning that the remote station forced close the > existing connection. The file transfer protocol uses two connections for data transfers, a control connection to send commands and responses, and a data connection for the data payload itself. Now it may be that the data connection, after having started the transfer, works as it should, but the control connection times out because the duration of the transfer is too long. A hint at this is that the traceback above contains `getline` and `readline` calls which strongly suggest that this socket was involved in some text transfer (presumably for a status message). Most FTP servers are configured for a timeout of 5 or 10 minutes. If you find that the file transfers don't fail reproducably for a certain size limit, it's probably not the size of the file that causes the problem but some timing issue (see above). What to do about it? One approach is to try to get the timeout value increased. Of course that depends on the relation between you and the party running the server. Another approach is to catch the exception and ignore it. To make sure you only ignore timeout messages, you may want to check the status code at the start of the error message and re-raise the exception if it's not the status expected for a timeout. Something along the lines of: try: # transer involving `retrbinary` except socket.error, exc: if str(exc).startswith("[Errno 10054] "): pass else: raise Note, however, that this is a rather brittle way to handle the problem, as the status code or format of the error message may depend on the platform your program runs on, library versions, etc. In any case you should close and re-open the FTP connection after you got the error from the server. > Now I'm trying with saving the file into temporary file, not hold in > memory. If my theory holds, that shouldn't make a difference. But maybe my theory is wrong. :) Could you do me a favor and try your download with ftputil [1]? The code should be something like: import ftputil host = ftputil.FTPHost(server, userid, passwd) for name in host.listdir(host.curdir): host.download(name, name, 'b') host.close() There's neither a need nor - at the moment - a possibility to specify a callback if you just want the download. (I'm working on the callback support though!) For finding the error, it's of course better to just use the download command for the file that troubles you. I'm the maintainer of ftputil and if you get the same or similar error here, I may find a workaround for ftputil. As it happens, someone reported a similar problem (_if_ it's the same problem in your case) just a few days ago. [2] [1] http://ftputil.sschwarzer.net [2] http://www.mail-archive.com/ftputil at codespeak.net/msg00141.html Stefan From fetchinson at googlemail.com Wed Aug 25 06:00:04 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 25 Aug 2010 12:00:04 +0200 Subject: pypy In-Reply-To: References: Message-ID: > Just curious if anyone had the chance to build pypy on a 64bit > environment and to see if it really makes a huge difference in > performance. Would like to hear some thoughts (or alternatives). I'd recommend asking about this on the pypy mailing list or looking at their documentation first; see http://codespeak.net/pypy/dist/pypy/doc/ HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From dak at gnu.org Wed Aug 25 06:04:08 2010 From: dak at gnu.org (David Kastrup) Date: Wed, 25 Aug 2010 12:04:08 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> Message-ID: <87eidnnh47.fsf@lola.goethe.zz> Hugh Aguilar writes: > On Aug 24, 5:16?pm, Paul Rubin wrote: >> Anyway, as someone else once said, studying a subject like CS isn't done >> by reading. ?It's done by writing out answers to problem after problem. >> Unless you've been doing that, you haven't been studying. > > What about using what I learned to write programs that work? Does that > count for anything? No. Having put together a cupboard that holds some books without falling apart does not make you a carpenter, much less an architect. -- David Kastrup From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 25 06:35:27 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 25 Aug 2010 12:35:27 +0200 Subject: Using String Methods In Jump Tables In-Reply-To: References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c74f1e9$0$21917$426a74cc@news.free.fr> Tim Daneliuk a ?crit : > On 8/19/2010 7:23 PM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: >> >>> Problem: >>> >>> Given tuples in the form (key, string), use 'key' to determine what >>> string method to apply to the string: >>>>> table = {'l': str.lower, 'u': str.upper} >>>>> table['u']('hello world') >> 'HELLO WORLD' >> > (snip) > > Yeah ... those old assembler memories never quite fade do they. > I dunno what you might call this. A Function Dispatch Table > perhaps? I usually refers to this idiom as "dict-based dispatch". And FWIW, it's in fact (part of...) polymorphic dispatch implemention in Python's object model: >>> str.__dict__['lower'] >>> d = dict(l="lower", u="upper") >>> s = "aHa" >>> for k, v in d.items(): ... print "%s : %s" % (k, s.__class__.__dict__[v](s)) From alex at moreati.org.uk Wed Aug 25 06:36:38 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Wed, 25 Aug 2010 03:36:38 -0700 (PDT) Subject: problem with strptime and time zone References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> <45faa241-620e-42c7-b524-949936f63610@f6g2000yqa.googlegroups.com> Message-ID: <611bf2ee-3715-4816-94ca-8a63b5ae8154@s9g2000yqd.googlegroups.com> On Aug 25, 8:48?am, Lawrence D'Oliveiro wrote: > In message > <45faa241-620e-42c7-b524-949936f63... at f6g2000yqa.googlegroups.com>, Alex > > Willmer wrote: > > Dateutil has it's own timezone database ... > > I hate code which doesn?t just use /usr/share/zoneinfo. How many places do > you need to patch every time somebody changes their daylight-saving rules? >From reading http://labix.org/python-dateutil can read timezone information from several platforms, including /usr/share/zoneinfo. I don't know whether one chooses the source explicitly, or if it is detected with fall back to the internal database. From mail at johnohagan.com Wed Aug 25 07:00:23 2010 From: mail at johnohagan.com (John O'Hagan) Date: Wed, 25 Aug 2010 11:00:23 +0000 Subject: Helper classes design question In-Reply-To: <4C73AF10.5010703@sequans.com> References: <201008231047.57128.mail@johnohagan.com> <4C73AF10.5010703@sequans.com> Message-ID: <201008251100.23743.mail@johnohagan.com> On Tue, 24 Aug 2010, Jean-Michel Pichavant wrote: > John O'Hagan wrote: > > I want to know the best way to organise a bunch of functions designed to > > operate on instances of a given class without cluttering the class itself > > with a bunch of unrelated methods. > > > > What I've done is make what I think are called helper classes, each of > > which are initialized with an instance of the main class and has methods > > which are all of the same type (insofar as they return a boolean, or > > modify the object in place, or whatever). > > > > I'm not sure if I'm on the right track here design-wise. Maybe this could > > be better done with inheritance (not my forte), but my first thought is > > that no, the helper classes (if that's what they are) are not actually a > > type of the main class, but are auxiliary to it. I wasn't subscribed when I posted this question so the quoting and threading is messed up (sorry), but thanks for the differing approaches; in the end I have taken Peter Otten's advice and simply put the functions in separate modules according to type (instead of in classes as methods), then imported them. This has all the advantages of using a class, in that I can add new functions in just one place and call them as required without knowing what they are, e.g.: options = {dictionary of option names and values} #derived from optparse for sequence in sequences: for option, value in options.items(): {imported namespace}[option](sequence, value) but it seems simpler and cleaner. John From blog at rivadpm.com Wed Aug 25 07:05:58 2010 From: blog at rivadpm.com (Alex McDonald) Date: Wed, 25 Aug 2010 04:05:58 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> Message-ID: <0b04a316-a147-4179-a11f-de7a935385ea@q16g2000prf.googlegroups.com> On 25 Aug, 01:00, Hugh Aguilar wrote: > On Aug 24, 4:17?pm, Richard Owlett wrote: > > > Hugh Aguilar wrote: > > > [SNIP ;] > > > > The real problem here is that C, Forth and C++ lack automatic garbage > > > collection. If I have a program in which I have to worry about memory > > > leaks (as described above), I would be better off to ignore C, Forth > > > and C++ and just use a language that supports garbage collection. Why > > > should I waste my time carefully freeing up heap space? I will very > > > likely not find everything but yet have a few memory leaks anyway. > > > IOW Hugh has surpassed GIGO to achieve AGG - > > *A*utomatic*G*arbage*G*eneration ;) > > The C programmers reading this are likely wondering why I'm being > attacked. The reason is that Elizabeth Rather has made it clear to > everybody that this is what she wants:http://groups.google.com/group/comp.lang.forth/browse_thread/thread/c... > > Every Forth programmer who aspires to get a job at Forth Inc. is > obliged to attack me. Attacking my software that I posted on the FIG > site is preferred, but personal attacks work too. It is a loyalty > test. Complete bollox. A pox on your persecution fantasies. This isn't about Elizabeth Rather or Forth Inc. It's about your massive ego and blind ignorance. Your example of writing code with memory leaks *and not caring because it's a waste of your time* makes me think that you've never been a programmer of any sort. Ever. In a commercial environment, your slide rule code would be rejected during unit testing, and you'd be fired and your code sent to the bit bucket. This isn't about CS BS; this is about making sure that banks accounts square, that planes fly, that nuclear reactors stay sub-critical; that applications can run 24 by 7, 365 days a year without requiring any human attention. So who designs and writes compilers for fail-safe systems? Who designs and writes operating systems that will run for years, non-stop? Where do they get the assurance that what they're writing is correct -- and provably so? From people that do research, hard math, have degrees, and design algorithms and develop all those other abstract ideas you seem so keen to reject as high-falutin' nonsense. I'd rather poke myself in the eye than run any of the crap you've written. From sschwarzer at sschwarzer.net Wed Aug 25 07:41:27 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 25 Aug 2010 13:41:27 +0200 Subject: ftplib limitations? In-Reply-To: <8b5971fe-8561-4801-8605-5b9c1e186c84@f42g2000yqn.googlegroups.com> References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74B333.5020206@sschwarzer.net> <8b5971fe-8561-4801-8605-5b9c1e186c84@f42g2000yqn.googlegroups.com> Message-ID: <4C750167.7040000@sschwarzer.net> Hi durumdara, On 2010-08-25 11:18, durumdara wrote: > On aug. 25, 08:07, Stefan Schwarzer wrote: >> >> The file is 2 GB in size and is fully transferred, without >> blocking or an error message. The status message from the >> server is '226-File successfully transferred\n226 31.760 >> seconds (measured here), 64.48 Mbytes per second', so this >> looks ok, too. >> >> I think your problem is related to the FTP server or its >> configuration. >> >> Have you been able to reproduce the problem? > > Yes. I tried with saving the file, but I also got this error. > but: Total COmmander CAN download the file, and ncftpget also can > download it without problem... I suppose they do the same as in my former suggestion: "catching" the error and ignoring it. ;-) After all, if I understood you correctly, you get the complete file contents, so with ftplib the download succeeds as well (in a way). You might want to do something like (untested): import os import socket import ftputil def my_download(host, filename): """Some intelligent docstring.""" # Need timestamp to check if we actually have a new # file after the attempted download try: old_mtime = os.path.getmtime(filename) except OSError: old_mtime = 0.0 try: host.download(filename, filename, 'b') except socket.error: is_rewritten = (os.path.getmtime(filename) != old_mtime) # If you're sure that suffices as a test is_complete = (host.path.getsize(filename) == os.path.getsize(filename)) if is_rewritten and is_complete: # Transfer presumably successful, ignore error pass else: # Something else went wrong raise def main(): host = ftputil.FTPHost(...) my_download(host, "large_file") host.close() If you don't want to use an external library, you can use `ftplib.FTP`'s `retrbinary` and check the file size with `ftplib.FTP.size`. This size command requires support for the SIZE command on the server, whereas ftputil parses the remote directory listing to extract the size and so doesn't depend on SIZE support. Stefan From magguru.chinnamnaidu at gmail.com Wed Aug 25 07:42:40 2010 From: magguru.chinnamnaidu at gmail.com (paypal cash) Date: Wed, 25 Aug 2010 04:42:40 -0700 (PDT) Subject: Simple hack to get *$5000* to your Paypal account Message-ID: <1e8ff0e9-212e-44c3-97c8-6d165cf593ac@x20g2000pro.googlegroups.com> Simple hack to get* $5000 * to your Paypal account At http://moneyforwarding.co.cc i have hidden the Paypal Form link in an image. in that website on Right Side below search box, click on image and enter your name and Paypal ID. From anton at mips.complang.tuwien.ac.at Wed Aug 25 08:26:20 2010 From: anton at mips.complang.tuwien.ac.at (Anton Ertl) Date: Wed, 25 Aug 2010 12:26:20 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> <0b04a316-a147-4179-a11f-de7a935385ea@q16g2000prf.googlegroups.com> Message-ID: <2010Aug25.142620@mips.complang.tuwien.ac.at> Alex McDonald writes: > Your example of writing code with >memory leaks *and not caring because it's a waste of your time* makes >me think that you've never been a programmer of any sort. Ever. Well, I find his approach towards memory leaks as described in <779b992b-7199-4126-bf3a-7ec40ea801a6 at j18g2000yqd.googlegroups.com> quite sensible, use something like that myself, and recommend it to others. Followups set to c.l.f (adjust as appropriate). - anton -- M. Anton Ertl http://www.complang.tuwien.ac.at/anton/home.html comp.lang.forth FAQs: http://www.complang.tuwien.ac.at/forth/faq/toc.html New standard: http://www.forth200x.org/forth200x.html EuroForth 2010: http://www.euroforth.org/ef10/ From darwin at nowhere.com Wed Aug 25 08:33:21 2010 From: darwin at nowhere.com (Paul Hemans) Date: Wed, 25 Aug 2010 22:33:21 +1000 Subject: Newbie: Win32 COM problem Message-ID: Simple class to wrap the xlwt module for COM access pyXLS.py: from xlwt import Workbook class WrapXLS: _reg_clsid_ = "{c94df6f0-b001-11df-8d63-00e09103a9a0}" _reg_desc_ = "XLwt wrapper" _reg_progid_ = "PyXLS.Write" _public_methods_ = ['createBook','createSheet','writeSheetCell','saveBook'] # _public_attrs_ = ['book'] def __init__(self): self.book = None def createBook(self): self.book = Workbook() def createSheet(self,sheetName): self.book.add_sheet(sheetName) def writeSheetCell(self, sheet, row, col, value, style=""): sheet = self.book.get_sheet(sheet) sheet.write(row,col,value,style) def saveBook(self,fileName): self.book.save(fileName) if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(WrapXLS) It registers ok with --debug. Code executing within Foxpro (no comments pls): oPyXLS = CREATEOBJECT("PyXLS.Write") oPyXLS.createBook() oPyXLS.createSheet("Sheet 1") -- Error here Output in Python Trace Collector (PythonWin): ... in _GetIDsOfNames_ with '(u'createsheet',)' and '1033' in _Invoke_ with 1001 1033 3 (u'Sheet 1',) Traceback (most recent call last): File "C:\Python26\lib\site-packages\win32com\server\dispatcher.py", line 47, in _Invoke_ return self.policy._Invoke_(dispid, lcid, wFlags, args) File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 277, in _Invoke_ return self._invoke_(dispid, lcid, wFlags, args) File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 282, in _invoke_ return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 585, in _invokeex_ return func(*args) File "C:\development\PyXLS\pyXLS.py", line 13, in createSheet def createBook(self): AttributeError: WrapXLS instance has no attribute '_book' pythoncom error: Python error invoking COM method. Can anyone help? From samufuentes at gmail.com Wed Aug 25 09:03:51 2010 From: samufuentes at gmail.com (Samu) Date: Wed, 25 Aug 2010 06:03:51 -0700 (PDT) Subject: staticmethod behaviour Message-ID: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Hi, I run today into some problems with my code and I realized that there is something in the behaviours of the @staticmethod that I don't really understand. I don't know if it is an error or not, actually, only that it was, definitely, unexpected. I wrote a small demo of what happens. The code: http://dpaste.com/hold/233795/ The answer I get: User created with static: id, rights, rights2 1 ['read', 'write'] ['write2'] ['write3'] User created with User() None [] ['write2'] ['write3'] I was expecting either all arrays from the second to be [] or to be a copy of the first one. If someone can provide an explanation, I would be thankful :) Regards, Samu From samufuentes at gmail.com Wed Aug 25 09:18:37 2010 From: samufuentes at gmail.com (Samu) Date: Wed, 25 Aug 2010 06:18:37 -0700 (PDT) Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: <7492d4d2-8b35-4fc3-a9a1-fe894eba50b1@g17g2000yqe.googlegroups.com> On Aug 25, 3:03?pm, Samu wrote: > Hi, > > I run today into some problems with my code and I realized that there > is something in the behaviours of the @staticmethod that I don't > really understand. I don't know if it is an error or not, actually, > only that it was, definitely, unexpected. > > I wrote a small demo of what happens. > > The code:http://dpaste.com/hold/233795/ > > The answer I get: > User created with static: id, rights, rights2 > 1 ['read', 'write'] ['write2'] ['write3'] > User created with User() > None [] ['write2'] ['write3'] > > I was expecting either all arrays from the second to be [] or to be a > copy of the first one. > > If someone can provide an explanation, I would be thankful :) > > Regards, > Samu In addition, if I don't define the function as static, but either as a method of the object or a function outside of the class, something like this: def cr_user(): user = User(1, ['read'], rights3=[]) user.rights.append('write') user.rights2.append('write2') user.rights3.append('write3') return user I get instead: User created with static: id, rights, rights2 1 ['read', 'write'] ['write2'] ['write3'] User created with User() None [] ['write2'] [] There is some (maybe deep) concept that I don't get it seems, because that output puzzles me... From __peter__ at web.de Wed Aug 25 09:26:10 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Aug 2010 15:26:10 +0200 Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: Samu wrote: > Hi, > > I run today into some problems with my code and I realized that there > is something in the behaviours of the @staticmethod that I don't > really understand. I don't know if it is an error or not, actually, > only that it was, definitely, unexpected. > > I wrote a small demo of what happens. > The code: > class User: > def __init__(self, id=None, rights=[], rights2=[], rights3=[]): > self.id = id > self.rights = rights > self.rights2 = rights2 > self.rights3 = rights3 > @staticmethod > def cr_user(): > user = User(1, ['read'], rights3=[]) > user.rights.append('write') > user.rights2.append('write2') > user.rights3.append('write3') > return user > > print "User created with static: id, rights, rights2" > a = User.cr_user() > print a.id, a.rights, a.rights2, a.rights3 > print "User created with User()" > b = User() > print b.id, b.rights, b.rights2, a.rights3 > The answer I get: > User created with static: id, rights, rights2 > 1 ['read', 'write'] ['write2'] ['write3'] > User created with User() > None [] ['write2'] ['write3'] > > I was expecting either all arrays from the second to be [] or to be a > copy of the first one. > > If someone can provide an explanation, I would be thankful :) The problem is not the staticmethod, it's the mutable default values for __init__(). See http://effbot.org/zone/default-values.htm Peter From dsdale24 at gmail.com Wed Aug 25 09:49:29 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Wed, 25 Aug 2010 06:49:29 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: <23146f03-2502-427d-b55d-aec06f732fbf@x21g2000yqa.googlegroups.com> On Aug 24, 5:29?pm, Benjamin Kaplan wrote: > On Tue, Aug 24, 2010 at 3:31 PM, Darren Dale wrote: > > On Aug 23, 9:58?am, Darren Dale wrote: > >> The following script runs without problems on Ubuntu and Windows 7. > >> h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > >> h5py/): > > >> from multiprocessing import Pool > >> import h5py > > >> def update(i): > >> ? ? print i > > >> def f(i): > >> ? ? "hello foo" > >> ? ? return i*i > > >> if __name__ == '__main__': > >> ? ? pool = Pool() > >> ? ? for i in range(10): > >> ? ? ? ? pool.apply_async(f, [i], callback=update) > >> ? ? pool.close() > >> ? ? pool.join() > > >> On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > >> comment out the as-yet unused h5py import, otherwise I get a > >> traceback: > > >> Exception in thread Thread-1: > >> Traceback (most recent call last): > >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > >> lib/python2.6/threading.py", line 532, in __bootstrap_inner > >> ? ? self.run() > >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > >> lib/python2.6/threading.py", line 484, in run > >> ? ? self.__target(*self.__args, **self.__kwargs) > >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > >> lib/python2.6/multiprocessing/pool.py", line 226, in _handle_tasks > >> ? ? put(task) > >> PicklingError: Can't pickle : attribute lookup > >> __builtin__.function failed > > > This is a really critical bug for me, but I'm not sure how to proceed. > > Can I file a bug report on the python bugtracker if the only code I > > can come up with to illustrate the problem requires a lame import of a > > third party module? > > -- > > It's working fine for me, OS X 10.6.4, Python 2.6 and h5py from Macports. Really? With the h5py import uncommented? I just uninstalled and reinstalled my entire macports python26/py26-numpy/hdf5-18/py26-h5py stack, and I still see the same error. From steve.ferg.bitbucket at gmail.com Wed Aug 25 09:56:22 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Wed, 25 Aug 2010 06:56:22 -0700 (PDT) Subject: Help please! strange Tkinter behavior has me totally baffled. References: <6270b512-8b73-434d-83c3-ec5c60100eb1@w17g2000vbn.googlegroups.com> Message-ID: Thanks mucho! That was it! -- Steve Ferg From dsdale24 at gmail.com Wed Aug 25 09:58:35 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Wed, 25 Aug 2010 06:58:35 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: <1cbf9e1f-67c5-4519-880b-7c65c9504777@s9g2000yqd.googlegroups.com> On Aug 24, 4:32?pm, Thomas Jollans wrote: > On Tuesday 24 August 2010, it occurred to Darren Dale to exclaim: > > > > > > > On Aug 23, 9:58 am, Darren Dale wrote: > > > The following script runs without problems on Ubuntu and Windows 7. > > > h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > > > h5py/): > > > > from multiprocessing import Pool > > > import h5py > > > > def update(i): > > > ? ? print i > > > > def f(i): > > > ? ? "hello foo" > > > ? ? return i*i > > > > if __name__ == '__main__': > > > ? ? pool = Pool() > > > ? ? for i in range(10): > > > ? ? ? ? pool.apply_async(f, [i], callback=update) > > > ? ? pool.close() > > > ? ? pool.join() > > > > On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > > > comment out the as-yet unused h5py import, otherwise I get a > > > traceback: > > What on earth is h5py doing there? ?If what you're telling us is actually > happening, and the code works 1:1 on Linux and Windows, but fails on OSX, and > you're using the same versions of h5py and Python, then the h5py > initialization code is not only enticing multiprocessing to try to pickle > something other than usual, but it is also doing that due to some platform- > dependent witchcraft, and I doubt there's very much separating the OSX > versions from the Linux versions of anything involved. I can't find anything in the source to suggest that h5py is doing any platform-specific magic. Do you have an idea of how it would be possible for initialization code to cause multiprocessing to try to pickle something it normally would not? > > This is a really critical bug for me, but I'm not sure how to proceed. > > Can I file a bug report on the python bugtracker if the only code I > > can come up with to illustrate the problem requires a lame import of a > > third party module? > > I doubt this is an issue with Python. File a bug on the h5py tracker and see > what they say. The people there might at least have some vague inkling of what > may be going on. Thanks for the suggestion. I was in touch with the h5py maintainer before my original post. We don't have any leads. From samufuentes at gmail.com Wed Aug 25 09:58:46 2010 From: samufuentes at gmail.com (Samu) Date: Wed, 25 Aug 2010 06:58:46 -0700 (PDT) Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: On Aug 25, 3:26?pm, Peter Otten <__pete... at web.de> wrote: > Samu wrote: > > Hi, > > > I run today into some problems with my code and I realized that there > > is something in the behaviours of the @staticmethod that I don't > > really understand. I don't know if it is an error or not, actually, > > only that it was, definitely, unexpected. > > > I wrote a small demo of what happens. > > The code: > > class User: > > ?def __init__(self, id=None, rights=[], rights2=[], rights3=[]): > > ? self.id = id > > ? self.rights = rights > > ? self.rights2 = rights2 > > ? self.rights3 = rights3 > > ?@staticmethod > > ?def cr_user(): > > ? user = User(1, ['read'], rights3=[]) > > ? user.rights.append('write') > > ? user.rights2.append('write2') > > ? user.rights3.append('write3') > > ? return user > > > print "User created with static: id, rights, rights2" > > a = User.cr_user() > > print a.id, a.rights, a.rights2, a.rights3 > > print "User created with User()" > > b = User() > > print b.id, b.rights, b.rights2, a.rights3 > > The answer I get: > > User created with static: id, rights, rights2 > > 1 ['read', 'write'] ['write2'] ['write3'] > > User created with User() > > None [] ['write2'] ['write3'] > > > I was expecting either all arrays from the second to be [] or to be a > > copy of the first one. > > > If someone can provide an explanation, I would be thankful :) > > The problem is not the staticmethod, it's the mutable default values for > __init__(). See > > http://effbot.org/zone/default-values.htm > > Peter Ahh, thank you very much for the link. Now I understand. I remember having read that before, but it is not until you face the problem that the concept sticks. But why does it have a different behaviour the staticmethod with the "rights3" case then? From carlos.grohmann at gmail.com Wed Aug 25 09:59:36 2010 From: carlos.grohmann at gmail.com (Carlos Grohmann) Date: Wed, 25 Aug 2010 06:59:36 -0700 (PDT) Subject: speed of numpy.power()? Message-ID: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Hi all, I'd like to hear from you on the benefits of using numpy.power(x,y) over (x*x*x*x..) I looks to me that numpy.power takes more time to run. cheers Carlos From nanothermite911fbibustards at gmail.com Wed Aug 25 10:12:22 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 07:12:22 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards Message-ID: <9c3b672d-b636-4f12-9918-4837784fce42@x42g2000yqx.googlegroups.com> CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list From breamoreboy at yahoo.co.uk Wed Aug 25 10:20:50 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 25 Aug 2010 15:20:50 +0100 Subject: speed of numpy.power()? In-Reply-To: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: On 25/08/2010 14:59, Carlos Grohmann wrote: > Hi all, > > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > > I looks to me that numpy.power takes more time to run. > > cheers > > Carlos > Measure it yourself using the timeit module. Cheers. Mark Lawrence. From nanothermite911fbibustards at gmail.com Wed Aug 25 10:22:22 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 07:22:22 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards Message-ID: <059e2fea-bf6d-4f55-b9e9-7338ea1fbe97@f6g2000yqa.googlegroups.com> CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list From ajeet.yadav.77 at gmail.com Wed Aug 25 10:25:38 2010 From: ajeet.yadav.77 at gmail.com (Ajeet Yadav) Date: Wed, 25 Aug 2010 19:55:38 +0530 Subject: Python2.4 on ARM-Linux "import time module fails" Message-ID: Hi, I cross-compiled Python2.4 for ARM (Linux 2.6.30) in order to run autotest-client-xxx on my ARM target. When I run autotest on ARM target I get "ImportError: No module named time" Which package I need to install to add support for time module. # bin/autotest samples/filesystem Traceback (most recent call last): File "bin/autotest", line 6, in ? import common File "/dtv/usb/sda1/autotest-client-0.12.0-dirty/bin/common.py", line 8, in ? root_module_name="autotest_lib.client") File "/dtv/usb/sda1/autotest-client-0.12.0-dirty/setup_modules.py", line 139, in setup _monkeypatch_logging_handle_error() File "/dtv/usb/sda1/autotest-client-0.12.0-dirty/setup_modules.py", line 103, in _monkeypatch_logging_handle_error import logging File "/dtv/usb/sda1/Python-2.4/Lib/logging/__init__.py", line 29, in ? import sys, os, types, time, string, cStringIO ImportError: No module named time With Regards Ajeet Yadav -------------- next part -------------- An HTML attachment was scrubbed... URL: From stndshp at gmail.com Wed Aug 25 10:31:03 2010 From: stndshp at gmail.com (Standish P) Date: Wed, 25 Aug 2010 07:31:03 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards References: <9c3b672d-b636-4f12-9918-4837784fce42@x42g2000yqx.googlegroups.com> Message-ID: On Aug 25, 7:12?am, nanothermite911fbibustards wrote: > CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria > Lauterbach and KILL THEM > > Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist > Bustard who > > The girl was a German like the one Roman Polansky raped, Semantha > Geimer > > http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ > > Look at his face, what criminal race is he ? What goes around comes > around !!! > > Former Marine convicted in North Carolina of killing female colleague > By the CNN Wire Staff > August 23, 2010 8:33 p.m. EDT > > For more on this story, read the coverage from CNN affiliate WRAL. > > (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North > Carolina on Monday of first degree murder in the 2007 death of Lance > Cpl. Maria Lauterbach, who was eight months pregnant when she died. > > An autopsy showed that Lauterbach, 20, died of blunt force trauma to > the head. Police unearthed her charred body from beneath a barbecue > pit in Laurean's backyard in January 2008. She had disappeared the > month before. > > Laurean, who was dressed in black slacks and wore a white shirt and > black tie, did not show any emotion as the judge read his sentence of > life in prison without parole. He either said or mouthed something to > someone in the audience of the courtroom before he was led out in > handcuffs, video showed. > > Laurean and Lauterbach were stationed together at Camp Lejeune, North > Carolina. > > North Carolina prosecutors alleged Laurean killed Lauterbach on > December 14 and used her ATM card 10 days later before fleeing to > Mexico.Laurean was arrested there in April 2008. He holds dual > citizenship in the United States and Mexico. > > Before her death, Lauterbach told the Marines that Laurean had raped > her. Laurean denied it, and disappeared just a few weeks before a > scheduled rape hearing at Camp LeJeune. > > The DNA of Lauterbach's unborn child did not match that of Laurean, > according to law enforcement personnel. > > Authorities found Lauterbach's body after Laurean's wife, Christina, > produced a note her husband had written claiming the 20-year-old > woman > slit her own throat during an argument, according to officials. > > Although a gaping 4-inch wound was found on the left side of > Lauterbach's neck, autopsy results indicated that the wound itself > would not have been fatal and may have occurred after death. > > Asked by a Mexican reporter at the time of his arrest whether he > killed Lauterbach, Laurean replied, "I loved her." > > Laurean's lawyer said his client would appeal the decision. > > ///////////////////////////////////////////////////////////////// > > The MARINE BASTARD will probably claim INSANITY ........ > > ////////////////////// > The FAT per DIEM FBI bustards use our TAX PAYER MONEY and > INCOMPETENCE > is UNACCEPTABLE. > > ===== > > http://www.youtube.com/watch?v=lX18zUp6WPY > > http://www.youtube.com/watch?v=XQapkVCx1HI > > http://www.youtube.com/watch?v=tXJ-k-iOg0M > > Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX > Mailer ? > Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did > you release the 5 dancing Israelis compromising the whole 911 > investigation ? If the Dubai Police can catch Mossad Murderers and > put > the videos and Iranian Police can why cant you put the Pentagon > Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and > puting on INTERNATIONAL MEDIA a day after catching him without > TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did > you have to LIE about Dr Afiya Siddiqui and torture that Innocent > little mother of 3 and smashing the skull of her one child ? > > http://www.youtube.com/watch?v=DhMcii8smxkhttp://www.youtube.com/watch?v=0SZ2lxDJmdg > > There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian > courts. > > FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but > only because he was a white. They got away with MURDER of thousands > of > Non-whites in all parts of the world. > > Daily 911 news :http://911blogger.com > > http://www.youtube.com/watch?v=tRfhUezbKLw > > http://www.youtube.com/watch?v=x7kGZ3XPEm4 > > http://www.youtube.com/watch?v=lX18zUp6WPY > > Conclusion : FBI bustards are RACIST and INcompetent. They could > neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they > cover them up - whichever was their actual goal or task. > > SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across > tbe board, esp the whites/jew on the top. > > FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST > and > UNPATRIOTIC Act > FBI bustards failed to prevent ROMAN POLANSKY from absconding to > europe and rapes. > FBI bustards failed to prevent OKLAHOMA > > --http://mail.python.org/mailman/listinfo/python-list ... so you want to render this in TeX ... ? From __peter__ at web.de Wed Aug 25 10:32:02 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Aug 2010 16:32:02 +0200 Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: Samu wrote: > the concept sticks. But why does it have a different behaviour the > staticmethod with the "rights3" case then? Moving from staticmethod to standalone function doesn't affect the output. You have inadvertently changed something else. Peter From hniksic at xemacs.org Wed Aug 25 10:41:27 2010 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 25 Aug 2010 16:41:27 +0200 Subject: speed of numpy.power()? References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: <874oei69go.fsf@busola.homelinux.net> Carlos Grohmann writes: > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > > I looks to me that numpy.power takes more time to run. You can use math.pow, which is no slower than repeated multiplication, even for small exponents. Obviously, after the exponent has grown large enough, numpy.power becomes faster than repeated exponentiation (it's already faster at 100). Like math.pow, it supports negative and non-integer exponents. Unlike math.pow, numpy.power also supports all kinds of interesting objects as bases for exponentiation. From nick_keighley_nospam at hotmail.com Wed Aug 25 10:43:36 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Wed, 25 Aug 2010 07:43:36 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> <518b97c6-78ad-4ce9-9967-c7f72ea74109@5g2000yqz.googlegroups.com> <4c6d356f.608280081@text.giganews.com> Message-ID: <2e241131-17f7-4cf0-9e0e-f2ec4e11f714@v41g2000yqv.googlegroups.com> On 19 Aug, 16:25, c... at tiac.net (Richard Harter) wrote: > On Wed, 18 Aug 2010 01:39:09 -0700 (PDT), Nick Keighley > wrote: > >On 17 Aug, 18:34, Standish P wrote: > >> How are these heaps being implemented ? Is there some illustrative > >> code or a book showing how to implement these heaps in C for example ? > > >any book of algorithms I'd have thought my library is currently inaccessible. Normally I'd have picked up Sedgewick and seen what he had to say on the subject. And possibly Knuth (though that requires taking more of a deep breath). Presumably Plauger's library book includes an implementation of malloc()/free() so that might be a place to start. > >http://en.wikipedia.org/wiki/Dynamic_memory_allocation > >http://www.flounder.com/inside_storage_allocation.htm > > >I've no idea how good either of these is serves me right for not checking :-( > The wikipedia page is worthless. ? odd really, you'd think basic computer science wasn't that hard... I found even wikipedia's description of a stack confusing and heavily biased towards implementation > The flounder page has > substantial meat, but the layout and organization is a mess. ?A > quick google search didn't turn up much that was general - most > articles are about implementations in specific environments. From samufuentes at gmail.com Wed Aug 25 11:17:03 2010 From: samufuentes at gmail.com (Samu) Date: Wed, 25 Aug 2010 08:17:03 -0700 (PDT) Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: <9ac9f8a0-4127-4138-9452-bc0431a3c579@x42g2000yqx.googlegroups.com> On Aug 25, 4:32?pm, Peter Otten <__pete... at web.de> wrote: > Samu wrote: > > the concept sticks. But why does it have a different behaviour the > > staticmethod with the "rights3" case then? > > Moving from staticmethod to standalone function doesn't affect the output. > You have inadvertently changed something else. > > Peter Absolutely right. Thank you very much for your time and answers, Peter :) It helped me a lot! From exarkun at twistedmatrix.com Wed Aug 25 11:24:13 2010 From: exarkun at twistedmatrix.com (Jean-Paul Calderone) Date: Wed, 25 Aug 2010 08:24:13 -0700 (PDT) Subject: How to see intermediate fail results from unittest as tests are running? References: Message-ID: <68309158-cc5d-4857-952a-d89cb767cb35@q22g2000yqm.googlegroups.com> On Aug 18, 9:20?pm, Margie Roginski wrote: > Hi, > > I am using unittest in a fairly basic way, where I have a single file > that simply defines a class that inherits from unittest.TestCase and > then within that class I have a bunch of methods that start with > "test". ?Within that file, at the bottom I have: > > if __name__ == "__main__": > ? ? unittest.main() > > This works fine and it runs all of the testxx() methods in my file. > As it runs it prints if the tests passed or failed, but if they fail, > it does not print the details of the assert that made them fail. ?It > collects this info up and prints it all at the end. > > Ok - my question: Is there any way to get unittest to print the > details of the assert that made a test fail, as the tests are > running? ?IE, after a test fails, I would like to see why, rather than > waiting until all the tests are done. > > I've searched the doc and even looked at the code, and it seems the > answer is no, but I'm just wondering if I'm missing something. > > Thanks! > > Margie trial (Twisted's test runner) has a `--rterrors` option which causes it to display errors as soon as they happen. Jean-Paul From cournape at gmail.com Wed Aug 25 11:40:10 2010 From: cournape at gmail.com (David Cournapeau) Date: Thu, 26 Aug 2010 00:40:10 +0900 Subject: speed of numpy.power()? In-Reply-To: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: On Wed, Aug 25, 2010 at 10:59 PM, Carlos Grohmann wrote: > Hi all, > > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) Without more context, I would say None if x*x*x*x*... works and you are not already using numpy. The point of numpy is mostly to work on numpy arrays, and to support types of data not "natively" supported by python (single, extended precision). If x is a python object such as int or float, numpy will also be much slower. Using numpy would make sense if for example you are already using numpy everywhere else, for consistency reason, David From carlos.grohmann at gmail.com Wed Aug 25 11:59:19 2010 From: carlos.grohmann at gmail.com (Carlos Grohmann) Date: Wed, 25 Aug 2010 08:59:19 -0700 (PDT) Subject: speed of numpy.power()? References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: <5cd0c88f-5be7-443a-885e-6fc6deaaf3f0@x42g2000yqx.googlegroups.com> On 25 ago, 12:40, David Cournapeau wrote: > On Wed, Aug 25, 2010 at 10:59 PM, Carlos Grohmann > Thanks David and Hrvoje. That was the feedback I was looking for. I am using numpy in my app but in some cases I will use math.pow(), as some tests with timeit showed that numpy.power was slower for (x*x*x*x*x). best Carlos From dsdale24 at gmail.com Wed Aug 25 12:24:01 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Wed, 25 Aug 2010 09:24:01 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: On Aug 24, 4:32?pm, Thomas Jollans wrote: > On Tuesday 24 August 2010, it occurred to Darren Dale to exclaim: > > > > > > > On Aug 23, 9:58 am, Darren Dale wrote: > > > The following script runs without problems on Ubuntu and Windows 7. > > > h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > > > h5py/): > > > > from multiprocessing import Pool > > > import h5py > > > > def update(i): > > > ? ? print i > > > > def f(i): > > > ? ? "hello foo" > > > ? ? return i*i > > > > if __name__ == '__main__': > > > ? ? pool = Pool() > > > ? ? for i in range(10): > > > ? ? ? ? pool.apply_async(f, [i], callback=update) > > > ? ? pool.close() > > > ? ? pool.join() > > > > On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > > > comment out the as-yet unused h5py import, otherwise I get a > > > traceback: > > What on earth is h5py doing there? ?If what you're telling us is actually > happening, and the code works 1:1 on Linux and Windows, but fails on OSX, and > you're using the same versions of h5py and Python, then the h5py > initialization code is not only enticing multiprocessing to try to pickle > something other than usual, but it is also doing that due to some platform- > dependent witchcraft, and I doubt there's very much separating the OSX > versions from the Linux versions of anything involved. Your analysis was spot on. About a year ago, I contributed a patch to h5py which checks to see if h5py is being imported into an active IPython session. If so, then a custom tab completer is loaded to make it easier to navigate hdf5 files. In the development version of IPython, a function that used to return None if there was no instance of an IPython interactive shell now creates and returns a new instance. This was the cause of the error I was reporting. If one were to install ipython from the master branch at github or from http://ipython.scipy.org/dist/testing/ipython-dev-nightly.tgz, then the following script will reproduce the problem. I'm not sure why this causes an error, but I'll discuss it with the IPython devs. Thank you Thomas and Benjamin for helping me understand the problem. Darren from multiprocessing import Pool import IPython.core.ipapi as ip ip.get() def update(i): print i def f(i): return i*i if __name__ == '__main__': pool = Pool() for i in range(10): pool.apply_async(f, [i], callback=update) pool.close() pool.join() From robert.kern at gmail.com Wed Aug 25 12:44:06 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 25 Aug 2010 11:44:06 -0500 Subject: speed of numpy.power()? In-Reply-To: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: On 8/25/10 8:59 AM, Carlos Grohmann wrote: > Hi all, > > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > > I looks to me that numpy.power takes more time to run. You will want to ask numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists The advantage that numpy.power(x,y) has over (x*x*x...) is that y can be floating point. We do not attempt to do strength reduction in the integer case. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ppearson at nowhere.invalid Wed Aug 25 13:39:46 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 25 Aug 2010 17:39:46 GMT Subject: speed of numpy.power()? References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: <8dl2r2F5h4U1@mid.individual.net> On Wed, 25 Aug 2010 06:59:36 -0700 (PDT), Carlos Grohmann wrote: > > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > Using the "dis" package under Python 2.5, I see that computing x_to_the_16 = x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x uses 15 multiplies. I hope that numpy.power does it with 4. -- To email me, substitute nowhere->spamcop, invalid->net. From zapwireDASHgroups at yahoo.com Wed Aug 25 14:36:07 2010 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 25 Aug 2010 11:36:07 -0700 Subject: Can PySerial's write method be called by multiple threads? Message-ID: I have a multi-threaded application where several of the threads need to write to a serial port that's being handled by pySerial. If pySerial thread-safe in the sense that pySerial.write behaves atomically? I.e., if thread 1 executes, serport.write("Hello, world!") and thread 2 executes serport.write("All your bases are belong to us!"), is it guaranteed that the output over the serial port won't "mix" the two together (e.g., "Hello All your bases are belong to us!, world!") ? I looked at the source code, and the write method eventually boils down to calling an the OS's "write" function, which presumably ends up being a call to a C function. Given the global interpreter lock -- and particularly how C functions can't be interrupted by the Python interpreter at all -- it sure seems as though everything is copacetic here? If not I can just add a queue and have everything go through it, but of course I'd like to avoid the extra code and CPU cycles if it isn't at all necessary. Thank you, ---Joel Koltner From thomas at jollybox.de Wed Aug 25 14:54:36 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 25 Aug 2010 20:54:36 +0200 Subject: Can PySerial's write method be called by multiple threads? In-Reply-To: References: Message-ID: <201008252054.37377.thomas@jollybox.de> On Wednesday 25 August 2010, it occurred to Joel Koltner to exclaim: > I have a multi-threaded application where several of the threads need to > write to a serial port that's being handled by pySerial. If pySerial > thread-safe in the sense that pySerial.write behaves atomically? I.e., if > thread 1 executes, serport.write("Hello, world!") and thread 2 executes > serport.write("All your bases are belong to us!"), is it guaranteed that > the output over the serial port won't "mix" the two together (e.g., "Hello > All your bases are belong to us!, world!") ? > > I looked at the source code, and the write method eventually boils down to > calling an the OS's "write" function, which presumably ends up being a call > to a C function. Given the global interpreter lock -- and particularly > how C functions can't be interrupted by the Python interpreter at all -- > it sure seems as though everything is copacetic here? I expect that it gives away the GIL to call the resident write() function, to allow other threads to run while it's sitting there, blocking. I haven't looked at the code, so maybe it doesn't hand over the GIL, but if it doesn't, I'd consider that a bug rather than a feature: the GIL shouldn't be abused as some kind of local mutex, and only gets in the way anyway. Speaking of the GIL, you shouldn't rely on it being there. Ever. It's a necessary evil, or it appears to be necessary. but nobody likes it and if somebody finds a good way to kick it out then that will happen. (That happens to be an explicit exception from the language moratorium, so it's not just my own personal wishful thinking) > > If not I can just add a queue and have everything go through it, but of > course I'd like to avoid the extra code and CPU cycles if it isn't at all > necessary. From python at mrabarnett.plus.com Wed Aug 25 15:02:21 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 25 Aug 2010 20:02:21 +0100 Subject: Can PySerial's write method be called by multiple threads? In-Reply-To: References: Message-ID: <4C7568BD.3040400@mrabarnett.plus.com> On 25/08/2010 19:36, Joel Koltner wrote: > I have a multi-threaded application where several of the threads need to > write to a serial port that's being handled by pySerial. If pySerial > thread-safe in the sense that pySerial.write behaves atomically? I.e., > if thread 1 executes, serport.write("Hello, world!") and thread 2 > executes serport.write("All your bases are belong to us!"), is it > guaranteed that the output over the serial port won't "mix" the two > together (e.g., "Hello All your bases are belong to us!, world!") ? > > I looked at the source code, and the write method eventually boils down > to calling an the OS's "write" function, which presumably ends up being > a call to a C function. Given the global interpreter lock -- and > particularly how C functions can't be interrupted by the Python > interpreter at all -- it sure seems as though everything is copacetic here? > Don't assume that just because it calls a C function the GIL won't be released. I/O calls which can take a relatively long time to complete often release the GIL. > If not I can just add a queue and have everything go through it, but of > course I'd like to avoid the extra code and CPU cycles if it isn't at > all necessary. > Unless I know that something is definitely thread-safe, that would be the way I would go. From zapwireDASHgroups at yahoo.com Wed Aug 25 15:02:27 2010 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 25 Aug 2010 12:02:27 -0700 Subject: Can PySerial's write method be called by multiple threads? References: Message-ID: <8Nddo.61739$MG3.56239@en-nntp-16.dc1.easynews.com> "Thomas Jollans" wrote in message news:mailman.36.1282762569.29448.python-list at python.org... > I expect that it gives away the GIL to call the resident write() function, > to > allow other threads to run while it's sitting there, blocking. I haven't > looked at the code, so maybe it doesn't hand over the GIL, but if it > doesn't, > I'd consider that a bug rather than a feature: the GIL shouldn't be abused > as > some kind of local mutex, and only gets in the way anyway. Ah, I expect you're correct. I'm still largely a Python newbie, and only know enough about things like the GIL to get myself into trouble. > Speaking of the GIL, you shouldn't rely on it being there. Ever. It's a > necessary evil, or it appears to be necessary. but nobody likes it and if > somebody finds a good way to kick it out then that will happen. OK, but presumably I can't know whether or not someone who wrote a library like pySerial relied on it or not. Although I suppose this is really a documentation bug -- pySerial's documentation doesn't talk about multi-threaded access directly, although their "minicom" example does demonstrate it in action. Thanks for the help, ---Joel From jedmeltzer at gmail.com Wed Aug 25 15:46:25 2010 From: jedmeltzer at gmail.com (Jed) Date: Wed, 25 Aug 2010 12:46:25 -0700 (PDT) Subject: split string into multi-character "letters" Message-ID: Hi, I'm seeking help with a fairly simple string processing task. I've simplified what I'm actually doing into a hypothetical equivalent. Suppose I want to take a word in Spanish, and divide it into individual letters. The problem is that there are a few 2-character combinations that are considered single letters in Spanish - for example 'ch', 'll', 'rr'. Suppose I have: alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include the whole alphabet but I shortened it here theword = 'churro' I would like to split the string 'churro' into a list containing: 'ch','u','rr','o' So at each letter I want to look ahead and see if it can be combined with the next letter to make a single 'letter' of the Spanish alphabet. I think this could be done with a regular expression passing the list called "alphabet" to re.match() for example, but I'm not sure how to use the contents of a whole list as a search string in a regular expression, or if it's even possible. My real application is a bit more complex than the Spanish alphabet so I'm looking for a fairly general solution. Thanks, Jed From nagle at animats.com Wed Aug 25 15:54:00 2010 From: nagle at animats.com (John Nagle) Date: Wed, 25 Aug 2010 12:54:00 -0700 Subject: Declare self.cursor In-Reply-To: References: Message-ID: <4c7574e6$0$1655$742ec2ed@news.sonic.net> On 8/24/2010 10:15 AM, Dani Valverde wrote: > Hello! > I am working on a GUI to connect to a MySQL database using MySQLdb (code > in attached file). I define the cursor in lines 55-66 in the OnLogin > function within the LoginDlg class. > > /db= MySQLdb.connect(host='localhost', user=Username , passwd=pwd, > db='Ornithobase') > self.cursor = db.cursor()/ > > When I try to use the cursor on another part of the code (EditUser > class, line 176) > > /sql = 'select substring_index(CURRENT_USER(),"@",1)' > login.cursor.execute(sql)/ > > I get this error: > > /AttributeError: 'LoginDlg' object has no attribute 'cursor'/ > > You can check the code for details, I think is better. > Cheers! > > Dani > self.cursor = db.cursor() ... self.Destroy() # probably clears the object Also, it's generally better to hold on to the database handle and get a cursor from it as a local variable when needed. You need the database handle for "db.commit()", at least. Getting a cursor is fast. (Actually, in MySQL, there is only one cursor.) I realize it's a desktop application, but still: db= MySQLdb.connect(host='localhost', user='root' , passwd='acrsci00', db='Ornithobase') From john.passaniti at gmail.com Wed Aug 25 15:56:06 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Wed, 25 Aug 2010 12:56:06 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> Message-ID: <81e52218-b72c-4b7c-aed6-82e040803064@s9g2000yqd.googlegroups.com> On Aug 24, 8:00?pm, Hugh Aguilar wrote: > The C programmers reading this are likely wondering why I'm being > attacked. The reason is that Elizabeth Rather has made it clear to > everybody that this is what she wants: [http://tinyurl.com/2bjwp7q] Hello to those outside of comp.lang.forth, where Hugh usually leaves his slime trail. I seriously doubt many people will bother to read the message thread Hugh references, but if you do, you'll get to delight in the same nonsense Hugh has brought to comp.lang.forth. Here's the compressed version: 1. Hugh references code ("symtab") that he wrote (in Factor) to manage symbol tables. 2. I (and others) did some basic analysis and found it to be a poor algorithm-- both in terms of memory use and performance-- especially compared to the usual solutions (hash tables, splay trees, etc.). 3. I stated that symtab sucked for the intended application. 4. Hugh didn't like that I called his baby ugly and decided to expose his bigotry. 5. Elizabeth Rather said she didn't appreciate Hugh's bigotry in the newsgroup. Yep, that's it. What Hugh is banking on is that you won't read the message thread, and that you'll blindly accept that Elizabeth is some terrible ogre with a vendetta against Hugh. The humor here is that Hugh himself provides a URL that disproves that! So yes, if you care, do read the message thread. It won't take long for you to get a clear impression of Hugh's character. From nagle at animats.com Wed Aug 25 16:01:01 2010 From: nagle at animats.com (John Nagle) Date: Wed, 25 Aug 2010 13:01:01 -0700 Subject: Can PySerial's write method be called by multiple threads? In-Reply-To: References: Message-ID: <4c75768a$0$1608$742ec2ed@news.sonic.net> On 8/25/2010 11:36 AM, Joel Koltner wrote: > I have a multi-threaded application where several of the threads need to > write to a serial port that's being handled by pySerial. If pySerial > thread-safe in the sense that pySerial.write behaves atomically? I.e., > if thread 1 executes, serport.write("Hello, world!") and thread 2 > executes serport.write("All your bases are belong to us!"), is it > guaranteed that the output over the serial port won't "mix" the two > together (e.g., "Hello All your bases are belong to us!, world!") ? You're not guaranteed that one Python "write" maps to one OS-level "write". Individual "print" statements in Python are not atomic. You don't need a queue, though; just use your own "write" function with a lock. import threading lok = threading.Lock() def atomicwrite(fd, data) : with lok : fd.write(data) John Nagle From jpiitula at ling.helsinki.fi Wed Aug 25 16:05:39 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 25 Aug 2010 23:05:39 +0300 Subject: split string into multi-character "letters" References: Message-ID: Jed writes: > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would > include the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' All non-overlapping matches, each as long as can be, and '.' catches single characters by default: >>> import re >>> re.findall('ch|ll|rr|.', 'churro') ['ch', 'u', 'rr', 'o'] From vlastimil.brom at gmail.com Wed Aug 25 16:08:19 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Wed, 25 Aug 2010 22:08:19 +0200 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: 2010/8/25 Jed : > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. ?The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. ?I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. ?My real application > is a bit more complex than the Spanish alphabet so I'm looking for a > fairly general solution. > Thanks, > Jed > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I am not sure, whether it can be generalised enough for your needs, but you can try something like >>> re.findall(r"rr|ll|ch|[a-z]", "asdasdallasdrrcvb") ['a', 's', 'd', 'a', 's', 'd', 'a', 'll', 'a', 's', 'd', 'rr', 'c', 'v', 'b'] of course, the pattern should be adjusted precisely in order not to loose characters... hth, vbr From python at mrabarnett.plus.com Wed Aug 25 16:10:11 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 25 Aug 2010 21:10:11 +0100 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: <4C7578A3.2080603@mrabarnett.plus.com> On 25/08/2010 20:46, Jed wrote: > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. My real application > is a bit more complex than the Spanish alphabet so I'm looking for a > fairly general solution. You can build a regex with: >>> '|'.join(alphabet) 'a|b|c|ch|d|u|r|rr|o' You want to try to match, say, 'ch' before 'c', so you want the longest first: >>> '|'.join(sorted(alphabet, key=len, reverse=True)) 'ch|rr|a|b|c|d|u|r|o' If you were going to match the Spanish alphabet then I would recommend that you do it in Unicode. Well, any text that's not pure ASCII should be done in Unicode! From thomas at jollybox.de Wed Aug 25 16:16:52 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 25 Aug 2010 22:16:52 +0200 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: <201008252216.53347.thomas@jollybox.de> On Wednesday 25 August 2010, it occurred to Jed to exclaim: > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. My real application > is a bit more complex than the Spanish alphabet so I'm looking for a > fairly general solution. A very simple solution that might be general enough: >>> def tokensplit(string, bits): ... while string: ... for b in bits: ... if string.startswith(b): ... yield b ... string = string[len(b):] ... break ... else: ... raise ValueError("string not composed of the right bits.") ... >>> >>> alphabet = ['a','b','c','ch','d','u','r','rr','o'] >>> # move longer letters to the front >>> alphabet.sort(key=len, reverse=True) >>> >>> list(tokensplit("churro", alphabet)) ['ch', 'u', 'rr', 'o'] >>> From python.list at tim.thechases.com Wed Aug 25 16:17:54 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 25 Aug 2010 15:17:54 -0500 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: <4C757A72.7020404@tim.thechases.com> On 08/25/10 14:46, Jed wrote: > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. My first attempt at the problem: >>> import re >>> special = ['ch', 'rr', 'll'] >>> r = re.compile(r'(?:%s)|[a-z]' % ('|'.join(re.escape(c) for c in special)), re.I) >>> r.findall('churro') ['ch', 'u', 'rr', 'o'] >>> [r.findall(word) for word in 'churro lorenzo caballo'.split()] [['ch', 'u', 'rr', 'o'], ['l', 'o', 'r', 'e', 'n', 'z', 'o'], ['c', 'a', 'b', 'a', 'll', 'o']] This joins escaped versions of all your special characters. Due to the sequential nature used by Python's re module to handle "|" or-branching, the paired versions get tested (and found) before proceeding to the single-letters. -tkc From zapwireDASHgroups at yahoo.com Wed Aug 25 16:24:52 2010 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 25 Aug 2010 13:24:52 -0700 Subject: Can PySerial's write method be called by multiple threads? References: <4c75768a$0$1608$742ec2ed@news.sonic.net> Message-ID: Hi John, "John Nagle" wrote in message news:4c75768a$0$1608$742ec2ed at news.sonic.net... > You don't need a queue, though; just use your own "write" function > with a lock. Hmm... that would certainly work. I suppose it's even more efficient than a queue in that the first thing the queue is going to do is to acquire a lock; thanks for the idea! > def atomicwrite(fd, data) : > with lok : > fd.write(data) Cool, I didn't know that threading.Lock() supported "with!" -- Just the other day I was contemplating how one might go about duplicating the pattern in C++ where you do something like this: { Lock lok; // Constructor acquires lock, will be held until destructor called (i.e., while lok remains in scope) DoSomething(); } // Lock released ...clearly "with" does the job here. ---Joel From alex.kapps at web.de Wed Aug 25 16:26:53 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Wed, 25 Aug 2010 22:26:53 +0200 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: <4C757C8D.3040208@web.de> Jed wrote: > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. My real application > is a bit more complex than the Spanish alphabet so I'm looking for a > fairly general solution. > Thanks, > Jed I don't know the Spanish alphabet, and you didn't say in what way your real application is more complex, but maybe something like this could be a starter: In [13]: import re In [14]: theword = 'churro' In [15]: two_chars=["ch", "rr"] In [16]: re.findall('|'.join(two_chars)+"|[a-z]", theword) Out[16]: ['ch', 'u', 'rr', 'o'] From john.passaniti at gmail.com Wed Aug 25 16:44:46 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Wed, 25 Aug 2010 13:44:46 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> Message-ID: <471f4b3f-5a95-432b-8d4b-4d18d0855f6c@h19g2000yqb.googlegroups.com> On Aug 24, 9:05?pm, Hugh Aguilar wrote: > What about using what I learned to write programs that work? > Does that count for anything? It obviously counts, but it's not the only thing that matters. Where I'm employed, I am currently managing a set of code that "works" but the quality of that code is poor. The previous programmer suffered from a bad case of cut-and-paste programming mixed with a unsophisticated use of the language. The result is that this code that "works" is a maintenance nightmare, has poor performance, wastes memory, and is very brittle. The high level of coupling between code means that when you change virtually anything, it invariably breaks something else. And then you have the issue of the programmer thinking the code "works" but it doesn't actually meet the needs of the customer. The same code I'm talking about has a feature where you can pass message over the network and have the value you pass configure a parameter. It "works" fine, but it's not what the customer wants. The customer wants to be able to bump the value up and down, not set it to an absolute value. So does the code "work"? Depends on the definition of "work." In my experience, there are a class of software developers who care only that their code "works" (or more likely, *appears* to work) and think that is the gold standard. It's an attitude that easy for hobbyists to take, but not one that serious professionals can afford to have. A hobbyist can freely spend hours hacking away and having a grand time writing code. Professionals are paid for their efforts, and that means that *someone* is spending both time and money on the effort. A professional who cares only about slamming out code that "works" is invariably merely moving the cost of maintaining and extending the code to someone else. It becomes a hidden cost, but why do they care... it isn't here and now, and probably won't be their problem. > If I don't have a professor to pat me on the back, will my > programs stop working? What a low bar you set for yourself. Does efficiency, clarity, maintainability, extensibility, and elegance not matter to you? From joshuamaurice at gmail.com Wed Aug 25 17:01:49 2010 From: joshuamaurice at gmail.com (Joshua Maurice) Date: Wed, 25 Aug 2010 14:01:49 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> <471f4b3f-5a95-432b-8d4b-4d18d0855f6c@h19g2000yqb.googlegroups.com> Message-ID: <1bc3a400-1631-454b-bdd6-54a58e172fd4@f20g2000pro.googlegroups.com> On Aug 25, 1:44?pm, John Passaniti wrote: > On Aug 24, 9:05?pm, Hugh Aguilar wrote: > > > What about using what I learned to write programs that work? > > Does that count for anything? > > It obviously counts, but it's not the only thing that matters. ?Where > I'm employed, I am currently managing a set of code that "works" but > the quality of that code is poor. ?The previous programmer suffered > from a bad case of cut-and-paste programming mixed with a > unsophisticated use of the language. ?The result is that this code > that "works" is a maintenance nightmare, has poor performance, wastes > memory, and is very brittle. ?The high level of coupling between code > means that when you change virtually anything, it invariably breaks > something else. > > And then you have the issue of the programmer thinking the code > "works" but it doesn't actually meet the needs of the customer. ?The > same code I'm talking about has a feature where you can pass message > over the network and have the value you pass configure a parameter. > It "works" fine, but it's not what the customer wants. ?The customer > wants to be able to bump the value up and down, not set it to an > absolute value. ?So does the code "work"? ?Depends on the definition > of "work." > > In my experience, there are a class of software developers who care > only that their code "works" (or more likely, *appears* to work) and > think that is the gold standard. ?It's an attitude that easy for > hobbyists to take, but not one that serious professionals can afford > to have. ?A hobbyist can freely spend hours hacking away and having a > grand time writing code. ?Professionals are paid for their efforts, > and that means that *someone* is spending both time and money on the > effort. ?A professional who cares only about slamming out code that > "works" is invariably merely moving the cost of maintaining and > extending the code to someone else. ?It becomes a hidden cost, but why > do they care... it isn't here and now, and probably won't be their > problem. I agree. Sadly, with managers, especially non-technical managers, it's hard to make this case when the weasel guy says "See! It's working.". From davea at ieee.org Wed Aug 25 17:05:27 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 25 Aug 2010 17:05:27 -0400 Subject: speed of numpy.power()? In-Reply-To: <8dl2r2F5h4U1@mid.individual.net> References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> <8dl2r2F5h4U1@mid.individual.net> Message-ID: <4C758597.2040507@ieee.org> Peter Pearson wrote: > On Wed, 25 Aug 2010 06:59:36 -0700 (PDT), Carlos Grohmann wrote: > > > >> I'd like to hear from you on the benefits of using numpy.power(x,y) >> over (x*x*x*x..) >> >> > > Using the "dis" package under Python 2.5, I see that > computing x_to_the_16 = x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x uses > 15 multiplies. I hope that numpy.power does it with 4. > > Right. Square/multiply algorithm takes something like 2*(log2(y)) multiplies worst case. That should not only be faster, but quite likely more accurate, at least for non-integer x values and large enough integer y. DaveA From rosswilliamson.spt at gmail.com Wed Aug 25 17:18:15 2010 From: rosswilliamson.spt at gmail.com (Ross Williamson) Date: Wed, 25 Aug 2010 16:18:15 -0500 Subject: Overload print Message-ID: Hi All Is there anyway in a class to overload the print function? >> class foo_class(): >> pass >> cc = foo_class() >> print cc Gives: <__main__.foo_class instance at ....> Can I do something like: >> class foo_class(): >> def __print__(self): >> print "hello" >> cc = foo_class() >> print cc Gives: hello I'm looking at finding nice way to print variables in a class just by asking to print it Cheers Ross -- Ross Williamson University of Chicago Department of Astronomy & Astrophysics 773-834-9785 (office) 312-504-3051 (Cell) From john at castleamber.com Wed Aug 25 17:19:33 2010 From: john at castleamber.com (John Bokma) Date: Wed, 25 Aug 2010 16:19:33 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> <81e52218-b72c-4b7c-aed6-82e040803064@s9g2000yqd.googlegroups.com> Message-ID: <87pqx6z8yi.fsf@castleamber.com> John Passaniti writes: > On Aug 24, 8:00?pm, Hugh Aguilar wrote: >> The C programmers reading this are likely wondering why I'm being >> attacked. The reason is that Elizabeth Rather has made it clear to >> everybody that this is what she wants: [http://tinyurl.com/2bjwp7q] > > Hello to those outside of comp.lang.forth, where Hugh usually leaves > his slime trail. I seriously doubt many people will bother to read > the message thread Hugh references, but if you do, you'll get to > delight in the same nonsense Hugh has brought to comp.lang.forth. > Here's the compressed version: I did :-). I have somewhat followed Forth from a far, far distance since the 80's (including hardware), and did read several messages in the thread, also since it was not clear what Hugh was referring to. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From zondo42 at gmail.com Wed Aug 25 17:23:41 2010 From: zondo42 at gmail.com (Glenn Hutchings) Date: Wed, 25 Aug 2010 14:23:41 -0700 (PDT) Subject: Overload print References: mailman.44.1282771124.29448.python-list@python.org Message-ID: <3aa21cb0-1787-47f9-b674-d79c3632b92d@q22g2000yqm.googlegroups.com> On 25 Aug, 22:18, Ross Williamson wrote: > Is there anyway in a class to overload the print function? > > >> class foo_class(): > >> ? ? ?pass > >> cc = foo_class() > >> print cc > > Gives: > > <__main__.foo_class instance at ....> > > Can I do something like: > > >> class foo_class(): > >> ? ? def __print__(self): > >> ? ? ? ? ? print "hello" > >> cc = foo_class() > >> print cc > > Gives: > > hello Yes. Just define the __str__ method, like this: class foo_class(): def __str__(self): return "hello" From chris at rebertia.com Wed Aug 25 17:32:25 2010 From: chris at rebertia.com (Chris Rebert) Date: Wed, 25 Aug 2010 14:32:25 -0700 Subject: Overload print In-Reply-To: References: Message-ID: On Wed, Aug 25, 2010 at 2:18 PM, Ross Williamson wrote: > Hi All > > Is there anyway in a class to overload the print function? > >>> class foo_class(): >>> ? ? ?pass > >>> cc = foo_class() >>> print cc > > Gives: > > <__main__.foo_class instance at ....> > > Can I do something like: > >>> class foo_class(): >>> ? ? def __print__(self): >>> ? ? ? ? ? print "hello" > >>> cc = foo_class() >>> print cc > > Gives: > > hello > > I'm looking at finding nice way to print variables in a class just by > asking to print it You want to overload the __str__() method: http://docs.python.org/reference/datamodel.html#object.__str__ Cheers, Chris -- http://blog.rebertia.com From darcy at druid.net Wed Aug 25 17:39:58 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 25 Aug 2010 17:39:58 -0400 Subject: Overload print In-Reply-To: References: Message-ID: <20100825173958.c3c5f63f.darcy@druid.net> On Wed, 25 Aug 2010 16:18:15 -0500 Ross Williamson wrote: > Hi All > > Is there anyway in a class to overload the print function? Your terminology threw me off for a moment. You don't want to override print. You want to override the default representation of an object. > > >> class foo_class(): > >> pass > > >> cc = foo_class() > >> print cc > > Gives: > > <__main__.foo_class instance at ....> That's the default representation. > Can I do something like: > > >> class foo_class(): > >> def __print__(self): > >> print "hello" Close. Check this. >>> class foo_class(): ... def __repr__(self): ... return "hello" ... >>> x = foo_class() >>> x hello -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From alex.kapps at web.de Wed Aug 25 17:42:42 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Wed, 25 Aug 2010 23:42:42 +0200 Subject: Overload print In-Reply-To: References: Message-ID: <4C758E52.3090107@web.de> Ross Williamson wrote: > Hi All > > Is there anyway in a class to overload the print function? In Python <= 2.x "print" is a statement and thus can't be "overloaded". That's exactly the reason, why Python 3 has turned "print" into a function. >>> class foo_class(): >>> def __print__(self): >>> print "hello" > >>> cc = foo_class() >>> print cc > > Gives: > > hello Hmm, on what Python version are you? To my knowledge there is no __print__ special method. Did you mean __str__ or __repr__ ? > I'm looking at finding nice way to print variables in a class just by > asking to print it In Python3 you *can* overload print(), but still, you better define __str__() on your class to return a string, representing what ever you want: In [11]: class Foo(object): ....: def __str__(self): ....: return "foo" ....: ....: In [12]: f = Foo() In [13]: print f foo From ckaynor at zindagigames.com Wed Aug 25 17:43:51 2010 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 25 Aug 2010 14:43:51 -0700 Subject: Overload print In-Reply-To: <3aa21cb0-1787-47f9-b674-d79c3632b92d@q22g2000yqm.googlegroups.com> References: <3aa21cb0-1787-47f9-b674-d79c3632b92d@q22g2000yqm.googlegroups.com> Message-ID: On Wed, Aug 25, 2010 at 2:23 PM, Glenn Hutchings wrote: > On 25 Aug, 22:18, Ross Williamson > wrote: > > Is there anyway in a class to overload the print function? > > > > >> class foo_class(): > > >> pass > > >> cc = foo_class() > > >> print cc > > > > Gives: > > > > <__main__.foo_class instance at ....> > > > > Can I do something like: > > > > >> class foo_class(): > > >> def __print__(self): > > >> print "hello" > > >> cc = foo_class() > > >> print cc > > > > Gives: > > > > hello > > Yes. Just define the __str__ method, like this: > > class foo_class(): > def __str__(self): > return "hello" > -- > http://mail.python.org/mailman/listinfo/python-list > I'd recommend looking at both the __str__ and __repr__ functions at http://docs.python.org/reference/datamodel.html. Depending on your specific use case, its possible __repr__ may be perfered for you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rda.selin at gmail.com Wed Aug 25 17:57:33 2010 From: rda.selin at gmail.com (becky_s) Date: Wed, 25 Aug 2010 14:57:33 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) Message-ID: All, I?m having a problem with the matplotlib.pyplot.contourf function. I have a 1-D array of latitudes (mesolat), a 1-D array of longitudes (mesolon), and a 1-D array of rainfall values (rain) at those corresponding lat, lon points. After importing the necessary libraries, and reading in these 1-D arrays, I do the following commands: p = Basemap(projection='lcc',llcrnrlon=-108.173,llcrnrlat=26.809999, urcrnrlon=-81.944664,urcrnrlat=45.730892, lon_0=-97.00, lat_0=37.00, resolution='i') px,py = p(mesolon, mesolat) prplvls = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] crain = p.contourf(px,py,rain,prplvls) At this point the contourf function returns an error saying ?Input z must be a 2D array.? However, based on the documentation (http:// matplotlib.sourceforge.net/api/ pyplot_api.html#matplotlib.pyplot.contourf) I thought that as long as px, py, and rain are the same dimensions, everything should be fine. Apparently that is not the case? If 1D arrays are not allowed in contourf, then how can I change my data into a 2D array? Thanks in advance for the help. From rda.selin at gmail.com Wed Aug 25 18:17:43 2010 From: rda.selin at gmail.com (becky_s) Date: Wed, 25 Aug 2010 15:17:43 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) References: Message-ID: <2a415d82-c631-42ad-a96d-917d0b3ee17f@d8g2000yqf.googlegroups.com> On Aug 25, 4:57?pm, becky_s wrote: > All, > > I?m having a problem with the matplotlib.pyplot.contourf function. ?I > have a 1-D array of latitudes (mesolat), a 1-D array of longitudes > (mesolon), and a 1-D array of rainfall values (rain) at those > corresponding lat, lon points. ?After importing the necessary > libraries, and reading in these 1-D arrays, I do the following > commands: > > p = Basemap(projection='lcc',llcrnrlon=-108.173,llcrnrlat=26.809999, > ? ? ? ? ? ? urcrnrlon=-81.944664,urcrnrlat=45.730892, > ? ? ? ? ? ? lon_0=-97.00, lat_0=37.00, resolution='i') > > px,py = p(mesolon, mesolat) > > prplvls = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] > > crain = p.contourf(px,py,rain,prplvls) > > At this point the contourf function returns an error saying ?Input z > must be a 2D array.? ?However, based on the documentation (http:// > matplotlib.sourceforge.net/api/ > pyplot_api.html#matplotlib.pyplot.contourf) I thought that as long as > px, py, and rain are the same dimensions, everything should be fine. > Apparently that is not the case? ?If 1D arrays are not allowed in > contourf, then how can I change my data into a 2D array? > > Thanks in advance for the help. I neglected to mention that these are masked arrays, due to some missing data. I tried using numpy.griddata: mesolati = np.linspace(33.8,37.0,150) mesoloni = np.linspace(-94.5,-102.9,150) raini = griddata(mesolon,mesolat,rain,mesoloni,mesolati) but the raini array returned was entirely masked (no values). Thanks again, Becky From john.passaniti at gmail.com Wed Aug 25 19:01:07 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Wed, 25 Aug 2010 16:01:07 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> <471f4b3f-5a95-432b-8d4b-4d18d0855f6c@h19g2000yqb.googlegroups.com> <1bc3a400-1631-454b-bdd6-54a58e172fd4@f20g2000pro.googlegroups.com> Message-ID: <22c66313-bf7c-4999-9d3e-02d9695fdc38@x21g2000yqa.googlegroups.com> On Aug 25, 5:01?pm, Joshua Maurice wrote: > I agree. Sadly, with managers, especially non-technical > managers, it's hard to make this case when the weasel > guy says "See! It's working.". Actually, it's not that hard. The key to communicating the true cost of software development to non-technical managers (and even some technical ones!) is to express the cost in terms of a metaphor they can understand. Non-technical managers may not understand the technology or details of software development, but they can probably understand money. So finding a metaphor along those lines can help them to understand. http://c2.com/cgi/wiki?WardExplainsDebtMetaphor I've found that explaining the need to improve design and code quality in terms of a debt metaphor usually helps non-technical managers have a very real, very concrete understanding of the problem. For example, telling a non-technical manager that a piece of code is poorly written and needs to be refactored may not resonate with them. To them, the code "works" and isn't that the only thing that matters? But put in terms of a debt metaphor, it becomes easier for them to see the problem. From nanothermite911fbibustards at gmail.com Wed Aug 25 19:44:12 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 16:44:12 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria - Re: GERMAN GIRLS HOT SEX VIDEOS. - I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post References: <968e144b-b230-4b60-ae2a-f3c1dc2f8573@v6g2000prd.googlegroups.com> Message-ID: <78f2b6a1-8c0f-42c0-9461-9c7e5d7d7003@q1g2000yqg.googlegroups.com> I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post ///////////////////////////////////////////////////////////////////////////////////// CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post On Aug 14, 6:07?am, Hot Hot wrote: > GERMAN GIRLS ?HOT SEX VIDEOS Athttp://simpletoget.co.cc > > Due to high sex content, i have hidden the videos in an image.in that > website on Right side ?below search box click on image and watch > videos in all angles. From joshuamaurice at gmail.com Wed Aug 25 20:06:38 2010 From: joshuamaurice at gmail.com (Joshua Maurice) Date: Wed, 25 Aug 2010 17:06:38 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> <471f4b3f-5a95-432b-8d4b-4d18d0855f6c@h19g2000yqb.googlegroups.com> <1bc3a400-1631-454b-bdd6-54a58e172fd4@f20g2000pro.googlegroups.com> <22c66313-bf7c-4999-9d3e-02d9695fdc38@x21g2000yqa.googlegroups.com> Message-ID: <59dafb50-0c98-4bdc-915e-fc99501d3399@u31g2000pru.googlegroups.com> On Aug 25, 4:01?pm, John Passaniti wrote: > On Aug 25, 5:01?pm, Joshua Maurice wrote: > > > I agree. Sadly, with managers, especially non-technical > > managers, it's hard to make this case when the weasel > > guy says "See! It's working.". > > Actually, it's not that hard. ?The key to communicating the true cost > of software development to non-technical managers (and even some > technical ones!) is to express the cost in terms of a metaphor they > can understand. ?Non-technical managers may not understand the > technology or details of software development, but they can probably > understand money. ?So finding a metaphor along those lines can help > them to understand. > > http://c2.com/cgi/wiki?WardExplainsDebtMetaphor > > I've found that explaining the need to improve design and code quality > in terms of a debt metaphor usually helps non-technical managers have > a very real, very concrete understanding of the problem. ?For example, > telling a non-technical manager that a piece of code is poorly written > and needs to be refactored may not resonate with them. ?To them, the > code "works" and isn't that the only thing that matters? ?But put in > terms of a debt metaphor, it becomes easier for them to see the > problem. But then it becomes a game of "How bad is this code exactly?" and "How much technical debt have we accrued?". At least in my company's culture, it is quite hard. From tjreedy at udel.edu Wed Aug 25 20:15:31 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Aug 2010 20:15:31 -0400 Subject: split string into multi-character "letters" In-Reply-To: <4C757A72.7020404@tim.thechases.com> References: <4C757A72.7020404@tim.thechases.com> Message-ID: > On 08/25/10 14:46, Jed wrote: >> I would like to split the string 'churro' into a list containing: >> >> 'ch','u','rr','o' Dirt simple, straightforward, easily generalized solution: def sp_split(s): n,i,ret = len(s), 0, [] while i < n: s2 = s[i:i+2] if s2 in ('ch', 'll', 'rr'): ret.append(s2) i += 2 else: ret.append(s[i]) i += 1 return ret print(sp_split('churro')) #'ch', 'u', 'rr', 'o'] -- Terry Jan Reedy From skippy.hammond at gmail.com Wed Aug 25 21:08:11 2010 From: skippy.hammond at gmail.com (Mark Hammond) Date: Thu, 26 Aug 2010 11:08:11 +1000 Subject: Newbie: Win32 COM problem In-Reply-To: References: Message-ID: <4C75BE7B.1030305@gmail.com> On 25/08/2010 10:33 PM, Paul Hemans wrote: > File "C:\development\PyXLS\pyXLS.py", line 13, in createSheet > def createBook(self): > AttributeError: WrapXLS instance has no attribute '_book' > pythoncom error: Python error invoking COM method. > > Can anyone help? That line seems an unlikely source of the error. Note that as win32com uses an in-process model by default, your problem may be that you changed your implementation but didn't restart the hosting process - and therefore are still using an earlier implementation. HTH, Mark From darwin at nowhere.com Wed Aug 25 22:17:40 2010 From: darwin at nowhere.com (Paul Hemans) Date: Thu, 26 Aug 2010 12:17:40 +1000 Subject: Newbie: Win32 COM problem References: Message-ID: Yes, that was it. I just needed to restart the host process. Thanks "Mark Hammond" wrote in message news:mailman.51.1282784920.29448.python-list at python.org... > On 25/08/2010 10:33 PM, Paul Hemans wrote: >> File "C:\development\PyXLS\pyXLS.py", line 13, in createSheet >> def createBook(self): >> AttributeError: WrapXLS instance has no attribute '_book' >> pythoncom error: Python error invoking COM method. >> >> Can anyone help? > > That line seems an unlikely source of the error. Note that as win32com > uses an in-process model by default, your problem may be that you changed > your implementation but didn't restart the hosting process - and therefore > are still using an earlier implementation. > > HTH, > > Mark From nanothermite911fbibustards at gmail.com Wed Aug 25 23:11:14 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 20:11:14 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - Re: GERMAN GIRLS HOT SEX VIDEOS. - I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post References: <968e144b-b230-4b60-ae2a-f3c1dc2f8573@v6g2000prd.googlegroups.com> Message-ID: I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post ///////////////////////////////////////////////////////////////////////////?////////// CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxkhttp://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news :http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA --http://mail.python.org/mailman/listinfo/python-list I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post On Aug 14, 6:07 am, Hot Hot wrote: > GERMAN GIRLS HOT SEX VIDEOS Athttp://simpletoget.co.cc > Due to high sex content, i have hidden the videos in an image.in that > website on Right side below search box click on image and watch > videos in all angles.- Hide quoted text - From nanothermite911fbibustards at gmail.com Thu Aug 26 00:22:31 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 21:22:31 -0700 (PDT) Subject: OBAMA created by the CIA - Proofs by Wayne Madsen, the Investigative Journalist - Obama's StepMother Ruth Niedesand and two StepBrothers are JEW References: <0f2ba00f-2589-44fb-acb6-ea8b693677b7@d8g2000yqf.googlegroups.com> <87aaoaxtyu.fsf@kuiper.lan.informatimago.com> <4c75e310$0$7111$607ed4bc@cv.net> Message-ID: <01c5fea9-264f-48ff-b076-5d3b459fd6c5@t20g2000yqa.googlegroups.com> OBAMA created by the CIA - Proofs by Wayne Madsen, the Investigative Journalist - Obama's StepMother Ruth Niedesand and two StepBrothers are JEW OBAMA family are CIA agents or employees http://www.presstv.ir/detail/140093.html http://www.voltairenet.org/article166741.html Special Report The Story of Obama: All in The Company (Part I) by Wayne Madsen* Investigative journalist Wayne Madsen has discovered CIA files that document the agency?s connections to institutions and individuals figuring prominently in the lives of Barack Obama and his mother, father, grandmother, and stepfather. The first part of his report highlights the connections between Barack Obama, Sr. and the CIA- sponsored operations in Kenya to counter rising Soviet and Chinese influence among student circles and, beyond, to create conditions obstructing the emergence of independent African leaders. -------------------------------------------------------------------------------- 20 August 2010 From Washington D.C. (USA) Themes AfriCom: Control of Africa Biographies Barack Obama In 1983-84, Barack Obama worked as Editor at Business Internation Corporation, a Business International Corporation, a known CIA front company. President Obama?s own work in 1983 for Business International Corporation, a CIA front that conducted seminars with the world?s most powerful leaders and used journalists as agents abroad, dovetails with CIA espionage activities conducted by his mother, Stanley Ann Dunham in 1960s post-coup Indonesia on behalf of a number of CIA front operations, including the East-West Center at the University of Hawaii, the U.S. Agency for International Development (USAID), and the Ford Foundation. Dunham met and married Lolo Soetoro, Obama?s stepfather, at the East-West Center in 1965. Soetoro was recalled to Indonesia in 1965 to serve as a senior army officer and assist General Suharto and the CIA in the bloody overthrow of President Sukarno. Barack Obama, Sr., who met Dunham in 1959 in a Russian language class at the University of Hawaii, had been part of what was described as an airlift of 280 East African students to the United States to attend various colleges ? merely ?aided? by a grant from the Joseph P. Kennedy Foundation, according to a September 12, 1960, Reuters report from London. The airlift was a CIA operation to train and indoctrinate future agents of influence in Africa, which was becoming a battleground between the United States and the Soviet Union and China for influence among newly-independent and soon-to-be independent countries on the continent. The airlift was condemned by the deputy leader of the opposition Kenyan African Democratic Union (KADU) as favoring certain tribes ? the majority Kikuyus and minority Luos ? over other tribes to favor the Kenyan African National Union (KANU), whose leader was Tom Mboya, the Kenyan nationalist and labor leader who selected Obama, Sr. for a scholarship at the University of Hawaii. Obama, Sr., who was already married with an infant son and pregnant wife in Kenya, married Dunham on Maui on February 2, 1961 and was also the university?s first African student. Dunham was three month?s pregnant with Barack Obama, Jr. at the time of her marriage to Obama, Sr. KADU deputy leader Masinda Muliro, according to Reuters, said KADU would send a delegation to the United States to investigate Kenyan students who received ?gifts? from the Americans and ?ensure that further gifts to Kenyan students are administered by people genuinely interested in Kenya?s development.?? The CIA allegedly recruited Tom M?Boya in a heavily funded "selective liberation" programme to isolate Kenya?s founding President Jomo Kenyatta, whom the American spy agency labelled as "unsafe." Mboya received a $100,000 grant for the airlift from the Kennedy Foundation after he turned down the same offer from the U.S. State Department, obviously concerned that direct U.S. assistance would look suspicious to pro-Communist Kenyan politicians who suspected Mboya of having CIA ties. The Airlift Africa project was underwritten by the Kennedy Foundation and the African-American Students Foundation. Obama, Sr. was not on the first airlift but a subsequent one. The airlift, organized by Mboya in 1959, included students from Kenya, Uganda, Tanganyika, Zanzibar, Northern Rhodesia, Southern Rhodesia, and Nyasaland. Reuters also reported that Muliro charged that Africans were ?disturbed and embittered? by the airlift of the selected students. Muliro ?stated that ?preferences were shown to two major tribes [Kikuyu and Luo] and many U.S.-bound students had failed preliminary and common entrance examinations, while some of those left behind held first-class certificates.? CIA-airlifted to Hawaii, Barack Obama Sr., with leis, stands with Stanley Dunham, President Obama?s grandfather, on his right. Obama, Sr. was a friend of Mboya and a fellow Luo. After Mboya was assassinated in 1969, Obama, Sr. testified at the trial of his alleged assassin. Obama, Sr. claimed he was the target of a hit-and-run assassination attempt after his testimony. Obama, Sr., who left Hawaii for Harvard in 1962, divorced Dunham in 1964. Obama, Sr. married a fellow Harvard student, Ruth Niedesand, a Jewish-American woman, who moved with him to Kenya and had two sons. They were later divorced. Obama, Sr. worked for the Kenyan Finance and Transport ministries as well as an oil firm. Obama, Sr. died in a 1982 car crash and his funeral was attended by leading Kenyan politicians, including future Foreign Minister Robert Ouko, who was murdered in 1990. CIA files indicate that Mboya was an important agent-of-influence for the CIA, not only in Kenya but in all of Africa. A formerly Secret CIA Current Intelligence Weekly Summary, dated November 19, 1959, states that Mboya served as a check on extremists at the second All-African People?s Conference (AAPC) in Tunis. The report states that ?serious friction developed between Ghana?s Prime Minister Kwame Nkrumah and Kenyan nationalist Tom Mboya who cooperated effectively last December to check extremists at the AAPC?s first meeting in Accra.? The term ?cooperated effectively? appears to indicate that Mboya was cooperating with the CIA, which filed the report from field operatives in Accra and Tunis. While ?cooperating? with the CIA in Accra and Tunis, Mboya selected the father of the president of the United States to receive a scholarship and be airlifted to the University of Hawaii where he met and married President Obama?s mother. An earlier CIA Current Intelligence Weekly Summary, secret, and dated April 3, 1958, states that Mboya ?still appears to be the most promising of the African leaders.? Another CIA weekly summary, secret and dated December 18, 1958, calls Mboya the Kenyan nationalist an ?able and dynamic young chairman? of the People?s Convention party who was viewed as an opponent of ?extremists? like Nkrumah, supported by ?Sino-Soviet representatives.? In a formerly Secret CIA report on the All-Africa Peoples Conference in 1961, dated November 1, 1961, Mboya?s conservatism, along with that of Taleb Slim of Tunisia, are contrasted to the leftist policies of Nkrumah and others. Pro-communists who were elected to the AAPC?s steering committee at the March 1961 Cairo conference, attended by Mboya, are identified in the report as Abdoulaye Diallo, AAPC Secretary General, of Senegal; Ahmed Bourmendjel of Algeria; Mario de Andrade of Angola; Ntau Mokhele of Basutoland; Kingue Abel of Cameroun; Antoine Kiwewa of Congo (Leopoldville); Kojo Botsio of Ghana; Ismail Toure of Guinea; T. O. Dosomu Johnson of Liberia; Modibo Diallo of Mali; Mahjoub Ben Seddik of Morocco; Djibo Bakari of Niger; Tunji Otegbeya of Nigeria; Kanyama Chiume of Nyasaland; Ali Abdullahi of Somalia; Tennyson Makiwane of South Africa, and Mohamed Fouad Galal of the United Arab Republic. The only attendees in Cairo who were given a clean bill of health by the CIA were Mboya, who appears to have been a snitch for the agency, and Joshua Nkomo of Southern Rhodesia, B. Munanka of Tanganyika, Abdel Magid Shaker of Tunisia, and John Kakonge of Uganda. Nkrumah would eventually be overthrown in a 1966 CIA-backed coup while he was on a state visit to China and North Vietnam. The CIA overthrow of Nkrumah followed by one year the agency?s overthrow of Sukarno, another coup that was connected to President Obama?s family on his mother?s side. There are suspicions that Mboya was assassinated in 1969 by Chinese agents working with anti-Mboya factions in the government of Kenyan President Jomo Kenyatta in order to eliminate a pro-U.S. leading political leader in Africa. Upon Mboya?s death, every embassy in Nairobi flew its flag at half-mast except for one, the embassy of the People?s Republic of China. Jomo Kenyatta, first President of Kenya. Mboya?s influence in the Kenyatta government would continue long after his death and while Obama, Sr. was still alive. In 1975, after the assassination of KANU politician Josiah Kariuki, a socialist who helped start KANU, along with Mboya and Obama, Sr., Kenyatta dismissed three rebellious cabinet ministers who ?all had personal ties to either Kariuki or Tom Mboya.? This information is contained in CIA Staff Notes on the Middle East, Africa, and South Asia, formerly Top Secret Umbra, Handle via COMINT Channels, dated June 24, 1975. The intelligence in the report, based on its classification, indicate the information was derived from National Security Agency intercepts in Kenya. No one was ever charged in the assassination of Kariuki. The intecepts of Mboya?s and Kariuki?s associates are an indication that the NSA and CIA also maintain intercepts on Barack Obama, Sr., who, as a non-U.S. person, would have been lawfully subject at the time to intercepts carried out by NSA and Britain?s Government Communications Headquarters (GCHQ). (To be continued) == Article concerning Barack Obama?s own meddling in Kenya?s domestic affairs: "Behind the 2009 Nobel Peace Prize", by Thierry Meyssan, Voltaire Network, 19 October 2009. From python.koda at gmail.com Thu Aug 26 00:29:28 2010 From: python.koda at gmail.com (Alban Nona) Date: Thu, 26 Aug 2010 00:29:28 -0400 Subject: Path / Listing and os.walk problem. Message-ID: Hi So here is my problem: I have my render files that are into a directory like this: c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0001.exr c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0002.exr c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0003.exr .... c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0001.exr c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0002.exr c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0003.exr True is, there is like 1000 Files is the directory (C:\log\renderfiles\) What Iam looking to is to extract the first part of the filenames as a list, but I dont want the script to extract it 1000times, I mean I dont need it to extract HPO7_SEQ004_031_VDM_AMB 150 times, because there is 150 Frames. (not sure if its clear tought) so far, I would like the list to look lik: ["HPO7_SEQ004_031_VDM_DIF", "HPO7_SEQ004_031_VDM_AMB", etc...] I start to think about that, to try to use a for (path, dirs, files) in os.walk(path): list.append(files) but this kind of thing will just append the whole 1000 files, thing that I dont want, and more complicated I dont want the thing after "AMB" or "DIF" in the name files to follow. (thing I can delete using a split, if I read well ?) I trying to search on internet for answer, but seems I find nothing about it. Someone can help me with that please, show me the way or something ? Thank you ! :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Aug 26 03:54:13 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Aug 2010 09:54:13 +0200 Subject: Path / Listing and os.walk problem. References: Message-ID: Alban Nona wrote: > Hi > > So here is my problem: > > I have my render files that are into a directory like this: > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0001.exr > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0002.exr > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0003.exr > .... > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0001.exr > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0002.exr > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0003.exr > > True is, there is like 1000 Files is the directory (C:\log\renderfiles\) > > What Iam looking to is to extract the first part of the filenames as a > list, but I dont want the script to extract it 1000times, I mean I dont > need it to extract HPO7_SEQ004_031_VDM_AMB 150 times, because there is 150 > Frames. (not sure if its clear tought) > > so far, I would like the list to look lik: > > ["HPO7_SEQ004_031_VDM_DIF", "HPO7_SEQ004_031_VDM_AMB", etc...] > > > I start to think about that, to try to use a > > for (path, dirs, files) in os.walk(path): > list.append(files) > > > but this kind of thing will just append the whole 1000 files, thing that I > dont want, and more complicated I dont want the thing after "AMB" or "DIF" > in the name files to follow. > (thing I can delete using a split, if I read well ?) > > > I trying to search on internet for answer, but seems I find nothing about > it. > Someone can help me with that please, show me the way or something ? You can use glob. Assuming the files are all in one directory: import os import glob folder = r"C:\log\renderfiles" # find files that end with "_V001.0001.exr" pattern = os.path.join(folder, "*_V001.0001.exr") files = glob.glob(pattern) # remove the directory names = [os.path.basename(f) for f in files] # remove everything after and including the last occurence of "_" names = [n.rpartition("_")[0] for n in names] print "\n".join(sorted(names)) Peter From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 26 04:19:25 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 26 Aug 2010 10:19:25 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com><4c6dcbc5$0$11111$c3e8da3@news.astraweb.com><4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4c762382$0$20848$426a34cc@news.free.fr> BartC a ?crit : > "Steven D'Aprano" wrote in > message news:4c6f8edd$0$28653$c3e8da3 at news.astraweb.com... >> On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: > >>> I onced worked in a shop (Win32 desktop / accouting applications mainly) >>> where I was the only guy that could actually understand recursion. FWIW, >>> I also was the only guy around that understood "hairy" (lol) concepts >>> like callback functions, FSM, polymorphism, hashtables, linked lists, >>> ADTs, algorithm complexity etc... >> >> >> Was there anything they *did* understand, or did they just bang on the >> keyboard at random until the code compiled? *wink* > > You underestimate how much programming (of applications) can be done > without needing any of this stuff. From personal experience : almost nothing worth being maintained. I'm talking about complex domain-specific applications here - not shell scripts or todo-lists. >>> Needless to say, I didn't last long !-) >> >> And rightly so :) > > I guess they wanted code that could be maintained by anybody. The code base was an unmaintainable, undecip?erable mess loaded with global state (litteraly *hundreds* of global variables), duplication, dead code, and enough WTF to supply thedailywtf.com for years - to make a long story short, the perfect BigBallOfMudd. FWIW, the company didn't last long neither - they just kept on introducing ten new bugs each time they "fixed" one. From navkirats at gmail.com Thu Aug 26 04:35:16 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 26 Aug 2010 14:05:16 +0530 Subject: Webcam support Message-ID: <2E90C179-B58D-44E6-9779-FA072BF220C5@gmail.com> Hi Guys, I am programming a web centric app in python for customer, which needs to click a snap of the customer and forward the pic to the server via POST. I am not very familiar with how I can achieve this. Any direction would be much appreciated. Regards, Nav From sathish at solitontech.com Thu Aug 26 05:59:47 2010 From: sathish at solitontech.com (Sathish S) Date: Thu, 26 Aug 2010 15:29:47 +0530 Subject: Python Editor or IDE ActiveX control Message-ID: Hi Ppl, Is there any python IDE or editor that has an ActiveX control which could be embed in other Windows applications. I'm basically looking to write a application that can show the indentations of python, change the color of keywords etc on a application, which will save this python script and run it from command prompt. Thanks, Sathish -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Thu Aug 26 06:34:30 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 26 Aug 2010 03:34:30 -0700 Subject: Webcam support In-Reply-To: <2E90C179-B58D-44E6-9779-FA072BF220C5@gmail.com> References: <2E90C179-B58D-44E6-9779-FA072BF220C5@gmail.com> Message-ID: On Thu, Aug 26, 2010 at 1:35 AM, Navkirat Singh wrote: > Hi Guys, > > I am programming a web centric app in python for customer, which needs to click a snap of the customer and forward the pic to the server via POST. I am not very familiar with how I can achieve this. Any direction would be much appreciated. I think Flash (*shudder*) has some sort of webcam API. Cheers, Chris -- http://blog.rebertia.com From richie8105 at gmail.com Thu Aug 26 07:02:35 2010 From: richie8105 at gmail.com (richie05 bal) Date: Thu, 26 Aug 2010 04:02:35 -0700 (PDT) Subject: seach for pattern based on string References: <6054e266-4730-411e-9a27-9b501e6086cd@j8g2000yqd.googlegroups.com> Message-ID: <673b629a-9072-44a8-aa8a-970ac4c84711@l20g2000yqm.googlegroups.com> On Aug 24, 11:05?pm, Alex Willmer wrote: > On Aug 24, 5:33?pm, richie05 bal wrote: > > > i am starting to learn python and I am stuck with query I want to > > generate with python > > File looks something like this > > TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, > > publishingCompanyId 7} > > TRACE: AddNewBookD {bookId 21, noofBooks 6577, authorId 42, > > publishingCompanyId 8} > > > I want to first search for AddNewBookD > > if found > > ? ?store bookId, noofBooks, authorId and publishingCompanyId > > > I know how to search for only AddNewBookD or find the pattern bookId > > 20, noofBooks 6576, authorId 41, publishingCompanyId 7 but I don't > > know how search one based on another. > > Using a regular expression I would perform a match against each line. > If the match fails, it will return None. If the match succeeds it > returns a match object with which you can extract the values > > >>> import re > >>> pattern = re.compile(r'TRACE: AddNewBookD \{bookId (\d+), noofBooks (\d+), authorId (\d+), publishingCompanyId (\d+)\}\s*') > >>> s = '''TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, publishingCompanyId 7} ''' > >>> pattern.match(s) > > <_sre.SRE_Match object at 0xa362f40> # If the match failed this would > be None>>> m = pattern.match(s) > >>> m.groups() > > ('20', '6576', '41', '7') > > > > So your code to store the result would be inside an if m: block > > HTH, Alex thanks Alex. exactly what i was looking for. From stephan0h at yahoo.de Thu Aug 26 07:16:51 2010 From: stephan0h at yahoo.de (steph) Date: Thu, 26 Aug 2010 04:16:51 -0700 (PDT) Subject: pil and reportlab: image compression Message-ID: <0e89301b-2cb3-42fe-ba24-4018b5343c4d@v41g2000yqv.googlegroups.com> Hi group, I've written a small application that puts images into a pdf document. It works ok, but my problem is that the pdf-files become quite huge, bigger than the original jpegs. The problem seems to arise because I use PIL to resize the pictures - and the images seem to get uncompressed in the process. Unfortunately I have not found a way to compress them again before rendering them to the pdf. Any clues? Thanks, Stephan From jeeva235 at hotmail.com Thu Aug 26 07:36:19 2010 From: jeeva235 at hotmail.com (superman) Date: Thu, 26 Aug 2010 04:36:19 -0700 (PDT) Subject: HOW TO MAKE $2000 IN YOUR WEEKEND NO INVESTMENT Message-ID: HOW TO MAKE $2000 IN YOUR WEEKEND NO INVESTMENT Great way to earn $$$ from online. Earn $100 everyday from online part time jobs. Last week i have earned $800 from this money making network. It is a free money making network Lot of people earn more than $2000 p/m from this network. Just join this network and start working today & Get paid to your bank account http://alturl.com/z9cz7 EARN AWESOME EARNINGS FROM ONLINE From chris at simplistix.co.uk Thu Aug 26 08:51:15 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 26 Aug 2010 13:51:15 +0100 Subject: bug? pkgutil.walk_packages returns packages that result in an ImportError Message-ID: <4C766343.1080908@simplistix.co.uk> Hi All, From the docs of pkgutils.walk_packages: """ 'onerror' is a function which gets called with one argument (the name of the package which was being imported) if any exception occurs while trying to import a package. If no onerror function is supplied, ImportErrors are caught and ignored, while all other exceptions are propagated, terminating the search. """ My expectation of this is that if onerrors is left as None, names yielded will be importable. However, because the yield is before the import check, you can get packages returned that are not importable. This feels at odds with the docs above and I think is a bug. If the yield were dropped to befoer the import check, we wouldn't have this problem. what do others think? cheers, Chris From rda.selin at gmail.com Thu Aug 26 08:58:14 2010 From: rda.selin at gmail.com (becky_s) Date: Thu, 26 Aug 2010 05:58:14 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) References: Message-ID: <2aa0205a-bb19-4265-a0ac-cd87445b7e0e@i13g2000yqd.googlegroups.com> On Aug 26, 1:52?am, Dennis Lee Bieber wrote: > On Wed, 25 Aug 2010 14:57:33 -0700 (PDT), becky_s > declaimed the following in gmane.comp.python.general: > > > > > px,py = p(mesolon, mesolat) > > ? ? ? ? For my elucidation, what does that ? ? ?p(x,y) ?actually do? Especially > as you appear to expect the result to be split into separate x and y > afterwards? I can't find it defined in either matplotlib nor numpy. p was declared as a basemap object in the previous statement, which sets up a map projection. Calling p(mesolon, mesolat) converts those lons, lats to units in that map projection and stores them in px,py. (See http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html for more info on basemap.) > > > pyplot_api.html#matplotlib.pyplot.contourf) I thought that as long as > > px, py, and rain are the same dimensions, everything should be fine. > > ? ? ? ? And are they? You don't demonstrate that you've checked for that I did a simple print px.shape, rain.shape, etc. to check. They are all size (135,). > > > Apparently that is not the case? ?If 1D arrays are not allowed in > > contourf, then how can I change my data into a 2D array? > > ? ? ? ? Also note (jumping to your follow up) that contourf is described as > having a potential problem with masked arrays (whatever those are) for > "Z" My problem isn't with the masked arrays as much as it is with rain being a 1D array. IDL can handle contouring 1D arrays with missing variables lickety-split, so I was really hoping Python could as well. Also, numpy.ma is the masked array library. See http://docs.scipy.org/doc/numpy/reference/routines.ma.html. From rda.selin at gmail.com Thu Aug 26 08:58:14 2010 From: rda.selin at gmail.com (becky_s) Date: Thu, 26 Aug 2010 05:58:14 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) References: Message-ID: <2aa0205a-bb19-4265-a0ac-cd87445b7e0e@i13g2000yqd.googlegroups.com> On Aug 26, 1:52?am, Dennis Lee Bieber wrote: > On Wed, 25 Aug 2010 14:57:33 -0700 (PDT), becky_s > declaimed the following in gmane.comp.python.general: > > > > > px,py = p(mesolon, mesolat) > > ? ? ? ? For my elucidation, what does that ? ? ?p(x,y) ?actually do? Especially > as you appear to expect the result to be split into separate x and y > afterwards? I can't find it defined in either matplotlib nor numpy. p was declared as a basemap object in the previous statement, which sets up a map projection. Calling p(mesolon, mesolat) converts those lons, lats to units in that map projection and stores them in px,py. (See http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html for more info on basemap.) > > > pyplot_api.html#matplotlib.pyplot.contourf) I thought that as long as > > px, py, and rain are the same dimensions, everything should be fine. > > ? ? ? ? And are they? You don't demonstrate that you've checked for that I did a simple print px.shape, rain.shape, etc. to check. They are all size (135,). > > > Apparently that is not the case? ?If 1D arrays are not allowed in > > contourf, then how can I change my data into a 2D array? > > ? ? ? ? Also note (jumping to your follow up) that contourf is described as > having a potential problem with masked arrays (whatever those are) for > "Z" My problem isn't with the masked arrays as much as it is with rain being a 1D array. IDL can handle contouring 1D arrays with missing variables lickety-split, so I was really hoping Python could as well. Also, numpy.ma is the masked array library. See http://docs.scipy.org/doc/numpy/reference/routines.ma.html. From __peter__ at web.de Thu Aug 26 09:29:33 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Aug 2010 15:29:33 +0200 Subject: bug? pkgutil.walk_packages returns packages that result in an ImportError References: Message-ID: Chris Withers wrote: > From the docs of pkgutils.walk_packages: > """ > 'onerror' is a function which gets called with one argument (the > name of the package which was being imported) if any exception > occurs while trying to import a package. If no onerror function is > supplied, ImportErrors are caught and ignored, while all other > exceptions are propagated, terminating the search. > """ > > My expectation of this is that if onerrors is left as None, names > yielded will be importable. I would infer no such promise, especially as the generator also yields modules, and no attempt at all is made to import those. > However, because the yield is before the import check, you can get > packages returned that are not importable. > > This feels at odds with the docs above and I think is a bug. > > If the yield were dropped to befoer the import check, we wouldn't have > this problem. > > what do others think? I've never worked with that function; I'd like to hear more about your usecase. Peter From john at castleamber.com Thu Aug 26 10:32:47 2010 From: john at castleamber.com (John Bokma) Date: Thu, 26 Aug 2010 09:32:47 -0500 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> <4c762382$0$20848$426a34cc@news.free.fr> Message-ID: <87zkw9bg1c.fsf@castleamber.com> Bruno Desthuilliers writes: > BartC a ?crit : >> "Steven D'Aprano" wrote in >> message news:4c6f8edd$0$28653$c3e8da3 at news.astraweb.com... >>> On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: >> >>>> I onced worked in a shop (Win32 desktop / accouting applications mainly) >>>> where I was the only guy that could actually understand recursion. FWIW, >>>> I also was the only guy around that understood "hairy" (lol) concepts >>>> like callback functions, FSM, polymorphism, hashtables, linked lists, >>>> ADTs, algorithm complexity etc... >>> >>> >>> Was there anything they *did* understand, or did they just bang on the >>> keyboard at random until the code compiled? *wink* >> >> You underestimate how much programming (of applications) can be done >> without needing any of this stuff. > > From personal experience : almost nothing worth being maintained. I'm > talking about complex domain-specific applications here - not shell > scripts or todo-lists. I doubt anyone who codes like that keeps a todo-list. >>>> Needless to say, I didn't last long !-) >>> >>> And rightly so :) >> >> I guess they wanted code that could be maintained by anybody. > > The code base was an unmaintainable, undecip?erable mess loaded with > global state (litteraly *hundreds* of global variables), duplication, > dead code, and enough WTF to supply thedailywtf.com for years - to > make a long story short, the perfect BigBallOfMudd. FWIW, the company > didn't last long neither - they just kept on introducing ten new bugs > each time they "fixed" one. and they forgot to sell that as new features, I guess :-D. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From python.koda at gmail.com Thu Aug 26 10:35:27 2010 From: python.koda at gmail.com (Alban Nona) Date: Thu, 26 Aug 2010 10:35:27 -0400 Subject: Path / Listing and os.walk problem. In-Reply-To: References: Message-ID: Hey ! Thank you guys ! It help me a lot ! @Dennis (Gomes): Thanks ! I tried it it worked well but list me the whole files :P (and finally crashed python...lol) I looked at the Peter method and, Im really dumb to didnt tough about defining a pattern like *_v001.0001.exr * like this, it sort me only one frame...which is perfect and less memory consuming I guess. And glob use seems to be perfect for what I want to do ! so thank you to point me in this direction :p I tried also the Peter code, and it give me a good listing of my element like I wanted: HPO7_SEQ004_031_VDMRoom_ALB HPO7_SEQ004_031_VDMRoom_AMB HPO7_SEQ004_031_VDMRoom_BTY HPO7_SEQ004_031_VDMRoom_Cutouts_ALB HPO7_SEQ004_031_VDMRoom_Cutouts_AMB HPO7_SEQ004_031_VDMRoom_Cutouts_DET .... HPO7_SEQ004_031_VDMRoom_DET HPO7_SEQ004_031_VDMRoom_DIF HPO7_SEQ004_031_VDMRoom_DPF HPO7_SEQ004_031_VDMRoom_Decals_ALB .... HPO7_SEQ004_031_VDM_ALB HPO7_SEQ004_031_VDM_AMB HPO7_SEQ004_031_VDM_BTY HPO7_SEQ004_031_VDM_DIF HPO7_SEQ004_031_VDM_DPF HPO7_SEQ004_031_VDM_Fresnel_mat Unfortunatly, a new problem come to me, I looking to get that kind of list: HPO7_SEQ004_031_VDMRoom HPO7_SEQ004_031_VDMRoom HPO7_SEQ004_031_VDMRoom HPO7_SEQ004_031_VDMRoom_Cutouts HPO7_SEQ004_031_VDMRoom_Cutouts HPO7_SEQ004_031_VDMRoom_Cutouts .... Right now, Im looking the documentation to find a way to do it, Im thinking about string methods, I also though: " hey, I just have to delete the 4 last characters, but na ! itll not work because sometime I have something like "_Fresnel_mat'' which is of course more than 4 chars...) Maybe the best would be to declare something like "in the string, look at the last "_" and delete it + whatever there is after" but I didnt find how to do it, I mean I tried splitext which is, not appropriate. Do I have to declare a list of element like: elementList: ["_ALB", "AMB", "_Beauty", etc...] and to search that pattern in the files name to remove it after ? it seems not bad as solution, but I pretty sure there is a better way to do it. right ? anyway, thank very much guys ! :) and have a good day ! 2010/8/26 Peter Otten <__peter__ at web.de> > Alban Nona wrote: > > > Hi > > > > So here is my problem: > > > > I have my render files that are into a directory like this: > > > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0001.exr > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0002.exr > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0003.exr > > .... > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0001.exr > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0002.exr > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0003.exr > > > > True is, there is like 1000 Files is the directory (C:\log\renderfiles\) > > > > What Iam looking to is to extract the first part of the filenames as a > > list, but I dont want the script to extract it 1000times, I mean I dont > > need it to extract HPO7_SEQ004_031_VDM_AMB 150 times, because there is > 150 > > Frames. (not sure if its clear tought) > > > > so far, I would like the list to look lik: > > > > ["HPO7_SEQ004_031_VDM_DIF", "HPO7_SEQ004_031_VDM_AMB", etc...] > > > > > > I start to think about that, to try to use a > > > > for (path, dirs, files) in os.walk(path): > > list.append(files) > > > > > > but this kind of thing will just append the whole 1000 files, thing that > I > > dont want, and more complicated I dont want the thing after "AMB" or > "DIF" > > in the name files to follow. > > (thing I can delete using a split, if I read well ?) > > > > > > I trying to search on internet for answer, but seems I find nothing about > > it. > > Someone can help me with that please, show me the way or something ? > > You can use glob. Assuming the files are all in one directory: > > import os > import glob > > folder = r"C:\log\renderfiles" > > # find files that end with "_V001.0001.exr" > pattern = os.path.join(folder, "*_V001.0001.exr") > files = glob.glob(pattern) > > # remove the directory > names = [os.path.basename(f) for f in files] > > # remove everything after and including the last occurence of "_" > names = [n.rpartition("_")[0] for n in names] > > print "\n".join(sorted(names)) > > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nanothermite911fbibustards at gmail.com Thu Aug 26 11:56:12 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Thu, 26 Aug 2010 08:56:12 -0700 (PDT) Subject: JEW BUSTARDS , MOSSAD BUSTARDS , CIA Bustards did 911 and bustards are afraid of truth, GOOGLE BUSTARDS do censorship and but not in CHINA to subvert it ... Re: GERMAN GIRLS HOT SEX VIDEOS. References: <968e144b-b230-4b60-ae2a-f3c1dc2f8573@v6g2000prd.googlegroups.com> Message-ID: On Aug 26, 1:31?am, nanothermite911fbibustards wrote: > On Aug 14, 6:07?am, Hot Hot wrote: > > > GERMAN GIRLS ?HOT SEX VIDEOS Athttp://simpletoget.co.cc > > > Due to high sex content, i have hidden the videos in an image.in that > > website on Right side ?below search box click on image and watch > > videos in all angles. > > I dont think the JEW COMPANY GOOGLE will delete your post, but it will > delete my post > ///////////////////////////////////////////////////////////////////////////??////////// > > CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria > Lauterbach and KILL THEM > > Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist > Bustard who > > The girl was a German like the one Roman Polansky raped, Semantha > Geimer > > http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ > > Look at his face, what criminal race is he ? What goes around comes > around !!! > > Former Marine convicted in North Carolina of killing female colleague > By the CNN Wire Staff > August 23, 2010 8:33 p.m. EDT > > For more on this story, read the coverage from CNN affiliate WRAL. > > (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North > Carolina on Monday of first degree murder in the 2007 death of Lance > Cpl. Maria Lauterbach, who was eight months pregnant when she died. > > An autopsy showed that Lauterbach, 20, died of blunt force trauma to > the head. Police unearthed her charred body from beneath a barbecue > pit in Laurean's backyard in January 2008. She had disappeared the > month before. > > Laurean, who was dressed in black slacks and wore a white shirt and > black tie, did not show any emotion as the judge read his sentence of > life in prison without parole. He either said or mouthed something to > someone in the audience of the courtroom before he was led out in > handcuffs, video showed. > > Laurean and Lauterbach were stationed together at Camp Lejeune, North > Carolina. > > North Carolina prosecutors alleged Laurean killed Lauterbach on > December 14 and used her ATM card 10 days later before fleeing to > Mexico.Laurean was arrested there in April 2008. He holds dual > citizenship in the United States and Mexico. > > Before her death, Lauterbach told the Marines that Laurean had raped > her. Laurean denied it, and disappeared just a few weeks before a > scheduled rape hearing at Camp LeJeune. > > The DNA of Lauterbach's unborn child did not match that of Laurean, > according to law enforcement personnel. > > Authorities found Lauterbach's body after Laurean's wife, Christina, > produced a note her husband had written claiming the 20-year-old > woman > slit her own throat during an argument, according to officials. > > Although a gaping 4-inch wound was found on the left side of > Lauterbach's neck, autopsy results indicated that the wound itself > would not have been fatal and may have occurred after death. > > Asked by a Mexican reporter at the time of his arrest whether he > killed Lauterbach, Laurean replied, "I loved her." > > Laurean's lawyer said his client would appeal the decision. > > ///////////////////////////////////////////////////////////////// > > The MARINE BASTARD will probably claim INSANITY ........ > > ////////////////////// > The FAT per DIEM FBI bustards use our TAX PAYER MONEY and > INCOMPETENCE > is UNACCEPTABLE. > > ===== > > http://www.youtube.com/watch?v=lX18zUp6WPY > > http://www.youtube.com/watch?v=XQapkVCx1HI > > http://www.youtube.com/watch?v=tXJ-k-iOg0M > > Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX > Mailer ? > Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did > you release the 5 dancing Israelis compromising the whole 911 > investigation ? If the Dubai Police can catch Mossad Murderers and > put > the videos and Iranian Police can why cant you put the Pentagon > Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and > puting on INTERNATIONAL MEDIA a day after catching him without > TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did > you have to LIE about Dr Afiya Siddiqui and torture that Innocent > little mother of 3 and smashing the skull of her one child ? > > http://www.youtube.com/watch?v=DhMcii8smxkhttp://www.youtube.com/watc... > > There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian > courts. > > FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but > only because he was a white. They got away with MURDER of thousands > of > Non-whites in all parts of the world. > > Daily 911 news :http://911blogger.com > > http://www.youtube.com/watch?v=tRfhUezbKLw > > http://www.youtube.com/watch?v=x7kGZ3XPEm4 > > http://www.youtube.com/watch?v=lX18zUp6WPY > > Conclusion : FBI bustards are RACIST and INcompetent. They could > neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they > cover them up - whichever was their actual goal or task. > > SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across > tbe board, esp the whites/jew on the top. > > FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST > and > UNPATRIOTIC Act > FBI bustards failed to prevent ROMAN POLANSKY from absconding to > europe and rapes. > FBI bustards failed to prevent OKLAHOMA > > --http://mail.python.org/mailman/listinfo/python-list > > I dont think the JEW COMPANY GOOGLE will delete your post, but it will > delete my post > > On Aug 14, 6:07 am, Hot Hot wrote: > > > > > GERMAN GIRLS ?HOT SEX VIDEOS Athttp://simpletoget.co.cc > > Due to high sex content, i have hidden the videos in an image.in that > > website on Right side ?below search box click on image and watch > > videos in all angles.- Hide quoted text -- Hide quoted text - > > - Show quoted text - From garabik-news-2005-05 at kassiopeia.juls.savba.sk Thu Aug 26 12:19:38 2010 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Thu, 26 Aug 2010 16:19:38 +0000 (UTC) Subject: Webcam support References: Message-ID: Navkirat Singh wrote: > Hi Guys, > > I am programming a web centric app in python for customer, which needs > to click a snap of the customer and forward the pic to the server via > POST. I am not very familiar with how I can achieve this. Any > direction would be much appreciated. > For something very similar, I used fswebcam, the crucial code looked like this: def capture_frame(filename, brightness=50): os.system('fswebcam -S 1 -r %s -s brightness=%i%% --font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf --jpeg 60 --save %s' % (RESOLUTION, brightness, filename)) -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread From navkirats at gmail.com Thu Aug 26 13:22:16 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 26 Aug 2010 22:52:16 +0530 Subject: Writing byte stream as jpeg format to disk Message-ID: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> Hey guys, I am programming a webserver, I receive a jpeg file with the POST method.The file (.jpeg) is encoded in bytes, I parse the bytes by decoding them to a string. I wanted to know how i could write the file (now a string) as a jpeg image on disk. When I try to encode the same string to a bytes and write them in binary format to disk, the file is not recognized as jpeg. I would be grateful if someone could help me with this. Regards, Nav From navkirats at gmail.com Thu Aug 26 13:23:50 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 26 Aug 2010 22:53:50 +0530 Subject: Webcam support In-Reply-To: References: Message-ID: <1B995359-7C7C-47E7-8360-9A629A9BFB7D@gmail.com> On 26-Aug-2010, at 9:49 PM, garabik-news-2005-05 at kassiopeia.juls.savba.sk wrote: > Navkirat Singh wrote: >> Hi Guys, >> >> I am programming a web centric app in python for customer, which needs >> to click a snap of the customer and forward the pic to the server via >> POST. I am not very familiar with how I can achieve this. Any >> direction would be much appreciated. >> > > For something very similar, I used fswebcam, the crucial code looked > like this: > > def capture_frame(filename, brightness=50): > os.system('fswebcam -S 1 -r %s -s brightness=%i%% > --font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf > --jpeg 60 --save %s' % (RESOLUTION, brightness, filename)) > > > -- > ----------------------------------------------------------- > | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | > | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | > ----------------------------------------------------------- > Antivirus alert: file .signature infected by signature virus. > Hi! I'm a signature virus! Copy me into your signature file to help me spread > -- > http://mail.python.org/mailman/listinfo/python-list Thanks guys, I stumbled upon jpegcam (javascript and flash library) which does this. It works awesome !! :) Regards From john at castleamber.com Thu Aug 26 13:31:07 2010 From: john at castleamber.com (John Bokma) Date: Thu, 26 Aug 2010 12:31:07 -0500 Subject: Writing byte stream as jpeg format to disk References: Message-ID: <874oeh2sdg.fsf@castleamber.com> Navkirat Singh writes: > Hey guys, > > I am programming a webserver, I receive a jpeg file with the POST > method.The file (.jpeg) is encoded in bytes, I parse the bytes by > decoding them to a string. Why? -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From navkirats at gmail.com Thu Aug 26 14:25:46 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 26 Aug 2010 23:55:46 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <874oeh2sdg.fsf@castleamber.com> References: <874oeh2sdg.fsf@castleamber.com> Message-ID: On 26-Aug-2010, at 11:01 PM, John Bokma wrote: > Navkirat Singh writes: > >> Hey guys, >> >> I am programming a webserver, I receive a jpeg file with the POST >> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >> decoding them to a string. > > Why? > > -- > John Bokma j3b > > Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma > Freelance Perl & Python Development: http://castleamber.com/ > -- > http://mail.python.org/mailman/listinfo/python-list why? I am not quite sure what you have not understood. From invalid at invalid.invalid Thu Aug 26 14:35:37 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 26 Aug 2010 18:35:37 +0000 (UTC) Subject: Writing byte stream as jpeg format to disk References: <874oeh2sdg.fsf@castleamber.com> Message-ID: On 2010-08-26, Navkirat Singh wrote: > > On 26-Aug-2010, at 11:01 PM, John Bokma wrote: > >> Navkirat Singh writes: >> >>> Hey guys, >>> >>> I am programming a webserver, I receive a jpeg file with the POST >>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>> decoding them to a string. >> >> Why? > > why? I am not quite sure what you have not understood. You're starting with JPEG data. If you want to write it to a file, then write it to a file. Whatever process you're describing as "I parse the bytes by decoding them to a string" is not needed and is apparently converting the JPEG data into something that's not JPEG data. -- Grant Edwards grant.b.edwards Yow! PARDON me, am I at speaking ENGLISH? gmail.com From sschwarzer at sschwarzer.net Thu Aug 26 14:37:44 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 26 Aug 2010 20:37:44 +0200 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: Message-ID: <4C76B478.1090700@sschwarzer.net> Hi Navkirat, On 2010-08-26 19:22, Navkirat Singh wrote: > I am programming a webserver, I receive a jpeg file with > the POST method.The file (.jpeg) is encoded in bytes, I > parse the bytes by decoding them to a string. I wanted to > know how i could write the file (now a string) as a jpeg > image on disk. When I try to encode the same string to a > bytes and write them in binary format to disk, the file is > not recognized as jpeg. I would be grateful if someone > could help me with this. I guess you mean you "see" a byte string in your server and want to write that to disk. Assuming the string you got is the correct image data in the first place, you can, in Python 2.x, write the string data to disk like this: fobj = open("some_image.jpg", "wb") fobj.write(byte_string) fobj.close() Note that you should use "wb" as mode to write as binary. Otherwise you'll get automatic line ending conversion (at least on Windows) which will give the result you describe. If my answer doesn't help, you probably need to describe in more detail what you're doing, including showing some real code. Stefan From python.koda at gmail.com Thu Aug 26 14:41:49 2010 From: python.koda at gmail.com (Alban Nona) Date: Thu, 26 Aug 2010 14:41:49 -0400 Subject: Path / Listing and os.walk problem. In-Reply-To: References: Message-ID: So I found a way to do it, maybe some people could be interested: listNames = [] for n in names: listNames.append('_'.join(n.split('_')[:-1])) #It will cut the last part of the file name convention listNames = list(set(listNames)) #we Delete duplicates from the list, like this we only have what we are interested in for e in listNames: #Juste to check. print e :) 2010/8/26 Alban Nona > Hey ! Thank you guys ! > It help me a lot ! > > @Dennis (Gomes): Thanks ! I tried it it worked well but list me the whole > files :P (and finally crashed python...lol) > > I looked at the Peter method and, Im really dumb to didnt tough about > defining a pattern like *_v001.0001.exr * like this, it sort me only one > frame...which is perfect and less memory consuming I guess. > > And glob use seems to be perfect for what I want to do ! so thank you to > point me in this direction :p > > I tried also the Peter code, and it give me a good listing of my element > like I wanted: > > HPO7_SEQ004_031_VDMRoom_ALB > HPO7_SEQ004_031_VDMRoom_AMB > HPO7_SEQ004_031_VDMRoom_BTY > HPO7_SEQ004_031_VDMRoom_Cutouts_ALB > HPO7_SEQ004_031_VDMRoom_Cutouts_AMB > HPO7_SEQ004_031_VDMRoom_Cutouts_DET > .... > HPO7_SEQ004_031_VDMRoom_DET > HPO7_SEQ004_031_VDMRoom_DIF > HPO7_SEQ004_031_VDMRoom_DPF > HPO7_SEQ004_031_VDMRoom_Decals_ALB > .... > HPO7_SEQ004_031_VDM_ALB > > HPO7_SEQ004_031_VDM_AMB > HPO7_SEQ004_031_VDM_BTY > > HPO7_SEQ004_031_VDM_DIF > HPO7_SEQ004_031_VDM_DPF > HPO7_SEQ004_031_VDM_Fresnel_mat > > > Unfortunatly, a new problem come to me, I looking to get that kind of > list: > > HPO7_SEQ004_031_VDMRoom > HPO7_SEQ004_031_VDMRoom > HPO7_SEQ004_031_VDMRoom > HPO7_SEQ004_031_VDMRoom_Cutouts > HPO7_SEQ004_031_VDMRoom_Cutouts > HPO7_SEQ004_031_VDMRoom_Cutouts > .... > > Right now, Im looking the documentation to find a way to do it, Im thinking > about string methods, I also though: " hey, I just have to delete the 4 last > characters, but na ! itll not work because sometime I have something like > "_Fresnel_mat'' which is of course more than 4 chars...) > > Maybe the best would be to declare something like "in the string, look at > the last "_" and delete it + whatever there is after" > but I didnt find how to do it, I mean I tried splitext which is, not > appropriate. > > Do I have to declare a list of element like: > elementList: ["_ALB", "AMB", "_Beauty", etc...] > and to search that pattern in the files name to remove it after ? it seems > not bad as solution, but I pretty sure there is a better way to do it. > > right ? > > anyway, thank very much guys ! :) > and have a good day ! > > > 2010/8/26 Peter Otten <__peter__ at web.de> > > Alban Nona wrote: >> >> > Hi >> > >> > So here is my problem: >> > >> > I have my render files that are into a directory like this: >> > >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0001.exr >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0002.exr >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0003.exr >> > .... >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0001.exr >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0002.exr >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0003.exr >> > >> > True is, there is like 1000 Files is the directory (C:\log\renderfiles\) >> > >> > What Iam looking to is to extract the first part of the filenames as a >> > list, but I dont want the script to extract it 1000times, I mean I dont >> > need it to extract HPO7_SEQ004_031_VDM_AMB 150 times, because there is >> 150 >> > Frames. (not sure if its clear tought) >> > >> > so far, I would like the list to look lik: >> > >> > ["HPO7_SEQ004_031_VDM_DIF", "HPO7_SEQ004_031_VDM_AMB", etc...] >> > >> > >> > I start to think about that, to try to use a >> > >> > for (path, dirs, files) in os.walk(path): >> > list.append(files) >> > >> > >> > but this kind of thing will just append the whole 1000 files, thing that >> I >> > dont want, and more complicated I dont want the thing after "AMB" or >> "DIF" >> > in the name files to follow. >> > (thing I can delete using a split, if I read well ?) >> > >> > >> > I trying to search on internet for answer, but seems I find nothing >> about >> > it. >> > Someone can help me with that please, show me the way or something ? >> >> You can use glob. Assuming the files are all in one directory: >> >> import os >> import glob >> >> folder = r"C:\log\renderfiles" >> >> # find files that end with "_V001.0001.exr" >> pattern = os.path.join(folder, "*_V001.0001.exr") >> files = glob.glob(pattern) >> >> # remove the directory >> names = [os.path.basename(f) for f in files] >> >> # remove everything after and including the last occurence of "_" >> names = [n.rpartition("_")[0] for n in names] >> >> print "\n".join(sorted(names)) >> >> Peter >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From navkirats at gmail.com Thu Aug 26 14:57:19 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 00:27:19 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76B478.1090700@sschwarzer.net> References: <4C76B478.1090700@sschwarzer.net> Message-ID: I am sorry, maybe I was not elaborate in what I was having trouble with. I am using a jpegcam library, which on my web page captures a webcam image and sends it to the server via the POST method. On the Server side (python 3), I receive this image as a part of header content in bytes (I know thats not how it should be done, but the author has some reason for it), so I first convert the headers to a string so I can separate them. From the separated headers I fish out the content of the image file (which is a string). This is where I get stuck, how am I supposed to convert it back to an image, so I can save as a jpeg on disk. Regards, Nav On 27-Aug-2010, at 12:07 AM, Stefan Schwarzer wrote: > Hi Navkirat, > > On 2010-08-26 19:22, Navkirat Singh wrote: >> I am programming a webserver, I receive a jpeg file with >> the POST method.The file (.jpeg) is encoded in bytes, I >> parse the bytes by decoding them to a string. I wanted to >> know how i could write the file (now a string) as a jpeg >> image on disk. When I try to encode the same string to a >> bytes and write them in binary format to disk, the file is >> not recognized as jpeg. I would be grateful if someone >> could help me with this. > > I guess you mean you "see" a byte string in your server and > want to write that to disk. Assuming the string you got is > the correct image data in the first place, you can, in > Python 2.x, write the string data to disk like this: > > fobj = open("some_image.jpg", "wb") > fobj.write(byte_string) > fobj.close() > > Note that you should use "wb" as mode to write as binary. > Otherwise you'll get automatic line ending conversion (at > least on Windows) which will give the result you describe. > > If my answer doesn't help, you probably need to describe in > more detail what you're doing, including showing some real > code. > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list From python at mrabarnett.plus.com Thu Aug 26 15:15:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 26 Aug 2010 20:15:25 +0100 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <4C76B478.1090700@sschwarzer.net> Message-ID: <4C76BD4D.8060303@mrabarnett.plus.com> On 26/08/2010 19:57, Navkirat Singh wrote: > I am sorry, maybe I was not elaborate in what I was having trouble > with. I am using a jpegcam library, which on my web page captures a > webcam image and sends it to the server via the POST method. On the > Server side (python 3), I receive this image as a part of header > content in bytes (I know thats not how it should be done, but the > author has some reason for it), so I first convert the headers to a > string so I can separate them. From the separated headers I fish out > the content of the image file (which is a string). This is where I > get stuck, how am I supposed to convert it back to an image, so I can > save as a jpeg on disk. > [snip] What does that string look like? Try printing out repr(image[ : 100]). If it looks like plain bytes, then write it to file. If it looks like a series of hex digits, then decode to bytes before writing. From johnroth1 at gmail.com Thu Aug 26 15:29:25 2010 From: johnroth1 at gmail.com (John Roth) Date: Thu, 26 Aug 2010 12:29:25 -0700 (PDT) Subject: Overload print References: Message-ID: <7e793b96-1f42-43d7-91d8-3aac1e6d7188@a4g2000prm.googlegroups.com> On Aug 25, 3:42?pm, Alexander Kapps wrote: > Ross Williamson wrote: > > Hi All > > > Is there anyway in a class to overload the print function? > > In Python <= 2.x "print" is a statement and thus can't be > "overloaded". That's exactly the reason, why Python 3 has turned > "print" into a function. > > >>> class foo_class(): > >>> ? ? def __print__(self): > >>> ? ? ? ? ? print "hello" > > >>> cc = foo_class() > >>> print cc > > > Gives: > > > hello > > Hmm, on what Python version are you? To my knowledge there is no > __print__ special method. Did you mean __str__ or __repr__ ? > > > I'm looking at finding nice way to print variables in a class just by > > asking to print it > > In Python3 you *can* overload print(), but still, you better define > __str__() on your class to return a string, representing what ever > you want: > > In [11]: class Foo(object): > ? ? ....: ? ? def __str__(self): > ? ? ....: ? ? ? ? return "foo" > ? ? ....: > ? ? ....: > > In [12]: f = Foo() > > In [13]: print f > foo Maybe what the OP really wants is the format() method on a string? That gives a very rich set of override options, at the expense of not using the print statement/method, including the ability to define your own formatting language for a class. John Roth From stillyet+nntp at googlemail.com Thu Aug 26 15:31:17 2010 From: stillyet+nntp at googlemail.com (Simon Brooke) Date: 26 Aug 2010 19:31:17 GMT Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards References: <9c3b672d-b636-4f12-9918-4837784fce42@x42g2000yqx.googlegroups.com> Message-ID: <8dnto5F4poU2@mid.individual.net> On Wed, 25 Aug 2010 07:31:03 -0700, Standish P wrote: > ... so you want to render this in TeX ... ? It was very thoughtful of you to repost the whole spammer text for the benefit of those of us who have the spammer killfiled, and consequently would not otherwise have been able to read it. -- ;; Semper in faecibus sumus, sole profundam variat From robert.kern at gmail.com Thu Aug 26 15:40:30 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 14:40:30 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <874oeh2sdg.fsf@castleamber.com> Message-ID: On 8/26/10 1:25 PM, Navkirat Singh wrote: > > On 26-Aug-2010, at 11:01 PM, John Bokma wrote: > >> Navkirat Singh writes: >> >>> Hey guys, >>> >>> I am programming a webserver, I receive a jpeg file with the POST >>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>> decoding them to a string. >> >> Why? >> >> -- >> John Bokma j3b >> >> Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma >> Freelance Perl& Python Development: http://castleamber.com/ >> -- >> http://mail.python.org/mailman/listinfo/python-list > > why? I am not quite sure what you have not understood. Why decode the bytes to (presumably) unicode strings just to encode them back to bytes again? JPEG is not composed of unicode characters; you need to leave them as bytes. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From navkirats at gmail.com Thu Aug 26 15:47:18 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 01:17:18 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <874oeh2sdg.fsf@castleamber.com> Message-ID: On 27-Aug-2010, at 1:10 AM, Robert Kern wrote: > On 8/26/10 1:25 PM, Navkirat Singh wrote: >> >> On 26-Aug-2010, at 11:01 PM, John Bokma wrote: >> >>> Navkirat Singh writes: >>> >>>> Hey guys, >>>> >>>> I am programming a webserver, I receive a jpeg file with the POST >>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>> decoding them to a string. >>> >>> Why? >>> >>> -- >>> John Bokma j3b >>> >>> Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma >>> Freelance Perl& Python Development: http://castleamber.com/ >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> why? I am not quite sure what you have not understood. > > Why decode the bytes to (presumably) unicode strings just to encode them back to bytes again? JPEG is not composed of unicode characters; you need to leave them as bytes. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list The image bytes are a part of a HTTP header content ( not the message body ). To separate the header content from the image I have to first convert the bytes to string to perform parsing. The resultant string then needs to be converted back to the image. Hence, my problem. From navkirats at gmail.com Thu Aug 26 15:54:43 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 01:24:43 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76BD4D.8060303@mrabarnett.plus.com> References: <4C76B478.1090700@sschwarzer.net> <4C76BD4D.8060303@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 12:45 AM, MRAB wrote: > On 26/08/2010 19:57, Navkirat Singh wrote: >> I am sorry, maybe I was not elaborate in what I was having trouble >> with. I am using a jpegcam library, which on my web page captures a >> webcam image and sends it to the server via the POST method. On the >> Server side (python 3), I receive this image as a part of header >> content in bytes (I know thats not how it should be done, but the >> author has some reason for it), so I first convert the headers to a >> string so I can separate them. From the separated headers I fish out >> the content of the image file (which is a string). This is where I >> get stuck, how am I supposed to convert it back to an image, so I can >> save as a jpeg on disk. >> > [snip] > What does that string look like? Try printing out repr(image[ : 100]). > If it looks like plain bytes, then write it to file. If it looks like a > series of hex digits, then decode to bytes before writing. > -- > http://mail.python.org/mailman/listinfo/python-list Thanks MRAB, your suggestions have always been very helpful to me. I shall let you know on what I see. Regards, Nav From davea at ieee.org Thu Aug 26 16:02:36 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 26 Aug 2010 16:02:36 -0400 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> Message-ID: <4C76C85C.7030505@ieee.org> Navkirat Singh wrote: > Hey guys, > > I am programming a webserver, I receive a jpeg file with the POST method.The file (.jpeg) is encoded in bytes, I parse the bytes by decoding them to a string. I wanted to know how i could write the file (now a string) as a jpeg image on disk. When I try to encode the same string to a bytes and write them in binary format to disk, the file is not recognized as jpeg. I would be grateful if someone could help me with this. > > > Regards, > Nav > If by "decoding them to a string" you mean converting to Unicode, then you've already trashed the data. That's only valid if the bytes had been encoded from valid Unicode characters, and then only if you use the corresponding decoding technique. If you mean some other decoding, then the question is meaningless without telling us just what the decoding is, preferably with some code. It also might be useful to know what version of Python you're using, when you post the code. DaveA From navkirats at gmail.com Thu Aug 26 16:14:40 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 01:44:40 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76C85C.7030505@ieee.org> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> Message-ID: <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: > Navkirat Singh wrote: >> Hey guys, >> >> I am programming a webserver, I receive a jpeg file with the POST method.The file (.jpeg) is encoded in bytes, I parse the bytes by decoding them to a string. I wanted to know how i could write the file (now a string) as a jpeg image on disk. When I try to encode the same string to a bytes and write them in binary format to disk, the file is not recognized as jpeg. I would be grateful if someone could help me with this. >> >> >> Regards, >> Nav > If by "decoding them to a string" you mean converting to Unicode, then you've already trashed the data. That's only valid if the bytes had been encoded from valid Unicode characters, and then only if you use the corresponding decoding technique. > > If you mean some other decoding, then the question is meaningless without telling us just what the decoding is, preferably with some code. > > It also might be useful to know what version of Python you're using, when you post the code. > > DaveA > Dave, I am using Python3 and I receive a byte stream with a jpeg attached sent by the web browser over a socket, which looks like this: b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f From the above, I need to: a) Split the header content from the image content, which comes after the keep-alive\r\n\r\n part b) Then write the image content to file for further use as a jpeg. Nav -------------- next part -------------- An HTML attachment was scrubbed... URL: From navkirats at gmail.com Thu Aug 26 16:19:25 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 01:49:25 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76C85C.7030505@ieee.org> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> Message-ID: <279000F8-D9C6-464C-912D-A49BC3AC4D3F@gmail.com> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: > Navkirat Singh wrote: >> Hey guys, >> >> I am programming a webserver, I receive a jpeg file with the POST method.The file (.jpeg) is encoded in bytes, I parse the bytes by decoding them to a string. I wanted to know how i could write the file (now a string) as a jpeg image on disk. When I try to encode the same string to a bytes and write them in binary format to disk, the file is not recognized as jpeg. I would be grateful if someone could help me with this. >> >> >> Regards, >> Nav > If by "decoding them to a string" you mean converting to Unicode, then you've already trashed the data. That's only valid if the bytes had been encoded from valid Unicode characters, and then only if you use the corresponding decoding technique. > > If you mean some other decoding, then the question is meaningless without telling us just what the decoding is, preferably with some code. > > It also might be useful to know what version of Python you're using, when you post the code. > > DaveA > Also, my apologies for lack of knowledge of character encodings. You have pointed out correctly about unicode encoding. I was under the impression that a unicode will preserve the integrity of the message which has been encoded. From rda.selin at gmail.com Thu Aug 26 16:24:56 2010 From: rda.selin at gmail.com (becky_s) Date: Thu, 26 Aug 2010 13:24:56 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) References: Message-ID: I was able to figure this out on my own. First, to eliminate the masked arrays, I used a combination of the where and compress functions to remove any missing data from my 1-D arrays. Then, I used the griddata function as described above. This did the trick. From python at mrabarnett.plus.com Thu Aug 26 16:27:21 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 26 Aug 2010 21:27:21 +0100 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> Message-ID: <4C76CE29.8080507@mrabarnett.plus.com> On 26/08/2010 21:14, Navkirat Singh wrote: > > On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: > >> Navkirat Singh wrote: >>> Hey guys, >>> >>> I am programming a webserver, I receive a jpeg file with the POST >>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>> decoding them to a string. I wanted to know how i could write the >>> file (now a string) as a jpeg image on disk. When I try to encode the >>> same string to a bytes and write them in binary format to disk, the >>> file is not recognized as jpeg. I would be grateful if someone could >>> help me with this. >>> >>> >>> Regards, >>> Nav >> If by "decoding them to a string" you mean converting to Unicode, then >> you've already trashed the data. That's only valid if the bytes had >> been encoded from valid Unicode characters, and then only if you use >> the corresponding decoding technique. >> >> If you mean some other decoding, then the question is meaningless >> without telling us just what the decoding is, preferably with some code. >> >> It also might be useful to know what version of Python you're using, >> when you post the code. >> >> DaveA >> > > Dave, > > I am using Python3 and I receive a byte stream with a jpeg attached sent > by the web browser over a socket, which looks like this: > > b': image/jpeg\r\nAccept: text/*\r\nReferer: > http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: > gzip, deflate\r\nContent-Length: 91783\r\nConnection: > keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f > > From the above, I need to: > > a) Split the header content from the image content, which comes after > the keep-alive\r\n\r\n part > > b) Then write the image content to file for further use as a jpeg. > Try: image = header.split(b'keep-alive\r\n\r\n', 1)[-1] open(image_path, 'wb').write(image) From davea at ieee.org Thu Aug 26 16:32:59 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 26 Aug 2010 16:32:59 -0400 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> Message-ID: <4C76CF7B.3070809@ieee.org> Navkirat Singh wrote: > O > > I am using Python3 and I receive a byte stream with a jpeg attached sent by the web browser over a socket, which looks like this: > > b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f > > From the above, I need to: > > a) Split the header content from the image content, which comes after the keep-alive\r\n\r\n part > > b) Then write the image content to file for further use as a jpeg. > > Nav > An arbitrary string of bytes is not necessarily valid utf-8, so I'm not sure why you haven't been getting errors during that "decode." In any case, such a conversion is not reversible. I would parse that as bytes, perhaps by searching for 'keep-alive'. Then split the byte stream into the two parts, and only convert the first part to Unicode (Python 3 string). For safety, you could check to make sure the search pattern only appears once, and potentially decode it multiple times. It'll only make sense once. DaveA From hwfwguy at gmail.com Thu Aug 26 16:44:32 2010 From: hwfwguy at gmail.com (Brad) Date: Thu, 26 Aug 2010 13:44:32 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> <0b04a316-a147-4179-a11f-de7a935385ea@q16g2000prf.googlegroups.com> Message-ID: On Aug 25, 4:05?am, Alex McDonald wrote: > Your example of writing code with > memory leaks *and not caring because it's a waste of your time* makes > me think that you've never been a programmer of any sort. "Windows applications are immune from memory leaks since programmers can count on regular crashes to automatically release previously allocated RAM." From navkirats at gmail.com Thu Aug 26 16:47:05 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:17:05 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76CE29.8080507@mrabarnett.plus.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 1:57 AM, MRAB wrote: > On 26/08/2010 21:14, Navkirat Singh wrote: >> >> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >> >>> Navkirat Singh wrote: >>>> Hey guys, >>>> >>>> I am programming a webserver, I receive a jpeg file with the POST >>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>> decoding them to a string. I wanted to know how i could write the >>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>> same string to a bytes and write them in binary format to disk, the >>>> file is not recognized as jpeg. I would be grateful if someone could >>>> help me with this. >>>> >>>> >>>> Regards, >>>> Nav >>> If by "decoding them to a string" you mean converting to Unicode, then >>> you've already trashed the data. That's only valid if the bytes had >>> been encoded from valid Unicode characters, and then only if you use >>> the corresponding decoding technique. >>> >>> If you mean some other decoding, then the question is meaningless >>> without telling us just what the decoding is, preferably with some code. >>> >>> It also might be useful to know what version of Python you're using, >>> when you post the code. >>> >>> DaveA >>> >> >> Dave, >> >> I am using Python3 and I receive a byte stream with a jpeg attached sent >> by the web browser over a socket, which looks like this: >> >> b': image/jpeg\r\nAccept: text/*\r\nReferer: >> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >> >> From the above, I need to: >> >> a) Split the header content from the image content, which comes after >> the keep-alive\r\n\r\n part >> >> b) Then write the image content to file for further use as a jpeg. >> > Try: > > image = header.split(b'keep-alive\r\n\r\n', 1)[-1] > open(image_path, 'wb').write(image) > -- > http://mail.python.org/mailman/listinfo/python-list I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes From navkirats at gmail.com Thu Aug 26 16:48:57 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:18:57 +0530 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> <0b04a316-a147-4179-a11f-de7a935385ea@q16g2000prf.googlegroups.com> Message-ID: <111315E9-1191-48A3-A56C-C37131F0A23A@gmail.com> On 27-Aug-2010, at 2:14 AM, Brad wrote: > On Aug 25, 4:05 am, Alex McDonald wrote: >> Your example of writing code with >> memory leaks *and not caring because it's a waste of your time* makes >> me think that you've never been a programmer of any sort. > > "Windows applications are immune from memory leaks since programmers > can count on regular crashes to automatically release previously > allocated RAM." > -- > http://mail.python.org/mailman/listinfo/python-list Sorry if I may sound rude, but I have to do this on the windows applications comment - hahahahaha From john at castleamber.com Thu Aug 26 17:09:02 2010 From: john at castleamber.com (John Bokma) Date: Thu, 26 Aug 2010 16:09:02 -0500 Subject: Writing byte stream as jpeg format to disk References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <87vd6x13pt.fsf@castleamber.com> Navkirat Singh writes: >>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>> by the web browser over a socket, which looks like this: >>> >>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f You're mistaken that the content is part of the headers, it's not. The \r\n\r\n separates headers from the content. Why don't you use urllib to save you from all this hassle? -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From robert.kern at gmail.com Thu Aug 26 17:10:26 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:10:26 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 8/26/10 3:47 PM, Navkirat Singh wrote: > > On 27-Aug-2010, at 1:57 AM, MRAB wrote: > >> On 26/08/2010 21:14, Navkirat Singh wrote: >>> >>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>> >>>> Navkirat Singh wrote: >>>>> Hey guys, >>>>> >>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>> decoding them to a string. I wanted to know how i could write the >>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>> same string to a bytes and write them in binary format to disk, the >>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>> help me with this. >>>>> >>>>> >>>>> Regards, >>>>> Nav >>>> If by "decoding them to a string" you mean converting to Unicode, then >>>> you've already trashed the data. That's only valid if the bytes had >>>> been encoded from valid Unicode characters, and then only if you use >>>> the corresponding decoding technique. >>>> >>>> If you mean some other decoding, then the question is meaningless >>>> without telling us just what the decoding is, preferably with some code. >>>> >>>> It also might be useful to know what version of Python you're using, >>>> when you post the code. >>>> >>>> DaveA >>>> >>> >>> Dave, >>> >>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>> by the web browser over a socket, which looks like this: >>> >>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>> >>> From the above, I need to: >>> >>> a) Split the header content from the image content, which comes after >>> the keep-alive\r\n\r\n part >>> >>> b) Then write the image content to file for further use as a jpeg. >>> >> Try: >> >> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >> open(image_path, 'wb').write(image) >> -- >> http://mail.python.org/mailman/listinfo/python-list > > I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). > > @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes This is incorrect. Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> bytes = b'Connection: keep-alive\r\n\r\nbody' >>> bytes.split(b'\r\n\r\n', 1)[-1] b'body' FYI: the JPEG data is not in the header. The b'\r\n\r\n' sequence delimits the header from the body. Do not rely on "Connection: keep-alive" being the last header. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From navkirats at gmail.com Thu Aug 26 17:17:05 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:47:05 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76CE29.8080507@mrabarnett.plus.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 1:57 AM, MRAB wrote: > On 26/08/2010 21:14, Navkirat Singh wrote: >> >> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >> >>> Navkirat Singh wrote: >>>> Hey guys, >>>> >>>> I am programming a webserver, I receive a jpeg file with the POST >>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>> decoding them to a string. I wanted to know how i could write the >>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>> same string to a bytes and write them in binary format to disk, the >>>> file is not recognized as jpeg. I would be grateful if someone could >>>> help me with this. >>>> >>>> >>>> Regards, >>>> Nav >>> If by "decoding them to a string" you mean converting to Unicode, then >>> you've already trashed the data. That's only valid if the bytes had >>> been encoded from valid Unicode characters, and then only if you use >>> the corresponding decoding technique. >>> >>> If you mean some other decoding, then the question is meaningless >>> without telling us just what the decoding is, preferably with some code. >>> >>> It also might be useful to know what version of Python you're using, >>> when you post the code. >>> >>> DaveA >>> >> >> Dave, >> >> I am using Python3 and I receive a byte stream with a jpeg attached sent >> by the web browser over a socket, which looks like this: >> >> b': image/jpeg\r\nAccept: text/*\r\nReferer: >> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >> >> From the above, I need to: >> >> a) Split the header content from the image content, which comes after >> the keep-alive\r\n\r\n part >> >> b) Then write the image content to file for further use as a jpeg. >> > Try: > > image = header.split(b'keep-alive\r\n\r\n', 1)[-1] > open(image_path, 'wb').write(image) > -- > http://mail.python.org/mailman/listinfo/python-list Yay !! I figured it out....it was really very simple. And if I really feel guilty if I have wasted your time - @MRAB, @DAVE. Here is what I needed to do: a) Separate image content from header content of the byte stream received from the web browser. b) Save the image content to disk for further use. Here is what I did. Following is just a snippet: #-------------HERE IS WHERE I RECEIVE THE DATA while True: buff = socket.recv(8192) byteStr +=buff if not buff: break #--------------ENCODING/DECODING STARTS FROM HERE (since I want to use split/partition functions to separate header content from the image content) strMsg = byteStr.decode("ISO-8859-1") listMsg = strMsg.split('\r\n') #---------------------------- # do some more processing to search the list for the image content, say supposing index is 11 #--------------------------- imageStr = listMsg[11].encode("ISO-8859-1") #Transform the byte string just the way I found it f = open('received.jpg','w'b) f.write(imageStr) The resultant file is a jpg file. Thanks, Nav From python at mrabarnett.plus.com Thu Aug 26 17:18:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 26 Aug 2010 22:18:26 +0100 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <4C76DA22.7030404@mrabarnett.plus.com> On 26/08/2010 21:47, Navkirat Singh wrote: > > On 27-Aug-2010, at 1:57 AM, MRAB wrote: > >> On 26/08/2010 21:14, Navkirat Singh wrote: >>> >>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>> >>>> Navkirat Singh wrote: >>>>> Hey guys, >>>>> >>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>> decoding them to a string. I wanted to know how i could write the >>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>> same string to a bytes and write them in binary format to disk, the >>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>> help me with this. >>>>> >>>>> >>>>> Regards, >>>>> Nav >>>> If by "decoding them to a string" you mean converting to Unicode, then >>>> you've already trashed the data. That's only valid if the bytes had >>>> been encoded from valid Unicode characters, and then only if you use >>>> the corresponding decoding technique. >>>> >>>> If you mean some other decoding, then the question is meaningless >>>> without telling us just what the decoding is, preferably with some code. >>>> >>>> It also might be useful to know what version of Python you're using, >>>> when you post the code. >>>> >>>> DaveA >>>> >>> >>> Dave, >>> >>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>> by the web browser over a socket, which looks like this: >>> >>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>> >>> From the above, I need to: >>> >>> a) Split the header content from the image content, which comes after >>> the keep-alive\r\n\r\n part >>> >>> b) Then write the image content to file for further use as a jpeg. >>> >> Try: >> >> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >> open(image_path, 'wb').write(image) >> -- >> http://mail.python.org/mailman/listinfo/python-list > > I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). > > @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes > All i can say is that it works for me: >>> header = b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>> image b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' What error did you get? From navkirats at gmail.com Thu Aug 26 17:25:38 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:55:38 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <67C524B2-53CB-4E38-BA33-CF3999089CF2@gmail.com> On 27-Aug-2010, at 2:40 AM, Robert Kern wrote: > On 8/26/10 3:47 PM, Navkirat Singh wrote: >> >> On 27-Aug-2010, at 1:57 AM, MRAB wrote: >> >>> On 26/08/2010 21:14, Navkirat Singh wrote: >>>> >>>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>>> >>>>> Navkirat Singh wrote: >>>>>> Hey guys, >>>>>> >>>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>>> decoding them to a string. I wanted to know how i could write the >>>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>>> same string to a bytes and write them in binary format to disk, the >>>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>>> help me with this. >>>>>> >>>>>> >>>>>> Regards, >>>>>> Nav >>>>> If by "decoding them to a string" you mean converting to Unicode, then >>>>> you've already trashed the data. That's only valid if the bytes had >>>>> been encoded from valid Unicode characters, and then only if you use >>>>> the corresponding decoding technique. >>>>> >>>>> If you mean some other decoding, then the question is meaningless >>>>> without telling us just what the decoding is, preferably with some code. >>>>> >>>>> It also might be useful to know what version of Python you're using, >>>>> when you post the code. >>>>> >>>>> DaveA >>>>> >>>> >>>> Dave, >>>> >>>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>>> by the web browser over a socket, which looks like this: >>>> >>>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>>> >>>> From the above, I need to: >>>> >>>> a) Split the header content from the image content, which comes after >>>> the keep-alive\r\n\r\n part >>>> >>>> b) Then write the image content to file for further use as a jpeg. >>>> >>> Try: >>> >>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>> open(image_path, 'wb').write(image) >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). >> >> @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes > > This is incorrect. > > Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) > [GCC 4.0.1 (Apple Inc. build 5493)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > > >>> bytes = b'Connection: keep-alive\r\n\r\nbody' > >>> bytes.split(b'\r\n\r\n', 1)[-1] > b'body' > > > FYI: the JPEG data is not in the header. The b'\r\n\r\n' sequence delimits the header from the body. Do not rely on "Connection: keep-alive" being the last header. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks Everyone, @Robert - Thanks a lot for your time :-) , I did know that the body starts after the occurrence two CRLF sequences, but I was following RFC2616 as a guide, which specifically mentions: "The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer- Encoding header field in the request?s message-headers" Which has not been done by the author of the library, hence I said what I did. Or I have misunderstood the RFC Regards, Nav -------------- next part -------------- An HTML attachment was scrubbed... URL: From navkirats at gmail.com Thu Aug 26 17:28:08 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:58:08 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76DA22.7030404@mrabarnett.plus.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 2:48 AM, MRAB wrote: > On 26/08/2010 21:47, Navkirat Singh wrote: >> >> On 27-Aug-2010, at 1:57 AM, MRAB wrote: >> >>> On 26/08/2010 21:14, Navkirat Singh wrote: >>>> >>>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>>> >>>>> Navkirat Singh wrote: >>>>>> Hey guys, >>>>>> >>>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>>> decoding them to a string. I wanted to know how i could write the >>>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>>> same string to a bytes and write them in binary format to disk, the >>>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>>> help me with this. >>>>>> >>>>>> >>>>>> Regards, >>>>>> Nav >>>>> If by "decoding them to a string" you mean converting to Unicode, then >>>>> you've already trashed the data. That's only valid if the bytes had >>>>> been encoded from valid Unicode characters, and then only if you use >>>>> the corresponding decoding technique. >>>>> >>>>> If you mean some other decoding, then the question is meaningless >>>>> without telling us just what the decoding is, preferably with some code. >>>>> >>>>> It also might be useful to know what version of Python you're using, >>>>> when you post the code. >>>>> >>>>> DaveA >>>>> >>>> >>>> Dave, >>>> >>>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>>> by the web browser over a socket, which looks like this: >>>> >>>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>>> >>>> From the above, I need to: >>>> >>>> a) Split the header content from the image content, which comes after >>>> the keep-alive\r\n\r\n part >>>> >>>> b) Then write the image content to file for further use as a jpeg. >>>> >>> Try: >>> >>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>> open(image_path, 'wb').write(image) >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). >> >> @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes >> > All i can say is that it works for me: > > >>> header = b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' > >>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] > >>> image > b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' > > What error did you get? > -- > http://mail.python.org/mailman/listinfo/python-list Hi MRAB, Here is the error: >>> b = b'asdf' >>> type(b) >>> s = b.split(':') Traceback (most recent call last): File "", line 1, in TypeError: Type str doesn't support the buffer API >>> From robert.kern at gmail.com Thu Aug 26 17:32:17 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:32:17 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 8/26/10 4:17 PM, Navkirat Singh wrote: > Here is what I needed to do: > > a) Separate image content from header content of the byte stream received from the web browser. > b) Save the image content to disk for further use. > > Here is what I did. Following is just a snippet: > > > #-------------HERE IS WHERE I RECEIVE THE DATA > while True: > buff = socket.recv(8192) > byteStr +=buff > if not buff: break > #--------------ENCODING/DECODING STARTS FROM HERE (since I want to use split/partition functions to separate header content from the image content) > strMsg = byteStr.decode("ISO-8859-1") > listMsg = strMsg.split('\r\n') > #---------------------------- > # do some more processing to search the list for the image content, say supposing index is 11 > #--------------------------- > imageStr = listMsg[11].encode("ISO-8859-1") #Transform the byte string just the way I found it If your JPEG happens to contain the bytes \r\n, then this will not work. Please follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 argument to make sure that you do not split on spurious b'\r\n\r\n' sequences inside the JPEG body. Do not decode the bytes. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Thu Aug 26 17:34:34 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:34:34 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <67C524B2-53CB-4E38-BA33-CF3999089CF2@gmail.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <67C524B2-53CB-4E38-BA33-CF3999089CF2@gmail.com> Message-ID: On 8/26/10 4:25 PM, Navkirat Singh wrote: > @Robert - Thanks a lot for your time :-) , I did know that the body starts after > the occurrence two CRLF sequences, but I was following RFC2616 as a guide, which > specifically mentions: > > "The presence of a message-body in a request is signaled by the inclusion of a > > Content-Length or Transfer- Encoding header field in the > > request?s message-headers" > > Which has not been done by the author of the library, hence I said what I did. > Or I have misunderstood the RFC It certainly looks like the data has a Content-length header: b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\n ... -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From navkirats at gmail.com Thu Aug 26 17:35:03 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 03:05:03 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 2:58 AM, Navkirat Singh wrote: > > On 27-Aug-2010, at 2:48 AM, MRAB wrote: > >> On 26/08/2010 21:47, Navkirat Singh wrote: >>> >>> On 27-Aug-2010, at 1:57 AM, MRAB wrote: >>> >>>> On 26/08/2010 21:14, Navkirat Singh wrote: >>>>> >>>>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>>>> >>>>>> Navkirat Singh wrote: >>>>>>> Hey guys, >>>>>>> >>>>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>>>> decoding them to a string. I wanted to know how i could write the >>>>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>>>> same string to a bytes and write them in binary format to disk, the >>>>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>>>> help me with this. >>>>>>> >>>>>>> >>>>>>> Regards, >>>>>>> Nav >>>>>> If by "decoding them to a string" you mean converting to Unicode, then >>>>>> you've already trashed the data. That's only valid if the bytes had >>>>>> been encoded from valid Unicode characters, and then only if you use >>>>>> the corresponding decoding technique. >>>>>> >>>>>> If you mean some other decoding, then the question is meaningless >>>>>> without telling us just what the decoding is, preferably with some code. >>>>>> >>>>>> It also might be useful to know what version of Python you're using, >>>>>> when you post the code. >>>>>> >>>>>> DaveA >>>>>> >>>>> >>>>> Dave, >>>>> >>>>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>>>> by the web browser over a socket, which looks like this: >>>>> >>>>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>>>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>>>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>>>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>>>> >>>>> From the above, I need to: >>>>> >>>>> a) Split the header content from the image content, which comes after >>>>> the keep-alive\r\n\r\n part >>>>> >>>>> b) Then write the image content to file for further use as a jpeg. >>>>> >>>> Try: >>>> >>>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>>> open(image_path, 'wb').write(image) >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>> >>> I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). >>> >>> @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes >>> >> All i can say is that it works for me: >> >>>>> header = b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >>>>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>>>> image >> b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >> >> What error did you get? >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Hi MRAB, > > Here is the error: > >>>> b = b'asdf' >>>> type(b) > >>>> s = b.split(':') > Traceback (most recent call last): > File "", line 1, in > TypeError: Type str doesn't support the buffer API >>>> > > I got your point The argument for the split I have give is a string, hence the error. From robert.kern at gmail.com Thu Aug 26 17:43:00 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:43:00 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: On 8/26/10 4:28 PM, Navkirat Singh wrote: > > On 27-Aug-2010, at 2:48 AM, MRAB wrote: > >> On 26/08/2010 21:47, Navkirat Singh wrote: >>> >>> On 27-Aug-2010, at 1:57 AM, MRAB wrote: >>> >>>> On 26/08/2010 21:14, Navkirat Singh wrote: >>>>> >>>>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>>>> >>>>>> Navkirat Singh wrote: >>>>>>> Hey guys, >>>>>>> >>>>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>>>> decoding them to a string. I wanted to know how i could write the >>>>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>>>> same string to a bytes and write them in binary format to disk, the >>>>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>>>> help me with this. >>>>>>> >>>>>>> >>>>>>> Regards, >>>>>>> Nav >>>>>> If by "decoding them to a string" you mean converting to Unicode, then >>>>>> you've already trashed the data. That's only valid if the bytes had >>>>>> been encoded from valid Unicode characters, and then only if you use >>>>>> the corresponding decoding technique. >>>>>> >>>>>> If you mean some other decoding, then the question is meaningless >>>>>> without telling us just what the decoding is, preferably with some code. >>>>>> >>>>>> It also might be useful to know what version of Python you're using, >>>>>> when you post the code. >>>>>> >>>>>> DaveA >>>>>> >>>>> >>>>> Dave, >>>>> >>>>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>>>> by the web browser over a socket, which looks like this: >>>>> >>>>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>>>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>>>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>>>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>>>> >>>>> From the above, I need to: >>>>> >>>>> a) Split the header content from the image content, which comes after >>>>> the keep-alive\r\n\r\n part >>>>> >>>>> b) Then write the image content to file for further use as a jpeg. >>>>> >>>> Try: >>>> >>>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>>> open(image_path, 'wb').write(image) >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>> >>> I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). >>> >>> @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes >>> >> All i can say is that it works for me: >> >>>>> header = b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >>>>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>>>> image >> b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >> >> What error did you get? >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Hi MRAB, > > Here is the error: > >>>> b = b'asdf' >>>> type(b) > >>>> s = b.split(':') > Traceback (most recent call last): > File "", line 1, in > TypeError: Type str doesn't support the buffer API >>>> Follow MRAB's example. You need to use a bytes object for the *argument*, too. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Thu Aug 26 17:45:04 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:45:04 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 8/26/10 4:17 PM, Navkirat Singh wrote: > #-------------HERE IS WHERE I RECEIVE THE DATA > while True: > buff = socket.recv(8192) > byteStr +=buff > if not buff: break Also, you probably shouldn't bother writing an HTTP server using raw sockets. Use HTTPServer instead: http://docs.python.org/py3k/library/http.server.html or better, wsgiref: http://docs.python.org/py3k/library/wsgiref.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From navkirats at gmail.com Thu Aug 26 17:48:56 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 03:18:56 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <9B50381E-AEA2-4573-BB6E-314DFB5B0DF6@gmail.com> On 27-Aug-2010, at 3:02 AM, Robert Kern wrote: > On 8/26/10 4:17 PM, Navkirat Singh wrote: > >> Here is what I needed to do: >> >> a) Separate image content from header content of the byte stream received from the web browser. >> b) Save the image content to disk for further use. >> >> Here is what I did. Following is just a snippet: >> >> >> #-------------HERE IS WHERE I RECEIVE THE DATA >> while True: >> buff = socket.recv(8192) >> byteStr +=buff >> if not buff: break >> #--------------ENCODING/DECODING STARTS FROM HERE (since I want to use split/partition functions to separate header content from the image content) >> strMsg = byteStr.decode("ISO-8859-1") >> listMsg = strMsg.split('\r\n') >> #---------------------------- >> # do some more processing to search the list for the image content, say supposing index is 11 >> #--------------------------- >> imageStr = listMsg[11].encode("ISO-8859-1") #Transform the byte string just the way I found it > > If your JPEG happens to contain the bytes \r\n, then this will not work. Please follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 argument to make sure that you do not split on spurious b'\r\n\r\n' sequences inside the JPEG body. Do not decode the bytes. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks Robert, My method worked too, I was able to do the above and save the jpeg flawlessly, but your method seems better as I will not have to take the extra step of encoding/decoding. From navkirats at gmail.com Thu Aug 26 17:51:49 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 03:21:49 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <67C524B2-53CB-4E38-BA33-CF3999089CF2@gmail.com> Message-ID: <27CFAC22-56FD-43BA-80F1-15041A46F779@gmail.com> On 27-Aug-2010, at 3:04 AM, Robert Kern wrote: > On 8/26/10 4:25 PM, Navkirat Singh wrote: > >> @Robert - Thanks a lot for your time :-) , I did know that the body starts after >> the occurrence two CRLF sequences, but I was following RFC2616 as a guide, which >> specifically mentions: >> >> "The presence of a message-body in a request is signaled by the inclusion of a >> >> Content-Length or Transfer- Encoding header field in the >> >> request?s message-headers" >> >> Which has not been done by the author of the library, hence I said what I did. >> Or I have misunderstood the RFC > > It certainly looks like the data has a Content-length header: > > b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\n > ... > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list Once again you opened my eyes, I think its been a tough night for me. Seeing too much and nothing at the same time. Regards From navkirats at gmail.com Thu Aug 26 18:18:07 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 03:48:07 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 3:15 AM, Robert Kern wrote: > On 8/26/10 4:17 PM, Navkirat Singh wrote: > >> #-------------HERE IS WHERE I RECEIVE THE DATA >> while True: >> buff = socket.recv(8192) >> byteStr +=buff >> if not buff: break > > Also, you probably shouldn't bother writing an HTTP server using raw sockets. Use HTTPServer instead: > > http://docs.python.org/py3k/library/http.server.html > > or better, wsgiref: > > http://docs.python.org/py3k/library/wsgiref.html > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks a lot guys, you all have been a lot of help !! From thomas at jollybox.de Thu Aug 26 18:22:36 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 27 Aug 2010 00:22:36 +0200 Subject: Python Editor or IDE ActiveX control In-Reply-To: References: Message-ID: <201008270022.37040.thomas@jollybox.de> On Thursday 26 August 2010, it occurred to Sathish S to exclaim: > Hi Ppl, > > Is there any python IDE or editor that has an ActiveX control which could > be embed in other Windows applications. I'm basically looking to write a > application that can show the indentations of python, change the color of > keywords etc on a application, which will save this python script and run > it from command prompt. It sounds to me like you're just looking for any old halfway decent embeddable programmer's editor that happens to have syntax definitions for Python. I'd suggest you have a look at Scintilla. Quite a good editing control, I don't think it comes wrapped in ActiveX or anything like that, just interface it in your favourite language using the DLL's C API. From tjreedy at udel.edu Thu Aug 26 18:53:08 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Aug 2010 18:53:08 -0400 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: On 8/26/2010 5:28 PM, Navkirat Singh wrote: >>>> b = b'asdf' >>>> type(b) > >>>> s = b.split(':') You are trying to split bytes with a string, which is impossible. Split bytes with bytes, strings with strings. > Traceback (most recent call last): > File "", line 1, in > TypeError: Type str doesn't support the buffer API -- Terry Jan Reedy From navkirats at gmail.com Thu Aug 26 18:57:57 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 04:27:57 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: <820C2670-61F1-4587-8ACA-189FC78EC61A@gmail.com> On 27-Aug-2010, at 4:23 AM, Terry Reedy wrote: > On 8/26/2010 5:28 PM, Navkirat Singh wrote: > >>>>> b = b'asdf' >>>>> type(b) >> >>>>> s = b.split(':') > > You are trying to split bytes with a string, which is impossible. > Split bytes with bytes, strings with strings. > >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: Type str doesn't support the buffer API > > > -- > Terry Jan Reedy > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks ! From stef.mientki at gmail.com Thu Aug 26 19:17:34 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 27 Aug 2010 01:17:34 +0200 Subject: Python Editor or IDE ActiveX control In-Reply-To: <201008270022.37040.thomas@jollybox.de> References: <201008270022.37040.thomas@jollybox.de> Message-ID: <4C76F60E.9090708@gmail.com> On 27-08-2010 00:22, Thomas Jollans wrote: > On Thursday 26 August 2010, it occurred to Sathish S to exclaim: >> Hi Ppl, >> >> Is there any python IDE or editor that has an ActiveX control which could >> be embed in other Windows applications. I'm basically looking to write a >> application that can show the indentations of python, change the color of >> keywords etc on a application, which will save this python script and run >> it from command prompt. > It sounds to me like you're just looking for any old halfway decent embeddable > programmer's editor that happens to have syntax definitions for Python. > > I'd suggest you have a look at Scintilla. Quite a good editing control, I > don't think it comes wrapped in ActiveX or anything like that, just interface > it in your favourite language using the DLL's C API. Scintilla is full embedded in wxPython. cheers, Stef From joshua.r.english at gmail.com Thu Aug 26 19:30:46 2010 From: joshua.r.english at gmail.com (Josh English) Date: Thu, 26 Aug 2010 16:30:46 -0700 (PDT) Subject: pyxser-1.5r --- Python Object to XML serializer/deserializer References: Message-ID: <72aa2291-d979-4deb-9e9b-147af2c9d0af@b4g2000pra.googlegroups.com> It looks nice, but it's a shame it doesn't work on Windows. This could solve a lot of the problems I'm running into in my own attempt to build a python Class implementation of an XML Validation object. From cliff.martin at gmail.com Thu Aug 26 23:08:42 2010 From: cliff.martin at gmail.com (Cliff Martin) Date: Thu, 26 Aug 2010 20:08:42 -0700 (PDT) Subject: Trouble importing cx_Oracle on HPUX Message-ID: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> I have just gotten done building Python 3.1.2 on HPUX 11.31 Itanium (IA64) using gcc 4.4.3, and have tried building cx_Oracle to go with it. The build succeeds, but test and importing does not. I have tried building Python with threads and without. The only exotic thing I do with the configure for python is to supply -mlp64, which makes it a 64 bit build. Python 3 appears to work just fine, and cx_Oracle has worked on this same architecture in the past with Python 2.6.5. Help! I would really like to use Python 3, but Oracle support is a requirement. Everything I've read indicates it should work, but there is not a lot of people doing this or posting notes about their install problems or successes on HP-UX. Cliff From stefan_ml at behnel.de Fri Aug 27 01:02:03 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 27 Aug 2010 07:02:03 +0200 Subject: pyxser-1.5r --- Python Object to XML serializer/deserializer In-Reply-To: <72aa2291-d979-4deb-9e9b-147af2c9d0af@b4g2000pra.googlegroups.com> References: <72aa2291-d979-4deb-9e9b-147af2c9d0af@b4g2000pra.googlegroups.com> Message-ID: Josh English, 27.08.2010 01:30: > solve a lot of the problems I'm running into in my own attempt to > build a python Class implementation of an XML Validation object. How would object serialisation help here? Stefan From yooots2 at gmail.com Fri Aug 27 01:38:05 2010 From: yooots2 at gmail.com (yooots) Date: Thu, 26 Aug 2010 22:38:05 -0700 (PDT) Subject: ipad Message-ID: <6c99818e-9daa-4b58-bf76-dabfe784c195@s17g2000prh.googlegroups.com> I was in a foreign trade company in New York, a sales manager. Because I often need to travel, a powerful laptop for me is essential. However, the computers I used before can not satisfy my request in many ways. However, I recently ordered an ipad online. I really feel the prompt wireless Internet access speed, and the easy controlling. What?s more ,it?s cheap .So I want to share the experience with you, my friends. Terms of quality, iPad is a new type of computer, can be run through a simple interface similar to PC's complex software, large screen, it also brings more. But iPad is a new type of computer, only after the full experience and use, ,you can feel it is so convenient. Terms of powerful e-book function, the iPad make a modern discovery, iBook software in the App Store is also a free download through the free software now, and as if I carry a small library daily with updated best-selling book, making my reading full offun. Also read the file is quite easy! When I get iPad, first of all want to do is browse the web, and check whether the virtual keyboard easy to use. In the new iPad screen, I like the site has a good display. iPad's screen is 9.7 inches, while the iPhone is only 3.5 inches. The iPad the wide side facing down will go to landscape mode, the larger screen more convenient typing. I use Facebook and other web page, select the picture or article for browsing, but very comfortable! In the video, and photo area, iPad's performance is very good. I can watch HD video in YouTube, zoom mode is also very clear. Browse pictures is also very easy .Slideshow is also very good to meet my work requirements, built-in speaker can also play background music. IPad's music player interface is simple and very convenient to use. In particular, I think that reading better when the reading with the iPad. Simple and comfortable, full of fun, so I experience the multi- use benefits. Game features: iPad can run all the App Store process. While waiting for the metro I can play my favorite Need for Speed and MIB.COM so I experienced the powerful entertainment features of ipad. In the spare time I enjoy the short game fun! On the electronic map function, ipad has a strong electronic map function, when I drove away in a strange neighborhood, I will not need the help of GPS, a ipad can save a lot of extra cost! It provided me with many other applications also! All in all, ipad has its own value, carry on business when deal in the PPT, read e-books, search in the wireless network information, check maps and other applications, will demonstrate the advantages of more convenient. Ipad used, I have love it up. I will not use the other laptop, since they can not meet the needs of my operation, and www.Yooots.com company provided me with very good after-sales service . Cheap prices, high quality service, so I'm very satisfied ! From enleverLesX_XXmcX at XmclavXeauX.com.invalid Fri Aug 27 01:55:11 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Fri, 27 Aug 2010 07:55:11 +0200 Subject: Python Editor or IDE ActiveX control References: Message-ID: <4c775348$0$5428$ba4acef3@reader.news.orange.fr> Hi! Scintilla come like a "control" (a piece for a window), raleted to the file SciLexer.DLL For call the scintilla-componant, use "messages". Example : SendMessage(Sci, SCI_GOTOLINE, line, 0) For the constant SCI_GOTOLINE, I suggest scintillacon.py, include in Pywin32. @-salutations -- Michel Claveau From bryanjugglercryptographer at yahoo.com Fri Aug 27 02:56:26 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Thu, 26 Aug 2010 23:56:26 -0700 (PDT) Subject: Writing byte stream as jpeg format to disk References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <6dd639c4-f5e0-4df8-8816-9cad28ae2460@q40g2000prg.googlegroups.com> Robert Kern wrote: > Please > follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 argument to > make sure that you do not split on spurious b'\r\n\r\n' sequences inside the > JPEG body. Do not decode the bytes. Correct, and I'll add that this is a case where we might want to be better than correct. BaseHTTPRequestHandler in the Python standard library accommodates clients that incorrectly omit the '\r' and end header lines with just '\n'. Such apps have been seen in the wild. Since bare '\n' never appears in correctly formed HTTP headers, interpreting it as equivalent to '\r\n' doesn't break anything. The re module offers a split that does what we want. import re boundary_re = re.compile(br'\r?\n\r?\n') then you can use: (headers, content) = boundary_re.split(rawdata, 1) I like Robert's suggestion to use the HTTP server or wsgiref in the Python library. There's significant arcane wisdom programmed in already. From rami.chowdhury at merton.oxon.org Fri Aug 27 03:28:46 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Fri, 27 Aug 2010 13:28:46 +0600 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: On Wed, Aug 25, 2010 at 05:04, Lawrence D'Oliveiro wrote: > In message , Nobody wrote: > >> Having this as a separate permission allows normal users to add entries to >> log files but not to erase existing entries. > > Unix/Linux systems can do this already. Ooh, I didn't know that -- what combination of permissions would I have to use to get such an effect? -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From nobody at nowhere.com Fri Aug 27 04:16:49 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 27 Aug 2010 09:16:49 +0100 Subject: Reading the access attributes of directories in Windows References: Message-ID: On Fri, 27 Aug 2010 13:28:46 +0600, Rami Chowdhury wrote: >>> Having this as a separate permission allows normal users to add entries >>> to log files but not to erase existing entries. >> >> Unix/Linux systems can do this already. > > Ooh, I didn't know that -- what combination of permissions would I have to > use to get such an effect? You can't do it with permissions, you need to use ext2 attributes. Specifically, "chattr +a " will set the "append" attribute, which prevents the file being opened for write except in append mode. Changing this attribute requires root privilege or the CAP_LINUX_IMMUTABLE capability. From nobody at nowhere.com Fri Aug 27 04:30:37 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 27 Aug 2010 09:30:37 +0100 Subject: Writing byte stream as jpeg format to disk References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <6dd639c4-f5e0-4df8-8816-9cad28ae2460@q40g2000prg.googlegroups.com> Message-ID: On Thu, 26 Aug 2010 23:56:26 -0700, Bryan wrote: >> follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 >> argument to make sure that you do not split on spurious b'\r\n\r\n' >> sequences inside the JPEG body. Do not decode the bytes. > > Correct, and I'll add that this is a case where we might want to be better > than correct. BaseHTTPRequestHandler in the Python standard library > accommodates clients that incorrectly omit the '\r' and end header lines > with just '\n'. Such apps have been seen in the wild. Since bare '\n' > never appears in correctly formed HTTP headers, interpreting it as > equivalent to '\r\n' doesn't break anything. Yes it does. It breaks upstream filtering rules which are intended to prohibit, remove or modify certain headers. This class of attack is known as "HTTP request smuggling". By appending a header preceded by a bare '\r' or '\n' to the end of another header, the header can be "smuggled" past a filter which parses headers using the correct syntax, but will still be treated as a header by software which incorrectly parses headers using bare '\r' or '\n' as separators. The safest solution would be to simply reject any request (or response) which contains bare '\r' or '\n' characters within headers, at least by default. Force the programmer to read the documentation (where the risks would be described) if they want the "fault tolerant" behaviour. From raoulbia at gmail.com Fri Aug 27 04:53:17 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 27 Aug 2010 01:53:17 -0700 (PDT) Subject: palindrome iteration Message-ID: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> level: beginner the following code looks ok to me but it doesn't work. I would like some hints as to where my reasoning / thought goes wrong def i_palindrome(pal): while len(pal)>1: if pal[0] == pal[-1]: pal=pal[1:-1] return True print i_palindrome('annab') my reasoning: - i check the length of the string: if > 1 continue - i check first and last char: if they are equal continue - create a new, shorter string starting at index 1 and ending at second last index (up to but not including index-1 -restart the while loop as long as length of string is > 1 - exiting this loop means all compared chars were identical hence it is a palindrome and i return True tnx Baba From contact at xavierho.com Fri Aug 27 05:03:35 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 27 Aug 2010 19:03:35 +1000 Subject: palindrome iteration In-Reply-To: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: One possible reason I can think of - "- exiting this loop means all compared chars were identical hence it is a palindrome and i return True" is probably incorrect reasoning. Think again. Also, you may consider posting your code in a way that preserves the whitespace characters. Cheers, Xav On 27 August 2010 18:53, Baba wrote: > level: beginner > > the following code looks ok to me but it doesn't work. I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] > return True > > print i_palindrome('annab') > > > my reasoning: > - i check the length of the string: if > 1 continue > - i check first and last char: if they are equal continue > - create a new, shorter string starting at index 1 and ending at > second last index (up to but not including index-1 > -restart the while loop as long as length of string is > 1 > - exiting this loop means all compared chars were identical hence it > is a palindrome and i return True > > tnx > Baba > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Aug 27 05:33:15 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Aug 2010 11:33:15 +0200 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Baba wrote: > level: beginner > > the following code looks ok to me but it doesn't work. I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] > return True Do yourself a favour and use 4-space indent. That makes the structure of your code more obvious. > print i_palindrome('annab') > > > my reasoning: > - i check the length of the string: if > 1 continue > - i check first and last char: if they are equal continue > - create a new, shorter string starting at index 1 and ending at > second last index (up to but not including index-1 > -restart the while loop as long as length of string is > 1 > - exiting this loop means all compared chars were identical hence it > is a palindrome and i return True If the test pal[0] == pal[-1] fails, i. e. the two compared characters differ, what happens? More generally, if pal is not a palindrome, can your function ever return False? If not, at what point should it? Peter From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 27 05:52:08 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Aug 2010 11:52:08 +0200 Subject: palindrome iteration In-Reply-To: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4c778ab6$0$4778$426a74cc@news.free.fr> Baba a ?crit : > level: beginner > > the following code looks ok to me but it doesn't work. "doesn't work" is about the most useless description of a problem. Please specify what you expected and what actually happens. > I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] Can you explain what happens if pal[0] != pal[-1] ? (answer below) > return True > print i_palindrome('annab') And then you go in an infinite loop !-) > > my reasoning: > - i check the length of the string: if > 1 continue > - i check first and last char: if they are equal continue > - create a new, shorter string starting at index 1 and ending at > second last index (up to but not including index-1 > -restart the while loop as long as length of string is > 1 > - exiting this loop means all compared chars were identical hence it > is a palindrome and i return True Your problem is that when first and last char are not equal, you don't exit the while loop. You need a "return False" somewhere here, ie: def is_palindrom(pal): while len(pal)>1: # NB : inverted the test here to make exit more obvious if pal[0] != pal[-1]: return False pal=pal[1:-1] return True Now there is another solution. A palindrom is made of two symetric halves, with (odd len) or without (even len) a single char between the symetric halves, ie : * odd : ABCBA ('AB' + 'C' + 'BA') * even : ABCCBA ('ABC' + 'CBA') So you just have to extract the symetric halves, reverse one, and compare both (case insensitive compare while we're at it). Here's a possible (and a bit tricky) Python 2.x implementation: def is_palindrom(s): s = s.lower() slen = len(s) until = slen / 2 # Python 2x integer division offset = int(not(slen % 2)) runtil = until - offset return s[0:until] == s[-1:runtil:-1] From arts.richard at gmail.com Fri Aug 27 06:40:01 2010 From: arts.richard at gmail.com (Richard Arts) Date: Fri, 27 Aug 2010 12:40:01 +0200 Subject: palindrome iteration In-Reply-To: <4c778ab6$0$4778$426a74cc@news.free.fr> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: > Now there is another solution. A palindrom is made of two symetric halves, > with (odd len) or without (even len) a single char between the symetric > halves, ie : > > * odd : ABCBA ('AB' + 'C' + 'BA') > * even : ABCCBA ('ABC' + 'CBA') > > So you just have to extract the symetric halves, reverse one, and compare > both (case insensitive compare while we're at it). Yes, this is a correct observation, but it is not necessary to compare the halves; Simply compare the complete string with its reverse. If they match, it is a palindrome. > Here's a possible (and a > bit tricky) Python 2.x implementation: > > def is_palindrom(s): > ? ?s = s.lower() > ? ?slen = len(s) > ? ?until = slen / 2 # Python 2x integer division > ? ?offset = int(not(slen % 2)) > ? ?runtil = until - offset > ? ?return s[0:until] == s[-1:runtil:-1] > > At first glance this seems to be correct, but it is tricky indeed. Particularly the assignment of the offset variable, casting a bool to an integer of a negated expression. Given that Baba notes that this is a beginners level query, it wouldn't have hurt to be a little bit more verbose there. Richard From stephan0h at yahoo.de Fri Aug 27 07:23:36 2010 From: stephan0h at yahoo.de (steph) Date: Fri, 27 Aug 2010 04:23:36 -0700 (PDT) Subject: pil and reportlab: image compression References: <0e89301b-2cb3-42fe-ba24-4018b5343c4d@v41g2000yqv.googlegroups.com> Message-ID: On 26 Aug., 13:16, steph wrote: > Hi group, > > I've written a small application that puts images into a pdf document. > It works ok, but my problem is that the pdf-files become quite huge, > bigger than the original jpegs. The problem seems to arise because I > use PIL to resize the pictures - and the images seem to get > uncompressed in the process. Unfortunately I have not found a way to > compress them again before rendering them to the pdf. Any clues? > > Thanks, > Stephan Solved this by writung to anonymous mmap. Works nicely :-) From landimatte at gmail.com Fri Aug 27 07:43:16 2010 From: landimatte at gmail.com (Matteo Landi) Date: Fri, 27 Aug 2010 13:43:16 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: > Yes, this is a correct observation, but it is not necessary to compare > the halves; Simply compare the complete string with its reverse. If > they match, it is a palindrome. I've always used to implement the is_palindrome function as you suggest, i.e. comparing the original string with the reverse one, but while reading, I tought about a imho nicer version which prevent from creating another string. Here are both the recursive/iterative versions of the function: def palindrome(str, i=0, j=-1): try: if str[i] == str[j]: return palindrome(str, i + 1, j - 1) return False except IndexError: return True def palindrome(str, i=0, j=-1): try: while True: if str[i] != str[j]: return False i, j = i + 1, j - 1 return True except IndexError: return True Regards, Matteo > >> Here's a possible (and a >> bit tricky) Python 2.x implementation: >> >> def is_palindrom(s): >> ? ?s = s.lower() >> ? ?slen = len(s) >> ? ?until = slen / 2 # Python 2x integer division >> ? ?offset = int(not(slen % 2)) >> ? ?runtil = until - offset >> ? ?return s[0:until] == s[-1:runtil:-1] >> >> > > At first glance this seems to be correct, but it is tricky indeed. > Particularly the assignment of the offset variable, casting a bool to > an integer of a negated expression. Given that Baba notes that this is > a beginners level query, it wouldn't have hurt to be a little bit more > verbose there. > > Richard > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From davea at ieee.org Fri Aug 27 09:14:02 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 27 Aug 2010 09:14:02 -0400 Subject: palindrome iteration In-Reply-To: <4c778ab6$0$4778$426a74cc@news.free.fr> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: <4C77BA1A.4040601@ieee.org> Bruno Desthuilliers wrote: >
Baba a > ?crit : >> level: beginner >> >> the following code looks ok to me but it doesn't work. > > "doesn't work" is about the most useless description of a problem. > Please specify what you expected and what actually happens. > >> I would like >> some hints as to where my reasoning / thought goes wrong >> >> def i_palindrome(pal): >> while len(pal)>1: >> if pal[0] == pal[-1]: >> pal=pal[1:-1] > > Can you explain what happens if pal[0] != pal[-1] ? (answer below) > >> return True > >> print i_palindrome('annab') > > And then you go in an infinite loop !-) > >> >> my reasoning: >> - i check the length of the string: if > 1 continue >> - i check first and last char: if they are equal continue >> - create a new, shorter string starting at index 1 and ending at >> second last index (up to but not including index-1 >> -restart the while loop as long as length of string is > 1 >> - exiting this loop means all compared chars were identical hence it >> is a palindrome and i return True > > Your problem is that when first and last char are not equal, you don't > exit the while loop. You need a "return False" somewhere here, ie: > > def is_palindrom(pal): > while len(pal)>1: > # NB : inverted the test here to make exit more obvious > if pal[0] != pal[-1]: > return False > pal=pal[1:-1] > return True > > > Now there is another solution. A palindrom is made of two symetric > halves, with (odd len) or without (even len) a single char between the > symetric halves, ie : > > * odd : ABCBA ('AB' + 'C' + 'BA') > * even : ABCCBA ('ABC' + 'CBA') > > So you just have to extract the symetric halves, reverse one, and > compare both (case insensitive compare while we're at it). Here's a > possible (and a bit tricky) Python 2.x implementation: > > def is_palindrom(s): > s = s.lower() > slen = len(s) > until = slen / 2 # Python 2x integer division > offset = int(not(slen % 2)) > runtil = until - offset > return s[0:until] == s[-1:runtil:-1] > > or (untested) def is_palindrom(s): s = s.lower() return s == s[::-1] DaveA From bryanjugglercryptographer at yahoo.com Fri Aug 27 09:53:30 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Fri, 27 Aug 2010 06:53:30 -0700 (PDT) Subject: Writing byte stream as jpeg format to disk References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <6dd639c4-f5e0-4df8-8816-9cad28ae2460@q40g2000prg.googlegroups.com> Message-ID: <09ef926c-6622-41c3-a303-f33782f087fe@u4g2000prn.googlegroups.com> Nobody wrote: > Bryan wrote: > > this is a case where we might want to be better > > than correct. BaseHTTPRequestHandler in the Python standard library > > accommodates clients that incorrectly omit the '\r' and end header lines > > with just '\n'. Such apps have been seen in the wild. Since bare '\n' > > never appears in correctly formed HTTP headers, interpreting it as > > equivalent to '\r\n' doesn't break anything. > > Yes it does. It breaks upstream filtering rules which are intended to > prohibit, remove or modify certain headers. > > This class of attack is known as "HTTP request smuggling". By > appending a header preceded by a bare '\r' or '\n' to the end of > another header, the header can be "smuggled" past a filter which > parses headers using the correct syntax, How does a bare '\r' or '\n' get past a filter which parses headers using the correct syntax? I don't see where the correct syntax of the HTTP protocol allows that. > but will still be treated as a > header by software which incorrectly parses headers using bare '\r' or > '\n' as separators. Why blame software that incorrectly accepts '\n' as a line break, and not the filter that incorrectly accepted '\n' in the middle of a header? Both are accepting incorrect syntax, but only the former has good reason to do so. > The safest solution would be to simply reject any request (or response) > which contains bare '\r' or '\n' characters within headers, at least by > default. Force the programmer to read the documentation (where the risks > would be described) if they want the "fault tolerant" behaviour. The Internet has a tradition of protocols above the transport level being readable by eye and writable by hand. The result has been quick development, but many mistakes that can induce unforeseen consequences. This case is somewhat subtle. Within a text entity-body, HTTP allows any one of the three end-of-line delimiters. That's just the body; the header portion is more rigid. In HTTP 1.0: "This flexibility regarding line breaks applies only to text media in the Entity-Body; a bare CR or LF should not be substituted for CRLF within any of the HTTP control structures (such as header fields and multipart boundaries)." -- RFC 1945 While in HTTP 1.1: "This flexibility regarding line breaks applies only to text media in the entity-body; a bare CR or LF MUST NOT be substituted for CRLF within any of the HTTP control structures (such as header fields and multipart boundaries)." -- RFC 2616 Note the change from "should not" to "MUST NOT". In reality our code might be called upon to work with apps that botch the technically- correct HTTP end-of-line marker. Rejecting bare '\n' may be safe from a technical security perspective, but if our safe code breaks a previously working system, then it will appear in a bug database and not in production. 'Nobody' makes a fair point. I'd love to see Internet protocols defined with mechanical rigor. Our discipline commonly specifies programming language syntax formally, and Internet protocols are syntactically simpler than programming languages. For now, HTTP is a bit of a mess, so write it absolutely correctly but read it a bit flexibly. From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 27 10:41:28 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Aug 2010 16:41:28 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: <4c77ce84$0$20290$426a74cc@news.free.fr> Richard Arts a ?crit : >> Now there is another solution. A palindrom is made of two symetric halves, >> with (odd len) or without (even len) a single char between the symetric >> halves, ie : >> >> * odd : ABCBA ('AB' + 'C' + 'BA') >> * even : ABCCBA ('ABC' + 'CBA') >> >> So you just have to extract the symetric halves, reverse one, and compare >> both (case insensitive compare while we're at it). > > Yes, this is a correct observation, but it is not necessary to compare > the halves; Simply compare the complete string with its reverse. If > they match, it is a palindrome. Duh :( I kinda feel stupid right now, thanks Richard :-/ From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 27 10:43:16 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Aug 2010 16:43:16 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: <4c77cef1$0$20290$426a74cc@news.free.fr> Dave Angel a ?crit : (snip) > or (untested) > def is_palindrom(s): > s = s.lower() > return s == s[::-1] > Right, go on, make me feel a bit more stupid :-/ Who's next ? From aahz at pythoncraft.com Fri Aug 27 11:03:53 2010 From: aahz at pythoncraft.com (Aahz) Date: 27 Aug 2010 08:03:53 -0700 Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: In article <2dd74ab4-5ed6-40ac-aea7-705977b61b21 at g21g2000prn.googlegroups.com>, fuglyducky wrote: > >I am a complete newbie to Python (and programming in general) and I >have no idea what I'm missing. Below is a script that I am trying to >work with and I cannot get it to work. Side note: while it's fine to ask newbie questions on comp.lang.python, you may want to use resources oriented more toward newbies, such as the tutor list: http://www.python.org/about/help/ http://www.python.org/mailman/listinfo/tutor -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From darcy at druid.net Fri Aug 27 11:49:42 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 27 Aug 2010 11:49:42 -0400 Subject: palindrome iteration In-Reply-To: <4c77cef1$0$20290$426a74cc@news.free.fr> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> Message-ID: <20100827114942.0b1210cd.darcy@druid.net> On Fri, 27 Aug 2010 16:43:16 +0200 Bruno Desthuilliers wrote: > Dave Angel a ?crit : > > def is_palindrom(s): > > s = s.lower() > > return s == s[::-1] > > > Right, go on, make me feel a bit more stupid :-/ > Who's next ? How about a one-liner? is_palindrome = lambda x: len(x)> 0 and x == x.lower()[::-1] Note that the above assumes that single characters are palindromes but empty strings are not. I'm not 100% sure that that last is true. If not then this can be simplified. is_palindrome = lambda x: x == x.lower()[::-1] -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Fri Aug 27 12:02:39 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 27 Aug 2010 12:02:39 -0400 Subject: palindrome iteration In-Reply-To: <20100827114942.0b1210cd.darcy@druid.net> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> <20100827114942.0b1210cd.darcy@druid.net> Message-ID: <20100827120239.5a0b2396.darcy@druid.net> On Fri, 27 Aug 2010 11:49:42 -0400 "D'Arcy J.M. Cain" wrote: > is_palindrome = lambda x: x == x.lower()[::-1] Oops. Simple and wrong. is_palindrome = lambda x: x.lower() == x.lower()[::-1] -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From aahz at pythoncraft.com Fri Aug 27 12:16:52 2010 From: aahz at pythoncraft.com (Aahz) Date: 27 Aug 2010 09:16:52 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: In article , MRAB wrote: > >An object will be available for garbage collection when nothing refers >to it either directly or indirectly. If it's unreferenced then it will >go away. This isn't actually garbage collection as most people think of it. Refcounting semantics mean that objects get reaped as soon as nothing points at them. OTOH, CPython does also have garbage collection to back up refcounting so that when you have unreferenced object cycles they don't stay around. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From breamoreboy at yahoo.co.uk Fri Aug 27 12:20:30 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 27 Aug 2010 17:20:30 +0100 Subject: palindrome iteration In-Reply-To: <4c77cef1$0$20290$426a74cc@news.free.fr> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> Message-ID: On 27/08/2010 15:43, Bruno Desthuilliers wrote: > Dave Angel a ?crit : > (snip) > >> or (untested) >> def is_palindrom(s): >> s = s.lower() >> return s == s[::-1] >> > > > Right, go on, make me feel a bit more stupid :-/ > Who's next ? It could be worse, try responding to issue 9702. :) Cheers. Mark Lawrence. From ms18817 at googlemail.com Fri Aug 27 12:28:21 2010 From: ms18817 at googlemail.com (marianne rosen) Date: Fri, 27 Aug 2010 09:28:21 -0700 (PDT) Subject: layer geld verdienen , leicht geldverdienen , wie kann ich onlinespiele geld gewinnen , geldgewinnspiele , zu geld machen , geld machen beim , pennergame geld verdienen , schnell geld vedienen , ohne geld online , geld mit online casino , * * * + Message-ID: layer geld verdienen , leicht geldverdienen , wie kann ich onlinespiele geld gewinnen , geldgewinnspiele , zu geld machen , geld machen beim , pennergame geld verdienen , schnell geld vedienen , ohne geld online , geld mit online casino , * * * +++ SOFORT GEWINN +++ REICH WERDEN +++ * http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET * * * ich will bargeld gewinn leicht viel geld verdienen wie kann ich online casino geld gewinnen wo kann ich geld am pc verdienen schnell geld verdienen im internet man mit dem internet geld schnell geld verdienen ohne internet viel geld verdienen drakensang geld machen uploads geld verdienen internet noch geld geld im internet forum geld verdienen durch internet ws schnell sofort geld gewinnen shop geld verdienen wie kann ich geld gewinnen bei mann schnell geld machen man leicht geld texte schreiben geld verdienen mit internet geld machen geld verdienen leicht gemacht wo kann ich geld gewinn spiel eigenen fotos geld verdienen kann man geld gewinnen pennergame geld machen einfach online geld verdienen wo kann ich geld am pc verdienen ich schnelles geld machen werbung internet geld geld verdienen im internet forum kann man online geld verdienen gewinnspiel gewinnen jetzt sofort mann geld machen schnell und legal geld verdienen online um echtes geld spielen sofort geld gewonnen wie kann ich geld gewinnen bei internet leicht geld uploaded to geld verdienen leichtes geld verdienen From hobson42 at gmaiil.com Fri Aug 27 12:37:36 2010 From: hobson42 at gmaiil.com (Ian) Date: Fri, 27 Aug 2010 17:37:36 +0100 Subject: palindrome iteration In-Reply-To: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4C77E9D0.5070401@gmaiil.com> On 27/08/2010 09:53, Baba wrote: > level: beginner > > the following code looks ok to me but it doesn't work. I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] > return True > > print i_palindrome('annab') > If you want to or must do it recursively. (Shown in pseudo code to make the logic clearer) def isPalindrome(pal) ''' test pal (a list) is a palindrome ''' if length of pal = 1 return True # all one letter strings are palindromes. if first equals last # pal could be a palindrome # so test inner part p = pal with first and last removed return isPalendrome(p) # and true - implied else return False # it can't be Of course, the simpler way is to use the definition of a Palindrome as the same backwards and forwards. def isPalindrome(pal) return pal == pal.reverse From justpark78 at gmail.com Fri Aug 27 12:40:03 2010 From: justpark78 at gmail.com (justin) Date: Fri, 27 Aug 2010 09:40:03 -0700 (PDT) Subject: numpy is not installed with Python2. Message-ID: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> My university has a cluster computer, on which I want to run my python program that uses numpy. I am installing my Python2.7 locally separated from the main system, and trying to install numpy, attach it with Python2.7. I used many different versions of numpys to make it happen, but I got stuck with the same following error on every trial, "[hp6 at login1 numpy]$ python2.7 setup.py install Running from numpy source directory.Traceback (most recent call last): File "setup.py", line 210, in setup_package() File "setup.py", line 187, in setup_package from numpy.distutils.core import setup File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in from numpy.distutils.command import config, config_compiler, \ File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", line 9, in from distutils.command.build_ext import build_ext as old_build_ext File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ build_ext.py", line 13, in from site import USER_BASE, USER_SITE ImportError: cannot import name USER_BASE" It seems the error is related to the inability of Python2.7 to process "from site import USER_BASE, USER_SITE", since the machine I succeeded to install numpy with Python2.7 doesn't prompt an error from this command, whereas this machine in which I failed to do so cannot handle this. My question is: How can I make Python2.7 to process this, since the manual says this package is the one that's automatically turned on in startup. Thanks, Justin. From python at mrabarnett.plus.com Fri Aug 27 12:53:42 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 27 Aug 2010 17:53:42 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> Message-ID: <4C77ED96.7090306@mrabarnett.plus.com> On 27/08/2010 17:20, Mark Lawrence wrote: > On 27/08/2010 15:43, Bruno Desthuilliers wrote: >> Dave Angel a ?crit : >> (snip) >> >>> or (untested) >>> def is_palindrom(s): >>> s = s.lower() >>> return s == s[::-1] >>> >> >> >> Right, go on, make me feel a bit more stupid :-/ >> Who's next ? > > It could be worse, try responding to issue 9702. :) > As a wise man once said: Ay caramba! :-) From robert.kern at gmail.com Fri Aug 27 13:10:44 2010 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Aug 2010 12:10:44 -0500 Subject: numpy is not installed with Python2. In-Reply-To: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> References: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> Message-ID: On 8/27/10 11:40 AM, justin wrote: > My university has a cluster computer, on which I want to run my python > program that uses numpy. > I am installing my Python2.7 locally separated from the main system, > and trying to install numpy, attach it with Python2.7. > I used many different versions of numpys to make it happen, but I got > stuck with the same following error on every trial, > > "[hp6 at login1 numpy]$ python2.7 setup.py install > Running from numpy source directory.Traceback (most recent call last): > File "setup.py", line 210, in > setup_package() > File "setup.py", line 187, in setup_package > from numpy.distutils.core import setup > File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in > > from numpy.distutils.command import config, config_compiler, \ > File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", > line 9, in > from distutils.command.build_ext import build_ext as old_build_ext > File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ > build_ext.py", line 13, in > from site import USER_BASE, USER_SITE > ImportError: cannot import name USER_BASE" > > It seems the error is related to the inability of Python2.7 to process > "from site import USER_BASE, USER_SITE", > since the machine I succeeded to install numpy with Python2.7 doesn't > prompt an error from this command, > whereas this machine in which I failed to do so cannot handle this. Your Python installation appears to be broken. Find the site.py module that you are actually importing. I.e. from the numpy source directory: $ python2.7 -c "import site; print site.__file__" This will tell you the site.pyc file that actually gets imported. Find the associated site.py file (it should be in the same directory) and check to see if it has USER_BASE defined. The filename should be /users/hp6/apps/python27/lib/python2.7/site.pyc If it isn't, that may be the source of your problem. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From breamoreboy at yahoo.co.uk Fri Aug 27 13:28:06 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 27 Aug 2010 18:28:06 +0100 Subject: palindrome iteration In-Reply-To: <4C77ED96.7090306@mrabarnett.plus.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> <4C77ED96.7090306@mrabarnett.plus.com> Message-ID: On 27/08/2010 17:53, MRAB wrote: > On 27/08/2010 17:20, Mark Lawrence wrote: >> On 27/08/2010 15:43, Bruno Desthuilliers wrote: >>> Dave Angel a ?crit : >>> (snip) >>> >>>> or (untested) >>>> def is_palindrom(s): >>>> s = s.lower() >>>> return s == s[::-1] >>>> >>> >>> >>> Right, go on, make me feel a bit more stupid :-/ >>> Who's next ? >> >> It could be worse, try responding to issue 9702. :) >> > As a wise man once said: Ay caramba! :-) Isn't that a syntax error? Shouldn't it be ?Ay caramba! :) Cheers. Mark Lawrence. From tjreedy at udel.edu Fri Aug 27 13:39:08 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Aug 2010 13:39:08 -0400 Subject: palindrome iteration In-Reply-To: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: On 8/27/2010 4:53 AM, Baba wrote: > level: beginner > > the following code looks ok to me but it doesn't work. I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] > return True > > print i_palindrome('annab') General practical debugging procedurewhen logic inspection fails: insert print statements at key points. In the case above, put "print pal" before the if statement and you should see the problem. And/or "print 'equal'" after the if. -- Terry Jan Reedy From python at mrabarnett.plus.com Fri Aug 27 13:46:56 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 27 Aug 2010 18:46:56 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> <4C77ED96.7090306@mrabarnett.plus.com> Message-ID: <4C77FA10.6040505@mrabarnett.plus.com> On 27/08/2010 18:28, Mark Lawrence wrote: > On 27/08/2010 17:53, MRAB wrote: >> On 27/08/2010 17:20, Mark Lawrence wrote: >>> On 27/08/2010 15:43, Bruno Desthuilliers wrote: >>>> Dave Angel a ?crit : >>>> (snip) >>>> >>>>> or (untested) >>>>> def is_palindrom(s): >>>>> s = s.lower() >>>>> return s == s[::-1] >>>>> >>>> >>>> >>>> Right, go on, make me feel a bit more stupid :-/ >>>> Who's next ? >>> >>> It could be worse, try responding to issue 9702. :) >>> >> As a wise man once said: Ay caramba! :-) > > Isn't that a syntax error? Shouldn't it be ?Ay caramba! :) > I stand (OK, sit) corrected. From jpiitula at ling.helsinki.fi Fri Aug 27 14:05:55 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 27 Aug 2010 21:05:55 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Ian writes: > If you want to or must do it recursively. > (Shown in pseudo code to make the logic clearer) > > def isPalindrome(pal) > ''' test pal (a list) is a palindrome ''' > if length of pal = 1 > return True # all one letter strings are palindromes. > if first equals last > # pal could be a palindrome > # so test inner part > p = pal with first and last removed > return isPalendrome(p) # and true - implied > else > return False # it can't be def palindromep(s): return ( s == "" or ( s[0] == s[-1] and palindromep(s[1:-1]) ) ) > Of course, the simpler way is to use the definition of a Palindrome > as the same backwards and forwards. > > def isPalindrome(pal) > return pal == pal.reverse Agreed. But is there any nicer way to spell .reverse than [::-1] in Python? There is .swapcase() but no .reverse(), right? From chrisj at puffin.com Fri Aug 27 14:22:51 2010 From: chrisj at puffin.com (Chris Jewell) Date: Fri, 27 Aug 2010 11:22:51 -0700 Subject: mailbox.mbox not locking mbox properly References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: <7rtymfrk3o.fsf@pileated.puffin.com> Even if you replace the python mbox code with something that uses fcntl.flock() to protect against concurrent updating, you should also understand that NFS does *not* provide full Unix filesystem semantics. In particular, Unix flock(2) (which Python's fcntl.flock() wraps) doesn't work over NFS. That's why if you want to access mail over NFS, you should use maildir, rather than mbox, no matter what your programming language. -- Chris Jewell chrisj at puffin.com PO Box 1396 Gualala CA USA 95445-1396 From justpark78 at gmail.com Fri Aug 27 14:38:56 2010 From: justpark78 at gmail.com (justin) Date: Fri, 27 Aug 2010 11:38:56 -0700 (PDT) Subject: numpy is not installed with Python2. References: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> Message-ID: On Aug 27, 12:10?pm, Robert Kern wrote: > On 8/27/10 11:40 AM, justin wrote: > > > > > > > My university has a cluster computer, on which I want to run my python > > program that uses numpy. > > I am installing my Python2.7 locally separated from the main system, > > and trying to install numpy, attach it with Python2.7. > > I used many different versions of numpys to make it happen, but I got > > stuck with the same following error on every trial, > > > "[hp6 at login1 numpy]$ python2.7 setup.py install > > Running from numpy source directory.Traceback (most recent call last): > > ? ?File "setup.py", line 210, in > > ? ? ?setup_package() > > ? ?File "setup.py", line 187, in setup_package > > ? ? ?from numpy.distutils.core import setup > > ? ?File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in > > > > ? ? ?from numpy.distutils.command import config, config_compiler, \ > > ? ?File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", > > line 9, in > > ? ? ?from distutils.command.build_ext import build_ext as old_build_ext > > ? ?File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ > > build_ext.py", line 13, in > > ? ? ?from site import USER_BASE, USER_SITE > > ImportError: cannot import name USER_BASE" > > > It seems the error is related to the inability of Python2.7 to process > > "from site import USER_BASE, USER_SITE", > > since the machine I succeeded to install numpy with Python2.7 doesn't > > prompt an error from this command, > > whereas this machine in which I failed to do so cannot handle this. > > Your Python installation appears to be broken. Find the site.py module that you > are actually importing. I.e. from the numpy source directory: > > ? ?$ python2.7 -c "import site; print site.__file__" > > This will tell you the site.pyc file that actually gets imported. Find the > associated site.py file (it should be in the same directory) and check to see if > it has USER_BASE defined. The filename should be > > ? ?/users/hp6/apps/python27/lib/python2.7/site.pyc > > If it isn't, that may be the source of your problem. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco Dear Kern, Thanks a lot. Your quick and detailed comment saves me a lot of time and effort now. It seems the file path links are out of order as you diagnosed. Like you said, there is a site.py on /users/hp6/apps/python27/lib/ python2.7/. But when I typed in "$ python2.7 -c "import site; print site.__file__", it refers to another place: "/opt/apps/gurobi/3.0.0/linux64/lib/python2.5/site.pyc", and it doesn't have USER_BASE! So I changed the value of PYTHONPATH accordingly. Thanks again, Justin. From davea at ieee.org Fri Aug 27 15:15:25 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 27 Aug 2010 15:15:25 -0400 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4C780ECD.8010204@ieee.org> Jussi Piitulainen wrote: > Ian writes: > > >> If you want to or must do it recursively. >> (Shown in pseudo code to make the logic clearer) >> >> def isPalindrome(pal) >> ''' test pal (a list) is a palindrome ''' >> if length of pal = 1 >> return True # all one letter strings are palindromes. >> if first equals last >> # pal could be a palindrome >> # so test inner part >> p = pal with first and last removed >> return isPalendrome(p) # and true - implied >> else >> return False # it can't be >> > > def palindromep(s): > return ( s == "" or > ( s[0] == s[-1] and > palindromep(s[1:-1]) ) ) > > >> Of course, the simpler way is to use the definition of a Palindrome >> as the same backwards and forwards. >> >> def isPalindrome(pal) >> return pal == pal.reverse >> > > Agreed. But is there any nicer way to spell .reverse than [::-1] in > Python? There is .swapcase() but no .reverse(), right? > > There can't be a .reverse() method on string, because it's immutable. You could use "".join(reversed(pal)) but I'd prefer pal[::-1] as I said earlier. DaveA From jdixon at omniti.com Fri Aug 27 15:34:20 2010 From: jdixon at omniti.com (Jason Dixon) Date: Fri, 27 Aug 2010 15:34:20 -0400 Subject: Surge 2010 Early Registration ends Tuesday! Message-ID: <20100827193420.GN1736@omniti.com> Early Bird Registration for Surge Scalability Conference 2010 ends next Tuesday, August 31. We have a killer lineup of speakers and architects from across the Internet. Listen to experts talk about the newest methods and technologies for scaling your Web presence. http://omniti.com/surge/2010/register This year's event is all about the challenges faced (and overcome) in real-life production architectures. Meet the engineering talent from some of the best and brightest throughout the Internet: John Allspaw, Etsy Theo Schlossnagle, OmniTI Bryan Cantrill, Joyent Rasmus Lerdorf, creator of PHP Tom Cook, Facebook Benjamin Black, fast_ip Christopher Brown, Opscode Artur Bergman, Wikia Baron Schwartz, Percona Paul Querna, Cloudkick Surge 2010 takes place at the Tremont Grand Historic Venue on Sept 30 and Oct 1, 2010 in Baltimore, MD. Register NOW for the Early Bird discount and guarantee your seat to this year's event! -- Jason Dixon OmniTI Computer Consulting, Inc. jdixon at omniti.com 443.325.1357 x.241 From robert.kern at gmail.com Fri Aug 27 15:37:40 2010 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Aug 2010 14:37:40 -0500 Subject: numpy is not installed with Python2. In-Reply-To: References: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> Message-ID: On 8/27/10 1:38 PM, justin wrote: > On Aug 27, 12:10 pm, Robert Kern wrote: >> On 8/27/10 11:40 AM, justin wrote: >> >> >> >> >> >>> My university has a cluster computer, on which I want to run my python >>> program that uses numpy. >>> I am installing my Python2.7 locally separated from the main system, >>> and trying to install numpy, attach it with Python2.7. >>> I used many different versions of numpys to make it happen, but I got >>> stuck with the same following error on every trial, >> >>> "[hp6 at login1 numpy]$ python2.7 setup.py install >>> Running from numpy source directory.Traceback (most recent call last): >>> File "setup.py", line 210, in >>> setup_package() >>> File "setup.py", line 187, in setup_package >>> from numpy.distutils.core import setup >>> File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in >>> >>> from numpy.distutils.command import config, config_compiler, \ >>> File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", >>> line 9, in >>> from distutils.command.build_ext import build_ext as old_build_ext >>> File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ >>> build_ext.py", line 13, in >>> from site import USER_BASE, USER_SITE >>> ImportError: cannot import name USER_BASE" >> >>> It seems the error is related to the inability of Python2.7 to process >>> "from site import USER_BASE, USER_SITE", >>> since the machine I succeeded to install numpy with Python2.7 doesn't >>> prompt an error from this command, >>> whereas this machine in which I failed to do so cannot handle this. >> >> Your Python installation appears to be broken. Find the site.py module that you >> are actually importing. I.e. from the numpy source directory: >> >> $ python2.7 -c "import site; print site.__file__" >> >> This will tell you the site.pyc file that actually gets imported. Find the >> associated site.py file (it should be in the same directory) and check to see if >> it has USER_BASE defined. The filename should be >> >> /users/hp6/apps/python27/lib/python2.7/site.pyc >> >> If it isn't, that may be the source of your problem. >> >> -- >> Robert Kern >> >> "I have come to believe that the whole world is an enigma, a harmless enigma >> that is made terrible by our own mad attempt to interpret it as though it had >> an underlying truth." >> -- Umberto Eco > > Dear Kern, > > Thanks a lot. > Your quick and detailed comment saves me a lot of time and effort > now. > > It seems the file path links are out of order as you diagnosed. > Like you said, there is a site.py on /users/hp6/apps/python27/lib/ > python2.7/. > But when I typed in "$ python2.7 -c "import site; print > site.__file__", it refers to another place: > "/opt/apps/gurobi/3.0.0/linux64/lib/python2.5/site.pyc", and it > doesn't have USER_BASE! > > So I changed the value of PYTHONPATH accordingly. You should not set PYTHONPATH to those directories ever. The correct one will already be on the sys.path. In a multiple-Python environment, you simply shouldn't use PYTHONPATH at all since all of the interpreters will try to use it. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From darcy at druid.net Fri Aug 27 15:42:18 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 27 Aug 2010 15:42:18 -0400 Subject: palindrome iteration In-Reply-To: <20100827120239.5a0b2396.darcy@druid.net> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> <20100827114942.0b1210cd.darcy@druid.net> <20100827120239.5a0b2396.darcy@druid.net> Message-ID: <20100827154218.b8193916.darcy@druid.net> On Fri, 27 Aug 2010 12:02:39 -0400 "D'Arcy J.M. Cain" wrote: > On Fri, 27 Aug 2010 11:49:42 -0400 > "D'Arcy J.M. Cain" wrote: > > is_palindrome = lambda x: x == x.lower()[::-1] > > Oops. Simple and wrong. > > is_palindrome = lambda x: x.lower() == x.lower()[::-1] slightly more efficient I think. is_palindrome = lambda y: (lambda x: x == x[::-1])(y.lower()) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From jpiitula at ling.helsinki.fi Fri Aug 27 15:43:10 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 27 Aug 2010 22:43:10 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Dave Angel writes: > Jussi Piitulainen wrote: >> Ian writes: >>> Of course, the simpler way is to use the definition of a >>> Palindrome as the same backwards and forwards. >>> >>> def isPalindrome(pal) >>> return pal == pal.reverse >> >> Agreed. But is there any nicer way to spell .reverse than [::-1] in >> Python? There is .swapcase() but no .reverse(), right? >> > There can't be a .reverse() method on string, because it's > immutable. You could use > > "".join(reversed(pal)) > > but I'd prefer pal[::-1] as I said earlier. There could easily be a .reverse() method on strings. It would return the reversed string, like .swapcase() returns the swapcased string. From nagle at animats.com Fri Aug 27 15:57:42 2010 From: nagle at animats.com (John Nagle) Date: Fri, 27 Aug 2010 12:57:42 -0700 Subject: Queue cleanup In-Reply-To: <9b270554-e7cb-48ec-aa0e-c78690a81b54@q26g2000vbn.googlegroups.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> <7xvd7h2d90.fsf@ruckus.brouhaha.com> <9b270554-e7cb-48ec-aa0e-c78690a81b54@q26g2000vbn.googlegroups.com> Message-ID: <4c7818c5$0$1664$742ec2ed@news.sonic.net> On 8/11/2010 1:26 PM, EW wrote: > On Aug 11, 2:52 pm, Paul Rubin wrote: >> EW writes: >>> Well I cared because I thought garbage collection would only happen >>> when the script ended - the entire script. Since I plan on running >>> this as a service it'll run for months at a time without ending. So I >>> thought I was going to have heaps of Queues hanging out in memory, >>> unreferenced and unloved. It seemed like bad practice so I wanted to >>> get out ahead of it. >> >> Even if GC worked that way it wouldn't matter, if you use just one queue >> per type of task. That number should be a small constant so the memory >> consumption is small. > > Well I can't really explain it but 1 Queue per task for what I'm > designing just doesn't feel right to me. It feels like it will lack > future flexibility. I like having 1 Queue per producer thread object > and the person instantiating that object can do whatever he wants with > that Queue. I can't prove I'll need that level of flexibility but I > don't see why it' bad to have. It's still a small number of Queues, > it's just a small, variable, number of Queues. That's backwards. Usually, you want one queue per unique consumer. That is, if you have a queue that contains one kind of request, there's one thread reading the queue, blocked until some other thread puts something on the queue. No polling is needed. One consumer reading multiple queues is difficult to implement well. Note, by the way, that CPython isn't really concurrent. Only one thread runs at a time, due to an archaic implementation. So if your threads are compute-bound, even on a multicore CPU threading will not help. There's a "multiprocessing module" which allows spreading work over several processes instead of threads. That can be helpful as a workaround. John Nagle From nagle at animats.com Fri Aug 27 16:09:25 2010 From: nagle at animats.com (John Nagle) Date: Fri, 27 Aug 2010 13:09:25 -0700 Subject: mailbox.mbox not locking mbox properly In-Reply-To: References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: <4c781b84$0$1619$742ec2ed@news.sonic.net> On 8/10/2010 2:25 AM, Chris Rebert wrote: > On Tue, Aug 10, 2010 at 2:01 AM, wrote: >> Tim Roberts wrote: >>> tinnews at isbd.co.uk wrote: >>>> >>>> I'm using the python mailbox class in a script that processes incoming >>>> mail and delivers it to various mbox format mailboxes. It appears >>>> that, although I am calling the lock method on the destination before >>>> writing to the mbox and calling unlock afterwards the locking isn't >>>> working correctly. >>>> ... >>>> So it seems that python's mailbox class locking isn't playing nicely >>>> with mutt's mailbox locking whereas postfix's locking does work >>>> correctly. >>> >>> Correct. The "dest.flush()" method creates a temporary file, copies the >>> entire modified mailbox into it, removed the original file, and renames the >>> temp file into place. >>> >> Yes, I just took a look at the mailbox.py code and it does exactly >> that which of course screws up just about any normal MUA looking at >> the mbox. Grrrrrr! >> >> >>> The Postfix MDA, like most MDAs, just opens the existing file and appends >>> the new data to it. >>> >>>> Has anyone seen this problem before, and/or do I need to anything more >>>> than the following for the locking to work correctly:- >>> >>> It's not the locking. It's the flush mechanism. The mbox class doesn't >>> know that the ONLY thing you did was an append. You might have modified >>> other messages in the middle. If you want to do an append, you'll need to >>> write your own subclass of mbox. >> >> OK, thanks. In reality I can probably just use straightforward file >> reading and writing as the *only* thing I will ever be doing is to >> append a message to a mailbox file. >> >> I think there should be a big warning in the mailbox documentation to >> this effect as doing it the way that Python's mailbox class does it >> will break all sorts of things. There should maybe be a specific >> 'append' method. > > File a documentation and/or library bug: > http://bugs.python.org/ > > Cheers, > Chris From python at mrabarnett.plus.com Fri Aug 27 16:14:44 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 27 Aug 2010 21:14:44 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4C781CB4.5080108@mrabarnett.plus.com> On 27/08/2010 20:43, Jussi Piitulainen wrote: > Dave Angel writes: > >> Jussi Piitulainen wrote: >>> Ian writes: >>>> Of course, the simpler way is to use the definition of a >>>> Palindrome as the same backwards and forwards. >>>> >>>> def isPalindrome(pal) >>>> return pal == pal.reverse >>> >>> Agreed. But is there any nicer way to spell .reverse than [::-1] in >>> Python? There is .swapcase() but no .reverse(), right? >>> >> There can't be a .reverse() method on string, because it's >> immutable. You could use >> >> "".join(reversed(pal)) >> >> but I'd prefer pal[::-1] as I said earlier. > > There could easily be a .reverse() method on strings. It would return > the reversed string, like .swapcase() returns the swapcased string. Lists have a .reverse method, but it's an in-place reversal. In order to reduce confusion, a string method which returned the string reversed would be better called .reversed(). From jpiitula at ling.helsinki.fi Fri Aug 27 16:51:17 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 27 Aug 2010 23:51:17 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: MRAB writes: > On 27/08/2010 20:43, Jussi Piitulainen wrote: >> Dave Angel writes: >>> Jussi Piitulainen wrote: >>>> Agreed. But is there any nicer way to spell .reverse than [::-1] >>>> in Python? There is .swapcase() but no .reverse(), right? >>>> >>> There can't be a .reverse() method on string, because it's >>> immutable. You could use >>> >>> "".join(reversed(pal)) >>> >>> but I'd prefer pal[::-1] as I said earlier. >> >> There could easily be a .reverse() method on strings. It would >> return the reversed string, like .swapcase() returns the swapcased >> string. > > Lists have a .reverse method, but it's an in-place reversal. In > order to reduce confusion, a string method which returned the string > reversed would be better called .reversed(). Yes, agreed. Meanwhile, I have decided to prefer this: def palindromep(s): def reversed(s): return s[::-1] return s == reversed(s) From tjreedy at udel.edu Fri Aug 27 17:41:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Aug 2010 17:41:07 -0400 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: > Dave Angel writes: > There could easily be a .reverse() method on strings. It would return > the reversed string, like .swapcase() returns the swapcased string. Could be, but the main use case seems to be for palindrome testing ;-) Given that slicing and reversed() can do the same thing, the need is thin. -- Terry Jan Reedy From arts.richard at gmail.com Fri Aug 27 17:47:26 2010 From: arts.richard at gmail.com (Richard Arts) Date: Fri, 27 Aug 2010 23:47:26 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: On Fri, Aug 27, 2010 at 10:51 PM, Jussi Piitulainen wrote: > MRAB writes: >> On 27/08/2010 20:43, Jussi Piitulainen wrote: >>> Dave Angel writes: >>>> Jussi Piitulainen wrote: >>>>> Agreed. But is there any nicer way to spell .reverse than [::-1] >>>>> in Python? There is .swapcase() but no .reverse(), right? >>>>> >>>> There can't be a .reverse() method on string, because it's >>>> immutable. You could use >>>> >>>> ? ? ?"".join(reversed(pal)) >>>> >>>> but I'd prefer ?pal[::-1] ?as I said earlier. >>> >>> There could easily be a .reverse() method on strings. It would >>> return the reversed string, like .swapcase() returns the swapcased >>> string. >> >> Lists have a .reverse method, but it's an in-place reversal. In >> order to reduce confusion, a string method which returned the string >> reversed would be better called .reversed(). > > Yes, agreed. > > Meanwhile, I have decided to prefer this: > > def palindromep(s): > ? ?def reversed(s): > ? ? ? ?return s[::-1] > ? ?return s == reversed(s) > -- > http://mail.python.org/mailman/listinfo/python-list > That seems like a bit of overkill... Why would you want to define a function in a function for something trivial like this? Just def palindrome(s): return s[::-1] will do fine. Of course, you can stick the inner function in a library somewhere if you like. Regards, Richard From arts.richard at gmail.com Fri Aug 27 17:52:39 2010 From: arts.richard at gmail.com (Richard Arts) Date: Fri, 27 Aug 2010 23:52:39 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: On Fri, Aug 27, 2010 at 11:47 PM, Richard Arts wrote: > On Fri, Aug 27, 2010 at 10:51 PM, Jussi Piitulainen > wrote: >> MRAB writes: >>> On 27/08/2010 20:43, Jussi Piitulainen wrote: >>>> Dave Angel writes: >>>>> Jussi Piitulainen wrote: >>>>>> Agreed. But is there any nicer way to spell .reverse than [::-1] >>>>>> in Python? There is .swapcase() but no .reverse(), right? >>>>>> >>>>> There can't be a .reverse() method on string, because it's >>>>> immutable. You could use >>>>> >>>>> ? ? ?"".join(reversed(pal)) >>>>> >>>>> but I'd prefer ?pal[::-1] ?as I said earlier. >>>> >>>> There could easily be a .reverse() method on strings. It would >>>> return the reversed string, like .swapcase() returns the swapcased >>>> string. >>> >>> Lists have a .reverse method, but it's an in-place reversal. In >>> order to reduce confusion, a string method which returned the string >>> reversed would be better called .reversed(). >> >> Yes, agreed. >> >> Meanwhile, I have decided to prefer this: >> >> def palindromep(s): >> ? ?def reversed(s): >> ? ? ? ?return s[::-1] >> ? ?return s == reversed(s) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > That seems like a bit of overkill... Why would you want to define a > function in a function for something trivial like this? Just > > def palindrome(s): > ? ?return s[::-1] > > will do fine. > > Of course, you can stick the inner function in a library somewhere if you like. > > Regards, > Richard > Duh, of course I mean def palindrome(s): return s == s[::-1] I'm sorry. Richard From ldo at geek-central.gen.new_zealand Fri Aug 27 18:58:59 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 10:58:59 +1200 Subject: Writing byte stream as jpeg format to disk References: Message-ID: In message , Navkirat Singh wrote: > I receive a jpeg file with the POST method.The file (.jpeg) is encoded in > bytes, I parse the bytes by decoding them to a string. I wanted to know > how i could write the file (now a string) as a jpeg image on disk. I assume the JPEG data is received along with other field values in the POST. You?ll be saving those other fields in a database, right? So why not save the JPEG image there as well? From ldo at geek-central.gen.new_zealand Fri Aug 27 19:01:04 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 11:01:04 +1200 Subject: Writing byte stream as jpeg format to disk References: <874oeh2sdg.fsf@castleamber.com> Message-ID: In message , Navkirat Singh wrote: > The image bytes are a part of a HTTP header content ( not the message body > ). In which case, won?t they be in some encoding like Base-64? I don?t think you?re allowed arbitrary binary bytes in an HTTP header. From ldo at geek-central.gen.new_zealand Fri Aug 27 19:07:30 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 11:07:30 +1200 Subject: Reading the access attributes of directories in Windows References: Message-ID: In message , Rami Chowdhury wrote: > On Wed, Aug 25, 2010 at 05:04, Lawrence D'Oliveiro > wrote: > >> In message , Nobody wrote: >> >>> Having this as a separate permission allows normal users to add entries >>> to log files but not to erase existing entries. >> >> Unix/Linux systems can do this already. > > Ooh, I didn't know that -- what combination of permissions would I > have to use to get such an effect? No special permissions needed at all?just use the syslog(3) functions. And the nice thing is, you don?t have to know whether the system logs are kept on the local machine or on a remote machine, or how different categories of messages are divided up into different files, how log rotation is done, or anything like that?it?s all transparent. From robert.kern at gmail.com Fri Aug 27 19:14:05 2010 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Aug 2010 18:14:05 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: Message-ID: On 8/27/10 5:58 PM, Lawrence D'Oliveiro wrote: > In message > , Navkirat Singh wrote: > >> I receive a jpeg file with the POST method.The file (.jpeg) is encoded in >> bytes, I parse the bytes by decoding them to a string. I wanted to know >> how i could write the file (now a string) as a jpeg image on disk. > > I assume the JPEG data is received along with other field values in the > POST. You?ll be saving those other fields in a database, right? So why not > save the JPEG image there as well? No, the only thing in the body of the POST are the bytes of the JPEG. He was incorrect in thinking that the JPEG data was arriving in the header. See the later posts in the thread for complete answers to his problem. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sridharr at activestate.com Fri Aug 27 19:24:36 2010 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Fri, 27 Aug 2010 16:24:36 -0700 Subject: ANN: ActivePython 2.6.6.15 is now available Message-ID: <4C784934.6090809@activestate.com> ActiveState is pleased to announce ActivePython 2.6.6.15, a complete, ready-to-install binary distribution of Python 2.6.6. http://www.activestate.com/activepython What's New in ActivePython-2.6.6.15 =================================== *Release date: 25-Aug-2010* New Features & Upgrades ----------------------- - Upgrade to Python 2.6.6 (`release notes `__) - Security upgrade to openssl-0.9.8o - [MacOSX] 64-bit support (PPC and 10.4 are no longer supported) - Upgrade to PyPM 1.1.1; noteworthy changes: - Custom config file support w/ new repository settings (-R free,be instead of -L) - Support for installing a local package, eg: ``pypm install /path/to/foo.pypm`` - Bug #87687: Prevent partial downloading of repo index cache - Upgraded the following packages: - Distribute-0.6.14 - pip-0.8 - SQLAlchemy-0.6.3 Noteworthy Changes & Bug Fixes ------------------------------ - [MacOSX] Fix Help index on Snow Leopard (10.6) - Bug #87290 - [Windows] Add file extension to Tools\scripts\2to3.py - Bug #87465 What's New in ActivePython-2.6.5.14 =================================== *Release date: 07-Jul-2010* New Features & Upgrades ----------------------- - Upgrade to PyPM 1.0.2 - 'pypm search' now also shows if a package is installed and upgradeable - 'pypm info' now prints a concise representation by default - 'pypm list --short' will show only packages names; for scripting purposes - Respect distutils install schemes (purelib, scripts) Noteworthy Changes & Bug Fixes ------------------------------ - [MacOSX] Fix /usr/local/bin symlinks to not use the 'Current' symlink - [MacOSX] Fix uninstall on Snow Leopard (10.6) - [Windows] Include IDLE in the Start Menu shortcut, instead of PythonWin See the release notes for full details: http://docs.activestate.com/activepython/2.6/relnotes.html#changes What is ActivePython? ===================== ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and AIX builds, and access to older versions are available in ActivePython Business, Enterprise and OEM editions: http://www.activestate.com/python ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. ActivePython 2.6 and 2.7 also include a binary package manager for Python (PyPM) that can be used to install packages much easily. For example: C:\>pypm install mysql-python [...] C:\>python >>> import MySQLdb >>> See this page for full details: http://docs.activestate.com/activepython/2.6/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/2.6/ We would welcome any and all feedback to: activepython-feedback at activestate.com Please file bugs against ActivePython at: http://bugs.activestate.com/enter_bug.cgi?product=ActivePython Supported Platforms =================== ActivePython is available for the following platforms: - Windows/x86 (32-bit) - Windows/x64 (64-bit) (aka "AMD64") - Mac OS X - Linux/x86 (32-bit) - Linux/x86_64 (64-bit) (aka "AMD64") - Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) - Solaris/x86 (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/PA-RISC (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/IA-64 (32-bit and 64-bit) (Enterprise or OEM edition only) - AIX/PowerPC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) More information about the Business Edition can be found here: http://www.activestate.com/business-edition Custom builds are available in the Enterprise Edition: http://www.activestate.com/enterprise-edition Thanks, and enjoy! The Python Team -- Sridhar Ratnakumar sridharr at activestate.com From sridharr at activestate.com Fri Aug 27 19:29:20 2010 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Fri, 27 Aug 2010 16:29:20 -0700 Subject: ANN: ActivePython 2.7.0.2 is now available Message-ID: <4C784A50.5050608@activestate.com> ActiveState is pleased to announce ActivePython 2.7.0.2, a complete, ready-to-install binary distribution of Python 2.7. http://www.activestate.com/activepython What's New in ActivePython-2.7.0.2 ================================== *Release date: 25-Aug-2010* New Features & Upgrades ----------------------- - Security upgrade to openssl-0.9.8o - Upgrade to PyPM 1.1.1; noteworthy changes: - Custom config file support w/ new repository settings (-R free,be instead of -L) - Support for installing a local package, eg: ``pypm install /path/to/foo.pypm`` - Bug #87687: Prevent partial downloading of repo index cache - Upgraded the following packages: - Distribute-0.6.14 - pip-0.8 - SQLAlchemy-0.6.3 Noteworthy Changes & Bug Fixes ------------------------------ - [MacOSX] Fix Help index on Snow Leopard (10.6) - Bug #87290 - [Windows] Add file extension to Tools\scripts\2to3.py - Bug #87465 What is ActivePython? ===================== ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and AIX builds, and access to older versions are available in ActivePython Business, Enterprise and OEM editions: http://www.activestate.com/python ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. ActivePython 2.6 and 2.7 also include a binary package manager for Python (PyPM) that can be used to install packages much easily. For example: C:\>pypm install mysql-python [...] C:\>python >>> import MySQLdb >>> See this page for full details: http://docs.activestate.com/activepython/2.7/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/2.7/ We would welcome any and all feedback to: activepython-feedback at activestate.com Please file bugs against ActivePython at: http://bugs.activestate.com/enter_bug.cgi?product=ActivePython Supported Platforms =================== ActivePython is available for the following platforms: - Windows/x86 (32-bit) - Windows/x64 (64-bit) (aka "AMD64") - Mac OS X - Linux/x86 (32-bit) - Linux/x86_64 (64-bit) (aka "AMD64") - Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) - Solaris/x86 (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/PA-RISC (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/IA-64 (32-bit and 64-bit) (Enterprise or OEM edition only) - AIX/PowerPC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) More information about the Business Edition can be found here: http://www.activestate.com/business-edition Custom builds are available in the Enterprise Edition: http://www.activestate.com/enterprise-edition Thanks, and enjoy! The Python Team -- Sridhar Ratnakumar sridharr at activestate.com From ldo at geek-central.gen.new_zealand Fri Aug 27 19:49:35 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 11:49:35 +1200 Subject: ftplib limitations? References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74E604.6090208@sschwarzer.net> Message-ID: In message <4C74E604.6090208 at sschwarzer.net>, Stefan Schwarzer wrote: > Now it may be that the data connection, after having started > the transfer, works as it should, but the control connection > times out because the duration of the transfer is too long. It might not be the fault of the FTP server. If you?re going through a router doing NAT, that could be where the timeout is happening. From no.email at please.post Fri Aug 27 20:01:27 2010 From: no.email at please.post (kj) Date: Sat, 28 Aug 2010 00:01:27 +0000 (UTC) Subject: How to convert (unicode) text to image? Message-ID: Hi! Does anyone know of an easy way to convert a Unicode string into an image file (either jpg or png)? TIA! ~k From jrmy.lnrd at gmail.com Fri Aug 27 20:03:09 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Fri, 27 Aug 2010 17:03:09 -0700 (PDT) Subject: Overload print References: Message-ID: <88356697-058e-4ae5-ab2b-782a593f51de@z28g2000yqh.googlegroups.com> On Aug 25, 5:18?pm, Ross Williamson wrote: > Hi All > > Is there anyway in a class to overload the print function? > > >> class foo_class(): > >> ? ? ?pass > >> cc = foo_class() > >> print cc > > Gives: > > <__main__.foo_class instance at ....> > > Can I do something like: > > >> class foo_class(): > >> ? ? def __print__(self): > >> ? ? ? ? ? print "hello" > >> cc = foo_class() > >> print cc > > Gives: > > hello > > I'm looking at finding nice way to print variables in a class just by > asking to print it > > Cheers > > Ross > > -- > Ross Williamson > University of Chicago > Department of Astronomy & Astrophysics > 773-834-9785 (office) > 312-504-3051 (Cell) Are you talking about overriding print(), kind of like overloading the << operator in c++ so that you can determine how the foo_class gets printed? From steve at REMOVE-THIS-cybersource.com.au Fri Aug 27 20:24:12 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 00:24:12 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <4c78572c$0$28655$c3e8da3@news.astraweb.com> On Fri, 27 Aug 2010 09:16:52 -0700, Aahz wrote: > In article , MRAB > wrote: >> >>An object will be available for garbage collection when nothing refers >>to it either directly or indirectly. If it's unreferenced then it will >>go away. > > This isn't actually garbage collection as most people think of it. > Refcounting semantics mean that objects get reaped as soon as nothing > points at them. OTOH, CPython does also have garbage collection to back > up refcounting so that when you have unreferenced object cycles they > don't stay around. I've repeatedly asked, both here and elsewhere, why reference counting isn't "real" garbage collection. Nobody has been able to give me a satisfactory answer. As far as I can tell, it's a bit of pretentiousness with no basis in objective fact. http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) http://en.wikipedia.org/wiki/Reference_counting Reference counting is one specific kind of garbage collection, and like all gc strategies, it has strengths as well as weaknesses. It is *simple* to implement (which may be why a certain class of programmer likes to think it isn't "real" gc). When it runs is deterministic, and is immediate upon the resource being freed. The overhead is very light (a plus) and continuous (which can be both a plus and a minus). It is better suited to managing scarce resources like open files than are tracing garbage collectors. It avoids the "embarrassing pause" of tracing collectors. It doesn't deal well with reference cycles, and (at least with Python's implementation of ref counting) it causes performance issues with threaded applications. http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) http://en.wikipedia.org/wiki/Reference_counting So CPython has two garbage collectors -- a reference counting implementation, and a tracing implementation. Jython and IronPython use the native garbage collectors from Java and .Net. Other Pythons may use something else. -- Steven From benjamin.kaplan at case.edu Fri Aug 27 20:34:54 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 27 Aug 2010 20:34:54 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: References: Message-ID: On Fri, Aug 27, 2010 at 8:01 PM, kj wrote: > > > Hi! ?Does anyone know of an easy way to convert a Unicode string into an image file (either jpg or png)? > Do you mean you have some text and you want an image containing that text? PIL's ImageDraw module can do that. From no.email at nospam.invalid Fri Aug 27 21:06:19 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Fri, 27 Aug 2010 18:06:19 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> Message-ID: <7x4oeftuk4.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I've repeatedly asked, both here and elsewhere, why reference counting > isn't "real" garbage collection. Nobody has been able to give me a > satisfactory answer. As far as I can tell, it's a bit of pretentiousness > with no basis in objective fact. Well, it's a bit of a subjective matter. I'd say it's not real gc because 1) it's unsound (misses reference cycles), and 2) it requires constant attention from the mutator to incr and decr the reference counts. So developing modules for the CPython API means endlessly finding and fixing refcount bugs that lead to either crashes/security failures, or memory leaks. If you program the Java JNI or a typical Lisp FFI, you'll find that real gc is a lot simpler to use since you avoid all the refcount maintenance hassles. You allocate memory and shut your eyes, and the gc takes care of freeing it when it figures out that you are done. Refcounting is basically a form of manual memory management, while gc is automatic. Someone said here recently that as a program gets larger, saying "this will work as long as we do X every time without fail" becomes equal to saying "this won't work". Substitute "properly maintain all ref counts" for X and you can see the problem. I've seen released "production" "tested" Python C modules with subtle refcount bugs on more than one occasion. In gc'd systems there are fewer places for the code to go wrong. From mahaboobnisha at gmail.com Fri Aug 27 22:42:30 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Fri, 27 Aug 2010 19:42:30 -0700 (PDT) Subject: comp.lang.python Message-ID: <4acae78f-3e8b-4781-b23b-8ced464c5021@f20g2000pro.googlegroups.com> www.127760.blogspot.com From 2011.love.me at gmail.com Fri Aug 27 22:50:53 2010 From: 2011.love.me at gmail.com (love me) Date: Fri, 27 Aug 2010 19:50:53 -0700 (PDT) Subject: love me Message-ID: <7a78b3e7-6616-4f25-899f-7dbb48e87c2d@f42g2000yqn.googlegroups.com> 1st step like me on facbook at this link http://www.facebook.com/pages/loveme/145529285481739 2nd step visit this link http://www.kqzyfj.com/click-3778203-10786395 From donn.ingle at gmail.com Fri Aug 27 23:21:09 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 05:21:09 +0200 Subject: Walking deeply nested lists Message-ID: <4C7880A5.1070304@gmail.com> This is all about walking trees, recursion and generators. None of which fit my brain at all! From an XML tree (an SVG file) I build a bunch of Tag objects. [I use lxml, but I am combining multiple svg files into a 'forest' of trees, so I can't use the lxml walking methods because they all stop at the 'end' of a branch where there is actually a 'link' over to another tree.] Each Tag has a flatwalk() method. The return from that is a list which can be deeply nested. As an example, something like this: L=[1, [2, 3, [4, [5, 6], 7], 8], [9, 10] ] (The numbers in the example would actually be Tag Instances.) Aim 1 --- I'm trying to write a generator around such lists so that I can 'walk' them: for parent, child in mystery_generator(L): print level, item Right now, I am running a 'flatten' function on the entire list (which I don't savvy, I found it online) and then I iterate over that flattened list. This doesn't feel right to me. (Code at end.) Aim 2 --- The Objects that represent the svg tags use that flatwalk() method to build the nested list, I'd far prefer flatwalk() to be directly useable in something like this way: for container, child in some_tag.flatwalk(): print container, child The flatwalk() function is (and this is another puzzle see *) kind of recursive. "For each of my children, tell that child to go flatwalk()". (Code at end.) I am not sure how to turn such a thing into a generator. I keep wondering how os.walk() does its thing. My hierarchy of Tag objects can be thought of as directories (tags:g, symbol, svg), files (path, circle, etc.) and soft-links (use tags). * If an Instance calls a method on *another* Instance of the *same* class, is this still recursion? And how does this 'stack up'? I mean, literally, on the stack. Does each instance get its own stack, or does all the push, call, pop stuff happen in one main stack? (I worry about recursion depth limits because svg trees can get quite deep.) The walking code so far: ## Found code. def flatten(input): output = [] stack = [] stack.extend(reversed(input)) while stack: top = stack.pop() if isinstance(top, list): stack.extend(reversed(top)) else: output.append(top) return output ## My walker def test_walk(e): #lxml Element comes in obj = ebag_get(e)['obj'] #get a tag object l=obj.flatwalk() ll= flatten(l) #No current solution to get 'parent' in this iterator #ie. for parent, child in ... for tag in ll: print tag Here's one of my Tag objects: class Brancher(object): def __init__(self, elem): self.elem = elem self.children = [] def flatwalk(self): l=[self] for child in self.children: l.append( child.flatwalk() ) #recur(ish)ion here return l class G( Brancher ): #Object for tags. pass \d From ldo at geek-central.gen.new_zealand Sat Aug 28 00:39:59 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 16:39:59 +1200 Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: In message , Tim Golden wrote: > Can you run Python from within a Run-As-Administrator command > prompt? Kind of worrying, isn?t it, when the answer to ?my program won?t work? is ?give it more privileges?? Defeats the point of having such a complex security system, doesn?t it, when people are no longer able to understand its ramifications, and have to resort to bypassing it to get work done? From maral.nikfar at gmail.com Sat Aug 28 01:57:34 2010 From: maral.nikfar at gmail.com (sarah) Date: Fri, 27 Aug 2010 22:57:34 -0700 (PDT) Subject: rfile.readline() Message-ID: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> i want to know that what this function returns??? and what does this function do?? From jpiitula at ling.helsinki.fi Sat Aug 28 02:22:13 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 09:22:13 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Terry Reedy writes: > On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: > > Dave Angel writes: > > > There could easily be a .reverse() method on strings. It would return > > the reversed string, like .swapcase() returns the swapcased string. > > Could be, but the main use case seems to be for palindrome testing ;-) > Given that slicing and reversed() can do the same thing, the need is thin. The need is quite thin, but immutability of strings is not an issue, just like there can be .swapcase() though strings are immutable. That is all I am saying above. From __peter__ at web.de Sat Aug 28 02:43:07 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 08:43:07 +0200 Subject: Walking deeply nested lists References: Message-ID: donn wrote: > * If an Instance calls a method on another Instance of the same > class, is this still recursion? And how does this 'stack up'? I mean, > literally, on the stack. Does each instance get its own stack, or does > all the push, call, pop stuff happen in one main stack? > (I worry about recursion depth limits because svg trees can get quite > deep.) If you call functions within functions (or methods, it doesn't matter) they consume stack space, e. g: >>> def alpha(): ... return beta() ... >>> def beta(): ... return gamma() ... >>> import random >>> def gamma(): ... return random.choice([alpha, beta, gamma])() ... >>> import sys >>> sys.setrecursionlimit(10) >>> alpha() Traceback (most recent call last): File "", line 1, in File "", line 2, in alpha File "", line 2, in beta File "", line 2, in gamma File "", line 2, in gamma File "", line 2, in alpha File "", line 2, in beta File "", line 2, in gamma File "", line 2, in beta File "", line 2, in gamma RuntimeError: maximum recursion depth exceeded The normal recursion limit is 1000, I'm reducing it to give you a smaller traceback. Peter From __peter__ at web.de Sat Aug 28 02:57:02 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 08:57:02 +0200 Subject: rfile.readline() References: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> Message-ID: sarah wrote: > i want to know that what this function returns??? > and what does this function do?? Where do you get rfile from? The readline() function (or method) could read one line from a file (likely) or wipe your harddisk (unlikely). Without some context it is impossible to tell. Peter From jpiitula at ling.helsinki.fi Sat Aug 28 02:57:26 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 09:57:26 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Richard Arts writes: > On Fri, Aug 27, 2010 at 10:51 PM, Jussi Piitulainen wrote: >> >> Meanwhile, I have decided to prefer this: >> >> def palindromep(s): >> ? ?def reversed(s): >> ? ? ? ?return s[::-1] >> ? ?return s == reversed(s) > > That seems like a bit of overkill... Why would you want to define a > function in a function for something trivial like this? Just > > def palindrome(s): > return s[::-1] > > will do fine. I'm sure your version will do something just fine, but what that something is, I can not tell. The body of your version is quite obscure and does not seem to agree with the name of the function. I find (s == reversed(s)) a clearer expression than (s == s[::-1]), and I found a simple way to use my preferred expression. > Of course, you can stick the inner function in a library somewhere > if you like. >From my point of view, it would be an understatement to say that setting up a library for this would be an overkill. A simple local auxiliary function is nothing. From clp2 at rebertia.com Sat Aug 28 03:06:52 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 28 Aug 2010 00:06:52 -0700 Subject: rfile.readline() In-Reply-To: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> References: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> Message-ID: On Fri, Aug 27, 2010 at 10:57 PM, sarah wrote: > i want to know that what this function returns??? > > and what does this function do?? RTFM: http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects Honestly, it's the 2nd google hit for "python readline". Regards, Chris From arnodel at googlemail.com Sat Aug 28 03:21:31 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 28 Aug 2010 08:21:31 +0100 Subject: Walking deeply nested lists References: Message-ID: donn writes: > This is all about walking trees, recursion and generators. None of > which fit my brain at all! > > From an XML tree (an SVG file) I build a bunch of Tag objects. > > [I use lxml, but I am combining multiple svg files into a 'forest' of > trees, so I can't use the lxml walking methods because they all stop > at the 'end' of a branch where there is actually a 'link' over to > another tree.] > > Each Tag has a flatwalk() method. The return from that is a list which > can be deeply nested. As an example, something like this: > L=[1, [2, 3, [4, [5, 6], 7], 8], [9, 10] ] > > (The numbers in the example would actually be Tag Instances.) > > Aim 1 > --- > I'm trying to write a generator around such lists so that I can 'walk' them: > > for parent, child in mystery_generator(L): > print level, item > > Right now, I am running a 'flatten' function on the entire list (which > I don't savvy, I found it online) and then I iterate over that > flattened list. This doesn't feel right to me. (Code at end.) > > Aim 2 > --- > The Objects that represent the svg tags use that flatwalk() method to > build the nested list, I'd far prefer flatwalk() to be directly > useable in something like this way: > > for container, child in some_tag.flatwalk(): > print container, child > > The flatwalk() function is (and this is another puzzle see *) kind of > recursive. "For each of my children, tell that child to go > flatwalk()". > (Code at end.) > I am not sure how to turn such a thing into a generator. > > I keep wondering how os.walk() does its thing. My hierarchy of Tag > objects can be thought of as directories (tags:g, symbol, svg), files > (path, circle, etc.) and soft-links (use tags). > > * If an Instance calls a method on *another* Instance of the *same* > class, is this still recursion? And how does this 'stack up'? I mean, > literally, on the stack. Does each instance get its own stack, or does > all the push, call, pop stuff happen in one main stack? > (I worry about recursion depth limits because svg trees can get quite deep.) > > > The walking code so far: > > ## Found code. > def flatten(input): > output = [] > stack = [] > stack.extend(reversed(input)) > while stack: > top = stack.pop() > if isinstance(top, list): > stack.extend(reversed(top)) > else: > output.append(top) > return output not a bad idea. I would rather write it as: def flatten(input): output = [] stack = list(input) while stack: top = stack.pop() if isinstance(top, list): stack.extend(top) else: output.append(top) output.reverse() return output If you want to make it a generator function though, the initial version is better. All you need to do is: * change the line "output.append(top)" to "yield top" * delete the line "return output" Or you can go for the simple recursive approach: def flatten(lst): for el in lst: if isinstance(el, list): for x in flatten(el): yield x else: yield el > ## My walker > def test_walk(e): #lxml Element comes in > obj = ebag_get(e)['obj'] #get a tag object > l=obj.flatwalk() > ll= flatten(l) > #No current solution to get 'parent' in this iterator > #ie. for parent, child in ... > for tag in ll: > print tag > > Here's one of my Tag objects: > > class Brancher(object): > def __init__(self, elem): > self.elem = elem > self.children = [] > > def flatwalk(self): > l=[self] > for child in self.children: > l.append( child.flatwalk() ) #recur(ish)ion here > return l This flattens the list in the flatwalk method (which IMHO it should do given its name!): def flatwalk(self): flatlist = [self] for child in self.children: for el is child.flatwalk(): flatlist.append(el) return flatlist This turns it into a generator method: def flatwalk(self): yield self for child in self.children: for el is child.flatwalk(): yield el This turns it into a generator method which yields parents as well: def flatwalk(self, parent=None): yield self, parent for child in self.children: for el is child.flatwalk(self): yield el Then you can write: for tag, parent in mytag.flatwalk(): ... Of course, for the above to work, "leaf" objects need a modified flatwalk method, e.g.: Class LeafTag: def flatwalk(self, parent=None): yield self, parent HTH (warning: all code untested). -- Arnaud From donn.ingle at gmail.com Sat Aug 28 03:29:26 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 09:29:26 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C78BAD6.2010202@gmail.com> On 28/08/2010 08:43, Peter Otten wrote: > If you call functions within functions (or methods, it doesn't matter) they > consume stack space Right, got it. Darn, but at least there's that setrecursionlimit call. Thanks, \e From no.email at nospam.invalid Sat Aug 28 03:33:10 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 28 Aug 2010 00:33:10 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> Message-ID: <7x39tz42fd.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > The nice thing about it [reference counting] is that it is sort > of deterministic -- one can examine code and determine that an object > is collected at some point in the execution... > Heap marking, OTOH, tends to run at indeterminate times, which could > have an impact if one needs predictable response timings Reference counting has the same problem. If you drop the last reference to a complex structure, it could take quite a long time to free all the components. By contrast there are provably real-time tracing gc schemes, including some parallelizeable ones. One reason CPython still can't run threads on parallel cores is it would have to lock the reference counts every time they're updated, and the slowdown from that is terrible. From donn.ingle at gmail.com Sat Aug 28 03:37:44 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 09:37:44 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C78BCC8.6000009@gmail.com> On 28/08/2010 09:21, Arnaud Delobelle wrote: > This flattens the list in the flatwalk method (which IMHO it should > do given its name!): Heh, I often name things ahead of my actual capacity to implement them! > el is child.flatwalk(): Ah, I see what you mean. I think 'is' is 'in', but I kind of get the idea. > This turns it into a generator method: And thanks for the generator versions too. I shall hack them in and poke them with a stick. > Of course, for the above to work, "leaf" objects need a modified > flatwalk method, e.g.: Yes, My 'stubs' (leaves) do have such, but I will edit to use yield. Thanks a mill. \d From sschwarzer at sschwarzer.net Sat Aug 28 04:42:53 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 28 Aug 2010 10:42:53 +0200 Subject: ftplib limitations? In-Reply-To: References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74E604.6090208@sschwarzer.net> Message-ID: <4C78CC0D.8050606@sschwarzer.net> Hi Lawrence, On 2010-08-28 01:49, Lawrence D'Oliveiro wrote: >> Now it may be that the data connection, after having started >> the transfer, works as it should, but the control connection >> times out because the duration of the transfer is too long. > > It might not be the fault of the FTP server. If you?re going through a > router doing NAT, that could be where the timeout is happening. Good point, thanks! That may explain why it's a low-level socket error instead of a 4xx timeout message from the server which I would have expected. If it's the router, the OP might try to change their router settings to get rid of the problem. Stefan From hobson42 at gmaiil.com Sat Aug 28 04:48:47 2010 From: hobson42 at gmaiil.com (Ian) Date: Sat, 28 Aug 2010 09:48:47 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4C78CD6F.2070008@gmaiil.com> On 27/08/2010 21:51, Jussi Piitulainen wrote: > Meanwhile, I have decided to prefer this: > > def palindromep(s): > def reversed(s): > return s[::-1] > return s == reversed(s) I like this. s[::-1] is obscure and non-obvious, especially to Python noobs. This makes it clear what is going on and why at a cost of very little code. Very helpful to the maintenance programming in 18 months time! Regards Ian From pavlovevidence at gmail.com Sat Aug 28 05:17:06 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 28 Aug 2010 02:17:06 -0700 (PDT) Subject: Walking deeply nested lists References: Message-ID: On Aug 27, 8:21?pm, donn wrote: > Each Tag has a flatwalk() method. The return from that is a list which > can be deeply nested. As an example, something like this: > L=[1, [2, 3, [4, [5, 6], 7], 8], [9, 10] ] > > (The numbers in the example would actually be Tag Instances.) > > Aim 1 > --- > I'm trying to write a generator around such lists so that I can 'walk' them: > > for parent, child in mystery_generator(L): > ? print level, item > > Right now, I am running a 'flatten' function on the entire list (which I > don't savvy, I found it online) and then I iterate over that flattened > list. This doesn't feel right to me. (Code at end.) Hmm. In the past I've argued that iterative techniques are superior to recursive approaches in terms of readability, understandability, and conciseness, and thus Python made the right decision to stress iteration over the Lisp/functional preference for recursion. I did consider recursion to be superior to operate on branched structures like trees. However, lately I've started thinking it's better to use iterative techniques even for situations like that. I say that as someone with no problem getting my head around recursion. Even if you disagree, I think there's value in learning iterative approaches to nested problems, in the same way that there's value to learning recursive approaches to linear problems. So here it is: def flatten_iter(s): stack = list() stack.extend(reversed(s)) while stack: item = stack.pop() if isinstance(item,list): stack.extend(reversed(item)) else: yield item It's simple. Copy the object to flatten onto your stack. Pop one item off the stack. If the item you popped is a list, push each item of that list onto the stack. Otherwise yield the value. Loop until stack is empty. There's many advantages to iterative approaches: 1. Less function call overhead (in time and space, I'd think) 2. Opportunity to optimize by scanning through the stack, something you can't do *at all* with recursion 3. Might be able to avoid things like passing around a namespace 4. Iteration is more readable, understandable, and concise in general (though I'd expect recursion is more refactorable than iteration so as the system grows the refactorability of recursion will start to outweigh other factors) The main advantage of recursion is if you have baggage associated with processing a node which does needed to be passed around. In the iterative approach that state has to be stored on the stack. So in those cases recursion is better. So I'm not suggesting that recursion be avoided (I've probably written a dozen recursive functions in the last week), I'm just saying sometimes it makes sense to use iteration even for problems recursion is tailor-made for. Carl Banks From davea at ieee.org Sat Aug 28 05:18:15 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 28 Aug 2010 05:18:15 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: References: Message-ID: <4C78D457.8040501@ieee.org> kj wrote: > Hi! Does anyone know of an easy way to convert a Unicode string into an image file (either jpg or png)? > > TIA! > > ~k > > The question has no meaning as presently worded. If you have Unicode text that you need to render, so that you end up with an image of the text, as printed in some particular font and style, you'd probably start with PIL. Or perhaps one of the gui packages, like tkinter, wxpython, etc. If you have Unicode that was produced by trying to decode some jpeg image, then back up and don't do that. See the recent thread called "Writing byte stream as jpeg format to disk". The OP there had run a unicode decode on a byte stream that represented a jpeg file, and then tried to encode it again to get the jpeg data. Bad idea. If you have Unicode that specifies a file path that refers to a jpeg file, then you need to open the file, in "rb" mode, and copy it. If you have Unicode that gives the name of a person, and you want a portrait of that person, you need to call a photographer() function. The last one was a weak attempt at humor. DaveA From no.email at nospam.invalid Sat Aug 28 05:34:59 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 28 Aug 2010 02:34:59 -0700 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <7xaao7f5bw.fsf@ruckus.brouhaha.com> Ian writes: > On 27/08/2010 21:51, Jussi Piitulainen wrote: >> Meanwhile, I have decided to prefer this: >> >> def palindromep(s): >> def reversed(s): >> return s[::-1] >> return s == reversed(s) > I like this. > s[::-1] is obscure and non-obvious, especially to Python noobs. Overriding the 'reversed' builtin even in an inner scope is a little bit ugly. If you don't mind some overhead, list(s)==list(reversed(s)) (using the built-in reversed, not the special obscure one) is pretty clear. From davea at ieee.org Sat Aug 28 05:39:53 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 28 Aug 2010 05:39:53 -0400 Subject: rfile.readline() In-Reply-To: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> References: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> Message-ID: <4C78D969.5080707@ieee.org> sarah wrote: > i want to know that what this function returns??? > > and what does this function do?? > > rfile.readline() No way to tell what the function returns from your subject line. As for what calling it does, that depends entirely on the object rfile. If it's an instance of a class you wrote, you'll have to look up in your source code. If it's an instance of one of the built-in system types, or of a class in the standard library, then you can tell by looking up that type. I see standard classes bz2.BZ2File, codecs.StreamReader, distutils.text_file, file, imaplib, mmap, io.IOBase, io.TextIOBase, and multifile. These were from the docs for Python 2.6. Most of these are probably analogous to file, in which case I can elaborate. If rfile is an instance of file, perhaps by doing rfile = open("myfile.txt", "r") then rfile.readline() reads one line from that file, starting at the current position, and leaves the file position after that line. readline() stops when it reaches a newline (which it may convert, depending on the setting of 'rb' versus 'r'), or when it reaches end of file. The trailing newline (if any) is included in the returned string. That string may be in byte form (Python 2.x), or in unicode (Python 3.x). In the latter case, it has been decoded according to parameters of the particular open file. DaveA From arnodel at googlemail.com Sat Aug 28 05:57:52 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 28 Aug 2010 10:57:52 +0100 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <7xaao7f5bw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Ian writes: >> On 27/08/2010 21:51, Jussi Piitulainen wrote: >>> Meanwhile, I have decided to prefer this: >>> >>> def palindromep(s): >>> def reversed(s): >>> return s[::-1] >>> return s == reversed(s) >> I like this. >> s[::-1] is obscure and non-obvious, especially to Python noobs. It may be non-obvious to newcomers, but it is quite a well known idiom. Also, I an not aware that it is customary in python to name predicate functions with a "p" suffix - Python is not Lisp! > > Overriding the 'reversed' builtin even in an inner scope is a little bit > ugly. I agree. > If you don't mind some overhead, list(s)==list(reversed(s)) (using the > built-in reversed, not the special obscure one) is pretty clear. May I suggest a comment instead: def ispalindrome(s): # s[::-1] evaluates to the string s reversed return s == s[::-1] -- Arnaud From __peter__ at web.de Sat Aug 28 06:03:09 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 12:03:09 +0200 Subject: Walking deeply nested lists References: Message-ID: donn wrote: > On 28/08/2010 08:43, Peter Otten wrote: >> If you call functions within functions (or methods, it doesn't matter) >> they consume stack space > > Right, got it. Darn, but at least there's that setrecursionlimit call. But be warned that if you set the limit too high instead of giving you a RuntimeError your program will segfault. Peter From pavlovevidence at gmail.com Sat Aug 28 06:11:59 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 28 Aug 2010 03:11:59 -0700 (PDT) Subject: Walking deeply nested lists References: Message-ID: <1a1f7374-351f-4a57-9b77-cf98a5d90f0b@q40g2000prg.googlegroups.com> On Aug 28, 3:03?am, Peter Otten <__pete... at web.de> wrote: > donn wrote: > > On 28/08/2010 08:43, Peter Otten wrote: > >> If you call functions within functions (or methods, it doesn't matter) > >> they consume stack space > > > Right, got it. Darn, but at least there's that setrecursionlimit call. > > But be warned that if you set the limit too high instead of giving you a > RuntimeError your program will segfault. Ah, an advantage of iteration I forgot: no recursion limits or stack overflows. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 06:40:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 10:40:37 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> Message-ID: <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 00:33:10 -0700, Paul Rubin wrote: > Dennis Lee Bieber writes: >> The nice thing about it [reference counting] is that it is sort >> of deterministic -- one can examine code and determine that an object >> is collected at some point in the execution... >> Heap marking, OTOH, tends to run at indeterminate times, which could >> have an impact if one needs predictable response timings > > Reference counting has the same problem. In theory, yes, but in practice ref counting tends to spread out the performance impact more smoothly. There are exceptions, such as the one you mention below, but as a general rule ref counting isn't subject to the "embarrassing pauses" that tracing garbage collectors tend to be subject to. > If you drop the last reference > to a complex structure, it could take quite a long time to free all the > components. By contrast there are provably real-time tracing gc > schemes, including some parallelizeable ones. I could be wrong, but how can they not be subject to the same performance issue? If you have twenty thousand components that all have to be freed, they all have to be freed whether you do it when the last reference is cleared, or six seconds later when the gc does a sweep. > One reason CPython still > can't run threads on parallel cores is it would have to lock the > reference counts every time they're updated, and the slowdown from that > is terrible. On the other hand, the reason that CPython still has reference counting is that the alternatives tried so far are unacceptably for non-threaded code. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 06:51:16 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 10:51:16 GMT Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4c78ea24$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 09:48:47 +0100, Ian wrote: > On 27/08/2010 21:51, Jussi Piitulainen wrote: >> Meanwhile, I have decided to prefer this: >> >> def palindromep(s): >> def reversed(s): >> return s[::-1] >> return s == reversed(s) > I like this. It's silly, needlessly complicated, and inefficient. Why create a *one line* nested function that only gets called once? Every single time you call the function, it has to create the inner function again, then call it once, then throw it away. Admittedly Python does recreate the inner function from pre-compiled parts, which is quick, but still, it doesn't gain you anything that a simple comment wouldn't give: def palindromep(s): return s == s[::-1] # Compare s to its reverse. > s[::-1] is obscure and non-obvious, especially to Python noobs. *Only* to Python noobs. Slicing is fundamental to Python, and using a slice of [::-1] to reverse something is a basic Python idiom. > This makes it clear what is going on and why at a cost of very little > code. > > Very helpful to the maintenance programming in 18 months time! Only if writing three lines when one would do is your definition of "helpful". -- Steven From no.email at please.post Sat Aug 28 06:55:08 2010 From: no.email at please.post (kj) Date: Sat, 28 Aug 2010 10:55:08 +0000 (UTC) Subject: How to convert (unicode) text to image? References: Message-ID: In Benjamin Kaplan writes: >On Fri, Aug 27, 2010 at 8:01 PM, kj wrote: >> >> >> Hi! =A0Does anyone know of an easy way to convert a Unicode string into a= >n image file (either jpg or png)? >> >Do you mean you have some text and you want an image containing that >text? PIL's ImageDraw module can do that. Thanks for the pointer, but... The documentation I have found for PIL (at http://www.pythonware.com/library/pil/handbook) is beyond atrocious. If this is the only way to learn how to use this library, then I really don't understand how anyone who is not clairvoyant can do it. Example: I went to the docs page for ImageDraw. There I find that the constructor for an ImageDraw.Draw object takes an argument, but *what* this argument should be (integer? object? string?) is left entirely undefined. From the examples given I *guessed* that it was an object of class Image, so I repeated the exercise: I consulted the docs for the Image module. There I learn that the constructor for the Image class takes among its parameters one called "mode" and one called "color", but, here again, what these parameters are is left completely undefined. ("mode" is left both syntactically and semantically undefined; "color" is left syntactically undefined, though the documentation includes a bit by way of semantic definition of this parameter.) What's up with this practice of leaving parameters undefined like this??? Wasn't it obvious to the person writing the Image module docs that without explaining what these parameters should be the documentation is nearly useless? Is such poor documentation an unintended consequence of "duck typing"??? Sorry for the outburst, but unfortunately, PIL is not alone in this. Python is awash in poor documentation. The number two complaint I've heard from those who dislike Python is the poor quality of its documentation, and in particular the fact that function parameters are typically left undefined, as is the case in the PIL docs. I like Python a lot, but I have to agree with this criticism. (The number one complaint has to do with the syntactic significance of whitespace; of course, I find *this* criticism silly.) What is most frustrating about such poor documentation is that it is exactly the opposite from what one would expect from the carefulness and thoroughness found in the PEPs... I have been using Python as my primary scripting language for about one year, after many years of programming in Perl, and now Python is my language of choice. But I must say that the documentation standards I found in the Perl world are *well above* those in the Python world. This is not to say that Perl documentation is always excellent; it certainly has its gaps, as one would expect from volunteer-contributed software. But I don't recall being frustrated by Perl module docs anywhere nearly as often as I am by Python module docs. I have to conclude that the problem with Python docs is somehow "systemic"... From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 06:55:30 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 10:55:30 GMT Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4c78eb21$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 09:22:13 +0300, Jussi Piitulainen wrote: > Terry Reedy writes: >> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: >> > Dave Angel writes: >> >> > There could easily be a .reverse() method on strings. It would return >> > the reversed string, like .swapcase() returns the swapcased string. >> >> Could be, but the main use case seems to be for palindrome testing ;-) >> Given that slicing and reversed() can do the same thing, the need is >> thin. > > The need is quite thin, but immutability of strings is not an issue, > just like there can be .swapcase() though strings are immutable. That is > all I am saying above. You're right, there could be a reversed() method for strings. There could also be a disemvowel method that removes vowels, a randomise method that shuffles the letters around, a studlycaps method that changes the case of each letter randomly, and a method to check that brackets () are well- formed. They would all be useful to somebody. There are lots of different methods that strings could have. Where do you draw the line? Not everything needs to be a built-in method. There is already a standard way to spell "reverse a string": astring[::-1] If you don't like that, you can do this: ''.join(reversed(astring)) I don't object to a hypothetical reverse() method on strings, but the gain is minimal. -- Steven From m.appalakonda at gmail.com Sat Aug 28 07:21:30 2010 From: m.appalakonda at gmail.com (Hot Hot Hot) Date: Sat, 28 Aug 2010 04:21:30 -0700 (PDT) Subject: Simple hack to get $5000 to your *Paypal account Message-ID: <6b9af75f-97a2-4542-8fd2-109544702ebd@g21g2000prn.googlegroups.com> Simple hack to get $5000 to your *Paypal account At http://ucanget.co.cc i have hidden the Paypal Form link in an image. in that website on Right Side below search box, click on image and enter your name and Paypal ID. From ldo at geek-central.gen.new_zealand Sat Aug 28 07:22:14 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 23:22:14 +1200 Subject: ftplib limitations? References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74E604.6090208@sschwarzer.net> <4C78CC0D.8050606@sschwarzer.net> Message-ID: In message <4C78CC0D.8050606 at sschwarzer.net>, Stefan Schwarzer wrote: > In message , Lawrence D'Oliveiro wrote: >> >> It might not be the fault of the FTP server. If you?re going through a >> router doing NAT, that could be where the timeout is happening. > > Good point, thanks! That may explain why it's a low-level > socket error instead of a 4xx timeout message from the > server which I would have expected. The reason why I thought of it was because it kept happening to me back when I was using a D-Link DSL-500 to provide my ADSL connection. Unfortunately... > If it's the router, the OP might try to change their router > settings to get rid of the problem. ... if they?re using a typical consumer ADSL router box like the above, they may not have any NAT table timeout settings to play with to cure the problem. I certainly couldn?t find any in mine. In my case, I solved the problem by using a Linux box as my router. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 07:25:05 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 11:25:05 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> Message-ID: <4c78f210$0$28655$c3e8da3@news.astraweb.com> On Fri, 27 Aug 2010 18:06:19 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> I've repeatedly asked, both here and elsewhere, why reference counting >> isn't "real" garbage collection. Nobody has been able to give me a >> satisfactory answer. As far as I can tell, it's a bit of >> pretentiousness with no basis in objective fact. > > Well, it's a bit of a subjective matter. I'd say it's not real gc > because 1) it's unsound (misses reference cycles), You can add cycle detection to a reference count gc, at the cost of more complexity. If you read the Wikipedia article I linked to, tracing algorithms can also be unsound: Some collectors running in a particular environment can correctly identify all pointers (references) in an object; these are called "precise" (also "exact" or "accurate") collectors, the opposite being a "conservative" or "partly conservative" collector. Conservative collectors have to assume that any bit pattern in memory could be a pointer if (when interpreted as a pointer) it would point into any allocated object. Thus, conservative collectors may have some false negatives, where storage is not released because of accidental fake pointers... http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) > and 2) it requires > constant attention from the mutator to incr and decr the reference > counts. Yes. And? > So developing modules for the CPython API means endlessly > finding and fixing refcount bugs that lead to either crashes/security > failures, or memory leaks. If you program the Java JNI or a typical > Lisp FFI, you'll find that real gc is a lot simpler to use since you > avoid all the refcount maintenance hassles. You allocate memory and > shut your eyes, and the gc takes care of freeing it when it figures out > that you are done. Refcounting is basically a form of manual memory > management, while gc is automatic. That's a problem with the CPython API, not reference counting. The problem is that the CPython API is written at too low a level, beneath that at which the garbage collector exists, so naturally you have to manually manage memory. > Someone said here recently that as a program gets larger, saying "this > will work as long as we do X every time without fail" becomes equal to > saying "this won't work". Substitute "properly maintain all ref counts" > for X and you can see the problem. I've seen released "production" > "tested" Python C modules with subtle refcount bugs on more than one > occasion. In gc'd systems there are fewer places for the code to go > wrong. On the other hand, tracing gcs have their own set of problems too, mostly due to the use of finalizers and attempts to make garbage collection run more predictably. See here: http://publib.boulder.ibm.com/infocenter/javasdk/v1r4m2/topic/com.ibm.java.doc.diagnostics.142j9/html/coexistwithgc.html Quote: For tidying Java resources, think about the use of a clean up routine. When you have finished with an object, call the routine to null out all references, deregister listeners, clear out hash tables, and so on. This is far more efficient than using a finalizer and has the useful side-benefit of speeding up garbage collection. The Garbage Collector does not have so many object references to chase in the next garbage collection cycle. Translated: "Rather than relying on the garbage collector to clean up resources after you, do it yourself, manually, so the garbage collector has less work to do." Tracing garbage collectors aren't a panacea. They're software themselves, and complex software, which means they're subject to bugs like the one which plagued Flash plugin 9: http://gskinner.com/blog/archives/2008/04/failure_to_unlo.html The more complicated the garbage collector, the more scope you have for some interaction between your high-level code and the gc leading to memory not be reclaimed or extreme slowdown. Like this: http://tech.puredanger.com/2009/02/11/linkedblockingqueue-garbagecollection/ -- Steven From arnodel at googlemail.com Sat Aug 28 07:29:08 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 28 Aug 2010 12:29:08 +0100 Subject: How to convert (unicode) text to image? References: Message-ID: kj writes: > Thanks for the pointer, but... > > > The documentation I have found for PIL (at > http://www.pythonware.com/library/pil/handbook) is beyond atrocious. > If this is the only way to learn how to use this library, then I > really don't understand how anyone who is not clairvoyant can do it. > > Example: I went to the docs page for ImageDraw. There I find that > the constructor for an ImageDraw.Draw object takes an argument, > but *what* this argument should be (integer? object? string?) is > left entirely undefined. From the examples given I *guessed* that > it was an object of class Image, so I repeated the exercise: I > consulted the docs for the Image module. There I learn that the > constructor for the Image class takes among its parameters one > called "mode" and one called "color", but, here again, what these > parameters are is left completely undefined. ("mode" is left both > syntactically and semantically undefined; "color" is left syntactically > undefined, though the documentation includes a bit by way of semantic > definition of this parameter.) The first time you read the PIL docs, read the introduction. After that I find the docs pretty easy to use, even though it is true that it is quite terse. E.g. for the mode, look at the "concepts" page in the intro: http://www.pythonware.com/library/pil/handbook/concepts.htm > What's up with this practice of leaving parameters undefined like > this??? Wasn't it obvious to the person writing the Image module > docs that without explaining what these parameters should be the > documentation is nearly useless? Is such poor documentation an > unintended consequence of "duck typing"??? > > Sorry for the outburst, but unfortunately, PIL is not alone in > this. Python is awash in poor documentation. > > The number two complaint I've heard from those who dislike Python > is the poor quality of its documentation, and in particular the > fact that function parameters are typically left undefined, as is > the case in the PIL docs. I like Python a lot, but I have to agree > with this criticism. (The number one complaint has to do with the > syntactic significance of whitespace; of course, I find *this* > criticism silly.) > > What is most frustrating about such poor documentation is that it > is exactly the opposite from what one would expect from the > carefulness and thoroughness found in the PEPs... I find the Python docs very good on the whole. > I have been using Python as my primary scripting language for about > one year, after many years of programming in Perl, and now Python > is my language of choice. But I must say that the documentation > standards I found in the Perl world are *well above* those in the > Python world. This is not to say that Perl documentation is always > excellent; it certainly has its gaps, as one would expect from > volunteer-contributed software. But I don't recall being frustrated > by Perl module docs anywhere nearly as often as I am by Python > module docs. I have to conclude that the problem with Python docs > is somehow "systemic"... I have never programmed in Perl (although I have needed to read some Perl) but over the years I have used C, C++, lisp variants, PHP, Ruby, Caml variants, Haskell, Javascript (and others before the era of the web). I don't find that Python online docs on the web are worse than online docs for any of those languages. -- Arnaud From donn.ingle at gmail.com Sat Aug 28 07:55:40 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 13:55:40 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C78F93C.5070609@gmail.com> On 28/08/2010 11:17, Carl Banks wrote: > It's simple. Copy the object to flatten onto your stack. Pop one item > off the stack. If the item you popped is a list, push each item of > that list onto the stack. Otherwise yield the value. Loop until stack > is empty. Nice. The reversed thing was throwing me, but I think it's so that what comes first in a list will thus come first (on the end) of the stack. > So I'm not suggesting that recursion be avoided (I've probably written > a dozen recursive functions in the last week), I'm just saying > sometimes it makes sense to use iteration even for problems recursion > is tailor-made for. > Thanks for that. In parsing the XML (using lxml) I actually did my own stack thing with while loops, to build the entire Tag object 'tree' ? just because I wanted to see how to do it sans recursion. I still get cold shakes when I scroll past that monster! On the subject of recursion, and looking at my OP object model: the Tag objects that model the tags in an SVG file; how would I 'walk' the object tree without employing recursion? I am stuck on the eventual need to call child.flatwalk() and bang! there's recursion. I get the sense that it would be an external walk() function that does some stackery-trickery and reuturns/yields the tree/branch ? all divorced from the actual objects. So, no flatwalk() methods needed at all. This kind of bothers me because it's nice to have objects 'know' what to do and addressing their siblings and children seems a vital part of that. Look at the case of asking a Tag for its XML source: Say g is a G() instance: print g.get_xml(), would have to do some string churning (specific to a g tag) and then start walking its children and ask them to do specific string stuff (in their contexts). This means I have short methods in each Tag instance that "know" how to represent themselves as XML and they can return that value. If I divorce the thing, it becomes a large loop with a lot of switchy-ifs to engage various blocks of string-fu. I hope that made sense. I can post my code if that would help. \d From donn.ingle at gmail.com Sat Aug 28 07:57:33 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 13:57:33 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C78F9AD.2020508@gmail.com> On 28/08/2010 12:03, Peter Otten wrote: > But be warned that if you set the limit too high instead of giving you a > RuntimeError your program will segfault. Silly question: is there any way to tell the future in this case? I mean, ask for X recursion limit, and catch an error (or something) if that won't fly. \d From jpiitula at ling.helsinki.fi Sat Aug 28 08:11:03 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 15:11:03 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Sat, 28 Aug 2010 09:22:13 +0300, Jussi Piitulainen wrote: >> Terry Reedy writes: >>> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: >>> > Dave Angel writes: >>> >>> > There could easily be a .reverse() method on strings. It would return >>> > the reversed string, like .swapcase() returns the swapcased string. >>> >>> Could be, but the main use case seems to be for palindrome testing ;-) >>> Given that slicing and reversed() can do the same thing, the need is >>> thin. >> >> The need is quite thin, but immutability of strings is not an issue, >> just like there can be .swapcase() though strings are immutable. That is >> all I am saying above. > > You're right, there could be a reversed() method for strings. There > could also be a disemvowel method that removes vowels, a randomise > method that shuffles the letters around, a studlycaps method that > changes the case of each letter randomly, and a method to check that > brackets () are well- formed. They would all be useful to > somebody. There are lots of different methods that strings could > have. Where do you draw the line? When I said that there could be such a method, I was merely objecting to a statement, made in response to me, that there could not be such a method because strings are immutable. You clearly agree with me that that statement was not correct. Would you have let it stand if it was made to you? To answer your question, I don't see a real need for .reversed() in strings, but I do think .reversed() would be much more useful than .swapcase() which is in Python now and for which I see no use at all. I have not proposed adding anything to Python. I have only asked if there is any nicer expression for string reversal than [::-1] in Python now, and corrected an incorrect statement that was made in response to me that there could not be a string reversal method because Python strings are immutable. I am still not proposing that anything be added to Python. I have not even criticized Python for not having a nicer expression for string reversal than [::-1]. I have merely asked if there is one, because I didn't know if there is one, and I have shown some snippets of code to illustrate what I might mean by nicer. Someone even understood me. (Thanks.) I think I have received the answer to my question by now - that there is no obviously nicer way, and all other string reversal expressions require some extra cruft and overhead. > Not everything needs to be a built-in method. There is already a > standard way to spell "reverse a string": > > astring[::-1] > > If you don't like that, you can do this: > > ''.join(reversed(astring)) I know. I agree. I was also shown a different way to test for palindromicity, list(s) == list(reversed(s)) which is quite nice apart from the overhead. > I don't object to a hypothetical reverse() method on strings, but > the gain is minimal. I have not suggested that such a method should be added to the language. I merely corrected a statement that there could not be such a method because strings are immutable. I would not have bothered to do even that if that incorrect statement had not been made in response to my own post. I agree that the gain would be minimal. There is no harm in the method either, so I would not object to it if somebody were to propose its addition, but just to clarify my position: I have not proposed it. Hope this helps. From jpiitula at ling.helsinki.fi Sat Aug 28 08:29:07 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 15:29:07 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <7xaao7f5bw.fsf@ruckus.brouhaha.com> Message-ID: Arnaud Delobelle writes: > Also, I an not aware that it is customary in python to name > predicate functions with a "p" suffix - Python is not Lisp! Just to clarify my position: I did not mean to imply that names like palindromep might be customary in Python - clearly they are not - and I am quite aware that Python is not Lisp. My background is elsewhere, I was not paying particular attention to the name at all, and I just could not be bothered to look up what implications any of palindrome, palindromic, ispalindrome, is_palindrome, isPalindrome, has_palindrome_nature, check_palindrome and so on might have in Python. Perhaps I should have used a neutral name like f or test or so, but it did not occur to me at the time. From xrgtn at yandex.ru Sat Aug 28 08:33:05 2010 From: xrgtn at yandex.ru (Alexander Gattin) Date: Sat, 28 Aug 2010 15:33:05 +0300 Subject: GSM to ISO / UCS2 to ISO In-Reply-To: References: Message-ID: <20100828123305.GA11764@xrgtn-q40> Hello, On Mon, Aug 16, 2010 at 08:01:36PM +1000, James Mills wrote: > In an effort to avoid re-inventing the wheel so to speak > I was wondering if anyone's come across libraries/tools, etc > that achieve the same kind of functionality as the tools > library in this java app. unfortunately, no (except some Perl implementations). I'd suggest to add GSM0338 module to standard GNU libc's iconv: /usr/lib/gconv/GSM0338.so /usr/lib/gconv/gconv-modules Probably I'm wrong, but this way it'd become readily available to all programs using iconv(3), including python. > http://code.google.com/p/ipddump/source/browse/trunk/src/ipddump/tools/Gsm2Iso.java I'm Amazed (c) Pixies. This Java code really sucks. -- With best regards, xrgtn From jpiitula at ling.helsinki.fi Sat Aug 28 08:34:07 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 15:34:07 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <7xaao7f5bw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Ian writes: > > On 27/08/2010 21:51, Jussi Piitulainen wrote: > >> Meanwhile, I have decided to prefer this: > >> > >> def palindromep(s): > >> def reversed(s): > >> return s[::-1] > >> return s == reversed(s) > > I like this. > > s[::-1] is obscure and non-obvious, especially to Python noobs. > > Overriding the 'reversed' builtin even in an inner scope is a little > bit ugly. > > If you don't mind some overhead, list(s)==list(reversed(s)) (using > the built-in reversed, not the special obscure one) is pretty clear. Thanks for that. I'm beginning to like it - not its overhead but certainly its natural clarity. It wins over ''.join(reversed(s)) easily, in my eyes. From __peter__ at web.de Sat Aug 28 08:41:45 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 14:41:45 +0200 Subject: Walking deeply nested lists References: Message-ID: donn wrote: > On 28/08/2010 12:03, Peter Otten wrote: >> But be warned that if you set the limit too high instead of giving you a >> RuntimeError your program will segfault. > Silly question: is there any way to tell the future in this case? I > mean, ask for X recursion limit, and catch an error (or something) if > that won't fly. I don't think it's a silly question, and I don't think there is an exact answer, even for a given platform. You'll want to stay well below the number calculated by the following script: import os import subprocess SCRIPT = "tmp_check.py" def ok(n): return subprocess.call(["python", SCRIPT, str(n)]) == 0 if __name__ == "__main__": if not os.path.exists(SCRIPT): with open(SCRIPT, "w") as out: out.write("""\ import sys def f(): return f() if __name__ == "__main__": n = int(sys.argv[1]) sys.setrecursionlimit(n) try: f() except RuntimeError: pass """) low = 1000 while True: new_low = 2*low if not ok(new_low): high = new_low break low = new_low while high - low > 1: mid = (low + high) // 2 if ok(mid): low = mid else: high = mid print "max recursion limit", low, high BTW, I didn't expect it but I get different results on different runs. Peter From aahz at pythoncraft.com Sat Aug 28 08:42:55 2010 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2010 05:42:55 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> Message-ID: In article <4c78572c$0$28655$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Fri, 27 Aug 2010 09:16:52 -0700, Aahz wrote: >> In article , MRAB >> wrote: >>> >>>An object will be available for garbage collection when nothing refers >>>to it either directly or indirectly. If it's unreferenced then it will >>>go away. >> >> This isn't actually garbage collection as most people think of it. >> Refcounting semantics mean that objects get reaped as soon as nothing >> points at them. OTOH, CPython does also have garbage collection to back >> up refcounting so that when you have unreferenced object cycles they >> don't stay around. > >I've repeatedly asked, both here and elsewhere, why reference counting >isn't "real" garbage collection. Nobody has been able to give me a >satisfactory answer. As far as I can tell, it's a bit of pretentiousness >with no basis in objective fact. You'll notice that I was very careful to qualify my statement with "as most people think of it". Also, because CPython has two different memory management mechanisms, refcounting and cycle detection, and the module that controls cycle detection is called "gc", I think it's simpler to follow along with the Python docs -- and critically important to remind people that there are in fact two different systems. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From aahz at pythoncraft.com Sat Aug 28 08:44:17 2010 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2010 05:44:17 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> Message-ID: In article <4c78e7a5$0$28655$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > >On the other hand, the reason that CPython still has reference counting >is that the alternatives tried so far are unacceptably for non-threaded >code. No, it's *a* reason, the other main reason being that refcounting is much easier for a random C library. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From joncle at googlemail.com Sat Aug 28 08:57:25 2010 From: joncle at googlemail.com (Jon Clements) Date: Sat, 28 Aug 2010 05:57:25 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4648f9ab-5890-4018-aa4c-83bd38db4925@t20g2000yqa.googlegroups.com> On Aug 28, 11:55?am, Steven D'Aprano wrote: > On Sat, 28 Aug 2010 09:22:13 +0300, Jussi Piitulainen wrote: > > Terry Reedy writes: > >> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: > >> > Dave Angel writes: [snip] > Not everything needs to be a built-in method. There is already a standard > way to spell "reverse a string": > > astring[::-1] > > If you don't like that, you can do this: > > ''.join(reversed(astring)) I've had to debug code that assumed str(reversed('abc')) == 'cba' >>> str(reversed('abc')) '' So, a str doesn't "construct" like tuple/list...it's a call to __str__(). It's designated as a "friendly print out" (that's my phrasing). >>> list('abc') ['a', 'b', 'c'] I s'pose str is special (2.6) in some way, but it doesn't parallel the other builtins. [Not at Terry / Steve intended -- just most relevant post to respond to] Jon. From xrgtn at yandex.ru Sat Aug 28 09:11:29 2010 From: xrgtn at yandex.ru (Alexander Gattin) Date: Sat, 28 Aug 2010 16:11:29 +0300 Subject: Trouble importing cx_Oracle on HPUX In-Reply-To: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> References: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> Message-ID: <20100828131129.GB11764@xrgtn-q40> Hello, On Thu, Aug 26, 2010 at 08:08:42PM -0700, Cliff Martin wrote: > I have just gotten done building Python 3.1.2 on > HPUX 11.31 Itanium (IA64) using gcc 4.4.3, and > have tried building cx_Oracle to go with it. The > build succeeds, but test and importing does not. > I have tried building Python with threads and > without. The only exotic thing I do with the > configure for python is to supply -mlp64, which BTW, did you build all GNU toolchain in 64 bit mode? I made some tries to get 64bit python etc but stubmled over compilation errors and didn't get enough free time to finish the effort. > makes it a 64 bit build. Python 3 appears to > work just fine, and cx_Oracle has worked on this > same architecture in the past with Python 2.6.5. did you try to start python -d and >>> import cx_Oracle? It may reveal that some symbols in libnnz10 aren't resolvable. If this is the case, try linking with bith libttsh10 and libnnz10: .../cx_Oracle-x.y.z $ LDFLAGS="-lttsh10" python setup.py install Alternatively, try linking against "static" version of libclntsh10 -- libclntst10. -- With best regards, xrgtn From cliff.martin at gmail.com Sat Aug 28 09:27:05 2010 From: cliff.martin at gmail.com (Cliff Martin) Date: Sat, 28 Aug 2010 09:27:05 -0400 Subject: Trouble importing cx_Oracle on HPUX In-Reply-To: <20100828131129.GB11764@xrgtn-q40> References: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> <20100828131129.GB11764@xrgtn-q40> Message-ID: Hi, thank you for getting back to me. Yes, our entire toolchain is 64 bit - a mix of stuff I have downloaded and built and some packages from HP (in the form of depot files) GCC was downloaded from HP, for example. I had to manually add -mlp64 to the CC and CXX lines in the Python Makefile to get it to build 64 bit Python 3. I also had to define PATH_MAX in about 5 files, because it was not resolving it, and it was just easier to add it than to spend more time trying to make it work. I hate HP-UX, BTW. Python -d did not generate any additional information, and so was not helpful (should this work?). Python -v did, however, and it came up with a number of unresolved symbols all seeming to be from libnnz11.so. I tried linking against all of the *.so files in ORACLE_HOME/lib, but I don't remember trying libttsh11 specifically. I will try it again on Monday. -- Cliff On Sat, Aug 28, 2010 at 9:11 AM, Alexander Gattin wrote: > Hello, > > On Thu, Aug 26, 2010 at 08:08:42PM -0700, Cliff > Martin wrote: > > I have just gotten done building Python 3.1.2 on > > HPUX 11.31 Itanium (IA64) using gcc 4.4.3, and > > have tried building cx_Oracle to go with it. The > > build succeeds, but test and importing does not. > > I have tried building Python with threads and > > without. The only exotic thing I do with the > > configure for python is to supply -mlp64, which > > BTW, did you build all GNU toolchain in 64 bit > mode? I made some tries to get 64bit python etc > but stubmled over compilation errors and didn't > get enough free time to finish the effort. > > > makes it a 64 bit build. Python 3 appears to > > work just fine, and cx_Oracle has worked on this > > same architecture in the past with Python 2.6.5. > > did you try to start python -d and > >>> import cx_Oracle? > > It may reveal that some symbols in libnnz10 aren't > resolvable. If this is the case, try linking with > bith libttsh10 and libnnz10: > > .../cx_Oracle-x.y.z $ LDFLAGS="-lttsh10" python setup.py install > > Alternatively, try linking against "static" > version of libclntsh10 -- libclntst10. > > -- > With best regards, > xrgtn > -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Sat Aug 28 09:32:57 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 28 Aug 2010 09:32:57 -0400 Subject: palindrome iteration In-Reply-To: <4C78CD6F.2070008@gmaiil.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4C78CD6F.2070008@gmaiil.com> Message-ID: <20100828093257.e1bc7af6.darcy@druid.net> On Sat, 28 Aug 2010 09:48:47 +0100 Ian wrote: > > def palindromep(s): > > def reversed(s): > > return s[::-1] > > return s == reversed(s) > I like this. > > s[::-1] is obscure and non-obvious, especially to Python noobs. > > This makes it clear what is going on and why at a cost of very little code. It seems unnecessary to me. Even if you can't figure it out through simple inspection, it takes seconds to fire up Python and type "print 'abc'[::-1]" into it to see what that does. Then you have another tool in your toolbox. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From donn.ingle at gmail.com Sat Aug 28 10:39:16 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 16:39:16 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C791F94.7090802@gmail.com> On 28/08/2010 14:41, Peter Otten wrote: > BTW, I didn't expect it but I get different results on different > runs. Clever code. I will give it a go soonest. Elec off for the next 24 hours in my neck of the woods. Urgh. Python can't "import electricity" just yet :) \d From 2011.love.me at gmail.com Sat Aug 28 11:03:35 2010 From: 2011.love.me at gmail.com (love me) Date: Sat, 28 Aug 2010 08:03:35 -0700 (PDT) Subject: love me Message-ID: <20915819-8858-4374-9442-4fc31885c0c8@x42g2000yqx.googlegroups.com> 1st step add me in like box on my facbook page at this link http://www.facebook.com/pages/loveme/145529285481739 2nd step visit this link http://www.kqzyfj.com/click-3778203-10786395 From xrgtn at yandex.ru Sat Aug 28 11:20:46 2010 From: xrgtn at yandex.ru (Alexander Gattin) Date: Sat, 28 Aug 2010 18:20:46 +0300 Subject: rouble importing cx_Oracle on HPUX In-Reply-To: References: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> <20100828131129.GB11764@xrgtn-q40> Message-ID: <20100828152046.GA16623@xrgtn-q40> Hello, On Sat, Aug 28, 2010 at 09:27:05AM -0400, Cliff Martin wrote: > Yes, our entire toolchain is 64 bit - a mix of > stuff I have downloaded and built and some > packages from HP (in the form of depot files) > GCC was downloaded from HP, for example. I see. I bootstrapped from bundled cc, hence all the problems. > Python -d did not generate any additional > information, and so was not helpful (should this > work?). Oops I was wrong about the python -d -- correct option is -v of course... > Python -v did, however, and it came up with a > number of unresolved symbols all seeming to be > from libnnz11.so. I tried linking against all of > the *.so files in ORACLE_HOME/lib, but I don't > remember trying libttsh11 specifically. I will > try it again on Monday. You're using Oracle 11 vs our v10 (we also have v8, v9 and v11 in production, but not on this HP-UX server), but I think the problem with the libnnz is the same: Oracle doesn't put correct shared library dependencies into the libnnzXX.so dynamic section header (it should list libttshXX.so as NEEDED but apperently doesn't). Probably their distribution for Solaris is better, I didn't check (I'll ask our DBAs on Monday). -- With best regards, xrgtn From deepud at gmail.com Sat Aug 28 12:14:53 2010 From: deepud at gmail.com (agnibhu) Date: Sat, 28 Aug 2010 09:14:53 -0700 (PDT) Subject: Tag parsing in python Message-ID: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Hi all, I'm a newbie in python. I'm trying to create a library for parsing certain keywords. For example say I've key words like abc: bcd: cde: like that... So the user may use like abc: How are you bcd: I'm fine cde: ok So I've to extract the "How are you" and "I'm fine" and "ok"..and assign them to abc:, bcd: and cde: respectively.. There may be combination of keyowords introduced in future. like abc: xy: How are you So new keywords qualifying the other keywords so on.. So I would like to know the python way of doing this. Is there any library already existing for making my work easier. ? ~ Agnibhu From lambdadmitry at gmail.com Sat Aug 28 13:30:39 2010 From: lambdadmitry at gmail.com (Dmitry Groshev) Date: Sat, 28 Aug 2010 21:30:39 +0400 Subject: Functional composition in python Message-ID: Hello all. Some time ago I wrote a little library: http://github.com/si14/python-functional-composition/ , inspired by modern functional languages like F#. In my opinion it is quite useful now, but I would like to discuss it. An example of usage: import os from pyfuncomp import composable, c, _ def comment_cutter(s): t = s.find("#") return s if t < 0 else s[0:t].strip() @composable #one can use a decorator to make a composable function def empty_tester(x): return len(x) > 0 and x[0] != "#" path_prefix = "test" config_parser = (c(open) >> #or use a transformer function c(str.strip).map >> #"map" acts like a function modifier c(comment_cutter).map >> empty_tester.filter >> #so does "filter" c(os.path.join)[path_prefix, _].map) #f[a, _, b] is used to make a partial. #f[a, foo:bar, baz:_] is also correct print config_parser("test.txt") print (c("[x ** %s for x in %s]")[2, _] << c(lambda x: x * 2).map)([1, 2, 3]) Any suggestions are appreciated. From python.list at tim.thechases.com Sat Aug 28 13:44:37 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 28 Aug 2010 12:44:37 -0500 Subject: Tag parsing in python In-Reply-To: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: <4C794B05.6010906@tim.thechases.com> On 08/28/10 11:14, agnibhu wrote: > For example say I've key words like abc: bcd: cde: like that... So the > user may use like > abc: How are you bcd: I'm fine cde: ok > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > assign them to abc:, bcd: and cde: respectively.. For this, you can do something like >>> s = "abc: how are you bcd: I'm fine cde: ok" >>> import re >>> r = re.compile(r'(\w+):\s*((?:[^:](?!\w+:))*)') >>> r.findall(s) [('abc', 'how are you'), ('bcd', "I'm fine"), ('cde', 'ok')] Yes, it's a bit of a gnarled regexp, but it seems to do the job. > There may be combination of keyowords introduced in future. > like abc: xy: How are you So new keywords qualifying the other > keywords so on. I'm not sure I understand this bit of what you're asking. If you have s = "abc: xy: How are you" why should that not be parsed as >>> r.findall("abc: xy: How are you") [('abc', ''), ('xy', 'How are you')] as your initial description prescribes? -tkc From cocolombo at gmail.com Sat Aug 28 13:48:14 2010 From: cocolombo at gmail.com (cocolombo) Date: Sat, 28 Aug 2010 10:48:14 -0700 (PDT) Subject: Object containing a list of objects. Message-ID: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Hello. I am putting objects (test) into a container object (tests) and the test object is also a container for a another list of object (scores). Problem is that all instances of class tests have the same value. To illustrate: class score(object): val = 0 def __init__(self, val): self.val = val def __str__(self): return str(self.val) + "\n" class test(object): listOfScores = [] def __str__(self): ret = "" for s in self.listOfScores: ret += str(s) return ret class tests(object): listOfTest = [] def __str__(self): ret = "" for t in self.listOfTest: ret += str(t) return ret Now I run the script : ====================== score1 = score(10) score2 = score(20) score3 = score(30) score4 = score(40) test1 = test() test2 = test() test1.listOfScores.append(score1) test1.listOfScores.append(score2) test2.listOfScores.append(score3) test2.listOfScores.append(score4) theTests = tests() theTests.listOfTest.append(test1) theTests.listOfTest.append(test2) print theTests.listOfTest[0] print theTests.listOfTest[1] ============== This is the data structure I am EXPECTING: theTests ----test1 ---score1=10 ---score2=20 ----test2 ---score3=30 ---score4=40 But what I get is this: theTests ----test1 ---score1=10 ---score2=20 ---score3=30 ---score4=40 ----test2 ---score1=10 ---score2=20 ---score3=30 ---score4=40 What is wrong ? Thanks From __peter__ at web.de Sat Aug 28 14:02:40 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 20:02:40 +0200 Subject: Object containing a list of objects. References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Message-ID: cocolombo wrote: > Problem is that all instances of class tests have the same value. > > To illustrate: > class tests(object): > listOfTest = [] This makes listOfTest a class attribute. To get one list per instance define it in the initializer: class Tests(object): def __init__(self): self.tests = [] Peter From python at mrabarnett.plus.com Sat Aug 28 14:04:16 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 19:04:16 +0100 Subject: Object containing a list of objects. In-Reply-To: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Message-ID: <4C794FA0.7050209@mrabarnett.plus.com> On 28/08/2010 18:48, cocolombo wrote: > Hello. > > I am putting objects (test) into a container object (tests) and the > test object is also a container for a another list of object > (scores). > > Problem is that all instances of class tests have the same value. > > To illustrate: > > class score(object): > val = 0 > def __init__(self, val): > self.val = val > def __str__(self): > return str(self.val) + "\n" > > class test(object): > listOfScores = [] > def __str__(self): > ret = "" > for s in self.listOfScores: > ret += str(s) > return ret > > class tests(object): > listOfTest = [] > def __str__(self): > ret = "" > for t in self.listOfTest: > ret += str(t) > return ret > > > Now I run the script > : > ====================== > score1 = score(10) > score2 = score(20) > score3 = score(30) > score4 = score(40) > > test1 = test() > test2 = test() > > > test1.listOfScores.append(score1) > test1.listOfScores.append(score2) > test2.listOfScores.append(score3) > test2.listOfScores.append(score4) > > theTests = tests() > theTests.listOfTest.append(test1) > theTests.listOfTest.append(test2) > > print theTests.listOfTest[0] > print theTests.listOfTest[1] > > ============== > > This is the data structure I am EXPECTING: > > theTests > ----test1 > ---score1=10 > ---score2=20 > ----test2 > ---score3=30 > ---score4=40 > > > But what I get is this: > > theTests > ----test1 > ---score1=10 > ---score2=20 > ---score3=30 > ---score4=40 > ----test2 > ---score1=10 > ---score2=20 > ---score3=30 > ---score4=40 > > What is wrong ? > When you write: class test(object): listOfScores = [] you're making 'listOfScores' an attribute of the class. If you want it to be an attribute of an instance you should write: class test(object): def __init__(self): self.listOfScores = [] From clp2 at rebertia.com Sat Aug 28 14:11:18 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 28 Aug 2010 11:11:18 -0700 Subject: Object containing a list of objects. In-Reply-To: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Message-ID: On Sat, Aug 28, 2010 at 10:48 AM, cocolombo wrote: > Hello. > > I am putting objects (test) into a container object (tests) and the > test object is also a container for a another list of object > (scores). > > Problem is that all instances of class tests have the same value. > > To illustrate: > > class score(object): > ? ?val = 0 The previous line does nothing useful; delete it. > ? ?def __init__(self, val): > ? ? ? ?self.val = val > ? ?def __str__(self): > ? ? ? ?return str(self.val) + "\n" > > class test(object): > ? ?listOfScores = [] No! This makes the list a class/static variable *shared between all instances*. Delete the previous line and define a proper initializer: def __init__(self): self.listOfScores = [] > ? ?def __str__(self): > ? ? ? ?ret = "" > ? ? ? ?for s in self.listOfScores: > ? ? ? ? ? ?ret += str(s) > ? ? ? ?return ret > > class tests(object): > ? ?listOfTest = [] Again, same problem. def __init__(self): self.listOfTest = [] > ? ?def __str__(self): > ? ? ? ?ret = "" > ? ? ? ?for t in self.listOfTest: > ? ? ? ? ? ?ret += str(t) > ? ? ? ?return ret That is more efficiently+concisely written as: return "".join(str(t) for t in self.listOfTest) > Now I run the script > : > ====================== > score1 = score(10) > score2 = score(20) > score3 = score(30) > score4 = score(40) > > test1 = test() > test2 = test() > > > test1.listOfScores.append(score1) > test1.listOfScores.append(score2) > test2.listOfScores.append(score3) > test2.listOfScores.append(score4) > > theTests = tests() > theTests.listOfTest.append(test1) > theTests.listOfTest.append(test2) > > print theTests.listOfTest[0] > print theTests.listOfTest[1] > > ============== > > This is the data structure I am EXPECTING: > But what I get is this: > What is wrong ? Python is not Java/C# and has no instance variable declarations. You just assign to an attribute of self in __init__ and *that* is what creates instance variables. Any variables you assign to directly in the class body (as you were doing with listOfScores and listOfTest) are made class variables (Java lingo: "static variables"), and are /shared between all instances/, which is rarely what one actually wants. To get regular instance variables, define a proper __init__() and assign the variables to self therein. Also, per PEP 8 (http://www.python.org/dev/peps/pep-0008/ ): - Classes are conventionally CapitalizedWords, so name your classes Score, Test, and Tests rather than score, test, and tests. - Variables/methods are conventionally underscored_between_words, so list_of_test rather than listOfTest. Cheers, Chris -- http://blog.rebertia.com From cocolombo at gmail.com Sat Aug 28 14:11:42 2010 From: cocolombo at gmail.com (cocolombo) Date: Sat, 28 Aug 2010 11:11:42 -0700 (PDT) Subject: Object containing a list of objects. References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Message-ID: <31d02de9-c7f8-42d2-9390-70f7ddbda7e2@v41g2000yqv.googlegroups.com> Thanks MRAB and Peter Otten that solved the problem. From cocolombo at gmail.com Sat Aug 28 14:23:38 2010 From: cocolombo at gmail.com (cocolombo) Date: Sat, 28 Aug 2010 11:23:38 -0700 (PDT) Subject: Object containing a list of objects. References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> <31d02de9-c7f8-42d2-9390-70f7ddbda7e2@v41g2000yqv.googlegroups.com> Message-ID: <317b3a26-fbc8-45dc-9fcb-df252dc782d6@q22g2000yqm.googlegroups.com> Chris I take good notice of your comments and suggestions. Thanks. From nikos.the.gr33k at gmail.com Sat Aug 28 15:10:01 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 12:10:01 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> Message-ID: <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> On 20 ???, 09:04, Nik Gr wrote: > With regard to the "%" operator, it considers the string on the left to > be a format string with multiple %blah things in it to replace. The > thing on the right is a sequence of items to place into the format > string. Can you please clarify what you mean by that? > In you usage above you're supplying "page" instead of "(page,)". > The latter matches the .execute() method's requirements. I tried it and "page" as a string and not a as a single element tuple works ok. From __peter__ at web.de Sat Aug 28 15:13:25 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 21:13:25 +0200 Subject: Functional composition in python References: Message-ID: Dmitry Groshev wrote: > Hello all. Some time ago I wrote a little library: > http://github.com/si14/python-functional-composition/ , inspired by > modern functional languages like F#. In my opinion it is quite useful > now, but I would like to discuss it. > An example of usage: > > import os > from pyfuncomp import composable, c, _ > > def comment_cutter(s): > t = s.find("#") > return s if t < 0 else s[0:t].strip() > > @composable #one can use a decorator to make a composable function > def empty_tester(x): > return len(x) > 0 and x[0] != "#" > > path_prefix = "test" > > config_parser = (c(open) >> #or use a transformer function > c(str.strip).map >> #"map" acts like a function modifier > c(comment_cutter).map >> > empty_tester.filter >> #so does "filter" > c(os.path.join)[path_prefix, _].map) #f[a, _, b] is > used to make a partial. > #f[a, foo:bar, > baz:_] is also correct > > print config_parser("test.txt") > Any suggestions are appreciated. With some effort you could perhaps tweak your library to accept something like config_parser = c(open) | str.strip | comment_cutter | empty_tester | c(os.path.join)(path_prefix, _) This looks more like a shell pipe than a C++ print statement -- which I think is a good thing. More general: Yes, I know that the functional style is contagious. However, I find that more traditional Python code is easier to understand. Compare: import os def config_parser(configfile, folder): with open(configfile) as lines: for line in lines: name = line.partition("#")[0].strip() if name: yield os.path.join(folder, name) for path in config_parser("test.txt", "test"): print path (at least that's what I'm guessing your code is trying to achieve) Peter From python at mrabarnett.plus.com Sat Aug 28 15:35:08 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 20:35:08 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> Message-ID: <4C7964EC.4080500@mrabarnett.plus.com> On 28/08/2010 20:10, ????? wrote: > On 20 ???, 09:04, Nik Gr wrote: >> With regard to the "%" operator, it considers the string on the left to >> be a format string with multiple %blah things in it to replace. The >> thing on the right is a sequence of items to place into the format >> string. > > Can you please clarify what you mean by that? > Basically: format_string % (item_1, item_2, item_3) >> In you usage above you're supplying "page" instead of "(page,)". >> The latter matches the .execute() method's requirements. > > I tried it and "page" as a string and not a as a single element tuple > works ok. Although the .execute() method might accept a single string: cursor.execute(sql_query, page) as well as a tuple containing the string: cursor.execute(sql_query, (page, )) try to be consistent. As I said before: """When there's more than one value you provide a tuple. It's makes sense from the point of view of consistency that you also provide a tuple when there's only one value.""" From nikos.the.gr33k at gmail.com Sat Aug 28 15:37:09 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 28 Aug 2010 12:37:09 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> Message-ID: <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> On 22 ???, 10:27, ????? wrote: > On 16 ???, 14:31, Peter Otten <__pete... at web.de> wrote: > > > > > > > > > > > ????? wrote: > > > # initializecookie > > >cookie=Cookie.SimpleCookie() > > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > > mycookie =cookie.get('visitor') > > > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > > > yandex|13448|spider|crawl)', host ) is None: > > > ? ? blabla... > > > ======================== > > > > I checked and Chrome has acookienames visitor with a value ofnikos > > > within. > > > So, i have to ask why the if fails? > > > Maybe it's because != != == > > Iwant ti if code block to be executed only if the browsercookienames > visitor fetched doesnt cotnain the vbalue of 'nikos' > > Is there somethign wrong with the way i wrote it? Please do help me with this too becaus eif i dont solve this my website keeps count my each visit like iam a guest visitor! From nikos.the.gr33k at gmail.com Sat Aug 28 15:48:52 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 12:48:52 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> Message-ID: <877b27f8-061c-4a0e-bc96-aa66a889519f@f6g2000yqa.googlegroups.com> On 28 ???, 22:35, MRAB wrote: > On 28/08/2010 20:10, ????? wrote:> On 20 ???, 09:04, Nik Gr ?wrote: > >> With regard to the "%" operator, it considers the string on the left to > >> be a format string with multiple %blah things in it to replace. The > >> thing on the right is a sequence of items to place into the format > >> string. > > > Can you please clarify what you mean by that? > > Basically: > > ? ? ?format_string % (item_1, item_2, item_3) I still don't follow by means that i dotn see the point here... > > >> In you usage above you're supplying "page" instead of "(page,)". > >> The latter matches the .execute() method's requirements. > > > I tried it and "page" as a string and not a as a single element tuple > > works ok. > > Although the .execute() method might accept a single string: > > ? ? ?cursor.execute(sql_query, page) > > as well as a tuple containing the string: > > ? ? ?cursor.execute(sql_query, (page, )) > > try to be consistent. As I said before: > > """When there's more than one value you provide a tuple. It's makes sense > from the point of view of consistency that you also provide a tuple when > there's only one value.""" cursor.execute(sql_query, (page, )) is different than? cursor.execute(sql_query, page, ) ? =========================== Why in mysql string substitution example i have to use page='%s' and in the comma way(automatic mysql convertion i dont need the single quotes and use it as page=%s ? What is the diff? =========================== From nikos.the.gr33k at gmail.com Sat Aug 28 15:51:46 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 12:51:46 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> Message-ID: <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> On 28 ???, 22:35, MRAB wrote: > """When there's more than one value you provide a tuple. It's makes sense > from the point of view of consistency that you also provide a tuple when > there's only one value.""" Can you write something that make use of more than one value? Perhaps you mena somethign like? cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date = %s and host = %s''' , (page,) ) Is this what you mean? All those special format strign identifiers will grab their values out of the tuple? From rami.chowdhury at merton.oxon.org Sat Aug 28 16:07:27 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Sun, 29 Aug 2010 02:07:27 +0600 Subject: String substitution VS proper mysql escaping In-Reply-To: <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> Message-ID: 2010/8/29 ????? : > On 28 ???, 22:35, MRAB wrote: > >> """When there's more than one value you provide a tuple. It's makes sense >> from the point of view of consistency that you also provide a tuple when >> there's only one value.""" > > Can you write something that make use of more than one value? > > > Perhaps you mena somethign like? > > cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date > = %s and host = %s''' , (page,) ) > > Is this what you mean? > > All those special format strign identifiers will grab their values out > of the tuple? Yes, that's exactly right -- they'll try to grab values out of the tuple, and since in that particular code snippet the tuple doesn't contain enough items, you'll get an error :-) HTH, Rami -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From __peter__ at web.de Sat Aug 28 16:07:57 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 22:07:57 +0200 Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> Message-ID: ????? wrote: > On 22 ???, 10:27, ????? wrote: >> On 16 ???, 14:31, Peter Otten <__pete... at web.de> wrote: >> > ????? wrote: >> > > # initializecookie >> > >cookie=Cookie.SimpleCookie() >> > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) >> > > mycookie =cookie.get('visitor') >> >> > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >> > > yandex|13448|spider|crawl)', host ) is None: >> > > blabla... >> > > ======================== >> >> > > I checked and Chrome has acookienames visitor with a value ofnikos >> > > within. >> > > So, i have to ask why the if fails? >> >> > Maybe it's because != != == >> >> Iwant ti if code block to be executed only if the browsercookienames >> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >> Is there somethign wrong with the way i wrote it? > > Please do help me with this too becaus eif i dont solve this my > website keeps count my each visit like iam a guest visitor! In your initial post it sounded like you wanted the if-branch to execute for a user named "nikos", but now it seems that I misunderstood you and swapping 'mycookie.value != "nikos"' for 'mycookie.value == "nikos"' won't help. Maybe you could add a print statement like print mycookie.value to start with your debugging efforts. Peter From python at mrabarnett.plus.com Sat Aug 28 16:09:11 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 21:09:11 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <877b27f8-061c-4a0e-bc96-aa66a889519f@f6g2000yqa.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <877b27f8-061c-4a0e-bc96-aa66a889519f@f6g2000yqa.googlegroups.com> Message-ID: <4C796CE7.8020508@mrabarnett.plus.com> On 28/08/2010 20:48, ????? wrote: > On 28 ???, 22:35, MRAB wrote: >> On 28/08/2010 20:10, ????? wrote:> On 20 ???, 09:04, Nik Gr wrote: >>>> With regard to the "%" operator, it considers the string on the left to >>>> be a format string with multiple %blah things in it to replace. The >>>> thing on the right is a sequence of items to place into the format >>>> string. >> >>> Can you please clarify what you mean by that? >> >> Basically: >> >> format_string % (item_1, item_2, item_3) > > I still don't follow by means that i dotn see the point here... > >> >>>> In you usage above you're supplying "page" instead of "(page,)". >>>> The latter matches the .execute() method's requirements. >> >>> I tried it and "page" as a string and not a as a single element tuple >>> works ok. >> >> Although the .execute() method might accept a single string: >> >> cursor.execute(sql_query, page) >> >> as well as a tuple containing the string: >> >> cursor.execute(sql_query, (page, )) >> >> try to be consistent. As I said before: >> >> """When there's more than one value you provide a tuple. It's makes sense >> from the point of view of consistency that you also provide a tuple when >> there's only one value.""" > > cursor.execute(sql_query, (page, )) > > is different than? > > cursor.execute(sql_query, page, ) > > ? > Yes. The first has 2 arguments: a string and a tuple containing the value of 'page'. The second has 2 arguments: a string and the value of 'page'. > =========================== > Why in mysql string substitution example i have to use page='%s' and > in the comma way(automatic mysql convertion i dont need the single > quotes and use it as page=%s ? > What is the diff? > =========================== In the first case you're doing the substitution yourself, but you might not get it right, leaving your website open an SQL injection attacks. In the second case you're letting the .execute method do the substitution. It will have been written to do it correctly and safely. From python at mrabarnett.plus.com Sat Aug 28 16:12:03 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 21:12:03 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> Message-ID: <4C796D93.20303@mrabarnett.plus.com> On 28/08/2010 20:51, ????? wrote: > On 28 ???, 22:35, MRAB wrote: > >> """When there's more than one value you provide a tuple. It's makes sense >> from the point of view of consistency that you also provide a tuple when >> there's only one value.""" > > Can you write something that make use of more than one value? > > > Perhaps you mena somethign like? > > cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date > = %s and host = %s''' , (page,) ) > > Is this what you mean? > > All those special format strign identifiers will grab their values out > of the tuple? Your example contains 3 placeholders, so it needs 3 values: cursor.execute('''SELECT hits FROM counters WHERE page = %s and date = %s and host = %s''', (page, date, host)) This will be safe. Any quoting that's needed will be done by .execute(). From python at mrabarnett.plus.com Sat Aug 28 16:15:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 21:15:59 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> Message-ID: <4C796E7F.4070105@mrabarnett.plus.com> On 28/08/2010 20:37, ????? wrote: > On 22 ???, 10:27, ????? wrote: >> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >> >> >> >> >> >> >> >> >>> ????? wrote: >>>> # initializecookie >>>> cookie=Cookie.SimpleCookie() >>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>> mycookie =cookie.get('visitor') >> >>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>> yandex|13448|spider|crawl)', host ) is None: >>>> blabla... >>>> ======================== >> >>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>> within. >>>> So, i have to ask why the if fails? >> >>> Maybe it's because != != == >> >> Iwant ti if code block to be executed only if the browsercookienames >> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >> Is there somethign wrong with the way i wrote it? > > Please do help me with this too becaus eif i dont solve this my > website keeps count my each visit like iam a guest visitor! Print out mycookie, repr(mycookie.value) (unless mycookie is None) and repr(host). Then follow the code yourself to see whether the condition is True. From rami.chowdhury at merton.oxon.org Sat Aug 28 16:17:05 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Sun, 29 Aug 2010 02:17:05 +0600 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: On Fri, Aug 27, 2010 at 14:16, Nobody wrote: > On Fri, 27 Aug 2010 13:28:46 +0600, Rami Chowdhury wrote: > >>>> Having this as a separate permission allows normal users to add entries >>>> to log files but not to erase existing entries. >>> >>> Unix/Linux systems can do this already. >> >> Ooh, I didn't know that -- what combination of permissions would I have to >> use to get such an effect? > > You can't do it with permissions, you need to use ext2 attributes. > Specifically, "chattr +a " will set the "append" attribute, > which prevents the file being opened for write except in append mode. > Changing this attribute requires root privilege or the CAP_LINUX_IMMUTABLE > capability. Fascinating, thank you! -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From rami.chowdhury at merton.oxon.org Sat Aug 28 16:19:02 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Sun, 29 Aug 2010 02:19:02 +0600 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: On Sat, Aug 28, 2010 at 05:07, Lawrence D'Oliveiro wrote: > In message , Rami > Chowdhury wrote: > >> On Wed, Aug 25, 2010 at 05:04, Lawrence D'Oliveiro >> wrote: >> >>> In message , Nobody wrote: >>> >>>> Having this as a separate permission allows normal users to add entries >>>> to log files but not to erase existing entries. >>> >>> Unix/Linux systems can do this already. >> >> Ooh, I didn't know that -- what combination of permissions would I >> have to use to get such an effect? > > No special permissions needed at all?just use the syslog(3) functions. > > And the nice thing is, you don?t have to know whether the system logs are > kept on the local machine or on a remote machine, or how different > categories of messages are divided up into different files, how log rotation > is done, or anything like that?it?s all transparent. Ah, thanks -- I think I'd misread your first post as indicating that that kind of "append" effect would work for any file. Apologies for the misunderstanding! -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From davea at ieee.org Sat Aug 28 16:53:12 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 28 Aug 2010 16:53:12 -0400 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4C797738.70803@ieee.org> Jussi Piitulainen wrote: > Steven D'Aprano writes: > >> On Sat, 28 Aug 2010 09:22:13 +0300, Jussi Piitulainen wrote: >> >>> Terry Reedy writes: >>> >>>> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: >>>> >>>>> Dave Angel writes: >>>>> >>>>> There could easily be a .reverse() method on strings. It would return >>>>> the reversed string, like .swapcase() returns the swapcased string. >>>>> >>>> Could be, but the main use case seems to be for palindrome testing ;-) >>>> Given that slicing and reversed() can do the same thing, the need is >>>> thin. >>>> >>> The need is quite thin, but immutability of strings is not an issue, >>> just like there can be .swapcase() though strings are immutable. That is >>> all I am saying above. >>> >> You're right, there could be a reversed() method for strings. There >> could also be a disemvowel method that removes vowels, a randomise >> method that shuffles the letters around, a studlycaps method that >> changes the case of each letter randomly, and a method to check that >> brackets () are well- formed. They would all be useful to >> somebody. There are lots of different methods that strings could >> have. Where do you draw the line? >> > > When I said that there could be such a method, I was merely objecting > to a statement, made in response to me, that there could not be such a > method because strings are immutable. You clearly agree with me that > that statement was not correct. Would you have let it stand if it was > made to you? > > Since you repeat that assertion three times, I figure you must think it's important. And it was I who asserted that a reverse() method wouldn't be possible on an immutable object. reverse() would reverse the characters in place, and return None. At least it would if it tried to be at all consistent with the list, array, and audioop methods of the same name. reversed() is certainly possible, and it'd make a new string with the reverse order of the original. DaveA From david at ombrepixel.com Sat Aug 28 17:37:39 2010 From: david at ombrepixel.com (David ROBERT) Date: Sat, 28 Aug 2010 22:37:39 +0100 Subject: InteractiveConsole and namespace Message-ID: Hi all, I want to use an InteractiveConsole at some stage in a program to interact with the local namespace: access, but also modify objects. When the interactive console ends (ctrl-d) I want the program to continue processing with the variables that may have been modified interactively. The code below works (block invoking the console is not in a function). During the interactive session, I can read value of a, I can change value of a and the new value is "updated" in the block namespace. import code if __name__ == '__main__': a=1 c = code.InteractiveConsole(locals()) c.interact() # Here I interactively change the value of a (a=2) print "Value of a: ", a print returns --> Value of a: 2 However, on the other code below (the console is invoked from within a function block), during the interactive session, I can read value of a, I can change value of a. But the local namespace of the function is not updated: import code def test(): a=1 c = code.InteractiveConsole(locals()) c.interact() # Here I interactively change the value of a (a=2) print "Value of a: ", a if __name__ == '__main__': test() print returns --> Value of a: 1 I need to run the InteractiveConsole from a function block. I tried different things with the local and parent frames (sys._getframe()) but nothing successful. If I put a in the global namespace it works, but I would like to find a nicer solution and also understand what the problem is. Thanks for any help -- David ROBERT http://blog.ombrepixel.com/ From joshua.r.english at gmail.com Sat Aug 28 18:09:16 2010 From: joshua.r.english at gmail.com (Josh English) Date: Sat, 28 Aug 2010 15:09:16 -0700 (PDT) Subject: pyxser-1.5r --- Python Object to XML serializer/deserializer References: <72aa2291-d979-4deb-9e9b-147af2c9d0af@b4g2000pra.googlegroups.com> Message-ID: <245507cb-9936-40bb-83f8-6db7c819ad62@t5g2000prd.googlegroups.com> On Aug 26, 10:02?pm, Stefan Behnel wrote: > Josh English, 27.08.2010 01:30: > > > solve a lot of the problems I'm running into in my own attempt to > > build a python Class implementation of an XML Validation object. > > How would object serialisation help here? > > I'm running into the same problem in a lot of projects I'm working on. I can't decide one the best way to serialize instances of classes. I want to be able to store these instances in a human-readable and editable format that I can reload back into their objects. The XML validation tool requires the rules of the XML to be written out in Python as classes and instances. I would love to have a consistent way to write the definition file and load it. For example, Relax NG can be written out, the rules loaded into a parser, and actual XML data can be validated against it. Since I started in Python, I want that bridge back to serialization. In this project, and others, subclassing plays a big role in using the code, so I need a reliable way of writing a definition, loading it into the proper subclass, and running with those subclasses. I am familiar with XML, but I've played with YAML and may try that. I'm hesitant to use YAML because it requires that I add the YAML.object. I even wrote a program to store data similar to GEDCOM format, which seemed the simplest from a user's perspective. Josh From joshua.r.english at gmail.com Sat Aug 28 18:12:17 2010 From: joshua.r.english at gmail.com (Josh English) Date: Sat, 28 Aug 2010 15:12:17 -0700 (PDT) Subject: Tag parsing in python References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: <83d3d6df-751e-4ef3-8ce9-3c329a0c32aa@s17g2000prh.googlegroups.com> On Aug 28, 9:14?am, agnibhu wrote: > Hi all, > > I'm a newbie in python. I'm trying to create a library for parsing > certain keywords. > For example say I've key words like abc: bcd: cde: like that... So the > user may use like > abc: How are you bcd: I'm fine cde: ok > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > assign them to abc:, bcd: and cde: respectively.. There may be > combination of keyowords introduced in future. like abc: xy: How are > you > So new keywords qualifying the other keywords so on.. > So I would like to know the python way of doing this. Is there any > library already existing for making my work easier. ? > > ~ > Agnibhu Have you looked at pyparsing? (http://pyparsing.wikispaces.com/) It may be possible to use that library to do this. Josh From kevinlcarlson at gmail.com Sat Aug 28 18:31:36 2010 From: kevinlcarlson at gmail.com (kevinlcarlson) Date: Sat, 28 Aug 2010 15:31:36 -0700 (PDT) Subject: Helper app for intranet site Message-ID: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> I'm exploring the possibility of developing a helper app for an existing internal company website. Basically, it would automatically scan the current page contents, including prepopulated forms, and provide context-related business rule comments to the user, via a stay- on-top wxPython panel. Any suggestions on how to do this? (The web developers are unavailable to do this within the site.) Thanks, Kevin From raoulbia at gmail.com Sat Aug 28 19:12:36 2010 From: raoulbia at gmail.com (Baba) Date: Sat, 28 Aug 2010 16:12:36 -0700 (PDT) Subject: Fibonacci: How to think recursively Message-ID: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Level: beginner I would like to know how to approach the following Fibonacci problem: How may rabbits do i have after n months? I'm not looking for the code as i could Google that very easily. I'm looking for a hint to put me on the right track to solve this myself without looking it up. my brainstorming so far brought me to a stand still as i can't seem to imagine a recursive way to code this: my attempted rough code: def fibonacci(n): # base case: result = fibonacci (n-1) + fibonacci (n-2) >> this will end up in a mess as it will create overlapping recursions OR def fibonacci(n): # base case: fibonacci(n+2) - fibonacci(n+1) - n = 0 >> this too would create overlapping recursions How to go about this? Thanks Baba From mwilson at the-wire.com Sat Aug 28 19:54:54 2010 From: mwilson at the-wire.com (Mel) Date: Sat, 28 Aug 2010 19:54:54 -0400 Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: Baba wrote: > Level: beginner > > I would like to know how to approach the following Fibonacci problem: > How may rabbits do i have after n months? > > I'm not looking for the code as i could Google that very easily. I'm > looking for a hint to put me on the right track to solve this myself > without looking it up. > > my brainstorming so far brought me to a stand still as i can't seem to > imagine a recursive way to code this: > > my attempted rough code: > > def fibonacci(n): > # base case: > result = fibonacci (n-1) + fibonacci (n-2) >>> this will end up in a mess as it will create overlapping recursions I don't think this is the base case. The base case would be one or more values of `n` that you already know the fibonacci number for. Your recursive function can just test for those and return the right answer right away. The the expression you've coded contains a good way to handle the non-base cases. There's no such problem as "overlapping recursions". Mel. From clp2 at rebertia.com Sat Aug 28 20:05:12 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 28 Aug 2010 17:05:12 -0700 Subject: InteractiveConsole and namespace In-Reply-To: References: Message-ID: On Sat, Aug 28, 2010 at 2:37 PM, David ROBERT wrote: > Hi all, > > I want to use an InteractiveConsole at some stage in a program to > interact with the local namespace: access, but also modify objects. > When the interactive console ends (ctrl-d) I want the program to > continue processing with the variables that may have been modified > interactively. > > The code below works (block invoking the console is not in a > function). During the interactive session, I can read value of a, I > can change value of a and the new value is "updated" in the block > namespace. > > import code > if __name__ == '__main__': > ? ?a=1 > ? ?c = code.InteractiveConsole(locals()) > ? ?c.interact() ?# Here I interactively change the value of a (a=2) > ? ?print "Value of a: ", a > > print returns --> Value of a: 2 > > However, on the other code below (the console is invoked from within a > function block), during the interactive session, I can read value of > a, I can change value of a. But the local namespace of the function is > not updated: > > import code > def test(): > ? ?a=1 > ? ?c = code.InteractiveConsole(locals()) > ? ?c.interact() # Here I interactively change the value of a (a=2) > ? ?print "Value of a: ", a > > if __name__ == '__main__': > ? ?test() > > print returns --> Value of a: 1 > > I need to run the InteractiveConsole from a function block. I tried > different things with the local and parent frames (sys._getframe()) > but nothing successful. If I put a in the global namespace it works, > but I would like to [...] > understand what the > problem is. Read http://docs.python.org/library/functions.html#locals (emphasis added): "locals() [...] Note: The contents of this dictionary should not be modified; ***changes may not affect the values of local and free variables used by the interpreter***." At the top-level / module scope, it just so happens that `locals() is globals() == True`; and unlike locals(), globals() does not have the aforequoted limitation. I don't know if there's a non-ugly workaround. Cheers, Chris -- http://blog.rebertia.com From ben+python at benfinney.id.au Sat Aug 28 20:23:52 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 29 Aug 2010 10:23:52 +1000 Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: <87hbiegtbb.fsf@benfinney.id.au> Baba writes: > my brainstorming so far brought me to a stand still as i can't seem to > imagine a recursive way to code this: > > my attempted rough code: > > def fibonacci(n): > # base case: > result = fibonacci (n-1) + fibonacci (n-2) > >> this will end up in a mess as it will create overlapping recursions It also never returns anything (which, in Python, means it returns the None object). Worse, it will endlessly recurse; every time it's called it will call itself (twice). Perhaps a way to approach the problem is: How will your function know when *not* to call itself? What will it do instead? Try writing that case first, and then write the rest of it on that basis. -- \ ?Science is a way of trying not to fool yourself. The first | `\ principle is that you must not fool yourself, and you are the | _o__) easiest person to fool.? ?Richard P. Feynman, 1964 | Ben Finney From landimatte at gmail.com Sat Aug 28 20:33:30 2010 From: landimatte at gmail.com (Matteo Landi) Date: Sun, 29 Aug 2010 02:33:30 +0200 Subject: Fibonacci: How to think recursively In-Reply-To: <87hbiegtbb.fsf@benfinney.id.au> References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <87hbiegtbb.fsf@benfinney.id.au> Message-ID: I suggest you to memoize results in order to prevent overlapping recursion. Regards, Matteo On Sun, Aug 29, 2010 at 2:23 AM, Ben Finney wrote: > Baba writes: > >> my brainstorming so far brought me to a stand still as i can't seem to >> imagine a recursive way to code this: >> >> my attempted rough code: >> >> def fibonacci(n): >> ? ? # base case: >> ? ? ? ? result = fibonacci (n-1) + fibonacci (n-2) >> >> this will end up in a mess as it will create overlapping recursions > > It also never returns anything (which, in Python, means it returns the > None object). > > Worse, it will endlessly recurse; every time it's called it will call > itself (twice). > > Perhaps a way to approach the problem is: How will your function know > when *not* to call itself? What will it do instead? Try writing that > case first, and then write the rest of it on that basis. > > -- > ?\ ? ? ? ? ?Science is a way of trying not to fool yourself. The first | > ?`\ ? ? principle is that you must not fool yourself, and you are the | > _o__) ? ? ? ? ? ? ? easiest person to fool.? ?Richard P. Feynman, 1964 | > Ben Finney > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From momo.reina at gmail.com Sat Aug 28 20:50:38 2010 From: momo.reina at gmail.com (mo reina) Date: Sat, 28 Aug 2010 17:50:38 -0700 (PDT) Subject: looking for open source python project Message-ID: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> looking for a python project (preferably something a bit small) that is looking for contributors. the small bit is because i've never worked in a team before and haven't really read source code that's 1000s of lines long, so i'm not too sure i can keep up. my python fu is decent (i think), i recently wrote a small archive/ grimoire program (command line only) that can store multiline text with title, tags, and basic search functionality (not using curses so the entry, once entered, can't be modified), entries are stored in a pickle file. anybody have any suggestions? i'm keen to work on something with others, both for learning and i'd like to do something a bit meaningful, plus i'm sure it's fun. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 21:00:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2010 01:00:10 GMT Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4c79b11a$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 15:11:03 +0300, Jussi Piitulainen wrote: [...] > When I said that there could be such a method, I was merely objecting to > a statement, made in response to me, that there could not be such a > method because strings are immutable. You clearly agree with me that > that statement was not correct. Would you have let it stand if it was > made to you? Ha ha, you're new here aren't you? > To answer your question, I don't see a real need for .reversed() in > strings, but I do think .reversed() would be much more useful than > .swapcase() which is in Python now and for which I see no use at all. It's hard to disagree with that. I'm not entirely sure what the use-case for swapcase is. It's not quite as specialised as sTUdlEycApS but not far off. [...] > I agree that the gain would be minimal. There is no harm in the method > either, so I would not object to it if somebody were to propose its > addition, but just to clarify my position: I have not proposed it. Then we are in agreement :) I think the only thing we disagree on is that I think [::-1] is a perfectly nice expression for reversal, while you don't. True, it's not entirely intuitive to newbies, or self-documenting, you need to learn slicing to understand it. But then, if you were Dutch and had not learned English, you would probably be looking for a method called omgekeerde and would find reverse equally unintuitive. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 21:14:56 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2010 01:14:56 GMT Subject: Functional composition in python References: Message-ID: <4c79b48f$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 21:30:39 +0400, Dmitry Groshev wrote: > Hello all. Some time ago I wrote a little library: > http://github.com/si14/python-functional-composition/ , inspired by > modern functional languages like F#. In my opinion it is quite useful > now, but I would like to discuss it. > An example of usage: > > import os > from pyfuncomp import composable, c, _ > > def comment_cutter(s): > t = s.find("#") > return s if t < 0 else s[0:t].strip() > > @composable #one can use a decorator to make a composable function > def empty_tester(x): > return len(x) > 0 and x[0] != "#" Why do you need a decorator to make a composable function? Surely all functions are composable -- it is the nature of functions that you can call one function with the output of another function. > path_prefix = "test" > > config_parser = (c(open) >> #or use a transformer function > c(str.strip).map >> #"map" acts like a function modifier > c(comment_cutter).map >> > empty_tester.filter >> #so does "filter" > c(os.path.join)[path_prefix, _].map) #f[a, _, b] is > used to make a partial. > #f[a, foo:bar, > baz:_] is also correct > > print config_parser("test.txt") > print (c("[x ** %s for x in %s]")[2, _] << c(lambda x: x * 2).map)([1, > 2, 3]) > > Any suggestions are appreciated. Did you expect us to guess what the above code would do? Without showing the output, the above is just line noise. What does c() do? What does compose() do that ordinary function composition doesn't do? You say that "map" acts as a function modifier, but don't tell us *what* it modifies or in what way. Same for filter. So anyone not familiar with C syntax, the use of << is just line noise. You need to at say what you're using it for. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 22:25:21 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2010 02:25:21 GMT Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: <4c79c510$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 16:12:36 -0700, Baba wrote: > Level: beginner > > I would like to know how to approach the following Fibonacci problem: > How may rabbits do i have after n months? > > I'm not looking for the code as i could Google that very easily. I'm > looking for a hint to put me on the right track to solve this myself > without looking it up. > > my brainstorming so far brought me to a stand still as i can't seem to > imagine a recursive way to code this: Perhaps you need to start with a simpler case to get your head around the ideas. Let's look at factorial first. fact(n) = n*(n-1)*(n-2)*(n-3)*...*2*1 Working upwards: fact(0) = 1 # this is by definition. fact(1) = 1 # also by definition. fact(2) = 2*1 = 2*fact(1) fact(3) = 3*2*1 = 3*fact(2) ... fact(n) = n*fact(n-1) So now you have the base case: if n is 1 or smaller, fact(n) returns 1 and the recursive case: otherwise fact(n) returns n*fact(n-1) Now write that as a Python function, and test it to see that it is correct. Come back once you've got it working satisfactorily. Now, can you apply the same reasoning to the Fibonacci problem? What is your base case? You need some way to halt the recursion, something that *doesn't* make a recursive call. def fib(n): if SOME_CONDITION: return SOME_VALUE else: return SOME_RECURSION is the most basic form you can have. Notice that you must *return* something. That's basic Python syntax -- if you don't call return, the function will return the special None object, which is not what you want. More generally, you could have multiple base cases and multiple recursive cases, not necessarily one of each. But there must be at least one non- recursive expression that gets returned, or the recursion can never terminate. > my attempted rough code: > > def fibonacci(n): > # base case: > result = fibonacci (n-1) + fibonacci (n-2) >>> this will end up in a mess as it will create overlapping recursions Mathematically, there is nothing wrong with overlapping recursion. It will work, and Python can handle it easily. But in practical terms, it can lead to great inefficiency. In this example, it should be avoided because it is slow. Very slow. To calculate the nth Fibonacci number using naive recursion requires *many* calls: fib(4) # first call => fib(3) + fib(2) # three calls => fib(2) + fib(1) + fib(1) + fib(0) # seven calls => fib(1) + fib(0) + 1 + 1 + 0 # nine calls => 1 + 0 + 1 + 1 + 0 = 3 So to get fib(4) = 3 requires nine calls to fib(). This growth function doesn't have a name (as far as I know), but it grows much faster than fib() itself: n = 0 1 2 3 4 5 6 ... 35 ... fib(n) = 0 1 1 2 3 5 8 ... 9227465 ... calls = 1 1 3 5 9 15 25 ... 29860703 ... As you can see, the number of calls is also calculable by a recursive expression R: R(0) = R(1) = 1 R(n) = R(n-1) + R(n-2) + 1 This is very similar to the Fibonacci recursion, only it grows more quickly. But I digress... You can make the recursive version more efficient if you give it a memory. In the call to fib(5), for example, it ends up calling fib(4) once, fib(3) twice, fib(2) three times, fib(1) four times, and fib(0) twice. If it could remember each value once it saw it, it could potentially save nine calls (out of fifteen). That's a less inefficient use of recursion. Think about ways to give it a short-term memory. You can make it even more efficient by giving fib() a long-term cache, so that each call to fib(5) requires one cache lookup rather than six (or fifteen) recursive calls. Other than the first time, obviously. This is called memoisation, but again I digress. There are other techniques, but this will do to get started. -- Steven From lambdadmitry at gmail.com Sat Aug 28 22:54:13 2010 From: lambdadmitry at gmail.com (Dmitry Groshev) Date: Sat, 28 Aug 2010 19:54:13 -0700 (PDT) Subject: Functional composition in python References: <4c79b48f$0$28655$c3e8da3@news.astraweb.com> Message-ID: <6bedbd75-2fc7-43d6-a3ba-e76e4b447db6@l20g2000yqe.googlegroups.com> On Aug 29, 5:14?am, Steven D'Aprano wrote: > On Sat, 28 Aug 2010 21:30:39 +0400, Dmitry Groshev wrote: > > Hello all. Some time ago I wrote a little library: > >http://github.com/si14/python-functional-composition/, inspired by > > modern functional languages like F#. In my opinion it is quite useful > > now, but I would like to discuss it. > > An example of usage: > > > import os > > from pyfuncomp import composable, c, _ > > > def comment_cutter(s): > > ? ? t = s.find("#") > > ? ? return s if t < 0 else s[0:t].strip() > > > @composable #one can use a decorator to make a composable function > > def empty_tester(x): > > ? ? return len(x) > 0 and x[0] != "#" > > Why do you need a decorator to make a composable function? Surely all > functions are composable -- it is the nature of functions that you can > call one function with the output of another function. > > > > > path_prefix = "test" > > > config_parser = (c(open) >> ?#or use a transformer function > > ? ? ? ? ? ? ?c(str.strip).map >> #"map" acts like a function modifier > > ? ? ? ? ? ? ?c(comment_cutter).map >> > > ? ? ? ? ? ? ?empty_tester.filter >> #so does "filter" > > ? ? ? ? ? ? ?c(os.path.join)[path_prefix, _].map) #f[a, _, b] is > > used to make a partial. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #f[a, foo:bar, > > baz:_] is also correct > > > print config_parser("test.txt") > > print (c("[x ** %s for x in %s]")[2, _] << c(lambda x: x * 2).map)([1, > > 2, 3]) > > > Any suggestions are appreciated. > > Did you expect us to guess what the above code would do? Without showing > the output, the above is just line noise. > > What does c() do? What does compose() do that ordinary function > composition doesn't do? You say that "map" acts as a function modifier, > but don't tell us *what* it modifies or in what way. Same for filter. > > So anyone not familiar with C syntax, the use of << is just line noise. > You need to at say what you're using it for. > > -- > Steven Yep, it's my mistake. I thought this syntax is quite intuitive. Here is some explanations in code: @composable def f1(x): return x * 2 @composable def f2(x): return x + 3 @composable def f3(x): return (-1) * x @composable def f4(a): return a + [0] @composable def sqrsum(x, y): return x ** 2 + y ** 2 print f1(2) #4 print f2(2) #5 print (f1 << f2 << f1)(2) #14 print (f3 >> f2)(2) #1 print (f2 >> f3)(2) #-5 print (c(float) << f1 << f2)(4) #14.0 print (sqrsum[_, 1] << f1)(2) #17 print (sqrsum[_, _].map)([1, 2, 3, 4, 5]) #[2, 8, 18, 32, 50] print (c(lambda x: x * 2).map >> c("[x * %s for x in %s]")[3, _])([1, 2, 3]) #[6, 12, 18] Generally, f1 >> f2 means "lambda x: f2(f1(x))" or "pass the result of f1 to f2". But in python function can return only one value, so a composable function should be a function of one argument. So some form of making partial is needed, and here comes a f[a, b, _] notation, which means "substitute 3rd argument of f, first twos are a and b". Finally, we need some form of syntactic sugar for this: c(map)[c(f),_], so we have a "map" modifier, which transforms function F to an isomorphism or mapping between lists. For example, c(lambda x: x * 2).map is equal to lambda x: map(lambda y: y * 2, x). "Filter" modifier is the same thing for boolean functions. >What does c() do? What does compose() do that ordinary function >composition doesn't do? I need c() or composable() to make an objects with overloaded operators. All in all, all this stuff is just a syntactic sugar for nested functions, maps and filters, which brings a new semantics for old operators (so one can call it edsl). From metolone+gmane at gmail.com Sat Aug 28 23:07:23 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 28 Aug 2010 20:07:23 -0700 Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: "Steven D'Aprano" wrote in message news:4c79c510$0$28655$c3e8da3 at news.astraweb.com... > On Sat, 28 Aug 2010 16:12:36 -0700, Baba wrote: > There are other techniques, but this will do to get started. Once you realize recursion for Fibonacci numbers is still fairly slow, look up generator functions :^) -Mark From clp2 at rebertia.com Sun Aug 29 00:19:05 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 28 Aug 2010 21:19:05 -0700 Subject: Fibonacci: How to think recursively In-Reply-To: <4c79c510$0$28655$c3e8da3@news.astraweb.com> References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: On Sat, Aug 28, 2010 at 7:25 PM, Steven D'Aprano wrote: > On Sat, 28 Aug 2010 16:12:36 -0700, Baba wrote: >> Level: beginner >> >> I would like to know how to approach the following Fibonacci problem: >> my attempted rough code: >> >> def fibonacci(n): >> ? ? # base case: >> ? ? ? ? result = fibonacci (n-1) + fibonacci (n-2) >>>> this will end up in a mess as it will create overlapping recursions > > Mathematically, there is nothing wrong with overlapping recursion. It > will work, and Python can handle it easily. > > But in practical terms, it can lead to great inefficiency. In this > example, it should be avoided because it is slow. Very slow. To calculate > the nth Fibonacci number using naive recursion requires *many* calls: > > ? ?fib(4) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# first call > ? ?=> fib(3) + fib(2) ? ? ? ? ? ? ? ? ? ?# three calls > ? ?=> fib(2) + fib(1) + fib(1) + fib(0) ?# seven calls > ? ?=> fib(1) + fib(0) + 1 + 1 + 0 ? ? ? ?# nine calls > ? ?=> 1 + 0 + 1 + 1 + 0 = 3 > > So to get fib(4) = 3 requires nine calls to fib(). > > This growth function doesn't have a name (as far as I know), It's A001595 in OEIS; http://www.research.att.com/~njas/sequences/A001595 "Sometimes called 'Leonardo numbers'" Also apparently "2-ranks of difference sets constructed from Segre hyperovals." > but it grows > much faster than fib() itself: > > n ? ? ?= 0 ? 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? ... 35 ? ? ? ... > fib(n) = 0 ? 1 ? 1 ? 2 ? 3 ? 5 ? 8 ? ... 9227465 ?... > calls ?= 1 ? 1 ? 3 ? 5 ? 9 ? 15 ?25 ?... 29860703 ... > > As you can see, the number of calls is also calculable by a recursive > expression R: > > R(0) = R(1) = 1 > R(n) = R(n-1) + R(n-2) + 1 > > This is very similar to the Fibonacci recursion, only it grows more > quickly. But I digress... Other formulations courtesy OEIS: R(n) = sum(fib(i) for i in range(1, n+1)) - fib(n-1) R(n) = 2*fib(n+1) - 1 Cheers, Chris -- http://blog.rebertia.com From ptmcg at austin.rr.com Sun Aug 29 00:23:13 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 28 Aug 2010 21:23:13 -0700 (PDT) Subject: Tag parsing in python References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: On Aug 28, 11:14?am, agnibhu wrote: > Hi all, > > I'm a newbie in python. I'm trying to create a library for parsing > certain keywords. > For example say I've key words like abc: bcd: cde: like that... So the > user may use like > abc: How are you bcd: I'm fine cde: ok > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > assign them to abc:, bcd: and cde: respectively.. There may be > combination of keyowords introduced in future. like abc: xy: How are > you > So new keywords qualifying the other keywords so on.. > So I would like to know the python way of doing this. Is there any > library already existing for making my work easier. ? > > ~ > Agnibhu Here's how pyparsing can parse your keyword/tags: from pyparsing import Combine, Word, alphas, Group, OneOrMore, empty, SkipTo, LineEnd text1 = "abc: How are you bcd: I'm fine cde: ok" text2 = "abc: xy: How are you" tag = Combine(Word(alphas)+":") tag_defn = Group(OneOrMore(tag))("tag") + empty + SkipTo(tag | LineEnd())("body") for text in (text1,text2): print text for td in tag_defn.searchString(text): print td.dump() print Prints: abc: How are you bcd: I'm fine cde: ok [['abc:'], 'How are you'] - body: How are you - tag: ['abc:'] [['bcd:'], "I'm fine"] - body: I'm fine - tag: ['bcd:'] [['cde:'], 'ok'] - body: ok - tag: ['cde:'] abc: xy: How are you [['abc:', 'xy:'], 'How are you'] - body: How are you - tag: ['abc:', 'xy:'] Now here's how to further use pyparsing to actually use those tags as substitution macros: from pyparsing import Forward, MatchFirst, Literal, And, replaceWith, FollowedBy # now combine macro detection with substitution macros = {} macro_substitution = Forward() def make_macro_sub(tokens): macros[tuple(tokens.tag)] = tokens.body # define macro substitution macro_substitution << MatchFirst( [(Literal(k[0]) if len(k)==1 else And([Literal(kk) for kk in k])).setParseAction(replaceWith(v)) for k,v in macros.items()] ) + ~FollowedBy(tag) return "" tag_defn.setParseAction(make_macro_sub) scan_pattern = macro_substitution | tag_defn test_text = text1 + "\nBob said, 'abc:?' I said, 'bcd:.'" + text2 + "\nThen Bob said 'abc: xy:?'" print test_text print scan_pattern.transformString(test_text) Prints: abc: How are you bcd: I'm fine cde: ok Bob said, 'abc:?' I said, 'bcd:.'abc: xy: How are you Then Bob said 'abc: xy:?' Bob said, 'How are you?' I said, 'I'm fine.' Then Bob said 'How are you?' From greg.ewing at canterbury.ac.nz Sun Aug 29 00:39:00 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 29 Aug 2010 16:39:00 +1200 Subject: palindrome iteration In-Reply-To: <4c79b11a$0$28655$c3e8da3@news.astraweb.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: <8dunm7Fv5nU1@mid.individual.net> Steven D'Aprano wrote: > I'm not entirely sure what the use-case for swapcase is. Obviously it's for correcting things that were typed in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) -- Greg From nikos.the.gr33k at gmail.com Sun Aug 29 01:13:49 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 22:13:49 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> Message-ID: <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> On 28 ???, 23:12, MRAB wrote: > On 28/08/2010 20:51, ????? wrote: > > > > > > > > > > > On 28 ???, 22:35, MRAB ?wrote: > > >> """When there's more than one value you provide a tuple. It's makes sense > >> from the point of view of consistency that you also provide a tuple when > >> there's only one value.""" > > > Can you write something that make use of more than one value? > > > Perhaps you mena somethign like? > > > cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date > > = %s and host = %s''' , (page,) ) > > > Is this what you mean? > > > All those special format strign identifiers will grab their values out > > of the tuple? > > Your example contains 3 placeholders, so it needs 3 values: > > ? ? ?cursor.execute('''SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s''', (page, date, host)) > > This will be safe. Any quoting that's needed will be done by .execute(). Will this also work without the parentheses? > cursor.execute('''SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s''', page, date, host) or python will not allow it cause it might think there are 4 args isntead of two? > cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > date = '%s' and host = '%s' ''', (page, date, host)) Whats happens if i attempt to also quote by single or double quoting the above although now i'm aware that .execute method does the quoting for me? From nikos.the.gr33k at gmail.com Sun Aug 29 01:34:25 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 28 Aug 2010 22:34:25 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> Message-ID: <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> On 28 ???, 23:15, MRAB wrote: > On 28/08/2010 20:37, ????? wrote: > > > > > > > > > > > On 22 ???, 10:27, ????? ?wrote: > >> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ?wrote: > > >>> ????? wrote: > >>>> # initializecookie > >>>> cookie=Cookie.SimpleCookie() > >>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>> mycookie =cookie.get('visitor') > > >>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>> yandex|13448|spider|crawl)', host ) is None: > >>>> ? ? ?blabla... > >>>> ======================== > > >>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>> within. > >>>> So, i have to ask why the if fails? > > >>> Maybe it's because != != == > > >> Iwant ti if code block to be executed only if the browsercookienames > >> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >> Is there somethign wrong with the way i wrote it? > > > Please do help me with this too becaus eif i dont solve this my > > website keeps count my each visit like iam a guest visitor! > > Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > repr(host). Then follow the code yourself to see whether the condition > is True. print mycookie outputs 'None' Thts weird because i check with the browser and the cookie is there! print repr(host) outputs '78-236-176.adsl.cyta.gr' repr(mycookie.value) (unless mycookie is None) and also print mycookie.value gives an error too. Maybe there is not a value method? From nikos.the.gr33k at gmail.com Sun Aug 29 01:35:41 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 22:35:41 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> Message-ID: <7b1b4e8b-835b-4b9a-81fd-9957ec4e9ece@d8g2000yqf.googlegroups.com> On 28 ???, 23:07, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > On 22 ???, 10:27, ????? wrote: > >> On 16 ???, 14:31, Peter Otten <__pete... at web.de> wrote: > >> > ????? wrote: > >> > > # initializecookie > >> > >cookie=Cookie.SimpleCookie() > >> > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >> > > mycookie =cookie.get('visitor') > > >> > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >> > > yandex|13448|spider|crawl)', host ) is None: > >> > > blabla... > >> > > ======================== > > >> > > I checked and Chrome has acookienames visitor with a value ofnikos > >> > > within. > >> > > So, i have to ask why the if fails? > > >> > Maybe it's because != != == > > >> Iwant ti if code block to be executed only if the browsercookienames > >> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >> Is there somethign wrong with the way i wrote it? > > > Please do help me with this too becaus eif i dont solve this my > > website keeps count my each visit like iam a guest visitor! > > In your initial post it sounded like you wanted the if-branch to execute for > a user named "nikos", but now it seems that I misunderstood you and swapping > 'mycookie.value != "nikos"' for 'mycookie.value == "nikos"' won't help. > Maybe you could add a print statement like > > print mycookie.value > > to start with your debugging efforts. > > Peter Maybe > # initialize cookie > cookie = Cookie.SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > mycookie = cookie.get('visitor') wont load the cookie correctly? because print mycookie.value outputs an error. From mahaboobnisha at gmail.com Sun Aug 29 01:43:27 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Sat, 28 Aug 2010 22:43:27 -0700 (PDT) Subject: comp.lang.python Message-ID: www.127760.blogspot.com From kushal.kumaran+python at gmail.com Sun Aug 29 02:11:21 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sun, 29 Aug 2010 11:41:21 +0530 Subject: looking for open source python project In-Reply-To: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> References: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> Message-ID: On Sun, Aug 29, 2010 at 6:20 AM, mo reina wrote: > looking for a python project (preferably something a bit small) that > is looking for contributors. the small bit is because i've never > worked in a team before and haven't really read source code that's > 1000s of lines long, so i'm not too sure i can keep up. > > my python fu is decent (i think), i recently wrote a small archive/ > grimoire program (command line only) that can store multiline text > with title, tags, and basic search functionality (not using curses so > the entry, once entered, can't be modified), entries are stored in a > pickle file. > > anybody have any suggestions? i'm keen to work on something with > others, both for learning and i'd like to do something a bit > meaningful, plus i'm sure it's fun. You can take a look at http://openhatch.org/ -- regards, kushal From joshua.r.english at gmail.com Sun Aug 29 02:53:54 2010 From: joshua.r.english at gmail.com (Josh English) Date: Sat, 28 Aug 2010 23:53:54 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: This whole conversation got interesting, so I thought I'd run some speed tests: The code: from timeit import Timer def is_palindrome_recursive(s): if len(s) <= 1: return True if s[0] != s[-1]: return False else: return is_palindrome(s[1:-1]) def is_palindrome_slice(s): return s == s[::-1] def is_palindrome_list(s): l = list(s) l.reverse() return s == ''.join(l) def is_palindrome_reversed(s): return s == ''.join(reversed(s)) t = Timer("is_palindrome_recursive('madamimadam')", "from __main__ import is_palindrome_recursive") print "is_palindrome_recursive", min(t.repeat()) t = Timer("is_palindrome_slice('madamimadam')", "from __main__ import is_palindrome_slice") print "is_palindrome_slice", min(t.repeat()) t = Timer("is_palindrome_list('madamimadam')", "from __main__ import is_palindrome_list") print "is_palindrome_list", min(t.repeat()) t = Timer("is_palindrome_reversed('madamimadam')", "from __main__ import is_palindrome_reversed") print "is_palindrome_reversed", min(t.repeat()) The results: is_palindrome_recursive 6.32680866827 is_palindrome_slice 1.23618350114 is_palindrome_list 4.60104846653 is_palindrome_reversed 5.99355296513 The slice method is uglier, I have to admit, but it's the fastest of these four on my machine. Josh From fetchinson at googlemail.com Sun Aug 29 03:47:40 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 29 Aug 2010 09:47:40 +0200 Subject: looking for open source python project In-Reply-To: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> References: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> Message-ID: > looking for a python project (preferably something a bit small) that > is looking for contributors. the small bit is because i've never > worked in a team before and haven't really read source code that's > 1000s of lines long, so i'm not too sure i can keep up. > > my python fu is decent (i think), i recently wrote a small archive/ > grimoire program (command line only) that can store multiline text > with title, tags, and basic search functionality (not using curses so > the entry, once entered, can't be modified), entries are stored in a > pickle file. > > anybody have any suggestions? i'm keen to work on something with > others, both for learning and i'd like to do something a bit > meaningful, plus i'm sure it's fun. Have a look at http://wiki.python.org/moin/CodingProjectIdeas Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From niceshoes1 at 163.com Sun Aug 29 03:48:32 2010 From: niceshoes1 at 163.com (jersey-2009) Date: Sun, 29 Aug 2010 00:48:32 -0700 (PDT) Subject: basketball shoe ( http://www.brandtrade66.com/ Message-ID: hox Shoes (http:// www.brandtrade66.com/) shoes shox shoes (http:// www.brandtrade66.com/) nike shox shoe (http:// www.brandtrade66.com/) nike shox shoes ( http://www.brandtrade66.com/ ) shox shoe ( http://www.brandtrade66.com/ ) LV,coach,chanel boots wholesale ( http://www.brandtrade66.com/ ) air force ones (http:// www.brandtrade66.com/) nike trading ( http://www.brandtrade66.com/ ) nike shox ( http://www.brandtrade66.com/ ) shox air ( http://www.brandtrade66.com/) white shoe (http:// www.brandtrade66.com/ ) nike shoe ( http://www.brandtrade66.com/ ) nike air shox ( http://www.brandtrade66.com/) shox r4 tennis shoes (http:// www.brandtrade66.com/ ) tennis shoe ( http://www.brandtrade66.com/) basketball shoe ( http://www.brandtrade66.com/ ) jordan shoe (http:// www.brandtrade66.com/) From arnodel at googlemail.com Sun Aug 29 04:00:08 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 09:00:08 +0100 Subject: InteractiveConsole and namespace References: Message-ID: Chris Rebert writes: > On Sat, Aug 28, 2010 at 2:37 PM, David ROBERT wrote: >> Hi all, >> >> I want to use an InteractiveConsole at some stage in a program to >> interact with the local namespace: access, but also modify objects. >> When the interactive console ends (ctrl-d) I want the program to >> continue processing with the variables that may have been modified >> interactively. >> [...] >> However, on the other code below (the console is invoked from within a >> function block), during the interactive session, I can read value of >> a, I can change value of a. But the local namespace of the function is >> not updated: >> >> import code >> def test(): >> ? ?a=1 >> ? ?c = code.InteractiveConsole(locals()) >> ? ?c.interact() # Here I interactively change the value of a (a=2) >> ? ?print "Value of a: ", a >> >> if __name__ == '__main__': >> ? ?test() >> >> print returns --> Value of a: 1 >> >> I need to run the InteractiveConsole from a function block. I tried >> different things with the local and parent frames (sys._getframe()) >> but nothing successful. If I put a in the global namespace it works, >> but I would like to > [...] >> understand what the >> problem is. > > Read http://docs.python.org/library/functions.html#locals (emphasis added): > > "locals() > [...] > Note: The contents of this dictionary should not be modified; [...] Here is a solution: def test(): a=1 loc = dict(locals()) c = code.InteractiveConsole(loc) c.interact() # Here I interactively change the value of a (a=2) for key in loc: if key != '__builtins__': exec "%s = loc[%r]" % (key, key) print "Value of a: ", a HTH -- Arnaud From lamlbiro at optusnet.com.au Sun Aug 29 04:18:26 2010 From: lamlbiro at optusnet.com.au (L) Date: Sun, 29 Aug 2010 18:18:26 +1000 Subject: PyGeo Message-ID: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu 10.04) , the site says http://www.wspiegel.de/pymaxima/index_en.html "Note: The installation of PyGeo work's only under Python 2.4 (The further development of pygeo seems to be stopped)" is this to do with re-org of site-packages, dist_packages etc. any help most appreciated. TIA From landimatte at gmail.com Sun Aug 29 05:19:24 2010 From: landimatte at gmail.com (Matteo Landi) Date: Sun, 29 Aug 2010 11:19:24 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: Well, I tried the also the solution posted above (recursive w/o slicing and iterative), and I discovered they were the slowest.. is_palindrome_recursive 2.68151649808 is_palindrome_slice 0.44510699381 is_palindrome_list 1.93861944217 is_palindrome_reversed 3.28969831976 is_palindrome_recursive_no_slicing 6.78929775328 is_palindrome_iterative 4.88826141315 Nothing to say about the iterative function, but the benchmark of the recursive was unexpected, at least for my point of view: do you think it is due to the try/except overhead? On Sun, Aug 29, 2010 at 8:53 AM, Josh English wrote: > This whole conversation got interesting, so I thought I'd run some > speed tests: > > The code: > from timeit import Timer > > def is_palindrome_recursive(s): > ? ?if len(s) <= 1: > ? ? ? ?return True > ? ?if s[0] != s[-1]: > ? ? ? ?return False > ? ?else: > ? ? ? ?return is_palindrome(s[1:-1]) > > def is_palindrome_slice(s): > ? ?return s == s[::-1] > > def is_palindrome_list(s): > ? ?l = list(s) > ? ?l.reverse() > ? ?return s == ''.join(l) > > def is_palindrome_reversed(s): > ? ?return s == ''.join(reversed(s)) > > t = Timer("is_palindrome_recursive('madamimadam')", "from __main__ > import is_palindrome_recursive") > print "is_palindrome_recursive", min(t.repeat()) > > t = Timer("is_palindrome_slice('madamimadam')", "from __main__ import > is_palindrome_slice") > print "is_palindrome_slice", min(t.repeat()) > > t = Timer("is_palindrome_list('madamimadam')", "from __main__ import > is_palindrome_list") > print "is_palindrome_list", min(t.repeat()) > > t = Timer("is_palindrome_reversed('madamimadam')", "from __main__ > import is_palindrome_reversed") > print "is_palindrome_reversed", min(t.repeat()) > > The results: > is_palindrome_recursive 6.32680866827 > is_palindrome_slice 1.23618350114 > is_palindrome_list 4.60104846653 > is_palindrome_reversed 5.99355296513 > > The slice method is uglier, I have to admit, but it's the fastest of > these four on my machine. > > Josh > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From osmoma at gmail.com Sun Aug 29 05:39:43 2010 From: osmoma at gmail.com (Osmo Maatta) Date: Sun, 29 Aug 2010 11:39:43 +0200 Subject: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails. Message-ID: <4C7A2ADF.90800@gmail.com> Hello, Sub class test fails. ====================== I have a program that needs to load plugin-classes during runtime. The program has these subdirectories (modules). $ tree . `-- test.py | |-- plugins | |-- base_plugin.py | |-- base_plugin.pyc | |-- __init__.py | `-- oca | |-- __init__.py | |-- open_clipart.py The plugins (sub directory) contains one or more plugin modules, in this test-case there is only one; oca/open_clipart.py. The plugins/base_plugin.py (contains class Plugin()) is a base class of all plugins. I want to list and load all plugin-classes (that inherit from base_plugin.Plugin). I have a Python code that successfully browses the plugins, but the the test issubclass(x, base_plugin.Plugin) fails. Please see this Python code: http://futuredesktop.com/tmp/test6.tar.gz Why the issubclass(entry, cls) test fails? if issubclass(entry, cls): ....print "Found a subclass: " + key ....subclasses.append(entry) I can see that the class names are right, even objects of these classes are ok. My OS is Ubuntu 10.04. $ python --version Python 2.6.5 The actual, final product will be this http://www.futuredesktop.com/clipart-applet/clipart-applet.ogv It is a ClipArt query-engine and browser. It can translate queries from "any" language to english ;-) Most kindly Osmo Antero Maatta Gr?nland, Oslo From hansmu at xs4all.nl Sun Aug 29 05:45:26 2010 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 29 Aug 2010 11:45:26 +0200 Subject: Queue cleanup In-Reply-To: <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > On Sat, 28 Aug 2010 00:33:10 -0700, Paul Rubin wrote: >> If you drop the last reference >> to a complex structure, it could take quite a long time to free all the >> components. By contrast there are provably real-time tracing gc >> schemes, including some parallelizeable ones. > > I could be wrong, but how can they not be subject to the same performance > issue? If you have twenty thousand components that all have to be freed, > they all have to be freed whether you do it when the last reference is > cleared, or six seconds later when the gc does a sweep. Parallelizable garbage collectors have performance issues, but they're not the same issues as mark&sweep collectors have. Parallelizable GCs break up their work in a zillion little pieces and allow the VM to do some real work after each piece. They won't free your twenty thousand components all in one go and you won't have that embarrassing pause. Parallelizable garbage collectors require some careful coordination between the GC and the VM. This takes CPU time, so on the whole they're slower than traditional garbage collectors. So instead of unpredictable embarrassing pauses, you have a VM that's consistently slow. For some applications consistency is more important than raw speed and for these applications parallelizeable GCs are an improvement. HTH, -- HansM From arnodel at googlemail.com Sun Aug 29 06:36:57 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 11:36:57 +0100 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: Matteo Landi writes: > Well, I tried the also the solution posted above (recursive w/o > slicing and iterative), and I discovered they were the slowest.. > > is_palindrome_recursive 2.68151649808 > is_palindrome_slice 0.44510699381 > is_palindrome_list 1.93861944217 > is_palindrome_reversed 3.28969831976 > is_palindrome_recursive_no_slicing 6.78929775328 > is_palindrome_iterative 4.88826141315 What are the last two functions? I suggest another: def is_palindrome(s): return all(map(str.__eq__, s, reversed(s))) :) > Nothing to say about the iterative function, but the benchmark of the > recursive was unexpected, at least for my point of view: do you think > it is due to the try/except overhead? > > On Sun, Aug 29, 2010 at 8:53 AM, Josh English > wrote: >> This whole conversation got interesting, so I thought I'd run some >> speed tests: >> >> The code: >> from timeit import Timer >> >> def is_palindrome_recursive(s): >> ? ?if len(s) <= 1: >> ? ? ? ?return True >> ? ?if s[0] != s[-1]: >> ? ? ? ?return False >> ? ?else: >> ? ? ? ?return is_palindrome(s[1:-1]) This should be return is_palindrome_recursive(s[1:-1]). If this is copy-pasted, then you may call a different is_palindrome function and invalidate the timings! [...] -- Arnaud From arnodel at googlemail.com Sun Aug 29 06:40:28 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 11:40:28 +0100 Subject: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails. References: Message-ID: Osmo Maatta writes: > Hello, > > Sub class test fails. > ====================== > I have a program that needs to load plugin-classes during runtime. > > The program has these subdirectories (modules). > > $ tree > . > `-- test.py > | > |-- plugins > | |-- base_plugin.py > | |-- base_plugin.pyc > | |-- __init__.py > | `-- oca > | |-- __init__.py > | |-- open_clipart.py > > > The plugins (sub directory) contains one or more plugin modules, in this > test-case there is only one; oca/open_clipart.py. > > The plugins/base_plugin.py (contains class Plugin()) is a base class of > all plugins. > > I want to list and load all plugin-classes (that inherit from > base_plugin.Plugin). I have a Python code that successfully browses the > plugins, but the the test issubclass(x, base_plugin.Plugin) fails. > > Please see this Python code: > http://futuredesktop.com/tmp/test6.tar.gz > > Why the issubclass(entry, cls) test fails? > > if issubclass(entry, cls): > ....print "Found a subclass: " + key > ....subclasses.append(entry) > > I can see that the class names are right, even objects of these classes > are ok. > > My OS is Ubuntu 10.04. > $ python --version > Python 2.6.5 > > The actual, final product will be this > http://www.futuredesktop.com/clipart-applet/clipart-applet.ogv > It is a ClipArt query-engine and browser. > It can translate queries from "any" language to english ;-) > > Most kindly > Osmo Antero Maatta > Gr?nland, Oslo Hi, I haven't looked closely at your problem, but are you aware of the __subclasses__ class method? E.g. >>> class A(object): pass ... >>> class B(A): pass ... >>> class C(A): pass ... >>> A.__subclasses__() [, ] >>> This might help you. -- Arnaud From landimatte at gmail.com Sun Aug 29 06:45:54 2010 From: landimatte at gmail.com (Matteo Landi) Date: Sun, 29 Aug 2010 12:45:54 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: I thought they reached you. Here they are again: def palindrome(str, i=0, j=-1): try: if str[i] == str[j]: return palindrome(str, i + 1, j - 1) return False except IndexError: return True def palindrome(str, i=0, j=-1): try: while True: if str[i] != str[j]: return False i, j = i + 1, j - 1 return True except IndexError: return True On Sun, Aug 29, 2010 at 12:36 PM, Arnaud Delobelle wrote: > Matteo Landi writes: > >> Well, I tried the also the solution posted above (recursive w/o >> slicing and iterative), and I discovered they were the slowest.. >> >> is_palindrome_recursive 2.68151649808 >> is_palindrome_slice 0.44510699381 >> is_palindrome_list 1.93861944217 >> is_palindrome_reversed 3.28969831976 >> is_palindrome_recursive_no_slicing 6.78929775328 >> is_palindrome_iterative 4.88826141315 > > What are the last two functions? > > I suggest another: > > def is_palindrome(s): > ? ?return all(map(str.__eq__, s, reversed(s))) > > :) > >> Nothing to say about the iterative function, but the benchmark of the >> recursive was unexpected, at least for my point of view: do you think >> it is due to the try/except overhead? >> >> On Sun, Aug 29, 2010 at 8:53 AM, Josh English >> wrote: >>> This whole conversation got interesting, so I thought I'd run some >>> speed tests: >>> >>> The code: >>> from timeit import Timer >>> >>> def is_palindrome_recursive(s): >>> ? ?if len(s) <= 1: >>> ? ? ? ?return True >>> ? ?if s[0] != s[-1]: >>> ? ? ? ?return False >>> ? ?else: >>> ? ? ? ?return is_palindrome(s[1:-1]) > > This should be return is_palindrome_recursive(s[1:-1]). ?If this is > copy-pasted, then you may call a different is_palindrome function and > invalidate the timings! > > [...] > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From sazzadbinkamal at gmail.com Sun Aug 29 07:04:33 2010 From: sazzadbinkamal at gmail.com (Sazzad Kamal) Date: Sun, 29 Aug 2010 11:04:33 GMT Subject: setuptools msvc build References: Message-ID: <20108297426usenet@eggheadcafe.com> is it possible to build python setuptools with msvc? > On Monday, July 12, 2010 4:59 PM Alf P. Steinbach /Usenet wrote: > I let the setup.py script talk: > > > > > from distutils.core import setup, Extension > import distutils.ccompiler > > compilerName = distutils.ccompiler.get_default_compiler() > options = [] > if compilerName == "msvc": > options.append( "/W4" ) # Must be done in this script. > options.append( "/EHsc" ) # Could be done via CL env. var. > options.append( "/GR" ) # Could be done via CL env. var. > options.append( "/Zc:forScope,wchar_t" ) # Could be done via CL env. var. > > module1 = Extension( > name = "noddy", > sources = [ "noddy.cpp" ], > extra_compile_args = options > ) > > setup( > name = "noddy", > version = '1.0', > description = 'This is a demo package', > ext_modules = [module1] > ) > > > > Cheers, > > - Alf > > -- > Submitted via EggHeadCafe - Software Developer Portal of Choice > Custom Favorites Web Site with MongoDb and NoRM > http://www.eggheadcafe.com/tutorials/aspnet/7fbc7a01-5d30-4cd3-b373-51d4a0e1afa8/custom-favorites-web-site-with-mongodb-and-norm.aspx From __peter__ at web.de Sun Aug 29 07:06:33 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Aug 2010 13:06:33 +0200 Subject: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails. References: Message-ID: Osmo Maatta wrote: > Hello, > > Sub class test fails. > ====================== > I have a program that needs to load plugin-classes during runtime. > > The program has these subdirectories (modules). > > $ tree > . > `-- test.py > | > |-- plugins > | |-- base_plugin.py > | |-- base_plugin.pyc > | |-- __init__.py > | `-- oca > | |-- __init__.py > | |-- open_clipart.py > > > The plugins (sub directory) contains one or more plugin modules, in this > test-case there is only one; oca/open_clipart.py. > > The plugins/base_plugin.py (contains class Plugin()) is a base class of > all plugins. > > I want to list and load all plugin-classes (that inherit from > base_plugin.Plugin). I have a Python code that successfully browses the > plugins, but the the test issubclass(x, base_plugin.Plugin) fails. > > Please see this Python code: > http://futuredesktop.com/tmp/test6.tar.gz > > Why the issubclass(entry, cls) test fails? base_plugin.py is imported twice, once as plugins.base_plugin and a second time as base_plugin. You can see that when you add a bit more debug code into your test.py: --- a/test.py Sun Aug 29 12:57:25 2010 +0200 +++ b/test.py Sun Aug 29 12:58:25 2010 +0200 @@ -24,6 +24,8 @@ #print "entry's class<%s> -- cls's class=<%s>" % (obj1.get_name(), obj2.get_name(), ) print "Check %s against %s" % (entry, cls, ) + print entry.__bases__ + print cls if issubclass(entry, cls): print "Found a subclass: " + key $ python test.py Importing plugins.base_plugin Importing plugins.oca.open_clipart Check against (,) Got subclasses= [] The solution is to remove all sys.path gymnastics and to adapt your import statements accordingly: $ hg diff diff -r 9fe6129ba8fc plugins/oca/open_clipart.py --- a/plugins/oca/open_clipart.py Sun Aug 29 12:51:51 2010 +0200 +++ b/plugins/oca/open_clipart.py Sun Aug 29 13:02:55 2010 +0200 @@ -2,9 +2,7 @@ import os import threading, thread -sys.path.insert(0, '..') -import base_plugin -#sys.path.insert(0, '../..') +from .. import base_plugin # ------------------------------------------ # class OpenClipArt diff -r 9fe6129ba8fc test.py --- a/test.py Sun Aug 29 12:51:51 2010 +0200 +++ b/test.py Sun Aug 29 13:02:55 2010 +0200 @@ -1,7 +1,6 @@ import os, sys import inspect -sys.path.insert(0, "plugins") # Thanks to http://www.luckydonkey.com/2008/01/02/python-style-plugins- made-easy/ def find_subclasses(path, cls): $ python test.py Importing plugins.base_plugin Importing plugins.oca.open_clipart Check against Found a subclass: OpenClipArt Got subclasses= [] You should also remove the __init__.py from the folder containing test.py which is just begging for the same problem when you import your plugins as test.plugins.whatever. Peter From news1234 at free.fr Sun Aug 29 07:42:07 2010 From: news1234 at free.fr (News123) Date: Sun, 29 Aug 2010 13:42:07 +0200 Subject: Fibonacci: How to think recursively In-Reply-To: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: <4c7a4793$0$5857$426a74cc@news.free.fr> On 08/29/2010 01:12 AM, Baba wrote: > Level: beginner > > I would like to know how to approach the following Fibonacci problem: > How may rabbits do i have after n months? > > I'm not looking for the code as i could Google that very easily. I'm > looking for a hint to put me on the right track to solve this myself > without looking it up. > > my brainstorming so far brought me to a stand still as i can't seem to > imagine a recursive way to code this: > > my attempted rough code: > > def fibonacci(n): > # base case: > result = fibonacci (n-1) + fibonacci (n-2) >>> this will end up in a mess as it will create overlapping recursions > > OR > > def fibonacci(n): > # base case: > fibonacci(n+2) - fibonacci(n+1) - n = 0 >>> this too would create overlapping recursions > Hi Baba, Let's take another example: factorials: Trivial, but you 'just have to apply the same techniques FIbonacci n! = 1 * 2 * 3 . . . * n Very first thing is to always find a trivial case, or the terminal condition. Tjis is, when you reduced the problem to the most trivial case(s), for which you don't need anymore recursion for factorials this would be 0! = 1 for Fibonacci you might have multiple trivial cases and the recursive definition of factorial is\ n! = (n - 1) * n so the code for factorial looks something like: def factorial(n): if n == 0: # treat the trivial case / cases for which ou know the answer return 1 else: # reduce the problem by the recursive definition return factorial(n-1)*n Hope this helps. From ptmcg at austin.rr.com Sun Aug 29 08:43:49 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 29 Aug 2010 05:43:49 -0700 (PDT) Subject: Tag parsing in python References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: On Aug 28, 11:23?pm, Paul McGuire wrote: > On Aug 28, 11:14?am, agnibhu wrote: > > > > > > > Hi all, > > > I'm a newbie in python. I'm trying to create a library for parsing > > certain keywords. > > For example say I've key words like abc: bcd: cde: like that... So the > > user may use like > > abc: How are you bcd: I'm fine cde: ok > > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > > assign them to abc:, bcd: and cde: respectively.. There may be > > combination of keyowords introduced in future. like abc: xy: How are > > you > > So new keywords qualifying the other keywords so on.. I got to thinking more about your keywords-qualifying-keywords example, and I thought this would be a good way to support locale- specific tags. I also thought how one might want to have tags within tags, to be substituted later, requiring a "abc::" escaped form of "abc:", so that the tag is substituted with the value of tag "abc:" as a late binding. Wasn't too hard to modify what I posted yesterday, and now I rather like it. -- Paul # tag_substitute.py from pyparsing import (Combine, Word, alphas, FollowedBy, Group, OneOrMore, empty, SkipTo, LineEnd, Optional, Forward, MatchFirst, Literal, And, replaceWith) tag = Combine(Word(alphas) + ~FollowedBy("::") + ":") tag_defn = Group(OneOrMore(tag))("tag") + empty + SkipTo(tag | LineEnd())("body") + Optional(LineEnd().suppress()) # now combine macro detection with substitution macros = {} macro_substitution = Forward() def make_macro_sub(tokens): # unescape '::' and substitute any embedded tags tag_value = macro_substitution.transformString(tokens.body.replace("::",":")) # save this tag and value (or overwrite previous) macros[tuple(tokens.tag)] = tag_value # define overall macro substitution expression macro_substitution << MatchFirst( [(Literal(k[0]) if len(k)==1 else And([Literal(kk) for kk in k])).setParseAction(replaceWith(v)) for k,v in macros.items()] ) + ~FollowedBy(tag) # return empty string, so macro definitions don't show up in final # expanded text return "" tag_defn.setParseAction(make_macro_sub) # define pattern for macro scanning scan_pattern = macro_substitution | tag_defn sorry = """\ nm: Dave sorry: en: I'm sorry, nm::, I'm afraid I can't do that. sorry: es: Lo siento nm::, me temo que no puedo hacer eso. Hal said, "sorry: en:" Hal dijo, "sorry: es:" """ print scan_pattern.transformString(sorry) Prints: Hal said, "I'm sorry, Dave, I'm afraid I can't do that." Hal dijo, "Lo siento Dave, me temo que no puedo hacer eso." From osmoma at gmail.com Sun Aug 29 08:57:44 2010 From: osmoma at gmail.com (Osmo Maatta) Date: Sun, 29 Aug 2010 14:57:44 +0200 Subject: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails. In-Reply-To: References: Message-ID: <4C7A5948.1030306@gmail.com> Re-hi and thank you. That solved my problem. I can now see that the base_plugin.Plugin is loaded several times. The numeric id(the_class) is not the same in all places. Anyway, I thought that a class is always the same if it has been loaded from the same module (in Linux/Unix; from the same file and inode). So this experience was a bit confusing. I need to learn more about how to set the search path (sys.path) right. More Python! Thanks Osmo Antero Gr?nland, Oslo On 08/29/2010 01:06 PM, Peter Otten wrote: > Osmo Maatta wrote: > >> Hello, >> >> Sub class test fails. >> ====================== >> I have a program that needs to load plugin-classes during runtime. >> >> The program has these subdirectories (modules). >> >> $ tree >> . >> `-- test.py >> | >> |-- plugins >> | |-- base_plugin.py >> | |-- base_plugin.pyc >> | |-- __init__.py >> | `-- oca >> | |-- __init__.py >> | |-- open_clipart.py >> >> >> The plugins (sub directory) contains one or more plugin modules, in this >> test-case there is only one; oca/open_clipart.py. >> >> The plugins/base_plugin.py (contains class Plugin()) is a base class of >> all plugins. >> >> I want to list and load all plugin-classes (that inherit from >> base_plugin.Plugin). I have a Python code that successfully browses the >> plugins, but the the test issubclass(x, base_plugin.Plugin) fails. >> >> Please see this Python code: >> http://futuredesktop.com/tmp/test6.tar.gz >> >> Why the issubclass(entry, cls) test fails? > > base_plugin.py is imported twice, once as plugins.base_plugin and a second > time as base_plugin. You can see that when you add a bit more debug code > into your test.py: > > > --- a/test.py Sun Aug 29 12:57:25 2010 +0200 > +++ b/test.py Sun Aug 29 12:58:25 2010 +0200 > @@ -24,6 +24,8 @@ > #print "entry's class<%s> -- cls's class=<%s>" % > (obj1.get_name(), obj2.get_name(), ) > > print "Check %s against %s" % (entry, cls, ) > + print entry.__bases__ > + print cls > > if issubclass(entry, cls): > print "Found a subclass: " + key > > $ python test.py > Importing plugins.base_plugin > Importing plugins.oca.open_clipart > Check against 'plugins.base_plugin.Plugin'> > (,) > > Got subclasses= [] > > The solution is to remove all sys.path gymnastics and to adapt your import > statements accordingly: > > $ hg diff > diff -r 9fe6129ba8fc plugins/oca/open_clipart.py > --- a/plugins/oca/open_clipart.py Sun Aug 29 12:51:51 2010 +0200 > +++ b/plugins/oca/open_clipart.py Sun Aug 29 13:02:55 2010 +0200 > @@ -2,9 +2,7 @@ > import os > import threading, thread > > -sys.path.insert(0, '..') > -import base_plugin > -#sys.path.insert(0, '../..') > +from .. import base_plugin > > # ------------------------------------------ > # class OpenClipArt > diff -r 9fe6129ba8fc test.py > --- a/test.py Sun Aug 29 12:51:51 2010 +0200 > +++ b/test.py Sun Aug 29 13:02:55 2010 +0200 > @@ -1,7 +1,6 @@ > import os, sys > import inspect > > -sys.path.insert(0, "plugins") > > # Thanks to http://www.luckydonkey.com/2008/01/02/python-style-plugins- > made-easy/ > def find_subclasses(path, cls): > > > $ python test.py > Importing plugins.base_plugin > Importing plugins.oca.open_clipart > Check against 'plugins.base_plugin.Plugin'> > Found a subclass: OpenClipArt > Got subclasses= [] > > You should also remove the __init__.py from the folder containing test.py > which is just begging for the same problem when you import your plugins as > test.plugins.whatever. > > Peter > From gelonida at gmail.com Sun Aug 29 09:00:45 2010 From: gelonida at gmail.com (Gelonida) Date: Sun, 29 Aug 2010 15:00:45 +0200 Subject: controlling the mouse pointer on linux (or as vnc client) Message-ID: Hi, >From a python script I'd like to be able to move the mouse to certain absolute coordinates on the screen. There's no problems calling an external program with subprocess.popen, as I do not want to perform many movements. The mouse can jump it doesn't have to visibly move to the target coordinate. What would you suggest to achieve this on Linux Ubuntu 10.4? Lateron it would be intersting to acheive the same on a Windows PC One idea, that I had (for a cross platform solution) would be to start a VNC server on localhost and the current display and run a small custom VNC client, which will only control the mouse. However I have no idea how easy it would be to use a custom VNC client for moving the mouse. I read about python-vnc-viewer but don't know how complex it would be to use it as a base for 'just moving the mouse' Thanks for any suggestions and ideas From bruno.desthuilliers at gmail.com Sun Aug 29 09:19:01 2010 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 29 Aug 2010 06:19:01 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> Message-ID: <9fd03df8-a8e3-4781-8d72-c129fee20d8f@z28g2000yqh.googlegroups.com> On 27 ao?t, 18:20, Mark Lawrence wrote: > On 27/08/2010 15:43, Bruno Desthuilliers wrote: > > > Dave Angel a ?crit : > > (snip) > > >> or (untested) > >> def is_palindrom(s): > >> s = s.lower() > >> return s == s[::-1] > > > Right, go on, make me feel a bit more stupid :-/ > > Who's next ? > > It could be worse, try responding to issue 9702. :) lol ! Nice one, indeed. From raoulbia at gmail.com Sun Aug 29 09:43:40 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 29 Aug 2010 06:43:40 -0700 (PDT) Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: On Aug 29, 3:25?am, Steven D'Aprano wrote: > Mathematically, there is nothing wrong with overlapping recursion. It > will work, and Python can handle it easily. Based on the advice by Steven and Mel i tried my initial 'guess' and it does seem to work fine. When looking at it using pencil and paper i thought "well, each recursive call will call 2 new ones and if n is large i will have a huge overlap, so it probably is the wrong approach". However it turns out to be fine in principle. It can be handled, as Steven pointed out. > But in practical terms, it can lead to great inefficiency. In this > example, it should be avoided because it is slow. Very slow. To calculate > the nth Fibonacci number using naive recursion requires *many* calls: > > You can make it even more efficient by giving fib() a long-term cache, so > that each call to fib(5) requires one cache lookup rather than six (or > fifteen) recursive calls. Other than the first time, obviously. This is > called memoisation, but again I digress. > I looked memoisation up and decided that for now i will not go near it. First i will try to build up some bacic skills but thank you very much for the hint. Memoisation will certainly be on the list of future exercises. However, the idea that memoisation is needed to make the computation more efficient confirms my initial feeling that a 'simple' recursive approach is somewhat not ideal. So here's my code. It does still cause me one headache. If i use f(0)=0 and f(1)=1 as base cases the result will be 144. I was expecting the result to be the next value in the series (233)... If i use f(1)=1 and f(2)=2 as base cases them i get my expected result. I assume this has to do with our understanding/defining the start of the Fibonacci series? def r_fib(n): if n == 1: return 1 elif n == 2: return 2 else: return r_fib(n-2) + r_fib(n-1) print r_fib(12) Thanks Baba From michael.a.powe at gmail.com Sun Aug 29 10:22:33 2010 From: michael.a.powe at gmail.com (naugiedoggie) Date: Sun, 29 Aug 2010 07:22:33 -0700 (PDT) Subject: Using a function for regular expression substitution Message-ID: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Hello, I'm having a problem with using a function as the replacement in re.sub(). Here is the function: def normalize(s) : return urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) The purpose of this function is to proper-case the words contained in a URL query string parameter value. I'm massaging data in web log files. In case it matters, the regex pattern looks like this: provider_pattern = r'(?PSearch_Provider)=(?P[^&]+)' The call looks like this: re.sub(matcher,normalize,line) Where line is the log line entry. What I get back is first the entire line with the normalization of the parameter value, but missing the parameter; then appended to that string is the entire line again, with the query parameter back in place pointing to the normalized string. >>> fileReader = open(log,'r') >>> >>> lines = fileReader.readlines() >>> for line in lines: if line.find('Search_Type') != -1 and line.find('Search_Provider') != -1 : re.sub(provider_matcher,normalize,line) print line,'\n' The output of the print is like this: 'log-entry parameter=value&normalized-string¶meter=value\n log-entry parameter=value¶meter=normalized-string¶meter=value' The goal is to massage the specified entries in the log files and write the entire log back into a new file. The new file has to be exactly the same as the old one, with the exception of the entries I've altered with my function. No doubt I'm doing something trivially wrong, but I've tried to reproduce the structure as defined in the documentation. Thanks. mp From john at castleamber.com Sun Aug 29 10:25:36 2010 From: john at castleamber.com (John Bokma) Date: Sun, 29 Aug 2010 09:25:36 -0500 Subject: controlling the mouse pointer on linux (or as vnc client) References: Message-ID: <87r5hhmr6n.fsf@castleamber.com> Gelonida writes: > Hi, > >>From a python script I'd like to be able to move the mouse to certain > absolute coordinates on the screen. > > > There's no problems calling an external program with subprocess.popen, > as I do not want to perform many movements. xte? sudo apt-get install xautomation xte 'mousemove 200 200' see: http://linux.die.net/man/1/xte -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From nfdisco at gmail.com Sun Aug 29 10:44:47 2010 From: nfdisco at gmail.com (ernest) Date: Sun, 29 Aug 2010 07:44:47 -0700 (PDT) Subject: in place functions from operator module Message-ID: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Hi, The operator module provides separate functions for "in place" operations, such as iadd(), isub(), etc. However, it appears that these functions don't really do the operation in place: In [34]: a = 4 In [35]: operator.iadd(a, 3) Out[35]: 7 In [36]: a Out[36]: 4 So, what's the point? If you have to make the assignment yourself... I don't understand. Cheers, Ernest From __peter__ at web.de Sun Aug 29 11:00:22 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Aug 2010 17:00:22 +0200 Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: ernest wrote: > The operator module provides separate functions for > "in place" operations, such as iadd(), isub(), etc. > However, it appears that these functions don't really > do the operation in place: > > In [34]: a = 4 > > In [35]: operator.iadd(a, 3) > Out[35]: 7 > > In [36]: a > Out[36]: 4 > > So, what's the point? If you have to make the > assignment yourself... I don't understand. Integers are immutable, and for instances a of immutable types a += b is equivalent to a = a + b For mutable types like list add() and iadd() may differ: >>> a = ["first"] >>> operator.iadd(a, [42]) ['first', 42] >>> a ['first', 42] >>> a = ["first"] >>> operator.add(a, [42]) ['first', 42] >>> a ['first'] Peter From roy at panix.com Sun Aug 29 11:10:37 2010 From: roy at panix.com (Roy Smith) Date: Sun, 29 Aug 2010 11:10:37 -0400 Subject: Using a function for regular expression substitution References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: In article <9170aad0-478a-4222-b6e2-88d00899d8b4 at t2g2000yqe.googlegroups.com>, naugiedoggie wrote: > Hello, > > I'm having a problem with using a function as the replacement in > re.sub(). > > Here is the function: > > def normalize(s) : > return > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) I read though this entire post, and I'm not quite sure what you're asking. May I suggest that you need to break this down into smaller pieces and find a minimal test case. I'm guessing this is a problem with the regex processing. To prove that, strip away everything else and verify that part in isolation. Compile your regex, and match it against a string that you expect it to match. Then, examine the groups returned by the match object. If they're not what you expect, then re-post your question, with just this minimal test code. From nfdisco at gmail.com Sun Aug 29 11:29:11 2010 From: nfdisco at gmail.com (ernest) Date: Sun, 29 Aug 2010 08:29:11 -0700 (PDT) Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: <18f9b1ad-a549-4922-b346-393cf72ddc20@y11g2000yqm.googlegroups.com> On 29 Ago, 17:00, Peter Otten <__pete... at web.de> wrote: > ernest wrote: > > The operator module provides separate functions for > > "in place" operations, such as iadd(), isub(), etc. > > However, it appears that these functions don't really > > do the operation in place: > > > In [34]: a = 4 > > > In [35]: operator.iadd(a, 3) > > Out[35]: 7 > > > In [36]: a > > Out[36]: 4 > > > So, what's the point? If you have to make the > > assignment yourself... I don't understand. > > Integers are immutable, and for instances a of immutable types > > a += b > > is equivalent to > > a = a + b > > For mutable types like list add() and iadd() may differ: > > >>> a = ["first"] > >>> operator.iadd(a, [42]) > ['first', 42] > >>> a > > ['first', 42] > > >>> a = ["first"] > >>> operator.add(a, [42]) > ['first', 42] > >>> a > > ['first'] It makes sense now. Thank you :) Ernest From arnodel at googlemail.com Sun Aug 29 11:33:58 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 16:33:58 +0100 Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: ernest writes: > Hi, > > The operator module provides separate functions for > "in place" operations, such as iadd(), isub(), etc. > However, it appears that these functions don't really > do the operation in place: > > In [34]: a = 4 > > In [35]: operator.iadd(a, 3) > Out[35]: 7 > > In [36]: a > Out[36]: 4 > > So, what's the point? If you have to make the > assignment yourself... I don't understand. > > Cheers, > Ernest That's because a += b is executed as: a = a.__iadd__(b) For immutable objects, (such as integers), a.__iadd__(b) returns a + b *and then* this value is assigned to a (or rather 'a' is bound to the value). So for immutables objects, iadd(a, b) is the same as a + b For mutable objects (such as lists), a.__iadd__(b) mutates the object *and then* returns self so that when the assignement is executed, 'a' will still be bound the the same object. E.g. if a = [1, 2] then a += [3] will first append 3 to the list and then reassign the list to 'a' (it is unnecessary in this case but if this step was omitted, the "in place" operators wouldn't work on immutables types). -- Arnaud From gelonida at gmail.com Sun Aug 29 11:35:31 2010 From: gelonida at gmail.com (Gelonida) Date: Sun, 29 Aug 2010 17:35:31 +0200 Subject: controlling the mouse pointer on linux (or as vnc client) In-Reply-To: <87r5hhmr6n.fsf@castleamber.com> References: <87r5hhmr6n.fsf@castleamber.com> Message-ID: Hi John, > Hi, > >>From a python script I'd like to be able to move the mouse to certain > absolute coordinates on the screen. > > > There's no problems calling an external program with subprocess.popen, > as I do not want to perform many movements. > > The mouse can jump it doesn't have to visibly move to the target coordinate. > > > > What would you suggest to achieve this on Linux Ubuntu 10.4? > > Lateron it would be intersting to acheive the same on a Windows PC > On 08/29/2010 04:25 PM, John Bokma wrote: > sudo apt-get install xautomation > xte 'mousemove 200 200' > Thanks a lot. This solution is perfect for Linux. Exactly what I was looking for. :-) I guess for Windows it would be a little more complicated? bye G From tjreedy at udel.edu Sun Aug 29 11:35:56 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Aug 2010 11:35:56 -0400 Subject: Using a function for regular expression substitution In-Reply-To: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: On 8/29/2010 10:22 AM, naugiedoggie wrote: > Hello, > > I'm having a problem with using a function as the replacement in > re.sub(). > > Here is the function: > > def normalize(s) : > return > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) To debug your problem, I would start with print(s) in the function and if still not clear, unnest the expression and print intermediate results. -- Terry Jan Reedy From alain at dpt-info.u-strasbg.fr Sun Aug 29 11:55:55 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 29 Aug 2010 17:55:55 +0200 Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: <87hbidqupg.fsf@dpt-info.u-strasbg.fr> Baba writes: > Level: beginner > > I would like to know how to approach the following Fibonacci problem: > How may rabbits do i have after n months? > > I'm not looking for the code as i could Google that very easily. I'm > looking for a hint to put me on the right track to solve this myself > without looking it up. fib(n) = fib(n-1) + fib(n-2), so you need the two previous values to compute the next one (that's the main difference between fibonacci and factorial). So here is a hint: instead of computing only fib(n), compute a pair (fib(n),fib(n-1)). It now becomes a problem very similar to factorial: for instance, what's (fib(7),fib(6)) if you have the values of (fib(6),fib(5))? Now write a recursive function fib2(n) that returns the last two values. And a simple wrapper fib(n) that calls fib2(n) and returns the first element of the pair. -- Alain. From python at mrabarnett.plus.com Sun Aug 29 13:14:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Aug 2010 18:14:15 +0100 Subject: Using a function for regular expression substitution In-Reply-To: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: <4C7A9567.6090401@mrabarnett.plus.com> On 29/08/2010 15:22, naugiedoggie wrote: > Hello, > > I'm having a problem with using a function as the replacement in > re.sub(). > > Here is the function: > > def normalize(s) : > return > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) This normalises the provider and returns only that, and none of the remainder of the string. I think you might want this: def normalize(s): return s[ : s.start('provider')] + urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + s[s.start('provider') : ] It returns the part before the provider, followed by the normalised provider, and then the part after the provider. > > The purpose of this function is to proper-case the words contained in > a URL query string parameter value. I'm massaging data in web log > files. > > In case it matters, the regex pattern looks like this: > > provider_pattern = r'(?PSearch_Provider)=(?P[^&]+)' > > The call looks like this: > > > re.sub(matcher,normalize,line) > > > Where line is the log line entry. > > What I get back is first the entire line with the normalization of the > parameter value, but missing the parameter; then appended to that > string is the entire line again, with the query parameter back in > place pointing to the normalized string. > > >>>> fileReader = open(log,'r') >>>> >>>> lines = fileReader.readlines() >>>> for line in lines: > if line.find('Search_Type') != -1 and line.find('Search_Provider') != > -1 : These can be replaced by: if 'Search_Type' in line and 'Search_Provider' in line: > re.sub(provider_matcher,normalize,line) re.sub is returning the result, which you're throwing away! line = re.sub(provider_matcher,normalize,line) > print line,'\n' > > > The output of the print is like this: > > > 'log-entry parameter=value&normalized-string¶meter=value\n > log-entry parameter=value¶meter=normalized-string¶meter=value' > > > The goal is to massage the specified entries in the log files and > write the entire log back into a new file. The new file has to be > exactly the same as the old one, with the exception of the entries > I've altered with my function. > > No doubt I'm doing something trivially wrong, but I've tried to > reproduce the structure as defined in the documentation. > From raoulbia at gmail.com Sun Aug 29 13:36:45 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 29 Aug 2010 10:36:45 -0700 (PDT) Subject: Fibonacci: returning a selection of the series Message-ID: level: beginner i would like to return a selection of the Fibonacci series. example: start = 5 ; end = 55 the function should then return [5, 8, 13, 21, 34, 55] it seems that this is best resolved using an iterative approach to generate the series. In another post (http://groups.google.ie/group/ comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach which seems best to compute the nth number but it seems to me that the recursive code is not suited for generating the actual list. my questios: - would you agree that recursive is not ideal for generating a list? (in this particular case and in general) - can my code below be optimised? - how to deal with 'start' and 'end' values that are not in the list e.g. 4,76 ? def i_fib(n): a = 0 b = 1 list = [] counter = 0 while counter < n: a, b = b, a+b counter += 1 list = list + [b,] return list def fib_range(start,end): list = i_fib(12) if start in list and end in list: start = list.index(start) end = list.index(end) print list[start:end+1] else: print 'not in list' fib_range(5,55) thanks Baba From alain at dpt-info.u-strasbg.fr Sun Aug 29 14:18:55 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 29 Aug 2010 20:18:55 +0200 Subject: Fibonacci: returning a selection of the series References: Message-ID: <87d3t1qo34.fsf@dpt-info.u-strasbg.fr> Baba writes: > i would like to return a selection of the Fibonacci series. > example: > start = 5 ; end = 55 > the function should then return [5, 8, 13, 21, 34, 55] [...] > my questios: > - would you agree that recursive is not ideal for generating a list? > (in this particular case and in general) I would not, in the general case. Well-known problems like fact or fib have been scrutinized in so much detail that I find it hard to conclude anything by looking at them. And problems producing lists are usually "easy" to transform from one version to the other. However in the general case, to me, the recursive version is usually much easier to understand, and the iterative version is just an optimization to save space. There are recursive algorithms that I would have trouble to write in an iterative way (unless I use an explicit stack, but that doesn't really count). We'll stay with the iterative version here, because you've started with that and you're not far from the solution. But when you're done, try to think about a recursive version. When the goal is to produce a list, the recursion scheme is almost immediate: produce one element per call, one after the other. > - can my code below be optimised? Sure. What's this 12 there? Why traversing the list three times (index() needs to traverse at least some part of it)? And... > - how to deal with 'start' and 'end' values that are not in the list > e.g. 4,76 ? In general, if you have a program that produces something just to remove/ignore it five lines later, you have a problem. In your case: 1) are you sure you need to append to list(*) at every iteration? When do you *really* need to? And... 2) your loop runs up to n (the index of the fib number), but you want to stop on some fib number value (not index). So, why not pass start and end to i_fib, and use them where appropriate? -- Alain. (*) Don't use "list" as a name, because it's a (useful) built-in function. Use more expressive names: fn instead of b, fn_1 instead of a, fibnumbers instead of list, etc. > > def i_fib(n): > a = 0 > b = 1 > list = [] > counter = 0 > while counter < n: > a, b = b, a+b > counter += 1 > list = list + [b,] > return list > > def fib_range(start,end): > list = i_fib(12) > if start in list and end in list: > start = list.index(start) > end = list.index(end) > print list[start:end+1] > else: print 'not in list' From python at mrabarnett.plus.com Sun Aug 29 14:34:02 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Aug 2010 19:34:02 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> Message-ID: <4C7AA81A.10705@mrabarnett.plus.com> On 29/08/2010 06:13, ????? wrote: > On 28 ???, 23:12, MRAB wrote: >> On 28/08/2010 20:51, ????? wrote: >> >> >> >> >> >> >> >> >> >>> On 28 ???, 22:35, MRAB wrote: >> >>>> """When there's more than one value you provide a tuple. It's makes sense >>>> from the point of view of consistency that you also provide a tuple when >>>> there's only one value.""" >> >>> Can you write something that make use of more than one value? >> >>> Perhaps you mena somethign like? >> >>> cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date >>> = %s and host = %s''' , (page,) ) >> >>> Is this what you mean? >> >>> All those special format strign identifiers will grab their values out >>> of the tuple? >> >> Your example contains 3 placeholders, so it needs 3 values: >> >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s''', (page, date, host)) >> >> This will be safe. Any quoting that's needed will be done by .execute(). > > Will this also work without the parentheses? > Have you tried it? I did. It didn't like it! It likes the values to be in a tuple. If there's one value, that's a 1-tuple: (page, ). >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s''', page, date, host) > > or python will not allow it cause it might think there are 4 args > isntead of two? > Not Python (the language) as such, but the method. As I said, it expects the value(s) to be in a tuple. > >> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and >> date = '%s' and host = '%s' ''', (page, date, host)) > > Whats happens if i attempt to also quote by single or double quoting > the above although now i'm aware that .execute method does the quoting > for me? The method will put in any quoting that's needed. If you also put in quotes then that'll result in 2 sets of quoting, one inside the other (or something like that). Why make more work for yourself? Let the method do it for you, safely and correctly! From news1234 at free.fr Sun Aug 29 14:35:02 2010 From: news1234 at free.fr (News123) Date: Sun, 29 Aug 2010 20:35:02 +0200 Subject: Fibonacci: How to think recursively In-Reply-To: References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4c7aa857$0$703$426a74cc@news.free.fr> Hi Baba, > So here's my code. It does still cause me one headache. If i use > f(0)=0 > and f(1)=1 as base cases the result will be 144. I was expecting the > result to be the next value in the series (233)... > If i use f(1)=1 and f(2)=2 as base cases them i get my expected > result. I assume this has to do with our understanding/defining the > start of the Fibonacci series? > > > def r_fib(n): > if n == 1: return 1 > elif n == 2: return 2 > else: return r_fib(n-2) + r_fib(n-1) > > print r_fib(12) > Let's calculate the first 12 Fobonacci numbers first manually: 0: 0 # as of its definition 1: 1 @ as of its definition 2: 0 + 1 = 1 3: 1 + 1 = 2 4: 1 + 2 = 3 5: 2 + 3 = 5 6: 3 + 5 = 8 7: 5 + 8 = 13 8: 8 + 13 = 21 9: 13 + 21 = 34 10: 21 + 34 = 55 11: 34 + 55 = 89 12: 55 + 89 = 144 So if you use f(0) = 0 and f(1) = 1 you seem to get the coorec result, right? Now the question is why you get the wrong result with your code: def r_fib(n): if n == 1: return 1 elif n == 2: return 2 else: return r_fib(n-2) + r_fib(n-1) The answer is very simple your result n=2 is wrong. You wrote, that it is 2, but it should be 1 From python at mrabarnett.plus.com Sun Aug 29 14:44:12 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Aug 2010 19:44:12 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> Message-ID: <4C7AAA7C.8050900@mrabarnett.plus.com> On 29/08/2010 06:34, ????? wrote: > On 28 ???, 23:15, MRAB wrote: >> On 28/08/2010 20:37, ????? wrote: >> >> >> >> >> >> >> >> >> >>> On 22 ???, 10:27, ????? wrote: >>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >>>>> ????? wrote: >>>>>> # initializecookie >>>>>> cookie=Cookie.SimpleCookie() >>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>>>> mycookie =cookie.get('visitor') >> >>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>>>> yandex|13448|spider|crawl)', host ) is None: >>>>>> blabla... >>>>>> ======================== >> >>>>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>>>> within. >>>>>> So, i have to ask why the if fails? >> >>>>> Maybe it's because != != == >> >>>> Iwant ti if code block to be executed only if the browsercookienames >>>> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >>>> Is there somethign wrong with the way i wrote it? >> >>> Please do help me with this too becaus eif i dont solve this my >>> website keeps count my each visit like iam a guest visitor! >> >> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and >> repr(host). Then follow the code yourself to see whether the condition >> is True. > > print mycookie outputs 'None' > > Thts weird because i check with the browser and the cookie is there! > Just because you can see it doesn't mean your code can. > print repr(host) outputs '78-236-176.adsl.cyta.gr' > > repr(mycookie.value) (unless mycookie is None) > > and also > > print mycookie.value gives an error too. Maybe there is not a value > method? > If mycookie is None, then it's not surprising that doesn't have 'value'. In summary, mycookie is None, so: mycookie and mycookie.value != 'nikos' is false (actually None, which is treated as false). host == '78-236-176.adsl.cyta.gr', so: re.search(r'(cyta|yandex|13448|spider|crawl)', host) finds 'cyta' and the search returns a match. false or false == false blabla... isn't executed. From news1234 at free.fr Sun Aug 29 14:47:57 2010 From: news1234 at free.fr (News123) Date: Sun, 29 Aug 2010 20:47:57 +0200 Subject: Fibonacci: returning a selection of the series In-Reply-To: References: Message-ID: <4c7aab61$0$18873$426a74cc@news.free.fr> On 08/29/2010 07:36 PM, Baba wrote: > level: beginner > > i would like to return a selection of the Fibonacci series. > example: > start = 5 ; end = 55 > the function should then return [5, 8, 13, 21, 34, 55] > > it seems that this is best resolved using an iterative approach to > generate the series. In another post (http://groups.google.ie/group/ > comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ > d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach > which seems best to compute the nth number but it seems to me that the > recursive code is not suited for generating the actual list. > > my questios: > - would you agree that recursive is not ideal for generating a list? Of course, This is probably the whole point of this exercise. Just because something can be defined recursively doesn't mean, that it should be calculated recursively > - can my code below be optimised? > - how to deal with 'start' and 'end' values that are not in the list > e.g. 4,76 ? > > def i_fib(n): > a = 0 > b = 1 > list = [] > counter = 0 > while counter < n: > a, b = b, a+b > counter += 1 > list = list + [b,] > return list lateron you should probably use a generator function for i_fib(n) Then you will only calculate what is needed. minor suggestion for above code. Instead of: list = list + [b,] it is common practice to write list.append(b) > > def fib_range(start,end): > list = i_fib(12) > if start in list and end in list: > start = list.index(start) > end = list.index(end) > print list[start:end+1] > else: print 'not in list' > > fib_range(5,55) you know, that the list returned by i_fib() is sorted. Knowing this you can look at the python module bisect. It allows you to identify the index of the closest entry in a list. Just read it up in the net: http://docs.python.org/library/bisect.html You could do this of course also do manually (perhaps better for learning python than just using exsitng funtions) Search for the first Fibonacci number which is bigger than your start number Then search for the first Fibonacci number, which is bigger than your end number Display all numbers between these two indices From debatem1 at gmail.com Sun Aug 29 14:55:17 2010 From: debatem1 at gmail.com (geremy condra) Date: Sun, 29 Aug 2010 11:55:17 -0700 Subject: Fibonacci: returning a selection of the series In-Reply-To: References: Message-ID: On Sun, Aug 29, 2010 at 10:36 AM, Baba wrote: > level: beginner > > i would like to return a selection of the Fibonacci series. > example: > start = 5 ; end ?= 55 > the function should then return [5, 8, 13, 21, 34, 55] > > it seems that this is best resolved using an iterative approach to > generate the series. In another post (http://groups.google.ie/group/ > comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ > d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach > which seems best to compute the nth number but it seems to me that the > recursive code is not suited for generating the actual list. > > my questios: > - would you agree that recursive is not ideal for generating a list? > (in this particular case and in general) > - can my code below be optimised? > - how to deal with 'start' and 'end' values that are not in the list > e.g. 4,76 ? > > def i_fib(n): > ? ?a = 0 > ? ?b = 1 > ? ?list = [] > ? ?counter = 0 > ? ?while counter < n: > ? ? ? ?a, b = b, a+b > ? ? ? ?counter += 1 > ? ? ? ?list = list + [b,] > ? ?return list > > def fib_range(start,end): > ? ?list = i_fib(12) > ? ?if start in list and end in list: > ? ? ? ?start = list.index(start) > ? ? ? ?end = list.index(end) > ? ? ? ?print list[start:end+1] > ? ?else: print 'not in list' > > fib_range(5,55) > > thanks > Baba Get the index of the start, use that to generate the second, and iterate until you hit the end. from math import sqrt, log, floor phi = (1 + sqrt(5))/2 def fibonacci_index(n): return floor(log(n * sqrt(5))/log(phi) + .5) def ith_fibonacci(i): return floor(phi**i/sqrt(5) + .5) def next_fibonacci(a, b): return a + b def fibonacci_between(start, stop): # find the index of the first i = fibonacci_index(start) # find the second value given the first second_fib = ith_fibonacci(i+1) # build the list from there fibs = [start, second_fib] while fibs[-1] != stop: fibs.append(next_fibonacci(fibs[-1], fibs[-2])) # and we're done return fibs Now try to understand *why* the above works, rather than just copy-pasting it. Geremy Condra From thomas at jollybox.de Sun Aug 29 15:00:56 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 29 Aug 2010 21:00:56 +0200 Subject: PyGeo In-Reply-To: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> Message-ID: <201008292100.57165.thomas@jollybox.de> On Sunday 29 August 2010, it occurred to L to exclaim: > has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu > 10.04) , > the site says > > http://www.wspiegel.de/pymaxima/index_en.html > > "Note: The installation of PyGeo work's only under Python 2.4 (The > further development of pygeo seems to be stopped)" > > is this to do with re-org of site-packages, dist_packages etc. > > any help most appreciated. I don't know. I haven't tried. Maybe somebody else here has, but don't count on it. Have you tried it? If not, then why not? Try it. Maybe it just works. As far as I know, distutils haven't changed much, carefully avoiding any changes that could break packages. I think it's entirely possible that the web page author claiming "the installation" doesn't work was referring only to the Windows installer. Have fun, Thomas From bruno.desthuilliers at gmail.com Sun Aug 29 15:01:39 2010 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 29 Aug 2010 12:01:39 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <39148700-25c5-4534-8723-1c09d38bf2bb@q22g2000yqm.googlegroups.com> On 27 ao?t, 20:05, Jussi Piitulainen > def palindromep(s): > ? ? return ( s == "" or > ? ? ? ? ? ? ?( s[0] == s[-1] and > ? ? ? ? ? ? ? ?palindromep(s[1:-1]) ) ) > I-can-write-lisp-in-any-language-p !-) From bruno.desthuilliers at gmail.com Sun Aug 29 15:09:26 2010 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 29 Aug 2010 12:09:26 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> <8dunm7Fv5nU1@mid.individual.net> Message-ID: <944676c3-3f62-45c2-8259-2429bee5e7f6@n3g2000yqb.googlegroups.com> On 29 ao?t, 06:39, Gregory Ewing wrote: > Steven D'Aprano wrote: > > ?I'm not entirely sure what the use-case for swapcase is. > > Obviously it's for correcting things that were typed > in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) > +1 QOTW !-) From nagle at animats.com Sun Aug 29 15:12:52 2010 From: nagle at animats.com (John Nagle) Date: Sun, 29 Aug 2010 12:12:52 -0700 Subject: Performance: sets vs dicts. Message-ID: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Is the "in" test faster for a dict or a set? Is "frozenset" faster than "set"? Use case is for things like applying "in" on a list of 500 or so words while checking a large body of text. John Nagle From arnodel at googlemail.com Sun Aug 29 15:13:29 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 20:13:29 +0100 Subject: Fibonacci: returning a selection of the series References: Message-ID: Baba writes: > my questios: > - would you agree that recursive is not ideal for generating a list? > (in this particular case and in general) In Python that is probably correct in the vast majority of cases for two reasons: * lists in Python are implemented as arrays; * there is no tail call optimisation in Python. But not necessarily in other languages. In Lisp for example, recursion is *the* natural way of generating lists. -- Arnaud From arnodel at googlemail.com Sun Aug 29 15:24:04 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 20:24:04 +0100 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: John Nagle writes: > Is the "in" test faster for a dict or a set? > Is "frozenset" faster than "set"? Use case is > for things like applying "in" on a list of 500 or so words > while checking a large body of text. > > John Nagle IIRC Frozensets are implemented more or less as sets with a hash function and immutability so I would expect "in" to perform exactly the same as for sets. For dicts, I would think that the set implementation is very close to the dict one. So I wouldn't expect any significant difference between any of them. -- Arnaud From __peter__ at web.de Sun Aug 29 15:43:02 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Aug 2010 21:43:02 +0200 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > Is the "in" test faster for a dict or a set? > Is "frozenset" faster than "set"? Use case is > for things like applying "in" on a list of 500 or so words > while checking a large body of text. As Arnaud suspects: no significant difference: $ python dictperf.py dict --> 0.210289001465 set --> 0.202902793884 frozenset --> 0.198950052261 $ cat dictperf.py import random import timeit with open("/usr/share/dict/words") as instream: words = [line.strip() for line in instream] #random.seed(42) sample = random.sample(words, 501) n = sample.pop() y = random.choice(sample) d = dict.fromkeys(sample) s = set(sample) f = frozenset(sample) for lookup in d, s, f: print type(lookup).__name__, "-->", timeit.timeit( "n in lookup; y in lookup", "from __main__ import lookup, n, y") Peter From roy at panix.com Sun Aug 29 16:34:16 2010 From: roy at panix.com (Roy Smith) Date: Sun, 29 Aug 2010 16:34:16 -0400 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> <8dunm7Fv5nU1@mid.individual.net> Message-ID: In article <8dunm7Fv5nU1 at mid.individual.net>, Gregory Ewing wrote: > Steven D'Aprano wrote: > > I'm not entirely sure what the use-case for swapcase is. > > Obviously it's for correcting things that were typed > in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) So it would seem (http://bugs.python.org/msg94026). It's also useful for when you're looking for a crypto algorithm and rot13 is too strong. It also provides a handy way to write is_alpha()... def is_alpha(c): return abs(ord(c) - ord(c.swapcase())) == 32 print is_alpha('a') print is_alpha('A') print is_alpha('1') print is_alpha('>') From joshua.r.english at gmail.com Sun Aug 29 16:38:22 2010 From: joshua.r.english at gmail.com (Josh English) Date: Sun, 29 Aug 2010 13:38:22 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: I have no idea. That's a lower level of programming than I'm used to dealing with. Josh (I also only tried the one value. Had I tried with other strings that would fail the test, some functions may have performed better.) On Aug 29, 2:19?am, Matteo Landi wrote: > Well, I tried the also the solution posted above (recursive w/o > slicing and iterative), and I discovered they were the slowest.. > > is_palindrome_recursive 2.68151649808 > is_palindrome_slice 0.44510699381 > is_palindrome_list 1.93861944217 > is_palindrome_reversed 3.28969831976 > is_palindrome_recursive_no_slicing 6.78929775328 > is_palindrome_iterative 4.88826141315 > > Nothing to say about the iterative function, but the benchmark of the > recursive was unexpected, at least for my point of view: do you think > it is due to the try/except overhead? > From python at mrabarnett.plus.com Sun Aug 29 16:47:41 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Aug 2010 21:47:41 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> <8dunm7Fv5nU1@mid.individual.net> Message-ID: <4C7AC76D.5060402@mrabarnett.plus.com> On 29/08/2010 21:34, Roy Smith wrote: > In article<8dunm7Fv5nU1 at mid.individual.net>, > Gregory Ewing wrote: > >> Steven D'Aprano wrote: >>> I'm not entirely sure what the use-case for swapcase is. >> >> Obviously it's for correcting things that were typed >> in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) > > So it would seem (http://bugs.python.org/msg94026). > > It's also useful for when you're looking for a crypto algorithm and > rot13 is too strong. > > It also provides a handy way to write is_alpha()... > > def is_alpha(c): > return abs(ord(c) - ord(c.swapcase())) == 32 > > print is_alpha('a') > print is_alpha('A') > print is_alpha('1') > print is_alpha('>') How is that better than: print 'a'.isalpha() print 'A'.isalpha() print '1'.isalpha() print '>'.isalpha() From roy at panix.com Sun Aug 29 17:01:29 2010 From: roy at panix.com (Roy Smith) Date: Sun, 29 Aug 2010 17:01:29 -0400 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> <8dunm7Fv5nU1@mid.individual.net> Message-ID: In article , MRAB wrote: > On 29/08/2010 21:34, Roy Smith wrote: > > In article<8dunm7Fv5nU1 at mid.individual.net>, > > Gregory Ewing wrote: > > > >> Steven D'Aprano wrote: > >>> I'm not entirely sure what the use-case for swapcase is. > >> > >> Obviously it's for correcting things that were typed > >> in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) > > > > So it would seem (http://bugs.python.org/msg94026). > > > > It's also useful for when you're looking for a crypto algorithm and > > rot13 is too strong. > > > > It also provides a handy way to write is_alpha()... > > > > def is_alpha(c): > > return abs(ord(c) - ord(c.swapcase())) == 32 > > > > print is_alpha('a') > > print is_alpha('A') > > print is_alpha('1') > > print is_alpha('>') > > How is that better than: > > print 'a'.isalpha() > print 'A'.isalpha() > print '1'.isalpha() > print '>'.isalpha() Think of my post as an implemention of is_reader_humour_impaired(). From storm at chemicalstorm.org Sun Aug 29 17:57:18 2010 From: storm at chemicalstorm.org (Audric Schiltknecht) Date: Sun, 29 Aug 2010 23:57:18 +0200 Subject: Functional composition in python In-Reply-To: <6bedbd75-2fc7-43d6-a3ba-e76e4b447db6@l20g2000yqe.googlegroups.com> References: <4c79b48f$0$28655$c3e8da3@news.astraweb.com> <6bedbd75-2fc7-43d6-a3ba-e76e4b447db6@l20g2000yqe.googlegroups.com> Message-ID: <4c7ad78b$0$31660$426a34cc@news.free.fr> Le 29/08/2010 04:54, Dmitry Groshev a ?crit : > On Aug 29, 5:14 am, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 28 Aug 2010 21:30:39 +0400, Dmitry Groshev wrote: >>> Hello all. Some time ago I wrote a little library: >>> http://github.com/si14/python-functional-composition/, inspired by >>> modern functional languages like F#. In my opinion it is quite useful >>> now, but I would like to discuss it. >>> An example of usage: [snip] > > Generally, f1>> f2 means "lambda x: f2(f1(x))" or "pass the result of > f1 to f2". But in python function can return only one value, so a > composable function should be a function of one argument. You can use a tuple to return more than just one value: def f(a,b): return (a,b) >>> f(1,2) (1,2) Ok, technically, it is ONE value, but since you can access any member of this tuple :) From raoulbia at gmail.com Sun Aug 29 18:18:41 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 29 Aug 2010 15:18:41 -0700 (PDT) Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> <4c7aa857$0$703$426a74cc@news.free.fr> Message-ID: <03ee4309-2aaf-49cc-bea0-9d22444582fe@g17g2000yqe.googlegroups.com> Thanks to All for your kind help! Baba From diazona at ellipsix.net Sun Aug 29 18:30:41 2010 From: diazona at ellipsix.net (David Zaslavsky) Date: Sun, 29 Aug 2010 18:30:41 -0400 Subject: Change case of package name on PyPI Message-ID: <201008291830.41656.diazona@ellipsix.net> Hi everyone, I recently uploaded a package to PyPI under a name with mixed-case letters, but in retrospect I think it'd be better to have the package name be all lowercase. Is there a way I can change it? Thanks, :) David From ben+python at benfinney.id.au Sun Aug 29 19:09:37 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 30 Aug 2010 09:09:37 +1000 Subject: Change case of package name on PyPI References: Message-ID: <87d3t1ggni.fsf@benfinney.id.au> David Zaslavsky writes: > I recently uploaded a package to PyPI under a name with mixed-case > letters, but in retrospect I think it'd be better to have the package > name be all lowercase. Is there a way I can change it? Your question is on-topic here. However, you might get a more focussed discussion at the forum specific for discussing PyPI, the catalog SIG . Try starting the same discussion there. -- \ ?[Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself.? ?_Hocus Pocus_, Kurt | _o__) Vonnegut | Ben Finney From seth at sthrs.me Sun Aug 29 19:13:01 2010 From: seth at sthrs.me (Seth Rees) Date: Sun, 29 Aug 2010 18:13:01 -0500 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: On 08/29/10 14:43, Peter Otten wrote: > John Nagle wrote: > >> Is the "in" test faster for a dict or a set? >> Is "frozenset" faster than "set"? Use case is >> for things like applying "in" on a list of 500 or so words >> while checking a large body of text. > > As Arnaud suspects: no significant difference: > > $ python dictperf.py > dict --> 0.210289001465 > set --> 0.202902793884 > frozenset --> 0.198950052261 > > $ cat dictperf.py > import random > import timeit > > with open("/usr/share/dict/words") as instream: > words = [line.strip() for line in instream] > > #random.seed(42) > sample = random.sample(words, 501) > > n = sample.pop() > y = random.choice(sample) > > d = dict.fromkeys(sample) > s = set(sample) > f = frozenset(sample) > > > for lookup in d, s, f: > print type(lookup).__name__, "-->", timeit.timeit( > "n in lookup; y in lookup", > "from __main__ import lookup, n, y") > > Peter What about lists versus tuples? From news1234 at free.fr Sun Aug 29 19:46:16 2010 From: news1234 at free.fr (News123) Date: Mon, 30 Aug 2010 01:46:16 +0200 Subject: how to find out, whether a path is socket or device Message-ID: <4c7af148$0$28551$426a74cc@news.free.fr> Hi, Under Linux I'd like to find out, whether I got a file, a character device or a socket as a parameter. What is the right way to do this How can I found out, whether a path name is: - a file ( os.isfile() ) - a character device - a socket - a named pipe thanks a lot for pointers From steve at REMOVE-THIS-cybersource.com.au Sun Aug 29 20:09:27 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 00:09:27 GMT Subject: how to find out, whether a path is socket or device References: <4c7af148$0$28551$426a74cc@news.free.fr> Message-ID: <4c7af6b7$0$11118$c3e8da3@news.astraweb.com> On Mon, 30 Aug 2010 01:46:16 +0200, News123 wrote: > Hi, > > Under Linux I'd like to find out, whether I got a file, a character > device or a socket as a parameter. See the stat module. -- Steven From diazona at ellipsix.net Sun Aug 29 20:10:20 2010 From: diazona at ellipsix.net (David Zaslavsky) Date: Sun, 29 Aug 2010 20:10:20 -0400 Subject: Change case of package name on PyPI In-Reply-To: <87d3t1ggni.fsf@benfinney.id.au> References: <87d3t1ggni.fsf@benfinney.id.au> Message-ID: <201008292010.20717.diazona@ellipsix.net> On Sunday 29 August 2010 7:09:37 pm Ben Finney wrote: > David Zaslavsky writes: > > I recently uploaded a package to PyPI under a name with mixed-case > > letters, but in retrospect I think it'd be better to have the package > > name be all lowercase. Is there a way I can change it? > > Your question is on-topic here. However, you might get a more focussed > discussion at the forum specific for discussing PyPI, the catalog SIG > . Try > starting the same discussion there. Thanks, I'll do that. :) David From steve at REMOVE-THIS-cybersource.com.au Sun Aug 29 20:12:30 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 00:12:30 GMT Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: <4c7af76e$0$28653$c3e8da3@news.astraweb.com> On Sun, 29 Aug 2010 07:44:47 -0700, ernest wrote: > Hi, > > The operator module provides separate functions for "in place" > operations, such as iadd(), isub(), etc. However, it appears that these > functions don't really do the operation in place: > > In [34]: a = 4 > > In [35]: operator.iadd(a, 3) > Out[35]: 7 > > In [36]: a > Out[36]: 4 > > So, what's the point? If you have to make the assignment yourself... I > don't understand. The point is that if you could modify the int 4 to become 7, you would then see horrible things like this: >>> a = 4 >>> operator.iadd(a, 3) >>> 4 + 1 # the int "4" has been changed to have the value 7 8 Nobody wants that. Some very early versions of Fortran allowed that sort of thing, apparently by accident. I've been told you can get it to work with Lisp too, and Python with ctypes. You don't want to go there. That is why ints are immutable in Python, and so "in-place" operations aren't really in-place for them. Remember that 4 is an actual *object*, and so the iadd function can only see the object, not the name it is bound to. It sees 4 as the first argument, not the memory location of "a". There's no way for it to know which name you are trying to modify, or even if the object 4 is bound to any name. -- Steven From aahz at pythoncraft.com Sun Aug 29 20:15:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2010 17:15:44 -0700 Subject: problem in using linalg solver in numpy References: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> Message-ID: In article <242fd242-5f29-4358-8c12-f5763b7be137 at g21g2000prn.googlegroups.com>, Pramod wrote: > >When run the below program in python i got error like this , You may want to consider asking future questions on the NumPy list: http://projects.scipy.org/mailman/listinfo/numpy-discussion -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From steve at REMOVE-THIS-cybersource.com.au Sun Aug 29 20:16:55 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 00:16:55 GMT Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4c7af877$0$28653$c3e8da3@news.astraweb.com> On Sun, 29 Aug 2010 06:43:40 -0700, Baba wrote: > So here's my code. It does still cause me one headache. If i use f(0)=0 > and f(1)=1 as base cases the result will be 144. I was expecting the > result to be the next value in the series (233)... That's because you're not generating the Fibonacci series, but a similar unnamed(?) series with the same recurrence but different starting conditions. The Fibinacci series starts with f(0)=1, f(1)=1. > If i use f(1)=1 and > f(2)=2 as base cases them i get my expected result. Which implies that f(0) must be 1, not 0. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 29 20:25:29 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 00:25:29 GMT Subject: Fibonacci: returning a selection of the series References: Message-ID: <4c7afa79$0$28653$c3e8da3@news.astraweb.com> On Sun, 29 Aug 2010 10:36:45 -0700, Baba wrote: > level: beginner > > i would like to return a selection of the Fibonacci series. example: > start = 5 ; end = 55 > the function should then return [5, 8, 13, 21, 34, 55] Start with something to lazily generate Fibonacci numbers. It doesn't matter whether this is iterative or recursive, but it must be *lazy* -- only generating each number when you ask for the next one. Generators are ideal for this: # Untested. def fib(): """Generate the Fibonacci numbers.""" a, b = 1, 1 yield a while 1: yield b a, b = b, a+b Then pass it into a filter than skips numbers less than start, accumulates numbers until you exceed end, and stop. Then return the numbers that you collected. > it seems that this is best resolved using an iterative approach to > generate the series. In another post (http://groups.google.ie/group/ > comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ > d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach > which seems best to compute the nth number but it seems to me that the > recursive code is not suited for generating the actual list. In this specific case, you can get recursion to be much, much more efficient than the naive f(n) = f(n-1) + f(n-2) case, but iteration in Python is often more efficient. > my questios: > - would you agree that recursive is not ideal for generating a list? (in > this particular case and in general) In this particular case, an iterative approach to Fibonacci will probably be more effective. In general, no, recursion is fine for generating lists. -- Steven From no.email at nospam.invalid Sun Aug 29 20:39:21 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 17:39:21 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> Message-ID: <7xhbidndc6.fsf@ruckus.brouhaha.com> Hans Mulder writes: > Parallelizable garbage collectors have performance issues, but they're > not the same issues as mark&sweep collectors have. Parallelizable GCs > break up their work in a zillion little pieces and allow the VM to do > some real work after each piece. They won't free your twenty thousand > components all in one go and you won't have that embarrassing pause. Quibble: parallel GC just means any GC that runs in multiple threads simultaneously. A GC that guarantees no pauses (more technically, specifies a constant such that any GC pause is guaranteed to be shorter than the constant) is called a "real time" GC, and real-time GC's are usually single threaded. Parallel real-time GC's were once sort of a holy grail, though workable ones have been implemented. GHC for example currently uses a GC that is parallel (runs on multiple cores for speed) but is not real-time (there can be a pause), and I think the Sun JVM is the same way. These days I think the GC pause issue is overrated except for real-time control applications. GC's no longer frequently make the program freeze up for seconds at a time or anything like that. It was worse in the old days when CPU's were slower and memory was scarcer. Serious GC's are usually generational, with "minor" GC's taking microseconds and less frequent "major" GC's taking fractions of a second. So in an interactive program or animation on your desktop you might notice a little hiccup once in a while. For something like a web server an occasional slight variation in response time could easily be random network delays and so forth. From no.email at nospam.invalid Sun Aug 29 20:52:38 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 17:52:38 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> Message-ID: <7xd3t0orah.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > You can add cycle detection to a reference count gc, at the cost of more > complexity. But then it's not purely a refcount gc. ;) > If you read the Wikipedia article I linked to, tracing algorithms can > also be unsound: [describes "conservative" gc] Yeah, whether that counts as a real GC is subjective too. >> and 2) it requires constant attention from the mutator to incr and >> decr the reference counts. > Yes. And? I thought I made it clear, the purpose of gc is to improve programmer productivity and program reliability by relieving the programmer from the burden of memory allocation bookkeeping. If the programmer has to painstakingly manage refcounts by hand and the resulting programs are still prone to refcount bugs (both of which are the case with CPython), it's not really gc in a way that lives up to the name. > That's a problem with the CPython API, not reference counting. The > problem is that the CPython API is written at too low a level, beneath > that at which the garbage collector exists, so naturally you have to > manually manage memory. Care to give an example of a reference counted system that's written any other way? > On the other hand, tracing gcs have their own set of problems too, mostly > due to the use of finalizers and attempts to make garbage collection run > more predictably. See here: I think it's fairly common wisdom that finalizers and gc don't interact very well. Finalizers in general aren't in the gc spirit, which says the system should give the illusion that every object stays around forever. As for stuff like hash tables, a usual way to help out the gc is by populating the hash table with weak references, rather than by clearing it out manually when you're done with it. It's also possible for fancy compilers to use a mixture of gc and stack- or region-based allocation. > Tracing garbage collectors aren't a panacea. They're software themselves, > and complex software, which means they're subject to bugs like the one ... You could say the same thing about compilers instead of gc's. The idea in both cases is yes, they're complex, but they put the complexity in one place, so that the application program can rely on the complicated gc or compiler features while itself staying simple. From no.email at nospam.invalid Sun Aug 29 20:56:03 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 17:56:03 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> Message-ID: <7x8w3oor4s.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I could be wrong, but how can they not be subject to the same performance > issue? If you have twenty thousand components that all have to be freed, > they all have to be freed whether you do it when the last reference is > cleared, or six seconds later when the gc does a sweep. GC's on large machines these days do not sweep at all. They copy the live data to a new heap, then release the old heap. Because there is usually more garbage than live data, copying GC's that never touch the garbage are usually faster than any scheme involving freeing unused objects one by one. From nikos.the.gr33k at gmail.com Sun Aug 29 21:14:55 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 29 Aug 2010 18:14:55 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> Message-ID: <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> On 29 ???, 21:44, MRAB wrote: > On 29/08/2010 06:34, ????? wrote: > > > > > > > > > On 28 ???, 23:15, MRAB ?wrote: > >> On 28/08/2010 20:37, ????? wrote: > > >>> On 22 ???, 10:27, ????? ? ?wrote: > >>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ?wrote: > > >>>>> ????? wrote: > >>>>>> # initializecookie > >>>>>> cookie=Cookie.SimpleCookie() > >>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>>>> mycookie =cookie.get('visitor') > > >>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>>>> yandex|13448|spider|crawl)', host ) is None: > >>>>>> ? ? ? blabla... > >>>>>> ======================== > > >>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>>>> within. > >>>>>> So, i have to ask why the if fails? > > >>>>> Maybe it's because != != == > > >>>> Iwant ti if code block to be executed only if the browsercookienames > >>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >>>> Is there somethign wrong with the way i wrote it? > > >>> Please do help me with this too becaus eif i dont solve this my > >>> website keeps count my each visit like iam a guest visitor! > > >> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > >> repr(host). Then follow the code yourself to see whether the condition > >> is True. > > > print mycookie outputs 'None' > > > Thts weird because i check with the browser and the cookie is there! > > Just because you can see it doesn't mean your code can. > > > print repr(host) outputs '78-236-176.adsl.cyta.gr' > > > repr(mycookie.value) (unless mycookie is None) > > > and also > > > print mycookie.value gives an error too. Maybe there is not a value > > method? > > If mycookie is None, then it's not surprising that doesn't have 'value'. > > In summary, mycookie is None, so: > > ? ? ?mycookie and mycookie.value != 'nikos' > > is false (actually None, which is treated as false). > > host == '78-236-176.adsl.cyta.gr', so: > > ? ? ?re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > finds 'cyta' and the search returns a match. > > false or false == false > > blabla... isn't executed. Lets forget the 2nd or argument, ill put it off so we have this now if ( mycookie and mycookie.value != 'nikos' ): #do stuff as long as there ins't a cookie names visitor with a value of nikos in the broswer What does it mean practically that the mycookie equals to None? That mycookie doesnt exist? How should i write this if block to mkake sure it checks whether or not the cookie exists? From nikos.the.gr33k at gmail.com Sun Aug 29 21:38:42 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 29 Aug 2010 18:38:42 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> Message-ID: <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> On 29 ???, 21:34, MRAB wrote: > It likes the values to be in a tuple. If there's one value, that's a > 1-tuple: (page, ). I noticed that if we are dealing with just a single value 'page' will do, no need to tuple for 1-value. it handles fine as a string. > >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and > >> date = %s and host = %s''', page, date, host) > > > or python will not allow it cause it might think there are 4 args > > isntead of two? > > Not Python (the language) as such, but the method. As I said, it > expects the value(s) to be in a tuple. If i dont parenthesize the execute method instead of getting 2 args(sql_query and tuple value) as it expects by deficition, it gets 4 args instead and thats why it fails? I need to know why ti fails. Is that it? Also in here, page, date, host is 3 separate variable values here while (page, date, host) is 3 separate variables values also but withing a tuple. Is this correct? > >> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > >> date = '%s' and host = '%s' ''', (page, date, host)) > > > Whats happens if i attempt to also quote by single or double quoting > > the above although now i'm aware that .execute method does the quoting > > for me? > > The method will put in any quoting that's needed. If you also put in > quotes then that'll result in 2 sets of quoting, one inside the other > (or something like that). > > Why make more work for yourself? Let the method do it for you, safely > and correctly! I'am askign this because i'm tryong to see why On 29 ???, 21:34, MRAB wrote: > It likes the values to be in a tuple. If there's one value, that's a > 1-tuple: (page, ). I noticed that if we are dealing with just a single value 'page' will do, no need to tuple for 1-value. it handles fine as a string. > >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and > >> date = %s and host = %s''', page, date, host) > > > or python will not allow it cause it might think there are 4 args > > isntead of two? > > Not Python (the language) as such, but the method. As I said, it > expects the value(s) to be in a tuple. If i dont parenthesize the execute method instead of getting 2 args(sql_query and tuple value) as it expects by deficition, it gets 4 args instead and thats why it fails? I need to know why ti fails. Is that it? ======================== Also in here, page, date, host is 3 separate variable values here while (page, date, host) is 3 separate variables values also but withing a tuple. Is this correct? ========================= I'm asking this to see why cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and date = '%s' and host = '%s' ''' % (page, date, host) ) does work, while same thign qithout the quotes cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' % (page, date, host) ) doesn't. Dont know why but quotes somehopw confuse me both in strings and sql_queries as well when it comes to substitutions. From python at mrabarnett.plus.com Sun Aug 29 21:51:08 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 02:51:08 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> Message-ID: <4C7B0E8C.1040707@mrabarnett.plus.com> On 30/08/2010 02:14, ????? wrote: > On 29 ???, 21:44, MRAB wrote: >> On 29/08/2010 06:34, ????? wrote: >> >> >> >> >> >> >> >>> On 28 ???, 23:15, MRAB wrote: >>>> On 28/08/2010 20:37, ????? wrote: >> >>>>> On 22 ???, 10:27, ????? wrote: >>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >>>>>>> ????? wrote: >>>>>>>> # initializecookie >>>>>>>> cookie=Cookie.SimpleCookie() >>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>>>>>> mycookie =cookie.get('visitor') >> >>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>>>>>> yandex|13448|spider|crawl)', host ) is None: >>>>>>>> blabla... >>>>>>>> ======================== >> >>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>>>>>> within. >>>>>>>> So, i have to ask why the if fails? >> >>>>>>> Maybe it's because != != == >> >>>>>> Iwant ti if code block to be executed only if the browsercookienames >>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >>>>>> Is there somethign wrong with the way i wrote it? >> >>>>> Please do help me with this too becaus eif i dont solve this my >>>>> website keeps count my each visit like iam a guest visitor! >> >>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and >>>> repr(host). Then follow the code yourself to see whether the condition >>>> is True. >> >>> print mycookie outputs 'None' >> >>> Thts weird because i check with the browser and the cookie is there! >> >> Just because you can see it doesn't mean your code can. >> >>> print repr(host) outputs '78-236-176.adsl.cyta.gr' >> >>> repr(mycookie.value) (unless mycookie is None) >> >>> and also >> >>> print mycookie.value gives an error too. Maybe there is not a value >>> method? >> >> If mycookie is None, then it's not surprising that doesn't have 'value'. >> >> In summary, mycookie is None, so: >> >> mycookie and mycookie.value != 'nikos' >> >> is false (actually None, which is treated as false). >> >> host == '78-236-176.adsl.cyta.gr', so: >> >> re.search(r'(cyta|yandex|13448|spider|crawl)', host) >> >> finds 'cyta' and the search returns a match. >> >> false or false == false >> >> blabla... isn't executed. > > Lets forget the 2nd or argument, ill put it off > > so we have this now > > if ( mycookie and mycookie.value != 'nikos' ): > #do stuff as long as there ins't a cookie names visitor with a > value of nikos in the broswer > > What does it mean practically that the mycookie equals to None? > That mycookie doesnt exist? > > How should i write this if block to mkake sure it checks whether or > not the cookie exists? Under what conditions do you want to execute the block? This: mycookie and mycookie.value != 'nikos' will be true if: there _is_ a cookie, but its value isn't 'nikos' I think that you want is to execute the block if someone else is visiting. Correct? How do you know when it _is_ you? There'll be a cookie which says it's you? If so, then you want to execute the block if there isn't any cookie, or if there's a cookie but it doesn't say it's you: not mycookie or mycookie.value != 'nikos' From python at mrabarnett.plus.com Sun Aug 29 22:04:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 03:04:32 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> Message-ID: <4C7B11B0.704@mrabarnett.plus.com> On 30/08/2010 02:38, ????? wrote: > On 29 ???, 21:34, MRAB wrote: > >> It likes the values to be in a tuple. If there's one value, that's a >> 1-tuple: (page, ). > > I noticed that if we are dealing with just a single value 'page' will > do, no need to tuple for 1-value. > it handles fine as a string. > I tried it with sqlite3, which it didn't like it. For consistency, and compatibility with other SQL engines, I recommend that you always provide a tuple. >>>> cursor.execute('''SELECT hits FROM counters WHERE page = %s and >>>> date = %s and host = %s''', page, date, host) >> >>> or python will not allow it cause it might think there are 4 args >>> isntead of two? >> >> Not Python (the language) as such, but the method. As I said, it >> expects the value(s) to be in a tuple. > > If i dont parenthesize the execute method instead of getting 2 > args(sql_query and tuple value) as it expects by deficition, it gets 4 > args instead and thats why it fails? I need to know why ti fails. Is > that it? > If the SQL query contains placeholder(s), the .execute method expects the value(s) to be provided in a tuple. It's as simple as that. > Also in here, > > page, date, host is 3 separate variable values here > > while > > (page, date, host) is 3 separate variables values also but withing a > tuple. Is this correct? > It doesn't care about the variables as such, only their values. You're putting the values into a tuple and then passing that tuple because that's what the method wants. > >>>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and >>>> date = '%s' and host = '%s' ''', (page, date, host)) >> >>> Whats happens if i attempt to also quote by single or double quoting >>> the above although now i'm aware that .execute method does the quoting >>> for me? >> >> The method will put in any quoting that's needed. If you also put in >> quotes then that'll result in 2 sets of quoting, one inside the other >> (or something like that). >> >> Why make more work for yourself? Let the method do it for you, safely >> and correctly! > > I'am askign this because i'm tryong to see why > > On 29 ???, 21:34, MRAB wrote: > >> It likes the values to be in a tuple. If there's one value, that's a >> 1-tuple: (page, ). > > I noticed that if we are dealing with just a single value 'page' will > do, no need to tuple for 1-value. > it handles fine as a string. > As I've said, for consistency I recommend that you always provide a tuple because some SQL engines require it, and if you need to provide multiple values then you'll need to anyway. >>>> cursor.execute('''SELECT hits FROM counters WHERE page = %s and >>>> date = %s and host = %s''', page, date, host) >> >>> or python will not allow it cause it might think there are 4 args >>> isntead of two? >> >> Not Python (the language) as such, but the method. As I said, it >> expects the value(s) to be in a tuple. > > If i dont parenthesize the execute method instead of getting 2 > args(sql_query and tuple value) as it expects by deficition, it gets 4 > args instead and thats why it fails? I need to know why ti fails. Is > that it? > > ======================== > Also in here, > > page, date, host is 3 separate variable values here > > while > > (page, date, host) is 3 separate variables values also but withing a > tuple. Is this correct? > > > ========================= > I'm asking this to see why > > cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > date = '%s' and host = '%s' ''' % (page, date, host) ) > > does work, while same thign qithout the quotes > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date > = %s and host = %s ''' % (page, date, host) ) > > doesn't. Dont know why but quotes somehopw confuse me both in strings > and sql_queries as well when it comes to substitutions. Don't quote the placeholders yourself. Let the method do it. From nikos.the.gr33k at gmail.com Sun Aug 29 22:07:16 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 19:07:16 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> Message-ID: On 30 ???, 04:51, MRAB wrote: > On 30/08/2010 02:14, ????? wrote: > > > > > > > > > > > On 29 ???, 21:44, MRAB ?wrote: > >> On 29/08/2010 06:34, ????? wrote: > > >>> On 28 ???, 23:15, MRAB ? ?wrote: > >>>> On 28/08/2010 20:37, ????? wrote: > > >>>>> On 22 ???, 10:27, ????? ? ? ?wrote: > >>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ? ?wrote: > > >>>>>>> ????? wrote: > >>>>>>>> # initializecookie > >>>>>>>> cookie=Cookie.SimpleCookie() > >>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>>>>>> mycookie =cookie.get('visitor') > > >>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>>>>>> yandex|13448|spider|crawl)', host ) is None: > >>>>>>>> ? ? ? ?blabla... > >>>>>>>> ======================== > > >>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>>>>>> within. > >>>>>>>> So, i have to ask why the if fails? > > >>>>>>> Maybe it's because != != == > > >>>>>> Iwant ti if code block to be executed only if the browsercookienames > >>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >>>>>> Is there somethign wrong with the way i wrote it? > > >>>>> Please do help me with this too becaus eif i dont solve this my > >>>>> website keeps count my each visit like iam a guest visitor! > > >>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > >>>> repr(host). Then follow the code yourself to see whether the condition > >>>> is True. > > >>> print mycookie outputs 'None' > > >>> Thts weird because i check with the browser and the cookie is there! > > >> Just because you can see it doesn't mean your code can. > > >>> print repr(host) outputs '78-236-176.adsl.cyta.gr' > > >>> repr(mycookie.value) (unless mycookie is None) > > >>> and also > > >>> print mycookie.value gives an error too. Maybe there is not a value > >>> method? > > >> If mycookie is None, then it's not surprising that doesn't have 'value'. > > >> In summary, mycookie is None, so: > > >> ? ? ? mycookie and mycookie.value != 'nikos' > > >> is false (actually None, which is treated as false). > > >> host == '78-236-176.adsl.cyta.gr', so: > > >> ? ? ? re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > >> finds 'cyta' and the search returns a match. > > >> false or false == false > > >> blabla... isn't executed. > > > Lets forget the 2nd or argument, ill put it off > > > so we have this now > > > if ( mycookie and mycookie.value != 'nikos' ): > > ? ? ?#do stuff as long as there ins't a cookie names visitor with a > > value of nikos in the broswer > > > What does it mean practically that the mycookie equals to None? > > That mycookie doesnt exist? > > > How should i write this if block to mkake sure it checks whether or > > not the cookie exists? > > Under what conditions do you want to execute the block? > > This: > > ? ? ?mycookie and mycookie.value != 'nikos' > > will be true if: > > ? ? ?there _is_ a cookie, but its value isn't 'nikos' > > I think that you want is to execute the block if someone else is > visiting. Correct? Yes that exactyl right! To make sure a cookie is set i have a script names koukos.py containing this: ============================== #!/usr/bin/python # -*- coding: utf-8 -*- import cgitb; cgitb.enable() import cgi, os, Cookie # initialize cookie cookie = Cookie.SimpleCookie() cookie.load( os.environ.get('HTTP_COOKIE', '') ) mycookie = cookie.get('visitor') htmlBody = [] # if visitor cookie does exist if ( mycookie and mycookie.value == 'nikos' ): htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? ????????? ?????????? ??? ???????!') cookie['visitor'] = 'nikos' cookie['visitor']['expires'] = -1 #this cookie will expire now else: htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? ?? ??????! ?? ????? ????? ? ??????? ??????????!!') cookie['visitor'] = 'nikos' cookie['visitor']['expires'] = 60*60*24*30*12 htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') print(cookie) print('\n'.join(htmlBody)) ============================= Which i seicth on and off according to my desire if i want to be counted or not! > How do you know when it _is_ you? There'll be a cookie which says it's > you? > > If so, then you want to execute the block if there isn't any cookie, or > if there's a cookie but it doesn't say it's you: > > ? ? ?not mycookie or mycookie.value != 'nikos' i tried this as you suggested: if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| yandex|13448|spider|crawl)', host ) is None: but the counter keeps increasing although the cookie named visitor on my browser exist and also has the valuie of 'nikos'. Why it keeps increasing? Doesn't the if code "sees" that the cookie with a value of "nikos" is present!?!! From wuwei23 at gmail.com Sun Aug 29 22:21:57 2010 From: wuwei23 at gmail.com (alex23) Date: Sun, 29 Aug 2010 19:21:57 -0700 (PDT) Subject: How to convert (unicode) text to image? References: Message-ID: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> kj wrote: > Example: I went to the docs page for ImageDraw. ?There I find that > the constructor for an ImageDraw.Draw object takes an argument, > but *what* this argument should be (integer? object? string?) is > left entirely undefined. ?From the examples given I *guessed* that > it was an object of class Image[...] The docs say: Draw(image) => Draw instance Creates an object that can be used to draw in the given image. It seems pretty obvious that the first argument is an 'image' to me, and when the lib itself defines an Image class... You "guessed" this was the case from this prominent example at the top of the page? import Image, ImageDraw im = Image.open("lena.pgm") draw = ImageDraw.Draw(im) How much more clear can this be made? > Sorry for the outburst, but unfortunately, PIL is not alone in > this. ?Python is awash in poor documentation. [...] > I have to conclude that the problem with Python docs > is somehow "systemic"... Yes, if everyone else disagrees with you, the problem is obviously "systemic". What helps are concrete suggestions to the package maintainers about how these improvements could be made, rather than huge sprawling attacks on the state of Python documentation (and trying to tie it into the state of Python itself) as a whole. Instead, what we get are huge pointless rants like yours whenever someone finds that something isn't spelled out for them in exactly the way that they want. These people are _volunteering_ their effort and their code, all you're providing is an over-excess of hyperbole and punctuation. What is frustrating to me is seeing people like yourself spend far more time slamming these projects than actually contributing useful changes back. From nikos.the.gr33k at gmail.com Sun Aug 29 22:33:56 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 19:33:56 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> Message-ID: On 30 ???, 05:04, MRAB wrote: when iam trying to pass a tuple to the execute methos should i pass it like this? cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' % (page, date, host) ) or like tuple = (page, host, date) cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' % (tuple) ) Or is it the same thing? > > ========================= > > I'm asking this to see why > > > cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > > date = '%s' and host = '%s' ''' % (page, date, host) ) > > > does work, while same thign qithout the quotes > > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date > > = %s and host = %s ''' % (page, date, host) ) > > > doesn't. Dont know why but quotes somehopw confuse me both in strings > > and sql_queries as well when it comes to substitutions. > > Don't quote the placeholders yourself. Let the method do it. No, iam taking substitution here not mysql escaping. Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and date = '%s' and host = '%s' ''' % (page, date, host) ) As it is above it works , with double quotes still works but if i leave it unquoted it doesn't. This is because without sigle or double quotes the the method doesn't know where a value begins and here it ends? That why it needs quoting? From niklasro at gmail.com Sun Aug 29 22:40:09 2010 From: niklasro at gmail.com (Niklasro(.appspot)) Date: Sun, 29 Aug 2010 19:40:09 -0700 (PDT) Subject: Combining 2 regexes to 1 Message-ID: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> Hello, Suspecting it's completely doable combining these 2 regexes to just 1 expression I'm looking for the working syntax. If you know then kindly inform. Thanks in advance ('/a/([^/]*)',List), #list ('/a([^/]*)',List), #list Niklas Rosencrantz From python at mrabarnett.plus.com Sun Aug 29 22:43:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 03:43:07 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> Message-ID: <4C7B1ABB.8080308@mrabarnett.plus.com> On 30/08/2010 03:07, Nik the Greek wrote: > On 30 ???, 04:51, MRAB wrote: >> On 30/08/2010 02:14, ????? wrote: >> >>> On 29 ???, 21:44, MRAB wrote: >>>> On 29/08/2010 06:34, ????? wrote: >> >>>>> On 28 ???, 23:15, MRAB wrote: >>>>>> On 28/08/2010 20:37, ????? wrote: >> >>>>>>> On 22 ???, 10:27, ????? wrote: >>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >>>>>>>>> ????? wrote: >>>>>>>>>> # initializecookie >>>>>>>>>> cookie=Cookie.SimpleCookie() >>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>>>>>>>> mycookie =cookie.get('visitor') >> >>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: >>>>>>>>>> blabla... >>>>>>>>>> ======================== >> >>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>>>>>>>> within. >>>>>>>>>> So, i have to ask why the if fails? >> >>>>>>>>> Maybe it's because != != == >> >>>>>>>> Iwant ti if code block to be executed only if the browsercookienames >>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >>>>>>>> Is there somethign wrong with the way i wrote it? >> >>>>>>> Please do help me with this too becaus eif i dont solve this my >>>>>>> website keeps count my each visit like iam a guest visitor! >> >>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and >>>>>> repr(host). Then follow the code yourself to see whether the condition >>>>>> is True. >> >>>>> print mycookie outputs 'None' >> >>>>> Thts weird because i check with the browser and the cookie is there! >> >>>> Just because you can see it doesn't mean your code can. >> >>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' >> >>>>> repr(mycookie.value) (unless mycookie is None) >> >>>>> and also >> >>>>> print mycookie.value gives an error too. Maybe there is not a value >>>>> method? >> >>>> If mycookie is None, then it's not surprising that doesn't have 'value'. >> >>>> In summary, mycookie is None, so: >> >>>> mycookie and mycookie.value != 'nikos' >> >>>> is false (actually None, which is treated as false). >> >>>> host == '78-236-176.adsl.cyta.gr', so: >> >>>> re.search(r'(cyta|yandex|13448|spider|crawl)', host) >> >>>> finds 'cyta' and the search returns a match. >> >>>> false or false == false >> >>>> blabla... isn't executed. >> >>> Lets forget the 2nd or argument, ill put it off >> >>> so we have this now >> >>> if ( mycookie and mycookie.value != 'nikos' ): >>> #do stuff as long as there ins't a cookie names visitor with a >>> value of nikos in the broswer >> >>> What does it mean practically that the mycookie equals to None? >>> That mycookie doesnt exist? >> >>> How should i write this if block to mkake sure it checks whether or >>> not the cookie exists? >> >> Under what conditions do you want to execute the block? >> >> This: >> >> mycookie and mycookie.value != 'nikos' >> >> will be true if: >> >> there _is_ a cookie, but its value isn't 'nikos' >> >> I think that you want is to execute the block if someone else is >> visiting. Correct? > > Yes that exactyl right! > > To make sure a cookie is set i have a script names koukos.py > containing this: > > ============================== > #!/usr/bin/python > # -*- coding: utf-8 -*- > > import cgitb; cgitb.enable() > import cgi, os, Cookie > > > # initialize cookie > cookie = Cookie.SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > mycookie = cookie.get('visitor') > > htmlBody = [] > > # if visitor cookie does exist > if ( mycookie and mycookie.value == 'nikos' ): > htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? > ????????? ?????????? ??? ???????!') > cookie['visitor'] = 'nikos' > cookie['visitor']['expires'] = -1 #this cookie will expire > now > else: > htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? > ?? ??????! ?? ????? ????? ? ??????? ??????????!!') > cookie['visitor'] = 'nikos' > cookie['visitor']['expires'] = 60*60*24*30*12 > > htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') > > print(cookie) > print('\n'.join(htmlBody)) > ============================= > > Which i seicth on and off according to my desire if i want to be > counted or not! > >> How do you know when it _is_ you? There'll be a cookie which says it's >> you? >> >> If so, then you want to execute the block if there isn't any cookie, or >> if there's a cookie but it doesn't say it's you: >> >> not mycookie or mycookie.value != 'nikos' > > i tried this as you suggested: > > if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| > yandex|13448|spider|crawl)', host ) is None: > > but the counter keeps increasing although the cookie named visitor on > my browser exist and also has the valuie of 'nikos'. > > Why it keeps increasing? Doesn't the if code "sees" that the cookie > with a value of "nikos" is present!?!! Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you said that host was '78-236-176.adsl.cyta.gr', so it matched. Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the condition is true. From python at mrabarnett.plus.com Sun Aug 29 22:48:34 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 03:48:34 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> Message-ID: <4C7B1C02.8070506@mrabarnett.plus.com> On 30/08/2010 03:33, Nik the Greek wrote: > On 30 ???, 05:04, MRAB wrote: > > when iam trying to pass a tuple to the execute methos should i pass it > like this? > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' % (page, date, host) ) > > > or like > > tuple = (page, host, date) > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' % (tuple) ) > > > Or is it the same thing? > 'tuple' is the name of a built-in. Don't use it. The first example is clearer. >>> ========================= >>> I'm asking this to see why >> >>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and >>> date = '%s' and host = '%s' ''' % (page, date, host) ) >> >>> does work, while same thign qithout the quotes >> >>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date >>> = %s and host = %s ''' % (page, date, host) ) >> >>> doesn't. Dont know why but quotes somehopw confuse me both in strings >>> and sql_queries as well when it comes to substitutions. >> >> Don't quote the placeholders yourself. Let the method do it. > > No, iam taking substitution here not mysql escaping. > > Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > date = '%s' and host = '%s' ''' % (page, date, host) ) > > As it is above it works , with double quotes still works but if i > leave it unquoted it doesn't. > > This is because without sigle or double quotes the the method doesn't > know where a value begins and here it ends? That why it needs quoting? Let the method do the substitution: cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''', (page, date, host) ) This is the best way. From clp2 at rebertia.com Sun Aug 29 22:51:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 29 Aug 2010 19:51:59 -0700 Subject: Combining 2 regexes to 1 In-Reply-To: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> References: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> Message-ID: On Sun, Aug 29, 2010 at 7:40 PM, Niklasro(.appspot) wrote: > Hello, Suspecting it's completely doable combining these 2 regexes to > just 1 expression I'm looking for the working syntax. If you know then > kindly inform. Thanks in advance > ('/a/([^/]*)',List), #list > ('/a([^/]*)',List), #list Er, /a(/?)([^/]*) ? Cheers, Chris -- Parentheses probably extraneous. From nikos.the.gr33k at gmail.com Sun Aug 29 22:55:56 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 19:55:56 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> Message-ID: <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> On 30 ???, 05:43, MRAB wrote: > On 30/08/2010 03:07, Nik the Greek wrote: > > > > > > > > > > > On 30 ???, 04:51, MRAB ?wrote: > >> On 30/08/2010 02:14, ????? wrote: > > >>> On 29 ???, 21:44, MRAB ? ?wrote: > >>>> On 29/08/2010 06:34, ????? wrote: > > >>>>> On 28 ???, 23:15, MRAB ? ? ?wrote: > >>>>>> On 28/08/2010 20:37, ????? wrote: > > >>>>>>> On 22 ???, 10:27, ????? ? ? ? ?wrote: > >>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ? ? ?wrote: > > >>>>>>>>> ????? wrote: > >>>>>>>>>> # initializecookie > >>>>>>>>>> cookie=Cookie.SimpleCookie() > >>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>>>>>>>> mycookie =cookie.get('visitor') > > >>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: > >>>>>>>>>> ? ? ? ? blabla... > >>>>>>>>>> ======================== > > >>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>>>>>>>> within. > >>>>>>>>>> So, i have to ask why the if fails? > > >>>>>>>>> Maybe it's because != != == > > >>>>>>>> Iwant ti if code block to be executed only if the browsercookienames > >>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >>>>>>>> Is there somethign wrong with the way i wrote it? > > >>>>>>> Please do help me with this too becaus eif i dont solve this my > >>>>>>> website keeps count my each visit like iam a guest visitor! > > >>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > >>>>>> repr(host). Then follow the code yourself to see whether the condition > >>>>>> is True. > > >>>>> print mycookie outputs 'None' > > >>>>> Thts weird because i check with the browser and the cookie is there! > > >>>> Just because you can see it doesn't mean your code can. > > >>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' > > >>>>> repr(mycookie.value) (unless mycookie is None) > > >>>>> and also > > >>>>> print mycookie.value gives an error too. Maybe there is not a value > >>>>> method? > > >>>> If mycookie is None, then it's not surprising that doesn't have 'value'. > > >>>> In summary, mycookie is None, so: > > >>>> ? ? ? ?mycookie and mycookie.value != 'nikos' > > >>>> is false (actually None, which is treated as false). > > >>>> host == '78-236-176.adsl.cyta.gr', so: > > >>>> ? ? ? ?re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > >>>> finds 'cyta' and the search returns a match. > > >>>> false or false == false > > >>>> blabla... isn't executed. > > >>> Lets forget the 2nd or argument, ill put it off > > >>> so we have this now > > >>> if ( mycookie and mycookie.value != 'nikos' ): > >>> ? ? ? #do stuff as long as there ins't a cookie names visitor with a > >>> value of nikos in the broswer > > >>> What does it mean practically that the mycookie equals to None? > >>> That mycookie doesnt exist? > > >>> How should i write this if block to mkake sure it checks whether or > >>> not the cookie exists? > > >> Under what conditions do you want to execute the block? > > >> This: > > >> ? ? ? mycookie and mycookie.value != 'nikos' > > >> will be true if: > > >> ? ? ? there _is_ a cookie, but its value isn't 'nikos' > > >> I think that you want is to execute the block if someone else is > >> visiting. Correct? > > > Yes that exactyl right! > > > To make sure a cookie is set i have a script names koukos.py > > containing this: > > > ============================== > > #!/usr/bin/python > > # -*- coding: utf-8 -*- > > > import cgitb; cgitb.enable() > > import cgi, os, Cookie > > > # initialize cookie > > cookie = Cookie.SimpleCookie() > > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > mycookie = cookie.get('visitor') > > > htmlBody = [] > > > # if visitor cookie does exist > > if ( mycookie and mycookie.value == 'nikos' ): > > ? ? ?htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? > > ????????? ?????????? ??? ???????!') > > ? ? ?cookie['visitor'] = 'nikos' > > ? ? ?cookie['visitor']['expires'] = -1 ? ? ?#this cookie will expire > > now > > else: > > ? ? ?htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? > > ?? ??????! ?? ????? ????? ? ??????? ??????????!!') > > ? ? ?cookie['visitor'] = 'nikos' > > ? ? ?cookie['visitor']['expires'] = 60*60*24*30*12 > > > htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') > > > print(cookie) > > print('\n'.join(htmlBody)) > > ============================= > > > Which i seicth on and off according to my desire if i want to be > > counted or not! > > >> How do you know when it _is_ you? There'll be a cookie which says it's > >> you? > > >> If so, then you want to execute the block if there isn't any cookie, or > >> if there's a cookie but it doesn't say it's you: > > >> ? ? ? not mycookie or mycookie.value != 'nikos' > > > i tried this as you suggested: > > > if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| > > yandex|13448|spider|crawl)', host ) is None: > > > but the counter keeps increasing although the cookie named visitor on > > my browser exist and also has the valuie of 'nikos'. > > > Why it keeps increasing? Doesn't the if code "sees" that the cookie > > with a value of "nikos" is present!?!! > > Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you > said that host was '78-236-176.adsl.cyta.gr', so it matched. > > Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still > '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the > condition is true. Thats what i want. If host doesnt contain substringsa of the regex to execute if block. if it does match i dont want then if block to execute, hence the counter too. The reason i had 'cyta' before is because not mycookie or mycookie.value != 'nikos' doesn't filter me out. The problem is what happens with the not mycookie or mycookie.value != 'nikos' Since cookie 'visitor' does contain the 'nikos' value why the if code blck gets executed? From nikos.the.gr33k at gmail.com Sun Aug 29 23:01:26 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 20:01:26 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> Message-ID: <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> On 30 ???, 05:48, MRAB wrote: > On 30/08/2010 03:33, Nik the Greek wrote: > > > > > > > > > On 30 ???, 05:04, MRAB ?wrote: > > > when iam trying to pass a tuple to the execute methos should i pass it > > like this? > > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > > date = %s and host = %s ''' % (page, date, host) ) > > > or like > > > tuple = (page, host, date) > > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > > date = %s and host = %s ''' % (tuple) ) > > > Or is it the same thing? > > 'tuple' is the name of a built-in. Don't use it. > > The first example is clearer. ok a_tuple = (page, hist, host) cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' , a_tuple ) would that syntax be correct? No need to enclose the tuple name inside parenthesis here right? > >>> ========================= > >>> I'm asking this to see why > > >>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > >>> date = '%s' and host = '%s' ''' % (page, date, host) ) > > >>> does work, while same thign qithout the quotes > > >>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date > >>> = %s and host = %s ''' % (page, date, host) ) > > >>> doesn't. Dont know why but quotes somehopw confuse me both in strings > >>> and sql_queries as well when it comes to substitutions. > > >> Don't quote the placeholders yourself. Let the method do it. > > > No, iam taking substitution here not mysql escaping. > > > Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > > date = '%s' and host = '%s' ''' % (page, date, host) ) > > > As it is above it works , with double quotes still works but if i > > leave it unquoted it doesn't. > > > This is because without sigle or double quotes the the method doesn't > > know where a value begins and here it ends? That why it needs quoting? > > Let the method do the substitution: > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = > %s and host = %s ''', (page, date, host) ) > > This is the best way. Yes i will i just asked to know if i were to substitute what might be the problem so to understand why i need the quoting. why not like that? > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = > %s and host = %s ''' % (page, date, host) ) From python at mrabarnett.plus.com Sun Aug 29 23:07:13 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 04:07:13 +0100 Subject: Combining 2 regexes to 1 In-Reply-To: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> References: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> Message-ID: <4C7B2061.4080301@mrabarnett.plus.com> On 30/08/2010 03:40, Niklasro(.appspot) wrote: > Hello, Suspecting it's completely doable combining these 2 regexes to > just 1 expression I'm looking for the working syntax. If you know then > kindly inform. Thanks in advance > ('/a/([^/]*)',List), #list > ('/a([^/]*)',List), #list ('/a/?([^/]*)', List), #list From python at mrabarnett.plus.com Sun Aug 29 23:12:03 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 04:12:03 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> Message-ID: <4C7B2183.7000302@mrabarnett.plus.com> On 30/08/2010 03:55, Nik the Greek wrote: > On 30 ???, 05:43, MRAB wrote: >> On 30/08/2010 03:07, Nik the Greek wrote: >> >> >> >> >> >> >> >> >> >>> On 30 ???, 04:51, MRAB wrote: >>>> On 30/08/2010 02:14, ????? wrote: >> >>>>> On 29 ???, 21:44, MRAB wrote: >>>>>> On 29/08/2010 06:34, ????? wrote: >> >>>>>>> On 28 ???, 23:15, MRAB wrote: >>>>>>>> On 28/08/2010 20:37, ????? wrote: >> >>>>>>>>> On 22 ???, 10:27, ????? wrote: >>>>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >>>>>>>>>>> ????? wrote: >>>>>>>>>>>> # initializecookie >>>>>>>>>>>> cookie=Cookie.SimpleCookie() >>>>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>>>>>>>>>> mycookie =cookie.get('visitor') >> >>>>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: >>>>>>>>>>>> blabla... >>>>>>>>>>>> ======================== >> >>>>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>>>>>>>>>> within. >>>>>>>>>>>> So, i have to ask why the if fails? >> >>>>>>>>>>> Maybe it's because != != == >> >>>>>>>>>> Iwant ti if code block to be executed only if the browsercookienames >>>>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >>>>>>>>>> Is there somethign wrong with the way i wrote it? >> >>>>>>>>> Please do help me with this too becaus eif i dont solve this my >>>>>>>>> website keeps count my each visit like iam a guest visitor! >> >>>>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and >>>>>>>> repr(host). Then follow the code yourself to see whether the condition >>>>>>>> is True. >> >>>>>>> print mycookie outputs 'None' >> >>>>>>> Thts weird because i check with the browser and the cookie is there! >> >>>>>> Just because you can see it doesn't mean your code can. >> >>>>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' >> >>>>>>> repr(mycookie.value) (unless mycookie is None) >> >>>>>>> and also >> >>>>>>> print mycookie.value gives an error too. Maybe there is not a value >>>>>>> method? >> >>>>>> If mycookie is None, then it's not surprising that doesn't have 'value'. >> >>>>>> In summary, mycookie is None, so: >> >>>>>> mycookie and mycookie.value != 'nikos' >> >>>>>> is false (actually None, which is treated as false). >> >>>>>> host == '78-236-176.adsl.cyta.gr', so: >> >>>>>> re.search(r'(cyta|yandex|13448|spider|crawl)', host) >> >>>>>> finds 'cyta' and the search returns a match. >> >>>>>> false or false == false >> >>>>>> blabla... isn't executed. >> >>>>> Lets forget the 2nd or argument, ill put it off >> >>>>> so we have this now >> >>>>> if ( mycookie and mycookie.value != 'nikos' ): >>>>> #do stuff as long as there ins't a cookie names visitor with a >>>>> value of nikos in the broswer >> >>>>> What does it mean practically that the mycookie equals to None? >>>>> That mycookie doesnt exist? >> >>>>> How should i write this if block to mkake sure it checks whether or >>>>> not the cookie exists? >> >>>> Under what conditions do you want to execute the block? >> >>>> This: >> >>>> mycookie and mycookie.value != 'nikos' >> >>>> will be true if: >> >>>> there _is_ a cookie, but its value isn't 'nikos' >> >>>> I think that you want is to execute the block if someone else is >>>> visiting. Correct? >> >>> Yes that exactyl right! >> >>> To make sure a cookie is set i have a script names koukos.py >>> containing this: >> >>> ============================== >>> #!/usr/bin/python >>> # -*- coding: utf-8 -*- >> >>> import cgitb; cgitb.enable() >>> import cgi, os, Cookie >> >>> # initialize cookie >>> cookie = Cookie.SimpleCookie() >>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>> mycookie = cookie.get('visitor') >> >>> htmlBody = [] >> >>> # if visitor cookie does exist >>> if ( mycookie and mycookie.value == 'nikos' ): >>> htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? >>> ????????? ?????????? ??? ???????!') >>> cookie['visitor'] = 'nikos' >>> cookie['visitor']['expires'] = -1 #this cookie will expire >>> now >>> else: >>> htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? >>> ?? ??????! ?? ????? ????? ? ??????? ??????????!!') >>> cookie['visitor'] = 'nikos' >>> cookie['visitor']['expires'] = 60*60*24*30*12 >> >>> htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') >> >>> print(cookie) >>> print('\n'.join(htmlBody)) >>> ============================= >> >>> Which i seicth on and off according to my desire if i want to be >>> counted or not! >> >>>> How do you know when it _is_ you? There'll be a cookie which says it's >>>> you? >> >>>> If so, then you want to execute the block if there isn't any cookie, or >>>> if there's a cookie but it doesn't say it's you: >> >>>> not mycookie or mycookie.value != 'nikos' >> >>> i tried this as you suggested: >> >>> if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| >>> yandex|13448|spider|crawl)', host ) is None: >> >>> but the counter keeps increasing although the cookie named visitor on >>> my browser exist and also has the valuie of 'nikos'. >> >>> Why it keeps increasing? Doesn't the if code "sees" that the cookie >>> with a value of "nikos" is present!?!! >> >> Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you >> said that host was '78-236-176.adsl.cyta.gr', so it matched. >> >> Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still >> '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the >> condition is true. > > Thats what i want. > > If host doesnt contain substringsa of the regex to execute if block. > if it does match i dont want then if block to execute, hence the > counter too. > > The reason i had 'cyta' before is because not mycookie or > mycookie.value != 'nikos' doesn't filter me out. > > The problem is what happens with the > > not mycookie or mycookie.value != 'nikos' > > Since cookie 'visitor' does contain the 'nikos' value why the if code > blck gets executed? This part: ( not mycookie or mycookie.value != 'nikos' ) is false but this part: re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None is true because host doesn't contain any of those substrings. From aahz at pythoncraft.com Sun Aug 29 23:28:27 2010 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2010 20:28:27 -0700 Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> <40a6bfac-3f4b-43f4-990b-224cb2b654d3@i19g2000pro.googlegroups.com> Message-ID: In article <40a6bfac-3f4b-43f4-990b-224cb2b654d3 at i19g2000pro.googlegroups.com>, Carl Banks wrote: > >FWIW, I think it perfectly reasonable to let an application print a >traceback on an error. I've gotten a few bug reports on a little tool >I maintain where the user copies the traceback to me, it it's helped >me diagnose their issues a lot. That only really works for non-GUI applications. For GUI apps, log files are the way to go. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From nikos.the.gr33k at gmail.com Sun Aug 29 23:33:20 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 20:33:20 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> Message-ID: <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> On 30 ???, 06:12, MRAB wrote: > This part: > > ? ? ?( not mycookie or mycookie.value != 'nikos' ) > > is false but this part: > > ? ? ?re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > is true because host doesn't contain any of those substrings. So, the if code does executed because one of the condition is true? How should i write it? I cannot think clearly on this at all. I just wan to tell it to get executed ONLY IF the cookie values is not 'nikos' or ( don't knwo if i have to use and or 'or' here) host does not contain any of the substrings. What am i doign wrong?! From steve-REMOVE-THIS at cybersource.com.au Sun Aug 29 23:38:06 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 03:38:06 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> <7xd3t0orah.fsf@ruckus.brouhaha.com> Message-ID: <4c7b279d$0$28650$c3e8da3@news.astraweb.com> On Sun, 29 Aug 2010 17:52:38 -0700, Paul Rubin wrote: >> That's a problem with the CPython API, not reference counting. The >> problem is that the CPython API is written at too low a level, beneath >> that at which the garbage collector exists, so naturally you have to >> manually manage memory. > > Care to give an example of a reference counted system that's written any > other way? The complexity of the ref counter is invisible when writing pure Python code, and I believe it is also invisible when writing code in Cython. The difficulty of dealing with ref counts is abstracted away. The argument that "it will work if we always do this" means that it won't work is a nice quip, but it doesn't stand up. It's possible to defeat even Pascal compilers' type checking and do unsafe things by dropping down into assembly. So don't do it! It's not hard to not do something, although sometimes you might choose to do it anyway, because otherwise there is no way to get the code you need/want. But such code should be a rare exception. I'm not saying that ref counting systems can avoid incrementing and decrementing the ref counts. That would be silly. But I'm saying that it is an accident of implementation that writing C extensions requires you to manually manage the counts yourself. That's a side-effect of permitting coders to write C extensions in pure C, rather than in some intermediate language which handles the ref counts for you but otherwise compiles like C. If people cared enough, they could (probably) make the C compiler handle it for them, just as it currently handles incrementing and decrementing the return stack. There's nothing *fundamental* to the idea of ref counting that says that you must handle the counts manually -- it depends on how well insulated you are from the underlying machine. -- Steven From ldo at geek-central.gen.new_zealand Sun Aug 29 23:46:39 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 30 Aug 2010 15:46:39 +1200 Subject: Helper app for intranet site References: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> Message-ID: In message <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5 at n19g2000prf.googlegroups.com>, kevinlcarlson wrote: > I'm exploring the possibility of developing a helper app for an > existing internal company website. Basically, it would automatically > scan the current page contents, including prepopulated forms, and > provide context-related business rule comments to the user, via a stay- > on-top wxPython panel. Seems like a roundabout way of doing it. Can?t you integrate into the server code which is generating the page contents, instead of trying to reverse- engineer those contents? From ldo at geek-central.gen.new_zealand Sun Aug 29 23:57:58 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 30 Aug 2010 15:57:58 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> Message-ID: In message <7x4oeftuk4.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > I'd say [reference-counting is] not real gc because 1) it's unsound > (misses reference cycles), and 2) it requires constant attention from the > mutator to incr and decr the reference counts. So developing modules for > the CPython API means endlessly finding and fixing refcount bugs that lead > to either crashes/security failures, or memory leaks. I don?t see why that should be so. It seems a very simple discipline to follow: initialize, allocate, free. Here?s an example snippet from my DVD Menu Animator : static void GetBufferInfo ( PyObject * FromArray, unsigned long * addr, unsigned long * len ) /* returns the address and length of the data in a Python array object. */ { PyObject * TheBufferInfo = 0; PyObject * AddrObj = 0; PyObject * LenObj = 0; do /*once*/ { TheBufferInfo = PyObject_CallMethod(FromArray, "buffer_info", ""); if (TheBufferInfo == 0) break; AddrObj = PyTuple_GetItem(TheBufferInfo, 0); LenObj = PyTuple_GetItem(TheBufferInfo, 1); if (PyErr_Occurred()) break; Py_INCREF(AddrObj); Py_INCREF(LenObj); *addr = PyInt_AsUnsignedLongMask(AddrObj); *len = PyInt_AsUnsignedLongMask(LenObj); if (PyErr_Occurred()) break; } while (false); Py_XDECREF(AddrObj); Py_XDECREF(LenObj); Py_XDECREF(TheBufferInfo); } /*GetBufferInfo*/ It?s quite easy to assure yourself that this is never going to leak memory. More complicated examples can simply nest constructs like these one within the other to arbitrary depth, while still giving the same assurance at every level. In short, this technique scales well. > If you program the Java JNI or a typical Lisp FFI, you'll find that real > gc is a lot simpler to use since you avoid all the refcount maintenance > hassles. You allocate memory and shut your eyes, and the gc takes care of > freeing it when it figures out that you are done. And how do you run such an application? You have to limit it to a predetermined amount of memory to begin with, otherwise it would easily gobble up everything you have. In the old days of ?classic? MacOS, every application had to run in a fixed- size application heap. I have no wish to return to those days. From niklasro at gmail.com Mon Aug 30 00:03:07 2010 From: niklasro at gmail.com (Niklasro(.appspot)) Date: Sun, 29 Aug 2010 21:03:07 -0700 (PDT) Subject: Combining 2 regexes to 1 References: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> Message-ID: <2379250d-9cc5-4f07-a08c-1967e600c2f2@l20g2000yqe.googlegroups.com> Many thanks. It works. You also helped me refactor these ('/([0-9]*)/?([^/]*)',AById),#id2a ('/([0-9]*)',AById) to just 1 ('/([0-9]*)/?([^/]*)',AById),#id2a It's from the appspot framework. Sincerely Niklas R From rurpy at yahoo.com Mon Aug 30 00:23:08 2010 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sun, 29 Aug 2010 21:23:08 -0700 (PDT) Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On 08/29/2010 08:21 PM, alex23 wrote: > kj wrote: snip >> Sorry for the outburst, but unfortunately, PIL is not alone in >> this. Python is awash in poor documentation. [...] >> I have to conclude that the problem with Python docs >> is somehow "systemic"... > > Yes, if everyone else disagrees with you, the problem is obviously > "systemic". No, not everyone disagrees with him. There are many people who absolutely agree with him. > What helps are concrete suggestions to the package maintainers about > how these improvements could be made, rather than huge sprawling > attacks on the state of Python documentation (and trying to tie it > into the state of Python itself) as a whole. ] Nothing you quoted of what he wrote attempted to "tie it into the state of Python itself" > Instead, what we get are > huge pointless rants like yours whenever someone finds that something > isn't spelled out for them in exactly the way that they want. He never complained about spelling choices. > These people are _volunteering_ their effort and their code, Yes, we all know that. > all > you're providing is an over-excess of hyperbole It is hardly convincing when one criticizes hyperbole with hyperbole. > and punctuation. What > is frustrating to me is seeing people like yourself spend far more > time slamming these projects than actually contributing useful changes > back. Face the facts dude. The Python docs have some major problems. They were pretty good when Python was a new, cool, project used by a handful of geeks. They are good relative to the "average" (whatever that is) open source project -- but that bar is so low as to be a string lying on the ground. Your overly defensive and oppressive response does not help. All it (combined with similar knee-jerk responses) does is act to suppress any criticism leaving the impression that the Python docs are really great, an assertion commonly made here and often left unchallenged. Responses like yours create a force that works to maintain the status quo. From no.email at nospam.invalid Mon Aug 30 00:48:41 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 21:48:41 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> Message-ID: <7x39twpuxi.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: >> the CPython API means endlessly finding and fixing refcount bugs that lead >> to either crashes/security failures, or memory leaks. > > I don?t see why that should be so. It seems a very simple discipline to > follow: initialize, allocate, free. Here?s an example snippet from my DVD > Menu Animator : In practice it has been a problem. If it hasn't happened to you yet, you're either burning a bunch of effort that programmers of more automatic systems can put to more productive uses, or else you just haven't written enough such code to have gotten bitten yet. >> You allocate memory and shut your eyes, and the gc takes care of >> freeing it when it figures out that you are done. > > And how do you run such an application? You have to limit it to a > predetermined amount of memory to begin with, otherwise it would easily > gobble up everything you have. No that's usually not a problem-- the runtime system (generational gc) can figure out enough from your allocation pattern to prevent the heap from getting overlarge. From brian.curtin at gmail.com Mon Aug 30 00:57:51 2010 From: brian.curtin at gmail.com (Brian Curtin) Date: Sun, 29 Aug 2010 23:57:51 -0500 Subject: looking for open source python project In-Reply-To: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> References: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> Message-ID: On Sat, Aug 28, 2010 at 19:50, mo reina wrote: > looking for a python project (preferably something a bit small) that > is looking for contributors. the small bit is because i've never > worked in a team before and haven't really read source code that's > 1000s of lines long, so i'm not too sure i can keep up. > > my python fu is decent (i think), i recently wrote a small archive/ > grimoire program (command line only) that can store multiline text > with title, tags, and basic search functionality (not using curses so > the entry, once entered, can't be modified), entries are stored in a > pickle file. > > anybody have any suggestions? i'm keen to work on something with > others, both for learning and i'd like to do something a bit > meaningful, plus i'm sure it's fun. Check out http://bugs.python.org along with the pages of the Python development area at http://www.python.org/dev/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Mon Aug 30 02:07:03 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 23:07:03 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> Message-ID: <7xr5hg3a7s.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > static void GetBufferInfo > ( ... > do /*once*/ > { > TheBufferInfo = PyObject_CallMethod(FromArray, "buffer_info", ""); > if (TheBufferInfo == 0) > break; > AddrObj = PyTuple_GetItem(TheBufferInfo, 0); > LenObj = PyTuple_GetItem(TheBufferInfo, 1); > if (PyErr_Occurred()) > break; > ... > Py_INCREF(AddrObj); > Py_INCREF(LenObj); > } > while (false); > Py_XDECREF(AddrObj); > Py_XDECREF(LenObj); > Py_XDECREF(TheBufferInfo); > } /*GetBufferInfo*/ > > It?s quite easy to assure yourself that this is never going to leak memory. Actually that code looks suspicious. Suppose in AddrObj = PyTuple_GetItem(TheBufferInfo, 0); LenObj = PyTuple_GetItem(TheBufferInfo, 1); the first PyTuple_GetItem succeeds and the second one fails. Then AddrObj is a borrowed reference to the first tuple element and LenObj is null, the error flag is set, so you break out of the do/while. You then decrement the refcount of AddrObj even though you didn't increment it. Maybe there's an explanation that makes it ok somehow, but it still looks messy. This is the kind of problem I'm referring to in general. From python at rcn.com Mon Aug 30 02:25:12 2010 From: python at rcn.com (Raymond Hettinger) Date: Sun, 29 Aug 2010 23:25:12 -0700 (PDT) Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: On Aug 29, 12:12?pm, John Nagle wrote: > ? ? Is the "in" test faster for a dict or a set? > Is "frozenset" faster than "set"? ?Use case is > for things like applying "in" on a list of 500 or so words > while checking a large body of text. There is no significant difference. All three are implemented using substantially the same code. Raymond From julia.jacobson at arcor.de Mon Aug 30 02:29:43 2010 From: julia.jacobson at arcor.de (Julia Jacobson) Date: Mon, 30 Aug 2010 08:29:43 +0200 Subject: Passing variable to SQL statement when using psycopg2 Message-ID: <4c7b4fd3$0$6887$9b4e6d93@newsspool2.arcor-online.net> Dear python users, For passing a variable to a SQL query for psycopg2, I use: >>> my_var = xyz >>> print cur.mogrify("SELECT my_values FROM my_table WHERE my_column = %s",(my_var,)) This returns: >>> SELECT my_values FROM my_table WHERE my_column = E'xyz' Where does the "E" in front of 'xyz' come from? It's probably the reason, why my query doesn't work. Thanks in advance, Julia From deepud at gmail.com Mon Aug 30 02:35:26 2010 From: deepud at gmail.com (agnibhu) Date: Sun, 29 Aug 2010 23:35:26 -0700 (PDT) Subject: Tag parsing in python References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: <944bfce7-6e5c-4460-bc75-2d3e44c9e6b1@a4g2000prm.googlegroups.com> On Aug 29, 5:43?pm, Paul McGuire wrote: > On Aug 28, 11:23?pm, Paul McGuire wrote: > > > > > On Aug 28, 11:14?am, agnibhu wrote: > > > > Hi all, > > > > I'm a newbie in python. I'm trying to create a library for parsing > > > certain keywords. > > > For example say I've key words like abc: bcd: cde: like that... So the > > > user may use like > > > abc: How are you bcd: I'm fine cde: ok > > > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > > > assign them to abc:, bcd: and cde: respectively.. There may be > > > combination of keyowords introduced in future. like abc: xy: How are > > > you > > > So new keywords qualifying the other keywords so on.. > > I got to thinking more about your keywords-qualifying-keywords > example, and I thought this would be a good way to support locale- > specific tags. ?I also thought how one might want to have tags within > tags, to be substituted later, requiring a "abc::" escaped form of > "abc:", so that the tag is substituted with the value of tag "abc:" as > a late binding. > > Wasn't too hard to modify what I posted yesterday, and now I rather > like it. > > -- Paul > > # tag_substitute.py > > from pyparsing import (Combine, Word, alphas, FollowedBy, Group, > OneOrMore, > ? ? empty, SkipTo, LineEnd, Optional, Forward, MatchFirst, Literal, > And, replaceWith) > > tag = Combine(Word(alphas) + ~FollowedBy("::") + ":") > tag_defn = Group(OneOrMore(tag))("tag") + empty + SkipTo(tag | > LineEnd())("body") + Optional(LineEnd().suppress()) > > # now combine macro detection with substitution > macros = {} > macro_substitution = Forward() > def make_macro_sub(tokens): > ? ? # unescape '::' and substitute any embedded tags > ? ? tag_value = > macro_substitution.transformString(tokens.body.replace("::",":")) > > ? ? # save this tag and value (or overwrite previous) > ? ? macros[tuple(tokens.tag)] = tag_value > > ? ? # define overall macro substitution expression > ? ? macro_substitution << MatchFirst( > ? ? ? ? ? ? [(Literal(k[0]) if len(k)==1 > ? ? ? ? ? ? ? ? else And([Literal(kk) for kk in > k])).setParseAction(replaceWith(v)) > ? ? ? ? ? ? ? ? ? ? for k,v in macros.items()] ) + ~FollowedBy(tag) > > ? ? # return empty string, so macro definitions don't show up in final > ? ? # expanded text > ? ? return "" > > tag_defn.setParseAction(make_macro_sub) > > # define pattern for macro scanning > scan_pattern = macro_substitution | tag_defn > > sorry = """\ > nm: Dave > sorry: en: I'm sorry, nm::, I'm afraid I can't do that. > sorry: es: Lo siento nm::, me temo que no puedo hacer eso. > Hal said, "sorry: en:" > Hal dijo, "sorry: es:" """ > print scan_pattern.transformString(sorry) > > Prints: > > Hal said, "I'm sorry, Dave, I'm afraid I can't do that." > Hal dijo, "Lo siento Dave, me temo que no puedo hacer eso." Thanks all for giving me great solutions. I'm happy to see the respones. Will try out these and post the reply soon. Thanks once again, Agnibhu.. From __peter__ at web.de Mon Aug 30 02:36:06 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Aug 2010 08:36:06 +0200 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: Seth Rees wrote: > On 08/29/10 14:43, Peter Otten wrote: >> John Nagle wrote: >> >>> Is the "in" test faster for a dict or a set? >>> Is "frozenset" faster than "set"? Use case is >>> for things like applying "in" on a list of 500 or so words >>> while checking a large body of text. >> >> As Arnaud suspects: no significant difference: >> >> $ python dictperf.py >> dict --> 0.210289001465 >> set --> 0.202902793884 >> frozenset --> 0.198950052261 >> >> $ cat dictperf.py >> import random >> import timeit >> >> with open("/usr/share/dict/words") as instream: >> words = [line.strip() for line in instream] >> >> #random.seed(42) >> sample = random.sample(words, 501) >> >> n = sample.pop() >> y = random.choice(sample) >> >> d = dict.fromkeys(sample) >> s = set(sample) >> f = frozenset(sample) >> >> >> for lookup in d, s, f: >> print type(lookup).__name__, "-->", timeit.timeit( >> "n in lookup; y in lookup", >> "from __main__ import lookup, n, y") >> >> Peter > What about lists versus tuples? You trade O(1) for O(N) with both, a bad idea for all but the smallest lists/tuples. $ python dictperf.py dict --> 0.221934080124 set --> 0.220952987671 frozenset --> 0.225043058395 list --> 21.5041530132 tuple --> 20.8655071259 By the way, the script will run on your computer, too ;) Peter From python at rcn.com Mon Aug 30 02:41:42 2010 From: python at rcn.com (Raymond Hettinger) Date: Sun, 29 Aug 2010 23:41:42 -0700 (PDT) Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: On Aug 29, 8:33?am, Arnaud Delobelle wrote: > ernest writes: > > Hi, > > > The operator module provides separate functions for > > "in place" operations, such as iadd(), isub(), etc. > > However, it appears that these functions don't really > > do the operation in place: > > > In [34]: a = 4 > > > In [35]: operator.iadd(a, 3) > > Out[35]: 7 > > > In [36]: a > > Out[36]: 4 > > > So, what's the point? If you have to make the > > assignment yourself... I don't understand. > > > Cheers, > > Ernest > > That's because > > ? ?a += b > > is executed as: > > ? ?a = a.__iadd__(b) > > For immutable objects, (such as integers), a.__iadd__(b) returns a + b > *and then* this value is assigned to a (or rather 'a' is bound to the > value). ?So for immutables objects, iadd(a, b) is the same as a + b > > For mutable objects (such as lists), a.__iadd__(b) mutates the object > *and then* returns self so that when the assignement is executed, 'a' > will still be bound the the same object. ?E.g. if a = [1, 2] then > > ? ? a += [3] > > will first append 3 to the list and then reassign the list to 'a' (it is > unnecessary in this case but if this step was omitted, the "in place" > operators wouldn't work on immutables types). This is an excellent explanation. Perhaps, you can submit a documentation patch for the operator module so this doesn't get lost. Raymond From lamlbiro at optusnet.com.au Mon Aug 30 02:42:39 2010 From: lamlbiro at optusnet.com.au (L) Date: Mon, 30 Aug 2010 16:42:39 +1000 Subject: PyGeo In-Reply-To: References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> Message-ID: <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> On 30/08/10 05:00, Thomas Jollans wrote: > On Sunday 29 August 2010, it occurred to L to exclaim: > >> has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu >> 10.04) , >> the site says >> >> http://www.wspiegel.de/pymaxima/index_en.html >> >> "Note: The installation of PyGeo work's only under Python 2.4 (The >> further development of pygeo seems to be stopped)" >> >> is this to do with re-org of site-packages, dist_packages etc. >> >> any help most appreciated. >> > I don't know. I haven't tried. Maybe somebody else here has, but don't count > on it. Have you tried it? If not, then why not? Try it. Maybe it just works. > As far as I know, distutils haven't changed much, carefully avoiding any > changes that could break packages. > > I think it's entirely possible that the web page author claiming "the > installation" doesn't work was referring only to the Windows installer. > > Have fun, > Thomas > -------------------------------- I have tried it and as soon as you try any of the examples in the examples dir it cannot find numpy etc.... I have manually move the pygeo dirs and contents to /usr/lib/python2.6/dis-packages, (this is the directory where numpy, numeric and scipy were installed when using synaptic ) made sure that read and write permissions set for ALL FILES and DIRECTORIES to RW using sudo chmod 777 any ideas. From clp2 at rebertia.com Mon Aug 30 03:08:58 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 30 Aug 2010 00:08:58 -0700 Subject: Passing variable to SQL statement when using psycopg2 In-Reply-To: <4c7b4fd3$0$6887$9b4e6d93@newsspool2.arcor-online.net> References: <4c7b4fd3$0$6887$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sun, Aug 29, 2010 at 11:29 PM, Julia Jacobson wrote: > Dear python users, > > For passing a variable to a SQL query for psycopg2, I use: > > ?>>> my_var = xyz > ?>>> print cur.mogrify("SELECT my_values FROM my_table WHERE my_column = > %s",(my_var,)) > > This returns: > > ?>>> SELECT my_values FROM my_table WHERE my_column = E'xyz' > > Where does the "E" in front of 'xyz' come from? > It's probably the reason, why my query doesn't work. Quite doubtful, considering the example in the psycopg2 docs also has the E: http://initd.org/psycopg/docs/cursor.html#cursor.mogrify Cheers, Chris -- http://blog.rebertia.com From no.email at nospam.invalid Mon Aug 30 03:22:17 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 00:22:17 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> <7xd3t0orah.fsf@ruckus.brouhaha.com> <4c7b279d$0$28650$c3e8da3@news.astraweb.com> Message-ID: <7xmxs436qe.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I'm not saying that ref counting systems can avoid incrementing and > decrementing the ref counts. That would be silly. But I'm saying that it > is an accident of implementation that writing C extensions requires you > to manually manage the counts yourself. That's a side-effect of > permitting coders to write C extensions in pure C, rather than in some > intermediate language which handles the ref counts for you but otherwise > compiles like C. If people cared enough, they could (probably) make the C > compiler handle it for them, just as it currently handles incrementing > and decrementing the return stack. I guess that is how the so-called smart pointers in the Boost C++ template library work. I haven't used them so I don't have personal experience with how convenient or reliable they are, or what kinds of constraints they imposed on programming style. I've always felt a bit suspicious of them though, and I seem to remember Alex Martelli (I hope he shows up here again someday) advising against using them. I don't think a C compiler could really manage automatic decrementing while still being C. Think especially of the common style of exception handling in C using longjmp. From steve-REMOVE-THIS at cybersource.com.au Mon Aug 30 03:39:01 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 07:39:01 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> <7xd3t0orah.fsf@ruckus.brouhaha.com> <4c7b279d$0$28650$c3e8da3@news.astraweb.com> <7xmxs436qe.fsf@ruckus.brouhaha.com> Message-ID: <4c7b6015$0$28660$c3e8da3@news.astraweb.com> On Mon, 30 Aug 2010 00:22:17 -0700, Paul Rubin wrote: > I don't think a C compiler could really manage automatic decrementing > while still being C. Think especially of the common style of exception > handling in C using longjmp. You might very well be right. But that's the problem with C -- it's too low a level language to expect the compiler to protect you much. Or at all. There will always be some use cases for managing memory yourself, or even managing the return stack (as you can do in Forth, for example), and so there will always need to be some sort of high-level assembler like C. But it astounds me that in 2010 people still routinely use C for normal, everyday application programming. -- Steven From greg.ewing at canterbury.ac.nz Mon Aug 30 03:43:41 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 30 Aug 2010 19:43:41 +1200 Subject: Queue cleanup In-Reply-To: <7xhbidndc6.fsf@ruckus.brouhaha.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> <7xhbidndc6.fsf@ruckus.brouhaha.com> Message-ID: <8e15pqFn89U1@mid.individual.net> Paul Rubin wrote: > These days I think the GC pause issue is overrated except for real-time > control applications. Also for games, which are a fairly common application these days. Even a few milliseconds can be too long when you're trying to achieve smooth animation. I'd be disappointed if CPython ditched refcounting and then became unsuitable for real-time games as a result. -- Greg From nikos.the.gr33k at gmail.com Mon Aug 30 04:01:24 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 01:01:24 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> Message-ID: On 30 ???, 06:12, MRAB wrote: > On 30/08/2010 03:55, Nik the Greek wrote: > > > > > > > > > > > On 30 ???, 05:43, MRAB ?wrote: > >> On 30/08/2010 03:07, Nik the Greek wrote: > > >>> On 30 ???, 04:51, MRAB ? ?wrote: > >>>> On 30/08/2010 02:14, ????? wrote: > > >>>>> On 29 ???, 21:44, MRAB ? ? ?wrote: > >>>>>> On 29/08/2010 06:34, ????? wrote: > > >>>>>>> On 28 ???, 23:15, MRAB ? ? ? ?wrote: > >>>>>>>> On 28/08/2010 20:37, ????? wrote: > > >>>>>>>>> On 22 ???, 10:27, ????? ? ? ? ? ?wrote: > >>>>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ? ? ? ?wrote: > > >>>>>>>>>>> ????? wrote: > >>>>>>>>>>>> # initializecookie > >>>>>>>>>>>> cookie=Cookie.SimpleCookie() > >>>>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>>>>>>>>>> mycookie =cookie.get('visitor') > > >>>>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: > >>>>>>>>>>>> ? ? ? ? ?blabla... > >>>>>>>>>>>> ======================== > > >>>>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>>>>>>>>>> within. > >>>>>>>>>>>> So, i have to ask why the if fails? > > >>>>>>>>>>> Maybe it's because != != == > > >>>>>>>>>> Iwant ti if code block to be executed only if the browsercookienames > >>>>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >>>>>>>>>> Is there somethign wrong with the way i wrote it? > > >>>>>>>>> Please do help me with this too becaus eif i dont solve this my > >>>>>>>>> website keeps count my each visit like iam a guest visitor! > > >>>>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > >>>>>>>> repr(host). Then follow the code yourself to see whether the condition > >>>>>>>> is True. > > >>>>>>> print mycookie outputs 'None' > > >>>>>>> Thts weird because i check with the browser and the cookie is there! > > >>>>>> Just because you can see it doesn't mean your code can. > > >>>>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' > > >>>>>>> repr(mycookie.value) (unless mycookie is None) > > >>>>>>> and also > > >>>>>>> print mycookie.value gives an error too. Maybe there is not a value > >>>>>>> method? > > >>>>>> If mycookie is None, then it's not surprising that doesn't have 'value'. > > >>>>>> In summary, mycookie is None, so: > > >>>>>> ? ? ? ? mycookie and mycookie.value != 'nikos' > > >>>>>> is false (actually None, which is treated as false). > > >>>>>> host == '78-236-176.adsl.cyta.gr', so: > > >>>>>> ? ? ? ? re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > >>>>>> finds 'cyta' and the search returns a match. > > >>>>>> false or false == false > > >>>>>> blabla... isn't executed. > > >>>>> Lets forget the 2nd or argument, ill put it off > > >>>>> so we have this now > > >>>>> if ( mycookie and mycookie.value != 'nikos' ): > >>>>> ? ? ? ?#do stuff as long as there ins't a cookie names visitor with a > >>>>> value of nikos in the broswer > > >>>>> What does it mean practically that the mycookie equals to None? > >>>>> That mycookie doesnt exist? > > >>>>> How should i write this if block to mkake sure it checks whether or > >>>>> not the cookie exists? > > >>>> Under what conditions do you want to execute the block? > > >>>> This: > > >>>> ? ? ? ?mycookie and mycookie.value != 'nikos' > > >>>> will be true if: > > >>>> ? ? ? ?there _is_ a cookie, but its value isn't 'nikos' > > >>>> I think that you want is to execute the block if someone else is > >>>> visiting. Correct? > > >>> Yes that exactyl right! > > >>> To make sure a cookie is set i have a script names koukos.py > >>> containing this: > > >>> ============================== > >>> #!/usr/bin/python > >>> # -*- coding: utf-8 -*- > > >>> import cgitb; cgitb.enable() > >>> import cgi, os, Cookie > > >>> # initialize cookie > >>> cookie = Cookie.SimpleCookie() > >>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>> mycookie = cookie.get('visitor') > > >>> htmlBody = [] > > >>> # if visitor cookie does exist > >>> if ( mycookie and mycookie.value == 'nikos' ): > >>> ? ? ? htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? > >>> ????????? ?????????? ??? ???????!') > >>> ? ? ? cookie['visitor'] = 'nikos' > >>> ? ? ? cookie['visitor']['expires'] = -1 ? ? ?#this cookie will expire > >>> now > >>> else: > >>> ? ? ? htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? > >>> ?? ??????! ?? ????? ????? ? ??????? ??????????!!') > >>> ? ? ? cookie['visitor'] = 'nikos' > >>> ? ? ? cookie['visitor']['expires'] = 60*60*24*30*12 > > >>> htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') > > >>> print(cookie) > >>> print('\n'.join(htmlBody)) > >>> ============================= > > >>> Which i seicth on and off according to my desire if i want to be > >>> counted or not! > > >>>> How do you know when it _is_ you? There'll be a cookie which says it's > >>>> you? > > >>>> If so, then you want to execute the block if there isn't any cookie, or > >>>> if there's a cookie but it doesn't say it's you: > > >>>> ? ? ? ?not mycookie or mycookie.value != 'nikos' > > >>> i tried this as you suggested: > > >>> if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| > >>> yandex|13448|spider|crawl)', host ) is None: > > >>> but the counter keeps increasing although the cookie named visitor on > >>> my browser exist and also has the valuie of 'nikos'. > > >>> Why it keeps increasing? Doesn't the if code "sees" that the cookie > >>> with a value of "nikos" is present!?!! > > >> Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you > >> said that host was '78-236-176.adsl.cyta.gr', so it matched. > > >> Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still > >> '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the > >> condition is true. > > > Thats what i want. > > > If host doesnt contain substringsa of the regex to execute if block. > > if it does match i dont want then if block to execute, hence the > > counter too. > > > The reason i had 'cyta' before is because not mycookie or > > mycookie.value != 'nikos' ?doesn't filter me out. > > > The problem is what happens with the > > > not mycookie or mycookie.value != 'nikos' > > > Since cookie 'visitor' does contain the 'nikos' value why the if code > > blck gets executed? > > This part: > > ? ? ?( not mycookie or mycookie.value != 'nikos' ) > > is false but this part: > > ? ? ?re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > is true because host doesn't contain any of those substrings. So what is the problem here? And why mycookie when i print it it says None? Perhpas its doenst get loaded like that? # initialize cookie cookie = SimpleCookie() cookie.load( os.environ.get('HTTP_COOKIE', '') ) mycookie = cookie.get('visitor') From greg.ewing at canterbury.ac.nz Mon Aug 30 04:11:06 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 30 Aug 2010 20:11:06 +1200 Subject: String substitution VS proper mysql escaping In-Reply-To: <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> Message-ID: <8e17d7FsbU1@mid.individual.net> Nik the Greek wrote: > Yes i will i just asked to know if i were to substitute what might be > the problem so to understand why i need the quoting. Because if you use % to build a query string, the result must be syntactically valid SQL. The values that you substitute into the placeholders must end up looking like SQL literals. That means string values need to be in quotes, and probably dates as well, although numbers don't. When you use the execute method's own parameter substitution mechanism, things are different. It's not a textual replacement, and you don't put quotes around the placeholders. There's no particular reason for that, it's just the way it's defined to work. -- Greg From ldo at geek-central.gen.new_zealand Mon Aug 30 04:21:00 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 30 Aug 2010 20:21 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7xr5hg3a7s.fsf@ruckus.brouhaha.com> Message-ID: In message <7xr5hg3a7s.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Actually that code looks suspicious. Suppose in > > AddrObj = PyTuple_GetItem(TheBufferInfo, 0); > LenObj = PyTuple_GetItem(TheBufferInfo, 1); > > the first PyTuple_GetItem succeeds and the second one fails. Admittedly, I did take a shortcut here: array.buffer_info returns a tuple of two items, so I?m not expecting one GetItem to succeed and the other to fail. From greg.ewing at canterbury.ac.nz Mon Aug 30 04:22:21 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 30 Aug 2010 20:22:21 +1200 Subject: Passing variable to SQL statement when using psycopg2 In-Reply-To: References: <4c7b4fd3$0$6887$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <8e182aF4o0U1@mid.individual.net> Chris Rebert wrote: > On Sun, Aug 29, 2010 at 11:29 PM, Julia Jacobson >>Where does the "E" in front of 'xyz' come from? >>It's probably the reason, why my query doesn't work. > > Quite doubtful, considering the example in the psycopg2 docs also has the E: > http://initd.org/psycopg/docs/cursor.html#cursor.mogrify Seems to be a postgres extension to the sql string literal syntax: http://issues.liferay.com/browse/LEP-3182 -- Greg From ldo at geek-central.gen.new_zealand Mon Aug 30 04:23:00 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 30 Aug 2010 20:23 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> Message-ID: In message <7x39twpuxi.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Lawrence D'Oliveiro writes: > >>> the CPython API means endlessly finding and fixing refcount bugs that >>> lead to either crashes/security failures, or memory leaks. >> >> I don?t see why that should be so. It seems a very simple discipline to >> follow: initialize, allocate, free. Here?s an example snippet from my DVD >> Menu Animator : > > In practice it has been a problem. Maybe people need to learn to write code in a more structured fashion. > If it hasn't happened to you yet, you're either burning a bunch of effort > that programmers of more automatic systems can put to more productive > uses ... What makes you say that? Avoiding bugs is not a ?productive use?? >> And how do you run such an application? You have to limit it to a >> predetermined amount of memory to begin with, otherwise it would easily >> gobble up everything you have. > > No that's usually not a problem-- the runtime system (generational gc) > can figure out enough from your allocation pattern to prevent the heap > from getting overlarge. And yet Java apps, for example, are (in)famous for excessive memory usage compared to those written in non-GC-dependent languages. From news1234 at free.fr Mon Aug 30 04:44:39 2010 From: news1234 at free.fr (News123) Date: Mon, 30 Aug 2010 10:44:39 +0200 Subject: how to find out, whether a path is socket or device In-Reply-To: <4c7af6b7$0$11118$c3e8da3@news.astraweb.com> References: <4c7af148$0$28551$426a74cc@news.free.fr> <4c7af6b7$0$11118$c3e8da3@news.astraweb.com> Message-ID: <4c7b6f77$0$5359$426a74cc@news.free.fr> On 08/30/2010 02:09 AM, Steven D'Aprano wrote: > On Mon, 30 Aug 2010 01:46:16 +0200, News123 wrote: > >> Hi, >> >> Under Linux I'd like to find out, whether I got a file, a character >> device or a socket as a parameter. > > See the stat module. > > Thks a lot. I was looking in os.path and forgot about stat (it obviously was too late :-( ) From mahaboobnisha at gmail.com Mon Aug 30 04:53:29 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Mon, 30 Aug 2010 01:53:29 -0700 (PDT) Subject: comp.lang.python Message-ID: <8c31f2b7-c6df-4621-ab87-99cd8da3c718@s17g2000prh.googlegroups.com> www.127760.blogspot.com From thomas at jollybox.de Mon Aug 30 04:59:10 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 30 Aug 2010 10:59:10 +0200 Subject: PyGeo In-Reply-To: <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> Message-ID: <201008301059.11218.thomas@jollybox.de> On Monday 30 August 2010, it occurred to L to exclaim: > I have tried it and as soon as you try any of the examples in the > examples dir it cannot find numpy etc.... > > I have manually move the pygeo dirs and contents to > /usr/lib/python2.6/dis-packages, > > (this is the directory where numpy, numeric and scipy were installed > when using synaptic ) > > made sure that read and write permissions set for ALL FILES and > DIRECTORIES to RW using sudo chmod 777 Wait -- did you just try to use pymaxima, or did you properly (try to) install the dependencies? You need VPython. It's in the ubuntu archives. http://packages.ubuntu.com/lucid/python-visual And then you need to download and install pygeo. http://pygeo.sourceforge.net/download.html It probably uses distutils, so you'd extract the source archive and run sudo python setup.py install If THAT gives you any errors, then please come back here, with the exact error messages. If it works, then PyGeo should be installed. If it still doesn't work, then there's certainly a chance it won't work, but you can still ask here for help, with the exact error messages, so we have something to build upon when trying to figure out what's wrong. - Thomas From sschwarzer at sschwarzer.net Mon Aug 30 05:24:34 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 30 Aug 2010 11:24:34 +0200 Subject: Confused: Newbie Function Calls In-Reply-To: <13e3dc53-f475-46ad-bd3c-ca023b7b6bcb@c38g2000vba.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> <13e3dc53-f475-46ad-bd3c-ca023b7b6bcb@c38g2000vba.googlegroups.com> Message-ID: <4C7B78D2.80308@sschwarzer.net> Hi Pinku, On 2010-08-11 21:35, Pinku Surana wrote: > Even though I used the same name "x" for a local and global variable, > they are actually completely different. When I call "fun(x)" it COPIES > the global value of "x" into the local variable "x" in "fun". [...] The global value isn't copied when calling the function. Instead, the global and the local name both point to the same object when the body of the function starts to run. > def fun(x_local): > y_local = 1 > x_local += y_local > print x_local Only after the assignment "x_local += y_local" x_local points to a new object which is the result of the addition of the previously "shared" object and y_local. Stefan From eckhardt at satorlaser.com Mon Aug 30 06:45:58 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 30 Aug 2010 12:45:58 +0200 Subject: help in code References: <4c73717c$0$28639$c3e8da3@news.astraweb.com> Message-ID: <6oesk7-7lt.ln1@satorlaser.homedns.org> Steven D'Aprano wrote: [reading Bengali] > In Python 2, you probably need to do this: > > f = open("filename") > bytes = f.read() > text = bytes.decode('which-encoding-you-use') > f.close() In Python 2, I'd rather take a look at the "codecs" module (see http://docs.python.org), namely the "codecs.open" function. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From no.email at nospam.invalid Mon Aug 30 06:46:23 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 03:46:23 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7xr5hg3a7s.fsf@ruckus.brouhaha.com> Message-ID: <7xvd6sv0n4.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: >> AddrObj = PyTuple_GetItem(TheBufferInfo, 0); >> LenObj = PyTuple_GetItem(TheBufferInfo, 1); >> >> the first PyTuple_GetItem succeeds and the second one fails. > > Admittedly, I did take a shortcut here: array.buffer_info returns a tuple of > two items, so I?m not expecting one GetItem to succeed and the other to > fail. FromArray is a parameter to the function, with no type check to make sure it's really an array. In fact your code allows for the possibility that it doesn't support the buffer_info operation (if I understand the purpose of the null return check after the PyObject_CallMethod) which means it's prepared for the argument to -not- be an array. In that case maybe it's some other object with a "buffer_info" operation that returns a 1-element tuple. If the function is callable from Python code, then that arg type is completely out of the C code's control. Even if it's only callable from C, you're still depending on not one but two different invariants (that the arg is an array, and that array.buffer_info returns a 2-tuple) that are undocumented and unchecked in the function. I cannot agree with your claim that the approach scales. From thomas at jollybox.de Mon Aug 30 06:50:32 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 30 Aug 2010 12:50:32 +0200 Subject: How to convert (unicode) text to image? In-Reply-To: References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: <201008301250.32415.thomas@jollybox.de> On Monday 30 August 2010, it occurred to rurpy at yahoo.com to exclaim: > Face the facts dude. The Python docs have some major problems. > They were pretty good when Python was a new, cool, project used > by a handful of geeks. They are good relative to the "average" > (whatever that is) open source project -- but that bar is so low > as to be a string lying on the ground. Actually, the Python standard library reference manual is excellent. At least that's my opinion. Granted, it's not necessarily the best in the world. It could probably be better. But that goes for just about every documentation effort there is. What exactly are you comparing the Python docs to, I wonder? Obviously not something like Vala, but that goes without saying. "kj" said that the Perl docs were better. I can't comment on that. I also won't comment on the sorry mess that the language "Perl" is, either. There are a few documentation efforts that I recognize are actually better than the Python docs: Firstly, the MSDN Library docs for the .Net framework. Not that I refer to it much, but it is excellent, and it probably was a pretty darn expensive project too. Secondly, the libc development manual pages on Linux and the BSDs. Provided you know your way around the C library, they are really a top-notch reference. If you were comparing it to the Java standard library documentation, please provide a link. I've tried and failed to find any coherent documentation of the standard classpath that anything like approaches the quality of the Python documentation. > > Your overly defensive and oppressive response does not help. > All it (combined with similar knee-jerk responses) does is > act to suppress any criticism leaving the impression that > the Python docs are really great, an assertion commonly made > here and often left unchallenged. Responses like yours > create a force that works to maintain the status quo. From no.email at nospam.invalid Mon Aug 30 07:00:33 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 04:00:33 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> Message-ID: <7xr5hguzzi.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: >> If it hasn't happened to you yet, you're either burning a bunch of effort >> that programmers of more automatic systems can put to more productive >> uses ... > > What makes you say that? Avoiding bugs is not a ?productive use?? Avoiding any particular bug through constant and pervasive vigilance is far less productive than using a system where causing that particular type of bug is impossible to begin with. IMO the code you posted has latent bugs as discussed in the other post. It might work at the moment you checked it in but it is brittle. I wouldn't have signed off on it in a code review. > And yet Java apps, for example, are (in)famous for excessive memory > usage compared to those written in non-GC-dependent languages. I think that may mostly be an issue with the bloated nature of most Java apps. Certainly Lisp systems have run in production for decades on machines with much less memory than we would consider acceptable these days for any substantial Python app. It's probably true that gc copying-style gc is more memory hungry than Python's refcount system. Mark-sweep gc should have comparable memory consumption and better speed than refcounting, though less speed than copying. JHC (experimental Haskell compiler) recently started using a mixture of gc and region inference. It will be interesting to see how that works out. From no.email at nospam.invalid Mon Aug 30 07:10:06 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 04:10:06 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> <7xhbidndc6.fsf@ruckus.brouhaha.com> <8e15pqFn89U1@mid.individual.net> Message-ID: <7xmxs4uzjl.fsf@ruckus.brouhaha.com> Gregory Ewing writes: >> These days I think the GC pause issue is overrated except for real-time >> control applications. > > Also for games, which are a fairly common application > these days. Even a few milliseconds can be too long when > you're trying to achieve smooth animation. The usual hack with games is you do a major gc when the user advances between game levels. You can do minor gc's during the screen refresh interval. > I'd be disappointed if CPython ditched refcounting and > then became unsuitable for real-time games as a result. Refcounting is susceptable to the same pauses for reasons already discussed. From no.email at nospam.invalid Mon Aug 30 07:14:56 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 04:14:56 -0700 Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: <7xiq2suzbj.fsf@ruckus.brouhaha.com> Thomas Jollans writes: > Actually, the Python standard library reference manual is excellent. At least > that's my opinion.... > What exactly are you comparing the Python docs to, I wonder? Obviously not > something like Vala, but that goes without saying. I didn't know Vala had especially good docs. I think GCC's docs are pretty good. Python's are mostly ok but have significant gaps. For example, tkinter has been part of the stdlib for at least a decade but is totally undocumented in the Python library manual. From aahz at pythoncraft.com Mon Aug 30 08:40:03 2010 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2010 05:40:03 -0700 Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> <4c6c9b3f$0$28637$c3e8da3@news.astraweb.com> Message-ID: In article , Tim Chase wrote: >On 08/18/10 21:47, Steven D'Aprano wrote: >> >> Frankly, I think the OP doesn't really know what he wants, other than >> premature optimization. It's amazing how popular that is :) > >You see, the trick to prematurely optimizing is to have a good >algorithm for prematurely optimizing...the real question them >becomes "How can I optimize my premature-optimization algorithms >to O(1) instead of O(newsgroup)?" > >:-) > >-tkc > >PS: I'm not positive, but O(newsgroup) may asymptotically >approach O(log n) if the question is well formed, but O(2^n) if >flaming, indentation/line-length preferences, the meaning of OOP, >SQL-parameter escaping, McNugget combinations, or suggestions that >Python is "just a scripting language" are involved... +1 QOTW -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From thomas at jollybox.de Mon Aug 30 08:42:28 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 30 Aug 2010 14:42:28 +0200 Subject: How to convert (unicode) text to image? In-Reply-To: <7xiq2suzbj.fsf@ruckus.brouhaha.com> References: <7xiq2suzbj.fsf@ruckus.brouhaha.com> Message-ID: <201008301442.29025.thomas@jollybox.de> On Monday 30 August 2010, it occurred to Paul Rubin to exclaim: > Thomas Jollans writes: > > Actually, the Python standard library reference manual is excellent. At > > least that's my opinion.... > > What exactly are you comparing the Python docs to, I wonder? Obviously > > not something like Vala, but that goes without saying. > > I didn't know Vala had especially good docs. Sorry for being imprecise. Let me clarify: they're practically non existent. The language docs are okay if you know C#, but there are no API docs that are more than auto-generated lists of classes and methods. > I think GCC's docs are > pretty good. Python's are mostly ok but have significant gaps. For > example, tkinter has been part of the stdlib for at least a decade but > is totally undocumented in the Python library manual. From aahz at pythoncraft.com Mon Aug 30 08:47:05 2010 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2010 05:47:05 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> <7xd3t0orah.fsf@ruckus.brouhaha.com> <4c7b279d$0$28650$c3e8da3@news.astraweb.com> Message-ID: In article <4c7b279d$0$28650$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Sun, 29 Aug 2010 17:52:38 -0700, Paul Rubin wrote: >>Attribution lost: >>> >>> That's a problem with the CPython API, not reference counting. The >>> problem is that the CPython API is written at too low a level, beneath >>> that at which the garbage collector exists, so naturally you have to >>> manually manage memory. >> >> Care to give an example of a reference counted system that's written any >> other way? > >The complexity of the ref counter is invisible when writing pure Python >code, and I believe it is also invisible when writing code in Cython. The >difficulty of dealing with ref counts is abstracted away. That's not completely true. You know perfectly well that it's almost trivially easy to leak memory with refcounting, and there are certain ways in which Python leaks memory invisibly if you don't know how it works. One recent example at work was when someone was arguing with me about whether we were leaking file handles and I had to prove that you could leak file handles if you didn't clean up exceptions -- but that cleaning up the exception *did* close the file handles. (This code was originally written in Python 2.4, and partly because of this we are making more of a push to use "with"....) If you're restricting your claim just to the actual management of the reference counter, you're correct, but it's especially not clear that your second sentence is so restricted. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From michael.a.powe at gmail.com Mon Aug 30 08:52:02 2010 From: michael.a.powe at gmail.com (naugiedoggie) Date: Mon, 30 Aug 2010 05:52:02 -0700 (PDT) Subject: Using a function for regular expression substitution References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: On Aug 29, 1:14?pm, MRAB wrote: > On 29/08/2010 15:22, naugiedoggie wrote: > > I'm having a problem with using a function as the replacement in > > re.sub(). > > Here is the function: > > def normalize(s) : > > ? ? ?return > > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) > > This normalises the provider and returns only that, and none of the > remainder of the string. > > I think you might want this: > > def normalize(s): > ? ? ?return s[ : s.start('provider')] + > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + > s[s.start('provider') : ] > > It returns the part before the provider, followed by the normalised > provider, and then the part after the provider. Hello, Thanks for the reply. There must be something basic about the re.sub() function that I'm missing. The documentation shows this example: >>> def dashrepl(matchobj): ... if matchobj.group(0) == '-': return ' ' ... else: return '-' >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') 'pro--gram files' >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) 'Baked Beans & Spam' According to the doc, the modifying function takes one parameter, the MatchObject. The re.sub function takes only a compiled regex object or a pattern, generates a MatchObject from that object/pattern and passes the MatchObject to the given function. Notice that in the examples, the re.sub() returns the entire line, with the changes made. But the function itself returns only the change. What is happening for me is that, if I have a line that contains &Search_Provider=chen&p=value, the processed line ends up with &Chen&p=value. Now, I did follow up with your suggestion. `s' is actually a MatchObject (bad param naming on my part, I started out passing a string into the function and then changed it to a MatchObject, but didn't change the param name), so I made the following change: return line[s.pos : s.start('provider')] + \ urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + \ line[s.end('provider') : ] In order to make this work (finally), I had to make the processing function look like this: def processLine(l) : global line line = l provider = getProvider(line) if provider == "No Provider" : return line scenario = getScenario(line) if filter (lambda a: a != None, [getOrg(s,scenario) for s in orgs]) == [] : line = re.sub(provider_pattern,normalize,line) else : line.replace(provider_parameter, org_parameter) return line And then the call: lines = fileReader.readlines() [ fileWriter.write(l) for l in [processLine(l) for l in lines]] Without this complicated gobbledigook, I could not get the correct result. I hate global vars and I completely do not understand why I have to go through this twisting and turning to get the desired result. [ ... ] > These can be replaced by: > > ? ? ? ? if 'Search_Type' in line and 'Search_Provider' in line: > > > ? ? ? ? ? ?re.sub(provider_matcher,normalize,line) > > re.sub is returning the result, which you're throwing away! > > ? ? ? ? ? ? ? ? line = re.sub(provider_matcher,normalize,line) I can't count the number of times I have forgotten the meaning of 'returns a string' when reading docs about doing substitutions. In this case, I had put the `line = ' in and taken it out. And I should know better, from years of programming in Java, where strings are immutable and you _always_ get a new, returned string. Should be second nature. Thanks for the help, much appreciated. mp From aahz at pythoncraft.com Mon Aug 30 09:03:02 2010 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2010 06:03:02 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: In article , Raymond Hettinger wrote: >On Aug 29, 12:12=A0pm, John Nagle wrote: >> >> Is the "in" test faster for a dict or a set? Is "frozenset" faster >> than "set"? Use case is for things like applying "in" on a list of >> 500 or so words while checking a large body of text. > >There is no significant difference. All three are implemented using >substantially the same code. That reminds me: one co-worker (who really should have known better ;-) had the impression that sets were O(N) rather than O(1). Although writing that off as a brain-fart seems appropriate, it's also the case that the docs don't really make that clear, it's implied from requiring elements to be hashable. Do you agree that there should be a comment? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From cutebhavanaa at gmail.com Mon Aug 30 09:31:04 2010 From: cutebhavanaa at gmail.com (sexy girl) Date: Mon, 30 Aug 2010 06:31:04 -0700 (PDT) Subject: ***SEX IN COLLEGE HOT AND SEXY VIDEOS*** Message-ID: http://cute-actress-images.blogspot.com/ http://cute-sexy-images.blogspot.com/ http://actress.0jet.com http://factson-globalwarming.blogspot.com/ http://mysteries-that-threats.blogspot.com/ http://healthtips.06fr.com http://actress.0jet.com http://dailyscience.youblog.net http://jobs4all.menblogs.net http://healthtips.06fr.com http://dailyscience.youblog.net http://jobs4all.menblogs.net http://schoolsuniversities.web-day.net http://cute-actress-images.blogspot.com/ http://science-vs-technology.blogspot.com/ http://my-jobs-4-u.blogspot.com/ http://cute-sexy-images.blogspot.com/ From michael.a.powe at gmail.com Mon Aug 30 09:31:33 2010 From: michael.a.powe at gmail.com (naugiedoggie) Date: Mon, 30 Aug 2010 06:31:33 -0700 (PDT) Subject: Using a function for regular expression substitution References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: <291dd1c3-a63a-44d3-948d-bd88b27f92b4@j8g2000yqd.googlegroups.com> On Aug 30, 8:52?am, naugiedoggie wrote: > On Aug 29, 1:14?pm, MRAB wrote: > > > > > > > On 29/08/2010 15:22, naugiedoggie wrote: > > > I'm having a problem with using a function as the replacement in > > > re.sub(). > > > Here is the function: > > > def normalize(s) : > > > ? ? ?return > > > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) > > > This normalises the provider and returns only that, and none of the > > remainder of the string. > > > I think you might want this: > > > def normalize(s): > > ? ? ?return s[ : s.start('provider')] + > > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + > > s[s.start('provider') : ] > > > It returns the part before the provider, followed by the normalised > > provider, and then the part after the provider. > > Hello, > > Thanks for the reply. > > There must be something basic about the re.sub() function that I'm > missing. ?The documentation shows this example: > > >>> def dashrepl(matchobj): > > ... ? ? if matchobj.group(0) == '-': return ' ' > ... ? ? else: return '-'>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') > 'pro--gram files' > >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) > > 'Baked Beans & Spam' > > > According to the doc, the modifying function takes one parameter, the > MatchObject. ?The re.sub function takes only a compiled regex object > or a pattern, generates a MatchObject from that object/pattern and > passes the MatchObject to the given function. Notice that in the > examples, the re.sub() returns the entire line, with the changes made. > But the function itself returns only the change. ?What is happening > for me is that, if I have a line that contains > &Search_Provider=chen&p=value, the processed line ends up with > &Chen&p=value. > > Now, I did follow up with your suggestion. ?`s' is actually a > MatchObject (bad param naming on my part, I started out passing a > string into the function and then changed it to a MatchObject, but > didn't change the param name), so I made the following change: > > > return line[s.pos : s.start('provider')] + \ > > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + \ > ? ? ? ? line[s.end('provider') : ] > > > In order to make this work (finally), I had to make the processing > function look like this: > > > def processLine(l) : > ? ? ? ? global line > ? ? ? ? line = l > ? ? ? ? provider = getProvider(line) > ? ? ? ? if provider == "No Provider" : return line > ? ? ? ? scenario = getScenario(line) > ? ? ? ? if filter (lambda a: a != None, [getOrg(s,scenario) for s in > orgs]) == [] : > ? ? ? ? ? ? line = re.sub(provider_pattern,normalize,line) > ? ? ? ? else : > ? ? ? ? ? ? line.replace(provider_parameter, org_parameter) > ? ? ? ? return line > > > And then the call: > > > lines = fileReader.readlines() > [ fileWriter.write(l) for l in [processLine(l) for l in lines]] > > > Without this complicated gobbledigook, I could not get the correct > result. ?I hate global vars and I completely do not understand why I > have to go through this twisting and turning to get the desired > result. > > [ ... ] > > > These can be replaced by: > > > ? ? ? ? if 'Search_Type' in line and 'Search_Provider' in line: > > > > ? ? ? ? ? ?re.sub(provider_matcher,normalize,line) > > > re.sub is returning the result, which you're throwing away! > > > ? ? ? ? ? ? ? ? line = re.sub(provider_matcher,normalize,line) > > I can't count the number of times I have forgotten the meaning of > 'returns a string' when reading docs about doing substitutions. In > this case, I had put the `line = ' in and taken it out. ?And I should > know better, from years of programming in Java, where strings are > immutable and you _always_ get a new, returned string. ?Should be > second nature. > > Thanks for the help, much appreciated. > > mp Hello, Well, that turned out to be still wrong. I did start getting the proper param=value back from my `normalize' function, but I got "extra" data as well. This works: def normalize(s) : return s.group('search') +'='+urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) Essentially, the pattern contained two groups, one identifying the parameter name and one the value. By concat'ing the two back together, I was able to achieve the desired result. I suppose the lesson is, the function replaces the entire match rather than just the specified text captured. Thanks. mp From no.email at nospam.invalid Mon Aug 30 09:39:50 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 06:39:50 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: <7xiq2sqkwp.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > That reminds me: one co-worker (who really should have known better ;-) > had the impression that sets were O(N) rather than O(1). Although > writing that off as a brain-fart seems appropriate, it's also the case > that the docs don't really make that clear, it's implied from requiring > elements to be hashable. Do you agree that there should be a comment? It's O(1) with reasonable input distributions but can be O(N) for adverse distributions. The docs should say something like that, and include this link: http://www.cs.rice.edu/~scrosby/hash/CrosbyWallach_UsenixSec2003/index.html From nikos.the.gr33k at gmail.com Mon Aug 30 09:48:33 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 06:48:33 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> Message-ID: <6676c33f-0012-4051-bc75-b35af37df367@z28g2000yqh.googlegroups.com> On 30 ???, 11:01, Nik the Greek wrote: > On 30 ???, 06:12, MRAB wrote: > > > > > > > > > > > On 30/08/2010 03:55, Nik the Greek wrote: > > > > On 30 ???, 05:43, MRAB ?wrote: > > >> On 30/08/2010 03:07, Nik the Greek wrote: > > > >>> On 30 ???, 04:51, MRAB ? ?wrote: > > >>>> On 30/08/2010 02:14, ????? wrote: > > > >>>>> On 29 ???, 21:44, MRAB ? ? ?wrote: > > >>>>>> On 29/08/2010 06:34, ????? wrote: > > > >>>>>>> On 28 ???, 23:15, MRAB ? ? ? ?wrote: > > >>>>>>>> On 28/08/2010 20:37, ????? wrote: > > > >>>>>>>>> On 22 ???, 10:27, ????? ? ? ? ? ?wrote: > > >>>>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ? ? ? ?wrote: > > > >>>>>>>>>>> ????? wrote: > > >>>>>>>>>>>> # initializecookie > > >>>>>>>>>>>> cookie=Cookie.SimpleCookie() > > >>>>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > >>>>>>>>>>>> mycookie =cookie.get('visitor') > > > >>>>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > > >>>>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: > > >>>>>>>>>>>> ? ? ? ? ?blabla... > > >>>>>>>>>>>> ======================== > > > >>>>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > > >>>>>>>>>>>> within. > > >>>>>>>>>>>> So, i have to ask why the if fails? > > > >>>>>>>>>>> Maybe it's because != != == > > > >>>>>>>>>> Iwant ti if code block to be executed only if the browsercookienames > > >>>>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > > >>>>>>>>>> Is there somethign wrong with the way i wrote it? > > > >>>>>>>>> Please do help me with this too becaus eif i dont solve this my > > >>>>>>>>> website keeps count my each visit like iam a guest visitor! > > > >>>>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > > >>>>>>>> repr(host). Then follow the code yourself to see whether the condition > > >>>>>>>> is True. > > > >>>>>>> print mycookie outputs 'None' > > > >>>>>>> Thts weird because i check with the browser and the cookie is there! > > > >>>>>> Just because you can see it doesn't mean your code can. > > > >>>>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' > > > >>>>>>> repr(mycookie.value) (unless mycookie is None) > > > >>>>>>> and also > > > >>>>>>> print mycookie.value gives an error too. Maybe there is not a value > > >>>>>>> method? > > > >>>>>> If mycookie is None, then it's not surprising that doesn't have 'value'. > > > >>>>>> In summary, mycookie is None, so: > > > >>>>>> ? ? ? ? mycookie and mycookie.value != 'nikos' > > > >>>>>> is false (actually None, which is treated as false). > > > >>>>>> host == '78-236-176.adsl.cyta.gr', so: > > > >>>>>> ? ? ? ? re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > > >>>>>> finds 'cyta' and the search returns a match. > > > >>>>>> false or false == false > > > >>>>>> blabla... isn't executed. > > > >>>>> Lets forget the 2nd or argument, ill put it off > > > >>>>> so we have this now > > > >>>>> if ( mycookie and mycookie.value != 'nikos' ): > > >>>>> ? ? ? ?#do stuff as long as there ins't a cookie names visitor with a > > >>>>> value of nikos in the broswer > > > >>>>> What does it mean practically that the mycookie equals to None? > > >>>>> That mycookie doesnt exist? > > > >>>>> How should i write this if block to mkake sure it checks whether or > > >>>>> not the cookie exists? > > > >>>> Under what conditions do you want to execute the block? > > > >>>> This: > > > >>>> ? ? ? ?mycookie and mycookie.value != 'nikos' > > > >>>> will be true if: > > > >>>> ? ? ? ?there _is_ a cookie, but its value isn't 'nikos' > > > >>>> I think that you want is to execute the block if someone else is > > >>>> visiting. Correct? > > > >>> Yes that exactyl right! > > > >>> To make sure a cookie is set i have a script names koukos.py > > >>> containing this: > > > >>> ============================== > > >>> #!/usr/bin/python > > >>> # -*- coding: utf-8 -*- > > > >>> import cgitb; cgitb.enable() > > >>> import cgi, os, Cookie > > > >>> # initialize cookie > > >>> cookie = Cookie.SimpleCookie() > > >>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > >>> mycookie = cookie.get('visitor') > > > >>> htmlBody = [] > > > >>> # if visitor cookie does exist > > >>> if ( mycookie and mycookie.value == 'nikos' ): > > >>> ? ? ? htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? > > >>> ????????? ?????????? ??? ???????!') > > >>> ? ? ? cookie['visitor'] = 'nikos' > > >>> ? ? ? cookie['visitor']['expires'] = -1 ? ? ?#this cookie will expire > > >>> now > > >>> else: > > >>> ? ? ? htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? > > >>> ?? ??????! ?? ????? ????? ? ??????? ??????????!!') > > >>> ? ? ? cookie['visitor'] = 'nikos' > > >>> ? ? ? cookie['visitor']['expires'] = 60*60*24*30*12 > > > >>> htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') > > > >>> print(cookie) > > >>> print('\n'.join(htmlBody)) > > >>> ============================= > > > >>> Which i seicth on and off according to my desire if i want to be > > >>> counted or not! > > > >>>> How do you know when it _is_ you? There'll be a cookie which says it's > > >>>> you? > > > >>>> If so, then you want to execute the block if there isn't any cookie, or > > >>>> if there's a cookie but it doesn't say it's you: > > > >>>> ? ? ? ?not mycookie or mycookie.value != 'nikos' > > > >>> i tried this as you suggested: > > > >>> if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| > > >>> yandex|13448|spider|crawl)', host ) is None: > > > >>> but the counter keeps increasing although the cookie named visitor on > > >>> my browser exist and also has the valuie of 'nikos'. > > > >>> Why it keeps increasing? Doesn't the if code "sees" that the cookie > > >>> with a value of "nikos" is present!?!! > > > >> Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you > > >> said that host was '78-236-176.adsl.cyta.gr', so it matched. > > > >> Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still > > >> '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the > > >> condition is true. > > > > Thats what i want. > > > > If host doesnt contain substringsa of the regex to execute if block. > > > if it does match i dont want then if block to execute, hence the > > > counter too. > > > > The reason i had 'cyta' before is because not mycookie or > > > mycookie.value != 'nikos' ?doesn't filter me out. > > > > The problem is what happens with the > > > > not mycookie or mycookie.value != 'nikos' > > > > Since cookie 'visitor' does contain the 'nikos' value why the if code > > > blck gets executed? > > > This part: > > > ? ? ?( not mycookie or mycookie.value != 'nikos' ) > > > is false but this part: > > > ? ? ?re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > > is true because host doesn't contain any of those substrings. > > So what is the problem here? > > And why mycookie when i print it it says None? > > Perhpas its doenst get loaded like that? > > # initialize cookie > cookie = SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > mycookie = cookie.get('visitor') Please someone else has an idea on how this to work? From python at bdurham.com Mon Aug 30 09:54:04 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 30 Aug 2010 09:54:04 -0400 Subject: shlex, unicode, and subprocess.Popen on Windows Message-ID: <1283176444.5865.1392429397@webmail.messagingengine.com> Python 2.6/Windows: shlex.split() does not support unicode strings. Is this simply a limitation of the current shlex implementation or is this an intentional design decision that reflects the behavior of how the Windows shell supports unicode values? Specifically, it doesn't appear that subprocess.Popen() has any restrictions on unicode args, but perhaps I'm missing some edge cases where this may be true? If this is simply a limitation of the current shlex implementation, does anyone see any risks to encoding a command string using 'xmlreplace' ( command.encode( 'utf8', 'xmlreplace' ) ) in order to hide unicode chars, splitting the now ASCII string using shlex.split, and then walking the list of strings returned by shlex.split, decoding them back to Unicode ( .decode( 'utf8' ) ) before passing this list to subprocess.Popen() for execution? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Mon Aug 30 10:02:33 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 31 Aug 2010 00:02:33 +1000 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: <878w3ogpvq.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > That reminds me: one co-worker (who really should have known better ;-) > had the impression that sets were O(N) rather than O(1). For settling exactly this kind of confusion, Python's standard library comes with a module, the ?timeit? module. Your co-worker should have known better: don't guess about timing performance, measure it. Or am I missing something here? -- \ ?If you don't know what your program is supposed to do, you'd | `\ better not start writing it.? ?Edsger W. Dijkstra | _o__) | Ben Finney From clp2 at rebertia.com Mon Aug 30 10:04:24 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 30 Aug 2010 07:04:24 -0700 Subject: shlex, unicode, and subprocess.Popen on Windows In-Reply-To: <1283176444.5865.1392429397@webmail.messagingengine.com> References: <1283176444.5865.1392429397@webmail.messagingengine.com> Message-ID: On Mon, Aug 30, 2010 at 6:54 AM, wrote: > Python 2.6/Windows: shlex.split() does not support unicode strings. Is this > simply a limitation of the current shlex implementation or is this an > intentional design decision that reflects the behavior of how the Windows > shell supports unicode values? It's a bug: http://bugs.python.org/issue1170 Also, shlex is cross-platform; the limitation has nothing to do with Windows. As a matter of fact, the docs mention how shlex's functionality is based off of Unix and POSIX. Cheers, Chris -- Kudos for avoiding shell=True http://blog.rebertia.com From ethan at stoneleaf.us Mon Aug 30 10:10:49 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 30 Aug 2010 07:10:49 -0700 Subject: meta-class troubles Message-ID: <4C7BBBE9.8090003@stoneleaf.us> Good Day! I am stuck... hopefully a few fresh pairs of eyes will spot what I am missing. I have a metaclass, Traits, and two different testing files, test_traits.py and tests.py. test_traits works fine, tests generates the following error: C:\Python31\Lib\site-packages\traits\tests>\python31\python tests.py Traceback (most recent call last): File "tests.py", line 4, in class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): TypeError: type() takes 1 or 3 arguments Working code from test_traits.py: class DerivedClass(metaclass=Traits, traits=(TBundle1, TBundle2)): def repeat(yo, text, count): print('whatever...') def whatsit(yo, arg1): print("calling baseclass's whatsit...") print(super().whatsit(arg1)) Failing code from tests.py: class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): def useless(yo): print("this class won't compile") Any clues or pointers *greatly* appreciated! ~Ethan~ -- Traits is homegrown, the idea based on Michele Simionato's Simple Traits experiment. It was intrigueing, and I wanted to see if I could implement something similar in Python 3. Any ideas now on what to do with it will also be greatly appreciated! :) From contact at xavierho.com Mon Aug 30 10:16:55 2010 From: contact at xavierho.com (Xavier Ho) Date: Tue, 31 Aug 2010 00:16:55 +1000 Subject: meta-class troubles In-Reply-To: <4C7BBBE9.8090003@stoneleaf.us> References: <4C7BBBE9.8090003@stoneleaf.us> Message-ID: Ethan, are you trying to write the constructor in the class statement? Cheers, Xav On 31 August 2010 00:10, Ethan Furman wrote: > Good Day! > > I am stuck... hopefully a few fresh pairs of eyes will spot what I am > missing. > > I have a metaclass, Traits, and two different testing files, test_traits.py > and tests.py. test_traits works fine, tests generates the following error: > > C:\Python31\Lib\site-packages\traits\tests>\python31\python tests.py > Traceback (most recent call last): > File "tests.py", line 4, in > class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): > TypeError: type() takes 1 or 3 arguments > > > Working code from test_traits.py: > class DerivedClass(metaclass=Traits, traits=(TBundle1, TBundle2)): > def repeat(yo, text, count): > print('whatever...') > def whatsit(yo, arg1): > print("calling baseclass's whatsit...") > print(super().whatsit(arg1)) > > Failing code from tests.py: > class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): > def useless(yo): > print("this class won't compile") > > > Any clues or pointers *greatly* appreciated! > > ~Ethan~ > -- > Traits is homegrown, the idea based on Michele Simionato's Simple Traits > experiment. It was intrigueing, and I wanted to see if I could implement > something similar in Python 3. Any ideas now on what to do with it will > also be greatly appreciated! :) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Aug 30 10:17:24 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 30 Aug 2010 07:17:24 -0700 Subject: meta-class troubles In-Reply-To: <4C7BBBE9.8090003@stoneleaf.us> References: <4C7BBBE9.8090003@stoneleaf.us> Message-ID: On Mon, Aug 30, 2010 at 7:10 AM, Ethan Furman wrote: > Good Day! > > I am stuck... hopefully a few fresh pairs of eyes will spot what I am > missing. > > I have a metaclass, Traits, and two different testing files, test_traits.py > and tests.py. ?test_traits works fine, tests generates the following error: > > C:\Python31\Lib\site-packages\traits\tests>\python31\python tests.py > Traceback (most recent call last): > ?File "tests.py", line 4, in > ? ?class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): > TypeError: type() takes 1 or 3 arguments > > > Working code from test_traits.py: > class DerivedClass(metaclass=Traits, traits=(TBundle1, TBundle2)): > ? ?def repeat(yo, text, count): > ? ? ? ?print('whatever...') > ? ?def whatsit(yo, arg1): > ? ? ? ?print("calling baseclass's whatsit...") > ? ? ? ?print(super().whatsit(arg1)) > > Failing code from tests.py: > class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): > ? ?def useless(yo): > ? ? ? ?print("this class won't compile") Shouldn't meta= instead be metaclass= ? Cheers, Chris -- http://blog.rebertia.com From contact at xavierho.com Mon Aug 30 10:20:01 2010 From: contact at xavierho.com (Xavier Ho) Date: Tue, 31 Aug 2010 00:20:01 +1000 Subject: meta-class troubles In-Reply-To: References: <4C7BBBE9.8090003@stoneleaf.us> Message-ID: Actually, scrape what I said. I think you need to have metaclass in the class statement, not just meta. -Xav On 31 August 2010 00:16, Xavier Ho wrote: > Ethan, are you trying to write the constructor in the class statement? > > Cheers, > Xav > > > On 31 August 2010 00:10, Ethan Furman wrote: > >> Good Day! >> >> I am stuck... hopefully a few fresh pairs of eyes will spot what I am >> missing. >> >> I have a metaclass, Traits, and two different testing files, >> test_traits.py and tests.py. test_traits works fine, tests generates the >> following error: >> >> C:\Python31\Lib\site-packages\traits\tests>\python31\python tests.py >> Traceback (most recent call last): >> File "tests.py", line 4, in >> class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): >> TypeError: type() takes 1 or 3 arguments >> >> >> Working code from test_traits.py: >> class DerivedClass(metaclass=Traits, traits=(TBundle1, TBundle2)): >> def repeat(yo, text, count): >> print('whatever...') >> def whatsit(yo, arg1): >> print("calling baseclass's whatsit...") >> print(super().whatsit(arg1)) >> >> Failing code from tests.py: >> class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): >> def useless(yo): >> print("this class won't compile") >> >> >> Any clues or pointers *greatly* appreciated! >> >> ~Ethan~ >> -- >> Traits is homegrown, the idea based on Michele Simionato's Simple Traits >> experiment. It was intrigueing, and I wanted to see if I could implement >> something similar in Python 3. Any ideas now on what to do with it will >> also be greatly appreciated! :) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Mon Aug 30 10:24:26 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 30 Aug 2010 10:24:26 -0400 Subject: shlex, unicode, and subprocess.Popen on Windows In-Reply-To: <1283178224.12933.1392434421@webmail.messagingengine.com> References: <1283176444.5865.1392429397@webmail.messagingengine.com> <1283178224.12933.1392434421@webmail.messagingengine.com> Message-ID: <1283178266.13167.1392435533@webmail.messagingengine.com> Hi Chris, > It's a bug: http://bugs.python.org/issue1170 Thanks for pointing out the shlex bug. My concern was that shlex had Windows specific Unicode limitations because of the way the Windows shell so poorly supports unicode output. > Kudos for avoiding shell=True My understanding is that the only time one needs to use shell=True is when they are 'executing' a non-executable file whose executable must be discovered via file association rules? Does that sound accurate? Malcolm From jal at bethere.co.uk Mon Aug 30 10:29:59 2010 From: jal at bethere.co.uk (jal) Date: Mon, 30 Aug 2010 07:29:59 -0700 (PDT) Subject: python 2.6.6 installation problems on osx Message-ID: <15352d95-125c-41bb-8eca-7c5bc6b4bd94@k10g2000yqa.googlegroups.com> Hi All, I'm attempting a framework install of python 2.6.6 from source, on an intel mac running osx 10.6.4. At the end of the install the following errors occur. install: mkdir /usr/local/bin: Permission denied make[1]: *** [altinstallunixtools] Error 71 make: *** [frameworkaltinstallunixtools] Error 2 Does anyone one know of a fix? Kind regards, Jal From ritchy_gato at hotmail.com Mon Aug 30 10:51:34 2010 From: ritchy_gato at hotmail.com (Ritchy lelis) Date: Mon, 30 Aug 2010 07:51:34 -0700 (PDT) Subject: How to implement a pipeline...??? Please help References: <5242b005-31b6-4a9c-afd9-6fbb82e28db7@l14g2000yql.googlegroups.com> <08ce00ca-f58e-4ff4-a95e-54f7a4d5071f@w30g2000yqw.googlegroups.com> Message-ID: <4f39596e-2fa0-492f-9695-1397528e95a3@a36g2000yqc.googlegroups.com> On 26 Ago, 08:52, Dennis Lee Bieber wrote: > On Tue, 24 Aug 2010 22:21:34 -0700 (PDT), Ritchy lelis > declaimed the following in > gmane.comp.python.general: > > > hi friend Dennis Lee Bieber > > > I have watching your code sujestion and now i can understand more of > > what you have there.. > > ? ? ? ? Take warning -- I think I had a major flaw in the summation part of > the logic... It's probably easier just to use a list of lists (one list > per stage, and each list as long as the number of stages) and sum the > diagonal > > ? ? ? ? result = sum([list_of_lists[i][i] for i in range(number_of_stages)]) > > > i would like to show you them but i need to now if you still > > interested in the challenge it self and also in helping me with your > > extraordinary tips. > > > Can i count on your help? I hope so gratefully. > > ? ? ? ? My apologies... much more help and I'll have done the work for you > (though I'm still perplexed at simulating a hardware A/D converter when > the input is already a floating point digital, and the output is integer > digital) > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ My apologies... much more help and I'll have done the work for you Until now you were the only person who helped me so far... your help has served a lot. Already learned a lot with you so please do not stop helping me. To show you that you have not done it alone, i'll show you that i have made some arrangements. About the pipeline Class still have some errors and i'm working on it. Hope this link help. http://www.eetimes.com/design/automotive-design/4010021/SIGNAL-CHAIN-BASICS-Part-8--Flash-and-Pipeline-Converter-Operation-Explored though I'm still perplexed at simulating a hardware A/D converter when > the input is already a floating point digital, and the output is integer > digital I believe that de residuals that we're getting at the output, already are the wave forms that we should get if we had a Oscilloscope and analyzing the behavior of a A/D hardware and the digital parts is to quantify the analog input ie first we analyze and translate the analog input to a known residue and then quantifies to the digital output. I already initialized the "non linear" issues with the Class Calculate, and after this we will start to see how A/D converter really works. I would love you to help me at this one to Class Calculate: 1 - http://www.national.com/appinfo/adc/files/ABCs_of_ADCs.pdf 2 - http://www.atmel.com/dyn/resources/prod_documents/doc2559.pdf And now my new arrangements: # -*- coding: cp1252 -*- #######################################ADC##################################### ##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Incluir as Bibliotecas>>>>>>>>>>>>>>>>>>>>>>>> import matplotlib.pyplot as plt import numpy as np from numpy.random import * from numpy.fft import * from pylab import * ##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>CLASS ADC>>>>>>>>>>>>>>>>>>>>>>>>>>>> class ADC(object): def __init__(self, Inc, V_in, V_ref, Cs, Cf): ##Guarda o n?mero de est?gio e a tens?o de refer?ncia ## Stores the number of stage and reference voltage self.Inc = Inc self.V_ref = V_ref self.Cs = Cs self.Cf = Cs ##calcula os limiares da tens?o do comparador ##calculates the threshold voltage of the comparator self.V_H = self.V_ref * 0.25 self.V_L = -self.V_H self.V_in = V_in #define dois array de "Inc" elementos todos a uns e zeros respectivamente ##sets two array "Inc" elements all the ones and zeros respectively self.ones = np.ones(Inc, dtype=np.float) self.zeros = np.zeros(Inc, dtype=np.float) ##fun??o flash 1.5 bit ##1.5 bit flash function def flash1b5(self): # calcula as posi??es onde a tens?o de entrada excede o limiar alto ## calculates the positions where the input voltage exceeds the high threshold highBits = np.where(self.V_in > self.V_H, self.ones, self.zeros) # calcula as posi??es onde a tens?o de entrada ? menor que o limiar baixo ## calculates the positions where the input voltage is less than the low threshold lowBits = np.where(self.V_in < self.V_L, self.ones, self.zeros) # calcula as posi??es onde a tens?o de entrada ? maior que o limiar baixo e n?o excede o limiar alto ## calculates the positions where the input voltage is greater than the low threshold and does not exceed the high threshold midleBits = np.where(highBits + lowBits == 0, self.ones, self.zeros) # "digital" output pode ser obtido somando 1 e o highBits e subtraindo lowBits ## "Digital" output can be obtained by adding and subtracting 1 and highBits lowBits self.digital_out = 1 + highBits + -lowBits # calcular residuo ## Calculate residue self.residuals = (((1+self.Cs/self.Cf)* self.V_in) -((self.Cs/self.Cf) * self.V_ref)) * highBits + ((1+self.Cs/ self.Cf)* self.V_in )* midleBits + (((1+self.Cs/self.Cf)* self.V_in) + ((self.Cs/ self.Cf)* self.V_ref)) * lowBits # retorno da saida digital e do residuo ## return of the digital output and the residue out = [self.digital_out, self.residuals] return out ##fun??o flash 2 bit ## 2 bit flash function def flash2b(self): # calcula as posi??es onde a tens?o de entrada excede o limiar alto ## calculates the positions where the input voltage exceeds the high threshold # (2X the threshold of the 1.5B stages) highBits1 = np.where(self.V_in > 2*self.V_H, [3], self.zeros) # calcula as posi??es onde a tens?o de entrada est? entre zero e o limiar alto ## calculates the positions where the input voltage is between zero and the high threshold if any(self.V_in <= 2*self.V_H) and any(self.V_in > 0.0): highBits2 = np.where((self.V_in <= 2*self.V_H) & (self.V_in > 0.0), [2], self.zeros) # calcula as posi??es onde a tens?o de entrada est? entre zero e o limiar baixo ## calculates the positions where the input voltage is between zero and low threshold if any(self.V_in <= 0.0) and any(self.V_in > 2*self.V_L): lowBits1 = np.where((self.V_in <= 0.0) & (self.V_in > 2*self.V_L), self.ones,self.zeros) # calcula as posi??es onde a tens?o de entrada ? menor que o limiar baixo ## calculates the positions where the input voltage is less than the low threshold lowBits2 = np.where(self.V_in <= 2*self.V_L, self.zeros, self.zeros) # "digital" output pode ser obtido somando todas as posi?oes desta forma. ## "Digital" output can be obtained by adding all the positions in this way self.digital_out = lowBits2 + lowBits1 + highBits2+ highBits1 # retorno da saida digital ## Digital output return out = [self.digital_out] return out ##fun??o flash 2.5 bit ## 2.5 bit flash function def flash2b5(self): ## calculates the positions where the input voltage exceeds the high threshold highBits1 = np.where(self.V_in > (self.V_H*5/2), self.ones, self.zeros) ## calculates the positions where the input voltage is between zero and the high threshold if any(self.V_in <= (self.V_H*5/2)) and any(self.V_in >=(self.V_H*3/2)): highBits2 = np.where((self.V_in <= (self.V_H*5/2)) & (self.V_in >=(self.V_H*3/2)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*3/2)) and any(self.V_in >=(self.V_H*1/2)): highBits3 = np.where((self.V_in <= (self.V_H*3/2)) & (self.V_in >=(self.V_H*1/2)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*1/2)) and any(self.V_in >=(self.V_L*1/2)): midleBits = np.where((self.V_in <= (self.V_H*1/2)) & (self.V_in >=(self.V_L*1/2)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*1/2)) and any(self.V_in >=(self.V_L*3/2)): lowBits1 = np.where((self.V_in <= (self.V_L*1/2)) & (self.V_in >=(self.V_L*3/2)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*3/2)) and any(self.V_in >=(self.V_L*5/2)): lowBits2 = np.where((self.V_in <= (self.V_L*3/2)) & (self.V_in >=(self.V_L*5/2)), self.ones, self.zeros) ## calculates the positions where the input voltage is less than the low threshold lowBits3 = np.where(self.V_in < (self.V_L*5/2), self.ones, self.zeros) ## Calculate residue 2.5 Bit self.residuals = ((4*self.V_in - 3*self.V_ref)*highBits1 + (4*self.V_in - 2*self.V_ref) * highBits2 + (4*self.V_in - self.V_ref) * highBits3 + (4 * self.V_in) * midleBits + (4*self.V_in + self.V_ref) * lowBits1 + (4*self.V_in + 2*self.V_ref) * lowBits2 + (4*self.V_in + 3*self.V_ref) * lowBits3) ## Residue output return out = [self.residuals] return out ## ## ##fun??o flash 3 Bit ## 3 Bit flash function def flash3b(self): ## calculates the positions where the input voltage exceeds the high threshold highBits1 = np.where(self.V_in > (self.V_H*3), [7], self.zeros) ## calculates the positions where the input voltage is between zero and the high threshold if any(self.V_in <= (self.V_H*3)) and any(self.V_in >=self.V_H*2): highBits2 = np.where((self.V_in <= (self.V_H*3)) & (self.V_in >=(self.V_H*2)), [6], self.zeros) if any(self.V_in <= (self.V_H*2)) and any(self.V_in >=(self.V_H)): highBits3 = np.where((self.V_in <= (self.V_H*2)) & (self.V_in >=(self.V_H)), [5], self.zeros) if any(self.V_in <= (self.V_H)) and any(self.V_in >=0.0): highBits4 = np.where((self.V_in <= (self.V_H)) & (self.V_in >=0.0), [4], self.zeros) if any(self.V_in <= 0.0) and any(self.V_in >= (self.V_L)): lowBits1 = np.where((self.V_in <= 0.0) & (self.V_in >= (self.V_L)), [3], self.zeros) if any(self.V_in <= (self.V_L)) and any(self.V_in >=(self.V_L*2)): lowBits2 = np.where((self.V_in <= (self.V_L)) & (self.V_in >=(self.V_L*2)), [2], self.zeros) if any(self.V_in <= (self.V_L*2)) and any(self.V_in >=(self.V_L*3)): lowBits3 = np.where((self.V_in <= (self.V_L*2)) & (self.V_in >=(self.V_L*3)), [1], self.zeros) ## calculates the positions where the input voltage is less than the low threshold lowBits4 = np.where(self.V_in < (self.V_L*3), self.zeros, self.zeros) ## "Digital" output can be obtained by adding all the positions in this way self.digital_out = lowBits4 + lowBits3 + lowBits2 + lowBits1 + highBits4 + highBits3 + highBits2 +highBits1 # retorno da saida digital ## Digital output return out = [self.digital_out] return out ## ## ##fun??o flash 3.5 bit ## 3.5 Bit flash function def flash3b5(self): ## calculates the positions where the input voltage exceeds the high threshold highBits1 = np.where(self.V_in > (self.V_H*13/4), self.ones, self.zeros) ## calculates the positions where the input voltage is between zero and the high threshold if any(self.V_in <= (self.V_H*13/4)) and any(self.V_in >=(self.V_H*11/4)): highBits2 = np.where((self.V_in <= (self.V_H*13/4)) & (self.V_in >=(self.V_H*11/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*11/4)) and any(self.V_in >=(self.V_H*9/4)): highBits3 = np.where((self.V_in <= (self.V_H*11/4)) & (self.V_in >=(self.V_H*9/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*9/4)) and any(self.V_in >=(self.V_H*7/4)): highBits4 = np.where((self.V_in <= (self.V_H*9/4)) & (self.V_in >=(self.V_H*7/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*7/4)) and any(self.V_in >=(self.V_H*5/4)): highBits5 = np.where((self.V_in <= (self.V_H*7/4)) & (self.V_in >=(self.V_H*5/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*5/4)) and any(self.V_in >=(self.V_H*3/4)): highBits6 = np.where((self.V_in <= (self.V_H*5/4)) & (self.V_in >=(self.V_H*3/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*3/4)) and any(self.V_in >=(self.V_H*1/4)): highBits7 = np.where((self.V_in <= (self.V_H*3/4)) & (self.V_in >=(self.V_H*1/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*1/4)) and any(self.V_in >=(self.V_L*1/4)): midleBits = np.where((self.V_in <= (self.V_H*1/4)) & (self.V_in >=(self.V_L*1/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*1/4)) and any(self.V_in >=(self.V_L*3/4)): lowBits1 = np.where((self.V_in <= (self.V_L*1/4)) & (self.V_in >=(self.V_L*3/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*3/4)) and any(self.V_in >=(self.V_L*5/4)): lowBits2 = np.where((self.V_in <= (self.V_L*3/4)) & (self.V_in >=(self.V_L*5/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*5/4)) and any(self.V_in >=(self.V_L*7/4)): lowBits3 = np.where((self.V_in <= (self.V_L*5/4)) & (self.V_in >=(self.V_L*7/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*7/4)) and any(self.V_in >=(self.V_L*9/4)): lowBits4 = np.where((self.V_in <= (self.V_L*7/4)) & (self.V_in >=(self.V_L*9/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*9/4)) and any(self.V_in >=(self.V_L*11/4)): lowBits5 = np.where((self.V_in <= (self.V_L*9/4)) & (self.V_in >=(self.V_L*11/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*11/4)) and any(self.V_in >=(self.V_L*13/4)): lowBits6 = np.where((self.V_in <= (self.V_L*11/4)) & (self.V_in >=(self.V_L*13/4)), self.ones, self.zeros) ## calculates the positions where the input voltage is less than the low threshold lowBits7 = np.where(self.V_in < (self.V_L*13/4), self.ones, self.zeros) ## Calculate residue 3.5 Bit self.residuals = ((8*self.V_in - 7*self.V_ref) *highBits1 + (8*self.V_in - 6*self.V_ref)* highBits2 + (8*self.V_in - 5*self.V_ref)*highBits3 + (8*self.V_in - 4*self.V_ref) * highBits4 + (8*self.V_in - 3*self.V_ref) * highBits5 + (8*self.V_in - 2*self.V_ref) * highBits6 + (8*self.V_in - self.V_ref) * highBits7 + (8 * self.V_in) * midleBits + (8*self.V_in + self.V_ref) * lowBits1 + (8*self.V_in + 2*self.V_ref) * lowBits2 + (8*self.V_in + 3*self.V_ref) * lowBits3 + (8*self.V_in + 4*self.V_ref) * lowBits4 + (8*self.V_in + 5*self.V_ref) * lowBits5 + (8*self.V_in + 6*self.V_ref) * lowBits6 + (8*self.V_in + 7*self.V_ref) * lowBits7 ) ## Residue output return out = [self.residuals] return out ## ## ## ##fun??o Pipeline ## def pipeline(self): ##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>CLASS CALCULATE>>>>>>>>>>>>>>>>>>>>>>>>>>>> ##class calculate(ADC): ## ## def __init__ (self): ## ## ## def AC_Errors(self): ## ## ## def Offset_Errors(self): ## ## ## def plot_fft(self): ## ## ## def DNL_INL(self): ##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>SIMULA??O>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ## if __name__=='__main__': V_in = np.linspace(-1, 1, 10000) F1B5 = ADC(10000, V_in, 1, 2, 2).flash1b5() F2B = ADC(10000, V_in, 1, 2, 2).flash2b() F2B5 = ADC(10000, V_in, 1, 2, 2).flash2b5() F3B5 = ADC(10000, V_in, 1, 2, 2).flash3b5() F3B = ADC(10000, V_in, 1, 2, 2).flash3b() fig1 = figure(1,figsize=(8,5)) ax1 = fig1.add_subplot(111, autoscale_on=True) ax1.plot(V_in, F1B5[1], lw = 1, color='b') grid(True); xlabel('IN'); ylabel('OUT'); title('RESIDUALS 1B5') fig2 = figure(2,figsize=(8,5)) ax2 = fig2.add_subplot(111, autoscale_on=False,xlim=(-1,1), ylim=(-1,3)) ax2.plot(V_in, F1B5[0], lw=1, color='r') grid(True); xlabel('IN'); ylabel('OUT'); title('DIGITAL OUT 1B5') fig3 = figure(3,figsize=(8,5)) ax3 = fig3.add_subplot(111, autoscale_on=False,xlim=(-1,1), ylim=(-1,4)) ax3.plot(V_in, F2B[0], lw=1, color='g') grid(True); xlabel('IN'); ylabel('OUT'); title('DIGITAL OUT 2B') fig4 = figure(4,figsize=(8,5)) ax4 = fig4.add_subplot(111, autoscale_on=True) ax4.plot(V_in, F2B5[0], lw=1, color='y') grid(True); xlabel('IN'); ylabel('OUT'); title('RESIDUALS 2B5') fig5 = figure(5,figsize=(8,5)) ax5 = fig5.add_subplot(111, autoscale_on=False,xlim=(-1,1), ylim=(-1,8)) ax5.plot(V_in, F3B[0], lw=1, color='brown') grid(True); xlabel('IN'); ylabel('OUT'); title('DIGITAL OUT 3B') fig6 = figure(6,figsize=(8,5)) ax6 = fig6.add_subplot(111, autoscale_on=False, xlim=(-1,1), ylim=(-1,1)) ax6.plot(V_in, F3B5[0], lw=1, color='purple') grid(True); xlabel('IN'); ylabel('OUT'); title('RESIDUALS 3B5') plt.show() Ps: How can i put my messages just for you to read it like you always do? From wyj1046 at gmail.com Mon Aug 30 10:57:57 2010 From: wyj1046 at gmail.com (villorent) Date: Mon, 30 Aug 2010 07:57:57 -0700 (PDT) Subject: PyGeo References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> Message-ID: <6ffec87d-e86e-4143-8bef-055a606da929@x20g2000pro.googlegroups.com> Maybe you could try this: http://hyry.dip.jp/files/pygeo.7z I found it on this page: http://hyry.dip.jp/blogt.py?file=0432.blog From cliff.martin at gmail.com Mon Aug 30 11:06:39 2010 From: cliff.martin at gmail.com (Cliff Martin) Date: Mon, 30 Aug 2010 11:06:39 -0400 Subject: Trouble importing cx_Oracle on HPUX Message-ID: including libttsh11 fixed the problem. Thank you! Now I can get on with fixing everything that Python 3 broke... err changed. :) -- Cliff On Sat, Aug 28, 2010 at 11:20 AM, Alexander Gattin wrote: > Hello, > > On Sat, Aug 28, 2010 at 09:27:05AM -0400, Cliff > Martin wrote: > > Yes, our entire toolchain is 64 bit - a mix of > > stuff I have downloaded and built and some > > packages from HP (in the form of depot files) > > GCC was downloaded from HP, for example. > > I see. I bootstrapped from bundled cc, hence all > the problems. > > > Python -d did not generate any additional > > information, and so was not helpful (should this > > work?). > > Oops I was wrong about the python -d -- > correct option is -v of course... > > > Python -v did, however, and it came up with a > > number of unresolved symbols all seeming to be > > from libnnz11.so. I tried linking against all of > > the *.so files in ORACLE_HOME/lib, but I don't > > remember trying libttsh11 specifically. I will > > try it again on Monday. > > You're using Oracle 11 vs our v10 (we also have > v8, v9 and v11 in production, but not on this > HP-UX server), but I think the problem with the > libnnz is the same: Oracle doesn't put correct > shared library dependencies into the libnnzXX.so > dynamic section header (it should list > libttshXX.so as NEEDED but apperently doesn't). > > Probably their distribution for Solaris is better, > I didn't check (I'll ask our DBAs on Monday). > > -- > With best regards, > xrgtn > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Mon Aug 30 11:32:15 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 30 Aug 2010 11:32:15 -0400 Subject: python 2.6.6 installation problems on osx In-Reply-To: <15352d95-125c-41bb-8eca-7c5bc6b4bd94@k10g2000yqa.googlegroups.com> References: <15352d95-125c-41bb-8eca-7c5bc6b4bd94@k10g2000yqa.googlegroups.com> Message-ID: On Mon, Aug 30, 2010 at 10:29 AM, jal wrote: > Hi All, > > I'm attempting a framework install of python 2.6.6 from source, on an > intel mac running osx 10.6.4. > > At the end of the install the following errors occur. > > install: mkdir /usr/local/bin: Permission denied > make[1]: *** [altinstallunixtools] Error 71 > make: *** [frameworkaltinstallunixtools] Error 2 > > Does anyone one know of a fix? > did you sudo make install or just make install? From ethan at stoneleaf.us Mon Aug 30 11:39:02 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 30 Aug 2010 08:39:02 -0700 Subject: meta-class troubles In-Reply-To: References: <4C7BBBE9.8090003@stoneleaf.us> Message-ID: <4C7BD096.5090905@stoneleaf.us> Chris Rebert wrote: > Shouldn't meta= instead be metaclass= ? Xavier Ho wrote: > I think you need to have metaclass in the class statement, not just meta. Argh. Thank you both. I'm glad it was simple! ~Ethan~ From thomas at jollybox.de Mon Aug 30 11:53:24 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 30 Aug 2010 17:53:24 +0200 Subject: Optimising literals away In-Reply-To: References: Message-ID: <201008301753.25177.thomas@jollybox.de> On Monday 30 August 2010, it occurred to Tobias Weber to exclaim: > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. > > def m(arg): > if arg & set([1,2,3]): > return 4 > > Is the set created every time the method is called? What about a > frozenset? Or tuple vs list? After how many calls per second does it pay > to save it at the module level? Would anybody else find this ugly? That creates a list, and then calls "set" with the list as an argument. Every time, because that's what the code says: call "set" with a new list containing 1, 2, and 3. If you use a tuple instead of the list, the tuple can be loaded as a whole -- as tuples are immutable, it doesn't have to be re-created every time, it can be the same object. If you use a set literal instead of calling "set", the set is constructed directly, like a list would be. Details: >>> def m_l(arg): ... if arg & set([1,2,3]): ... return 4 ... >>> def m_t(arg): ... if arg & set((1,2,3)): ... return 4 ... >>> def m_s(arg): ... if arg & {1, 2, 3}: ... return 4 ... >>> from dis import dis >>> dis(m_l) 2 0 LOAD_FAST 0 (arg) 3 LOAD_GLOBAL 0 (set) 6 LOAD_CONST 1 (1) 9 LOAD_CONST 2 (2) 12 LOAD_CONST 3 (3) 15 BUILD_LIST 3 18 CALL_FUNCTION 1 21 BINARY_AND 22 POP_JUMP_IF_FALSE 29 3 25 LOAD_CONST 4 (4) 28 RETURN_VALUE >> 29 LOAD_CONST 0 (None) 32 RETURN_VALUE >>> dis(m_t) 2 0 LOAD_FAST 0 (arg) 3 LOAD_GLOBAL 0 (set) 6 LOAD_CONST 5 ((1, 2, 3)) 9 CALL_FUNCTION 1 12 BINARY_AND 13 POP_JUMP_IF_FALSE 20 3 16 LOAD_CONST 4 (4) 19 RETURN_VALUE >> 20 LOAD_CONST 0 (None) 23 RETURN_VALUE >>> dis(m_s) 2 0 LOAD_FAST 0 (arg) 3 LOAD_CONST 1 (1) 6 LOAD_CONST 2 (2) 9 LOAD_CONST 3 (3) 12 BUILD_SET 3 15 BINARY_AND 16 POP_JUMP_IF_FALSE 23 3 19 LOAD_CONST 4 (4) 22 RETURN_VALUE >> 23 LOAD_CONST 0 (None) 26 RETURN_VALUE >>> From benjamin at python.org Mon Aug 30 12:00:13 2010 From: benjamin at python.org (Benjamin Peterson) Date: Mon, 30 Aug 2010 16:00:13 +0000 (UTC) Subject: Optimising literals away References: Message-ID: Tobias Weber gmx.net> writes: > > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. > > def m(arg): > if arg & set([1,2,3]): > return 4 > > Is the set created every time the method is called? Yes, and the list. > What about a > frozenset? Yep. > Or tuple vs list? Tuples containing other immutable literals can be optimized. (In cpython anyway.) > After how many calls per second does it pay > to save it at the module level? Ask the profiler. Probably not many. > Would anybody else find this ugly? I do it all the time. From arnodel at googlemail.com Mon Aug 30 12:02:37 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 30 Aug 2010 17:02:37 +0100 Subject: Optimising literals away References: Message-ID: Tobias Weber writes: > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. > > def m(arg): > if arg & set([1,2,3]): > return 4 > > Is the set created every time the method is called? What about a > frozenset? Or tuple vs list? After how many calls per second does it pay > to save it at the module level? Would anybody else find this ugly? > > Also I never profiled the regular expression cache... the dis module can help you for these: >>> import dis >>> def m(arg): ... if arg & set([1,2,3]): ... return 4 ... >>> dis.dis(m) 2 0 LOAD_FAST 0 (arg) 3 LOAD_GLOBAL 0 (set) 6 LOAD_CONST 1 (1) 9 LOAD_CONST 2 (2) 12 LOAD_CONST 3 (3) 15 BUILD_LIST 3 18 CALL_FUNCTION 1 21 BINARY_AND 22 JUMP_IF_FALSE 5 (to 30) 25 POP_TOP 3 26 LOAD_CONST 4 (4) 29 RETURN_VALUE >> 30 POP_TOP 31 LOAD_CONST 0 (None) 34 RETURN_VALUE As you can see, the list literal is built every time the function code is executed. -- Arnaud From nikos.the.gr33k at gmail.com Mon Aug 30 12:09:48 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 09:09:48 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> Message-ID: <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> On 30 ???, 11:11, Gregory Ewing wrote: > Nik the Greek wrote: > > Yes i will i just asked to know if i were to substitute what might be > > the problem so to understand why i need the quoting. > > Because if you use % to build a query string, the result must > be syntactically valid SQL. The values that you substitute > into the placeholders must end up looking like SQL literals. > That means string values need to be in quotes, and probably > dates as well, although numbers don't. > > When you use the execute method's own parameter substitution > mechanism, things are different. It's not a textual replacement, > and you don't put quotes around the placeholders. There's no > particular reason for that, it's just the way it's defined > to work. > > -- > Greg cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' , a_tuple ) and cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' , (a_tuple) ) are both syntactically correct right? buw what about cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' , (a_tuple,) ) From __peter__ at web.de Mon Aug 30 12:21:09 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Aug 2010 18:21:09 +0200 Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <6676c33f-0012-4051-bc75-b35af37df367@z28g2000yqh.googlegroups.com> Message-ID: Nik the Greek wrote: >> Perhpas its doenst get loaded like that? >> >> # initialize cookie >> cookie = SimpleCookie() >> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >> mycookie = cookie.get('visitor') > > Please someone else has an idea on how this to work? Add a print statement to verify that HTTP_COOKIE does indeed have a visitor. Or use the stuff below as a template. Here is a minimal script to set the visitor: #!/usr/bin/env python import cgitb cgitb.enable() import cgi import Cookie import os import sys form = cgi.FieldStorage() name = form.getfirst("name", "Unknown") cookie = Cookie.SimpleCookie() cookie["visitor"] = name sys.stdout.write(cookie.output()) sys.stdout.write("\r\nContent-type: text/plain\r\n\r\n") print "Hello, your new name is", name Invoke it with the equivalent of http://localhost:8000/cgi-bin/set_visitor.py?name=Nikos for your website. Then proceed with a small script to show the visitor's name: #!/usr/bin/env python import cgitb cgitb.enable() import cgi import Cookie import os import sys cookie = Cookie.SimpleCookie() cookie.load(os.environ.get("HTTP_COOKIE")) visitor = cookie.get("visitor") if visitor is None: visitor_name = "Unknown" else: visitor_name = visitor.value sys.stdout.write("Content-type: text/plain\r\n\r\n") print "Hello,", visitor_name print print print "HTTP_COOKIE=%r" % os.environ.get("HTTP_COOKIE") which you can invoke with the equivalent of http://localhost:8000/cgi-bin/show_visitor.py With some luck you should see your name and can proceed to adapt your script accordingly. Peter From bthate at gmail.com Mon Aug 30 12:21:50 2010 From: bthate at gmail.com (Bart Thate) Date: Mon, 30 Aug 2010 09:21:50 -0700 (PDT) Subject: JSONBOT 0.3 RELEASE Message-ID: <53e76eb1-a5cf-4588-805e-d1cdf4a47ba3@t2g2000yqe.googlegroups.com> Hello world ! I just released version 0.3 of JSONBOT. JSONBOT is a remote event driven framework for building bots that talk JSON to each other over XMPP. This distribution provides bots built on this framework for console, IRC, XMPP for the shell and WWW and XMPP for the Google Application engine. JSONBOT 0.3 provides the following programs: jsb - console version of jsonbot jsb-import - import data from another bot jsb-installplug - install remote plugins jsb-irc - IRC version of jsonbot (socket) jsb-xmpp - XMPP version of jsonbot (socket) jsb-fleet - mix IRC and XMPP bots jsb-release - create a new release directory jsb-rollback - rollback a release jsb-run - run a release in the GAE dev_appserver jsb-stop - stop a running bot jsb-upload - upload a release to the GAE A plugin infrastructure is in place to program the functionality that is needed. JSONBOT 0.3 plugins: 8b - eight ball admin - administator related commands alias - keep aliases (per user) ask - plugin for asking "experts" a question choice - choice out of a list .. used in pipelines controlchar - set the control character of a channel forward - forward events of a channel to another bot clone - clone waves into new ones core - core bot commands count - count the numbers in a result .. used in pipelines data - provide data dumps of channels, bots, events fleet - support multiple bots in a running instance (list of bots) gae - provide GAE commands like flush cache or cache stats gadget - wave gadget support gcalc - use google to calculate grep - grep the result .. used in pipelines hubbub - pubsubhubbub plugin providing subscribe functionality ipcalc - ipcalculator irc - IRC related commands jsondata - enable/disable sharing of files through the jsonserver (not enabled right now) kickban - channel control commands for IRC misc - other commands more - do a more on buffered output nickcapture - retake nick (IRC) nickserv - nickserver support (IRC) not - negated grep .. used in pipelines outputcache - show outputcache data rss - provide RSS and Atom pollers relay - relay to other waves/xmpp restserver - provide REST functionality to the bot reload - reloading of plugins reverse - rever see the result .. also used in pipelines seen - keep track of users shop - keep shopping lists sort - sort the result .. used in pipelines tail - tail the result .. used in pipelines test - test commands tinyurl - get a tinyurl todo - keep a todo list underauth - undernet auth support (IRC) uniq - make the result unique .. used in pipelines user - user management userstate - userstate management watcher - watch channels that get forwarded to the bot. wave - wave related commands weather - show weather in a city welcome - welcome messages shown in the gadget wikipedia - query wikipedia xmpp - xmpp related functions account Project home is at http://jsonbot.googlecode.com Have fun with it! From alex.kapps at web.de Mon Aug 30 12:34:04 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Mon, 30 Aug 2010 18:34:04 +0200 Subject: String substitution VS proper mysql escaping In-Reply-To: <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> Message-ID: <4C7BDD7C.6010501@web.de> Nik the Greek wrote: > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , a_tuple ) > > and > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , (a_tuple) ) > > are both syntactically correct right? > > buw what about > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , (a_tuple,) ) Python has a wonderful interactive mode which is perfect for trying this out: >>> a_tuple = 1,2,3 >>> a_tuple (1, 2, 3) >>> (a_tuple) (1, 2, 3) >>> (a_tuple,) ((1, 2, 3),) >>> First note, that tuples are not created with parentheses, but with the comma. So, the first two are the same. The parens are only needed to remove ambiguity in certain situations, but are meaningless here. The third case is a tuple containing a_tuple as its only element. From python at mrabarnett.plus.com Mon Aug 30 12:41:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 17:41:52 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: <4C7BDF50.9030804@mrabarnett.plus.com> On 30/08/2010 04:33, Nik the Greek wrote: > On 30 ???, 06:12, MRAB wrote: > >> This part: >> >> ( not mycookie or mycookie.value != 'nikos' ) >> >> is false but this part: >> >> re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None >> >> is true because host doesn't contain any of those substrings. > > So, the if code does executed because one of the condition is true? > > How should i write it? > > I cannot think clearly on this at all. > > I just wan to tell it to get executed ONLY IF > > the cookie values is not 'nikos' > > or ( don't knwo if i have to use and or 'or' here) > > host does not contain any of the substrings. > > What am i doign wrong?! > It might be clearer if you reverse the condition and say: me_visiting = ... if not me_visiting: ... From python at mrabarnett.plus.com Mon Aug 30 12:43:34 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 17:43:34 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> Message-ID: <4C7BDFB6.1040404@mrabarnett.plus.com> On 30/08/2010 17:09, Nik the Greek wrote: > On 30 ???, 11:11, Gregory Ewing wrote: >> Nik the Greek wrote: >>> Yes i will i just asked to know if i were to substitute what might be >>> the problem so to understand why i need the quoting. >> >> Because if you use % to build a query string, the result must >> be syntactically valid SQL. The values that you substitute >> into the placeholders must end up looking like SQL literals. >> That means string values need to be in quotes, and probably >> dates as well, although numbers don't. >> >> When you use the execute method's own parameter substitution >> mechanism, things are different. It's not a textual replacement, >> and you don't put quotes around the placeholders. There's no >> particular reason for that, it's just the way it's defined >> to work. >> >> -- >> Greg > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , a_tuple ) > > and > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , (a_tuple) ) > > are both syntactically correct right? > > buw what about > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , (a_tuple,) ) That's syntactically correct, but not the same thing. From python at mrabarnett.plus.com Mon Aug 30 12:52:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 17:52:18 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C7BDD7C.6010501@web.de> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> <4C7BDD7C.6010501@web.de> Message-ID: <4C7BE1C2.2050107@mrabarnett.plus.com> On 30/08/2010 17:34, Alexander Kapps wrote: > Nik the Greek wrote: > >> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s ''' , a_tuple ) >> >> and >> >> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s ''' , (a_tuple) ) >> >> are both syntactically correct right? >> >> buw what about >> >> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s ''' , (a_tuple,) ) > > Python has a wonderful interactive mode which is perfect for trying this > out: > > >>> a_tuple = 1,2,3 > >>> a_tuple > (1, 2, 3) > >>> (a_tuple) > (1, 2, 3) > >>> (a_tuple,) > ((1, 2, 3),) > >>> > > > First note, that tuples are not created with parentheses, but with the > comma. So, the first two are the same. The parens are only needed to > remove ambiguity in certain situations, but are meaningless here. > There's only one exception: the empty tuple (). > The third case is a tuple containing a_tuple as its only element. From chris at simplistix.co.uk Mon Aug 30 12:55:53 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 30 Aug 2010 17:55:53 +0100 Subject: bug? pkgutil.walk_packages returns packages that result in an ImportError In-Reply-To: References: Message-ID: <4C7BE299.8080201@simplistix.co.uk> Peter Otten wrote: >> My expectation of this is that if onerrors is left as None, names >> yielded will be importable. > > I would infer no such promise, especially as the generator also yields > modules, and no attempt at all is made to import those. Really? I thought the __import__ fired over everything? > I've never worked with that function; I'd like to hear more about your > usecase. It's becoming a common use case for packages like martian [1] and venutian [2] that need to scan whole packages for things. In my case, I'm scanning for declaratively mapped SQLAlchemy models. It would be great if this function became part of the public API and got some more definition on what it will and won't do. When should I take this to Python-Dev? cheers, Chris [1] http://pypi.python.org/pypi/martian [2] http://pypi.python.org/pypi/venusian -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From denisg640 at gmail.com Mon Aug 30 13:07:34 2010 From: denisg640 at gmail.com (Denis Gomes) Date: Mon, 30 Aug 2010 13:07:34 -0400 Subject: python+sqlite3 in memory database Message-ID: Hi Everyone, I am using sqlite3 with python2.5 and the pysqlite wrapper. I am trying to copy tables from one database (in memory) to another database (file) using ATTACH. I looked on the internet and found a couple of sites that show how to do this but the table schema is not copied. def SaveToFile(self,filename): # Attach external db file - give it handle filename # Attaching automatically creates a database by default self.__curs.execute("ATTACH %s AS %s" % (filename,filename)) table_names=self.__curs.execute("SELECT name FROM main.sqlite_master WHERE type='table'").fetchall() for table_name, in table_names: #copy in mem db to persistent db self.__curs.execute("CREATE TABLE %s.%s AS SELECT * FROM main.%s" % (filename,table_name,table_name)) self.__curs.execute("DETACH %s" % filename) # Detach external db""" Is there a way to copy the schema from the sqlite_master table. I know we can used iter.dump from within python to dump to text based SQL but I would prefer not to do this. Eventually my goal is to dynamically load and unload sections of a file based database (could be tables or rows) in and out of memory for effeciency purposes. Any help is appreciated. Thanks in advance. Denis -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Mon Aug 30 13:16:42 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 10:16:42 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: On 30 ???, 19:41, MRAB wrote: > On 30/08/2010 04:33, Nik the Greek wrote: > > > > > > > > > On 30 ???, 06:12, MRAB ?wrote: > > >> This part: > > >> ? ? ? ( not mycookie or mycookie.value != 'nikos' ) > > >> is false but this part: > > >> ? ? ? re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > >> is true because host doesn't contain any of those substrings. > > > So, the if code does executed because one of the condition is true? > > > How should i write it? > > > I cannot think clearly on this at all. > > > I just wan to tell it to get executed ?ONLY IF > > > the cookie values is not 'nikos' > > > or ( don't knwo if i have to use and or 'or' here) > > > host does not contain any of the substrings. > > > What am i doign wrong?! > > It might be clearer if you reverse the condition and say: > > ? ? ?me_visiting = ... > ? ? ?if not me_visiting: > ? ? ? ? ?... I don't understand what are you trying to say Please provide a full example. You mean i should try it like this? unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn| yandex|13448|spider|crawl)', host ) not None: But isnt it the same thing like the if? From nikos.the.gr33k at gmail.com Mon Aug 30 13:17:25 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 10:17:25 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <6676c33f-0012-4051-bc75-b35af37df367@z28g2000yqh.googlegroups.com> Message-ID: <04e256a3-3bc3-44ef-a754-da913261f3f7@i15g2000yqe.googlegroups.com> On 30 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > Nik the Greek wrote: > >> Perhpas its doenst get loaded like that? > > >> # initialize cookie > >> cookie = SimpleCookie() > >> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >> mycookie = cookie.get('visitor') > > > Please someone else has an idea on how this to work? > > Add a print statement to verify that HTTP_COOKIE does indeed have a visitor. > Or use the stuff below as a template. > > Here is a minimal script to set the visitor: > > #!/usr/bin/env python > import cgitb > cgitb.enable() > > import cgi > import Cookie > import os > import sys > > form = cgi.FieldStorage() > name = form.getfirst("name", "Unknown") > > cookie = Cookie.SimpleCookie() > cookie["visitor"] = name > > sys.stdout.write(cookie.output()) > sys.stdout.write("\r\nContent-type: text/plain\r\n\r\n") > print "Hello, your new name is", name > > Invoke it with the equivalent of > > http://localhost:8000/cgi-bin/set_visitor.py?name=Nikos > > for your website. Then proceed with a small script to show the visitor's > name: > > #!/usr/bin/env python > import cgitb > cgitb.enable() > > import cgi > import Cookie > import os > import sys > > cookie = Cookie.SimpleCookie() > cookie.load(os.environ.get("HTTP_COOKIE")) > > visitor = cookie.get("visitor") > if visitor is None: > ? ? visitor_name = "Unknown" > else: > ? ? visitor_name = visitor.value > > sys.stdout.write("Content-type: text/plain\r\n\r\n") > print "Hello,", visitor_name > print > print > print "HTTP_COOKIE=%r" % os.environ.get("HTTP_COOKIE") > > which you can invoke with the equivalent of > > http://localhost:8000/cgi-bin/show_visitor.py > > With some luck you should see your name and can proceed to adapt your script > accordingly. > > Peter The cookie is set tyo the browser with the code i provided few posts back The problem is that i for soemreason cant check correctly its existance. From kevinlcarlson at gmail.com Mon Aug 30 13:24:49 2010 From: kevinlcarlson at gmail.com (kevinlcarlson) Date: Mon, 30 Aug 2010 10:24:49 -0700 (PDT) Subject: Helper app for intranet site References: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> Message-ID: <61894f54-90ff-4e0e-9c81-860b6e9cdc15@p12g2000prn.googlegroups.com> On Aug 29, 8:46?pm, Lawrence D'Oliveiro wrote: > In message > <45e0772c-24a8-4cbb-a4fc-74a1b6c25... at n19g2000prf.googlegroups.com>, > > kevinlcarlson wrote: > > I'm exploring the possibility of developing a helper app for an > > existing internal company website. ?Basically, it would automatically > > scan the current page contents, including prepopulated forms, and > > provide context-related business rule comments to the user, via a stay- > > on-top wxPython panel. > > Seems like a roundabout way of doing it. Can?t you integrate into the server > code which is generating the page contents, instead of trying to reverse- > engineer those contents? Absolutely - that would be the best way to accomplish this. Unfortunately, our group has no access to the web server and the developers have this functionality scheduled about a year into the future, but we need it ASAP. Also, our group would like to be in control of the code and business rule contents, rather than wait for updates from the busy web team... So far, it looks like PAMIE could be a good choice for the page scraping code - it includes WinGuiAuto.py which could be used to identify the correct window handle and parse the contents. Business rule data could be stored locally in Sqlite, since it changes rarely and there is a small user base... Does this seem like the right track? Thanks, Kevin From nikos.the.gr33k at gmail.com Mon Aug 30 13:36:01 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 10:36:01 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> On 30 ???, 19:41, MRAB wrote: > On 30/08/2010 04:33, Nik the Greek wrote: > > > > > > > > > On 30 ???, 06:12, MRAB ?wrote: > > >> This part: > > >> ? ? ? ( not mycookie or mycookie.value != 'nikos' ) > > >> is false but this part: > > >> ? ? ? re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > >> is true because host doesn't contain any of those substrings. > > > So, the if code does executed because one of the condition is true? > > > How should i write it? > > > I cannot think clearly on this at all. > > > I just wan to tell it to get executed ?ONLY IF > > > the cookie values is not 'nikos' > > > or ( don't knwo if i have to use and or 'or' here) > > > host does not contain any of the substrings. > > > What am i doign wrong?! > > It might be clearer if you reverse the condition and say: > > ? ? ?me_visiting = ... > ? ? ?if not me_visiting: > ? ? ? ? ?... # initialize cookie cookie = SimpleCookie() cookie.load( os.environ.get('HTTP_COOKIE', '') ) visitor = cookie.get('visitor') This statement if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| spider|crawl)', host ) is None: produces the following error: /home/webville/public_html/cgi-bin/counter.py 93 # do not increment the counter if a Cookie is set to the visitors browser already 94 # ================================================================================================================= 95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| spider|crawl)', host ) is None: 96 97 print visitor visitor = None, visitor.value undefined, re = , re.search = , host = '178-128-217.dynamic.cyta.gr', builtin None = None Why visitor.value is undefined? From mail at timgolden.me.uk Mon Aug 30 13:45:29 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Aug 2010 18:45:29 +0100 Subject: shlex, unicode, and subprocess.Popen on Windows In-Reply-To: <1283178266.13167.1392435533@webmail.messagingengine.com> References: <1283176444.5865.1392429397@webmail.messagingengine.com> <1283178224.12933.1392434421@webmail.messagingengine.com> <1283178266.13167.1392435533@webmail.messagingengine.com> Message-ID: <4C7BEE39.6020002@timgolden.me.uk> On 30/08/2010 3:24 PM, python at bdurham.com wrote: > My understanding is that the only time one needs to use shell=True is > when they are 'executing' a non-executable file whose executable must be > discovered via file association rules? Does that sound accurate? I'm not entirely sure what you mean by that last piece. Certainly, shell must be used if you're trying to run, eg, dir or copy which aren't executables in their own right but are sub-executables [a word I've just invented] of the command processor (cmd.exe). There's a slightly open question as to whether you need to say shell=True when running batch files (.bat/.cmd). My experience is not; others say yes. The ".... must be discovered via file association rules" looks out of place in your explanation above. (read: I can't see what you're getting at :) ) TJG From rami.chowdhury at merton.oxon.org Mon Aug 30 13:48:14 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Mon, 30 Aug 2010 23:48:14 +0600 Subject: Problem checking an existing browser cookie In-Reply-To: <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> Message-ID: On Mon, Aug 30, 2010 at 23:36, Nik the Greek wrote: > # initialize cookie > cookie = SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > visitor = cookie.get('visitor') > > This statement > > if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > spider|crawl)', host ) is None: > > produces the following error: > > ?/home/webville/public_html/cgi-bin/counter.py > ? 93 # do not increment the counter if a Cookie is set to the > visitors browser already > ? 94 # > ================================================================================================================= > ? 95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > spider|crawl)', host ) is None: > ? 96 > ? 97 ? ? ? ? print visitor > visitor = None, visitor.value undefined, re = lib64/python2.4/re.pyc'>, re.search = , host = > '178-128-217.dynamic.cyta.gr', builtin None = None > > Why visitor.value is undefined? Because, as the traceback tells you, visitor is None. As you said, the cookie is not recognized. Try inserting the following line at the top of your script: print "Content-type:text/html\r\n\r\n", os.environ.get('HTTP_COOKIE', 'NO COOKIE DATA') That should give you the value of the cookie, which might help you debug why it is not being loaded. -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From python at mrabarnett.plus.com Mon Aug 30 13:50:21 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 18:50:21 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: <4C7BEF5D.20602@mrabarnett.plus.com> On 30/08/2010 18:16, Nik the Greek wrote: > On 30 ???, 19:41, MRAB wrote: >> On 30/08/2010 04:33, Nik the Greek wrote: >> >> >> >> >> >> >> >>> On 30 ???, 06:12, MRAB wrote: >> >>>> This part: >> >>>> ( not mycookie or mycookie.value != 'nikos' ) >> >>>> is false but this part: >> >>>> re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None >> >>>> is true because host doesn't contain any of those substrings. >> >>> So, the if code does executed because one of the condition is true? >> >>> How should i write it? >> >>> I cannot think clearly on this at all. >> >>> I just wan to tell it to get executed ONLY IF >> >>> the cookie values is not 'nikos' >> >>> or ( don't knwo if i have to use and or 'or' here) >> >>> host does not contain any of the substrings. >> >>> What am i doign wrong?! >> >> It might be clearer if you reverse the condition and say: >> >> me_visiting = ... >> if not me_visiting: >> ... > > I don't understand what are you trying to say > > Please provide a full example. > > You mean i should try it like this? > > unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn| > yandex|13448|spider|crawl)', host ) not None: > > But isnt it the same thing like the if? My point is that the logic might be clearer to you if you think first about how you know when you _are_ the visitor. From python at mrabarnett.plus.com Mon Aug 30 13:53:05 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 18:53:05 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> Message-ID: <4C7BF001.1000904@mrabarnett.plus.com> On 30/08/2010 18:36, Nik the Greek wrote: > On 30 ???, 19:41, MRAB wrote: >> On 30/08/2010 04:33, Nik the Greek wrote: >> >> >> >> >> >> >> >>> On 30 ???, 06:12, MRAB wrote: >> >>>> This part: >> >>>> ( not mycookie or mycookie.value != 'nikos' ) >> >>>> is false but this part: >> >>>> re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None >> >>>> is true because host doesn't contain any of those substrings. >> >>> So, the if code does executed because one of the condition is true? >> >>> How should i write it? >> >>> I cannot think clearly on this at all. >> >>> I just wan to tell it to get executed ONLY IF >> >>> the cookie values is not 'nikos' >> >>> or ( don't knwo if i have to use and or 'or' here) >> >>> host does not contain any of the substrings. >> >>> What am i doign wrong?! >> >> It might be clearer if you reverse the condition and say: >> >> me_visiting = ... >> if not me_visiting: >> ... > > > # initialize cookie > cookie = SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > visitor = cookie.get('visitor') > > This statement > > if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > spider|crawl)', host ) is None: > > produces the following error: > > /home/webville/public_html/cgi-bin/counter.py > 93 # do not increment the counter if a Cookie is set to the > visitors browser already > 94 # > ================================================================================================================= > 95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > spider|crawl)', host ) is None: > 96 > 97 print visitor > visitor = None, visitor.value undefined, re = lib64/python2.4/re.pyc'>, re.search =, host = > '178-128-217.dynamic.cyta.gr', builtin None = None > > Why visitor.value is undefined? Because visitor is None. It's not seeing any cookie. From nikos.the.gr33k at gmail.com Mon Aug 30 13:59:43 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 10:59:43 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> Message-ID: <4aa14cf9-38b4-4240-a796-c8ba56093e46@z7g2000yqg.googlegroups.com> On 30 ???, 20:53, MRAB wrote: > > Why visitor.value is undefined? > > Because visitor is None. It's not seeing any cookie. WHY NOT?! THE COOKIE _DOES_EXIST !!! What am i missing here?! From jal at bethere.co.uk Mon Aug 30 14:01:58 2010 From: jal at bethere.co.uk (jal) Date: Mon, 30 Aug 2010 11:01:58 -0700 (PDT) Subject: python 2.6.6 installation problems on osx References: <15352d95-125c-41bb-8eca-7c5bc6b4bd94@k10g2000yqa.googlegroups.com> Message-ID: I just did 'make install' because according to the osx section of the README: On a clean OSX /usr/local does not exist. Do a "sudo mkdir -m 775 /usr/local" before you do a make install. It is probably not a good idea to do "sudo make install" which installs everything as superuser, as this may later cause problems when installing distutils- based additions. jal. On Aug 30, 4:32?pm, Benjamin Kaplan wrote: > On Mon, Aug 30, 2010 at 10:29 AM, jal wrote: > > Hi All, > > > I'm attempting a framework install of python 2.6.6 from source, on an > > intel mac running osx 10.6.4. > > > At the end of the install the following errors occur. > > > install: mkdir /usr/local/bin: Permission denied > > make[1]: *** [altinstallunixtools] Error 71 > > make: *** [frameworkaltinstallunixtools] Error 2 > > > Does anyone one know of a fix? > > did you sudo make install or just make install? From erik.reppen at gmail.com Mon Aug 30 14:21:50 2010 From: erik.reppen at gmail.com (Erik Reppen) Date: Mon, 30 Aug 2010 11:21:50 -0700 (PDT) Subject: Looking for Python and Python/Django workplaces in Chicago Message-ID: <894aa094-70c8-4c0e-b2c6-f2b783f68929@l20g2000yqe.googlegroups.com> I'm a really strong front end web dev with an interest in becoming more of a generalist web and app dev through Python. Anybody aware of studios/agencies that actually prefer Python in Chicago I could keep an eye on. From arnodel at googlemail.com Mon Aug 30 14:51:52 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 30 Aug 2010 19:51:52 +0100 Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: Raymond Hettinger writes: > On Aug 29, 8:33?am, Arnaud Delobelle wrote: >> ernest writes: >> > Hi, >> >> > The operator module provides separate functions for >> > "in place" operations, such as iadd(), isub(), etc. >> > However, it appears that these functions don't really >> > do the operation in place: >> >> > In [34]: a = 4 >> >> > In [35]: operator.iadd(a, 3) >> > Out[35]: 7 >> >> > In [36]: a >> > Out[36]: 4 >> >> > So, what's the point? If you have to make the >> > assignment yourself... I don't understand. >> >> > Cheers, >> > Ernest >> >> That's because >> >> ? ?a += b >> >> is executed as: >> >> ? ?a = a.__iadd__(b) >> >> For immutable objects, (such as integers), a.__iadd__(b) returns a + b >> *and then* this value is assigned to a (or rather 'a' is bound to the >> value). ?So for immutables objects, iadd(a, b) is the same as a + b >> >> For mutable objects (such as lists), a.__iadd__(b) mutates the object >> *and then* returns self so that when the assignement is executed, 'a' >> will still be bound the the same object. ?E.g. if a = [1, 2] then >> >> ? ? a += [3] >> >> will first append 3 to the list and then reassign the list to 'a' (it is >> unnecessary in this case but if this step was omitted, the "in place" >> operators wouldn't work on immutables types). > > This is an excellent explanation. > Perhaps, you can submit a documentation > patch for the operator module so this > doesn't get lost. > > > Raymond I have submitted a documentation patch: http://bugs.python.org/issue9717 -- Arnaud From benjamin at python.org Mon Aug 30 15:00:11 2010 From: benjamin at python.org (Benjamin Peterson) Date: Mon, 30 Aug 2010 19:00:11 +0000 (UTC) Subject: python+sqlite3 in memory database References: Message-ID: Denis Gomes gmail.com> writes: > > Eventually my goal is to dynamically load and unload sections of a file based database (could be tables or rows) in and out of memory for effeciency purposes. Have you actually found this to be an useful optimization? SQLite already internally caches database information in memory. From tjreedy at udel.edu Mon Aug 30 15:08:57 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Aug 2010 15:08:57 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: <7xiq2suzbj.fsf@ruckus.brouhaha.com> References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> <7xiq2suzbj.fsf@ruckus.brouhaha.com> Message-ID: On 8/30/2010 7:14 AM, Paul Rubin wrote: > example, tkinter has been part of the stdlib for at least a decade but > is totally undocumented in the Python library manual. I have trouble equating 'totally undocumented' to about 400 lines + 200 for tix + 600 for ttk ;-). Yes, 400, while more than most modules get, is inadequate as a complete reference. But no one has volunteered to reproduce the material available elsewhere. I am not sure that that is the highest priority for doc improvement yet. You are welcome to have a go at expanding the tkinter page. -- Terry Jan Reedy From nobody at nowhere.com Mon Aug 30 15:09:30 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 30 Aug 2010 20:09:30 +0100 Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On Mon, 30 Aug 2010 12:50:32 +0200, Thomas Jollans wrote: >> Face the facts dude. The Python docs have some major problems. >> They were pretty good when Python was a new, cool, project used >> by a handful of geeks. They are good relative to the "average" >> (whatever that is) open source project -- but that bar is so low >> as to be a string lying on the ground. > > Actually, the Python standard library reference manual is excellent. At > least that's my opinion. The core library documentation isn't as bad as most Python documentation, but it's still far from adequate for core language functionality. Anyone who thinks that the library documentation is "good" has become too accustomed to FOSS "documentation" which is little more than an HTMLified copy of the header files, with each function's documentation consisting of a prototype and a one-sentence description which provides no information which couldn't have been guessed from the function name. For add-ons, you can get away with second-rate documentation. If the documentation isn't sufficient to allow the module to be used, don't use it; write your own instead. But that doesn't work for core language features. From tjreedy at udel.edu Mon Aug 30 15:14:48 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Aug 2010 15:14:48 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On 8/30/2010 12:23 AM, rurpy at yahoo.com wrote: > The Python docs have some major problems. And I have no idea what you think they are. I have participated in 71 doc improvement issues on the tracker. Most of those I either initiated or provided suggestions. How many have you helped with? -- Terry Jan Reedy From nobody at nowhere.com Mon Aug 30 15:25:42 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 30 Aug 2010 20:25:42 +0100 Subject: shlex, unicode, and subprocess.Popen on Windows References: <1283176444.5865.1392429397@webmail.messagingengine.com> <1283178224.12933.1392434421@webmail.messagingengine.com> Message-ID: On Mon, 30 Aug 2010 10:24:26 -0400, python wrote: >> Kudos for avoiding shell=True > > My understanding is that the only time one needs to use shell=True is > when they are 'executing' a non-executable file whose executable must be > discovered via file association rules? Does that sound accurate? You also need to use it to execute commands which are built into the shell rather than being separate executables. On Windows, whether "shell" is True or False and whether "args" is a string or list are orthogonal. If args is a list, it will be converted to a string using the same rules regardless of whether the shell is used. From denisg640 at gmail.com Mon Aug 30 15:33:55 2010 From: denisg640 at gmail.com (Denis Gomes) Date: Mon, 30 Aug 2010 15:33:55 -0400 Subject: python+sqlite3 in memory database In-Reply-To: References: Message-ID: Hey Benjamin, Take a look at this website I found about cached and in-memory databases. I think the gist of the article is that caching is good if you are doing SELECTs on data that is frequently used whereas in-memory speeds up writes, (inserts and updates) to the db as well as querying. Maybe I am missing something? http://www.mcobject.com/in_memory_database Denis On Mon, Aug 30, 2010 at 3:00 PM, Benjamin Peterson wrote: > Denis Gomes gmail.com> writes: > > > > > Eventually my goal is to dynamically load and unload sections of a file > based > database (could be tables or rows) in and out of memory for effeciency > purposes. > > Have you actually found this to be an useful optimization? SQLite already > internally caches database information in memory. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From a_jtim at bellsouth.net Mon Aug 30 15:38:18 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Mon, 30 Aug 2010 12:38:18 -0700 (PDT) Subject: triangle python user's group? Message-ID: <3c95f09c-1fa7-4c63-9f13-3f2776c2ab41@j18g2000yqd.googlegroups.com> Hi, Is there a python users group in the Research Triangle Park area (North Carolina, USA)? If there is not one and you're in the area and would be interested, please send an email to jtim.arnold at gmail.com and I'll organize a get-together to get one started. I'll try to find a locale convenient to Chapel Hill, Durham, Raleigh, Cary, and Apex. thanks, --Tim From benjamin at python.org Mon Aug 30 15:51:34 2010 From: benjamin at python.org (Benjamin Peterson) Date: Mon, 30 Aug 2010 19:51:34 +0000 (UTC) Subject: python+sqlite3 in memory database References: Message-ID: Denis Gomes gmail.com> writes: > > > Hey Benjamin, > ? > ?Take a look at this website I found about cached and in-memory databases.? I think the gist of?the article?is that caching is good if you are doing SELECTs on data that is?frequently used whereas in-memory speeds up writes,?(inserts and updates)?to the db as well as querying.?Maybe I am missing something? Well, of course, but there's little point to doing INSERTs and UPDATEs if you don't write them to disk at some point. You could just have a long running transaction which will not write to the database file (though depending on how you have sqlite setup it may write to a journal file) until you commit it. From __peter__ at web.de Mon Aug 30 16:39:32 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Aug 2010 22:39:32 +0200 Subject: bug? pkgutil.walk_packages returns packages that result in an ImportError References: Message-ID: Chris Withers wrote: > Peter Otten wrote: >>> My expectation of this is that if onerrors is left as None, names >>> yielded will be importable. >> >> I would infer no such promise, especially as the generator also yields >> modules, and no attempt at all is made to import those. > > Really? Yes, and the docstring gives a hint: """ Note that this function must import all *packages* (NOT all modules!) on the given path, in order to access the __path__ attribute to find submodules. """ Emphasis *not* mine ;) > I thought the __import__ fired over everything? If in doubt have a look at the source code or make a little testcase. > It's becoming a common use case for packages like martian [1] and > venutian [2] that need to scan whole packages for things. In my case, > I'm scanning for declaratively mapped SQLAlchemy models. > > It would be great if this function became part of the public API and got > some more definition on what it will and won't do. When should I take > this to Python-Dev? My impression is that it was a conscious decision to import as little as necessary. It is easy to import the modules once you have their names, but impossible to undo an unwanted import. If you think the approach you expected is superior you can also escalate to python-ideas and see if you get more feedback there or make a feature request on the bug tracker. Peter From marduk at letterboxes.org Mon Aug 30 16:42:43 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Mon, 30 Aug 2010 16:42:43 -0400 Subject: triangle python user's group? In-Reply-To: <3c95f09c-1fa7-4c63-9f13-3f2776c2ab41@j18g2000yqd.googlegroups.com> References: <3c95f09c-1fa7-4c63-9f13-3f2776c2ab41@j18g2000yqd.googlegroups.com> Message-ID: <1283200963.512722.2.camel@paska> On Mon, 2010-08-30 at 12:38 -0700, Tim Arnold wrote: > Hi, > Is there a python users group in the Research Triangle Park area > (North Carolina, USA)? Google "triangle python user's group" From nagle at animats.com Mon Aug 30 16:43:32 2010 From: nagle at animats.com (John Nagle) Date: Mon, 30 Aug 2010 13:43:32 -0700 Subject: String substitution VS proper mysql escaping In-Reply-To: <8e17d7FsbU1@mid.individual.net> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> Message-ID: <4c7c17f4$0$1654$742ec2ed@news.sonic.net> On 8/30/2010 1:11 AM, Gregory Ewing wrote: > Nik the Greek wrote: > >> Yes i will i just asked to know if i were to substitute what might be >> the problem so to understand why i need the quoting. > > Because if you use % to build a query string, the result must > be syntactically valid SQL. The values that you substitute > into the placeholders must end up looking like SQL literals. > That means string values need to be in quotes, and probably > dates as well, although numbers don't. > > When you use the execute method's own parameter substitution > mechanism, things are different. It's not a textual replacement, > and you don't put quotes around the placeholders. There's no > particular reason for that, it's just the way it's defined > to work. Actually, it IS a textual replacement. What cursor.execute(sqlstring, values) is doing is essentially quotedstr = sqlstring % map(MySQLdb.escape_string, values) cursor.execute(quotedstr) There's much confusion about this, but it isn't complicated. John Nagle From nagle at animats.com Mon Aug 30 16:50:36 2010 From: nagle at animats.com (John Nagle) Date: Mon, 30 Aug 2010 13:50:36 -0700 Subject: python+sqlite3 in memory database In-Reply-To: References: Message-ID: <4c7c199d$0$1646$742ec2ed@news.sonic.net> On 8/30/2010 12:00 PM, Benjamin Peterson wrote: > Denis Gomes gmail.com> writes: > >> >> Eventually my goal is to dynamically load and unload sections of a file based > database (could be tables or rows) in and out of memory for effeciency purposes. > > Have you actually found this to be an useful optimization? SQLite already > internally caches database information in memory. In general, if you find yourself concerned about sqlite performance, it's time to move to MySQL or Postgres. "sqlite" is for simple, lightweight databases mostly accessed by one process at a time. You store your program's configuration options in sqlite. You store your web site's business transactions in MySQL. "sqlite" has reasonably good SELECT performance on simple indices, but anything beyond that isn't all that great. Multiple processes updating the same sqlite database will have terrible performance, because the locking mechanism not only locks the entire table, the wait mechanism is a timed retry. John Nagle From denisg640 at gmail.com Mon Aug 30 16:50:37 2010 From: denisg640 at gmail.com (Denis Gomes) Date: Mon, 30 Aug 2010 16:50:37 -0400 Subject: python+sqlite3 in memory database In-Reply-To: References: Message-ID: Yep, I see what you are saying. I am going to do a bit more research to see how sqlite3 works internally, ie. cache size, page size, etc, and then decide if I will need to mess with in-memory databases. Thanks for your insight, appreciate it. Denis On Mon, Aug 30, 2010 at 3:51 PM, Benjamin Peterson wrote: > Denis Gomes gmail.com> writes: > > > > > > > Hey Benjamin, > > > > Take a look at this website I found about cached and in-memory > databases. I > think the gist of the article is that caching is good if you are doing > SELECTs > on data that is frequently used whereas in-memory speeds up > writes, (inserts and > updates) to the db as well as querying. Maybe I am missing something? > > Well, of course, but there's little point to doing INSERTs and UPDATEs if > you > don't write them to disk at some point. You could just have a long running > transaction which will not write to the database file (though depending on > how > you have sqlite setup it may write to a journal file) until you commit it. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin at python.org Mon Aug 30 18:27:16 2010 From: benjamin at python.org (Benjamin Peterson) Date: Mon, 30 Aug 2010 22:27:16 +0000 (UTC) Subject: python+sqlite3 in memory database References: <4c7c199d$0$1646$742ec2ed@news.sonic.net> Message-ID: John Nagle animats.com> writes: > "sqlite" has reasonably good SELECT performance on simple indices, > but anything beyond that isn't all that great. Multiple processes > updating the same sqlite database will have terrible performance, > because the locking mechanism not only locks the entire table, > the wait mechanism is a timed retry. This is been improved significantly in recent versions with support for write ahead logging and different lock levels to prevent writer starvation. From ldo at geek-central.gen.new_zealand Mon Aug 30 19:13:26 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 31 Aug 2010 11:13:26 +1200 Subject: Helper app for intranet site References: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> <61894f54-90ff-4e0e-9c81-860b6e9cdc15@p12g2000prn.googlegroups.com> Message-ID: In message <61894f54-90ff-4e0e-9c81-860b6e9cdc15 at p12g2000prn.googlegroups.com>, kevinlcarlson wrote: > On Aug 29, 8:46 pm, Lawrence D'Oliveiro > wrote: >> >> In message >> <45e0772c-24a8-4cbb-a4fc-74a1b6c25... at n19g2000prf.googlegroups.com>, >> kevinlcarlson wrote: >>> >>> I'm exploring the possibility of developing a helper app for an >>> existing internal company website. Basically, it would automatically >>> scan the current page contents, including prepopulated forms, and >>> provide context-related business rule comments to the user, via a stay- >>> on-top wxPython panel. >> >> Seems like a roundabout way of doing it. Can?t you integrate into the >> server code which is generating the page contents, instead of trying to >> reverse- engineer those contents? > > Absolutely - that would be the best way to accomplish this. > Unfortunately, our group has no access to the web server and the > developers have this functionality scheduled about a year into the > future, but we need it ASAP. Also, our group would like to be in > control of the code and business rule contents, rather than wait for > updates from the busy web team... Conway?s Law: any piece of software reflects the organizational structure that produced it. From ldo at geek-central.gen.new_zealand Mon Aug 30 19:17:09 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 31 Aug 2010 11:17:09 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> <7xr5hguzzi.fsf@ruckus.brouhaha.com> Message-ID: In message <7xr5hguzzi.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > JHC (experimental Haskell compiler) recently started using a mixture of > gc and region inference. It will be interesting to see how that works > out. That?s what people have been saying about garbage collection for about half a century: ?this new experimental technique will solve all the problems, just you wait and see?. Meanwhile, real-world programmers get on to writing real-world code that is productive and efficient on real-world systems. From aahz at pythoncraft.com Mon Aug 30 19:42:11 2010 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2010 16:42:11 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: In article <878w3ogpvq.fsf at benfinney.id.au>, Ben Finney wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> That reminds me: one co-worker (who really should have known better ;-) >> had the impression that sets were O(N) rather than O(1). > >For settling exactly this kind of confusion, Python's standard library >comes with a module, the timeit module. Your co-worker should have >known better: don't guess about timing performance, measure it. > >Or am I missing something here? Possibly; IMO, people should not need to run timeit to determine basic algorithmic speed for standard Python datatypes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From bradley.h at aggiemail.usu.edu Mon Aug 30 20:05:28 2010 From: bradley.h at aggiemail.usu.edu (Bradley Hintze) Date: Mon, 30 Aug 2010 20:05:28 -0400 Subject: Functions continuing to ru after returning something? Message-ID: I may be having a brain fart, but is it at all possible to have a function first return a value then continue its calculation. Like this simple example: my_var = 5 def my_function(): return my_var my_var +=1 This obviously won't work as written but is there a cleaver way around this. -- Bradley J. Hintze Graduate Student Duke University School of Medicine 801-712-8799 From python at mrabarnett.plus.com Mon Aug 30 20:12:09 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 01:12:09 +0100 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4C7C48D9.7020800@mrabarnett.plus.com> On 31/08/2010 01:05, Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. > Do you mean a generator? From no.email at nospam.invalid Mon Aug 30 21:09:50 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 18:09:50 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> <7xr5hguzzi.fsf@ruckus.brouhaha.com> Message-ID: <7xtymbzixt.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > Meanwhile, real-world programmers get on to writing real-world code that is > productive and efficient on real-world systems. It's pretty well established by now that GC doesn't have any significant speed penalty compared with manual allocation. It does consume more memory, which is acceptable a lot of the time. It certainly leads to more reliable programs. From no.email at nospam.invalid Mon Aug 30 21:14:32 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 18:14:32 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: <7xpqwzzipz.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > Possibly; IMO, people should not need to run timeit to determine basic > algorithmic speed for standard Python datatypes. Indeed. Alex Stepanov (designer of C++ Standard Template Library) was emphatic that algorithm complexity assertions should be part of the interface of any STL function: http://www.sgi.com/tech/stl/drdobbs-interview.html He also said it should be part of the "unwritten contract" between the module and its user, but I don't understand why he said "unwritten", since in the C++ STL the complexity statements are part of the written spec. From reply-to at works.fine.invalid Mon Aug 30 21:45:47 2010 From: reply-to at works.fine.invalid (NickC) Date: 31 Aug 2010 01:45:47 GMT Subject: Structured programming with optionParser Message-ID: <4c7c5eca$0$11121$c3e8da3@news.astraweb.com> I'm writing a short (200 lines) script that has half-a-dozen parameter options, and using optionParser to process the options. I try to write well-written procedural programmes with functions doing one thing well, and so on. The problem I'm getting is that, inevitably, the function that uses OptionParser ends up doing all the work. So, I have a brief 6-line main() that calls other functions, a setup(), a couple of ancillary functions, and a whopping doOptionParsing() that is over 100 lines long. doOptionParsing is doing all the work. I'm struggling to see how you could refactor the option parsing function. After all, it has to process the options, so it has to do all the setup for those options, and then process them. Does anyone have some sort of design pattern or standard template approach to doing option parsing? Or perhaps should I make optionParser variables global? Thanks, -- NickC From michael.a.powe at gmail.com Mon Aug 30 21:55:20 2010 From: michael.a.powe at gmail.com (naugiedoggie) Date: Mon, 30 Aug 2010 18:55:20 -0700 (PDT) Subject: Installing Python as Scripting Language in IIS Message-ID: <4154f088-f746-4891-83ee-f64138c81e2e@x25g2000yqj.googlegroups.com> Hello, Windows 2003, 64-bit, standard edition server with IIS 6.0. I followed the MS instruction sheets on setting up CGI application with Python as scripting engine. I'm just getting 404 for the test script, whereas an html file in the same virtual directory is properly displayed. Here: Creating Applications in IIS 6.0 (IIS 6.0) http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/bc0c4729-e892-4871-b8f3-fcbf489f2f09.mspx?mfr=true Setting Application Mappings in IIS 6.0 (IIS 6.0) http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/bc0c4729-e892-4871-b8f3-fcbf489f2f09.mspx?mfr=true I mapped the exe thus: c:\Python26\python.exe -u "%s %s" to extension `py' for all verbs and checked the `script engine' box. There are no errors in the script itself, i ran it from the command line to be sure. Further, I enabled ASP and tried using python as the scripting language. That generates this error: Active Server Pages error 'ASP 0129' Unknown scripting language /cgi/index.asp, line 1 The scripting language 'Python' is not found on the server. I can't find any good references for dealing with this, either. I've dicked around with this for so long, now I don't know which way is up, anymore. Any thoughts on where I might be going wrong, much appreciated. Thanks. mp From vicente.soler at gmail.com Mon Aug 30 22:00:24 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 30 Aug 2010 19:00:24 -0700 (PDT) Subject: Source code for itertools Message-ID: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> I'm interested in studying the itertools source code, especially the permutations function. However, I cannot find the library. Where could I find it? Running Python 3.1 Thank you From ldo at geek-central.gen.new_zealand Mon Aug 30 22:14:29 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 31 Aug 2010 14:14:29 +1200 Subject: Source code for itertools References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: In message <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8 at t20g2000yqa.googlegroups.com>, vsoler wrote: > I'm interested in studying the itertools source code, especially the > permutations function. > > However, I cannot find the library. Where could I find it? ldo at theon:python> apt-get source python3.1 Reading package lists... Done Building dependency tree Reading state information... Done Need to get 12.0MB of source archives. Get:1 http://ftp.nz.debian.org sid/main python3.1 3.1.2+20100829-1 (dsc) [1,776B] Get:2 http://ftp.nz.debian.org sid/main python3.1 3.1.2+20100829-1 (tar) [11.8MB] Get:3 http://ftp.nz.debian.org sid/main python3.1 3.1.2+20100829-1 (diff) [239kB] Fetched 12.0MB in 28s (417kB/s) dpkg-source: info: extracting python3.1 in python3.1-3.1.2+20100829 dpkg-source: info: unpacking python3.1_3.1.2+20100829.orig.tar.gz dpkg-source: info: applying python3.1_3.1.2+20100829-1.diff.gz ldo at theon:python> find . -iname \*itertools\* ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c ./python3.1-3.1.2+20100829/Lib/test/test_itertools.py ./python3.1-3.1.2+20100829/Lib/lib2to3/fixes/fix_itertools_imports.py ./python3.1-3.1.2+20100829/Lib/lib2to3/fixes/fix_itertools.py ./python3.1-3.1.2+20100829/Doc/library/itertools.rst From anand.shashwat at gmail.com Mon Aug 30 22:22:34 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Tue, 31 Aug 2010 07:52:34 +0530 Subject: Source code for itertools In-Reply-To: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: On Tue, Aug 31, 2010 at 7:30 AM, vsoler wrote: > I'm interested in studying the itertools source code, especially the > permutations function. > > However, I cannot find the library. Where could I find it? > > Running Python 3.1 > > Thank you > Either you can download it or browse it on the net. http://svn.python.org/view/python/trunk/Modules/itertoolsmodule.c?view=markup > -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Mon Aug 30 22:27:29 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 30 Aug 2010 19:27:29 -0700 (PDT) Subject: Source code for itertools References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: On 31 ago, 04:14, Lawrence D'Oliveiro wrote: > In message <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad... at t20g2000yqa.googlegroups.com>, vsoler wrote: > > > I'm interested in studying the itertools source code, especially the > > permutations function. > > > However, I cannot find the library. Where could I find it? > > ldo at theon:python> apt-get source python3.1 > Reading package lists... Done > Building dependency tree ? ? ? > Reading state information... Done > Need to get 12.0MB of source archives. > Get:1http://ftp.nz.debian.orgsid/main python3.1 3.1.2+20100829-1 (dsc) [1,776B] > Get:2http://ftp.nz.debian.orgsid/main python3.1 3.1.2+20100829-1 (tar) [11.8MB] > Get:3http://ftp.nz.debian.orgsid/main python3.1 3.1.2+20100829-1 (diff) [239kB] ? ? ? ? ? ? ? ? ? > Fetched 12.0MB in 28s (417kB/s) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > dpkg-source: info: extracting python3.1 in python3.1-3.1.2+20100829 > dpkg-source: info: unpacking python3.1_3.1.2+20100829.orig.tar.gz > dpkg-source: info: applying python3.1_3.1.2+20100829-1.diff.gz > ldo at theon:python> find . -iname \*itertools\* > ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c > ./python3.1-3.1.2+20100829/Lib/test/test_itertools.py > ./python3.1-3.1.2+20100829/Lib/lib2to3/fixes/fix_itertools_imports.py > ./python3.1-3.1.2+20100829/Lib/lib2to3/fixes/fix_itertools.py > ./python3.1-3.1.2+20100829/Doc/library/itertools.rst I was expecting an itertools.py file, but I don't see it in your list. I can instead see the test_itertools.py file, but my understanding is that it is not the file I am looking for. Is it possible that it is a built-in module whose source code is not available for watching it? Thank you very much From no.email at nospam.invalid Mon Aug 30 22:42:33 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 19:42:33 -0700 Subject: Source code for itertools References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: <7xmxs3sdt2.fsf@ruckus.brouhaha.com> vsoler writes: > I was expecting an itertools.py file, but I don't see it in your list. >> ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c looks promising. Lots of stdlib modules are written in C for speed or access to system facilities. From vicente.soler at gmail.com Mon Aug 30 23:06:31 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 30 Aug 2010 20:06:31 -0700 (PDT) Subject: Source code for itertools References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> <7xmxs3sdt2.fsf@ruckus.brouhaha.com> Message-ID: On 31 ago, 04:42, Paul Rubin wrote: > vsoler writes: > > I was expecting an itertools.py file, but I don't see it in your list. > >> ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c > > looks promising. ?Lots of stdlib modules are written in C for speed or > access to system facilities. Lawrence, Paul, You seem to be running a utility I am not familiar with. Perhaps this is because I am using Windows, and most likely you are not. How could I have found the answer in a windows environment? Thank you very much From michele.simionato at gmail.com Mon Aug 30 23:23:44 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 30 Aug 2010 20:23:44 -0700 (PDT) Subject: Structured programming with optionParser References: <4c7c5eca$0$11121$c3e8da3@news.astraweb.com> Message-ID: <5ff8c04d-6fbc-4385-af3c-92e2bef62c63@i13g2000yqd.googlegroups.com> On Aug 31, 3:45?am, NickC wrote: > I'm struggling to see how you could refactor the option parsing function. > After all, it has to process the options, so it has to do all the setup > for those options, and then process them. Perhaps plac could simplify your life, by removing most of the boilerplate of option parsing: http://pypi.python.org/pypi/plac From aweraw at gmail.com Mon Aug 30 23:28:23 2010 From: aweraw at gmail.com (Aidan) Date: Tue, 31 Aug 2010 13:28:23 +1000 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4c7c77b0$1@dnews.tpgi.com.au> Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. > def my_function(): my_var = 5 while my_var <= 10: yield my_var my_var += 1 >>> for x in my_function(): ... print x 5 6 7 8 9 10 >>> From darkrho at gmail.com Mon Aug 30 23:33:24 2010 From: darkrho at gmail.com (Rolando Espinoza La Fuente) Date: Mon, 30 Aug 2010 23:33:24 -0400 Subject: Source code for itertools In-Reply-To: References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> <7xmxs3sdt2.fsf@ruckus.brouhaha.com> Message-ID: On Mon, Aug 30, 2010 at 11:06 PM, vsoler wrote: > On 31 ago, 04:42, Paul Rubin wrote: >> vsoler writes: >> > I was expecting an itertools.py file, but I don't see it in your list. >> >> ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c >> >> looks promising. ?Lots of stdlib modules are written in C for speed or >> access to system facilities. > > Lawrence, Paul, > > You seem to be running a utility I am not familiar with. Perhaps this > is because I am using Windows, and most likely you are not. > > How could I have found the answer in a windows environment? Hard question. They are using standard unix utilities. But you can find the source file of a python module within python: >>> import itertools >>> print(itertools.__file__) /usr/lib/python2.6/lib-dynload/itertools.so Yours should point to a windows path. If the file ends with a ".py", you can open the file with any editor. If ends with ".so" or something else likely is a compiled module in C and you should search in the source distribution, not the binary distribution. Hope it helps. Regards, Rolando Espinoza La fuente www.insophia.com From brian.curtin at gmail.com Mon Aug 30 23:37:05 2010 From: brian.curtin at gmail.com (Brian Curtin) Date: Mon, 30 Aug 2010 22:37:05 -0500 Subject: Source code for itertools In-Reply-To: References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> <7xmxs3sdt2.fsf@ruckus.brouhaha.com> Message-ID: On Mon, Aug 30, 2010 at 22:06, vsoler wrote: > On 31 ago, 04:42, Paul Rubin wrote: > > vsoler writes: > > > I was expecting an itertools.py file, but I don't see it in your list. > > >> ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c > > > > looks promising. Lots of stdlib modules are written in C for speed or > > access to system facilities. > > Lawrence, Paul, > > You seem to be running a utility I am not familiar with. Perhaps this > is because I am using Windows, and most likely you are not. > > How could I have found the answer in a windows environment? > > Thank you very much > -- > http://mail.python.org/mailman/listinfo/python-list > You need to checkout the source from svn (or pull from applicable hg mirrors). For example: 1. svn co http://svn.python.org/projects/python/branches/release31-maint 2. open Modules/itertoolsmodule.c The C code for extension modules doesn't get distributed with the installers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From crebert at ucsd.edu Mon Aug 30 23:42:22 2010 From: crebert at ucsd.edu (Chris Rebert) Date: Mon, 30 Aug 2010 20:42:22 -0700 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: On Mon, Aug 30, 2010 at 5:05 PM, Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > ? ?return my_var > ? ?my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. And what do you want to happen with the code the value was returned to? Cheers, Chris From tjreedy at udel.edu Mon Aug 30 23:47:34 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Aug 2010 23:47:34 -0400 Subject: Source code for itertools In-Reply-To: References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: On 8/30/2010 10:27 PM, vsoler wrote: > I was expecting an itertools.py file, but I don't see it in your > list. The manual page has the original python source for each function. I recommend you look at that. Itertool was rewritten in C for speed but the C source will not tell you any more about the functions themselves. -- Terry Jan Reedy From michele.simionato at gmail.com Tue Aug 31 00:19:08 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 30 Aug 2010 21:19:08 -0700 (PDT) Subject: Structured programming with optionParser References: <4c7c5eca$0$11121$c3e8da3@news.astraweb.com> Message-ID: Perhaps, I should give an example of using plac. For instance, here is how you could implement a SVN-like tool with two commands ``checkout`` and ``commit``. The trick is to write a class with two methods ``checkout`` and ``commit`` and an attribute ``.commands`` listing them, and to call the class with ``plac.Interpreter.call``:: $ cat vcs.py class VCS(object): "A fictitious version control tool" commands = ['checkout', 'commit'] def checkout(self, url): return 'ok' def commit(self): return 'ok' if __name__ == '__main__': import plac; plac.Interpreter.call(VCS) The line ``plac.Interpreter.call`` instantiates the ``VCS`` class by passing to it the arguments in the command line and then calls the appropriate method. You can use the script as follows:: $ python vcs.py -h usage: vcs.py [-h] [args [args ...]] positional arguments: args optional arguments: -h, --help show this help message and exit $ python vcs.py checkout url ok $ python vcs.py commit ok plac_ takes care of parsing the command line, giving the correct error message if you pass wrong arguments or not enough arguments:: $ python vcs.py checkout usage: checkout url checkout: error: too few arguments You should realize that there is no real difference between a command-line argument parser featuring subcommands and an command interpreter, therefore the previous script also works as an interactive interpreter:: $ python vcs.py -i i> .help special commands ================ .help .last_tb custom commands =============== checkout commit i> checkout url ok i> commit ok There is full help support, i.e. you can ask for ``.help `` for any command, including the special ones such as ``.help`` and ``.last_tb``. There is full support for autocompletion and command history too, provided you have the readline library installed (on Unices) or the pyreadline library (on Windows). plac also support a batch mode: you can write a set of commands on a file and have them executed by the plac runner. :: $ echo vcs-commands.plac #!vcs.py:VCS checkout url # nontrivial commands here commit $ plac_runner.py --batch vcs-commands.plac ok skip # ok For more (including managing options, which I have not shown here) you should check the full documentation of plac. I have just uploaded release 0.7.2, which is required for this example to work. From rurpy at yahoo.com Tue Aug 31 00:44:06 2010 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 30 Aug 2010 21:44:06 -0700 (PDT) Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: <28a1b252-e0fb-4992-bfff-be9b3f99cffc@t2g2000yqe.googlegroups.com> On 08/30/2010 04:50 AM, Thomas Jollans wrote: > On Monday 30 August 2010, it occurred to rurpy at yahoo.com to exclaim: >> Face the facts dude. The Python docs have some major problems. >> They were pretty good when Python was a new, cool, project used >> by a handful of geeks. They are good relative to the "average" >> (whatever that is) open source project -- but that bar is so low >> as to be a string lying on the ground. > > Actually, the Python standard library reference manual is excellent. At least > that's my opinion. > > Granted, it's not necessarily the best in the world. It could probably be > better. But that goes for just about every documentation effort there is. > > What exactly are you comparing the Python docs to, I wonder? Obviously not > something like Vala, but that goes without saying. "kj" said that the Perl > docs were better. I can't comment on that. I also won't comment on the sorry > mess that the language "Perl" is, either. > There are a few documentation efforts that I recognize are actually better > than the Python docs: Firstly, the MSDN Library docs for the .Net framework. > Not that I refer to it much, but it is excellent, and it probably was a pretty > darn expensive project too. Secondly, the libc development manual pages on > Linux and the BSDs. Provided you know your way around the C library, they are > really a top-notch reference. The Postgresql docs have always seemed pretty good to me. And I'll second kj's nomination of Perl. The Perl docs have plenty of faults but many years ago I was able to learn Perl with nothing more than those docs. It was well over five years later that I ever got around to buying a commercial Perl book. In contrast, I made several, honest efforts to learn Python the same way but found it impossible and never got a handle on it until I bought Lutz's and Beazley's books. (Of which Bealey's was by far the most useful; Lutz became a doorstop pretty quickly. And yes, I knew about but didn't use the tutorial -- tutorials are one way of presenting information that aren't appropriate for everyone or in every situation, and the existence of one in no way excuses inadequate reference material.) If one is comparing the Python docs to others, comparing it to Beazley's book is informative. Most of the faults I find with the book are the places he took material from the Python docs nearly verbatim. The material he interprets and explains (usually quite tersely) is much clearer that similar material (if it even exists) in the Python docs. Finally, it it not really necessary to compare the Python docs to others to make a judgment -- simply looking at the hours taken to solve some problem that could have been avoided with a couple more sentences in the docs -- the number of hours spent trying figure out some behavior by pouring over the standard lib code -- the number of times one decides how to write code by "trying it", with fingers crossed that one isn't relying on some accidental effect that will change with the next version or platform -- these can give a pretty good indication of the magnitude of the doc problems. I think one reason for the frequent "Python docs are great" opinions here is that eventually one figures out the hard way how things work, and tends to rely less on the docs as documentation, and more as a memmonic. And for that the existing docs are adequate. From rurpy at yahoo.com Tue Aug 31 00:47:17 2010 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 30 Aug 2010 21:47:17 -0700 (PDT) Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On 08/30/2010 01:14 PM, Terry Reedy wrote: > On 8/30/2010 12:23 AM, rurpy at yahoo.com wrote: >> The Python docs have some major problems. > > And I have no idea what you think they are. I have written about a few of them here in the past. I sure Google will turn up something. > I have participated in 71 doc improvement issues on the tracker. Most of > those I either initiated or provided suggestions. How many have you > helped with? Certainly not 71. But there is, for example, http://bugs.python.org/issue1397474 Please note the date on it. From lamlbiro at optusnet.com.au Tue Aug 31 02:17:33 2010 From: lamlbiro at optusnet.com.au (L) Date: Tue, 31 Aug 2010 16:17:33 +1000 Subject: PyGeo In-Reply-To: References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> Message-ID: <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> On 30/08/10 18:59, Thomas Jollans wrote: > On Monday 30 August 2010, it occurred to L to exclaim: > >> I have tried it and as soon as you try any of the examples in the >> examples dir it cannot find numpy etc.... >> >> I have manually move the pygeo dirs and contents to >> /usr/lib/python2.6/dis-packages, >> >> (this is the directory where numpy, numeric and scipy were installed >> when using synaptic ) >> >> made sure that read and write permissions set for ALL FILES and >> DIRECTORIES to RW using sudo chmod 777 >> > Wait -- did you just try to use pymaxima, or did you properly (try to) install > the dependencies? > > You need VPython. It's in the ubuntu archives. > http://packages.ubuntu.com/lucid/python-visual > > And then you need to download and install pygeo. > http://pygeo.sourceforge.net/download.html > It probably uses distutils, so you'd extract the source archive and run > sudo python setup.py install > > If THAT gives you any errors, then please come back here, with the exact error > messages. If it works, then PyGeo should be installed. If it still doesn't > work, then there's certainly a chance it won't work, but you can still ask > here for help, with the exact error messages, so we have something to build > upon when trying to figure out what's wrong. > > - Thomas > No, I have not tried pymaxma ( I have maxima and wxmaxima install via synaptic, tested and all works OK) yes, that is what I did for install. Vpython already install via synaptic, ran a number of examples and all produced the expected output. also the PyGeo readme text mentions Numerical python (I think it means Numeric, but I also have NumPy installed) to install i did the following steps PyGeo downloaded form sourceforge tar xvfc PyGeo-1.0a1.tar.gz cd PyGeo-1.0a1 python setup.py install NO ERROR MESSAGES ecountered IT DID NOT WORK coplaing about the NUMERIC module I repeated the install and issued the parameter to 'python steup.py install.....) to force the directory name to be the same where the other python modules are (see listing below) NO ERROR MESSAGES ecountered Note what I did to ensure permissions etc (see my second post for directories etc) install successful, but running the example from ...examples/real/ using IDLE I get IDLE 2.6.5 ==== No Subprocess ==== >>> Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/pygeo/examples/real/dandelinspheres2.py", line 2, in from pygeo.base.abstract_elements_real import _Sphere, _Point File "/usr/lib/python2.6/dist-packages/pygeo/__init__.py", line 3, in from pygeo.vpyframe import display File "/usr/lib/python2.6/dist-packages/pygeo/vpyframe.py", line 38, in class display( visual.ui.display): AttributeError: 'module' object has no attribute 'ui' >>> /usr/lib/python2.6/dist-packages has the following directories and permissions.... drwxr-xr-x 2 root root 4096 2010-04-29 22:42 appindicator drwxr-xr-x 3 root root 4096 2010-04-29 22:43 apport drwxr-xr-x 2 root root 4096 2010-07-29 17:56 AppTools-3.3.0.egg-info drwxr-xr-x 3 root root 4096 2010-08-10 12:43 apt drwxr-xr-x 2 root root 4096 2010-04-29 22:43 aptdaemon drwxr-xr-x 2 root root 4096 2010-08-10 12:43 aptsources drwxr-xr-x 3 root root 4096 2010-04-29 22:43 AptUrl drwxr-xr-x 5 root root 4096 2010-07-28 21:14 butterfly drwxr-xr-x 5 root root 4096 2010-04-29 22:41 checkbox drwxr-xr-x 2 root root 4096 2010-04-29 22:43 checkbox_gtk drwxr-xr-x 2 root root 4096 2010-04-29 22:43 CommandNotFound drwxr-xr-x 2 root root 4096 2010-08-10 12:43 computerjanitor drwxr-xr-x 3 root root 4096 2010-04-29 22:42 configglue drwxr-xr-x 2 root root 4096 2010-04-29 22:42 configglue-0.2dev.egg-info drwxr-xr-x 7 root root 4096 2010-04-29 22:42 Crypto drwxr-xr-x 7 root root 4096 2010-04-29 22:44 desktopcouch drwxr-xr-x 2 root root 4096 2010-08-28 17:36 distribute-0.6.10.egg-info drwxr-xr-x 2 root root 4096 2010-08-10 12:43 DistUpgrade drwxr-xr-x 3 root root 4096 2010-08-28 17:36 DistUtilsExtra drwxr-xr-x 26 root root 4096 2010-07-29 17:56 enthought drwxr-xr-x 2 root root 4096 2010-07-29 17:56 EnthoughtBase-3.0.3.egg-info drwxr-xr-x 2 root root 4096 2010-07-29 17:56 EnvisageCore-3.1.1.egg-info drwxr-xr-x 2 root root 4096 2010-07-29 17:56 EnvisagePlugins-3.1.1.egg-info drwxr-xr-x 2 root root 4096 2010-08-15 11:38 GDebi drwxr-xr-x 7 root root 4096 2010-04-29 22:28 glchess drwxr-xr-x 2 root root 4096 2010-04-29 22:43 gnome_app_install-0.4.2ubuntu2.egg-info drwxr-xr-x 2 root root 4096 2010-04-29 22:43 GnomeCodecInstall drwxr-xr-x 3 root root 4096 2010-04-29 22:28 gnome_sudoku drwxr-xr-x 2 root root 4096 2010-08-28 18:02 Gnuplot drwxr-xr-x 3 root root 4096 2010-04-29 22:32 gst-0.10 drwxr-xr-x 3 root root 4096 2010-04-29 22:32 gtk-2.0 drwxr-xr-x 4 root root 4096 2010-07-28 21:14 gwibber drwxr-xr-x 2 root root 4096 2010-04-29 22:42 indicate drwxr-xr-x 3 root root 4096 2010-07-29 17:56 integrationtests drwxr-xr-x 2 root root 4096 2010-07-28 21:14 jockey drwxr-xr-x 2 root root 4096 2010-07-29 20:31 kiki drwxr-xr-x 3 root root 4096 2010-07-28 21:14 LanguageSelector drwxr-xr-x 3 root root 4096 2010-08-11 16:45 lxml drwxr-xr-x 2 root root 4096 2010-07-29 17:56 Mayavi-3.3.0.egg-info drwxr-xr-x 5 root root 4096 2010-04-29 22:42 mx *drwxr-xr-x 7 root root 4096 2010-08-28 18:03 Numeric drwxr-xr-x 13 root root 4096 2010-07-29 17:56 numpy* drwxr-xr-x 2 root root 4096 2010-08-28 18:03 NumTut drwxr-xr-x 2 root root 4096 2010-04-29 22:42 NvidiaDetector drwxr-xr-x 2 root root 4096 2010-04-29 22:41 oauth drwxr-xr-x 2 root root 4096 2010-04-29 22:41 oauth-1.0a.egg-info drwxr-xr-x 2 root root 4096 2010-04-29 22:43 Onboard drwxr-xr-x 2 root root 4096 2010-08-15 11:38 packagekit drwxr-xr-x 2 root root 12288 2010-08-28 18:02 PIL drwxr-xr-x 2 root root 4096 2010-07-28 21:14 pyatspi *drwxrwx--- 11 root lou 4096 2010-08-29 12:49 pygeo* drwxr-xr-x 2 root root 4096 2010-08-28 17:36 python_distutils_extra-2.18.egg-info drwxr-xr-x 2 root root 4096 2010-08-28 18:03 pytz drwxr-xr-x 2 root root 4096 2010-08-28 18:03 pytz-2010b.egg-info drwxr-xr-x 7 root root 4096 2010-08-11 16:45 reportlab drwxr-xr-x 16 root root 4096 2010-08-28 18:03 Scientific drwxr-xr-x 23 root root 4096 2010-08-28 18:03 scipy drwxr-xr-x 2 root root 4096 2010-04-29 22:43 ScreenResolution drwxr-xr-x 2 root root 4096 2010-04-29 22:42 serial drwxr-xr-x 4 root root 4096 2010-08-28 17:36 setuptools drwxr-xr-x 4 root root 4096 2010-08-15 11:38 softwareproperties drwxr-xr-x 2 root root 4096 2010-04-29 22:41 speechd drwxr-xr-x 2 root root 4096 2010-04-29 22:41 speechd_config drwxr-xr-x 9 root root 4096 2010-08-28 18:03 tables drwxr-xr-x 5 root root 4096 2010-04-29 22:42 telepathy drwxr-xr-x 2 root root 4096 2010-07-29 17:56 Traits-3.2.0.egg-info drwxr-xr-x 2 root root 4096 2010-07-29 17:56 TraitsBackendWX-3.2.0.egg-info drwxr-xr-x 2 root root 4096 2010-07-29 17:56 TraitsGUI-3.1.0.egg-info drwxr-xr-x 18 root root 4096 2010-04-29 22:43 twisted drwxr-xr-x 5 root root 4096 2010-07-28 21:14 ubuntuone drwxr-xr-x 2 root root 4096 2010-08-05 16:41 UbuntuSystemService drwxr-xr-x 10 root root 4096 2010-08-24 11:21 ubuntutweak drwxr-xr-x 2 root root 4096 2010-08-24 11:21 ubuntu_tweak-0.5.6.egg-info drwxr-xr-x 2 root root 4096 2010-04-29 22:41 ufw drwxr-xr-x 4 root root 4096 2010-08-15 11:38 UpdateManager drwxr-xr-x 4 root root 4096 2010-04-29 22:43 usbcreator drwxr-xr-x 2 root root 4096 2010-08-11 17:04 visual drwxr-xr-x 4 root root 4096 2010-07-29 17:49 wx-2.6-gtk2-unicode drwxr-xr-x 4 root root 4096 2010-07-29 17:49 wx-2.8-gtk2-unicode drwxr-xr-x 6 root root 4096 2010-07-29 20:31 wxglade drwxr-xr-x 2 root root 4096 2010-04-29 22:42 XKit drwxr-xr-x 3 root root 4096 2010-04-29 22:43 zope drwxr-xr-x 2 root root 4096 2010-04-29 22:43 zope.interface-3.5.3.egg-info does this help somewhat?? From arnodel at googlemail.com Tue Aug 31 03:01:22 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 31 Aug 2010 08:01:22 +0100 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> <7xpqwzzipz.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > aahz at pythoncraft.com (Aahz) writes: >> Possibly; IMO, people should not need to run timeit to determine basic >> algorithmic speed for standard Python datatypes. > > Indeed. Alex Stepanov (designer of C++ Standard Template Library) was > emphatic that algorithm complexity assertions should be part of the > interface of any STL function: > > http://www.sgi.com/tech/stl/drdobbs-interview.html > > He also said it should be part of the "unwritten contract" between the > module and its user, but I don't understand why he said "unwritten", > since in the C++ STL the complexity statements are part of the written > spec. The spec is written, not the contract :) -- Arnaud From maxwellhansen at hotmail.com Tue Aug 31 03:56:00 2010 From: maxwellhansen at hotmail.com (Maxwell Hansen) Date: Tue, 31 Aug 2010 00:56:00 -0700 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4c7ca51f$0$2504$815e3792@news.qwest.net> On 08/30/2010 05:05 PM, Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. > return stops execution of any code remaining in the function, but just out of curiosity, why do you need to do this? From nikos.the.gr33k at gmail.com Tue Aug 31 04:02:33 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Tue, 31 Aug 2010 01:02:33 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> Message-ID: <0a7d62f1-6a0a-42d2-88c6-f0f42ef24aab@m1g2000yqo.googlegroups.com> On 30 ???, 20:48, Rami Chowdhury wrote: > On Mon, Aug 30, 2010 at 23:36, Nik the Greek wrote: > > > > > > > > > > > # initialize cookie > > cookie = SimpleCookie() > > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > visitor = cookie.get('visitor') > > > This statement > > > if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > > spider|crawl)', host ) is None: > > > produces the following error: > > > ?/home/webville/public_html/cgi-bin/counter.py > > ? 93 # do not increment the counter if a Cookie is set to the > > visitors browser already > > ? 94 # > > =========================================================================== ====================================== > > ? 95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > > spider|crawl)', host ) is None: > > ? 96 > > ? 97 ? ? ? ? print visitor > > visitor = None, visitor.value undefined, re = > lib64/python2.4/re.pyc'>, re.search = , host = > > '178-128-217.dynamic.cyta.gr', builtin None = None > > > Why visitor.value is undefined? > > Because, as the traceback tells you, visitor is None. As you said, the > cookie is not recognized. Try inserting the following line at the top > of your script: > > print "Content-type:text/html\r\n\r\n", os.environ.get('HTTP_COOKIE', > 'NO COOKIE DATA') > > That should give you the value of the cookie, which might help you > debug why it is not being loaded. > > -- > Rami Chowdhury > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) Unfortunately it produces an Internal Server Error :( From __peter__ at web.de Tue Aug 31 04:03:54 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 31 Aug 2010 10:03:54 +0200 Subject: Functions continuing to ru after returning something? References: Message-ID: Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around > this. >>> n = 1 >>> def f(): ... global n ... try: ... return n ... finally: ... n += 1 ... >>> f() 1 >>> f() 2 >>> f() 3 However, I would prefer the generator as Aidan has shown because it doesn't rely on a global variable. Peter From nikos.the.gr33k at gmail.com Tue Aug 31 04:07:56 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Tue, 31 Aug 2010 01:07:56 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: On 30 ???, 20:50, MRAB wrote: > On 30/08/2010 18:16, Nik the Greek wrote: > > > > > > > > > > > On 30 ???, 19:41, MRAB ?wrote: > >> On 30/08/2010 04:33, Nik the Greek wrote: > > >>> On 30 ???, 06:12, MRAB ? ?wrote: > > >>>> This part: > > >>>> ? ? ? ?( not mycookie or mycookie.value != 'nikos' ) > > >>>> is false but this part: > > >>>> ? ? ? ?re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > >>>> is true because host doesn't contain any of those substrings. > > >>> So, the if code does executed because one of the condition is true? > > >>> How should i write it? > > >>> I cannot think clearly on this at all. > > >>> I just wan to tell it to get executed ?ONLY IF > > >>> the cookie values is not 'nikos' > > >>> or ( don't knwo if i have to use and or 'or' here) > > >>> host does not contain any of the substrings. > > >>> What am i doign wrong?! > > >> It might be clearer if you reverse the condition and say: > > >> ? ? ? me_visiting = ... > >> ? ? ? if not me_visiting: > >> ? ? ? ? ? ... > > > I don't understand what are you trying to say > > > Please provide a full example. > > > You mean i should try it like this? > > > unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn| > > yandex|13448|spider|crawl)', host ) not None: > > > But isnt it the same thing like the if? > > My point is that the logic might be clearer to you if you think first > about how you know when you _are_ the visitor. Well my idea was to set a cookie on my browser with the name visitor and a value of "nikos" and then check each time that cooki. if value is "nikos" then dont count! I could also pass an extra url string like http://webville.gr?show=nikos and check that but i dont like the idea very much of giving an extra string each time i want to visit my webpage. So form the 2 solution mentioned the 1st one is better but cant come into action for some reason. Aprt form those too solution i cant think of anyhting else that would identify me and filter me out of the actual guest of my website. I'm all ears if you can think of something else. From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 31 04:18:56 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 31 Aug 2010 10:18:56 +0200 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4c7cbacb$0$4541$426a34cc@news.free.fr> Peter Otten a ?crit : >>>> n = 1 >>>> def f(): > ... global n > ... try: > ... return n > ... finally: > ... n += 1 > ... The same without a global: def f(_n=[0]): try: return _n[0] finally: _n[0] += 1 But yeps, using a generator would be better. From sandricionut at yahoo.com Tue Aug 31 04:25:50 2010 From: sandricionut at yahoo.com (sandric ionut) Date: Tue, 31 Aug 2010 01:25:50 -0700 (PDT) Subject: sendmail error Message-ID: <284495.60490.qm@web51302.mail.re2.yahoo.com> Hello: I have a script for sending email from python (it is attached bellow). When I am launching the script I get the error: TypeError: cannot concatenate 'str' and 'type' objects if I use sys.argv[1], but if I input from the begging an email address like "email at email.com", the script is working OK What could be the problem? Thank you, Ionut import mesaj = email.MIMEMultipart.MIMEMultipart() fromEmail = sys.argv[ toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ mesaj[ mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ atasament = r"Date"] = email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = email.MIMEBase.MIMEBase( atasamentP.set_payload(open(atasament, email.Encoders.encode_base64(atasamentP) atasamentP.add_header( mesaj.attach(atasamentP) mesaj.attach(email.MIMEText.MIMEText( smtpObj = smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attachement; filename="%s"'% os.path.basename(atasament))"Email transmis la data: ", email.Utils.formatdate(localtime=False)))"192.168.1.2")try smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ smtplib.SMTPException -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Tue Aug 31 04:25:52 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 31 Aug 2010 01:25:52 -0700 Subject: Functions continuing to ru after returning something? References: Message-ID: <7x62yrtchb.fsf@ruckus.brouhaha.com> Bradley Hintze writes: > my_var = 5 > def my_function(): > return my_var > my_var +=1 def my_function(): temp = my_var my_var += 1 return temp From brendan.simon at etrix.com.au Tue Aug 31 04:49:53 2010 From: brendan.simon at etrix.com.au (Brendan Simon (eTRIX)) Date: Tue, 31 Aug 2010 18:49:53 +1000 Subject: Can't find elements using ElementTree find method Message-ID: <4C7CC231.1040403@etrix.com.au> I am trying to use ElementTree (with Python 2.7) and can't seem to find elements at the top level. The find() and findall() methods seem to find elements within the top level, but not if it the elements are at the top level. How do I find top level elements ?? Here is my code. import xml.etree.ElementTree as ET xml = '''\ Fred Australia ''' root = ET.fromstring( xml ) ### This pattern is not found :( comps = root.find( './/components' ) ### These patterns are found ok :) comp = root.find( './/component' ) name = root.find( './/name' ) print 'comps =', comps print 'comp =', comp print 'name =', name Thanks, Brendan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitinpawar432 at gmail.com Tue Aug 31 04:57:21 2010 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Tue, 31 Aug 2010 14:27:21 +0530 Subject: Can't find elements using ElementTree find method In-Reply-To: <4C7CC231.1040403@etrix.com.au> References: <4C7CC231.1040403@etrix.com.au> Message-ID: Try using getroot() I think your root is components so its searching in root On Tue, Aug 31, 2010 at 2:19 PM, Brendan Simon (eTRIX) < brendan.simon at etrix.com.au> wrote: > I am trying to use ElementTree (with Python 2.7) and can't seem to find > elements at the top level. The find() and findall() methods seem to find > elements within the top level, but not if it the elements are at the top > level. > > How do I find top level elements ?? > Here is my code. > > import xml.etree.ElementTree as ET > > xml = '''\ > > > > Fred > Australia > > > ''' > > root = ET.fromstring( xml ) > > ### This pattern is not found :( > comps = root.find( './/components' ) > > ### These patterns are found ok :) > comp = root.find( './/component' ) > name = root.find( './/name' ) > > print 'comps =', comps > print 'comp =', comp > print 'name =', name > > > Thanks, Brendan. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Aug 31 05:00:41 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Aug 2010 11:00:41 +0200 Subject: Can't find elements using ElementTree find method In-Reply-To: <4C7CC231.1040403@etrix.com.au> References: <4C7CC231.1040403@etrix.com.au> Message-ID: Brendan Simon (eTRIX), 31.08.2010 10:49: > I am trying to use ElementTree (with Python 2.7) and can't seem to find > elements at the top level. The find() and findall() methods seem to > find elements within the top level, but not if it the elements are at > the top level. > > How do I find top level elements ?? > Here is my code. > > import xml.etree.ElementTree as ET > > xml = '''\ > > > > Fred > Australia > > > ''' > > root = ET.fromstring( xml ) > > ### This pattern is not found :( > comps = root.find( './/components' ) "." matches the current element, so the path expression looks for all "components" nodes *below* the current element. You can either wrap the root in an ElementTree and search globally (i.e. without the leading "."), or you can test the root node yourself. Stefan From thomas at jollybox.de Tue Aug 31 06:23:24 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 12:23:24 +0200 Subject: PyGeo In-Reply-To: <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> Message-ID: <201008311223.24696.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to L to exclaim: > Traceback (most recent call last): > File > "/usr/lib/python2.6/dist-packages/pygeo/examples/real/dandelinspheres2.py", > line 2, in > from pygeo.base.abstract_elements_real import _Sphere, _Point > File "/usr/lib/python2.6/dist-packages/pygeo/__init__.py", line 3, in > > from pygeo.vpyframe import display > File "/usr/lib/python2.6/dist-packages/pygeo/vpyframe.py", line 38, > in > class display( visual.ui.display): > AttributeError: 'module' object has no attribute 'ui' THAT's the information I was waiting for. So, it looks like everything is working together, except that the visual module appears to have changed somewhat since PyGeo was written. Importing "visual" within PyGeo appears to have worked, but "visual.ui" doesn't exist. After having a brief look at the documentation, I found no mention of a "ui" object, but there appears to be visual.display -- so, if you wanted to port the package to the latest VPython, that would be a place to start: replace "visual.ui.display" with "visual.display", and try again. And the fix the next problem, and so on, until it works, when you can send a patch to the old maintainer. http://www.vpython.org/webdoc/visual/index.html - Thomas From brendan.simon at etrix.com.au Tue Aug 31 06:51:53 2010 From: brendan.simon at etrix.com.au (Brendan Simon (eTRIX)) Date: Tue, 31 Aug 2010 20:51:53 +1000 Subject: Can't find elements using ElementTree find method In-Reply-To: References: <4C7CC231.1040403@etrix.com.au> Message-ID: <4C7CDEC9.8080805@etrix.com.au> I can't use getroot() when using fromstring() -- as fromstring() returns an Element, not an ElementTree object. Yes, my root is the 'components' element, but find() seems to insist on searching for sub-elements. Ideally, I would like root.find('components') or root.find('./components') to find the components element at the top-level. I'd also like to be able to do root.find('./components/component') or root.find('./components/component/name') and so on. I guess I just have to check that root.tag == 'components' first, then search for './component', './component/name' and so on. It's a bit ugly, but heaps better than using minidom :) Cheers, Brendan. On 31/08/10 6:57 PM, Nitin Pawar wrote: > Try using getroot() > > I think your root is components so its searching in root > > On Tue, Aug 31, 2010 at 2:19 PM, Brendan Simon (eTRIX) > > wrote: > > I am trying to use ElementTree (with Python 2.7) and can't seem to > find elements at the top level. The find() and findall() methods > seem to find elements within the top level, but not if it the > elements are at the top level. > > How do I find top level elements ?? > Here is my code. > > import xml.etree.ElementTree as ET > > xml = '''\ > > > > Fred > Australia > > > ''' > > root = ET.fromstring( xml ) > > ### This pattern is not found :( > comps = root.find( './/components' ) > > ### These patterns are found ok :) > comp = root.find( './/component' ) > name = root.find( './/name' ) > > print 'comps =', comps > print 'comp =', comp > print 'name =', name > > > Thanks, Brendan. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Nitin Pawar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Aug 31 07:49:29 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 31 Aug 2010 07:49:29 -0400 Subject: sendmail error In-Reply-To: <284495.60490.qm@web51302.mail.re2.yahoo.com> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> Message-ID: <4C7CEC49.9030209@ieee.org> sandric ionut wrote: > Hello: > > I have a script for sending email from python (it is attached bellow). When I am > launching the script I get the error: > TypeError: cannot concatenate 'str' and 'type' objects if I use sys.argv[1], but > if I input from the begging an email address like "email at email.com", the script > is working OK > > What could be the problem? > > Thank you, > > Ionut > > import > mesaj = email.MIMEMultipart.MIMEMultipart() > fromEmail = sys.argv[ > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > mesaj[ > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > atasament = r"Date"] = > email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = > email.MIMEBase.MIMEBase( > atasamentP.set_payload(open(atasament, > email.Encoders.encode_base64(atasamentP) > atasamentP.add_header( > mesaj.attach(atasamentP) > mesaj.attach(email.MIMEText.MIMEText( > smtpObj = > smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attachement; > filename="%s"'% os.path.basename(atasament))"Email transmis la data: ", > email.Utils.formatdate(localtime=False)))"192.168.1.2")try > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ > smtplib.SMTPException > > > Three things: When quoting code, do it exactly, and without wordwrap in your mail program. There are so many typos in that code sample that it's useless, presumably because you didn't use copy/paste. When quoting an error message, get it all. Since you omit the stacktrace part, we can't tell what line might be giving you that error. Once you've noticed which line, just examine the types of each of the elements you're combining. If you're using the + operator, and the left operand is a string, then the right one must also be string. Figure out why it's not and you have your own answer. DaveA > > From giacomo.boffi at polimi.it Tue Aug 31 08:21:32 2010 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Tue, 31 Aug 2010 14:21:32 +0200 Subject: PyGeo References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> Message-ID: <86bp8j7z1v.fsf@aiuole.stru.polimi.it> L writes: > also the PyGeo readme text mentions Numerical python (I think it > means Numeric, but I also have NumPy installed) afaict, Numerical python is numpy --- if you look at pygeo home page, the reference to Numerical python is a link to numpy home page on the contrary, there is no "import numpy" in all the sources of pygeo, and a couples or so of "import Numeric", so that the situation is unclear aiuole/../PyGeo-1.0a1 $ find build| grep py$ | xargs grep -n import'.*'numpy aiuole/../PyGeo-1.0a1 $ find build| grep py$ | xargs grep -n import'.*'Numeric build/lib.linux-i686-2.6/pygeo/base/pygeomath.py:1:import Numeric as N build/lib.linux-i686-2.6/pygeo/base/wiresphere.py:2:import Numeric aiuole/../PyGeo-1.0a1 $ to complicate matters, it is not possible to install python-numeric using the apt system on debian unstable i don't know if it is possible to build numeric against the default python (2.6) on my system, further i don't know if it is worthwhile because, at a first sight, it looks like pygeo does not use advanced features of numeric, and replacing numeric with numpy should be very easy From malaclypse2 at gmail.com Tue Aug 31 08:24:55 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 31 Aug 2010 08:24:55 -0400 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: On Mon, Aug 30, 2010 at 7:42 PM, Aahz wrote: > Possibly; IMO, people should not need to run timeit to determine basic > algorithmic speed for standard Python datatypes. http://wiki.python.org/moin/TimeComplexity takes a stab at it. IIRC, last time this came up, there was some resistance to making promises about time complexity in the official docs, since that would make those numbers part of the language, and thus binding on other implementations. -- Jerry From sandricionut at yahoo.com Tue Aug 31 08:57:14 2010 From: sandricionut at yahoo.com (sandric ionut) Date: Tue, 31 Aug 2010 05:57:14 -0700 (PDT) Subject: Fw: sendmail error In-Reply-To: <4C7CEC49.9030209@ieee.org> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <4C7CEC49.9030209@ieee.org> Message-ID: <191591.90081.qm@web51308.mail.re2.yahoo.com> ----- Forwarded Message ---- From: sandric ionut To: Dave Angel Sent: Tue, August 31, 2010 3:56:40 PM Subject: Re: sendmail error ________________________________ From: Dave Angel To: sandric ionut Cc: Python List Sent: Tue, August 31, 2010 2:49:29 PM Subject: Re: sendmail error The code was COPY and PASTE -> presume wrong ?? When quoting an error message, get it all.? Since you omit the stacktrace part, we can't tell what line might be giving you that error That is all the error code!!! ??? Once you've noticed which line, just examine the types of each of the elements you're combining.? If you're using the + operator, and the left operand is a string, then the right one must also be string.? Figure out why it's not and you have your own answer Do you really think that I didn't do it? What a... response. This + or , is really USELESS. Please don't bother to send useless replays This is the line where I get the error: smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) I.S. DaveA >? ? ? ? sandric ionut wrote: > Hello: > > I have a script for sending email from python (it is attached bellow). When I >am launching the script I get the error: > TypeError: cannot concatenate 'str' and 'type' objects if I use sys.argv[1], >but if I input from the begging an email address like "email at email.com", the >script is working OK > > What could be the problem? > > Thank you, > > Ionut > > import > mesaj = email.MIMEMultipart.MIMEMultipart() > fromEmail = sys.argv[ > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > mesaj[ > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > atasament = r"Date"] = >email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = >email.MIMEBase.MIMEBase( > atasamentP.set_payload(open(atasament, > email.Encoders.encode_base64(atasamentP) > atasamentP.add_header( > mesaj.attach(atasamentP) > mesaj.attach(email.MIMEText.MIMEText( > smtpObj = >smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attachement; > >? filename="%s"'% os.path.basename(atasament))"Email transmis la data: ", >email.Utils.formatdate(localtime=False)))"192.168.1.2")try > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ >smtplib.SMTPException > > >? ? Three things:? When quoting code, do it exactly, and without wordwrap in your mail program.? There are so many typos in that code sample that it's???? useless, presumably because you didn't use copy/paste -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.kapps at web.de Tue Aug 31 09:41:23 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Tue, 31 Aug 2010 15:41:23 +0200 Subject: Fw: sendmail error In-Reply-To: <191591.90081.qm@web51308.mail.re2.yahoo.com> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <4C7CEC49.9030209@ieee.org> <191591.90081.qm@web51308.mail.re2.yahoo.com> Message-ID: <4C7D0683.9000409@web.de> sandric ionut wrote: >> Three things: When quoting code, do it exactly, and without wordwrap >> in your mail program. There are so many typos in that code sample that >> it's useless, presumably because you didn't use copy/paste > > The code was COPY and PASTE -> presume wrong > >> When quoting an error message, get it all. Since you omit the >> stacktrace part, we can't tell what line might be giving you that error > > That is all the error code!!! > >> Once you've noticed which line, just examine the types of each of >> the elements you're combining. If you're using the + operator, and the >> left operand is a string, then the right one must also be string. >> Figure out why it's not and you have your own answer > > Do you really think that I didn't do it? What a... response. This + or , > is really USELESS. Please don't bother to send useless replays > This is the line where I get the error: smtpObj.sendmail(fromEmail, > toEmail, mesaj.as_string()) Indeed, what a response. But from you. Do you always attack people who tried to help you? Dave Angel, gave you a very useful hint on how to debug such errors. In particular, he asked you to paste the *full* traceback. And if your mail/news client messes up the code so heavily, it's probably time to move to a better client. And the mention of + is not useless. If you would have tried a little harder, you would probably find, that concatenating a string and an exception object, gives exactly the error you got. So, the problem is probably here: print "eroare: " + smtplib.SMTPException Instead you want something like: except smtplib.SMTPException, msg print "eroare: " + msg If you are sure, that's not the line which gave the error, again, post the *full* traceback. Next time, show a little more civility and follow the advices you got. "Help us, to help you." is the word. HTH From thomas at jollybox.de Tue Aug 31 09:46:58 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 15:46:58 +0200 Subject: sendmail error In-Reply-To: <284495.60490.qm@web51302.mail.re2.yahoo.com> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> Message-ID: <201008311546.59595.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to sandric ionut to exclaim: > Hello: > > I have a script for sending email from python (it is attached bellow). When > I am launching the script I get the error: > TypeError: cannot concatenate 'str' and 'type' objects if I use > sys.argv[1], but if I input from the begging an email address like > "email at email.com", the script is working OK > > What could be the problem? > > Thank you, > > Ionut > > import > mesaj = email.MIMEMultipart.MIMEMultipart() > fromEmail = sys.argv[ > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > mesaj[ > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > atasament = r"Date"] = > email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = > email.MIMEBase.MIMEBase( > atasamentP.set_payload(open(atasament, > email.Encoders.encode_base64(atasamentP) > atasamentP.add_header( > mesaj.attach(atasamentP) > mesaj.attach(email.MIMEText.MIMEText( > smtpObj = > smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attach > ement; filename="%s"'% os.path.basename(atasament))"Email transmis la data: > ", email.Utils.formatdate(localtime=False)))"192.168.1.2")try > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ > smtplib.SMTPException I struggle to imagine what one might do to a piece of code to garble it this badly. If this was actually the script you're trying to run, then it would have blown up in your face with a angry SyntaxError, not the helpful TypeError you quoted. As far as I can see, you never actually use sys.argv[1], so this can't be the right code. To paraphrase what you failed to spell correctly in your other message, please don't bother sending useless inquiries to this list. If you want to get a useful reply, please: - Quote the code correctly. Before sending, check that it actually makes sense. The above is quite simply nothing like Python. - Quote the entire stack trace and error message. You might have looked at it already, but we haven't. This information is not useless! Also, when replying: - Quote properly. While top posting is discouraged, the most important bit is to clearly distinguish quoted material from new material. Make it possible from the structure of the message you're sending which parts you wrote and which parts you're just quoting. - Keep your reply on-list. - Thomas From aahz at pythoncraft.com Tue Aug 31 10:09:30 2010 From: aahz at pythoncraft.com (Aahz) Date: 31 Aug 2010 07:09:30 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: In article , Jerry Hill wrote: >On Mon, Aug 30, 2010 at 7:42 PM, Aahz wrote: >> >> Possibly; IMO, people should not need to run timeit to determine basic >> algorithmic speed for standard Python datatypes. > >http://wiki.python.org/moin/TimeComplexity takes a stab at it. IIRC, >last time this came up, there was some resistance to making promises >about time complexity in the official docs, since that would make >those numbers part of the language, and thus binding on other >implementations. I'm thoroughly aware of that page and updated it yesterday to make it easier to find. ;-) However, I think there are some rock-bottom basic guarantees we can make regardless of implementation. Does anyone seriously think that an implementation would be accepted that had anything other than O(1) for index access into tuples and lists? Dicts that were not O(1) for access with non-pathological hashing? That we would accept sets having O() performance worse than dicts? I suggest that we should agree on these guarantees and document them in the core. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From stefan_ml at behnel.de Tue Aug 31 10:19:49 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Aug 2010 16:19:49 +0200 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: Jerry Hill, 31.08.2010 14:24: > On Mon, Aug 30, 2010 at 7:42 PM, Aahz wrote: >> Possibly; IMO, people should not need to run timeit to determine basic >> algorithmic speed for standard Python datatypes. > > http://wiki.python.org/moin/TimeComplexity takes a stab at it. IIRC, > last time this came up, there was some resistance to making promises > about time complexity in the official docs, since that would make > those numbers part of the language, and thus binding on other > implementations. The docs start getting clearer about what's language specification and what's implementation specific to CPython, so that would just add another couple of CPython-only bits to what's there already. Although I do consider facts like list indexing being O(1) pretty much at the language-rather-than-implementation level. Most Python code simply expects that and it would degrade a lot of code if that ever changed in whatever implementation. Stefan From hobson42 at gmaiil.com Tue Aug 31 10:42:25 2010 From: hobson42 at gmaiil.com (Ian) Date: Tue, 31 Aug 2010 15:42:25 +0100 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: <4C7D14D1.9060702@gmaiil.com> On 31/08/2010 15:09, Aahz wrote: > I suggest that we should agree on these guarantees and document them in > the core. I suspect that documenting them will be the easy part ;) From malaclypse2 at gmail.com Tue Aug 31 10:45:57 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 31 Aug 2010 10:45:57 -0400 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: On Tue, Aug 31, 2010 at 10:09 AM, Aahz wrote: > I suggest that we should agree on these guarantees and document them in > the core. I can't get to the online python-dev archives from work (stupid filter!) so I can't give you a link to the archives, but the original thread that resulted in the creation of that wiki page was started on March 9th, 2008 and was titled "Complexity documentation request". At the time, opposition to formally documenting this seemed pretty widespread, including from yourself and Guido. You've obviously changed your mind on the subject, so maybe it's something that would be worth revisiting, assuming someone wants to write the doc change. -- Jerry From AmFreak at web.de Tue Aug 31 10:49:36 2010 From: AmFreak at web.de (AmFreak at web.de) Date: Tue, 31 Aug 2010 16:49:36 +0200 Subject: Saving (unusual) linux filenames Message-ID: Hi, i have a script that reads and writes linux paths in a file. I save the path (as unicode) with 2 other variables. I save them seperated by "," and the "packets" by newlines. So my file looks like this: path1, var1A, var1B path2, var2A, var2B path3, var3A, var3B .... this works for "normal" paths but as soon as i have a path that does include a "," it breaks. The problem now is that (afaik) linux allows every char (aside from "/" and null) to be used in filenames. The only solution i can think of is using null as a seperator, but there have to a cleaner version ? Thanks for any help Biene_Maja From romsok.tech at gmail.com Tue Aug 31 10:58:04 2010 From: romsok.tech at gmail.com (Roman Sokolyuk) Date: Tue, 31 Aug 2010 10:58:04 -0400 Subject: Stackless Python and EVE Online Message-ID: Hi, I am new to Python and I wanted to understand something... The EVE Online Client is build using Stackless Python So when I install the client on my machine, how doe sit get run if I do not have Python installed? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollybox.de Tue Aug 31 11:05:32 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 17:05:32 +0200 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: <201008311705.32747.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to Roman Sokolyuk to exclaim: > Hi, > > I am new to Python and I wanted to understand something... > > The EVE Online Client is build using Stackless Python > > So when I install the client on my machine, how doe sit get run if I do not > have Python installed? If this program uses Stackless, and you do not have Stackless installed system-wide, then the program includes Stackless. This is probably not a bad idea, since the likelihood of Stackless Python being installed is realtively small. Stackless Python is not the same as Python -- as far as I know, it adds some new features not found in the actual Python language to the "PyPy" implementation of the language. From benjamin.kaplan at case.edu Tue Aug 31 11:10:16 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 31 Aug 2010 11:10:16 -0400 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: On Tuesday, August 31, 2010, Roman Sokolyuk wrote: > Hi, > > I am new to Python and I wanted to understand something... > The EVE Online Client is build using Stackless Python > So when I install the client on my machine, how doe sit get run if I do not have Python installed? > We call it "freezing" the program. There are several tools that do this with py2exe being the most popular. These tools create an executable that includes a bundled python interpreter along with all the scripts and modules needed to run the program. > Thanks. From invalid at invalid.invalid Tue Aug 31 11:22:00 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 31 Aug 2010 15:22:00 +0000 (UTC) Subject: Saving (unusual) linux filenames References: Message-ID: On 2010-08-31, AmFreak at web.de wrote: > Hi, > > i have a script that reads and writes linux paths in a file. I save the > path (as unicode) with 2 other variables. I save them seperated by "," and > the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B > .... > > this works for "normal" paths but as soon as i have a path that does > include a "," it breaks. The problem now is that (afaik) linux allows > every char (aside from "/" and null) to be used in filenames. The only > solution i can think of is using null as a seperator, but there have to a > cleaner version ? The normal thing to do is to escape the delimiter when it appears in data. There are lots of plenty of escaping standards to choose from, and some of them (e.g. the one used for URLs) are already present in various bits of Python's standard library. -- Grant Edwards grant.b.edwards Yow! ... the HIGHWAY is at made out of LIME JELLO and gmail.com my HONDA is a barbequeued OYSTER! Yum! From robert.kern at gmail.com Tue Aug 31 11:36:23 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 31 Aug 2010 10:36:23 -0500 Subject: PyGeo In-Reply-To: <86bp8j7z1v.fsf@aiuole.stru.polimi.it> References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> <86bp8j7z1v.fsf@aiuole.stru.polimi.it> Message-ID: On 8/31/10 7:21 AM, Giacomo Boffi wrote: > L writes: > >> also the PyGeo readme text mentions Numerical python (I think it >> means Numeric, but I also have NumPy installed) > > afaict, Numerical python is numpy --- if you look at pygeo home page, > the reference to Numerical python is a link to numpy home page > > on the contrary, there is no "import numpy" in all the sources of > pygeo, and a couples or so of "import Numeric", so that the situation > is unclear numpy supercedes the older Numeric package. However, "numpy" used to be a colloquial name for Numeric, too. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From python at bdurham.com Tue Aug 31 11:42:07 2010 From: python at bdurham.com (python at bdurham.com) Date: Tue, 31 Aug 2010 11:42:07 -0400 Subject: Find closest matching string based on collection of strings in list/dict/set Message-ID: <1283269327.22774.1392642985@webmail.messagingengine.com> I'm parsing a simple, domain specific scripting language that has commands like the following: *page, *title, *text, *footer, etc. There are about 100 of these '*' commands. When we see a command that we don't recognize, I would like to find the closest match possible (from a list of all legal commands) and include this suggestion in our diagnostic output. I'm not sure what you would call the type of algorithm I'm looking for: closest matching string or auto-correct? Any suggestions on algorithms or python libraries that would help me do what I'm looking for? Here's my short-list of ideas based on my research so far: - Soundex - Lawrence Philips' Metaphone Algorithm (from aspell?) - Edit Distance Algorithm - Levenstein Word Distance Any suggestions, comments on the above techniques, or ideas on a simpler algorithm for finding close string matches based on a list, dict, or set of possible strings? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 31 12:19:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 17:19:25 +0100 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D2B8D.20401@mrabarnett.plus.com> On 31/08/2010 15:49, AmFreak at web.de wrote: > Hi, > > i have a script that reads and writes linux paths in a file. I save the > path (as unicode) with 2 other variables. I save them seperated by "," > and the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B > .... > > this works for "normal" paths but as soon as i have a path that does > include a "," it breaks. The problem now is that (afaik) linux allows > every char (aside from "/" and null) to be used in filenames. The only > solution i can think of is using null as a seperator, but there have to > a cleaner version ? > You could use a tab character '\t' instead. From alekseymv at gmail.com Tue Aug 31 12:33:49 2010 From: alekseymv at gmail.com (Aleksey) Date: Tue, 31 Aug 2010 09:33:49 -0700 (PDT) Subject: Optimising literals away References: Message-ID: <69a8fbbc-5f45-491a-adf3-2fb5a4d79660@s9g2000yqd.googlegroups.com> On Aug 30, 10:38?pm, Tobias Weber wrote: > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. > > def m(arg): > ? if arg & set([1,2,3]): > ? ? return 4 > > Is the set created every time the method is called? What about a > frozenset? Or tuple vs list? After how many calls per second does it pay > to save it at the module level? Would anybody else find this ugly? > > Also I never profiled the regular expression cache... > > -- > ? Tobias Weber I test time creation of any types ang get next result: dictionary = 393 000 * 10 frozenset = 267 000 * 10 list = 519 000 * 10 set = 268 000 * 10 tuple = 5 935 500 * 10 global assign = 5 882 700 * 10 All results multiple by 10 becouse i do 10 creations in one loop and count loops per second. As you see create global variable is more faster (20 times) then create list and from it create set! Assigments is ~ 5 882 000*10,>>> set creation is 268 000*10 My test system is Ubuntu 10.04, Dell Inspiron 1525, Core2Duo, T8300, 2Gb , Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3]. I make tests with XPyLIB.timetest module. (XPyLIB hosted at sourceforge - http://sourceforge.net/apps/trac/xpylib/wiki/CookBook/TimeTest) Assign global (pre declared by "global") function is next (N - is a times of repeating): gset = set((1,2,3)) def t_set_assign_global(ntimes = N, funcloop=u'funcloop', excludecall=u'excludecall'): """Set assigment from global : global=(1,2,3); loop a = global 10 times in while. @UID@ e710b888-bacd-4248-9ff7-1f7a348e1c8f @author@ Mazhugin Aleksey @score_common@ 1 """ a = 0 global gset while ntimes > 0: a = gset a = gset a = gset a = gset a = gset a = gset a = gset a = gset a = gset a = gset ntimes -= 1 Set function is next: def t_set_create(ntimes = N, funcloop=u'funcloop', excludecall=u'excludecall'): """Set creation : t=(1,2,3); loop a = set(t) 10 times in while. @UID@ a021a756-f9a5-44ec-b9e6-e5532b56c09f @author@ Mazhugin Aleksey @score_common@ 1 """ a = 0 t = (1,2,3) while ntimes > 0: a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) ntimes -= 1 Also i test regular expression compiled pattern vs non-compiled: compiled = 343 000*2 not compiled = 164 000*2 Functions is next: patt5 = u'*.tmp,*.pyc,*.pyo,*.bak,*.log' path1 = u'/home/user/project/src/file.ext' path2 = u'/home/user/project/logs/debug.log' def t_rematch(ntimes=10, funcloop=u'funcloop', excludecall='excludecall'): """ Compiled. @UID@ 665f4014-9c11-4668-baae-e49230027bd4 @author@ Mazhugin Aleksey @score_common@ 1 """ ci = patt5.replace(u'\\',u'\\\\').replace(u'|',u'\ \|').replace(u'.',u'\\.').replace(u'*',u'.*'). \ replace(u'?',u'.?').replace(u'$',u'\\$').replace(u'^',u'\ \^').replace(u'{',u'\\{'). \ replace(u'(',u'\\(').replace(u'[',u'\\[').replace(u'+',u'\\ +').split(u',') repat = u'|'.join([u'('+i+u'$)' for i in ci]) rec = re.compile(repat) r = 0 while ntimes: r = rec.match(path1) is not None r = rec.match(path2) is not None ntimes -= 1 def t_rematch_string(ntimes=10, funcloop=u'funcloop', excludecall='excludecall'): """ Not compiled. @UID@ 80fa1ca3-5d51-4f6e-8ac2-4ccafe4c1160 @author@ Mazhugin Aleksey @score_common@ 1 """ ci = patt5.replace(u'\\',u'\\\\').replace(u'|',u'\ \|').replace(u'.',u'\\.').replace(u'*',u'.*'). \ replace(u'?',u'.?').replace(u'$',u'\\$').replace(u'^',u'\ \^').replace(u'{',u'\\{'). \ replace(u'(',u'\\(').replace(u'[',u'\\[').replace(u'+',u'\\ +').split(u',') repat = u'|'.join([u'('+i+u'$)' for i in ci]) #rec = re.compile(repat) r = 0 while ntimes: r = re.match(repat, path1) is not None r = re.match(repat, path2) is not None ntimes -= 1 From tim.arnold at sas.com Tue Aug 31 12:38:41 2010 From: tim.arnold at sas.com (Tim Arnold) Date: Tue, 31 Aug 2010 12:38:41 -0400 Subject: triangle python user's group? References: <3c95f09c-1fa7-4c63-9f13-3f2776c2ab41@j18g2000yqd.googlegroups.com> Message-ID: "Albert Hopkins" wrote in message news:mailman.219.1283200967.29448.python-list at python.org... > On Mon, 2010-08-30 at 12:38 -0700, Tim Arnold wrote: >> Hi, >> Is there a python users group in the Research Triangle Park area >> (North Carolina, USA)? > > Google "triangle python user's group" > thanks for the pointer.... --Tim From invalid at invalid.invalid Tue Aug 31 12:58:41 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 31 Aug 2010 16:58:41 +0000 (UTC) Subject: Saving (unusual) linux filenames References: Message-ID: On 2010-08-31, MRAB wrote: > On 31/08/2010 15:49, AmFreak at web.de wrote: >> Hi, >> >> i have a script that reads and writes linux paths in a file. I save the >> path (as unicode) with 2 other variables. I save them seperated by "," >> and the "packets" by newlines. So my file looks like this: >> path1, var1A, var1B >> path2, var2A, var2B >> path3, var3A, var3B >> .... >> >> this works for "normal" paths but as soon as i have a path that does >> include a "," it breaks. The problem now is that (afaik) linux allows >> every char (aside from "/" and null) to be used in filenames. The only >> solution i can think of is using null as a seperator, but there have to >> a cleaner version ? > > You could use a tab character '\t' instead. That just breaks with a different set of filenames. -- Grant Edwards grant.b.edwards Yow! ! Everybody out of at the GENETIC POOL! gmail.com From jeremy at jeremysanders.net Tue Aug 31 12:58:55 2010 From: jeremy at jeremysanders.net (Jeremy Sanders) Date: Tue, 31 Aug 2010 17:58:55 +0100 Subject: Saving (unusual) linux filenames References: Message-ID: AmFreak at web.de wrote: > i have a script that reads and writes linux paths in a file. I save the > path (as unicode) with 2 other variables. I save them seperated by "," and > the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B If you're generating the file and it is safe to do so (you're not getting the data from the internet), you could use repr((path1, v1, v2)) to save the line to the file and eval to interpret back the tuple. Alternatively you could use // as a separator, making sure that you replace multiple slashes in the path which a single slash (which are equivalent). Jeremy From python at mrabarnett.plus.com Tue Aug 31 13:13:44 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 18:13:44 +0100 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D3848.90106@mrabarnett.plus.com> On 31/08/2010 17:58, Grant Edwards wrote: > On 2010-08-31, MRAB wrote: >> On 31/08/2010 15:49, AmFreak at web.de wrote: >>> Hi, >>> >>> i have a script that reads and writes linux paths in a file. I save the >>> path (as unicode) with 2 other variables. I save them seperated by "," >>> and the "packets" by newlines. So my file looks like this: >>> path1, var1A, var1B >>> path2, var2A, var2B >>> path3, var3A, var3B >>> .... >>> >>> this works for "normal" paths but as soon as i have a path that does >>> include a "," it breaks. The problem now is that (afaik) linux allows >>> every char (aside from "/" and null) to be used in filenames. The only >>> solution i can think of is using null as a seperator, but there have to >>> a cleaner version ? >> >> You could use a tab character '\t' instead. > > That just breaks with a different set of filenames. > How many filenames contain control characters? Surely that's a bad idea. From sandricionut at yahoo.com Tue Aug 31 13:14:03 2010 From: sandricionut at yahoo.com (sandric ionut) Date: Tue, 31 Aug 2010 10:14:03 -0700 (PDT) Subject: sendmail error In-Reply-To: <201008311546.59595.thomas@jollybox.de> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <201008311546.59595.thomas@jollybox.de> Message-ID: <492442.26155.qm@web51305.mail.re2.yahoo.com> This is the only message that I will send to this list regarding my question: 1. I have copied and paste my code from Eclipe PyDev and I have used web interface for yahoo email to send the email. I don't know why the message arrived like that. I consider that the message from Dave was rude and just a replay considering the structure of the script would have been enough 2. Regarding the useless of the question: I consider that you two are also rude! There are some many more "useless" questions than my question on this forum! Do not bother to replay to this email because I would not receive the message. Your replays were enough to make me unsubscribe from the list I.S. ________________________________ From: Thomas Jollans To: python-list at python.org Sent: Tue, August 31, 2010 4:46:58 PM Subject: Re: sendmail error On Tuesday 31 August 2010, it occurred to sandric ionut to exclaim: > Hello: > > I have a script for sending email from python (it is attached bellow). When > I am launching the script I get the error: > TypeError: cannot concatenate 'str' and 'type' objects if I use > sys.argv[1], but if I input from the begging an email address like > "email at email.com", the script is working OK > > What could be the problem? > > Thank you, > > Ionut > > import > mesaj = email.MIMEMultipart.MIMEMultipart() > fromEmail = sys.argv[ > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > mesaj[ > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > atasament = r"Date"] = > email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = > email.MIMEBase.MIMEBase( > atasamentP.set_payload(open(atasament, > email.Encoders.encode_base64(atasamentP) > atasamentP.add_header( > mesaj.attach(atasamentP) > mesaj.attach(email.MIMEText.MIMEText( > smtpObj = > smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attach > ement; filename="%s"'% os.path.basename(atasament))"Email transmis la data: > ", email.Utils.formatdate(localtime=False)))"192.168.1.2")try > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ > smtplib.SMTPException I struggle to imagine what one might do to a piece of code to garble it this badly. If this was actually the script you're trying to run, then it would have blown up in your face with a angry SyntaxError, not the helpful TypeError you quoted. As far as I can see, you never actually use sys.argv[1], so this can't be the right code. To paraphrase what you failed to spell correctly in your other message, please don't bother sending useless inquiries to this list. If you want to get a useful reply, please: - Quote the code correctly. Before sending, check that it actually makes sense. The above is quite simply nothing like Python. - Quote the entire stack trace and error message. You might have looked at it already, but we haven't. This information is not useless! Also, when replying: - Quote properly. While top posting is discouraged, the most important bit is to clearly distinguish quoted material from new material. Make it possible from the structure of the message you're sending which parts you wrote and which parts you're just quoting. - Keep your reply on-list. - Thomas -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at simplistix.co.uk Tue Aug 31 13:17:47 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 31 Aug 2010 18:17:47 +0100 Subject: Fw: sendmail error In-Reply-To: <4C7D0683.9000409@web.de> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <4C7CEC49.9030209@ieee.org> <191591.90081.qm@web51308.mail.re2.yahoo.com> <4C7D0683.9000409@web.de> Message-ID: <4C7D393B.9030100@simplistix.co.uk> Alexander Kapps wrote: > Instead you want something like: > > except smtplib.SMTPException, msg > print "eroare: " + msg Err, that's still concatenating a string and an exception object. What *would* work is: except smtplib.SMTPException, msg print "eroare: " + str(msg) ...not that it's particularly good coding style, what with hiding the traceback and all... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From chris at simplistix.co.uk Tue Aug 31 13:18:52 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 31 Aug 2010 18:18:52 +0100 Subject: sendmail error In-Reply-To: <201008311546.59595.thomas@jollybox.de> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <201008311546.59595.thomas@jollybox.de> Message-ID: <4C7D397C.6020501@simplistix.co.uk> Thomas Jollans wrote: > I struggle to imagine what one might do to a piece of code to garble it this > badly. You viewed the text/plain part of his message, the text/html part showed the code almost correctly, complete with pasted-from-IDE colour formatting ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From alex.kapps at web.de Tue Aug 31 13:53:59 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Tue, 31 Aug 2010 19:53:59 +0200 Subject: Fw: sendmail error In-Reply-To: <4C7D393B.9030100@simplistix.co.uk> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <4C7CEC49.9030209@ieee.org> <191591.90081.qm@web51308.mail.re2.yahoo.com> <4C7D0683.9000409@web.de> <4C7D393B.9030100@simplistix.co.uk> Message-ID: <4C7D41B7.8080505@web.de> Chris Withers wrote: > Alexander Kapps wrote: >> Instead you want something like: >> >> except smtplib.SMTPException, msg >> print "eroare: " + msg > > Err, that's still concatenating a string and an exception object. OUCH! What a stupid error. Thanks for correction. :-) > What *would* work is: > > except smtplib.SMTPException, msg > print "eroare: " + str(msg) > > ...not that it's particularly good coding style, what with hiding the > traceback and all... Full Ack. > cheers, > > Chris > From marduk at letterboxes.org Tue Aug 31 14:10:28 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 31 Aug 2010 14:10:28 -0400 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <1283278228.892888.3.camel@paska> On Tue, 2010-08-31 at 16:49 +0200, AmFreak at web.de wrote: > i have a script that reads and writes linux paths in a file. I save > the > path (as unicode) with 2 other variables. I save them seperated by "," > and > the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B > .... > > this works for "normal" paths but as soon as i have a path that does > include a "," it breaks. The problem now is that (afaik) linux > allows > every char (aside from "/" and null) to be used in filenames. The > only > solution i can think of is using null as a seperator, but there have > to a > cleaner version ? Why is your impression that the null character is "dirty"? E.g. that's how find|xargs etc. usually work. Another alternative would be if you gaurantee that your varn's don't have commas then put the path last. But that doesn't account for filenames containing newlines. Another alternative would be to wrap with some kind of serialization library. But really, what's so dirty about null? From nobody at nowhere.com Tue Aug 31 14:33:26 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 31 Aug 2010 19:33:26 +0100 Subject: Saving (unusual) linux filenames References: Message-ID: On Tue, 31 Aug 2010 18:13:44 +0100, MRAB wrote: >>>> this works for "normal" paths but as soon as i have a path that does >>>> include a "," it breaks. The problem now is that (afaik) linux allows >>>> every char (aside from "/" and null) to be used in filenames. The only >>>> solution i can think of is using null as a seperator, but there have to >>>> a cleaner version ? >>> >>> You could use a tab character '\t' instead. >> >> That just breaks with a different set of filenames. >> > How many filenames contain control characters? Surely that's a bad idea. It may be a bad idea, but it's permitted by the OS. If you're writing a general-purpose tool, having it flake out whenever it encounters an "unusual" filename is also a bad idea. FWIW, my usual solution is URL-encoding (i.e. replacing any "awkward" character by a "%" followed by two hex digits representing the byte's value). It has the advantage that you can extend the set of bytes which need encoding as needed without having to change the code (e.g. you can provide a command-line argument or configuration file setting which specifies which bytes need to be encoded). From thomas at jollybox.de Tue Aug 31 14:33:53 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 20:33:53 +0200 Subject: sendmail error In-Reply-To: <492442.26155.qm@web51305.mail.re2.yahoo.com> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <201008311546.59595.thomas@jollybox.de> <492442.26155.qm@web51305.mail.re2.yahoo.com> Message-ID: <201008312033.54015.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to sandric ionut to exclaim: > This is the only message that I will send to this list regarding my > question: > > 1. I have copied and paste my code from Eclipe PyDev and I have used web > interface for yahoo email to send the email. I will try never to use Yahoo! mail then. > I don't know why the message > arrived like that. I consider that the message from Dave was rude and just > a replay considering the structure of the script would have been enough 2. > Regarding the useless of the question: I consider that you two are also > rude! There are some many more "useless" questions than my question on > this forum! > > Do not bother to replay to this email because I would not receive the > message. Your replays were enough to make me unsubscribe from the list Charming. Replay indeed. > > > > ________________________________ > From: Thomas Jollans > To: python-list at python.org > Sent: Tue, August 31, 2010 4:46:58 PM > Subject: Re: sendmail error > > On Tuesday 31 August 2010, it occurred to sandric ionut to exclaim: > > Hello: > > > > I have a script for sending email from python (it is attached bellow). > > When I am launching the script I get the error: > > TypeError: cannot concatenate 'str' and 'type' objects if I use > > sys.argv[1], but if I input from the begging an email address like > > "email at email.com", the script is working OK > > > > What could be the problem? > > > > Thank you, > > > > Ionut > > > > import > > mesaj = email.MIMEMultipart.MIMEMultipart() > > fromEmail = sys.argv[ > > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > > mesaj[ > > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > > atasament = r"Date"] = > > email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = > > email.MIMEBase.MIMEBase( > > atasamentP.set_payload(open(atasament, > > email.Encoders.encode_base64(atasamentP) > > atasamentP.add_header( > > mesaj.attach(atasamentP) > > mesaj.attach(email.MIMEText.MIMEText( > > smtpObj = > > smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','atta > > ch ement; filename="%s"'% os.path.basename(atasament))"Email transmis la > > data: ", email.Utils.formatdate(localtime=False)))"192.168.1.2")try > > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ > > smtplib.SMTPException > > I struggle to imagine what one might do to a piece of code to garble it > this badly. If this was actually the script you're trying to run, then it > would have blown up in your face with a angry SyntaxError, not the helpful > TypeError you quoted. As far as I can see, you never actually use > sys.argv[1], so this can't be the right code. > > To paraphrase what you failed to spell correctly in your other message, > please don't bother sending useless inquiries to this list. If you want to > get a useful reply, please: > > - Quote the code correctly. Before sending, check that it actually makes > sense. The above is quite simply nothing like Python. > > - Quote the entire stack trace and error message. You might have looked at > it already, but we haven't. This information is not useless! > > Also, when replying: > > - Quote properly. While top posting is discouraged, the most important > bit is to clearly distinguish quoted material from new material. Make it > possible from the structure of the message you're sending which parts you > wrote and which parts you're just quoting. > > - Keep your reply on-list. > > - Thomas From invalid at invalid.invalid Tue Aug 31 14:49:33 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 31 Aug 2010 18:49:33 +0000 (UTC) Subject: Saving (unusual) linux filenames References: Message-ID: On 2010-08-31, MRAB wrote: > On 31/08/2010 17:58, Grant Edwards wrote: >> On 2010-08-31, MRAB wrote: >>> On 31/08/2010 15:49, AmFreak at web.de wrote: >>>> Hi, >>>> >>>> i have a script that reads and writes linux paths in a file. I save the >>>> path (as unicode) with 2 other variables. I save them seperated by "," >>>> and the "packets" by newlines. So my file looks like this: >>>> path1, var1A, var1B >>>> path2, var2A, var2B >>>> path3, var3A, var3B >>>> .... >>>> >>>> this works for "normal" paths but as soon as i have a path that does >>>> include a "," it breaks. The problem now is that (afaik) linux allows >>>> every char (aside from "/" and null) to be used in filenames. The only >>>> solution i can think of is using null as a seperator, but there have to >>>> a cleaner version ? >>> >>> You could use a tab character '\t' instead. >> >> That just breaks with a different set of filenames. >> > How many filenames contain control characters? How many filenames contain ","? Not many, but the OP wants his program to be bulletproof. Can't fault him for that. If I had a nickle for every Unix program or shell-script that failed when a filename had a space it it.... > Surely that's a bad idea. Of course it's a bad idea. That doesn't stop people from doing it. -- Grant Edwards grant.b.edwards Yow! ! Now I understand at advanced MICROBIOLOGY and gmail.com th' new TAX REFORM laws!! From python at mrabarnett.plus.com Tue Aug 31 14:57:33 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 19:57:33 +0100 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D509D.8090607@mrabarnett.plus.com> On 31/08/2010 19:33, Nobody wrote: > On Tue, 31 Aug 2010 18:13:44 +0100, MRAB wrote: > >>>>> this works for "normal" paths but as soon as i have a path that does >>>>> include a "," it breaks. The problem now is that (afaik) linux allows >>>>> every char (aside from "/" and null) to be used in filenames. The only >>>>> solution i can think of is using null as a seperator, but there have to >>>>> a cleaner version ? >>>> >>>> You could use a tab character '\t' instead. >>> >>> That just breaks with a different set of filenames. >>> >> How many filenames contain control characters? Surely that's a bad idea. > > It may be a bad idea, but it's permitted by the OS. [snip] So are viruses. :-) From python.koda at gmail.com Tue Aug 31 14:57:36 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 14:57:36 -0400 Subject: Dumb Stupid Question About List and String Message-ID: Hi all, Im stuck on this problem: I have a function which return me a list of string (basically the result looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] In other hand, I have another list full of that kind of entries: ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] I would like to do something like this: myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] mySecondList = ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] for n in myFirstList: if n in mySecondList: mySecondList.remove(n) In fact, what I want to do it to remove entries with the secondlist which content the entries of the first one. But it seems to not work like this. Someone can help me please ? did I miss something ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Tue Aug 31 15:03:33 2010 From: nagle at animats.com (John Nagle) Date: Tue, 31 Aug 2010 12:03:33 -0700 Subject: Optimising literals away In-Reply-To: References: Message-ID: <4c7d5204$0$1582$742ec2ed@news.sonic.net> On 8/30/2010 8:38 AM, Tobias Weber wrote: > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. CPython is a "naive interpreter". It has almost no optimization. It doesn't even really comprehend "constants". This is an implementation problem, not a language problem. Shed Skin has serious optimization but limits the language. PyPy has been trying for years, but it still barely works. Iron Python seems to be nearing end of life, as Microsoft phases it out. Unladen Swallow seems to be in trouble; it's been almost a year since the last "quarterly release". John Nagle From arnodel at googlemail.com Tue Aug 31 15:12:41 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 31 Aug 2010 20:12:41 +0100 Subject: Saving (unusual) linux filenames References: Message-ID: AmFreak at web.de writes: > Hi, > > i have a script that reads and writes linux paths in a file. I save > the path (as unicode) with 2 other variables. I save them seperated by > "," and the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B > .... > > this works for "normal" paths but as soon as i have a path that does > include a "," it breaks. The problem now is that (afaik) linux allows > every char (aside from "/" and null) to be used in filenames. The only > solution i can think of is using null as a seperator, but there have > to a cleaner version ? > > Thanks for any help > > Biene_Maja A simple solution would be to save each line of data using JSON with the json module: >>> import json >>> >>> >>> path = "x,y,z" >>> varA = 12 >>> varB = "abc" >>> line = json.dumps([path, varA, varB]) >>> print line ["x,y,z", 12, "abc"] >>> loadpathA, loadvarA, loadvarB = json.loads(line) >>> print loadpathA x,y,z >>> print loadvarA 12 >>> print loadvarB abc HTH -- Arnaud From python.koda at gmail.com Tue Aug 31 15:20:39 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 15:20:39 -0400 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: Ok, here a solution: myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] mySecondList = ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] for n in myFirstList: var = str(n) for n in mySecondList: if var in n: mySecondList.remove(n) print mySecondList :) 2010/8/31 Alban Nona > Hi all, > > Im stuck on this problem: > I have a function which return me a list of string (basically the result > looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > In other hand, I have another list full of that kind of entries: > > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > I would like to do something like this: > > myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > mySecondList = > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > for n in myFirstList: > if n in mySecondList: > mySecondList.remove(n) > > In fact, what I want to do it to remove entries with the secondlist which > content the entries of the first one. But it seems to not work like this. > Someone can help me please ? did I miss something ? > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 31 15:25:46 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 20:25:46 +0100 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: <4C7D573A.9050602@mrabarnett.plus.com> On 31/08/2010 19:57, Alban Nona wrote: > Hi all, > > Im stuck on this problem: > I have a function which return me a list of string (basically the result > looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > In other hand, I have another list full of that kind of entries: > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > I would like to do something like this: > > myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > mySecondList = > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > for n in myFirstList: > if n in mySecondList: > mySecondList.remove(n) > > In fact, what I want to do it to remove entries with the secondlist > which content the entries of the first one. But it seems to not work > like this. > Someone can help me please ? did I miss something ? > Your code is asking whether, for example, "FN067_098_MEN" is in mySecondList. It isn't. mySecondList contains "FN067_098_MEN_Hair_PUZ_v001.0001.exr", but that's not the same as "FN067_098_MEN". If I understand you correctly, you want to remove entries from mySecondList which have an entry of myFirstList as a substring. Here's one solution: result_list = [] for second in mySecondList: if not any(first in second for first in myFirstList): result_list.append(second) mySecondList = result_list From clp2 at rebertia.com Tue Aug 31 15:26:02 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 31 Aug 2010 12:26:02 -0700 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: On Tue, Aug 31, 2010 at 12:20 PM, Alban Nona wrote: > Ok, here a solution: > for n in myFirstList: > ???? var = str(n) n is already a string, so the previous line doesn't do anything useful. Cheers, Chris From stefan_ml at behnel.de Tue Aug 31 15:28:24 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Aug 2010 21:28:24 +0200 Subject: Optimising literals away In-Reply-To: <4c7d5204$0$1582$742ec2ed@news.sonic.net> References: <4c7d5204$0$1582$742ec2ed@news.sonic.net> Message-ID: John Nagle, 31.08.2010 21:03: > On 8/30/2010 8:38 AM, Tobias Weber wrote: >> whenever I type an "object literal" I'm unsure what optimisation will do >> to it. > > CPython is a "naive interpreter". It has almost no optimization. > It doesn't even really comprehend "constants". > This is an implementation problem, not a language problem. > > Shed Skin has serious optimization but limits the language. > PyPy has been trying for years, but it still barely works. > Iron Python seems to be nearing end of life, as Microsoft > phases it out. Unladen Swallow seems to be in trouble; it's > been almost a year since the last "quarterly release". To continue the list, Cython also has a couple of optimisations for literals. It caches simple immutable constants, applies numeric constant folding and it's obviously a lot faster in packing tuples and lists than CPython as it avoids the interpreter loop. It also optimises away the literal sequences in "in" tests such as if x in (1,2,3): ... which, in the best case of integer literals, even compile down into C switch statements. Stefan From python at mrabarnett.plus.com Tue Aug 31 15:42:55 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 20:42:55 +0100 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: <4C7D5B3F.5070102@mrabarnett.plus.com> On 31/08/2010 20:20, Alban Nona wrote: > Ok, here a solution: > > myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] > > mySecondList = > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > for n in myFirstList: > var = str(n) Why str(n)? Also, it would be clearer if you used different variables for the different loops. > for n in mySecondList: > if var in n: > mySecondList.remove(n) You shouldn't change the length of a list over which you're iterating. Python will step along the list one entry at a time and won't notice when you remove an entry, so the next one will be skipped. For example: >>> letters = ["a", "b", "c", "d", "e"] >>> for i in letters: ... if i == "b" or i == "c": ... letters.remove(i) ... >>> print letters ['a', 'c', 'd', 'e'] It removed "b" and then moved on to the next entry, which is "d" because "b" has been removed and all the following entries have moved down one place. It never sees "c". > > print mySecondList > [snip] From anand.shashwat at gmail.com Tue Aug 31 15:44:22 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Wed, 1 Sep 2010 01:14:22 +0530 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: On Wed, Sep 1, 2010 at 12:27 AM, Alban Nona wrote: > Hi all, > > Im stuck on this problem: > I have a function which return me a list of string (basically the result > looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > In other hand, I have another list full of that kind of entries: > > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > I would like to do something like this: > > myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > mySecondList = > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > for n in myFirstList: > if n in mySecondList: > mySecondList.remove(n) > > In fact, what I want to do it to remove entries with the secondlist which > content the entries of the first one. But it seems to not work like this. > Someone can help me please ? did I miss something ? > You can try this if you don't care about the order. >>> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] >>> mySecondList = ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] >>> list(set(mySecondList).difference(myFirstList)) ['FN067_098_MEN_Jin_MVE_v001.0001.exr', 'FN067_098_MEN_Hair_PUZ_v001.0001.exr', 'FR043_010_GEN_NRM_v001.0001.exr', 'FN067_098_JIN_Hair_SPC_v001.0001.exr'] Another example to make this clear. >>> a = range(10) >>> b = range(5,15) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> b [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> list(set(b).difference(a)) [10, 11, 12, 13, 14] -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Tue Aug 31 15:57:22 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Wed, 1 Sep 2010 01:27:22 +0530 Subject: Find closest matching string based on collection of strings in list/dict/set In-Reply-To: <1283269327.22774.1392642985@webmail.messagingengine.com> References: <1283269327.22774.1392642985@webmail.messagingengine.com> Message-ID: On Tue, Aug 31, 2010 at 9:12 PM, wrote: > I'm parsing a simple, domain specific scripting language that has commands > like the following: *page, *title, *text, *footer, etc. There are about 100 > of these '*' commands. When we see a command that we don't recognize, I > would like to find the closest match possible (from a list of all legal > commands) and include this suggestion in our diagnostic output. > > I'm not sure what you would call the type of algorithm I'm looking for: > closest matching string or auto-correct? > > Any suggestions on algorithms or python libraries that would help me do > what I'm looking for? > > Here's my short-list of ideas based on my research so far: > - Soundex > - Lawrence Philips' Metaphone Algorithm (from aspell?) > - Edit Distance Algorithm > - Levenstein Word Distance > > Any suggestions, comments on the above techniques, or ideas on a simpler > algorithm for finding close string matches based on a list, dict, or set of > possible strings? > You are looking possibly for autocompletion/spell correction algorithm. You can write a HMM based Pos Tagger. > Thank you, > Malcolm > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Aug 31 15:59:40 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Aug 2010 15:59:40 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On 8/31/2010 12:47 AM, rurpy at yahoo.com wrote: >> I have participated in 71 doc improvement issues on the tracker. Most of >> those I either initiated or provided suggestions. How many have you >> helped with? > > Certainly not 71. But there is, for example, http://bugs.python.org/issue1397474 > Please note the date on it. Ugh. Some doc issues get resolved in hours. That didn't. I built on your proposed change and properly assigned the issue, so it is more likely to get attention. Please comment there on my revision. -- Terry Jan Reedy From tjreedy at udel.edu Tue Aug 31 16:18:13 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Aug 2010 16:18:13 -0400 Subject: Optimising literals away In-Reply-To: <69a8fbbc-5f45-491a-adf3-2fb5a4d79660@s9g2000yqd.googlegroups.com> References: <69a8fbbc-5f45-491a-adf3-2fb5a4d79660@s9g2000yqd.googlegroups.com> Message-ID: On 8/31/2010 12:33 PM, Aleksey wrote: > On Aug 30, 10:38 pm, Tobias Weber wrote: >> Hi, >> whenever I type an "object literal" I'm unsure what optimisation will do >> to it. Optimizations are generally implentation dependent. CPython currently creates numbers, strings, and tuple literals just once. Mutable literals must be created each time as they may be bound and saved. >> def m(arg): >> if arg& set([1,2,3]): set() is a function call, not a literal. When m is called, who knows what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, which is much faster as it avoids creating and deleting a list. On my machine, .35 versus .88 usec. Even then, it must be calculated each time because sets are mutable and could be returned to the calling code. >> return 4 >> >> Is the set created every time the method is called? What about a >> frozenset? Or tuple vs list? After how many calls per second does it pay >> to save it at the module level? Would anybody else find this ugly? Defining module level constants is considered good practice in some circles, especially if is something you might want to change. That is what function definitions are (as long as the name is not redefined. This is different from having lots of module level variables. To see what CPython does, you can use the dis module. -- Terry Jan Reedy From hexusnexus at gmail.com Tue Aug 31 16:37:01 2010 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Tue, 31 Aug 2010 13:37:01 -0700 (PDT) Subject: Python libs on Windows ME Message-ID: I'm not guessing that this is a problem on Windows 98, but on Windows ME modules in /Lib don't seem to load. Examples include site.py and os.py which are both located in the top level Lib directory. The same thing happens with Python 2.3, 2.4, and 2.5. I can't get IDLE to load and the Python interpreter always complains that it can't load the "site" module even if Python is run from the same directory as the module (note: this does not happen if a module is loaded from the current working directory while in the interpreter). I would use another os like Linux or Windows 2000, but this particular computer can't even seem to handle even the most minimal graphical Linux distributions. From hexusnexus at gmail.com Tue Aug 31 16:41:19 2010 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Tue, 31 Aug 2010 13:41:19 -0700 (PDT) Subject: Installing Python as Scripting Language in IIS References: <4154f088-f746-4891-83ee-f64138c81e2e@x25g2000yqj.googlegroups.com> Message-ID: <125c518f-d418-4f3f-ae8f-4f0fdcae00df@y12g2000prb.googlegroups.com> On Aug 30, 6:55?pm, naugiedoggie wrote: > Hello, > > Windows 2003, 64-bit, standard edition server with IIS 6.0. ?I > followed the MS instruction sheets on setting up CGI application with > Python as scripting engine. ?I'm just getting 404 for the test script, > whereas an html file in the same virtual directory is properly > displayed. > > Here: > > Creating Applications in IIS 6.0 (IIS 6.0)http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Librar... > > Setting Application Mappings in IIS 6.0 (IIS 6.0)http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Librar... > > I mapped the exe thus: ?c:\Python26\python.exe -u "%s %s" > to extension `py' for all verbs and checked the `script engine' box. > > There are no errors in the script itself, i ran it from the command > line to be sure. ?Further, I enabled ASP and tried using python as the > scripting language. ?That generates this error: > > > Active Server Pages error 'ASP 0129' > Unknown scripting language > /cgi/index.asp, line 1 > The scripting language 'Python' is not found on the server. > > > I can't find any good references for dealing with this, either. > > I've dicked around with this for so long, now I don't know which way > is up, anymore. > > Any thoughts on where I might be going wrong, much appreciated. > > Thanks. > > mp I had the same problem with Python 2.5 and IIS on Windows XP. I wonder if using ActivePython would make any difference? From kevinlcarlson at gmail.com Tue Aug 31 16:53:09 2010 From: kevinlcarlson at gmail.com (kevinlcarlson) Date: Tue, 31 Aug 2010 13:53:09 -0700 (PDT) Subject: Helper app for intranet site References: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> <61894f54-90ff-4e0e-9c81-860b6e9cdc15@p12g2000prn.googlegroups.com> Message-ID: <8a994714-4e42-4e53-8f67-c1357407a02e@h37g2000pro.googlegroups.com> On Aug 30, 4:13?pm, Lawrence D'Oliveiro wrote: > In message > <61894f54-90ff-4e0e-9c81-860b6e9cd... at p12g2000prn.googlegroups.com>, > > > > kevinlcarlson wrote: > > On Aug 29, 8:46 pm, Lawrence D'Oliveiro > > wrote: > > >> In message > >> <45e0772c-24a8-4cbb-a4fc-74a1b6c25... at n19g2000prf.googlegroups.com>, > >> kevinlcarlson wrote: > > >>> I'm exploring the possibility of developing a helper app for an > >>> existing internal company website. ?Basically, it would automatically > >>> scan the current page contents, including prepopulated forms, and > >>> provide context-related business rule comments to the user, via a stay- > >>> on-top wxPython panel. > > >> Seems like a roundabout way of doing it. Can?t you integrate into the > >> server code which is generating the page contents, instead of trying to > >> reverse- engineer those contents? > > > Absolutely - that would be the best way to accomplish this. > > Unfortunately, our group has no access to the web server and the > > developers have this functionality scheduled about a year into the > > future, but we need it ASAP. ?Also, our group would like to be in > > control of the code and business rule contents, rather than wait for > > updates from the busy web team... > > Conway?s Law: any piece of software reflects the organizational structure > that produced it. Hard to disagree with that sentiment - I've come across a fair amount of disorganized software in my day... ;) In any case, I'll try the WinGuiAuto approach and see how that works... From python.koda at gmail.com Tue Aug 31 16:56:26 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 16:56:26 -0400 Subject: Dumb Stupid Question About List and String In-Reply-To: <4C7D5B3F.5070102@mrabarnett.plus.com> References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: Well, I have a lot to learn :) Thank you very much both of you ! it seems to work now :p 2010/8/31 MRAB > On 31/08/2010 20:20, Alban Nona wrote: > >> Ok, here a solution: >> >> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] >> >> mySecondList = >> >> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] >> >> for n in myFirstList: >> var = str(n) >> > > Why str(n)? > > Also, it would be clearer if you used different variables for the > different loops. > > > for n in mySecondList: >> if var in n: >> mySecondList.remove(n) >> > > You shouldn't change the length of a list over which you're iterating. > Python will step along the list one entry at a time and won't notice when > you remove an entry, so the next one will be skipped. For example: > > >>> letters = ["a", "b", "c", "d", "e"] > >>> for i in letters: > ... if i == "b" or i == "c": > ... letters.remove(i) > ... > >>> print letters > ['a', 'c', 'd', 'e'] > > It removed "b" and then moved on to the next entry, which is "d" > because "b" has been removed and all the following entries have moved > down one place. It never sees "c". > > >> print mySecondList >> >> [snip] > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at columbuswebmakers.com Tue Aug 31 17:01:26 2010 From: joel.goldstick at columbuswebmakers.com (Joel Goldstick) Date: Tue, 31 Aug 2010 17:01:26 -0400 Subject: Find closest matching string based on collection of strings in list/dict/set In-Reply-To: <1283269327.22774.1392642985@webmail.messagingengine.com> References: <1283269327.22774.1392642985@webmail.messagingengine.com> Message-ID: <4C7D6DA6.80304@columbuswebmakers.com> python at bdurham.com wrote: > I'm parsing a simple, domain specific scripting language that has > commands like the following: *page, *title, *text, *footer, etc. > There are about 100 of these '*' commands. When we see a command > that we don't recognize, I would like to find the closest match > possible (from a list of all legal commands) and include this > suggestion in our diagnostic output. > > I'm not sure what you would call the type of algorithm I'm > looking for: closest matching string or auto-correct? > > Any suggestions on algorithms or python libraries that would help > me do what I'm looking for? > > Here's my short-list of ideas based on my research so far: > - Soundex > - Lawrence Philips' Metaphone Algorithm (from aspell?) > - Edit Distance Algorithm > - Levenstein Word Distance > > Any suggestions, comments on the above techniques, or ideas on a > simpler algorithm for finding close string matches based on a > list, dict, or set of possible strings? > > Thank you, > Malcolm > > Have you looked at difflib? From thomas at jollybox.de Tue Aug 31 17:04:56 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 23:04:56 +0200 Subject: Python libs on Windows ME In-Reply-To: References: Message-ID: <201008312304.57338.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to hexusnexus at gmail.com to exclaim: > I'm not guessing that this is a problem on Windows 98, but on Windows > ME modules in /Lib don't seem to load. Examples include site.py and > os.py which are both located in the top level Lib directory. The same > thing happens with Python 2.3, 2.4, and 2.5. I can't get IDLE to load > and the Python interpreter always complains that it can't load the > "site" module even if Python is run from the same directory as the > module (note: this does not happen if a module is loaded from the > current working directory while in the interpreter). What is sys.path set to ? python.exe -c "import sys; print(sys.path)" It sounds like the stdlib directory is not on sys.path. Couldn't say why though... > > I would use another os like Linux or Windows 2000, but this particular > computer can't even seem to handle even the most minimal graphical > Linux distributions. Really? I'm sure you can get Linux on there somehow. It might not be trivial, but it should definitely be possible. Out of interest: what distros did you try? From sschwarzer at sschwarzer.net Tue Aug 31 17:16:10 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 31 Aug 2010 23:16:10 +0200 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4C7D711A.5030907@sschwarzer.net> Hi, On 2010-08-31 02:05, Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. At least in CPython 2.6.5 the above code results in Traceback (most recent call last): File "test.py", line 7, in my_function() File "test.py", line 3, in my_function return my_var UnboundLocalError: local variable 'my_var' referenced before assignment as soon as the function is called. If you want to have the global my_var modified, you need a "global my_var" statement in the function body. Stefan From arnodel at googlemail.com Tue Aug 31 17:24:23 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 31 Aug 2010 22:24:23 +0100 Subject: Find closest matching string based on collection of strings in list/dict/set References: <1283269327.22774.1392642985@webmail.messagingengine.com> Message-ID: Joel Goldstick writes: > python at bdurham.com wrote: >> I'm parsing a simple, domain specific scripting language that has >> commands like the following: *page, *title, *text, *footer, etc. >> There are about 100 of these '*' commands. When we see a command >> that we don't recognize, I would like to find the closest match >> possible (from a list of all legal commands) and include this >> suggestion in our diagnostic output. >> >> I'm not sure what you would call the type of algorithm I'm >> looking for: closest matching string or auto-correct? >> >> Any suggestions on algorithms or python libraries that would help >> me do what I'm looking for? >> >> Here's my short-list of ideas based on my research so far: >> - Soundex >> - Lawrence Philips' Metaphone Algorithm (from aspell?) >> - Edit Distance Algorithm >> - Levenstein Word Distance >> >> Any suggestions, comments on the above techniques, or ideas on a >> simpler algorithm for finding close string matches based on a >> list, dict, or set of possible strings? >> >> Thank you, >> Malcolm >> >> > Have you looked at difflib? You only have a few words to compare with, so why not try this naive solution? >>> commands = ["page", "text", "footer", "header", "title"] >>> def closest(u): ... return min(commands, key=lambda v: len(set(u) ^ set(v))) ... >>> closest("paige") 'page' >>> closest("heeder") 'header' >>> closest("tilte") 'title' -- Arnaud PS: oddly, I didn't see the OP (reading newsgroup). From anand.shashwat at gmail.com Tue Aug 31 17:25:58 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Wed, 1 Sep 2010 02:55:58 +0530 Subject: Find closest matching string based on collection of strings in list/dict/set In-Reply-To: <4C7D6DA6.80304@columbuswebmakers.com> References: <1283269327.22774.1392642985@webmail.messagingengine.com> <4C7D6DA6.80304@columbuswebmakers.com> Message-ID: On Wed, Sep 1, 2010 at 2:31 AM, Joel Goldstick < joel.goldstick at columbuswebmakers.com> wrote: > python at bdurham.com wrote: > >> I'm parsing a simple, domain specific scripting language that has >> commands like the following: *page, *title, *text, *footer, etc. >> There are about 100 of these '*' commands. When we see a command >> that we don't recognize, I would like to find the closest match >> possible (from a list of all legal commands) and include this >> suggestion in our diagnostic output. >> >> I'm not sure what you would call the type of algorithm I'm >> looking for: closest matching string or auto-correct? >> >> Any suggestions on algorithms or python libraries that would help >> me do what I'm looking for? >> >> Here's my short-list of ideas based on my research so far: >> - Soundex >> - Lawrence Philips' Metaphone Algorithm (from aspell?) >> - Edit Distance Algorithm >> - Levenstein Word Distance >> >> Any suggestions, comments on the above techniques, or ideas on a >> simpler algorithm for finding close string matches based on a >> list, dict, or set of possible strings? >> >> Thank you, >> Malcolm >> >> >> Have you looked at difflib? > On a side note, you can read this awesome article by Peter Norvig. http://norvig.com/spell-correct.html > -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.kapps at web.de Tue Aug 31 17:33:27 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Tue, 31 Aug 2010 23:33:27 +0200 Subject: Python libs on Windows ME In-Reply-To: <201008312304.57338.thomas@jollybox.de> References: <201008312304.57338.thomas@jollybox.de> Message-ID: <4C7D7527.2040703@web.de> Thomas Jollans wrote: >> I would use another os like Linux or Windows 2000, but this particular >> computer can't even seem to handle even the most minimal graphical >> Linux distributions. > > Really? I'm sure you can get Linux on there somehow. It might not be trivial, > but it should definitely be possible. Out of interest: what distros did you > try? In my experiences, getting /some/ Linux on a usual, say, post-1995 PC is almost trivial, even with GUI. It's just a matter of choosing the right distro (and desktop environment). If the OP would post the exact hardware specs, I'm almost sure, that we can find a distro that works without much hassle. From sschwarzer at sschwarzer.net Tue Aug 31 17:35:07 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 31 Aug 2010 23:35:07 +0200 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D758B.7090406@sschwarzer.net> Hi Grant, On 2010-08-31 20:49, Grant Edwards wrote: > How many filenames contain ","? CVS repository files end with ,v . However, just let's agree that nobody uses CVS anymore. :-) > Not many, but the OP wants his > program to be bulletproof. Can't fault him for that. What about using the csv (not CVS) module? Stefan From AmFreak at web.de Tue Aug 31 17:45:13 2010 From: AmFreak at web.de (AmFreak at web.de) Date: Tue, 31 Aug 2010 23:45:13 +0200 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: Thanks for all the nice answers! > The normal thing to do is to escape the delimiter when it appears in > data. There are lots of plenty of escaping standards to choose from, > and some of them (e.g. the one used for URLs) are already present > in various bits of Python's standard library. The CSV module has something like that, but im using unicode and it doesn't work with that. > Why is your impression that the null character is "dirty"? >E.g. that's how find|xargs etc. usually work. >Another alternative would be if you gaurantee that your varn's don't > have commas then put the path last. But that doesn't account for > filenames containing newlines. >Another alternative would be to wrap with some kind of serialization > library. But really, what's so dirty about null? I think i just prefer a little formated file instead of one loooong row :) > A simple solution would be to save each line of data using JSON with the > json > module: >>> import json >>> path = "x,y,z" >>> varA = 12 >>> varB = "abc" >>> line = json.dumps([path, varA, varB]) >>> print line ["x,y,z", 12, "abc"] >>> loadpathA, loadvarA, loadvarB = json.loads(line) >>> print loadpathA x,y,z >>> print loadvarA 12 >>> print loadvarB abc Thanks, just tried it - so simple, but seems to work like a charm. Really aprecciated :D. From krister.svanlund at gmail.com Tue Aug 31 17:45:57 2010 From: krister.svanlund at gmail.com (Krister Svanlund) Date: Tue, 31 Aug 2010 23:45:57 +0200 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: On Tue, Aug 31, 2010 at 5:10 PM, Benjamin Kaplan wrote: > On Tuesday, August 31, 2010, Roman Sokolyuk wrote: >> Hi, >> >> I am new to Python and I wanted to understand something... >> The EVE Online Client is build using Stackless Python >> So when I install the client on my machine, how doe sit get run if I do not have Python installed? >> > We call it "freezing" the program. There are several tools that do > this with py2exe being the most popular. These tools create an > executable that includes a bundled python interpreter along with all > the scripts and modules needed to run the program. >> Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > I'm not sure but I do believe it is mainly the servers that are written in stackless... From benjamin.kaplan at case.edu Tue Aug 31 17:50:21 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 31 Aug 2010 17:50:21 -0400 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: On Tue, Aug 31, 2010 at 5:45 PM, Krister Svanlund wrote: > On Tue, Aug 31, 2010 at 5:10 PM, Benjamin Kaplan > wrote: >> On Tuesday, August 31, 2010, Roman Sokolyuk wrote: >>> Hi, >>> >>> I am new to Python and I wanted to understand something... >>> The EVE Online Client is build using Stackless Python >>> So when I install the client on my machine, how doe sit get run if I do not have Python installed? >>> >> We call it "freezing" the program. There are several tools that do >> this with py2exe being the most popular. These tools create an >> executable that includes a bundled python interpreter along with all >> the scripts and modules needed to run the program. >>> Thanks. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I'm not sure but I do believe it is mainly the servers that are > written in stackless... > You'd have a hard time scripting the game with Python if only the server used it. http://wiki.eveonline.com/en/wiki/How_is_the_game_logic_implemented_in_EVE From python at mrabarnett.plus.com Tue Aug 31 17:53:50 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 22:53:50 +0100 Subject: Optimising literals away In-Reply-To: References: <69a8fbbc-5f45-491a-adf3-2fb5a4d79660@s9g2000yqd.googlegroups.com> Message-ID: <4C7D79EE.8010402@mrabarnett.plus.com> On 31/08/2010 21:18, Terry Reedy wrote: > On 8/31/2010 12:33 PM, Aleksey wrote: >> On Aug 30, 10:38 pm, Tobias Weber wrote: >>> Hi, >>> whenever I type an "object literal" I'm unsure what optimisation will do >>> to it. > > Optimizations are generally implentation dependent. CPython currently > creates numbers, strings, and tuple literals just once. Mutable literals > must be created each time as they may be bound and saved. > >>> def m(arg): >>> if arg& set([1,2,3]): > > set() is a function call, not a literal. When m is called, who knows > what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, > which is much faster as it avoids creating and deleting a list. On my > machine, .35 versus .88 usec. Even then, it must be calculated each time > because sets are mutable and could be returned to the calling code. > There's still the possibility of some optimisation. If the resulting set is never stored anywhere (bound to a name, for example) then it could be created once. When the expression is evaluated there could be a check so see whether 'set' is bound to the built-in class, and, if it is, then just use the pre-created set. >>> return 4 >>> >>> Is the set created every time the method is called? What about a >>> frozenset? Or tuple vs list? After how many calls per second does it pay >>> to save it at the module level? Would anybody else find this ugly? > > Defining module level constants is considered good practice in some > circles, especially if is something you might want to change. That is > what function definitions are (as long as the name is not redefined. > This is different from having lots of module level variables. > > To see what CPython does, you can use the dis module. > From python.koda at gmail.com Tue Aug 31 17:57:45 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 17:57:45 -0400 Subject: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: Just Another Question on this one, Im trying to create that kind of thing in code now: #GENERE ET INCREMENT LE NOM DES ELEMENTS val = 0 list = ["0", "1", "2", "3"] listEl = [] for n in list: val = val + 1 next = "00" +str(val) elem = "ELM"+next listEl.append(elem) #INCREMENT LE NOM DES ELEMENTS AVEC LE NOM DES PASSES listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE", "DPF", "SDW", "MAT", "WPP"] listElem = [] for first in listEl: for second in listPass: listElem.append(first+"_"+second) print listElem print listEl What I would like to do is: if 'ELM001' Contained in one of the entries of listElem, create a new list with only 'ELM001' Elements (eg: newList=['ELM001_DIF', 'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS', 'ELM001_REFR', 'ELM001_ALB', 'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE', 'ELM001_DPF', 'ELM001_SDW', 'ELM001_MAT', 'ELM001_WPP'] Damn Im sooooooooo lost with this tables and loop, Im always trying to understand in which way I should do it.... :/ Any Ideas please ? 2010/8/31 Alban Nona > Well, I have a lot to learn :) > > Thank you very much both of you ! it seems to work now :p > > 2010/8/31 MRAB > >> On 31/08/2010 20:20, Alban Nona wrote: >> >> Ok, here a solution: >>> >>> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] >>> >>> mySecondList = >>> >>> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] >>> >>> for n in myFirstList: >>> var = str(n) >>> >> >> Why str(n)? >> >> Also, it would be clearer if you used different variables for the >> different loops. >> >> >> for n in mySecondList: >>> if var in n: >>> mySecondList.remove(n) >>> >> >> You shouldn't change the length of a list over which you're iterating. >> Python will step along the list one entry at a time and won't notice when >> you remove an entry, so the next one will be skipped. For example: >> >> >>> letters = ["a", "b", "c", "d", "e"] >> >>> for i in letters: >> ... if i == "b" or i == "c": >> ... letters.remove(i) >> ... >> >>> print letters >> ['a', 'c', 'd', 'e'] >> >> It removed "b" and then moved on to the next entry, which is "d" >> because "b" has been removed and all the following entries have moved >> down one place. It never sees "c". >> >> >>> print mySecondList >>> >>> [snip] >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hexusnexus at gmail.com Tue Aug 31 18:09:07 2010 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Tue, 31 Aug 2010 15:09:07 -0700 (PDT) Subject: Python libs on Windows ME References: Message-ID: On Aug 31, 2:04?pm, Thomas Jollans wrote: > On Tuesday 31 August 2010, it occurred to hexusne... at gmail.com to exclaim: > > > I'm not guessing that this is a problem on Windows 98, but on Windows > > ME modules in /Lib don't seem to load. ?Examples include site.py and > > os.py which are both located in the top level Lib directory. ?The same > > thing happens with Python 2.3, 2.4, and 2.5. ?I can't get IDLE to load > > and the Python interpreter always complains that it can't load the > > "site" module even if Python is run from the same directory as the > > module (note: this does not happen if a module is loaded from the > > current working directory while in the interpreter). > > What is sys.path set to ? > > python.exe -c "import sys; print(sys.path)" > > It sounds like the stdlib directory is not on sys.path. Couldn't say why > though... > > > > > I would use another os like Linux or Windows 2000, but this particular > > computer can't even seem to handle even the most minimal graphical > > Linux distributions. > > Really? I'm sure you can get Linux on there somehow. It might not be trivial, > but it should definitely be possible. Out of interest: what distros did you > try? I think Puppy Linux might work, but I'd need GTK for wxPython, and I assume that means version 2 of GTK which I'm not sure comes with Puppy Linux and I've experienced problems in the past compiling GTK with './ configure && make' and so on. Yeah, for some reason, the sys.path variable was set with 'python' instead of 'Python25'. Funny how I never had that problem on Windows XP. Renaming the directory or appending to sys.path fixes that problem. From cs at zip.com.au Tue Aug 31 18:11:28 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 1 Sep 2010 08:11:28 +1000 Subject: Optimising literals away In-Reply-To: <4C7D79EE.8010402@mrabarnett.plus.com> References: <4C7D79EE.8010402@mrabarnett.plus.com> Message-ID: <20100831221128.GA25577@cskk.homeip.net> On 31Aug2010 22:53, MRAB wrote: [...] | >>>def m(arg): | >>>if arg& set([1,2,3]): | > | >set() is a function call, not a literal. When m is called, who knows | >what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, | >which is much faster as it avoids creating and deleting a list. On my | >machine, .35 versus .88 usec. Even then, it must be calculated each time | >because sets are mutable and could be returned to the calling code. | > | There's still the possibility of some optimisation. If the resulting | set is never stored anywhere (bound to a name, for example) then it | could be created once. When the expression is evaluated there could be | a check so see whether 'set' is bound to the built-in class, and, if it | is, then just use the pre-created set. Wouldn't you need to repeat that check every time, otherwise "set" may no longer be the builtin? -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ From sci.physics: tron at mailzone.com: The only problem is, how do you send a message from Earth to Mars instantly? Does anyone have any ideas about where we can start? John Baez References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: <4C7D81A9.9040006@mrabarnett.plus.com> On 31/08/2010 22:57, Alban Nona wrote: > Just Another Question on this one, Im trying to create that kind of > thing in code now: > > #GENERE ET INCREMENT LE NOM DES ELEMENTS > > val = 0 > > list = ["0", "1", "2", "3"] > > listEl = [] > > for n in list: > > val = val + 1 > > next = "00" +str(val) > > elem = "ELM"+next > > listEl.append(elem) > > > > #INCREMENT LE NOM DES ELEMENTS AVEC LE NOM DES PASSES > > listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", > "MVE", "DPF", "SDW", "MAT", "WPP"] > > listElem = [] > > for first in listEl: > > for second in listPass: > > listElem.append(first+"_"+second) > > > print listElem > > print listEl > > > What I would like to do is: > > if 'ELM001' Contained in one of the entries of listElem, create a new > list with only 'ELM001' Elements (eg: newList=['ELM001_DIF', > 'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS', 'ELM001_REFR', 'ELM001_ALB', > 'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE', 'ELM001_DPF', 'ELM001_SDW', > 'ELM001_MAT', 'ELM001_WPP'] > > Damn Im sooooooooo lost with this tables and loop, Im always trying to > understand in which way I should do it.... :/ > Any Ideas please ? > How about: newList = [] for elem in listElem: if 'ELM001' in elem: newList.append(elem) From contact at xavierho.com Tue Aug 31 18:29:51 2010 From: contact at xavierho.com (Xavier Ho) Date: Wed, 1 Sep 2010 08:29:51 +1000 Subject: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: On 1 September 2010 07:57, Alban Nona wrote: > listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE", > "DPF", "SDW", "MAT", "WPP"] > Out of curiosity, could you briefly mention what "SDW" and "WPP" passes are? I've worked out the rest, and these two are riddling my brain. (On topic: If you want only the elements starting with ELM001, or whatever, use a if condition like what MRAB posted.) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 31 18:38:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 23:38:26 +0100 Subject: Optimising literals away In-Reply-To: <20100831221128.GA25577@cskk.homeip.net> References: <4C7D79EE.8010402@mrabarnett.plus.com> <20100831221128.GA25577@cskk.homeip.net> Message-ID: <4C7D8462.8060505@mrabarnett.plus.com> On 31/08/2010 23:11, Cameron Simpson wrote: > On 31Aug2010 22:53, MRAB wrote: > [...] > |>>>def m(arg): > |>>>if arg& set([1,2,3]): > |> > |>set() is a function call, not a literal. When m is called, who knows > |>what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, > |>which is much faster as it avoids creating and deleting a list. On my > |>machine, .35 versus .88 usec. Even then, it must be calculated each time > |>because sets are mutable and could be returned to the calling code. > |> > | There's still the possibility of some optimisation. If the resulting > | set is never stored anywhere (bound to a name, for example) then it > | could be created once. When the expression is evaluated there could be > | a check so see whether 'set' is bound to the built-in class, and, if it > | is, then just use the pre-created set. > > Wouldn't you need to repeat that check every time, otherwise "set" may > no longer be the builtin? Isn't that what I said? My point is that if you have a set of constants which is created and then discarded you can cache it and reuse it next time. You check every time whether 'set' is bound to the set class. From oliver.saunders at gmail.com Tue Aug 31 18:46:11 2010 From: oliver.saunders at gmail.com (Ollie Saunders) Date: Tue, 31 Aug 2010 15:46:11 -0700 (PDT) Subject: Ed Lambda: Functional programming meetup in Edinburgh Message-ID: <4038fe03-28d9-42eb-a982-8b6fff52c794@v41g2000yqv.googlegroups.com> Hi guys, I'm running a meetup for functional programming in Edinburgh. The first one will be on the 13th of September at Malone's Irish Bar (14 Forrest Road) and will continue every 2nd monday of each month. For the first meetup I think we'll just be having a chat and getting to know each other but I hope to be able to expand it to talks and coding dojos once we have some regular numbers. For more details: http://meetup.com/ed-lambda/ And we're on Twitter: http://twitter.com/ed_lambda From tjreedy at udel.edu Tue Aug 31 19:24:19 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Aug 2010 19:24:19 -0400 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: On 8/31/2010 10:09 AM, Aahz wrote: > In article, > Jerry Hill wrote: >> On Mon, Aug 30, 2010 at 7:42 PM, Aahz wrote: >>> >>> Possibly; IMO, people should not need to run timeit to determine basic >>> algorithmic speed for standard Python datatypes. >> >> http://wiki.python.org/moin/TimeComplexity takes a stab at it. IIRC, >> last time this came up, there was some resistance to making promises >> about time complexity in the official docs, since that would make >> those numbers part of the language, and thus binding on other >> implementations. > > I'm thoroughly aware of that page and updated it yesterday to make it > easier to find. ;-) > > However, I think there are some rock-bottom basic guarantees we can make > regardless of implementation. Does anyone seriously think that an > implementation would be accepted that had anything other than O(1) for > index access into tuples and lists? Does anyone seriously think that an implementation should be rejected as an implementation if it intellegently did seq[n] lookups in log2(n)/31 time units for all n (as humans would do), instead of stupidly taking 1 time unit for all n < 2**31 and rejecting all larger values (as 32-bit CPython does)? > Dicts that were not O(1) for access with non-pathological hashing? You would actually be unhappy if small dicts ran even faster than they do now (while large dicts ran the same)? Not me! > I suggest that we should agree on these guarantees and document them in > the core. I disagree for several reasons. 1. It would a category mistake. Python is an abstract algorithm language. The concept of speed is not applicable. I happen to think it one of the best, which is why I once dubbed it 'executable pseudocode', to compare it to similar but inferior, non-executable algorithm languages too often used still today. To human readers, as readers, speed of CPython or anything else is not relevant. 2. A Python interpreter is an abstract algorithm. Algorithms can be characterized by operation counts, but not by physical universe time. 3. Algorithms, including Python interpreters, can be embodied in anything that can compute, including humans, VonNeuman machines of various types, and possible future non-VonNeuman machines. To limit 'python interpreter' to current vonNeuman machines would be short sighted. Human interpretation of Python code (and other specifications) is part of development, testing, and debugging. 4. Guarantee? Who will pay what to who if what is not performed ;-?. The Python license intentionally disclaims any guarantee of performance. If you are using 'guarantee' metaphorically, perhaps try another word. 5. Accepted? If you want to claim that an interpreter that is useless for your purposes is not really an interpreter, you are free to, I suppose. Asking the PSF to impose your view on me would, to me, violate its diversity policy. 6. O-notation was developed for characterizing the asymptotic (large-N) behavior of abstract algorithms in terms of abstract operation counts. Left out are differences between operations, lower order terms, multiplicative constants, how large N must be to get large-N behavior, and what happens for smaller N. These and other factors make the translation of O(f(n)) into real time extremely mushy or even wrong. I already suggested that O(1) lookup is a symption of simple-minded arithmetic stupidity, of doing unnecessary work when adding small numbers. When it is a result doing most additions slower than necessary, it is a bad thing, not a good thing, and a bad criteria for an acceptable algorithm and acceptable interpreter. Similarly, books say that O(n*logn) sorting is 'better' that O(n**2) sorting. However, Tim Peters verified that the opposite is true for real times for small n, and hence the current list.sort smartly uses a fast O(n**2) algorithm for small lists (len < 64) and small runs in larger lists. Rejecting list.sort for this reason would be stupid. -- Terry Jan Reedy From aurfalien at gmail.com Tue Aug 31 19:24:26 2010 From: aurfalien at gmail.com (aurfalien at gmail.com) Date: Tue, 31 Aug 2010 16:24:26 -0700 Subject: msg.attach multiple attachments and passing vars to html Message-ID: Hi, Few questions as I've been at this for dayz. Can I do multiple attachments in order via msg.attach as so; part1 = MIMEText(html, 'html') msg.attach(part1) part2 = MIMEText(text, 'plain') msg.attach(part2) part3 = MIMEText(html, 'html') msg.attach(part3) I desire to attach part1, part2 and part3 in that order. Also, is it somehow possible to pas python vars to html? My goal to to have an email that says something like; Welcome to ACME. A few LINKS to get you started. Your user name is USRNM and your password is PASS Where USRNM and PASS are python vars but the rest is an html based email. LINKS is an actual hyperlink, hence the desire to do html based emails. Thanks in advance, - aurf From tjreedy at udel.edu Tue Aug 31 19:33:12 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Aug 2010 19:33:12 -0400 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: On 8/31/2010 11:10 AM, Benjamin Kaplan wrote: > On Tuesday, August 31, 2010, Roman Sokolyuk wrote: >> Hi, >> >> I am new to Python and I wanted to understand something... >> The EVE Online Client is build using Stackless Python >> So when I install the client on my machine, how doe sit get run if I do not have Python installed? >> > We call it "freezing" the program. There are several tools that do > this with py2exe being the most popular. These tools create an > executable that includes a bundled python interpreter along with all > the scripts and modules needed to run the program. Bundling Python with an app adds a few megabytes, depending on how many modules are included. For a 10K script, that is a big nuisance. For a 100M+ app, it is trivial. While I have not yet tried Eve, both for lack of a good enough machine and fear of having my life sucked away, it has been a positive for Python. Beyond the publicity, Eve is a pretty good stress test, and they have contributed a few bug reports and patches back to the core. -- Terry Jan Reedy From alex.kapps at web.de Tue Aug 31 19:36:14 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Wed, 01 Sep 2010 01:36:14 +0200 Subject: Python libs on Windows ME In-Reply-To: References: Message-ID: <4C7D91EE.3060108@web.de> hexusnexus at gmail.com wrote: > On Aug 31, 2:04 pm, Thomas Jollans wrote: >> On Tuesday 31 August 2010, it occurred to hexusne... at gmail.com to exclaim: >> >>> I'm not guessing that this is a problem on Windows 98, but on Windows >>> ME modules in /Lib don't seem to load. Examples include site.py and >>> os.py which are both located in the top level Lib directory. The same >>> thing happens with Python 2.3, 2.4, and 2.5. I can't get IDLE to load >>> and the Python interpreter always complains that it can't load the >>> "site" module even if Python is run from the same directory as the >>> module (note: this does not happen if a module is loaded from the >>> current working directory while in the interpreter). >> What is sys.path set to ? >> >> python.exe -c "import sys; print(sys.path)" >> >> It sounds like the stdlib directory is not on sys.path. Couldn't say why >> though... >> >> >> >>> I would use another os like Linux or Windows 2000, but this particular >>> computer can't even seem to handle even the most minimal graphical >>> Linux distributions. >> Really? I'm sure you can get Linux on there somehow. It might not be trivial, >> but it should definitely be possible. Out of interest: what distros did you >> try? > > I think Puppy Linux might work, but I'd need GTK for wxPython, and I > assume that means version 2 of GTK which I'm not sure comes with Puppy > Linux and I've experienced problems in the past compiling GTK with './ > configure && make' and so on. Well, just try. AFAIK, Puppy has GTK2 (actually, it would surprise me if not) From ameyer2 at yahoo.com Tue Aug 31 20:20:12 2010 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 31 Aug 2010 20:20:12 -0400 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D9C3C.70706@yahoo.com> On 8/31/2010 2:33 PM, Nobody wrote: ... > FWIW, my usual solution is URL-encoding (i.e. replacing any "awkward" > character by a "%" followed by two hex digits representing the byte's > value). It has the advantage that you can extend the set of bytes which > need encoding as needed without having to change the code (e.g. you can > provide a command-line argument or configuration file setting which > specifies which bytes need to be encoded). I like that one. A similar solution is to use an escape character, e.g., backslash, e.g., "This is a backslash\\ and this is a comma\,." However, because the comma won't appear at all in the URL-encoded version, it has the virtue of still allowing you to split on commas. You must of course also URL encode the '%' as %25, e.g., "Here is a comma (%2C) and this (%2C) is a percent sign." Alan From nobody at nowhere.com Tue Aug 31 20:25:37 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 01 Sep 2010 01:25:37 +0100 Subject: Saving (unusual) linux filenames References: Message-ID: On Tue, 31 Aug 2010 18:49:33 +0000, Grant Edwards wrote: >> How many filenames contain control characters? > > How many filenames contain ","? Not many, Unless you only ever deal with "Unix folk", it's not /that/ uncommon to encounter filenames which are essentially complete sentences, punctuation included. FWIW, I've found that a significant proportion of "why can't I burn this file to a CD" queries are because the Joliet extension to ISO-9660 "only" allows 64 characters in a filename. From python at mrabarnett.plus.com Tue Aug 31 20:44:10 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 01 Sep 2010 01:44:10 +0100 Subject: msg.attach multiple attachments and passing vars to html In-Reply-To: References: Message-ID: <4C7DA1DA.9040205@mrabarnett.plus.com> On 01/09/2010 00:24, aurfalien at gmail.com wrote: > Hi, > > Few questions as I've been at this for dayz. > > Can I do multiple attachments in order via msg.attach as so; > > part1 = MIMEText(html, 'html') > msg.attach(part1) > part2 = MIMEText(text, 'plain') > msg.attach(part2) > part3 = MIMEText(html, 'html') > msg.attach(part3) > > I desire to attach part1, part2 and part3 in that order. > This might help: http://snippets.dzone.com/posts/show/2038 > Also, is it somehow possible to pas python vars to html? > > My goal to to have an email that says something like; > > Welcome to ACME. > > A few LINKS to get you started. > > Your user name is USRNM and your password is PASS > > Where USRNM and PASS are python vars but the rest is an html based email. > > LINKS is an actual hyperlink, hence the desire to do html based emails. > Create a template HTML with placeholders and then the individual HTML by replacing the placeholders with the values, something like: template_html = "Your user name is %USRNM% and your password is %PASS%." ... user_html = template_html.replace("%USRNM%", username).replace("%PASS%", password) That's the general idea. From ldo at geek-central.gen.new_zealand Tue Aug 31 20:47:47 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 01 Sep 2010 12:47:47 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> <7xr5hguzzi.fsf@ruckus.brouhaha.com> <7xtymbzixt.fsf@ruckus.brouhaha.com> Message-ID: In message <7xtymbzixt.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > It's pretty well established by now that GC doesn't have any significant > speed penalty compared with manual allocation. It does consume more > memory, which is acceptable a lot of the time. It certainly leads to > more reliable programs. And yet Java code, for example, doesn?t have a reputation for greater reliability compared to, say code written in Ada or C++, or even C. What is the Java runtime written in? C. Why not use Java, if there is no speed penalty in doing so? From Eric_Dexter at msn.com Tue Aug 31 20:51:59 2010 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Tue, 31 Aug 2010 17:51:59 -0700 (PDT) Subject: ride tab editor 2.03 has been released Message-ID: <5f352ccf-71ba-45a9-9139-50eecf3d0d40@f6g2000yqa.googlegroups.com> ride tab editor 2.03 has been released. ride tab editor features customizable instruments and an editable tool menu (alpha help would be nice). also included are some scripts showing how you can use the output files in csound. The 2 series is an expansion of ride guitar tab editor that managed to get over 2000 downloads. http://dexrowem.blogspot.com/search?q=ride+tab+editor From clp2 at rebertia.com Tue Aug 31 20:53:48 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 31 Aug 2010 17:53:48 -0700 Subject: msg.attach multiple attachments and passing vars to html In-Reply-To: <4C7DA1DA.9040205@mrabarnett.plus.com> References: <4C7DA1DA.9040205@mrabarnett.plus.com> Message-ID: On Tue, Aug 31, 2010 at 5:44 PM, MRAB wrote: > On 01/09/2010 00:24, aurfalien at gmail.com wrote: >> Also, is it somehow possible to pas python vars to html? >> >> My goal to to have an email that says something like; >> >> Welcome to ACME. >> A few LINKS to get you started. >> Your user name is USRNM and your password is PASS >> >> Where USRNM and PASS are python vars but the rest is an html based email. >> LINKS is an actual hyperlink, hence the desire to do html based emails. >> > Create a template HTML with placeholders and then the individual HTML > by replacing the placeholders with the values, something like: > > ? ?template_html = "Your user name is %USRNM% and your password is %PASS%." > ? ... > ? user_html = template_html.replace("%USRNM%", username).replace("%PASS%", > password) > > That's the general idea. In the general case though, one needs to be sure to properly escape the inserted text: from cgi import escape user_html = template_html.replace("%USRNM%", escape(username)).replace("%PASS%", escape(password)) Also, string formatting would probably be safer than .replace() in the unlikely but not impossible event that user input and the magic placeholder names overlap. Cheers, Chris -- http://blog.rebertia.com From ldo at geek-central.gen.new_zealand Tue Aug 31 20:55:57 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 01 Sep 2010 12:55:57 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> Message-ID: In message <7x39tz42fd.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Dennis Lee Bieber writes: > >> Heap marking, OTOH, tends to run at indeterminate times, which could >> have an impact if one needs predictable response timings > > Reference counting has the same problem. If you drop the last reference > to a complex structure, it could take quite a long time to free all the > components. One difference is the interaction with caching behaviour. When a reference- counted object is freed, the odds are that happens fairly soon after the last access, so the object will still be in the CPU cache, and access will be fast. Whereas garbage collection will happen at some indeterminate time long after the last access to the object, when it very likely will no longer be in the cache, and have to be brought back in just to be freed, quite likely bumping out something else that the running program needs to access. This is one reason why garbage collection is still considered an expensive technique. Computing power has improved by something like five orders of magnitude over the last half-century, making possible all kinds of productivity-enhancing techniques that were once considered expensive to become commonplace: high-level languages, dynamic memory allocation, stacks, hardware floating-point, memory protection and so on. But alone of all of these, garbage collection still remains just as costly to implement as ever. That should tell you something about how poorly it matches the characteristics of modern computing hardware. From ldo at geek-central.gen.new_zealand Tue Aug 31 20:57:11 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 01 Sep 2010 12:57:11 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> <7xhbidndc6.fsf@ruckus.brouhaha.com> <8e15pqFn89U1@mid.individual.net> <7xmxs4uzjl.fsf@ruckus.brouhaha.com> Message-ID: In message <7xmxs4uzjl.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Gregory Ewing writes: > >> I'd be disappointed if CPython ditched refcounting and >> then became unsuitable for real-time games as a result. > > Refcounting is susceptable to the same pauses for reasons already > discussed. Doesn?t seem to happen in the real world, though. From cs at zip.com.au Tue Aug 31 21:22:45 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 1 Sep 2010 11:22:45 +1000 Subject: Optimising literals away In-Reply-To: <4C7D8462.8060505@mrabarnett.plus.com> References: <4C7D8462.8060505@mrabarnett.plus.com> Message-ID: <20100901012244.GA23427@cskk.homeip.net> On 31Aug2010 23:38, MRAB wrote: | On 31/08/2010 23:11, Cameron Simpson wrote: | >On 31Aug2010 22:53, MRAB wrote: | >| There's still the possibility of some optimisation. If the resulting | >| set is never stored anywhere (bound to a name, for example) then it | >| could be created once. When the expression is evaluated there could be | >| a check so see whether 'set' is bound to the built-in class, and, if it | >| is, then just use the pre-created set. | > | >Wouldn't you need to repeat that check every time, otherwise "set" may | >no longer be the builtin? | | Isn't that what I said? Yes. It's not what my brain decided to read to me. | My point is that if you have a set of constants which is created and | then discarded you can cache it and reuse it next time. You check every | time whether 'set' is bound to the set class. Ok then. I was thinking, for some reason, a JIT-like behaviour that didn't just reuse the previously made set but replaced the set([1,2,3]) itself, thus omitting the test you mentioned:-( Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ It's hard to make a man understand something when his livelihood depends on him not understanding it. - Upton Sinclair From mahaboobnisha at gmail.com Tue Aug 31 21:26:01 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Tue, 31 Aug 2010 18:26:01 -0700 (PDT) Subject: comp.lang.python Message-ID: www.127760.blogspot.com From reply-to at works.fine.invalid Tue Aug 31 21:51:25 2010 From: reply-to at works.fine.invalid (NickC) Date: 01 Sep 2010 01:51:25 GMT Subject: Structured programming with optionParser References: <4c7c5eca$0$11121$c3e8da3@news.astraweb.com> Message-ID: <4c7db19d$0$11121$c3e8da3@news.astraweb.com> On Mon, 30 Aug 2010 21:19:08 -0700, Michele Simionato wrote: > Perhaps, I should give an example of using plac. > > For more (including managing options, which I have not shown here) you > should check the full documentation of plac. I have just uploaded > release 0.7.2, which is required for this example to work. Many thanks, very useful. -- NickC From python.koda at gmail.com Tue Aug 31 22:00:45 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 22:00:45 -0400 Subject: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: @MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ? is there a way to do it automaticaly ? @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as WordPointCloud passe) :) Anyway, thank you ! 2010/8/31 Xavier Ho > On 1 September 2010 07:57, Alban Nona wrote: > >> listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE", >> "DPF", "SDW", "MAT", "WPP"] >> > > Out of curiosity, could you briefly mention what "SDW" and "WPP" passes > are? I've worked out the rest, and these two are riddling my brain. > > (On topic: If you want only the elements starting with ELM001, or whatever, > use a if condition like what MRAB posted.) > > Cheers, > Xav > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 31 22:18:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 01 Sep 2010 03:18:07 +0100 Subject: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: <4C7DB7DF.5050906@mrabarnett.plus.com> On 01/09/2010 03:00, Alban Nona wrote: > @MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ? > is there a way to do it automaticaly ? > If you can do it for 'Elem001', I'm sure you could write some code to produce a list of 'Elem001', 'Elem002', etc, and check whether any are substrings, just as was done for 'Elem001'. > @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as > WordPointCloud passe) :) > > Anyway, thank you ! > [snip] Do you want separate lists for 'Elem001', 'Elem002', etc, or all in the same list? From bussiere at gmail.com Tue Aug 31 22:33:50 2010 From: bussiere at gmail.com (bussiere bussiere) Date: Wed, 1 Sep 2010 04:33:50 +0200 Subject: [Pickle]dirty problem 3 lines Message-ID: i know it's dirty, i know i should use json but i want to know, it's quiet late here : import pickle dump = """b'\x80\x03]q\x00(K\x00K\x01e.'""" print(pickle.loads(dump)) how can i get back my object from this string ? the string is : b'\x80\x03]q\x00(K\x00K\x01e.' and i'am using python3 help will be appreciated i'am chewing on this for a long time now. Regards B. fan of dresden files From python at mrabarnett.plus.com Tue Aug 31 23:23:57 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 01 Sep 2010 04:23:57 +0100 Subject: [Pickle]dirty problem 3 lines In-Reply-To: References: Message-ID: <4C7DC74D.6060702@mrabarnett.plus.com> On 01/09/2010 03:33, bussiere bussiere wrote: > i know it's dirty, i know i should use json but i want to know, it's > quiet late here : > import pickle > dump = """b'\x80\x03]q\x00(K\x00K\x01e.'""" > print(pickle.loads(dump)) > > how can i get back my object from this string ? > the string is : b'\x80\x03]q\x00(K\x00K\x01e.' > and i'am using python3 > help will be appreciated i'am chewing on this for a long time now. Well, pickle.loads(b'\x80\x03]q\x00(K\x00K\x01e.') works. That, of course, is not the same as """b'\x80\x03]q\x00(K\x00K\x01e.'""". Do you mean r"""b'\x80\x03]q\x00(K\x00K\x01e.'"""? (It's also late here, well, actually, so late it's early... Time to sleep. :-)) From python.koda at gmail.com Tue Aug 31 23:47:08 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 23:47:08 -0400 Subject: Fwd: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> <4C7DB7DF.5050906@mrabarnett.plus.com> Message-ID: In fact, the First list (wich contain "Elm001, Elm002, Elm003) will be generated automatically from files that I have in a directory, that's why I cant write the same code for Elm002, 003, etc... Because Ill not know how many Elm there will be. 2010/8/31 MRAB > On 01/09/2010 03:00, Alban Nona wrote: > > @MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ? >> is there a way to do it automaticaly ? >> >> If you can do it for 'Elem001', I'm sure you could write some code to > produce a list of 'Elem001', 'Elem002', etc, and check whether any are > substrings, just as was done for 'Elem001'. > > > @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as >> WordPointCloud passe) :) >> >> Anyway, thank you ! >> >> [snip] > Do you want separate lists for 'Elem001', 'Elem002', etc, or all in the > same list? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sun Aug 1 00:08:51 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 31 Jul 2010 21:08:51 -0700 (PDT) Subject: Problem with Elementtree and XMLSchem instance type References: Message-ID: <96e47fd8-c939-48a2-9a2b-92afa720c8ac@k1g2000prl.googlegroups.com> On Jul 30, 6:21?am, Roland Hedberg wrote: > Hi! > > I have the following XML snippet: > > ? ? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > ? ? xmlns:fed="http://docs.oasis-open.org/wsfed/federation/200706" > ? ? xsi:type="fed:SecurityTokenServiceType"> > ? ? .... > > > This part after parsing with Elementtree gives me an Element instance > with the following properties: > > > tree.tag > > {urn:oasis:names:tc:SAML:2.0:metadata}RoleDescriptor> tree.keys() > > ['{http://www.w3.org/2001/XMLSchema-instance}type']> tree['{http://www.w3.org/2001/XMLSchema-instance}type'] > > fed:SecurityTokenServiceType > > And there is the problem, I've lost the coupling between the prefix > 'fed' and the namespace > "http://docs.oasis-open.org/wsfed/federation/200706". > > Is there any way I can get at the prefix <-> namespace mapping from an > Element instance ? > I've read the documentation I can find and there is nothing that tells > me how to get at the mapping. ElementTree doesn't have a way to do this. My general feeling is that ElementTree is a lot handier for reading and writing your own XML formats, than for handling XML files produced by other tools. The lxml package has an ElementTree like interface but with some methods to handle namespace abbreviations. Carl Banks From usernet at ilthio.net Sun Aug 1 01:17:50 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 1 Aug 2010 05:17:50 +0000 (UTC) Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 2010-08-01, Lawrence D'Oliveiro wrote: > In message , Tim Harig wrote: > >> It would be rewarding as it would make writing cross-platform charactor >> mode applications possible. > > I thought Windows users were allergic to command lines. To the best of my knowledge, there have never been any documentated cases of computer software related alleries. There are however several chemicals used in the process of constructing computer hardware componets which have been linked to allergy illnesses. Maybe Windows users are simply allergic to their computers. From breamoreboy at yahoo.co.uk Sun Aug 1 02:23:20 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Aug 2010 07:23:20 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 01/08/2010 06:17, Tim Harig wrote: > On 2010-08-01, Lawrence D'Oliveiro wrote: >> In message, Tim Harig wrote: >> >>> It would be rewarding as it would make writing cross-platform charactor >>> mode applications possible. >> >> I thought Windows users were allergic to command lines. > > To the best of my knowledge, there have never been any documentated > cases of computer software related alleries. There are however several > chemicals used in the process of constructing computer hardware componets > which have been linked to allergy illnesses. Maybe Windows users are > simply allergic to their computers. Windows users biggest allergy is to this strange world that involves "make" on other boxes, whatever that is, it strikes me as rather archaic. Personally I find double clicking on an msi file rather easier. Regards. Mark Lawrence. From legard4d at gmail.com Sun Aug 1 02:42:23 2010 From: legard4d at gmail.com (legard_new) Date: Sat, 31 Jul 2010 23:42:23 -0700 (PDT) Subject: Call CFUNCTYPE, class Structure, ctype, dll and Callback function problem References: <70faf0b4-fead-49ac-bf18-e182fd63bbff@j8g2000yqd.googlegroups.com> Message-ID: On Jul 31, 10:22?pm, "Mark Tolonen" wrote: > "legard_new" wrote in message > > news:70faf0b4-fead-49ac-bf18-e182fd63bbff at j8g2000yqd.googlegroups.com... > > > > > > > Hello, > > > I have a problem with calling Callback function with Python. I have a > > DLL file. > > > Below is a description in documentation. > > FUNCTION Callback > > Arguments: Callback ID integer read-only, immediate value > > CBackProc address read-only, immediate value > > Returns: status > > The Callback routine registers the callback routine for > > notification of a link state change. > > The callback procedure provided by the application must accept one > > parameter: > > the address of the structure containing the data. > > > CallbackID An integer identifying the callback routine being > > provided to the API. Can be one of 1 or 2. > > CBackProc The address of the callback procedure that the API will > > execute. > > > This procedure must accept one parameter, of type LinkStateStruct, > > passed by reference. > > > LinkStateStruct read-only, by reference > > OldState: byte > > NewState byte > > > The routine will return one of the following error codes: > > 1 - The callback address was successfully registered by the API. > > 2 - The API has not been initialised. > > 3 - The CallbackID value was not recognised as a valid link state > > callback. > > > Here is my little code in Python: > > > from ctypes import * > > class LinkStateStruct(Structure): > > ? ?_fields_ = [("OldState", c_byte), > > ? ? ? ? ? ? ? ?("NewState", c_byte)] > > demoapi=windll.LoadLibrary("D:\\DEMO.dll") > > #DECLARE CALLBACK FUNCTION > > g_HLSC = CFUNCTYPE(c_int, POINTER(LinkStateStruct)) > > def py_g_HLSC(x): > > ? ?print "CALLBACK__py_g_HLSC_FIRED->", x > > ? ?return 0 > > g__HLSC = g_HLSC(py_g_HLSC) > > status=demoapi.Callback(1,g__HLSC) > > print "Status=",status > > > My result is: > > Status= 1 > > > But Callback function is not executed. If think that i call g__HLSC > > witohout paramter that in document "The callback procedure > > > provided by the application must accept one parameter: the address of > > the structure containing the data.". I don't now how to do. > > I don't see anything wrong with your declarations. ?It indicates you > registered the callback successfully. ?Since the callback sounds like it > monitors changes in "link state" maybe it isn't changing. ?Perhaps you need > to call another function that causes this change. > > Here's a DLL I wrote to test your code, but I added a ChangeLinkState > function. ?When I call it after running your code the callback gets called, > so your code is working properly. > > (Compiled with Visual Studio 2008 "cl /MD /LD demo.c" > > typedef unsigned char BYTE; > > typedef struct tagLINKSTATE { > ?BYTE OldState, NewState; > > } LINKSTATE; > > typedef int (*CB)(LINKSTATE*); > > CB g_cb; > BYTE g_linkState; > > __declspec(dllexport) int __stdcall Callback(int a,CB cb) > { > ?g_cb = cb; > ?return 1; > > } > > __declspec(dllexport) void __stdcall ChangeLinkState(BYTE newState) > { > ?LINKSTATE state; > ?state.OldState = g_linkState; > ?state.NewState = newState; > ?g_linkState = newState; > ?g_cb(&state); > > } > > -Mark Thanks Mark for good news. >> Perhaps you need to call another function that causes this change. Exactly, i check again documentation and i must call another functions. Thanks for help. Best regards, Gregory From ldo at geek-central.gen.new_zealand Sun Aug 1 02:50:46 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 01 Aug 2010 18:50:46 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , Mark Lawrence wrote: > Personally I find double clicking on an msi file rather easier. Easier than apt-get dist-upgrade? From breamoreboy at yahoo.co.uk Sun Aug 1 03:03:13 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Aug 2010 08:03:13 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: > In message, Mark > Lawrence wrote: > >> Personally I find double clicking on an msi file rather easier. > > Easier than apt-get dist-upgrade? I'm sorry but I only do English, could you please translate. :) Mark Lawrence. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 1 03:16:21 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Aug 2010 07:16:21 GMT Subject: Docstrings and PEP 3174 References: Message-ID: <4c551f45$0$11091$c3e8da3@news.astraweb.com> On Sat, 31 Jul 2010 19:52:05 -0700, Carl Banks wrote: > PEP 3174 got me to thinking. > > There is now a subdirectory to deposit as many *.pyc files as you want > without cluttering the source directory (never mind the default case). > Which means you can pretty much write files with impunity. > > So I was wondering: what about a separate file just for docstrings. I'm not sure I understand what you mean by that? Do you mean that, when writing code for a function, you would open a second file for the docstring? If so, a big -INFINITY from me. The biggest advantage of docstrings is that the documentation is *right there* with the function when reading/writing code. If you're suggesting we should write them in another file, no thank you. If you mean a runtime optimization with no change to the source file, then maybe, tell me more. What I *think* you mean is that the coder would write: def spam(*args): "docs go here" pass as normal, but when it is compiled and loaded into memory, the docstring itself was *not* loaded until needed. If so, then I think you'd need to demonstrate significant practical benefit to make up for the complexity. I imagine Python-Dev will be very dubious. > __doc__ would become a descriptor that loads the docstring from the file > whenever it is referenced. "The file" being the source file, or a separate docstring file, or a temporary file generated by the compiler, or... ? > The vast majority of the time docstrings > just take up memory and do nothing, so why not lazy load those things? A guarded and provisional +0 on that. +1 if you can demonstrate real performance (memory or speed) gains. -- Steven From ldo at geek-central.gen.new_zealand Sun Aug 1 03:18:19 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 01 Aug 2010 19:18:19 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , Mark Lawrence wrote: > On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: > >> In message, Mark >> Lawrence wrote: >> >>> Personally I find double clicking on an msi file rather easier. >> >> Easier than apt-get dist-upgrade? > > I'm sorry but I only do English, could you please translate. :) I run Debian Unstable, which has new goodies coming out on a weekly basis. The last time I checked for updates, there were over 500 packages I had installed for which updates were available. It only took a command like the above to upgrade them all. How many .msi files would you have to click on to achieve the Windows equivalent? From steve at REMOVE-THIS-cybersource.com.au Sun Aug 1 03:38:44 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Aug 2010 07:38:44 GMT Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <8bfd5uF9gqU1@mid.individual.net> <4c52bc2d$0$11091$c3e8da3@news.astraweb.com> <8bhfcaF6ftU1@mid.individual.net> <4c53936d$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4c552483$0$11091$c3e8da3@news.astraweb.com> On Sat, 31 Jul 2010 13:29:25 +0000, Brian Victor wrote: > Steven D'Aprano wrote: >> On Sat, 31 Jul 2010 14:25:39 +1200, Gregory Ewing wrote: >> >>> Steven D'Aprano wrote: >>> >>>> A >>>> / \ >>>> C B >>>> \ / >>>> D >>>> / \ >>>> E F >>>> >>>> Yes, a super call might jog left from C to B, but only when being >>>> called from one of the lower classes D-F. That's still an upwards >>>> call relative to the originator, not sidewards. >>> >>> But it's not an upward call relative to the class mentioned in the >>> super() call, which is why I say it's misleading. >> >> Which class would that be? >> >> I think I'm going to need an example that demonstrates what you mean, >> because I can't make heads or tails of it. Are you suggesting that a >> call to super(C, self).method() from within C might call >> B.method(self)? > > Yes, it would. [snip example] Right, now I see what you mean. I don't have a problem with that behaviour, it is the correct behaviour, and you are making the call from D in the first place, so it *must* call B at some point. If you initiate the call from C instead: >>> C().test_mro() In C In A then B is not in C's MRO, and does not get called. This is the case I was referring to. I admit it did surprise me the first time I saw the example you gave. Hell, it *confused* me at first, until I realised that self inside the method isn't necessarily an instance of C, but could be an instance of a subclass of C (in this case, D), and then it was "Well duh, how obvious!" That's no different from a classic-style call to a superclass: # inside class C(B): B.method(self, *args) Inside B, method() gets called with an instance of C as self. Bringing it back to super(), since super(C, self) gets a D instance as argument, the MRO it looks at is D's MRO, and it all just works. I think the docs could make that a little more clear, but then, given how non- cooperative inheritance works exactly the same way, there's a good argument for saying the docs don't need to be changed at all. If the behaviour is confusing for super(), then it's confusing without super() too. See Guido's tutorial on cooperative multitasking for more detail: http://www.python.org/download/releases/2.2.3/descrintro/#cooperation > Since the idea of super() as I understand it is to make sure every class > in an object's hierarchy gets its method called, there's really no way > to implement super() in a way that didn't involve a non-superclass being > called by some class's super() call. You're reading the super() signature wrong. super(C, self) shouldn't be interpreted as "call C's superclasses from self". It means "starting just after C in the MRO, call self.__class__'s superclasses". super() never calls a non-superclass. If it did, it would be a huge bug, and inheritance would break. -- Steven From breamoreboy at yahoo.co.uk Sun Aug 1 03:52:17 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Aug 2010 08:52:17 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: > In message, Mark > Lawrence wrote: > >> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >> >>> In message, Mark >>> Lawrence wrote: >>> >>>> Personally I find double clicking on an msi file rather easier. >>> >>> Easier than apt-get dist-upgrade? >> >> I'm sorry but I only do English, could you please translate. :) > > I run Debian Unstable, which has new goodies coming out on a weekly basis. > The last time I checked for updates, there were over 500 packages I had > installed for which updates were available. It only took a command like the > above to upgrade them all. > > How many .msi files would you have to click on to achieve the Windows > equivalent? No idea, but your mental capacity is clearly infinitely higher than mine, as I simply couldn't cope with over 500 installed packages. What do they all do, make your lunch and fetch the beer from the fridge amongst other things? Cheers. Mark Lawrence. From greg.ewing at canterbury.ac.nz Sun Aug 1 04:21:08 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 01 Aug 2010 20:21:08 +1200 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <4c552483$0$11091$c3e8da3@news.astraweb.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <8bfd5uF9gqU1@mid.individual.net> <4c52bc2d$0$11091$c3e8da3@news.astraweb.com> <8bhfcaF6ftU1@mid.individual.net> <4c53936d$0$11091$c3e8da3@news.astraweb.com> <4c552483$0$11091$c3e8da3@news.astraweb.com> Message-ID: <8bkoitFpihU1@mid.individual.net> Steven D'Aprano wrote: > super(C, self) > > shouldn't be interpreted as "call C's superclasses from self". It means > "starting just after C in the MRO, call self.__class__'s superclasses". My contention is that nobody has any chance of guessing what it does based on the name "super". Superness doesn't come into it at all, except in the trivial sense that whatever class it picks will be in the mro of the second argument, which doesn't narrow it down much. So the word "super" here is little better than meaningless noise. If it were something like next_method(C, self) then one could claim with some justification that it stands for "call the next method found after C in the mro of self". -- Greg From greg.ewing at canterbury.ac.nz Sun Aug 1 04:26:21 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 01 Aug 2010 20:26:21 +1200 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: <8bkosiFpihU2@mid.individual.net> Lawrence D'Oliveiro wrote: > How many .msi files would you have to click on to achieve the Windows > equivalent? Don't you just leave the machine on overnight and wait for Microsoft to download all the stuff they think you should be using? -- Greg From greg.ewing at canterbury.ac.nz Sun Aug 1 04:30:22 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 01 Aug 2010 20:30:22 +1200 Subject: Docstrings and PEP 3174 In-Reply-To: <4c551f45$0$11091$c3e8da3@news.astraweb.com> References: <4c551f45$0$11091$c3e8da3@news.astraweb.com> Message-ID: <8bkp46FsbmU1@mid.individual.net> Steven D'Aprano wrote: > If you mean a runtime optimization with no change to the source file, > then maybe, tell me more. Note that you don't necessarily need a separate file for this. It could just be a separate part of the same file. -- Greg From georg at python.org Sun Aug 1 05:38:35 2010 From: georg at python.org (Georg Brandl) Date: Sun, 01 Aug 2010 11:38:35 +0200 Subject: [RELEASED] Python 3.2 alpha 1 Message-ID: <4C55409B.5000409@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the first alpha preview release of Python 3.2. Python 3.2 is a continuation of the efforts to improve and stabilize the Python 3.x line. Since the final release of Python 2.7, the 2.x line will only receive bugfixes, and new features are developed for 3.x only. Since PEP 3003, the Moratorium on Language Changes, is in effect, there are no changes in Python's syntax and built-in types in Python 3.2. Development efforts concentrated on the standard library and support for porting code to Python 3. Highlights are: * numerous improvements to the unittest module * PEP 3147, support for .pyc repository directories * an overhauled GIL implementation that reduces contention * many consistency and behavior fixes for numeric operations * countless fixes regarding string/unicode issues; among them full support for a bytes environment (filenames, environment variables) * a sysconfig module to access configuration information * a pure-Python implementation of the datetime module * additions to the shutil module, among them archive file support * improvements to pdb, the Python debugger For an extensive list of changes in 3.2, see Misc/NEWS in the Python distribution. To download Python 3.2 visit: http://www.python.org/download/releases/3.2/ 3.2 documentation can be found at: http://docs.python.org/3.2/ Please consider trying Python 3.2 with your code and reporting any bugs you may notice to: http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.2's contributors) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.16 (GNU/Linux) iEYEARECAAYFAkxVQJsACgkQN9GcIYhpnLBxIgCcCiVu/QUkFf0bYM2Vmi8St3mZ 2N4An04q36lr47OA+bslqG/4Zj7ZwVOX =iL8N -----END PGP SIGNATURE----- From ldo at geek-central.gen.new_zealand Sun Aug 1 06:17:02 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 01 Aug 2010 22:17:02 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <8bkosiFpihU2@mid.individual.net> Message-ID: In message <8bkosiFpihU2 at mid.individual.net>, Gregory Ewing wrote: > Don't you just leave the machine on overnight and wait > for Microsoft to download all the stuff they think > you should be using? That?s fine, but it doesn?t handle the non-Microsoft stuff. From news1234 at free.fr Sun Aug 1 06:27:12 2010 From: news1234 at free.fr (News123) Date: Sun, 01 Aug 2010 12:27:12 +0200 Subject: pylint scores In-Reply-To: References: <4C532577.8010906@free.fr> Message-ID: <4c554c01$0$6122$426a34cc@news.free.fr> Hi, On 07/31/2010 11:04 AM, Matteo Landi wrote: > What are the messages one should really care about while evaluating > its code using pylint? It's easy to get 5 scored with a "lot of public > methods" or bad named variables such as 'x' or 'y' .. Have you got any > config file to share? The most important ones are of course the errors. Some of them might be false, but in our team we agreed, that no file is allowed to report pylint errors. This means - just fixing errors (in most cases) - rewriting code (in a few cases) - masking errors with pylint directives in the source (some other few errrors) If you only want to see the errros, then just run pylint -E filename.py Note: This is a rather new but very useful switch.. It doesn't exist on Ubuntu 10.4's release pylint 0.19.0, but exists on pylint 0.21.1 Apart from that. You should discuss within your team, which errors you'd like to have ignored and adapt the pylintrc. This is a rather personal decision. For one project we disiabled for example following warnings: ## C0322 = "Operator not preceded by a space" ## C0323 = "Operator not followed by a space" ## C0324 = "Comma not followed by a space" As we did not have time to rewrite all of the existing code, that violated these rules. We prefered to 'hide' these warnings in order to sett the more important ones. On another new project however we did NOT comment therese rules and decided, that all new code should follow these rules We disabled some special global variables, which we'd like to have in lower case const-rgx ==((specialvar)|(v_[a-z_][a-z0-9_]*)|([A-Z_][A-Z0-9_]*)|(__.*__))$ you could also modify variables like # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 For some graphics module functions for example we wanted to be allowed to use variable names like x,y as they are completely meaningful names for pixel coordinates. so change the entry good-names good-names=x,y,ex,Run,_ Hope, that this gave you some ideas > > On Sat, Jul 31, 2010 at 2:48 AM, Dan Stromberg wrote: >> >> On Fri, Jul 30, 2010 at 12:18 PM, News123 wrote: >>> >>> On 07/30/2010 03:12 PM, wheres pythonmonks wrote: >>>> I am starting to use pylint to look at my code and I see that it gives a >>>> rating. >>>> What values do experienced python programmers get on code not >>>> targeting the benchmark? >>>> >>>> I wrote some code, tried to keep it under 80 characters per line, >>>> reasonable variable names, and I got: >>>> >>>> 0.12 / 10. >>>> >>>> Is this a good score for one not targeting the benchmark? (pylint >>>> running in default mode) >>>> >>> It's not a goodf core, but arrives easily if you never ran pylint before. >>> With very little effort you should be able to be above 5 >>> with a little more effort above 7 >>> >>> >>>> Somewhat related: Is the backslash the only way to extend arguments >>>> to statements over multiple lines? (e.g.) >>> >>> if you have an opening parenthesis, or bracked, then you don't need a >>> backslash >>> >>> so instead of >>> if longlonglonglonglonglonglonglongvar == \ >>> otherlonglonglonglongvar: >>> >>> you could also write: >>> >>> if (longlonglonglonglonglonglonglongvar == >>> otherlonglonglonglongvar): >>> >>> >>> same works of course with asserts. >>> >>>> >>>>>>> def f(x,y,z): return(x+y+z); >>>> ... >>>>>>> f(1,2, >>>> ... 3) >>>> 6 >>>>>>> assert f(1,2,3)>0, >>>> File "", line 1 >>>> assert f(1,2,3)>0, >>>> ^ >>>> SyntaxError: invalid syntax >>>>>>> >>>> >>>> In the above, I could split the arguments to f (I guess b/c of the >>>> parens) but not for assert. I could use a backslash, but I find this >>>> ugly -- it that my only (best?) option? >>>> >>>> [I really like to assert my code to correctness and I like using the >>>> second argument to assert, but this resulted in a lot of long lines >>>> that I was unable to break except with an ugly backslash.] >>>> >>>> W >>> >> IMO, the important thing about pylint's scoring is that it's but one way of >> many of producing good Python code. However, it's also one of the easier >> ways of producing good python code. >> I personally like to get my scores up near 10, by annotating in comments >> about the few things that pylint flags that I can't just code around. This >> requires jumping through some slightly silly hoops (EG the previously >> mentioned "too few public methods", which my various container classes >> always trip over), but going through this process is worthwhile for >> highlighting the hoops pylint can detect that -aren't- so silly. >> The one thing I like to leave unfixed is FIXME's - otherwise my preference >> would be to go for a score of 10 for production code. >> I also like to create a ./this-pylint script for my various projects, that >> have global overrides - things like identifier rules, line length, and... I >> don't get blanks instead of tabs. Blanks are fine if you don't understand >> tabs (or think someone in the future who doesn't understand tabs will need >> to work on your code), but tabs allow everyone to see code indented the way >> -they- want to see it, not just the way the original author wanted to see >> it. >> This script (./this-pylint) will also save output from the test in a text >> file, for make (or other dependency handling program) to use to avoid >> re-pylint'ing unmodified code. It'll give an error typically, if pytlint >> detects any errors other than FIXME's (excluding ones, as I mentioned >> before, that have a comment disabling the warning, of course). >> I'm more than a little sad that pylint doesn't seem to be moving to python 3 >> in any big hurry. >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > From usernet at ilthio.net Sun Aug 1 06:27:46 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 1 Aug 2010 10:27:46 +0000 (UTC) Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 2010-08-01, Mark Lawrence wrote: > On 01/08/2010 06:17, Tim Harig wrote: >> On 2010-08-01, Lawrence D'Oliveiro wrote: >>> In message, Tim Harig wrote: >>> >>>> It would be rewarding as it would make writing cross-platform charactor >>>> mode applications possible. >>> >>> I thought Windows users were allergic to command lines. >> >> To the best of my knowledge, there have never been any documentated >> cases of computer software related alleries. There are however several >> chemicals used in the process of constructing computer hardware componets >> which have been linked to allergy illnesses. Maybe Windows users are >> simply allergic to their computers. > > Windows users biggest allergy is to this strange world that involves > "make" on other boxes, whatever that is, it strikes me as rather > archaic. Personally I find double clicking on an msi file rather easier. I work with several thousand computers located on three different continents. Few of them have mice attached to them. If you think double clicking is a better method, be my guest; but, you need to get a package installed and configured on all of them before lunch. Its also kind of funny that I couldn't get the msi to work with a large percentage of the systems that I work with. Make works on all but one out of the box, and potentially on the last with the addition of SFU or Cygwin. With all that said, I am still not sure what the make/msi question has anything to do with packing a backup, cross platform, implementation of curses that allows the curses module to give Python a cross platform method of character mode manipulation. From thomas at jollans.com Sun Aug 1 06:32:19 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 01 Aug 2010 12:32:19 +0200 Subject: Normalizing A Vector In-Reply-To: References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <87sk2zhpcj.fsf@dpt-info.u-strasbg.fr> Message-ID: <4C554D33.6010903@jollans.com> On 08/01/2010 03:41 AM, Lawrence D'Oliveiro wrote: > In message <87sk2zhpcj.fsf at dpt-info.u-strasbg.fr>, Alain Ketterlin wrote: > >> Lawrence D'Oliveiro writes: >> >>> V = tuple \ >>> ( >>> x >>> / >>> l >>> for x in V >>> for l in >>> (math.sqrt(reduce(lambda a, b : a + b, (y * y for y in V), >>> 0)),) >>> ) >> >> You got the order wrong (it has to be for l ... for x ...) > > No, I deliberately put it in that order to ensure that the value for l can > only ever be evaulated once. > >> You're kind of lucky here, because the arglist to tuple() provides a >> scope that hides x and l. Be careful if you ever change tuple(...) to >> [...], because x and l would leak to the outer scope (with python 2.*). > > Interesting. However, using ?list( ... )? instead of ?[ ... ]? also prevents > the leakage. Yes. That's because the variable leakage of list comprehensions was never a good idea, and is kept in Python 2.x only for backwards compatibility. When generator expressions where introduced, it was done in such a way that the scope didn't leak (which probably wouldn't make any sense anyway since there's no guarantee a generator expression is executed at all before the next line) In Python 3, list comprehensions don't leak names any more - they act (nearly?) the same as like( ... expr ... ) now. From guandalino at gmail.com Sun Aug 1 07:01:15 2010 From: guandalino at gmail.com (guandalino) Date: Sun, 1 Aug 2010 04:01:15 -0700 (PDT) Subject: urllib2 test fails (2.7, linux) References: Message-ID: <02af1e8a-cd47-47ca-827e-52a531b36f22@l32g2000prn.googlegroups.com> On 22 Lug, 01:13, Terry Reedy wrote: > If you do not get an answer here, file a bug report. If you can, put > orsenthil,benjamin.peterson,ezio.melotti > on the nosy list, as they are recent committers to this file. Say I said > to do so if you want. Add tjreedy also so I can see responses and learn too. Done here: http://bugs.python.org/issue9446. Best regards, HAND. From news1234 at free.fr Sun Aug 1 07:08:53 2010 From: news1234 at free.fr (News123) Date: Sun, 01 Aug 2010 13:08:53 +0200 Subject: let optionparse.Optionparser ignore unknown command line switches. Message-ID: <4c5555c5$0$19337$426a74cc@news.free.fr> I wondered, whether there's a simple/standard way to let the Optionparser just ignore unknown command line switches. thanks in advance for any ideas From ldo at geek-central.gen.new_zealand Sun Aug 1 07:10:09 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 01 Aug 2010 23:10:09 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , Mark Lawrence wrote: > On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: > >> In message, Mark >> Lawrence wrote: >> >>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >>> >>>> In message, Mark >>>> Lawrence wrote: >>>> >>>>> Personally I find double clicking on an msi file rather easier. >>>> >>>> Easier than apt-get dist-upgrade? >>> >>> I'm sorry but I only do English, could you please translate. :) >> >> I run Debian Unstable, which has new goodies coming out on a weekly >> basis. The last time I checked for updates, there were over 500 packages >> I had installed for which updates were available. It only took a command >> like the above to upgrade them all. >> >> How many .msi files would you have to click on to achieve the Windows >> equivalent? > > ... I simply couldn't cope with over 500 installed packages. Precisely my point. Go back to playing with your .msi toys. Oh, and . From news1234 at free.fr Sun Aug 1 07:27:00 2010 From: news1234 at free.fr (News123) Date: Sun, 01 Aug 2010 13:27:00 +0200 Subject: let optionparse.Optionparser ignore unknown command line switches. In-Reply-To: <4c5555c5$0$19337$426a74cc@news.free.fr> References: <4c5555c5$0$19337$426a74cc@news.free.fr> Message-ID: <4c555a04$0$18011$426a74cc@news.free.fr> On 08/01/2010 01:08 PM, News123 wrote: > I wondered, whether there's a simple/standard way to let > the Optionparser just ignore unknown command line switches. > In order to illustrate, what I try to achieve: import optparse parser = optparse.OptionParser() parser.add_option("-t","--test",dest="test",action="store_true") argv=["tst.py","-t","--ignoreme_and_dont_fail"] try: (options,args)=parser.parse_args(argv) except: # due to --ignoreme_and_dont_fail # I will end up here and neither options nor # args will be populated print "parser error:" # However I would love to be able to see here # that options.test is true despite the # error, that occurred afterwards print "T",options.test From mohseni.aref at gmail.com Sun Aug 1 08:05:39 2010 From: mohseni.aref at gmail.com (Mohseniaref) Date: Sun, 1 Aug 2010 05:05:39 -0700 (PDT) Subject: how can I solve this erorr usr/lib/python2.6 : permisson denied Message-ID: <43e2d3fb-a0f9-468c-bd64-4516eed7dec5@u38g2000prh.googlegroups.com> Dear Friend I have this erorr after running pyhon script with header /usr/lib/python2.6 : permisson denied I change ownership with -hR in super user terminal From chare at labr.net Sun Aug 1 08:22:14 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 07:22:14 -0500 Subject: class doesn't open its window - newbie question Message-ID: I am a newbie to python, but not programming. I have a menubar item displaySubMenu.add_command(label="External", command=externalDisplay) externalDisplay is a new class, which I have already imported. The class is here: from Tkinter import * from datetime import datetime, date, time import urllib from PIL import Image #import Image # PIL required import ImageTk backColor = "Gray" highcolor = "Green" entryColor = "Cyan" okColor = "Green" warnColor = "Red" class externalDisplay(Frame): def __init__(self,callSign,nexrad): """Initialize yourself""" self.callSign = callSign self.nexrad = nexrad #"""Initialise the base class""" Frame.__init__(self) "Set the Window Title""" #self.title( "Test") self.findu = "http://www.findu.com/cgi-bin/radar-find.cgi?call=" + self.callSign + "&radar=" + self.nexrad """Display the main window" with a little bit of padding""" self.grid(padx=5,pady=5) self.CreateWidgets() def CreateWidgets(self): #"""Create all the widgets that we need""" self.f = Frame(self, bd=0, bg=backColor) self.title = "netcomm Online Radar" self.f.grid() # # Insert the date and time the radar image was updated # self.lblLastUpdate = Label(self.f, text="Last Updated: " + str(datetime.now()), bg=backColor) self.lblLastUpdate.grid( row=0, column=0, sticky=W) self.btnRefresh = Button(self.f, text="Refresh", command=handlesExternalDisplayByClick, bg=backColor,highlightbackground=okColor,highlightcolor=highcolor) self.btnRefresh.grid(row=0, column=1) self.btnRefresh = Button(self.f, text="Close", command=self.destroy, bg=backColor,highlightbackground=warnColor,highlightcolor=highcolor) self.btnRefresh.grid(row=0, column=2) # # Start the download from findu # # # This gets the image and saves it to the local disk as "image.png" # # NOTE - will ideally want to conver this to GIF and save it using # the date as part of the filename so the net can be re-created # for reporting and to create a flipbook of the radar images # urllib.urlretrieve(self.findu, "image.png") Image.open("image.png").save("image.gif") self.photo = PhotoImage(file="image.gif") # # create a canvas of the appropriate size for the image # self.w = Canvas(self.f, width=600, height=550) # # convert it into a photo item we can use in the display # self.netRadarImage = Label(self.w, image=self.photo) self.netRadarImage.image = self.photo self.w.grid(row=1, column=0, columnspan=3) self.netRadarImage.grid( row=1, column=0) def handlesExternalDisplayByClick(self): # # destroy the existing frame the radar is in # self.destroy() # # rebuild the radarWidgets # createRadarWidgets(frameRadar) def handlesRadarRefreshByClick(self): # # destroy the existing frame the radar is in # self.destroy() # # rebuild the radarWidgets # self.update() if __name__ == "__main__": guiFrame = externalDisplay("AE5PL-10","fws") guiFrame.mainloop() The problem is that the window defined in the class never appears, and I don't know why. I would like to get all of the code for the window into a single file which I import, but since I can't make this work right, I don't want to invest the time yet. Eve worse, is that when I run the code as a standalone module and click on the close button, I am left with a tk window instead of the app actually closing. Any suggestions are appreciated. From chare at labr.net Sun Aug 1 08:35:00 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 07:35:00 -0500 Subject: image resize doesn't work Message-ID: <2B79B253-B538-44DB-9796-77C2EFA6D3CC@labr.net> I have the following chunk of code. Although it seems to execute fine, no errors, the image is never resized. What am I missing? imagePNG = Image.open("image.png") photo = ImageTk.PhotoImage(imagePNG canvasWidth = 300 canvasHeight = 275 photo = ImagePNG.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) netRadarImage = Label(w, image=photo) From roy at panix.com Sun Aug 1 08:41:26 2010 From: roy at panix.com (Roy Smith) Date: Sun, 01 Aug 2010 08:41:26 -0400 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <8bkosiFpihU2@mid.individual.net> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message <8bkosiFpihU2 at mid.individual.net>, Gregory Ewing wrote: > > > Don't you just leave the machine on overnight and wait > > for Microsoft to download all the stuff they think > > you should be using? > > That???s fine, but it doesn???t handle the non-Microsoft stuff. You've apparently never worked in a big company. Your IT department downloads whatever *they* think you should be using. Eventually, your machine is so slow, you can't get any work done. From python at bdurham.com Sun Aug 1 09:12:46 2010 From: python at bdurham.com (python at bdurham.com) Date: Sun, 01 Aug 2010 09:12:46 -0400 Subject: Parse a string into argv-like list like OS does Message-ID: <1280668366.4854.1387755323@webmail.messagingengine.com> Before I reinvent the wheel, is there a module that provides a command-line like parser that I can use? By command-line like parser, I mean that I would like to pass a string to this function and get back a list in the same manner as the OS receives a command line string which it parses into discrete items (handling quoted strings, backslashes, etc) I have a bunch of command lines (as strings) and I would like to parse them into argv-like lists for analysis and documentation. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Sun Aug 1 09:28:01 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 01 Aug 2010 08:28:01 -0500 Subject: Parse a string into argv-like list like OS does In-Reply-To: <1280668366.4854.1387755323@webmail.messagingengine.com> References: <1280668366.4854.1387755323@webmail.messagingengine.com> Message-ID: <4C557661.6040907@tim.thechases.com> On 08/01/10 08:12, python at bdurham.com wrote: > Before I reinvent the wheel, is there a module that provides a > command-line like parser that I can use? By command-line like > parser, I mean that I would like to pass a string to this > function and get back a list in the same manner as the OS > receives a command line string which it parses into discrete > items (handling quoted strings, backslashes, etc) Sounds like the shlex module... http://docs.python.org/library/shlex.html -tkc From andrea.crotti.0 at gmail.com Sun Aug 1 09:28:23 2010 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Sun, 01 Aug 2010 15:28:23 +0200 Subject: how can I solve this erorr usr/lib/python2.6 : permisson denied References: <43e2d3fb-a0f9-468c-bd64-4516eed7dec5@u38g2000prh.googlegroups.com> Message-ID: Mohseniaref writes: > Dear Friend > I have this erorr after running pyhon script with header > /usr/lib/python2.6 : permisson denied > I change ownership with -hR in super user terminal Why /usr/lib... and not in bin? I guess this is the directory, of course if you put it in the header (shabang) it won't work. I use normally #!/usr/bin/env python From python at bdurham.com Sun Aug 1 09:42:47 2010 From: python at bdurham.com (python at bdurham.com) Date: Sun, 01 Aug 2010 09:42:47 -0400 Subject: Parse a string into argv-like list like OS does In-Reply-To: <4C557661.6040907@tim.thechases.com> References: <1280668366.4854.1387755323@webmail.messagingengine.com> <4C557661.6040907@tim.thechases.com> Message-ID: <1280670167.8260.1387757965@webmail.messagingengine.com> Tim, > Sounds like the shlex module... > http://docs.python.org/library/shlex.html Cheers for the link - that's *exactly* what I was searching for. For the archives: Here's an excellent tutorial on this module. http://www.oreillynet.com/onlamp/blog/2007/10/pymotw_shlex.html Malcolm From alain at dpt-info.u-strasbg.fr Sun Aug 1 09:59:38 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 01 Aug 2010 15:59:38 +0200 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <87sk2zhpcj.fsf@dpt-info.u-strasbg.fr> Message-ID: <87k4oah1rp.fsf@dpt-info.u-strasbg.fr> Lawrence D'Oliveiro writes: >>> V = tuple \ >>> ( >>> x >>> / >>> l >>> for x in V >>> for l in >>> (math.sqrt(reduce(lambda a, b : a + b, (y * y for y in V), >>> 0)),) >>> ) >> >> You got the order wrong (it has to be for l ... for x ...) > > No, I deliberately put it in that order to ensure that the value for l can > only ever be evaulated once. Try this (essentially equivalent to your code): def f(): print "hello" return 1 V = tuple( 1 for x in [1,2,3] for l in (f(),) ) How many "hello"s do you see? Comprehension are not loops spelled backwards. The values in: whatever for i ... for j ... are the values produced by the equivalent code: for i ... for j ... whatever -- Alain. From rantingrick at gmail.com Sun Aug 1 11:24:24 2010 From: rantingrick at gmail.com (rantingrick) Date: Sun, 1 Aug 2010 08:24:24 -0700 (PDT) Subject: image resize doesn't work References: Message-ID: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> On Aug 1, 7:35?am, Chris Hare wrote: > I have the following chunk of code. ?Although it seems to execute fine, no errors Not True! it contains syntax errors. Check the posted code and next time post all the code. From steveo at syslang.net Sun Aug 1 11:34:29 2010 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 01 Aug 2010 11:34:29 -0400 Subject: let optionparse.Optionparser ignore unknown command line switches. In-Reply-To: <4c555a04$0$18011$426a74cc@news.free.fr> References: <4c5555c5$0$19337$426a74cc@news.free.fr> <4c555a04$0$18011$426a74cc@news.free.fr> Message-ID: <4C559405.6030501@syslang.net> On 08/01/10 07:27, quoth News123: > On 08/01/2010 01:08 PM, News123 wrote: >> I wondered, whether there's a simple/standard way to let >> the Optionparser just ignore unknown command line switches. >> > > In order to illustrate, what I try to achieve: > > > import optparse > parser = optparse.OptionParser() > parser.add_option("-t","--test",dest="test",action="store_true") > argv=["tst.py","-t","--ignoreme_and_dont_fail"] > try: > (options,args)=parser.parse_args(argv) > except: > # due to --ignoreme_and_dont_fail > # I will end up here and neither options nor > # args will be populated > print "parser error:" > # However I would love to be able to see here > # that options.test is true despite the > # error, that occurred afterwards > print "T",options.test > You need to let us know *why* you want to do this. My psychotic imagination is contriving that you want to pass on the ignoremeanddontfail options to something else. If so, then you should be using -- instead of this. The other possible scheme to solve your unknown problem is to subclass OptionParser so it does what you want. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From chare at labr.net Sun Aug 1 11:36:07 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 10:36:07 -0500 Subject: image resize doesn't work In-Reply-To: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: On Aug 1, 2010, at 10:24 AM, rantingrick wrote: > On Aug 1, 7:35 am, Chris Hare wrote: >> I have the following chunk of code. Although it seems to execute fine, no errors > > Not True! it contains syntax errors. Check the posted code and next > time post all the code. > -- > http://mail.python.org/mailman/listinfo/python-list Hmmm... ok here is the code. I get no errors on my console when it execute urllib.urlretrieve(findu, "image.png") logging.debug("createRadarWidgets(): radar download complete") logging.debug("createRadarWidgets(): user has radarPanelSize of " + root.radarPanelSize.get()) # # open the image file # if os.path.exists("image.gif"): ctime = os.stat(dbPath)[ST_CTIME] print ctime filetime = datetime.fromtimestamp(ctime) filetime = filetime.strftime("%Y%m%d%H%M%S") print str(filetime) #filetime = datetime(ctime).isoformat() #print ctime imagePNG = Image.open("image.png") #photo = ImageTk.PhotoImage(imagePNG) Image.open("image.png").save("image.gif") image = Image.open("image.gif") photo = PhotoImage(file="image.gif") #photoimg = ImageTk.PhotoImage(photo) # # NOTE: - will want to track the size of the image displayed based upon # the actual screen resolution # Full/External = 600x550 - full file size # Large = 450x412 # Medium = 300x275 # Small = 150x137 # if root.radarPanelSize.get() == "Large": canvasWidth = 450 canvasHeight = 412 elif root.radarPanelSize.get() == "Medium": canvasWidth = 300 canvasHeight = 275 elif root.radarPanelSize.get() == "Small": canvasWidth = 150 canvasHeight = 137 logging.debug("createRadarWidgets(): creating image size " + str(canvasWidth) + "x" + str(canvasHeight)) # # create a canvas of the appropriate size for the image # w = Canvas(f, width=canvasWidth, height=canvasHeight) if root.radarPanelSize.get() == "Off": logging.debug("createRadarWidgets(): no net, no radar") netRadarImage = Label(w, text="No current radar") else: # # convert it into a photo item we can use in the display # # photo = photo.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) netRadarImage = Label(w, image=photo) netRadarImage.image = photo w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) From news1234 at free.fr Sun Aug 1 11:43:36 2010 From: news1234 at free.fr (News123) Date: Sun, 01 Aug 2010 17:43:36 +0200 Subject: let optionparse.Optionparser ignore unknown command line switches. In-Reply-To: References: <4c5555c5$0$19337$426a74cc@news.free.fr> <4c555a04$0$18011$426a74cc@news.free.fr> Message-ID: <4c559628$0$28678$426a74cc@news.free.fr> On 08/01/2010 05:34 PM, Steven W. Orr wrote: > On 08/01/10 07:27, quoth News123: >> On 08/01/2010 01:08 PM, News123 wrote: >>> I wondered, whether there's a simple/standard way to let >>> the Optionparser just ignore unknown command line switches. >>> >> >> In order to illustrate, what I try to achieve: >> >> >> import optparse >> parser = optparse.OptionParser() >> parser.add_option("-t","--test",dest="test",action="store_true") >> argv=["tst.py","-t","--ignoreme_and_dont_fail"] >> try: >> (options,args)=parser.parse_args(argv) >> except: >> # due to --ignoreme_and_dont_fail >> # I will end up here and neither options nor >> # args will be populated >> print "parser error:" >> # However I would love to be able to see here >> # that options.test is true despite the >> # error, that occurred afterwards >> print "T",options.test >> > > You need to let us know *why* you want to do this. My psychotic imagination is > contriving that you want to pass on the ignoremeanddontfail options to > something else. If so, then you should be using -- instead of this. The other > possible scheme to solve your unknown problem is to subclass OptionParser so > it does what you want. Hi Steven, '--' is good for many use cases, but not for the one I'm looking at. in my case one imported module should parse some of the options (but only the one it understands) already during import. the main program will have to parse the same options again. From nikos.the.gr33k at gmail.com Sun Aug 1 12:56:48 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sun, 1 Aug 2010 09:56:48 -0700 (PDT) Subject: Trying to set a cookie within a python script Message-ID: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> Hello fellow Python Coders! I don't see the error in my attempt to set a a cookie in this test script. Can you help please?! Thank you! [code] #!/usr/bin/python # -*- coding: utf-8 -*- import Cookie print ( "Content-type: text/html\n" ) cookie = Cookie.SimpleCookie() if cookie.has_key('visitor') == "nikos" #if visitor cookie exist print ( "??? ?? ????, ??? ?? ????, ??? ?? ??????. ?? ????? ? ???????? ??????????!!" ) cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire now else print ( "??? ?? ??? ??? ???? ??? ?? ?????? ??? ??????? ???? ??? ????????!!" ) cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year [/code] From joncle at googlemail.com Sun Aug 1 13:53:05 2010 From: joncle at googlemail.com (Jon Clements) Date: Sun, 1 Aug 2010 10:53:05 -0700 (PDT) Subject: let optionparse.Optionparser ignore unknown command line switches. References: <4c5555c5$0$19337$426a74cc@news.free.fr> <4c555a04$0$18011$426a74cc@news.free.fr> <4c559628$0$28678$426a74cc@news.free.fr> Message-ID: <8948edfa-2beb-4295-808e-11755f3d9128@p22g2000pre.googlegroups.com> On 1 Aug, 16:43, News123 wrote: > On 08/01/2010 05:34 PM, Steven W. Orr wrote: > > > > > On 08/01/10 07:27, quoth News123: > >> On 08/01/2010 01:08 PM, News123 wrote: > >>> I wondered, whether there's a simple/standard way to let > >>> the Optionparser just ignore unknown command line switches. > > >> In order to ?illustrate, what I try to achieve: > > >> import optparse > >> parser = optparse.OptionParser() > >> parser.add_option("-t","--test",dest="test",action="store_true") > >> argv=["tst.py","-t","--ignoreme_and_dont_fail"] > >> try: > >> ? ? (options,args)=parser.parse_args(argv) > >> except: > >> ? ? # due to --ignoreme_and_dont_fail > >> ? ? # I will end up here and neither options nor > >> ? ? # args will be populated > >> ? ? print "parser error:" > >> # However I would love to be able to see here > >> # that options.test is true despite the > >> # error, that occurred afterwards > >> print "T",options.test > > > You need to let us know *why* you want to do this. My psychotic imagination is > > contriving that you want to pass on the ignoremeanddontfail options to > > something else. If so, then you should be using -- instead of this. The other > > possible scheme to solve your unknown problem is to subclass OptionParser so > > it does what you want. > > Hi Steven, > > '--' is good for many use cases, but not for the one I'm looking at. > > in my case one imported module should parse some of the options (but > only the one it understands) already during import. > the main program will have to parse the same options again. Take it up a level. Dedicate a module (called app_configuration) or something to do the option parsing -- everything the application can support is listed there... It's a bad idea to ignore invalid options... When that's imported it runs the parsing for sys.argv whatever... and you guarantee a variable called app_settings (or whatever) is present in that module. Any module that needs the settings, just imports app_configuration and tries to take what it understands... Would that work for you? Jon. From __peter__ at web.de Sun Aug 1 14:08:28 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Aug 2010 20:08:28 +0200 Subject: image resize doesn't work References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: Chris Hare wrote: > On Aug 1, 2010, at 10:24 AM, rantingrick wrote: > >> On Aug 1, 7:35 am, Chris Hare wrote: >>> I have the following chunk of code. Although it seems to execute fine, >>> no errors >> >> Not True! it contains syntax errors. Check the posted code and next >> time post all the code. >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Hmmm... ok > here is the code. I get no errors on my console when it execute > > urllib.urlretrieve(findu, "image.png") I get a NameError on the very first line. >>> urllib.urlretrieve(findu, "image.png") Traceback (most recent call last): File "", line 1, in NameError: name 'urllib' is not defined When you want to demonstrate a problem try to make a self-contained example, i. e. one that can be run without the need for us guess the surrounding code. Remove everything that is irrelevant for the problem like the logging in code below and the png/gif conversion gymnastics. Anyway, here is a self-contained demo (you have to pass the filename of an image on the commandline): import Tkinter import ImageTk import Image import sys [filename] = sys.argv[1:] image = Image.open(filename) root = Tkinter.Tk() frame = Tkinter.Frame(root) frame.pack() label = Tkinter.Label(root) label.pack() def make_resize(percent): def resize(): width, height = image.size label.image = label["image"] = ImageTk.PhotoImage( image=image.resize((width*percent//100, height*percent//100))) return resize make_resize(100)() pairs = [ ("Small", 20), ("Medium", 50), ("Original", 100), ("Big", 200)] for i, (text, percent) in enumerate(pairs): button = Tkinter.Button(frame, text=text, command=make_resize(percent)) button.grid(row=0, column=i) root.mainloop() Peter From jjposner at optimum.net Sun Aug 1 14:37:34 2010 From: jjposner at optimum.net (John Posner) Date: Sun, 01 Aug 2010 14:37:34 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C545DF7.6040104@optimum.net> Message-ID: <4C55BEEE.8010503@optimum.net> On 7/31/2010 2:00 PM, Christian Heimes wrote: > > Your answer is confusing even me. ;) Yeah, I get that a lot. :-) > Let me try an easier to understand explanation. defaultdict *implements* > __missing__() to provide the default dict behavior. In my experience, the word *implements* is commonly used in two ways, nearly opposite to each other. Ex: My company just implemented a version-control system. Did your company (1) write the code for the version-control system, or did it (2) put the system in use, by downloading an installer from the Web and executing it? -John From chare at labr.net Sun Aug 1 15:08:44 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 14:08:44 -0500 Subject: image resize doesn't work In-Reply-To: References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: On Aug 1, 2010, at 1:08 PM, Peter Otten wrote: > Chris Hare wrote: > > >> On Aug 1, 2010, at 10:24 AM, rantingrick wrote: >> >>> On Aug 1, 7:35 am, Chris Hare wrote: >>>> I have the following chunk of code. Although it seems to execute fine, >>>> no errors >>> >>> Not True! it contains syntax errors. Check the posted code and next >>> time post all the code. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> Hmmm... ok >> here is the code. I get no errors on my console when it execute >> >> urllib.urlretrieve(findu, "image.png") > > I get a NameError on the very first line. > >>>> urllib.urlretrieve(findu, "image.png") > Traceback (most recent call last): > File "", line 1, in > NameError: name 'urllib' is not defined > > When you want to demonstrate a problem try to make a self-contained example, > i. e. one that can be run without the need for us guess the surrounding > code. Remove everything that is irrelevant for the problem like the logging > in code below and the png/gif conversion gymnastics. > > Anyway, here is a self-contained demo (you have to pass the filename of an > image on the commandline): > > import Tkinter > import ImageTk > import Image > import sys > > [filename] = sys.argv[1:] > > image = Image.open(filename) > > root = Tkinter.Tk() > frame = Tkinter.Frame(root) > frame.pack() > label = Tkinter.Label(root) > label.pack() > > def make_resize(percent): > def resize(): > width, height = image.size > label.image = label["image"] = ImageTk.PhotoImage( > image=image.resize((width*percent//100, height*percent//100))) > return resize > > make_resize(100)() > > pairs = [ > ("Small", 20), > ("Medium", 50), > ("Original", 100), > ("Big", 200)] > > for i, (text, percent) in enumerate(pairs): > button = Tkinter.Button(frame, text=text, command=make_resize(percent)) > button.grid(row=0, column=i) > > root.mainloop() > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list Thanks for the help. My one week of python is getting a workout. I have shortened it all down and made it a standalone example, using yours as a model. Your example, works, but it will take a lot of effort to retrofit it into the code I have. (which is maybe not a bad idea,). Anyway from Tkinter import * import ImageTk import Image import sys def sizeit(filename): image = Image.open(filename) w,h = image.size print w, h photo = ImageTk.PhotoImage(file=filename) canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) w,h = image.size print w, h netRadarImage = Label(frame, image=image) netRadarImage.image = photo w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) [filename] = sys.argv[1:] root = Tk() frame = Frame(root) frame.grid() sizeit(filename) root.mainloop() Just like yours it takes a filename. Unlike yours, mine gets an error that I can't figure out and is likely the root of the problem. When I run this code I get 600 550 <== ORIGINAL image size 450 412 <== resized image size Traceback (most recent call last): File "zztest.py", line 26, in sizeit(filename) File "zztest.py", line 16, in sizeit netRadarImage = Label(frame, image=image) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 2466, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1932, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "" doesn't exist So, my problem appeared to be the resize, but in fact is just getting it onto the label. What am I doing wrong? From cmpython at gmail.com Sun Aug 1 16:34:58 2010 From: cmpython at gmail.com (CM) Date: Sun, 1 Aug 2010 13:34:58 -0700 (PDT) Subject: exception handling with sqlite db errors Message-ID: <2a47b306-45d1-474a-9f8e-5b71eba629c9@p11g2000prf.googlegroups.com> I am using SQLite with Python 2.5 for an app and every now and then get an error when trying to write to the database. So far I haven't been careful about noting these down, but now I would like to address them. The two errors I've noticed are: 1) "database is locked" errors (probably due to write conflicts when using SQLite Database Browser to check and change the data while my app was trying to write to the db; this might be a problem for users if they too want to edit their data that way while running the app, though that scenario is pretty unlikely). 2) Today for the first time,"sqlite3.OperationalError: attempt to write a readonly database"--though I never set this database to be read-only. When I tried it a second time, it worked and didn't give this error. What I would like is a way to innoculate my app from these errors such that if they occur they don't cause any problems with the app. I'm not even sure if they do cause problems, since I can't figure out a way to reproduce the errors and see whether it causes the app to hang or not update the GUI properly, etc. Maybe it's not much of an issue, but I think it would be a shame if occasional hangs/crashes could be caused by these (rare?) database conflicts if there is a good approach for avoiding them. I guess I could put every last write to the db in a try/except block but I thought there should be a more general solution, since that will require many such exceptions and seems inelegant. Any suggestions for addressing this are appreciated. Che From __peter__ at web.de Sun Aug 1 17:32:56 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Aug 2010 23:32:56 +0200 Subject: image resize doesn't work References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: Chris Hare wrote: > Thanks for the help. My one week of python is getting a workout. > > I have shortened it all down and made it a standalone example, using yours > as a model. Your example, works, but it will take a lot of effort to > retrofit it into the code I have. (which is maybe not a bad idea,). You mean retrofit something that works into something tha doesn't? Seriously, you should never be afraid to throw away code, especially while you're still in the early phase of learning the language. > def sizeit(filename): > image = Image.open(filename) Now you have an Image > w,h = image.size > print w, h > photo = ImageTk.PhotoImage(file=filename) and now a photo, both created from the same file but otherwise independent > canvasWidth = 450 > canvasHeight = 412 > image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) Now you have a new resized Image > w,h = image.size > print w, h > netRadarImage = Label(frame, image=image) Label(image=...) expects a PhotoImage > netRadarImage.image = photo > w.grid(row=1, column=0, columnspan=3) Hmm... > netRadarImage.grid( row=1, column=0) Here's the fixed code: def sizeit(filename): image = Image.open(filename) canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS) photo = ImageTk.PhotoImage(image=image) netRadarImage = Label(frame, image=photo) netRadarImage.image = photo netRadarImage.grid(row=0, column=0) In plain English: - open the Image using the PIL - resize it - wrap it into a PhotoImage - wrap the PhotoImage into a Tkinter.Label either by passing it to the initialiser or by assigning to label["image"] - make sure the PhotoImage isn't garbage-collected e. g. by assigning to label.image Peter From chare at labr.net Sun Aug 1 18:11:57 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 17:11:57 -0500 Subject: image resize doesn't work In-Reply-To: References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: <37D9B818-DA6C-40D8-B8C5-185DFC8DAACD@labr.net> Thanks Peter - I know what I said sounded stupid :-) I have been working with Python for a week and as you know sometimes it is easier to learn by seeing what you did wrong as compared to what should have been done with the same example. I loved your code by the way - Thanks for help just another beginner .... On Aug 1, 2010, at 4:32 PM, Peter Otten wrote: > Chris Hare wrote: > >> Thanks for the help. My one week of python is getting a workout. >> >> I have shortened it all down and made it a standalone example, using yours >> as a model. Your example, works, but it will take a lot of effort to >> retrofit it into the code I have. (which is maybe not a bad idea,). > > You mean retrofit something that works into something tha doesn't? > Seriously, you should never be afraid to throw away code, especially while > you're still in the early phase of learning the language. > >> def sizeit(filename): >> image = Image.open(filename) > > Now you have an Image > >> w,h = image.size >> print w, h >> photo = ImageTk.PhotoImage(file=filename) > > and now a photo, both created from the same file but otherwise independent > >> canvasWidth = 450 >> canvasHeight = 412 >> image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) > > Now you have a new resized Image > >> w,h = image.size >> print w, h >> netRadarImage = Label(frame, image=image) > > Label(image=...) expects a PhotoImage > >> netRadarImage.image = photo >> w.grid(row=1, column=0, columnspan=3) > > Hmm... > >> netRadarImage.grid( row=1, column=0) > > Here's the fixed code: > > def sizeit(filename): > image = Image.open(filename) > canvasWidth = 450 > canvasHeight = 412 > image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS) > photo = ImageTk.PhotoImage(image=image) > netRadarImage = Label(frame, image=photo) > netRadarImage.image = photo > netRadarImage.grid(row=0, column=0) > > In plain English: > > - open the Image using the PIL > - resize it > - wrap it into a PhotoImage > - wrap the PhotoImage into a Tkinter.Label either by passing it to the > initialiser or by assigning to label["image"] > - make sure the PhotoImage isn't garbage-collected e. g. by assigning to > label.image > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list From chare at labr.net Sun Aug 1 18:15:26 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 17:15:26 -0500 Subject: beginner python GUI question Message-ID: <17F4F9B7-EB46-4FBB-9FCD-B74B861B105A@labr.net> I hope I can explain this correctly. I have a GUI, which is already being processed by a mainloop. I want to be able to open a second window so the user can interact with specific information in the second window. I pulled together this code example from Tkinter import * class Net: def __init__(self,tkWin): self.window = tkWin def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text="Again") button.bind("", self.Again) button.grid() def Again(self,event): win3 = Tk() x = Net(win3) x.show("window 3") root = Tk() root.title = "test" f = Frame(root,bg="Yellow") l = Label(f,text="window 1") f.grid() l.grid() win2 = Tk() x = Net(win2) x.show("window 2") if __name__ == "__main__": root.mainloop() Is this the right way to do things, or would you suggest something different? Thanks, Chris From chare at labr.net Sun Aug 1 18:33:58 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 17:33:58 -0500 Subject: image resize doesn't work In-Reply-To: References: <8446f625-b385-47ba-9e8d-602829955b5b@s24g2000pri.googlegroups.com> Message-ID: And I see now what I did wrong - thanks for putting up with the questions. On Aug 1, 2010, at 4:32 PM, Peter Otten wrote: > Chris Hare wrote: > >> Thanks for the help. My one week of python is getting a workout. >> >> I have shortened it all down and made it a standalone example, using yours >> as a model. Your example, works, but it will take a lot of effort to >> retrofit it into the code I have. (which is maybe not a bad idea,). > > You mean retrofit something that works into something tha doesn't? > Seriously, you should never be afraid to throw away code, especially while > you're still in the early phase of learning the language. > >> def sizeit(filename): >> image = Image.open(filename) > > Now you have an Image > >> w,h = image.size >> print w, h >> photo = ImageTk.PhotoImage(file=filename) > > and now a photo, both created from the same file but otherwise independent > >> canvasWidth = 450 >> canvasHeight = 412 >> image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) > > Now you have a new resized Image > >> w,h = image.size >> print w, h >> netRadarImage = Label(frame, image=image) > > Label(image=...) expects a PhotoImage > >> netRadarImage.image = photo >> w.grid(row=1, column=0, columnspan=3) > > Hmm... > >> netRadarImage.grid( row=1, column=0) > > Here's the fixed code: > > def sizeit(filename): > image = Image.open(filename) > canvasWidth = 450 > canvasHeight = 412 > image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS) > photo = ImageTk.PhotoImage(image=image) > netRadarImage = Label(frame, image=photo) > netRadarImage.image = photo > netRadarImage.grid(row=0, column=0) > > In plain English: > > - open the Image using the PIL > - resize it > - wrap it into a PhotoImage > - wrap the PhotoImage into a Tkinter.Label either by passing it to the > initialiser or by assigning to label["image"] > - make sure the PhotoImage isn't garbage-collected e. g. by assigning to > label.image > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list From candide at free.invalid Sun Aug 1 19:08:50 2010 From: candide at free.invalid (candide) Date: Mon, 02 Aug 2010 01:08:50 +0200 Subject: Why is python not written in C++ ? Message-ID: <4c55fe82$0$9111$426a34cc@news.free.fr> Python is an object oriented langage (OOL). The Python main implementation is written in pure and "old" C90. Is it for historical reasons? C is not an OOL and C++ strongly is. I wonder if it wouldn't be more suitable to implement an OOL with another one. Has it ever been planned to rewrite in C++ the historical implementation (of course in an object oriented design) ? From tjreedy at udel.edu Sun Aug 1 19:26:17 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Aug 2010 19:26:17 -0400 Subject: Docstrings and PEP 3174 In-Reply-To: <8bkp46FsbmU1@mid.individual.net> References: <4c551f45$0$11091$c3e8da3@news.astraweb.com> <8bkp46FsbmU1@mid.individual.net> Message-ID: On 8/1/2010 4:30 AM, Gregory Ewing wrote: > Steven D'Aprano wrote: > >> If you mean a runtime optimization with no change to the source file, >> then maybe, tell me more. > > Note that you don't necessarily need a separate file for this. > It could just be a separate part of the same file. Which is to say, all the docstrings in a modules *could* be placed at the end and not normally read in by the interpreter until needed. I have no idea what it does now, but I suspect not that. It might make module loading a bit faster. -- Terry Jan Reedy From tjreedy at udel.edu Sun Aug 1 19:31:42 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Aug 2010 19:31:42 -0400 Subject: how python works In-Reply-To: <930269.70649.qm@web50002.mail.re2.yahoo.com> References: <953403.23661.qm@web50003.mail.re2.yahoo.com> <930269.70649.qm@web50002.mail.re2.yahoo.com> Message-ID: On 7/30/2010 2:16 PM, Mahmood Naderan wrote: > So is it a compiler or interpreter? Python is a language. It does not 'work' in the sense of your subject line. CPython is a Python compiler/interpreter, as described. When loaded, it may be named python.exe, depending on system and installation. Jython and IronPython are also Python compiler/interpreters. There are also Python compilers of various sorts. -- Terry Jan Reedy From tjreedy at udel.edu Sun Aug 1 19:50:10 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Aug 2010 19:50:10 -0400 Subject: Normalizing A Vector In-Reply-To: References: Message-ID: On 7/30/2010 7:46 AM, Lawrence D'Oliveiro wrote: > Say a vector V is a tuple of 3 numbers, not all zero. You want to normalize > it (scale all components by the same factor) so its magnitude is 1. > > The usual way is something like this: > > L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) > V = (V[0] / L, V[1] / L, V[2] / L) > > What I don?t like is having that intermediate variable L leftover after the > computation. So, instead of fooling around with error-prone, hard-to-type constructions, just delete the damn thing! def L Compare those foolproof 5 chars to what at first did not work right and even what did. And, as other said, in most real applications, you will normalize in more than one place. In fact, you may well want a vlen function. def vlen(seq): return math.sqrt(sum(x*x for x in seq)) -- Terry Jan Reedy From me+list/python at ixokai.io Sun Aug 1 19:52:19 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sun, 01 Aug 2010 16:52:19 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4C5608B3.5030805@ixokai.io> On 8/1/10 4:08 PM, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? Portability if nothing else has been a strong reason to keep the Python implementation to standard C. Its not as bad as it used to be, but there's still quite a few differences between various C++ compilers. Even with the officially supported platforms shrinking of late, and talk of including some C++ in an isolated part of the CPython implementation (the UnladenSwallow JIT is C++, IIRC), rewriting the whole thing in C++ seems like a major waste of time. If you went and used the OO-features of C++, but then you run into a problem: Python's OO design is strikingly different from C++'s. There's no enforced encapsulation (on purpose), just as one example. That's not saying you -couldn't- match Python's OO design on top of C++, after all-- they've done it in Java, which has a hardcore interpretation of OOP. But what does that get you over the current status quo? C's leaner and meaner then C++. > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. Wny would this be more suitable? The Python idea of Object Orientedness doesn't line up with the C++ own *on purpose*, so why adopt one idea and design of OOP to implement a different one? > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? Have you actually looked at the "historical implementation"? It's actually quite object oriented. You don't have to have an object oriented language to use OO design. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From landimatte at gmail.com Sun Aug 1 19:56:14 2010 From: landimatte at gmail.com (Matteo Landi) Date: Mon, 2 Aug 2010 01:56:14 +0200 Subject: Normalizing A Vector In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 1:50 AM, Terry Reedy wrote: > On 7/30/2010 7:46 AM, Lawrence D'Oliveiro wrote: >> >> Say a vector V is a tuple of 3 numbers, not all zero. You want to >> normalize >> it (scale all components by the same factor) so its magnitude is 1. >> >> The usual way is something like this: >> >> ? ? L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) >> ? ? V = (V[0] / L, V[1] / L, V[2] / L) >> >> What I don?t like is having that intermediate variable L leftover after >> the >> computation. > > So, instead of fooling around with error-prone, hard-to-type constructions, > just delete the damn thing! > > def L del L :P > > Compare those foolproof 5 chars to what at first did not work right and even > what did. ?And, as other said, in most real applications, you will normalize > in more than one place. In fact, you may well want a vlen function. > > def vlen(seq): return math.sqrt(sum(x*x for x in seq)) > > -- > Terry Jan Reedy > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From tjreedy at udel.edu Sun Aug 1 20:01:59 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Aug 2010 20:01:59 -0400 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 8/1/2010 7:08 PM, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? Python was first released before C++. C is available on, and hence Python runs on, systems that do not have C++ available. > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. Python's object system is sufficiently different from that of C++ that I doubt the latter could used with much profit. > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? Proposed and rejected. Not every C programmer knows or wants to learn C++. -- Terry Jan Reedy From chare at labr.net Sun Aug 1 20:12:13 2010 From: chare at labr.net (Chris Hare) Date: Sun, 01 Aug 2010 19:12:13 -0500 Subject: how best to clear objects from a frame Message-ID: <47F2D553-FDD9-45AA-BFB8-BEEBE6900253@labr.net> Here is the situation: I have a window with a bunch of widgets in it. I want to clear the objects in a given frame and recreate them to update them. The example below destroys the top level frame, and so I can't recreate the widgets. I am likely doing this wrong. should I be doing this in a class? Thanks for the help. from Tkinter import * def createLeftWidgets(left): # # Add the Net Status Section # conditions = LabelFrame(left, text="Net Conditions",bg="Gray") conditions.grid(row=0,column=0); button = Button(conditions, text="Refresh", command=refreshNetConditions, highlightbackground="Green") button.grid(row=0,column=1, sticky=E) cText = Text(conditions,bg="Gray") cText.insert(END, root.netHistory.get()) cText.config(height=12,width=40) cText.grid(row=1,column=0,columnspan=2) status = LabelFrame(left, text="Net Details",bg="Gray") status.grid(row=1,column=0,sticky=N+E+W+S); lblNetNumber = Label(status, text="Net Number") lblNetNumber.grid( row=19, column=0, columnspan=2,sticky=W) return(conditions) def refreshNetConditions(): global frameLeft frameLeft.destroy() root.netHistory.set( "inserting text\n" + root.netHistory.get()) createLeftWidgets(frameLeft) root = Tk() root.netHistory = StringVar() root.netHistory.set("goes into the text widget") frame = Frame(root) frame.grid() frameLeft = createLeftWidgets(frame) root.mainloop() From roy at panix.com Sun Aug 1 20:36:20 2010 From: roy at panix.com (Roy Smith) Date: Sun, 01 Aug 2010 20:36:20 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article <4c55fe82$0$9111$426a34cc at news.free.fr>, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? > > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. One thing that comes to mind is that it's much easier to distribute C libraries than C++ libraries. If I compile a main program with one C compiler and you compile a dynamically loaded library with another C compiler on the same box, the odds are pretty good they'll interoperate without any problems. Not at all so with C++ compilers. The linkage is *way* more complicated. Not just how the two compilers do name mangling, but how they handle exceptions, RVO, and a zillion other details. Pretty much the only way to make it work is to compile everything with exactly the same compiler. That would make it pretty close to impossible for people to take a Python core distribution and add their own extension modules to it. From ldo at geek-central.gen.new_zealand Sun Aug 1 20:41:04 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 02 Aug 2010 12:41:04 +1200 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <87sk2zhpcj.fsf@dpt-info.u-strasbg.fr> <87k4oah1rp.fsf@dpt-info.u-strasbg.fr> Message-ID: In message <87k4oah1rp.fsf at dpt-info.u-strasbg.fr>, Alain Ketterlin wrote: > Lawrence D'Oliveiro writes: > >> No, I deliberately put it in that order to ensure that the value for l >> can only ever be evaulated once. > > Try this (essentially equivalent to your code): > > def f(): > print "hello" > return 1 > > V = tuple( 1 for x in [1,2,3] for l in (f(),) ) > > How many "hello"s do you see? > > Comprehension are not loops spelled backwards. The values in: > > whatever for i ... for j ... > > are the values produced by the equivalent code: > > for i ... > for j ... > whatever Damn. I thought that e for i ... for j ... was equivalent to (e for i ...) for j ... Looks like I was wrong. From ldo at geek-central.gen.new_zealand Sun Aug 1 20:43:33 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 02 Aug 2010 12:43:33 +1200 Subject: Problem with Elementtree and XMLSchem instance type References: <96e47fd8-c939-48a2-9a2b-92afa720c8ac@k1g2000prl.googlegroups.com> Message-ID: In message <96e47fd8-c939-48a2-9a2b-92afa720c8ac at k1g2000prl.googlegroups.com>, Carl Banks wrote: > My general feeling is that ElementTree is a lot handier for reading > and writing your own XML formats, than for handling XML files produced > by other tools. Why is that? I?ve successfully used it to parse SVG files produced by Inkscape . From steve-REMOVE-THIS at cybersource.com.au Sun Aug 1 20:52:15 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 00:52:15 GMT Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> Message-ID: <4c5616bf$0$11113$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 09:56:48 -0700, ????? wrote: > Hello fellow Python Coders! > > I don't see the error in my attempt to set a a cookie in this test > script. Neither do I. What makes you think there is an error? What sort of error? Do you get a core dump, an exception, or something else? Please report what you get, and what you expect, and how they are different. -- Steven From steve-REMOVE-THIS at cybersource.com.au Sun Aug 1 20:56:29 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 00:56:29 GMT Subject: how can I solve this erorr usr/lib/python2.6 : permisson denied References: <43e2d3fb-a0f9-468c-bd64-4516eed7dec5@u38g2000prh.googlegroups.com> Message-ID: <4c5617bc$0$11113$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 05:05:39 -0700, Mohseniaref wrote: > Dear Friend > I have this erorr after running pyhon script with header > /usr/lib/python2.6 : permisson denied I change ownership with -hR in > super user terminal Please COPY AND PASTE (do NOT retype them): (1) the header from the script (2) the command you use to run the script (3) the error message you get (4) the command you use to change ownership (5) the result of that command (6) what happens if you try running the script again -- Steven From magawake at gmail.com Sun Aug 1 20:59:24 2010 From: magawake at gmail.com (Mag Gam) Date: Sun, 1 Aug 2010 20:59:24 -0400 Subject: timeit function Message-ID: Currently, I have a bash shell script which does timing for me. For example, if I have a Unix Command I typically run time against it for 10 times and then get an average. It works fine but I have to write a post processing script to get the time and then do a graph on matplotlib. I was wondering if the timeit function would be helpful in my case. I was thinking to open a subprocess to run the Unix command 10 times (instead of 1 million times) and then do the average and then do the graph. Any thoughts about this? Is timeit the right tool for what I am trying to do? TIA... From john at castleamber.com Sun Aug 1 21:05:29 2010 From: john at castleamber.com (John Bokma) Date: Sun, 01 Aug 2010 20:05:29 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <87pqy14yee.fsf@castleamber.com> Terry Reedy writes: > On 8/1/2010 7:08 PM, candide wrote: >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? > > Python was first released before C++. C++ was named C++ in 1983 (development on it started in 1979) and the first commercial implementation was released in 1985 [1]. Implementation of Python started in December 1989 [2]. So: no. (I was quite sure on this, since I started to program in C++ in the late 80's/early 90's IIRC). [1] http://en.wikipedia.org/wiki/C_plus_plus#History [2] http://en.wikipedia.org/wiki/Python_%28programming_language%29#History http://python-history.blogspot.com/2009/01/brief-timeline-of-python.html -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From john at castleamber.com Sun Aug 1 21:09:48 2010 From: john at castleamber.com (John Bokma) Date: Sun, 01 Aug 2010 20:09:48 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <87lj8p4y77.fsf@castleamber.com> Roy Smith writes: > In article <4c55fe82$0$9111$426a34cc at news.free.fr>, > candide wrote: > >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. > > One thing that comes to mind is that it's much easier to distribute C > libraries than C++ libraries. In the beginning of C++ there were programs that just converted C++ to C (frontends). At least that is how the C++ compiler Acorn sold worked. So I don't think your argument was much true back then. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From rechardchen at gmail.com Sun Aug 1 21:17:14 2010 From: rechardchen at gmail.com (rechardchen) Date: Mon, 02 Aug 2010 09:17:14 +0800 Subject: How to catch windows shutdown/reboot message Message-ID: I'm writing a python script which runs as a windowsxp service. The problem is how to catch the windows shutdown/reboot message and do some cleaning job when system is going down? The atexit module and signal module on windows dont seems to work. I guess the python win32api may be of help, but I am not familiar with it... Thank you From lists at cheimes.de Sun Aug 1 21:20:15 2010 From: lists at cheimes.de (Christian Heimes) Date: Mon, 02 Aug 2010 03:20:15 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: Am 02.08.2010 01:08, schrieb candide: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? Python is written in C89 to support as many platforms as possible. We deliberately don't use any new features and almost no compiler specific extensions to make the interpreter portable. AFAIK the only compiler specific feature used in Python are computed gotos and they are optional. > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. > > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? I like to say that the Python interpreter is written in object oriented C code. Every Python object evolved around PyObject and PyType structs that are extended (subclassed) to add additional members. Python won't gain anything useful from a pure C++ implementation. C++ would only add a major layer of complexity and scary features. In your opinion what would Python gain from a C++ implementation? Christian From pavlovevidence at gmail.com Sun Aug 1 21:30:52 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 1 Aug 2010 18:30:52 -0700 (PDT) Subject: Problem with Elementtree and XMLSchem instance type References: <96e47fd8-c939-48a2-9a2b-92afa720c8ac@k1g2000prl.googlegroups.com> Message-ID: <6627204c-d0b1-456d-94bd-76d946ad21d9@g6g2000pro.googlegroups.com> On Aug 1, 5:43?pm, Lawrence D'Oliveiro wrote: > In message > <96e47fd8-c939-48a2-9a2b-92afa720c... at k1g2000prl.googlegroups.com>, Carl > > Banks wrote: > > My general feeling is that ElementTree is a lot handier for reading > > and writing your own XML formats, than for handling XML files produced > > by other tools. > > Why is that? I?ve successfully used it to parse SVG files produced by > Inkscape . I said it was not handy, not that is was not useful. And you don't *have* to try to start an argument over every tiny thing you disagree with. Carl Banks From rechardchen at gmail.com Sun Aug 1 21:33:00 2010 From: rechardchen at gmail.com (rechardchen) Date: Mon, 02 Aug 2010 09:33:00 +0800 Subject: beginner python GUI question In-Reply-To: References: Message-ID: ? 2010-8-2 6:15, Chris Hare ??: > I hope I can explain this correctly. > > I have a GUI, which is already being processed by a mainloop. I want to be able to open a second window so the user can interact with specific information in the second window. I pulled together this code example > > from Tkinter import * > > class Net: > def __init__(self,tkWin): > self.window = tkWin > def show(self,t): > self.l = Label(self.window,text=t) > self.l.grid() > button = Button(self.window, text="Again") > button.bind("", self.Again) > button.grid() > def Again(self,event): > win3 = Tk() > x = Net(win3) > x.show("window 3") > > root = Tk() > root.title = "test" > f = Frame(root,bg="Yellow") > l = Label(f,text="window 1") > f.grid() > l.grid() > > win2 = Tk() > x = Net(win2) > x.show("window 2") > if __name__ == "__main__": > root.mainloop() > > Is this the right way to do things, or would you suggest something different? > > Thanks, > Chris > Using Tkinter.Toplevel may be better. :) From rtomek at ceti.com.pl Sun Aug 1 21:49:50 2010 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Mon, 2 Aug 2010 03:49:50 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <87lj8p4y77.fsf@castleamber.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> Message-ID: On Sun, 1 Aug 2010, John Bokma wrote: > In the beginning of C++ there were programs that just converted C++ to C > (frontends). At least that is how the C++ compiler Acorn sold worked. > So I don't think your argument was much true back then. Those that I (tried to) used on Amiga were based around the same concept. It seems, that Comeau C++ compiler (which I never tried) still requires C compiler as a backend (and is highly regarded by some). Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From pavlovevidence at gmail.com Sun Aug 1 22:13:04 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 1 Aug 2010 19:13:04 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> Message-ID: <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> On Aug 1, 6:09?pm, John Bokma wrote: > Roy Smith writes: > > In article <4c55fe82$0$9111$426a3... at news.free.fr>, > > ?candide wrote: > > >> Python is an object oriented langage (OOL). The Python main > >> implementation is written in pure and "old" C90. Is it for historical > >> reasons? > > >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > >> suitable to implement an OOL with another one. > > > One thing that comes to mind is that it's much easier to distribute C > > libraries than C++ libraries. > > In the beginning of C++ there were programs that just converted C++ to C > (frontends). At least that is how the C++ compiler Acorn sold worked. > So I don't think your argument was much true back then. No, it was that way back then too. They might all generate C code but different C code by different backends wouldn't be able to call each other natively. For instnace the function int foo(int); might be name-mangled this way in one cfront: foo$d and this way in another: ____int_foo__int_i The virtual table of this class: class Bar { virtual int foo(int); virtual int bar(int); }; might be generated like this in one cfront: struct Bar$$Vtable$ { int (*Bar$$bar$d)(int); int (*Bar$$foo$d)(int); }; and like this in another: struct ____class_Foo___vtable_ { int (*foo)(int); int (*bar)(int); }; So, just because they both generated C code, it doesn't mean they can call one another. Carl Banks From eliben at gmail.com Sun Aug 1 22:15:55 2010 From: eliben at gmail.com (Eli Bendersky) Date: Mon, 2 Aug 2010 05:15:55 +0300 Subject: co_firstlineno on decorated functions Message-ID: Hello, I've been tinkering with __code__.co_firstlineno for testing the trace.py module (Python Issue 9315), and ran into an interesting problem. Consider this code: def dummydecorator(f): return f def foo(a): return a @dummydecorator def bar(a): return a if __name__ == "__main__": print foo.__code__.co_firstlineno print bar.__code__.co_firstlineno ---- The first print out correctly specifies the line "def foo" is in. However, the second one points to the line with "@dummydecorator" instead of "def bar". [Python 2.6] The side-effects of this behavior can be easily seen in the output of modules like trace and profile. Would you say it's normal, or could this be considered a bug? Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Sun Aug 1 22:16:29 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 1 Aug 2010 19:16:29 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> Message-ID: >On 2 ???, 03:52, Steven D'Aprano wrote: > Neither do I. What makes you think there is an error? What sort of error? > Do you get a core dump, an exception, or something else? > > Please report what you get, and what you expect, and how they are > different. Hello Steven, Here is the script when it tries to run from my remote web server: http://www.webville.gr/cgi-bin/koukos.py Its seems the error is in this line of code, somwthing with time. 19 cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year From nikos.the.gr33k at gmail.com Sun Aug 1 22:20:04 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sun, 1 Aug 2010 19:20:04 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> Message-ID: <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> Also my greek print appear in funny encoding although i do use # -*- coding: utf-8 -*- From pavlovevidence at gmail.com Sun Aug 1 22:20:07 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 1 Aug 2010 19:20:07 -0700 (PDT) Subject: Docstrings and PEP 3174 References: <4c551f45$0$11091$c3e8da3@news.astraweb.com> <8bkp46FsbmU1@mid.individual.net> Message-ID: <5984b623-f051-41b1-b5e0-b5c8baf1918f@b4g2000pra.googlegroups.com> On Aug 1, 4:26?pm, Terry Reedy wrote: > On 8/1/2010 4:30 AM, Gregory Ewing wrote: > > > Steven D'Aprano wrote: > > >> If you mean a runtime optimization with no change to the source file, > >> then maybe, tell me more. > > > Note that you don't necessarily need a separate file for this. > > It could just be a separate part of the same file. > > Which is to say, all the docstrings in a modules *could* be placed at > the end and not normally read in by the interpreter until needed. I'm going to guess that they don't want that in *.pyc files. In PEP 3147 they proposed a fat-format file (so a glob for each version) and it was not popular. > I have > no idea what it does now, There's a short header, then the rest of the file is a single marshaled glob. > but I suspect not that. It might make module > loading a bit faster. True but still probably a small optimization. Carl Banks From marduk at letterboxes.org Sun Aug 1 22:34:07 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 01 Aug 2010 22:34:07 -0400 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <1280716447.927705.20.camel@paska> On Mon, 2010-08-02 at 01:08 +0200, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? > > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. > > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? Disclaimer: I am neither a C nor C++ programmer. In fact I can barely even program in Python ;-) I would propose that in fact most programming languages are implemented in C. Sun's (Oracle's) Java compiler and runtime are written in ANSI C. The core of the Gnu Compiler Collection (which includes C++ and Objective-C compilers) is written in C. The official Ruby is implemented in C. The Squeak Smalltalk implementation uses C instead of C++. I can't even think of a programming language that is implemented in C++ (maybe C++ is). C seems to be a good, portable language for writing interpreters and compilers. But I wonder if someone has/has tried to write a programming language in C++ and what were their experiences. From python at mrabarnett.plus.com Sun Aug 1 22:49:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 02 Aug 2010 03:49:15 +0100 Subject: Trying to set a cookie within a python script In-Reply-To: <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> Message-ID: <4C56322B.2000903@mrabarnett.plus.com> ????? wrote: > Also my greek print appear in funny encoding although i do use # -*- > coding: utf-8 -*- That line just tells Python what encoding the source file itself uses. It doesn't affect what the program does or how it runs. From benjamin at python.org Sun Aug 1 23:01:25 2010 From: benjamin at python.org (Benjamin Peterson) Date: Sun, 1 Aug 2010 22:01:25 -0500 Subject: [Python-Dev] [RELEASED] Python 3.2 alpha 1 In-Reply-To: <4C55409B.5000409@python.org> References: <4C55409B.5000409@python.org> Message-ID: Hey, Georg! Congrats on your first release! 2010/8/1 Georg Brandl : > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team, I'm happy to announce the > first alpha preview release of Python 3.2. > > Python 3.2 is a continuation of the efforts to improve and stabilize the > Python 3.x line. ?Since the final release of Python 2.7, the 2.x line > will only receive bugfixes, and new features are developed for 3.x only. > > Since PEP 3003, the Moratorium on Language Changes, is in effect, there > are no changes in Python's syntax and built-in types in Python 3.2. > Development efforts concentrated on the standard library and support for > porting code to Python 3. ?Highlights are: > > * numerous improvements to the unittest module > * PEP 3147, support for .pyc repository directories > * an overhauled GIL implementation that reduces contention > * many consistency and behavior fixes for numeric operations > * countless fixes regarding string/unicode issues; among them full > ?support for a bytes environment (filenames, environment variables) > * a sysconfig module to access configuration information > * a pure-Python implementation of the datetime module > * additions to the shutil module, among them archive file support > * improvements to pdb, the Python debugger > > For an extensive list of changes in 3.2, see Misc/NEWS in the Python > distribution. > > To download Python 3.2 visit: > > ? ? http://www.python.org/download/releases/3.2/ > > 3.2 documentation can be found at: > > ? ? http://docs.python.org/3.2/ > > Please consider trying Python 3.2 with your code and reporting any bugs > you may notice to: > > ? ? http://bugs.python.org/ > > > Enjoy! > > - -- > Georg Brandl, Release Manager > georg at python.org > (on behalf of the entire python-dev team and 3.2's contributors) > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v2.0.16 (GNU/Linux) > > iEYEARECAAYFAkxVQJsACgkQN9GcIYhpnLBxIgCcCiVu/QUkFf0bYM2Vmi8St3mZ > 2N4An04q36lr47OA+bslqG/4Zj7ZwVOX > =iL8N > -----END PGP SIGNATURE----- > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: http://mail.python.org/mailman/options/python-dev/benjamin%40python.org > -- Regards, Benjamin From rtomek at ceti.pl Sun Aug 1 23:04:59 2010 From: rtomek at ceti.pl (Tomasz Rola) Date: Mon, 2 Aug 2010 05:04:59 +0200 (CEST) Subject: Why is python not written in C++ ? In-Reply-To: <1280716447.927705.20.camel@paska> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <1280716447.927705.20.camel@paska> Message-ID: On Sun, 1 Aug 2010, Albert Hopkins wrote: > C seems to be a good, portable language for writing interpreters and > compilers. And one should not forget about performance. C++ was for a long time behind C, and even now some parts (like iostreams) should be avoided in fast code. BTW, C++ can be IMHO a bit tricky in situations when one would like to call back from JIT-generated code into parts written in C++... I mean things like virtual functions, overloading, code generated from templates, accessing private members etc. All those issues are non essential from the point of interpreting or JIT, yet they stand in a way. While this could be solved (with some headache, I suspect), C is far simpler and function calls or manipulating structs are actually trivial... Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From rantingrick at gmail.com Sun Aug 1 23:13:55 2010 From: rantingrick at gmail.com (rantingrick) Date: Sun, 1 Aug 2010 20:13:55 -0700 (PDT) Subject: how best to clear objects from a frame References: Message-ID: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> On Aug 1, 7:12?pm, Chris Hare wrote: > Here is the situation: > > I have a window with a bunch of widgets in it. ?I want to clear the objects in a given frame and recreate them to update them. ? You need to check out the "w.update" and "w.update_idletasks" methods available on all Tkinter widgets. Just FYI: to remove a widget from view without destroying it use "w.pack_forget" or "w.grid_forget". However if you are simply trying to refresh a widget use one of the update methods. From steve-REMOVE-THIS at cybersource.com.au Sun Aug 1 23:21:21 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 03:21:21 GMT Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> Message-ID: <4c5639b1$0$11113$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 19:16:29 -0700, ????? wrote: >>On 2 ???, 03:52, Steven D'Aprano >>wrote: > >> Neither do I. What makes you think there is an error? What sort of >> error? Do you get a core dump, an exception, or something else? >> >> Please report what you get, and what you expect, and how they are >> different. > > Hello Steven, > > Here is the script when it tries to run from my remote web server: > http://www.webville.gr/cgi-bin/koukos.py > > Its seems the error is in this line of code, somwthing with time. > > 19 cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) > #this cookie will expire in an year What error? Please copy and paste (do not retype) the entire error you get. -- Steven From steve-REMOVE-THIS at cybersource.com.au Sun Aug 1 23:23:08 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 03:23:08 GMT Subject: Docstrings and PEP 3174 References: <4c551f45$0$11091$c3e8da3@news.astraweb.com> <8bkp46FsbmU1@mid.individual.net> Message-ID: <4c563a1c$0$11113$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 20:30:22 +1200, Gregory Ewing wrote: > Steven D'Aprano wrote: > >> If you mean a runtime optimization with no change to the source file, >> then maybe, tell me more. > > Note that you don't necessarily need a separate file for this. It could > just be a separate part of the same file. I would disagree with any attempt to move the docstring away from immediately next to the function in the source file. You can currently do that if you insist, after all __doc__ is just an ordinary attribute: >>> def f(): ... pass ... >>> f.__doc__ = some_other_text I don't think we should do anything that *encourages* people to separate the code and docstrings in the source file. On the assumption that functions will continue to be written: def f(): """Doc string""" pass I like the proposal to make f.__doc__ a descriptor that lazily loads the doc string from disk when needed, rather than keeping the string in memory at all times. Whether this leads to enough memory savings to justify it is an open question. -- Steven From torriem at gmail.com Mon Aug 2 00:23:33 2010 From: torriem at gmail.com (Michael Torrie) Date: Sun, 01 Aug 2010 22:23:33 -0600 Subject: Why is python not written in C++ ? In-Reply-To: <87lj8p4y77.fsf@castleamber.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> Message-ID: <4C564845.9040909@gmail.com> On 08/01/2010 07:09 PM, John Bokma wrote: >> One thing that comes to mind is that it's much easier to distribute C >> libraries than C++ libraries. > > In the beginning of C++ there were programs that just converted C++ to C > (frontends). At least that is how the C++ compiler Acorn sold worked. > So I don't think your argument was much true back then. No, he is still right. Each C++ implementation did name mangling differently leading to "C" libraries that had incompatible names and signatures. Also each frontend could have generated incompatible vtables and other C++ structures. So C code generated by one C++ frontend could not easily call C code generated by another C++ frontend. So the same arguments that are made about C++ now were just as valid back then when C++ was merely a fancy preprocessor. From doug.garstang at gmail.com Mon Aug 2 01:09:23 2010 From: doug.garstang at gmail.com (Douglas Garstang) Date: Sun, 1 Aug 2010 22:09:23 -0700 Subject: Merging two dictionaries Message-ID: Anyone, I have the two dictionaries below. How can I merge them, such that: 1. The cluster dictionary contains the additional elements from the default dictionary. 2. Nothing is removed from the cluster dictionary. The idea here is that the two dictionaries are read from different files where, if the value isn't found in the cluster dictionary, it's pulled from the default one, and I can have a new dictionary reflecting this. The update() method on dictionaries doesn't seem to work. The resulting dictionary always seems to be the one passed as a parameter. default = { 'cluster': { 'platform': { 'elements': { 'data_sources': { 'elements': { 'db_min_pool_size': 10 }, }, }, }, } } cluster = { 'cluster': { 'name': 'Customer 1', 'description': 'Production', 'environment': 'production', 'platform': { 'elements': { 'data_source': { 'elements': { 'username': 'username', 'password': 'password' }, }, }, }, } } The resulting dictionary would therefore look like this: new_dict = { 'cluster': { 'name': 'Customer 1', 'description': 'Production', 'environment': 'production', 'platform': { 'elements': { 'data_source': { 'elements': { 'username': 'username', 'password': 'password', 'db_min_pool_size': 10 # This was added from the default. }, }, }, }, } } Thanks, Doug. -- Regards, Douglas Garstang http://www.linkedin.com/in/garstang Email: doug.garstang at gmail.com Cell: +1-805-340-5627 From michele.simionato at gmail.com Mon Aug 2 02:15:11 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Sun, 1 Aug 2010 23:15:11 -0700 (PDT) Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> Message-ID: On Jul 31, 5:08?am, Steven D'Aprano wrote: > I have read Michelle Simionato's articles on super in Python. One "l" please! I am a man! ;-) > > But Michelle is wrong to conclude that the problem lies with the concept > of *superclass*. The problem lies with the idea that there is ONE > superclass. By dismissing the entire concept, he is throwing out the baby > with the bathwater. I am actually more radical than that. From http://www.artima.com/weblogs/viewpost.jsp?thread=237121: """ In this series I have argued that super is tricky; I think nobody can dispute that. However the existence of dark corners is not a compelling argument against a language construct: after all, they are rare and there is an easy solution to their obscurity, i.e. documenting them. This is what I have being doing all along. On the other hand, one may wonder if all super warts aren't hints of some serious problem underlying. It may well be that the problem is not with super, nor with cooperative methods: the problem may be with multiple inheritance itself. """ Then I spend thousands of words in the "Mixin considered harmful" series and in other articles arguing against multiple inheritance and cooperative methods. They are just bad design IMO. Of course we are in the range of opinions, this is a tricky subject: many smart people agree with me and many others equally smart disagree. Still I believe that super is a red herring and that you should really start thinking: what advantages did multiple inheritance *really* bring into my code? Could have I done without? And what would have happen? These are the relevant question, not the exact meaning of super in hairy hierarchies. M. Simionato From no.email at nospam.invalid Mon Aug 2 02:21:22 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 01 Aug 2010 23:21:22 -0700 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> Message-ID: <7xmxt5357h.fsf@ruckus.brouhaha.com> Michele Simionato writes: > I am actually more radical than that. From > http://www.artima.com/weblogs/viewpost.jsp?thread=237121: > In this series I have argued that super is tricky; I think nobody can... When I look at that URL, I see a Java stack dump: java.lang.RuntimeException: com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid at com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112) ... Seems appropriate. From nikos.the.gr33k at gmail.com Mon Aug 2 02:39:34 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 1 Aug 2010 23:39:34 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> Message-ID: <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> If you just click in my web page to see the script run in action due to the cgitb module i use it will provide you both the source code that the error appears and the error as well. All you have to do is click here: http://www.webville.gr/cgi-bin/koukos.py As for the encoding why when i print greek characters they dont appear correctly in chrome in runtime? From V.vanBeveren at rijnhuizen.nl Mon Aug 2 02:41:36 2010 From: V.vanBeveren at rijnhuizen.nl (Vincent van Beveren) Date: Mon, 2 Aug 2010 08:41:36 +0200 Subject: The untimely dimise of a weak-reference In-Reply-To: <8bhi2fFifjU1@mid.individual.net> References: <8bhi2fFifjU1@mid.individual.net> Message-ID: <2926F4BC94217A43A2D21792DE88189339C58B6374@ex1.rijnh.nl> Hi Gregory, > You can create your own wrapper that keeps a weak reference to > the underlying object. Here's an example. > [...] Thanks for the code! Regards, Vincent From V.vanBeveren at rijnhuizen.nl Mon Aug 2 02:46:13 2010 From: V.vanBeveren at rijnhuizen.nl (Vincent van Beveren) Date: Mon, 2 Aug 2010 08:46:13 +0200 Subject: The untimely dimise of a weak-reference In-Reply-To: References: <2926F4BC94217A43A2D21792DE88189339C58B6373@ex1.rijnh.nl> Message-ID: <2926F4BC94217A43A2D21792DE88189339C58B6375@ex1.rijnh.nl> Hi Christiaan, > Instances of a class have no means of storing the bound method object. > The or unbound bound method is a simple and small wrapper that keeps a > reference to the class, "self" and the function object. Python keeps a > pool of empty method objects in a free list. The creation of a new bound > method just takes a few pointer assignments and three INCREFs. Okay, that also explains the consistent memory assignment. Maybe I'll create a bound-method caching object, see how slow/fast it is in comparison, and see what ever other issues I run into. Regards, Vincent -----Original Message----- From: python-list-bounces+v.vanbeveren=rijnhuizen.nl at python.org [mailto:python-list-bounces+v.vanbeveren=rijnhuizen.nl at python.org] On Behalf Of Christian Heimes Sent: vrijdag 30 juli 2010 16:44 To: python-list at python.org Subject: Re: The untimely dimise of a weak-reference Am 30.07.2010 16:06, schrieb Vincent van Beveren: > I did not know the object did not keep track of its bound methods. What advantage is there in creating a new bound method object each time its referenced? It seems kind of expensive. Christian -- http://mail.python.org/mailman/listinfo/python-list From sanjeeb25 at gmail.com Mon Aug 2 02:52:18 2010 From: sanjeeb25 at gmail.com (Sanjeeb) Date: Sun, 1 Aug 2010 23:52:18 -0700 (PDT) Subject: sending a file chunk by chunk instead as a whole to a web server Message-ID: Hi, I have a web client which send a file to a server as multipart form data, the sending of data is from http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/. I dont want to open the whole file to memory(at cliend end) and then send, i just want to send part by part, say chunk of 1024 bytes to the server and then assemble at the server end. Could some one suggest what would be the best way to do this? Regards -Sanjeeb From gherron at islandtraining.com Mon Aug 2 02:57:34 2010 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 01 Aug 2010 23:57:34 -0700 Subject: Merging two dictionaries In-Reply-To: References: <4C565E79.6090307@islandtraining.com> Message-ID: <4C566C5E.9000008@islandtraining.com> On 08/01/2010 11:11 PM, Douglas Garstang wrote: > On Sun, Aug 1, 2010 at 10:58 PM, Gary Herron wrote: > >> On 08/01/2010 10:09 PM, Douglas Garstang wrote: >> >>> Anyone, >>> >>> I have the two dictionaries below. How can I merge them, such that: >>> >>> 1. The cluster dictionary contains the additional elements from the >>> default dictionary. >>> 2. Nothing is removed from the cluster dictionary. >>> >>> The idea here is that the two dictionaries are read from different >>> files where, if the value isn't found in the cluster dictionary, it's >>> pulled from the default one, and I can have a new dictionary >>> reflecting this. The update() method on dictionaries doesn't seem to >>> work. The resulting dictionary always seems to be the one passed as a >>> parameter. >>> >>> default = { >>> 'cluster': { >>> 'platform': { >>> 'elements': { >>> 'data_sources': { >>> 'elements': { >>> 'db_min_pool_size': 10 >>> }, >>> }, >>> }, >>> }, >>> } >>> } >>> >>> cluster = { >>> 'cluster': { >>> 'name': 'Customer 1', >>> 'description': 'Production', >>> 'environment': 'production', >>> 'platform': { >>> 'elements': { >>> 'data_source': { >>> 'elements': { >>> 'username': 'username', >>> 'password': 'password' >>> }, >>> }, >>> }, >>> }, >>> } >>> } >>> >>> The resulting dictionary would therefore look like this: >>> >>> new_dict = { >>> 'cluster': { >>> 'name': 'Customer 1', >>> 'description': 'Production', >>> 'environment': 'production', >>> 'platform': { >>> 'elements': { >>> 'data_source': { >>> 'elements': { >>> 'username': 'username', >>> 'password': 'password', >>> 'db_min_pool_size': 10 # This was added from >>> the default. >>> }, >>> }, >>> }, >>> }, >>> } >>> } >>> >>> >>> Thanks, >>> Doug. >>> >>> >>> >> Your dictionaries are annoyingly complicated -- making it hard to see what's >> going on. Here I've replaced all the distractions of your dictionary >> nesting with a simple (string) value. Now when you try to update >> >> >>>>> default = {'cluster': 'some_value'} >>>>> cluster = {'cluster': 'another_value'} >>>>> cluster.update(default) >>>>> print cluster >>>>> >> {'cluster': 'some_value'} >> >> If you read up on what update is supposed to do, this is correct -- keys in >> default are inserted into cluster -- replacing values if they already exist. >> >> I believe update is not what you want for two reasons: >> >> 1. It's doubtful that you want a default to replace an existing value, and >> that's what update does. >> >> 2. I get the distinct impression that you are expecting the update to be >> applied recursively down through the hierarchy. Such is not the case. >> >> >> >> >> And I just have to ask: Of what use whatsoever is a dictionary (hierarchy) >> that contains *one* single value which needs a sequence of 6 keys to access? >> >> print >> default['cluster']['platform']['elements']['data_sources']['elements']['db_min_pool_size'] >> >>>>> 10 >>>>> >> Seems absurd unless there is lots more going on here. >> > Thanks. Any particular reason you replied off-list? > Huh? Oh hell. My mistake. (This is now back on the list -- where it should have been to start with.) > Anyway, I'm trying to model a cluster of servers in a yaml file that > gets edited by humans and a tree structure makes it easier to > understand the context of each invidual key. If it was arrange in a > flat fashion, each key would have to be longer in order to make it > unique and provide some context as to what the user was actually > editing. > > I actually didn't paste the whole dictionary. I cut it down to make it > easier to explain. When you see the full version, the multiple levels > make more sense. Tried various approaches so far, and none work. I > can't traverse the tree recursively because each time you recurse, you > lose the absolute position of the key your currently at, and then > there's no way to update the values. > > Doug. > Ok. Thanks for simplifying things before sending the question out to the list. You probably wouldn't have gotten a response otherwise. I'm not sure I believe the reasoning for the inability to recurse. It seems rather simple to recurse through the structures in tandem, adding any key:value found in the default to the other if not already present. Gary Herron From doug.garstang at gmail.com Mon Aug 2 03:06:16 2010 From: doug.garstang at gmail.com (Douglas Garstang) Date: Mon, 2 Aug 2010 00:06:16 -0700 Subject: Merging two dictionaries In-Reply-To: <4C566C5E.9000008@islandtraining.com> References: <4C565E79.6090307@islandtraining.com> <4C566C5E.9000008@islandtraining.com> Message-ID: On Sun, Aug 1, 2010 at 11:57 PM, Gary Herron wrote: > On 08/01/2010 11:11 PM, Douglas Garstang wrote: >> >> On Sun, Aug 1, 2010 at 10:58 PM, Gary Herron >> ?wrote: >> >>> >>> On 08/01/2010 10:09 PM, Douglas Garstang wrote: >>> >>>> >>>> Anyone, >>>> >>>> I have the two dictionaries below. How can I merge them, such that: >>>> >>>> 1. The cluster dictionary contains the additional elements from the >>>> default dictionary. >>>> 2. Nothing is removed from the cluster dictionary. >>>> >>>> The idea here is that the two dictionaries are read from different >>>> files where, if the value isn't found in the cluster dictionary, it's >>>> pulled from the default one, and I can have a new dictionary >>>> reflecting this. The update() method on dictionaries doesn't seem to >>>> work. The resulting dictionary always seems to be the one passed as a >>>> parameter. >>>> >>>> default = { >>>> ? ? 'cluster': { >>>> ? ? ? ? 'platform': { >>>> ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? 'data_sources': { >>>> ? ? ? ? ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'db_min_pool_size': 10 >>>> ? ? ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? }, >>>> ? ? ? ? }, >>>> ? ? } >>>> } >>>> >>>> cluster = { >>>> ? ? 'cluster': { >>>> ? ? ? ? 'name': 'Customer 1', >>>> ? ? ? ? 'description': 'Production', >>>> ? ? ? ? 'environment': 'production', >>>> ? ? ? ? 'platform': { >>>> ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? 'data_source': { >>>> ? ? ? ? ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'username': 'username', >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'password': 'password' >>>> ? ? ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? }, >>>> ? ? ? ? }, >>>> ? ? } >>>> } >>>> >>>> The resulting dictionary would therefore look like this: >>>> >>>> new_dict = { >>>> ? ? 'cluster': { >>>> ? ? ? ? 'name': 'Customer 1', >>>> ? ? ? ? 'description': 'Production', >>>> ? ? ? ? 'environment': 'production', >>>> ? ? ? ? 'platform': { >>>> ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? 'data_source': { >>>> ? ? ? ? ? ? ? ? ? ? 'elements': { >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'username': 'username', >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'password': 'password', >>>> ? ? ? ? ? ? ? ? ? ? ? ? 'db_min_pool_size': 10 # This was added from >>>> the default. >>>> ? ? ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? ? ? }, >>>> ? ? ? ? ? ? }, >>>> ? ? ? ? }, >>>> ? ? } >>>> } >>>> >>>> >>>> Thanks, >>>> Doug. >>>> >>>> >>>> >>> >>> Your dictionaries are annoyingly complicated -- making it hard to see >>> what's >>> going on. ?Here I've replaced all the distractions of your dictionary >>> nesting with a simple (string) value. ?Now when you try to update >>> >>> >>>>>> >>>>>> default = {'cluster': 'some_value'} >>>>>> cluster = {'cluster': 'another_value'} >>>>>> cluster.update(default) >>>>>> print cluster >>>>>> >>> >>> {'cluster': 'some_value'} >>> >>> If you read up on what update is supposed to do, this is correct -- keys >>> in >>> default are inserted into cluster -- replacing values if they already >>> exist. >>> >>> I believe update is not what you want for two reasons: >>> >>> ?1. ?It's doubtful that you want a default to replace an existing value, >>> and >>> that's what update does. >>> >>> ?2. ?I get the distinct impression that you are expecting the update to >>> be >>> applied recursively down through the hierarchy. ?Such is not the case. >>> >>> >>> >>> >>> And I just have to ask: Of what use whatsoever is a dictionary >>> (hierarchy) >>> that contains *one* single value which needs a sequence of 6 keys to >>> access? >>> >>> print >>> >>> default['cluster']['platform']['elements']['data_sources']['elements']['db_min_pool_size'] >>> >>>>>> >>>>>> 10 >>>>>> >>> >>> Seems absurd unless there is lots more going on here. >>> >> >> Thanks. Any particular reason you replied off-list? >> > > Huh? ?Oh hell. ?My mistake. ?(This is now back on the list -- where it > should have been to start with.) > > >> Anyway, I'm trying to model a cluster of servers in a yaml file that >> gets edited by humans and a tree structure makes it easier to >> understand the context of each invidual key. If it was arrange in a >> flat fashion, each key would have to be longer in order to make it >> unique and provide some context as to what the user was actually >> editing. >> >> I actually didn't paste the whole dictionary. I cut it down to make it >> easier to explain. When you see the full version, the multiple levels >> make more sense. Tried various approaches so far, and none work. I >> can't traverse the tree recursively because each time you recurse, you >> lose the absolute position of the key your currently at, and then >> there's no way to update the values. >> >> Doug. >> > > Ok. ?Thanks for simplifying things before sending the question out to the > list. ?You probably wouldn't have gotten a response otherwise. > > I'm not sure I believe the reasoning for the inability to recurse. ?It seems > rather simple to recurse through the structures in tandem, adding any > key:value found in the default to the other if not already present. Actually, I had issues with trying recurse through the structures in tandem too. This didn't work: for a,b,c,d in ( cluster.iteritems(), default.iteritems() ): ... do something ... It returns an unpack error. Doug. From clp2 at rebertia.com Mon Aug 2 03:26:54 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 2 Aug 2010 00:26:54 -0700 Subject: Merging two dictionaries In-Reply-To: References: <4C565E79.6090307@islandtraining.com> <4C566C5E.9000008@islandtraining.com> Message-ID: On Mon, Aug 2, 2010 at 12:06 AM, Douglas Garstang wrote: > Actually, I had issues with trying recurse through the structures in > tandem too. This didn't work: > > for a,b,c,d in ( cluster.iteritems(), default.iteritems() ): > ? ?... do something ... > > It returns an unpack error. Well, yeah. That for-loop has several problems: - You're iterating over the items of a 2-tuple. It's just like: for a,b,c,d in [1, 2]: It's not treated any differently just because the items happen to be iterators themselves. The iterators aren't automagically iterated through in parallel just by putting them in a tuple. That would require a zip(). - iteritems() returns a sequence of 2-tuples. Even when zipped, these tuples don't get magically unpacked and repacked into 4-tuples: for a, b, c, d in zip([(1,2), (3,4)], [(5,6), (7,8)]): # still fails; can't unpack 2 separate tuples (i.e. (1,2) (5,6) ) directly into 4 variables; the nesting is wrong - iteritems() returns the keys in an arbitrary order; the two iteritems() calls won't be in any way "synchronized" so the keys match up Cheers, Chris -- http://blog.rebertia.com From no.email at nospam.invalid Mon Aug 2 03:47:11 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 02 Aug 2010 00:47:11 -0700 Subject: Merging two dictionaries References: Message-ID: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> Douglas Garstang writes: > default = {... > 'data_sources': { ... > cluster = {... > 'data_source': { ... Did you want both of those to say the same thing instead of one of them being 'data_source' and the other 'data_sources' ? If yes, then the following works for me: def merge(cluster, default): # destructively merge default into cluster for k,v in cluster.iteritems(): if k in default and type(v)==dict: assert type(default(k))==dict merge(v,default[k]) for k,v in default.iteritems(): if k not in cluster: cluster[k] = v From mail at timgolden.me.uk Mon Aug 2 04:00:17 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 02 Aug 2010 09:00:17 +0100 Subject: How to catch windows shutdown/reboot message In-Reply-To: References: Message-ID: <4C567B11.4060408@timgolden.me.uk> On 02/08/2010 02:17, rechardchen wrote: > I'm writing a python script which runs as a windowsxp service. > The problem is how to catch the windows shutdown/reboot message and do > some cleaning job when system is going down? > > The atexit module and signal module on windows dont seems to work. I > guess the python win32api may be of help, but I am not familiar with it... > Thank you Have a look at the SENS stuff: http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html TJG From newBlue at batbug.org Mon Aug 2 04:09:29 2010 From: newBlue at batbug.org (NewBlue) Date: Mon, 02 Aug 2010 16:09:29 +0800 Subject: Problem with Elementtree and XMLSchem instance type References: Message-ID: >>>>> "Lawrence" == Lawrence D'Oliveiro writes: Lawrence> In message Lawrence> , Lawrence> Roland Lawrence> Hedberg wrote: > And there is the problem, I've lost the coupling between the prefix >> 'fed' and the namespace >> "http://docs.oasis-open.org/wsfed/federation/200706". Lawrence> Why is this a problem? ???? -- ?????????????????? ????????????? My homepage:[http://211.92.88.40/~newblue] From __peter__ at web.de Mon Aug 2 04:09:35 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Aug 2010 10:09:35 +0200 Subject: Merging two dictionaries References: Message-ID: Douglas Garstang wrote: > I have the two dictionaries below. How can I merge them, such that: > > 1. The cluster dictionary contains the additional elements from the > default dictionary. > 2. Nothing is removed from the cluster dictionary. def inplace_merge(default, cluster): assert isinstance(default, dict) assert isinstance(cluster, dict) d = set(default) c = set(cluster) default_only = d - c both = d & c for key in both: dv = default[key] cv = cluster[key] if isinstance(cv, dict): inplace_merge(dv, cv) cluster.update((dk, default[dk]) for dk in default_only) should work once you've fixed your example dicts. Peter From thorsten at thorstenkampe.de Mon Aug 2 04:33:22 2010 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Aug 2010 10:33:22 +0200 Subject: How to capture all the environment variables from shell? References: <4C4E43D3.9070203@syslang.net> Message-ID: * Tim Chase (Mon, 26 Jul 2010 21:42:24 -0500) > On 07/26/10 21:26, Steven W. Orr wrote: > > Please! Never export anything from your .bashrc unless you > > really know what you're doing. Almost all exports should be > > done in your .bash_profile > > Could you elaborate on your reasoning why (or why-not)? I've > found that my .bash_profile doesn't get evaluated when I crank up > another terminal window, while my bashrc does. Thus I tend to > put my exports in my ~/.bashrc so they actually take effect in my > shell... ~/.bash_profile is only evaluated for login shells and ~/.bashrc only for non-login shells. Thus it's recommended to keep ~/.bash_profile empty (except a source statement for .bashrc) and put all your settings, aliases, exports, etc. in .bashrc. Thorsten From jeanmichel at sequans.com Mon Aug 2 04:50:03 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 02 Aug 2010 10:50:03 +0200 Subject: Access stdout from external program. In-Reply-To: <561066.47255.qm@web52905.mail.re2.yahoo.com> References: <561066.47255.qm@web52905.mail.re2.yahoo.com> Message-ID: <4C5686BB.7000508@sequans.com> Paul Lemelle wrote: > Hi JM, > > My last dumb question: When I try to run the below script as an > executable, I get the following error: > pttdev at pttTestVM:~$ ./argv.py 4 > import: unable to open X server `/tmp/launch-c8feFG/org.x:0' @ > import.c/ImportImageCommand/361. > ./argv.py: line 8: syntax error near unexpected token `print' > ./argv.py: line 8: ` print x' > > The script: > # Writing the output to a standard argv argument > > #!/usr/bin/env python > > import sys > > for x in sys.argv: > print x > > > #END > > Any idea why? > > Thanks, > Paul > Please don't remove python-list. I see 2 possibilities: 1/ this is related to the open X server, for that I can't help you, something related to your exported display if you're remotely logged on the machine 2/ you are using python 2.x syntax within a python 3 interpreter. Try "print (x)". JM From s.selvamsiva at gmail.com Mon Aug 2 04:59:49 2010 From: s.selvamsiva at gmail.com (S.Selvam) Date: Mon, 2 Aug 2010 14:29:49 +0530 Subject: Capturing running Application Message-ID: Hi all, I am using python 2.6(running ubuntu 9.10 ). I want to display the amount of time spent( by an user) among all the running applications like Gedit, Firefox, GIMP and display the result graphically. For eg: Firefox: 60% Gedit:25% Terminal:15% I think, i need to capture the currently focussed application, update the time spent in some format and display it graphically. I am not sure about the modules that need to be used.I welcome your ideas. -- Regards, S.Selvam " I am because we are " -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.wintle at teamrubber.com Mon Aug 2 05:00:58 2010 From: tim.wintle at teamrubber.com (Tim Wintle) Date: Mon, 02 Aug 2010 10:00:58 +0100 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <1280739658.10380.8.camel@tim-laptop> On Sun, 2010-08-01 at 20:01 -0400, Terry Reedy wrote: > Not every C programmer knows or wants to learn C++. I think Terry is the only person that's mentioned this - but I'd like to give extra support to it - I for one prefer C to C++ (as someone that writes quite a lot of C extension modules). And as Stephen mentioned - just because C is not an OO language, doesn't mean you can't write OO code in it - you just have to pass an instance of the class method is defined on in as the first parameter (like you do in Python). Tim From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 2 05:10:26 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 02 Aug 2010 11:10:26 +0200 Subject: The untimely dimise of a weak-reference In-Reply-To: <8bhi2fFifjU1@mid.individual.net> References: <8bhi2fFifjU1@mid.individual.net> Message-ID: <4c568b59$0$14545$426a34cc@news.free.fr> Gregory Ewing a ?crit : (snip) > import weakref > > class weakmethod(object): > > def __init__(self, bm): > self.ref = weakref.ref(bm.im_self) > self.func = bm.im_func > > def __call__(self, *args, **kwds): > obj = self.ref() > if obj is None: > raise ValueError("Calling dead weak method") > self.func(obj, *args, **kwds) Would be better with : return self.func(obj, *args, *kwds) From jeanmichel at sequans.com Mon Aug 2 05:23:30 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 02 Aug 2010 11:23:30 +0200 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <7xmxt5357h.fsf@ruckus.brouhaha.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> <7xmxt5357h.fsf@ruckus.brouhaha.com> Message-ID: <4C568E92.50907@sequans.com> Paul Rubin wrote: > Michele Simionato writes: > >> I am actually more radical than that. From >> http://www.artima.com/weblogs/viewpost.jsp?thread=237121: >> In this series I have argued that super is tricky; I think nobody can... >> > > When I look at that URL, I see a Java stack dump: > > java.lang.RuntimeException: com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid > at com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112) > ... > > Seems appropriate. > remove the ending double dot. JM From steve-REMOVE-THIS at cybersource.com.au Mon Aug 2 05:44:35 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 09:44:35 GMT Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> Message-ID: <4c569382$0$28655$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 23:39:34 -0700, ????? wrote: > If you just click in my web page to see the script run in action due to > the cgitb module i use it will provide you both the source code that the > error appears and the error as well. > > All you have to do is click here: > http://www.webville.gr/cgi-bin/koukos.py I'll do this just once, but next time, don't expect others to track down the error message for you. We're volunteers, we don't owe you anything, so if you want us to help, you make it easy for us. Some people have access to email, but not web. If you can't be bothered to copy and paste the error message into an email or news post, why should we be bothered to help you? The error you are getting is: NameError: name 'time' is not defined That tells you that you don't have a function called time() defined anywhere. You need to import the time module first: import time and then use the fully qualified function name time.time(), or do: from time import time and then use the function alone time(). > As for the encoding why when i print greek characters they dont appear > correctly in chrome in runtime? What encoding does the web page claim to be? You need to check the document encoding, and see that it matches the document encoding you are actually using. -- Steven From steve-REMOVE-THIS at cybersource.com.au Mon Aug 2 05:45:59 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2010 09:45:59 GMT Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4c5693d7$0$28655$c3e8da3@news.astraweb.com> On Sun, 01 Aug 2010 23:15:11 -0700, Michele Simionato wrote: > On Jul 31, 5:08?am, Steven D'Aprano cybersource.com.au> wrote: >> I have read Michelle Simionato's articles on super in Python. > > One "l" please! I am a man! ;-) My apologies. You'd think I would know the difference between Michele and Michelle :( [snip] > Still I believe that super is a red herring and that you should really > start thinking: what advantages did > multiple inheritance *really* bring into my code? Could have I done > without? And what would have happen? > These are the relevant question, not the exact meaning of super in hairy > hierarchies. Yes, these are very good points. It's always worth looking at alternatives to subclassing in the first place. Far too often it's not just the first idiom people think of, but the *only* idiom they think of. -- Steven From bartc at freeuk.com Mon Aug 2 05:55:50 2010 From: bartc at freeuk.com (Bartc) Date: Mon, 2 Aug 2010 10:55:50 +0100 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> Message-ID: <6Dw5o.72330$Ds3.63060@hurricane> "Alain Ketterlin" wrote in message news:877hkdhyl5.fsf at dpt-info.u-strasbg.fr... > Lawrence D'Oliveiro writes: > >> Say a vector V is a tuple of 3 numbers, not all zero. You want to >> normalize >> it (scale all components by the same factor) so its magnitude is 1. >> >> The usual way is something like this: >> >> L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) >> V = (V[0] / L, V[1] / L, V[2] / L) > Your best bet is to define a function that does the normalization. Your > (local) name will disappear at the end of the call. If you want it to > work for any vector size: > > def norm(V): > L = math.sqrt( sum( [x**2 for x in V] ) ) > return [ x/L for x in V ] There's a cost involved in using those fancy constructions. I found the following to be about twice as fast, when vectors are known to have 3 elements: def norm3d(v): L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2])) return (v[0]/L,v[1]/L,v[2]/L) (Strangely, changing those divides to multiplies made it slower.) -- Bartc From alain at dpt-info.u-strasbg.fr Mon Aug 2 06:19:36 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Mon, 02 Aug 2010 12:19:36 +0200 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <6Dw5o.72330$Ds3.63060@hurricane> Message-ID: <87fwyxgvuv.fsf@dpt-info.u-strasbg.fr> "Bartc" writes: >> def norm(V): >> L = math.sqrt( sum( [x**2 for x in V] ) ) >> return [ x/L for x in V ] > > There's a cost involved in using those fancy constructions. Sure. The above has three loops that take some time. > I found the following to be about twice as fast, when vectors are > known to have 3 elements: > > def norm3d(v): > L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2])) > return (v[0]/L,v[1]/L,v[2]/L) > > (Strangely, changing those divides to multiplies made it slower.) You mean by setting L to 1.0 / math.sqrt(...) and using v[0]*L etc.? I think * and / have the same cost on floats, and the added / adds some cost. But what you observe is probably caused by the overloading of "*", that needs more type checks. You may try with operator.mul to see if the call compensates the cost of type checking, but I doubt it. -- Alain. From alanwilter at gmail.com Mon Aug 2 06:37:05 2010 From: alanwilter at gmail.com (Alan) Date: Mon, 2 Aug 2010 11:37:05 +0100 Subject: python3: signal.signal/singal.alarm not working as expected Message-ID: Hi there, I have this example code to illustrate a problem I am having with python3. It works fine with python 2.6 and 2.7 but does not with python 3.1. Please, can someone tell me why or how to fix this example? from __future__ import print_function import os, subprocess, signal def signal_handler( signum, frame ): print( "PID: %s" % pid ) print( "Timed out! Process %s killed, max exec time (%ss) exceeded" % (pid, timeTol ) ) os.kill( int( pid ), 15 ) raise Exception( "Taking too long to finish... aborting!" ) if __name__ == '__main__': timeTol = 5 cmd = 'find /' signal.signal(signal.SIGALRM, signal_handler) signal.alarm(timeTol) p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout = subprocess.PIPE) pid = p.pid out = str( p.communicate()[0].decode() ) print(out) Many thanks, Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From bartc at freeuk.com Mon Aug 2 07:32:41 2010 From: bartc at freeuk.com (Bartc) Date: Mon, 2 Aug 2010 12:32:41 +0100 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr><6Dw5o.72330$Ds3.63060@hurricane> <87fwyxgvuv.fsf@dpt-info.u-strasbg.fr> Message-ID: <02y5o.243$e47.58@hurricane> "Alain Ketterlin" wrote in message news:87fwyxgvuv.fsf at dpt-info.u-strasbg.fr... > "Bartc" writes: >> def norm3d(v): >> L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2])) >> return (v[0]/L,v[1]/L,v[2]/L) >> >> (Strangely, changing those divides to multiplies made it slower.) > > You mean by setting L to 1.0 / math.sqrt(...) and using v[0]*L etc.? Yes. > I think * and / have the same cost on floats, and the added / adds > some cost. I expected no measurable difference, not running Python anyway (I tried it in gcc and using divides increased runtimes by 50%, corresponding to some 1% for Python). I would naturally have written it using multiplies, and was just surprised at a 3-4% slowdown. > But what you observe is probably caused by the overloading of > "*", that needs more type checks. That sounds reasonable. -- Bartc From chare at labr.net Mon Aug 2 07:46:05 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 06:46:05 -0500 Subject: beginner python GUI question In-Reply-To: References: Message-ID: <283352C2-4A6B-470D-B82C-12D2F130578B@labr.net> On Aug 1, 2010, at 8:33 PM, rechardchen wrote: > ? 2010-8-2 6:15, Chris Hare ??: >> I hope I can explain this correctly. >> >> I have a GUI, which is already being processed by a mainloop. I want to be able to open a second window so the user can interact with specific information in the second window. I pulled together this code example >> >> from Tkinter import * >> >> class Net: >> def __init__(self,tkWin): >> self.window = tkWin >> def show(self,t): >> self.l = Label(self.window,text=t) >> self.l.grid() >> button = Button(self.window, text="Again") >> button.bind("", self.Again) >> button.grid() >> def Again(self,event): >> win3 = Tk() >> x = Net(win3) >> x.show("window 3") >> >> root = Tk() >> root.title = "test" >> f = Frame(root,bg="Yellow") >> l = Label(f,text="window 1") >> f.grid() >> l.grid() >> >> win2 = Tk() >> x = Net(win2) >> x.show("window 2") >> if __name__ == "__main__": >> root.mainloop() >> >> Is this the right way to do things, or would you suggest something different? >> >> Thanks, >> Chris >> > Using Tkinter.Toplevel may be better. :) > -- > http://mail.python.org/mailman/listinfo/python-list I thought that would be a good idea, so I changed the code a bit to this: from Tkinter import * class Net: def __init__(self): self.window = Toplevel() def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text="Again") button.bind("", self.Again) button2 = Button(self.window, text="Dismiss") button2.bind("", self.window.destroy) button.grid() button2.grid() def Again(self,event): x = Net() x.show("window 3") root = Tk() root.title = "test" f = Frame(root,bg="Yellow") l = Label(f,text="window 1") f.grid() l.grid() x = Net() x.show("window 2") if __name__ == "__main__": root.mainloop() I put the call to Topevel into the Class. This however, gets me an error message Traceback (most recent call last): File "a.py", line 27, in x = Net() File "a.py", line 5, in __init__ self.window = Toplevel() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1978, in __init__ self.title(root.title()) TypeError: 'str' object is not callable I should think it would work, but I don't understand why it doesn't. Thanks From santiago.caracol at gmail.com Mon Aug 2 08:12:37 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Mon, 2 Aug 2010 05:12:37 -0700 (PDT) Subject: run subprocesses in parallel Message-ID: Hello, I want to run several subprocesses. Like so: p1 = Popen("mycmd1" + " myarg", shell=True) p2 = Popen("mycmd2" + " myarg", shell=True) ... pn = Popen("mycmdn" + " myarg", shell=True) What would be the most elegant and secure way to run all n subprocesses in parallel? Santiago From lists at cheimes.de Mon Aug 2 08:21:38 2010 From: lists at cheimes.de (Christian Heimes) Date: Mon, 02 Aug 2010 14:21:38 +0200 Subject: run subprocesses in parallel In-Reply-To: References: Message-ID: > I want to run several subprocesses. Like so: > > p1 = Popen("mycmd1" + " myarg", shell=True) > p2 = Popen("mycmd2" + " myarg", shell=True) > .... > pn = Popen("mycmdn" + " myarg", shell=True) > > What would be the most elegant and secure way to run all n > subprocesses in parallel? They already run in parallel. Depending on your command this may not be secure due to race conditions. You might want to drop shell=True and use a list as arguments instead. The shell=True argument is frowned upon and should only be used if your really, really need a shell. From __peter__ at web.de Mon Aug 2 08:25:49 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Aug 2010 14:25:49 +0200 Subject: beginner python GUI question References: Message-ID: Chris Hare wrote: >>> root = Tk() >>> root.title = "test" > I should think it would work, but I don't understand why it doesn't. Try root.title("test") title() is a method that you are hiding with your attribute leading to problems later on. By the way, what kind of documentation are you using for your efforts? Here's a concise one: http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html Also, effbot.org has a lot of information that you best access via Google. Peter From rechardchen at gmail.com Mon Aug 2 08:31:04 2010 From: rechardchen at gmail.com (rechardchen) Date: Mon, 02 Aug 2010 20:31:04 +0800 Subject: How to catch windows shutdown/reboot message In-Reply-To: References: Message-ID: ? 2010-8-2 16:00, Tim Golden ??: > On 02/08/2010 02:17, rechardchen wrote: >> I'm writing a python script which runs as a windowsxp service. >> The problem is how to catch the windows shutdown/reboot message and do >> some cleaning job when system is going down? >> >> The atexit module and signal module on windows dont seems to work. I >> guess the python win32api may be of help, but I am not familiar with >> it... >> Thank you > > Have a look at the SENS stuff: > > http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html > > TJG Thanks, the extended handler functionality works. :) From nikos.the.gr33k at gmail.com Mon Aug 2 08:32:49 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 2 Aug 2010 05:32:49 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: Steven, First of all thank you for your response. I cant beleive i neglected to import the time module! The only reason that i asked you guys to follow the link was for you to see the actualt coding and error report as python produces it by itself with all the relative characteristics. Of course it was not due to boredom and there was no need to be aggresive with me as this wasn't the case. I thouigh that by giving the URL was easier for you guys. Now the script runs but for some reason only the code block within the 'else' tun each time: This: else: print "??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? ?? ??????! ?? ????? ????? ? ??????? ??????????!!" cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year The cookie is only get set and never expires i changed the if with this if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist but still no luck. As for the encoding Notepad++, which is what i use for an editor say its UTF-8 without BOM. Isn't this what i'm supposed to use? My Python scripts only containes english and greek letters, so i though usign UTF-8 is the way to go. No?! Please if you explain to me in greater detail! From chare at labr.net Mon Aug 2 08:49:38 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 07:49:38 -0500 Subject: beginner python GUI question In-Reply-To: References: Message-ID: <5200041A-5B00-4E95-8229-0DD1C5078229@labr.net> On Aug 2, 2010, at 7:25 AM, Peter Otten wrote: > Chris Hare wrote: > >>>> root = Tk() >>>> root.title = "test" > >> I should think it would work, but I don't understand why it doesn't. > > Try > > root.title("test") > > title() is a method that you are hiding with your attribute leading to > problems later on. > > By the way, what kind of documentation are you using for your efforts? > > Here's a concise one: > > http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html > > Also, effbot.org has a lot of information that you best access via Google. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list I have several python books and I have been using effbot and various other sources. Thanks for the help. Your suggestion (and a couple others I added) got my example working exactly like I want it, so I can incorporate that into my program. Thanks again. Chris From flebber.crue at gmail.com Mon Aug 2 09:13:46 2010 From: flebber.crue at gmail.com (flebber) Date: Mon, 2 Aug 2010 06:13:46 -0700 (PDT) Subject: Mechanize - save to XML or CSV Message-ID: <1c0fcd51-4097-492f-891e-f224556ab62f@n19g2000prf.googlegroups.com> HI guys and gals this is probably a simple question but I can't find the answer directly in the docs for python mechanize. http://pypi.python.org/pypi/mechanize/ Is it possible to retrieve and save a web page data as xml or a csv file? From simon at brunningonline.net Mon Aug 2 09:41:20 2010 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 2 Aug 2010 14:41:20 +0100 Subject: Mechanize - save to XML or CSV In-Reply-To: <1c0fcd51-4097-492f-891e-f224556ab62f@n19g2000prf.googlegroups.com> References: <1c0fcd51-4097-492f-891e-f224556ab62f@n19g2000prf.googlegroups.com> Message-ID: On 2 August 2010 14:13, flebber wrote: > HI guys and gals this is probably a simple question but I can't find > the answer directly in the docs for python mechanize. > > http://pypi.python.org/pypi/mechanize/ > > Is it possible to retrieve and save a web page data as xml or a csv > file? Sure, but mechanize only does the first half of the job. You retrieve the data using mechanize, then use another module for the save-as bit. ElementTree for XML and csv for, um, for csv are both in the standard library. -- Cheers, Simon B. From invalid at invalid.invalid Mon Aug 2 10:42:21 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 2 Aug 2010 14:42:21 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 2010-08-02, Christian Heimes wrote: > In your opinion what would Python gain from a C++ implementation? Greater buzzword-compliance -- an important characteristic highly prized by Human-Resources poeple and mid-level managers here in the US. ;) -- Grant From amyjack1 at rediffmail.com Mon Aug 2 10:48:19 2010 From: amyjack1 at rediffmail.com (amyjack1 at rediffmail.com) Date: Mon, 2 Aug 2010 07:48:19 -0700 (PDT) Subject: AMY JACKSON HOT PICTURES including upcoming movies, biography, Message-ID: <1cb19434-2cf2-40d2-8e90-bb68ae6a25be@l32g2000prn.googlegroups.com> AMY JACKSON HOT PICTURES including upcoming movies, biography, http://amyjacksons.blogspot.com From megerea at gmail.com Mon Aug 2 11:00:39 2010 From: megerea at gmail.com (Mallan4) Date: Mon, 2 Aug 2010 08:00:39 -0700 (PDT) Subject: Simple Data Entry Work Message-ID: Hi there you need a job to work at the comfort of your home, here are the two links to earn you the money you want Note:you have to be hard working in order to earn big,give it a try and register, you have nothing to loose no registration charges http://www.dataentrywork.net/?id=27096 http://www.websitetester.biz/index.php?lang=en&ref=6a823270ced424cbba5ff86b04eeb5f2 join our team and get started to receive forms to fill up then submit and earn more money as much as you want!.. Registration is for free as we also need someone who are looking for an opportunity to be successful!. You have an option to choose your method of payment, either PayPal or Wire Transfer. From breamoreboy at yahoo.co.uk Mon Aug 2 11:21:33 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 16:21:33 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 01/08/2010 12:10, Lawrence D'Oliveiro wrote: > In message, Mark > Lawrence wrote: > >> On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: >> >>> In message, Mark >>> Lawrence wrote: >>> >>>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >>>> >>>>> In message, Mark >>>>> Lawrence wrote: >>>>> >>>>>> Personally I find double clicking on an msi file rather easier. >>>>> >>>>> Easier than apt-get dist-upgrade? >>>> >>>> I'm sorry but I only do English, could you please translate. :) >>> >>> I run Debian Unstable, which has new goodies coming out on a weekly >>> basis. The last time I checked for updates, there were over 500 packages >>> I had installed for which updates were available. It only took a command >>> like the above to upgrade them all. >>> >>> How many .msi files would you have to click on to achieve the Windows >>> equivalent? >> >> ... I simply couldn't cope with over 500 installed packages. > > Precisely my point. Go back to playing with your .msi toys. > > Oh, and. Repeating what was obviously deliberately snipped. "No idea, but your mental capacity is clearly infinitely higher than mine, as I simply couldn't cope with over 500 installed packages. What do they all do, make your lunch and fetch the beer from the fridge amongst other things?" How does any user or an admin cope with 500 packages? Can Python help here, assume an eight hour working day? c:\Python31\Lib>python Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 8*60*60/500 57.6 So every working day you have 57.6 seconds to use each package. Strangely I don't think anyone will get too much done. Am I in cloud cuckoo land or are you? As it happens, I'm also not a windows fan, did most of my work on VMS. Which to repeat myself stands for Very Much Safer. Thinking of which did *nix ever get around to providing proper clustering, or does VMS still rule? Mark Lawrence. From breamoreboy at yahoo.co.uk Mon Aug 2 11:35:53 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 16:35:53 +0100 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <4C568E92.50907@sequans.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> <7xmxt5357h.fsf@ruckus.brouhaha.com> <4C568E92.50907@sequans.com> Message-ID: On 02/08/2010 10:23, Jean-Michel Pichavant wrote: > Paul Rubin wrote: >> Michele Simionato writes: >>> I am actually more radical than that. From >>> http://www.artima.com/weblogs/viewpost.jsp?thread=237121: >>> In this series I have argued that super is tricky; I think nobody can... >> >> When I look at that URL, I see a Java stack dump: >> >> java.lang.RuntimeException: >> com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid >> at >> com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112) >> >> ... >> >> Seems appropriate. > remove the ending double dot. > > JM aka the colon. :) Cheers. Mark Lawrence From breamoreboy at yahoo.co.uk Mon Aug 2 11:37:05 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 16:37:05 +0100 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> Message-ID: On 02/08/2010 07:15, Michele Simionato wrote: > On Jul 31, 5:08 am, Steven D'Aprano cybersource.com.au> wrote: >> I have read Michelle Simionato's articles on super in Python. > > One "l" please! I am a man! ;-) > Please prove it, get your bits out!!! :) > > M. Simionato From benjamin.kaplan at case.edu Mon Aug 2 11:41:20 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 2 Aug 2010 08:41:20 -0700 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On Mon, Aug 2, 2010 at 8:21 AM, Mark Lawrence wrote: > On 01/08/2010 12:10, Lawrence D'Oliveiro wrote: > >> In message, Mark >> Lawrence wrote: >> >> On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: >>> >>> In message, Mark >>>> Lawrence wrote: >>>> >>>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >>>>> >>>>> In message, Mark >>>>>> Lawrence wrote: >>>>>> >>>>>> Personally I find double clicking on an msi file rather easier. >>>>>>> >>>>>> >>>>>> Easier than apt-get dist-upgrade? >>>>>> >>>>> >>>>> I'm sorry but I only do English, could you please translate. :) >>>>> >>>> >>>> I run Debian Unstable, which has new goodies coming out on a weekly >>>> basis. The last time I checked for updates, there were over 500 packages >>>> I had installed for which updates were available. It only took a command >>>> like the above to upgrade them all. >>>> >>>> How many .msi files would you have to click on to achieve the Windows >>>> equivalent? >>>> >>> >>> ... I simply couldn't cope with over 500 installed packages. >>> >> >> Precisely my point. Go back to playing with your .msi toys. >> >> Oh, and. >> > > Repeating what was obviously deliberately snipped. > > "No idea, but your mental capacity is clearly infinitely higher than mine, > as I simply couldn't cope with over 500 installed packages. What do they > all do, make your lunch and fetch the beer from the fridge amongst other > things?" > > How does any user or an admin cope with 500 packages? Can Python help > here, assume an eight hour working day? > > c:\Python31\Lib>python > Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> 8*60*60/500 > 57.6 > > So every working day you have 57.6 seconds to use each package. Strangely I > don't think anyone will get too much done. Am I in cloud cuckoo land or are > you? > > You seem to be mistaken as to what a "package" is. Python : * python * python-minimal * python2.6 * libbz2 * libc6 * libdb4.8 * libncursesw5 * libreadline6 * mime-support * python2.6-minimal * libssl0.9.8 * zlib1g * debconf * perl-base * dpkg * coreutils * lzma * libacl1 * libattr1 * libselinux1 * libgcc1 * libstdc++6 * gcc-4.4-base * libncurses5 * readline-common So these are the packages needed just to run Python in Ubuntu. It doesn't include the packages required for the kernel, the desktop environment, the window manager, the terminal, and whatever else you want running. In my fairly clean Ubuntu VM (I use it almost exclusively for testing), I have close to 1500 packages installed. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From magguru.chinnamnaidu at gmail.com Mon Aug 2 11:50:12 2010 From: magguru.chinnamnaidu at gmail.com (paypal cash) Date: Mon, 2 Aug 2010 08:50:12 -0700 (PDT) Subject: THANKS GOD! I GOT $2000 FROM PAYPAL.... Message-ID: <23d822e9-d554-4c35-b1af-c19fba0722d4@v35g2000prn.googlegroups.com> THANKS GOD! I GOT $2000 FROM PAYPAL At http://ukcollegegirls.co.cc I have hidden the PayPal Form link in an image. in that website On Top Side Above search box , click on image and enter your PayPal id And Your name. From cournape at gmail.com Mon Aug 2 12:11:44 2010 From: cournape at gmail.com (David Cournapeau) Date: Tue, 3 Aug 2010 01:11:44 +0900 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On Mon, Aug 2, 2010 at 10:20 AM, Christian Heimes wrote: > > In your opinion what would Python gain from a C++ implementation? The elusive advantages of "OO" in C++ are relatively minor compared to RIIA which would make reference counting much easier to deal with. But even that is not a strong enough argument for C++. The little C++ we have in scipy had causes a lot of headache - C++ portability is still an issue once you are outside the 4-5 main OS/Compilers combinations, David From thomas at jollans.com Mon Aug 2 12:15:53 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 18:15:53 +0200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4C56EF39.2060600@jollans.com> On 08/02/2010 04:42 PM, Grant Edwards wrote: > On 2010-08-02, Christian Heimes wrote: > >> In your opinion what would Python gain from a C++ implementation? > > Greater buzzword-compliance -- an important characteristic highly > prized by Human-Resources poeple and mid-level managers here in the > US. > > ;) > C++Python would never beat IronPython on that front From breamoreboy at yahoo.co.uk Mon Aug 2 12:27:22 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 17:27:22 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 02/08/2010 16:41, Benjamin Kaplan wrote: > On Mon, Aug 2, 2010 at 8:21 AM, Mark Lawrencewrote: > >> On 01/08/2010 12:10, Lawrence D'Oliveiro wrote: >> >>> In message, Mark >>> Lawrence wrote: >>> >>> On 01/08/2010 08:18, Lawrence D'Oliveiro wrote: >>>> >>>> In message, Mark >>>>> Lawrence wrote: >>>>> >>>>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote: >>>>>> >>>>>> In message, Mark >>>>>>> Lawrence wrote: >>>>>>> >>>>>>> Personally I find double clicking on an msi file rather easier. >>>>>>>> >>>>>>> >>>>>>> Easier than apt-get dist-upgrade? >>>>>>> >>>>>> >>>>>> I'm sorry but I only do English, could you please translate. :) >>>>>> >>>>> >>>>> I run Debian Unstable, which has new goodies coming out on a weekly >>>>> basis. The last time I checked for updates, there were over 500 packages >>>>> I had installed for which updates were available. It only took a command >>>>> like the above to upgrade them all. >>>>> >>>>> How many .msi files would you have to click on to achieve the Windows >>>>> equivalent? >>>>> >>>> >>>> ... I simply couldn't cope with over 500 installed packages. >>>> >>> >>> Precisely my point. Go back to playing with your .msi toys. >>> >>> Oh, and. >>> >> >> Repeating what was obviously deliberately snipped. >> >> "No idea, but your mental capacity is clearly infinitely higher than mine, >> as I simply couldn't cope with over 500 installed packages. What do they >> all do, make your lunch and fetch the beer from the fridge amongst other >> things?" >> >> How does any user or an admin cope with 500 packages? Can Python help >> here, assume an eight hour working day? >> >> c:\Python31\Lib>python >> Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit >> (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> 8*60*60/500 >> 57.6 >> >> So every working day you have 57.6 seconds to use each package. Strangely I >> don't think anyone will get too much done. Am I in cloud cuckoo land or are >> you? >> >> > You seem to be mistaken as to what a "package" is. > > Python : > * python > * python-minimal > * python2.6 > * libbz2 > * libc6 > * libdb4.8 > * libncursesw5 > * libreadline6 > * mime-support > * python2.6-minimal > * libssl0.9.8 > * zlib1g > * debconf > * perl-base > * dpkg > * coreutils > * lzma > * libacl1 > * libattr1 > * libselinux1 > * libgcc1 > * libstdc++6 > * gcc-4.4-base > * libncurses5 > * readline-common > > So these are the packages needed just to run Python in Ubuntu. It doesn't > include the packages required for the kernel, the desktop environment, the > window manager, the terminal, and whatever else you want running. In my > fairly clean Ubuntu VM (I use it almost exclusively for testing), I have > close to 1500 packages installed. > >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > I'll stick with my msi files and/or windows update then, unless I have the luck to get back to VMS. As I said earlier it strikes me that this *nix stuff is simply archaic. Kindest regards. Mark Lawrence. From ethan at stoneleaf.us Mon Aug 2 12:37:51 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 02 Aug 2010 09:37:51 -0700 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <4c552483$0$11091$c3e8da3@news.astraweb.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <8bfd5uF9gqU1@mid.individual.net> <4c52bc2d$0$11091$c3e8da3@news.astraweb.com> <8bhfcaF6ftU1@mid.individual.net> <4c53936d$0$11091$c3e8da3@news.astraweb.com> <4c552483$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C56F45F.2010509@stoneleaf.us> Steven D'Aprano wrote: > On Sat, 31 Jul 2010 13:29:25 +0000, Brian Victor wrote: > >> Steven D'Aprano wrote: >>> On Sat, 31 Jul 2010 14:25:39 +1200, Gregory Ewing wrote: >>> >>>> Steven D'Aprano wrote: >>>> >>>>> A >>>>> / \ >>>>> C B >>>>> \ / >>>>> D >>>>> / \ >>>>> E F >>>>> >>>>> Yes, a super call might jog left from C to B, but only when being >>>>> called from one of the lower classes D-F. That's still an upwards >>>>> call relative to the originator, not sidewards. >>>> But it's not an upward call relative to the class mentioned in the >>>> super() call, which is why I say it's misleading. >>> Which class would that be? >>> >>> I think I'm going to need an example that demonstrates what you mean, >>> because I can't make heads or tails of it. Are you suggesting that a >>> call to super(C, self).method() from within C might call >>> B.method(self)? >> Yes, it would. > [snip example] > > Right, now I see what you mean. I don't have a problem with that > behaviour, it is the correct behaviour, and you are making the call from > D in the first place, so it *must* call B at some point. > > If you initiate the call from C instead: [snip] I think the point is that when D initiates the super() chain, and C calls super, B will then get its turn -- which has to seem arbitrary from C's point of view. ~Ethan~ From doug.garstang at gmail.com Mon Aug 2 12:42:09 2010 From: doug.garstang at gmail.com (Douglas Garstang) Date: Mon, 2 Aug 2010 09:42:09 -0700 Subject: Merging two dictionaries In-Reply-To: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> References: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> Message-ID: On Mon, Aug 2, 2010 at 12:47 AM, Paul Rubin wrote: > Douglas Garstang writes: >> default = {... >> ? ? ? ? ? ? ? ? 'data_sources': { ... >> cluster = {... >> ? ? ? ? ? ? ? ? 'data_source': { ... > > Did you want both of those to say the same thing instead of one > of them being 'data_source' and the other 'data_sources' ? > > If yes, then the following works for me: > > ? ?def merge(cluster, default): > ? ? ? ?# destructively merge default into cluster > ? ? ? ?for k,v in cluster.iteritems(): > ? ? ? ? ? ?if k in default and type(v)==dict: > ? ? ? ? ? ? ? ?assert type(default(k))==dict > ? ? ? ? ? ? ? ?merge(v,default[k]) > ? ? ? ?for k,v in default.iteritems(): > ? ? ? ? ? ?if k not in cluster: > ? ? ? ? ? ? ? ?cluster[k] = v > -- > http://mail.python.org/mailman/listinfo/python-list > Hmmm, using that gives me: Traceback (most recent call last): File "./test4.py", line 48, in ? merge(cluster, default) File "./test4.py", line 42, in merge assert type(default(k))==dict TypeError: 'dict' object is not callable where line 42 is 'assert type(default(k))==dict', and the inputs are: default = { 'cluster': { 'platform': { 'elements': { 'data_sources': { 'elements': { 'db_min_pool_size': 10 }, }, }, }, } } cluster = { 'cluster': { 'name': 'Customer 1', 'description': 'Customer Production', 'environment': 'production', 'platform': { 'elements': { 'data_source': { 'elements': { 'username': 'username', 'password': 'password' }, }, }, }, } } and it's called with: merge(cluster, default) Doug. From __peter__ at web.de Mon Aug 2 12:50:52 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Aug 2010 18:50:52 +0200 Subject: Merging two dictionaries References: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> Message-ID: Douglas Garstang wrote: > On Mon, Aug 2, 2010 at 12:47 AM, Paul Rubin wrote: >> If yes, then the following works for me: >> >> def merge(cluster, default): >> # destructively merge default into cluster >> for k,v in cluster.iteritems(): >> if k in default and type(v)==dict: >> assert type(default(k))==dict >> merge(v,default[k]) >> for k,v in default.iteritems(): >> if k not in cluster: >> cluster[k] = v >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Hmmm, using that gives me: > > Traceback (most recent call last): > File "./test4.py", line 48, in ? > merge(cluster, default) > File "./test4.py", line 42, in merge > assert type(default(k))==dict > TypeError: 'dict' object is not callable > > where line 42 is 'assert type(default(k))==dict', and the inputs are: Not making an attempt to understand the code that you are about to use? default(k) should be default[k] Peter From drobinow at gmail.com Mon Aug 2 12:51:30 2010 From: drobinow at gmail.com (David Robinow) Date: Mon, 2 Aug 2010 12:51:30 -0400 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan wrote: >... > So these are the packages needed just to run Python in Ubuntu. It doesn't > include the packages required for the kernel, the desktop environment, the > window manager, the terminal, and whatever else you want running. In my > fairly clean Ubuntu VM (I use it almost exclusively for testing), I have > close to 1500 packages installed. As an admittedly stupid comparison, I have 1579 DLLs in my \windows\system32 directory. Some number of these have been upgraded by Windows Update. This is XP Service Pack 3. I'm not sure if this means that Windows is better because it has more packages or that it is worse because it's got too many. :) From donn.ingle at gmail.com Mon Aug 2 12:53:39 2010 From: donn.ingle at gmail.com (donn) Date: Mon, 02 Aug 2010 18:53:39 +0200 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> <7xmxt5357h.fsf@ruckus.brouhaha.com> <4C568E92.50907@sequans.com> Message-ID: <4C56F813.2080106@gmail.com> On 02/08/2010 17:35, Mark Lawrence wrote: > aka the colon. :) Ha. This is a case of the colon being the appendix! \d From doug.garstang at gmail.com Mon Aug 2 12:59:07 2010 From: doug.garstang at gmail.com (Douglas Garstang) Date: Mon, 2 Aug 2010 09:59:07 -0700 Subject: Merging two dictionaries In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 1:09 AM, Peter Otten <__peter__ at web.de> wrote: > Douglas Garstang wrote: > >> I have the two dictionaries below. How can I merge them, such that: >> >> 1. The cluster dictionary contains the additional elements from the >> default dictionary. >> 2. Nothing is removed from the cluster dictionary. > > def inplace_merge(default, cluster): > ? ?assert isinstance(default, dict) > ? ?assert isinstance(cluster, dict) > > ? ?d = set(default) > ? ?c = set(cluster) > ? ?default_only = d - c > ? ?both = d & c > ? ?for key in both: > ? ? ? ?dv = default[key] > ? ? ? ?cv = cluster[key] > ? ? ? ?if isinstance(cv, dict): > ? ? ? ? ? ?inplace_merge(dv, cv) > ? ?cluster.update((dk, default[dk]) for dk in default_only) > > should work once you've fixed your example dicts. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > Wooo! I think that did it! From nobody at nowhere.com Mon Aug 2 13:10:06 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 02 Aug 2010 18:10:06 +0100 Subject: run subprocesses in parallel References: Message-ID: On Mon, 02 Aug 2010 14:21:38 +0200, Christian Heimes wrote: > You might want to drop shell=True and use > a list as arguments instead. The two issues (whether "shell" is True/False and whether the command is a list or string) are orthogonal. You should always use a list for the command, unless you are given a string (e.g. by the user) which must be executed verbatim. > The shell=True argument is frowned upon and > should only be used if your really, really need a shell. It's the use of a string (rather than a list) for the command which is particularly frowned upon, as this tends to be error prone if any of the arguments contain characters which are significant to the shell (most commonly spaces, although other characters are also problematic). On Unix, using a list for the command effectively necessitates that shell=False (if you use a list with shell=True, the first element in the list is executed as the command, with any remaining elements used to initialise $1, $2, etc). On Windows, the list is converted to a string in the same way regardless of whether shell is True or False. The shell parameter determines whether the string is passed directly to CreateProcess or whether it has "%COMSPEC% /c " prepended to it. If shell is False, the first element in the list (the program) must refer to a binary executable and include the .exe (etc) extension. If shell is True, the program can be a batch file, Python script, etc, and will be executed according to its extension. From aahz at pythoncraft.com Mon Aug 2 13:29:03 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2010 10:29:03 -0700 Subject: Accumulate function in python References: <94c7c397-d644-4909-8b4b-709a9728901e@y21g2000pro.googlegroups.com> <7xpqyjgvjm.fsf@ruckus.brouhaha.com> Message-ID: In article <7xpqyjgvjm.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >I think Peter Otten's solution involving a generator is the one most in >the current Python spirit. It's cleaner (for my tastes) than the ones >that use things like list.append. Agreed -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From no.email at nospam.invalid Mon Aug 2 13:31:55 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 02 Aug 2010 10:31:55 -0700 Subject: Merging two dictionaries References: <7xy6cpcv7k.fsf@ruckus.brouhaha.com> Message-ID: <7xvd7ssyyc.fsf@ruckus.brouhaha.com> Douglas Garstang writes: > where line 42 is 'assert type(default(k))==dict', and the inputs are: Woops, cut and paste error. default(k) should say default[k]. Or you could remove the assertion altogether. From nagle at animats.com Mon Aug 2 13:34:25 2010 From: nagle at animats.com (John Nagle) Date: Mon, 02 Aug 2010 10:34:25 -0700 Subject: Behavior of re.split on empty strings is unexpected Message-ID: <4c5701a0$0$1638$742ec2ed@news.sonic.net> The regular expression "split" behaves slightly differently than string split: >>> import re >>> kresplit = re.compile(r'[^\w\&]+',re.UNICODE) >>> kresplit2.split(" HELLO THERE ") ['', 'HELLO', 'THERE', ''] >>> kresplit2.split("VERISIGN INC.") ['VERISIGN', 'INC', ''] I'd thought that "split" would never produce an empty string, but it will. The regular string split operation doesn't yield empty strings: >>> " HELLO THERE ".split() ['HELLO', 'THERE'] If I try to get the functionality of string split with re: >>> s2 = " HELLO THERE " >>> kresplit4 = re.compile(r'\W+', re.UNICODE) >>> kresplit4.split(s2) ['', 'HELLO', 'THERE', ''] I still get empty strings. The documentation just describes re.split as "Split string by the occurrences of pattern", which is not too helpful. John Nagle From maj_sawalha at yahoo.com Mon Aug 2 13:46:11 2010 From: maj_sawalha at yahoo.com (Majdi Sawalha) Date: Mon, 2 Aug 2010 10:46:11 -0700 (PDT) Subject: constructing and using large lexicon in a program Message-ID: <119487.45857.qm@web113614.mail.gq1.yahoo.com> Dear List members, I am developing a morphological analyzer that depends on a large lexicon. i construct a Lexicon class that reades a text file?and construct a dictionary of the lexicon entries.? the other class will use the lexicon class to chech if the word is found in the lexicon. the problem that this takes long time as?each time?an object of that class created, then?it needs to call the lexicon many times. then when the lexicon is called it re-construct the lexicon again. is there any way to construct the lexicon one time during the?execution of the program? and then the other modules will?search the already?constructed?lexicon. best regards Majdi ? Faculty of Engineering School of Computing University of Leeds Leeds, LS2 9JT UK http://www.comp.leeds.ac.uk/sawalha -------------- next part -------------- An HTML attachment was scrubbed... URL: From torriem at gmail.com Mon Aug 2 13:52:42 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 02 Aug 2010 11:52:42 -0600 Subject: constructing and using large lexicon in a program In-Reply-To: <119487.45857.qm@web113614.mail.gq1.yahoo.com> References: <119487.45857.qm@web113614.mail.gq1.yahoo.com> Message-ID: <4C5705EA.50705@gmail.com> On 08/02/2010 11:46 AM, Majdi Sawalha wrote: > I am developing a morphological analyzer that depends on a large lexicon. i > construct a Lexicon class that reades a text file and construct a dictionary of > the lexicon entries. > the other class will use the lexicon class to chech if the word is found in the > lexicon. the problem that this takes long time as each time an object of that > class created, then it needs to call the lexicon many times. then when the > lexicon is called it re-construct the lexicon again. is there any way to > construct the lexicon one time during the execution of the program? and then the > other modules will search the already constructed lexicon. Can you not create a module that, upon import, initializes this lexicon as a module attribute? Modules are by definition singleton objects, which is the pattern that you probably need. Any other module could import this module and get the already-created lexicon object. From __peter__ at web.de Mon Aug 2 14:01:21 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Aug 2010 20:01:21 +0200 Subject: Behavior of re.split on empty strings is unexpected References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > The regular string split operation doesn't yield empty strings: > > >>> " HELLO THERE ".split() > ['HELLO', 'THERE'] Note that invocation without separator argument (or None as the separator) is special in that respect: >>> " hello there ".split(" ") ['', 'hello', 'there', ''] Peter From python at mrabarnett.plus.com Mon Aug 2 14:02:47 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 02 Aug 2010 19:02:47 +0100 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <4c5701a0$0$1638$742ec2ed@news.sonic.net> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: <4C570847.6030906@mrabarnett.plus.com> John Nagle wrote: > The regular expression "split" behaves slightly differently than string > split: > > >>> import re > >>> kresplit = re.compile(r'[^\w\&]+',re.UNICODE) > > >>> kresplit2.split(" HELLO THERE ") > ['', 'HELLO', 'THERE', ''] > > >>> kresplit2.split("VERISIGN INC.") > ['VERISIGN', 'INC', ''] > > I'd thought that "split" would never produce an empty string, but > it will. > > The regular string split operation doesn't yield empty strings: > > >>> " HELLO THERE ".split() > ['HELLO', 'THERE'] > Yes it does. >>> " HELLO THERE ".split(" ") ['', '', '', 'HELLO', '', '', '', 'THERE', '', '', ''] > If I try to get the functionality of string split with re: > > >>> s2 = " HELLO THERE " > >>> kresplit4 = re.compile(r'\W+', re.UNICODE) > >>> kresplit4.split(s2) > ['', 'HELLO', 'THERE', ''] > > I still get empty strings. > > The documentation just describes re.split as "Split string by the > occurrences of pattern", which is not too helpful. > It's the plain str.split() which is unusual in that: 1. it splits on sequences of whitespace instead of one per occurrence; 2. it discards leading and trailing sequences of whitespace. Compare: >>> " A B ".split(" ") ['', '', 'A', '', 'B', '', ''] with: >>> " A B ".split() ['A', 'B'] It just happens that the unusual one is the most commonly used one, if you see what I mean! :-) From benjamin.kaplan at case.edu Mon Aug 2 14:14:07 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 2 Aug 2010 11:14:07 -0700 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On Mon, Aug 2, 2010 at 9:51 AM, David Robinow wrote: > On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan > wrote: > >... > > So these are the packages needed just to run Python in Ubuntu. It doesn't > > include the packages required for the kernel, the desktop environment, > the > > window manager, the terminal, and whatever else you want running. In my > > fairly clean Ubuntu VM (I use it almost exclusively for testing), I have > > close to 1500 packages installed. > As an admittedly stupid comparison, I have 1579 DLLs in my > \windows\system32 directory. > Some number of these have been upgraded by Windows Update. This is XP > Service Pack 3. > I'm not sure if this means that Windows is better because it has more > packages or that it is worse because it's got too many. :) > -- > A package is usually more than one file. http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Mon Aug 2 15:33:25 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 14:33:25 -0500 Subject: namespaces, scoping and variables Message-ID: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> I am having a problem getting around this variable namespace thing. Consider these code bits File a.py from Tkinter import * import a1 def doAgain(): x = a1.Net() x.show("Again!") root = Tk() root.title("test") f = Frame(root,bg="Yellow") l = Button(root,text="window 1",command=doAgain) f.grid() l.grid() a = 5 x = a1.Net() x.show("window 2") if __name__ == "__main__": root.mainloop() File a1.py from Tkinter import * class Net: def __init__(self): self.window = Toplevel() def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text="Again") button.bind("", self.Again) button2 = Button(self.window, text="Dismiss") button2.bind("", self.hide) button.grid() button2.grid() def Again(self,event): x = Net() x.show(a) def hide(self,event): self.window.destroy() When I run a.py, it imports a1.py and click on the Again button, I get the error Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ return self.func(*args) File "/Volumes/Development/py/a1.py", line 17, in Again x.show(a) NameError: global name 'a' is not defined I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using global a in a1.py doesn't change anything. since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. Thanks, Chris From nagle at animats.com Mon Aug 2 15:41:13 2010 From: nagle at animats.com (John Nagle) Date: Mon, 02 Aug 2010 12:41:13 -0700 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: <4c571f58$0$1674$742ec2ed@news.sonic.net> On 8/2/2010 11:02 AM, MRAB wrote: > John Nagle wrote: >> The regular expression "split" behaves slightly differently than >> string split: occurrences of pattern", which is not too helpful. >> > It's the plain str.split() which is unusual in that: > > 1. it splits on sequences of whitespace instead of one per occurrence; That can be emulated with the obvious regular expression: re.compile(r'\W+') > 2. it discards leading and trailing sequences of whitespace. But that can't, or at least I can't figure out how to do it. > It just happens that the unusual one is the most commonly used one, if > you see what I mean! :-) The no-argument form of "split" shouldn't be that much of a special case. John Nagle From thomas at jollans.com Mon Aug 2 15:48:13 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 21:48:13 +0200 Subject: namespaces, scoping and variables In-Reply-To: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> Message-ID: <4C5720FD.2080104@jollans.com> On 08/02/2010 09:33 PM, Chris Hare wrote: > I am having a problem getting around this variable namespace thing. > > Consider these code bits > > File a.py > from Tkinter import * > import a1 > > def doAgain(): > x = a1.Net() > x.show("Again!") > > root = Tk() > root.title("test") > f = Frame(root,bg="Yellow") > l = Button(root,text="window 1",command=doAgain) > f.grid() > l.grid() > a = 5 > x = a1.Net() > x.show("window 2") > if __name__ == "__main__": > root.mainloop() > > File a1.py > from Tkinter import * > > class Net: > def __init__(self): > self.window = Toplevel() > def show(self,t): > self.l = Label(self.window,text=t) > self.l.grid() > button = Button(self.window, text="Again") > button.bind("", self.Again) > button2 = Button(self.window, text="Dismiss") > button2.bind("", self.hide) > button.grid() > button2.grid() > def Again(self,event): > x = Net() > x.show(a) > def hide(self,event): > self.window.destroy() > > > When I run a.py, it imports a1.py and click on the Again button, I get the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "/Volumes/Development/py/a1.py", line 17, in Again > x.show(a) > NameError: global name 'a' is not defined > > I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using > > global a > > in a1.py doesn't change anything. > > since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. "global" in Python isn't the same as "global" in C, or in PHP. "Global" is, in essence, a shorter way of saying "within the scope of this module" -- which keeps the "global" nice and clean. You should probably just pass in the object you call "a" when creating the object that uses it, or when calling the function/method when calling it. If you don't want to do that, you can simply import the module where your global data is stored -- beware of "from XYZ import ...", though - that copies the variables, and won't do you much good here. From thomas at jollans.com Mon Aug 2 15:52:09 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 21:52:09 +0200 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <4c571f58$0$1674$742ec2ed@news.sonic.net> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <4c571f58$0$1674$742ec2ed@news.sonic.net> Message-ID: <4C5721E9.3040307@jollans.com> On 08/02/2010 09:41 PM, John Nagle wrote: > On 8/2/2010 11:02 AM, MRAB wrote: >> John Nagle wrote: >>> The regular expression "split" behaves slightly differently than >>> string split: > occurrences of pattern", which is not too helpful. >>> >> It's the plain str.split() which is unusual in that: >> >> 1. it splits on sequences of whitespace instead of one per occurrence; > > That can be emulated with the obvious regular expression: > > re.compile(r'\W+') > >> 2. it discards leading and trailing sequences of whitespace. > > But that can't, or at least I can't figure out how to do it. [ s in rexp.split(long_s) if s ] > >> It just happens that the unusual one is the most commonly used one, if >> you see what I mean! :-) > > The no-argument form of "split" shouldn't be that much of a special > case. > > John Nagle > From davea at ieee.org Mon Aug 2 15:54:44 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 02 Aug 2010 15:54:44 -0400 Subject: namespaces, scoping and variables In-Reply-To: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> Message-ID: <4C572284.6000906@ieee.org> Chris Hare wrote: > I am having a problem getting around this variable namespace thing. > > Consider these code bits > > File a.py > from Tkinter import * > import a1 > > def doAgain(): > x =1.Net() > x.show("Again!") > > root =k() > root.title("test") > f =rame(root,bg="Yellow") > l =utton(root,text="window 1",command=doAgain) > f.grid() > l.grid() > a = > x =1.Net() > x.show("window 2") > if __name__ ="__main__": > root.mainloop() > > File a1.py > from Tkinter import * > > class Net: > def __init__(self): > self.window =oplevel() > def show(self,t): > self.l =abel(self.window,text=t) > self.l.grid() > button =utton(self.window, text="Again") > button.bind("", self.Again) > button2 =utton(self.window, text="Dismiss") > button2.bind("", self.hide) > button.grid() > button2.grid() > def Again(self,event): > x =et() > x.show(a) > def hide(self,event): > self.window.destroy() > > > When I run a.py, it imports a1.py and click on the Again button, I get the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "/Volumes/Development/py/a1.py", line 17, in Again > x.show(a) > NameError: global name 'a' is not defined > > I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using > > global a > > in a1.py doesn't change anything. > > since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. > > Thanks, > Chris > > > First rule is never have circular referencing between modules. In other words, since a.py imports a1.py, a.py can refer to things in a1.py, but never the other way around. Any time you need to look backwards, find another means. One approach is to create another module c.py as a container to hold those things that both a and a1 need. That way they both import c, and there's no problem. Another approach is to pass the global from a.py into a1.py, and use it that way. And since you only have these two modules, you could just define it in a1.py, and reference it from a.py as a1.a I would point out that using the same name for a module and a global variable is bad practice. it certainly makes it hard to describe in this case. HTH, DaveA From mithrandiragainwiki at mailinator.com Mon Aug 2 15:58:34 2010 From: mithrandiragainwiki at mailinator.com (Mithrandir) Date: Mon, 02 Aug 2010 12:58:34 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 08/01/2010 07:34 PM, Albert Hopkins wrote: > On Mon, 2010-08-02 at 01:08 +0200, candide wrote: >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. >> >> Has it ever been planned to rewrite in C++ the historical implementation >> (of course in an object oriented design) ? > > Disclaimer: I am neither a C nor C++ programmer. In fact I can barely > even program in Python ;-) > > I would propose that in fact most programming languages are implemented > in C. Sun's (Oracle's) Java compiler and runtime are written in ANSI C. > The core of the Gnu Compiler Collection (which includes C++ and > Objective-C compilers) is written in C. The official Ruby is > implemented in C. The Squeak Smalltalk implementation uses C instead of > C++. I can't even think of a programming language that is implemented > in C++ (maybe C++ is). > > C seems to be a good, portable language for writing interpreters and > compilers. > > But I wonder if someone has/has tried to write a programming language in > C++ and what were their experiences. > (Sorry if this is a double post, but apparently my last one didn't go through.) I know that LOLCode has a .NET implementation (1), although it's "very much alpha." And someone was apparently working on a C++ only implementation of LOLCode (2), although that was 3 years ago. LOLCode itself is very much alpha anyway and development seems to be very slow (or dead.) Python has a way of extending it's modules with C or C++ (3). 1: http://lolcode.com/implementations/lolcode.net 2: http://forum.lolcode.com/viewtopic.php?id=14 3: http://docs.python.org/release/2.5.2/ext/intro.html - -- People should read more. https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain "All that is gold does not glitter, not all those who wander are lost; the old that is strong does not wither, deep roots are not reached by the frost. - From the ashes a fire shall be woken, a light from the shadows shall spring; renewed shall be blade that was broken, the crownless again shall be king." -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJMVyNqAAoJEKo37V1xH7gTeOUH/2/KYc4busZbATSB09ZUgW+v BmydxDTZaPQd0B56JWSeUiz0/kZrufdDrVc3XUTNNF2oa8ExW51IgsaZOxn2UJGv ydplycT1axs5hrzDG72v2Oo7/poPDxSsvpF58dBsb0XSI25I+orHKrTQpwvKz9cf x6nzahUoygTbaVqZUyxCW2Tc7Rv4T2gpskssD8sIYqaRNofNnPbf3h3NA+q4LMkR +F2UF3r1RE1jwJhs6RNAvUJBdLrHkA3isRsjQE38l6AioLdeTs2yrRtc+6xUkAig RxR11qLZl5OOer/Jrmg1My0+ZTYGnIcAfChxPh1YnHuYbp+H7doqLjlKIkoXZms= =F9Ou -----END PGP SIGNATURE----- From python at mrabarnett.plus.com Mon Aug 2 16:03:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 02 Aug 2010 21:03:18 +0100 Subject: namespaces, scoping and variables In-Reply-To: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> Message-ID: <4C572486.1030308@mrabarnett.plus.com> Chris Hare wrote: > I am having a problem getting around this variable namespace thing. > > Consider these code bits > > File a.py > from Tkinter import * > import a1 > > def doAgain(): > x = a1.Net() > x.show("Again!") > > root = Tk() > root.title("test") > f = Frame(root,bg="Yellow") > l = Button(root,text="window 1",command=doAgain) > f.grid() > l.grid() > a = 5 > x = a1.Net() > x.show("window 2") > if __name__ == "__main__": > root.mainloop() > > File a1.py > from Tkinter import * > > class Net: > def __init__(self): > self.window = Toplevel() > def show(self,t): > self.l = Label(self.window,text=t) > self.l.grid() > button = Button(self.window, text="Again") > button.bind("", self.Again) > button2 = Button(self.window, text="Dismiss") > button2.bind("", self.hide) > button.grid() > button2.grid() > def Again(self,event): > x = Net() > x.show(a) > def hide(self,event): > self.window.destroy() > > > When I run a.py, it imports a1.py and click on the Again button, I get the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "/Volumes/Development/py/a1.py", line 17, in Again > x.show(a) > NameError: global name 'a' is not defined > > I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using > > global a > > in a1.py doesn't change anything. > > since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. > Why in a database? If you need the modules to share it then you could put it in a shared module and refer to it there: File a.py --------- import my_globals ... my_globals.a = 5 File a1.py ---------- import my_globals ... x.show(my_globals.a) From ethan at stoneleaf.us Mon Aug 2 16:04:01 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 02 Aug 2010 13:04:01 -0700 Subject: namespaces, scoping and variables In-Reply-To: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> Message-ID: <4C5724B1.8060403@stoneleaf.us> Chris Hare wrote: > I am having a problem getting around this variable namespace thing. > > Consider these code bits > > File a.py > from Tkinter import * > import a1 > > def doAgain(): > x = a1.Net() > x.show("Again!") > > root = Tk() > root.title("test") > f = Frame(root,bg="Yellow") > l = Button(root,text="window 1",command=doAgain) > f.grid() > l.grid() > a = 5 > x = a1.Net() > x.show("window 2") > if __name__ == "__main__": > root.mainloop() > > File a1.py > from Tkinter import * > > class Net: > def __init__(self): > self.window = Toplevel() > def show(self,t): > self.l = Label(self.window,text=t) > self.l.grid() > button = Button(self.window, text="Again") > button.bind("", self.Again) > button2 = Button(self.window, text="Dismiss") > button2.bind("", self.hide) > button.grid() > button2.grid() > def Again(self,event): > x = Net() > x.show(a) > def hide(self,event): > self.window.destroy() > > > When I run a.py, it imports a1.py and click on the Again button, I get the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "/Volumes/Development/py/a1.py", line 17, in Again > x.show(a) > NameError: global name 'a' is not defined > > I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using > > global a > > in a1.py doesn't change anything. The global keyword does not make a variable global. It tells the interpreter that the variable in question can be find in the module scope, not the function/method scope. In other words, the variable is global to the module, but not to the whole program. What you'll need to do is pass a into Net when you instanciate it, like so (untested): def doAgain(): x = a1.Net(a) x.show("Again!") and in Net: class Net: def __init__(self, some_number): self.some_number = some_number self.window = Toplevel() . . . def Again(self,event): x = Net(self.some_number) x.show() Keep in mind, though, that if you change a in a.py after you've instanciated Net, your Net instance will not see the change. For the change to show up, a would need to be mutable, and you would have to mutate it. The other option is to change the Net instance's some_number directly (i.e. x.some_number = 9). Hope this helps. ~Ethan~ From chare at labr.net Mon Aug 2 16:12:03 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 15:12:03 -0500 Subject: namespaces, scoping and variables In-Reply-To: <4C572486.1030308@mrabarnett.plus.com> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> <4C572486.1030308@mrabarnett.plus.com> Message-ID: Thanks to everyone for answering my question. I think its clear now. I'll just go the "stuff 'em in a module and import that" route. Chris On Aug 2, 2010, at 3:03 PM, MRAB wrote: > Chris Hare wrote: >> I am having a problem getting around this variable namespace thing. >> Consider these code bits >> File a.py >> from Tkinter import * >> import a1 >> def doAgain(): >> x = a1.Net() >> x.show("Again!") >> root = Tk() >> root.title("test") >> f = Frame(root,bg="Yellow") >> l = Button(root,text="window 1",command=doAgain) >> f.grid() >> l.grid() >> a = 5 >> x = a1.Net() >> x.show("window 2") >> if __name__ == "__main__": >> root.mainloop() >> File a1.py >> from Tkinter import * >> class Net: >> def __init__(self): >> self.window = Toplevel() >> def show(self,t): >> self.l = Label(self.window,text=t) >> self.l.grid() >> button = Button(self.window, text="Again") >> button.bind("", self.Again) >> button2 = Button(self.window, text="Dismiss") >> button2.bind("", self.hide) >> button.grid() >> button2.grid() >> def Again(self,event): >> x = Net() >> x.show(a) >> def hide(self,event): >> self.window.destroy() >> When I run a.py, it imports a1.py and click on the Again button, I get the error >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__ >> return self.func(*args) >> File "/Volumes/Development/py/a1.py", line 17, in Again >> x.show(a) >> NameError: global name 'a' is not defined >> I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using >> global a >> in a1.py doesn't change anything. >> since I am using SQLite for the disk database, I was thinking I could keep all the "global" variables in an in memory database and just access them when I need to, but other ideas are welcome. > Why in a database? If you need the modules to share it then you could > put it in a shared module and refer to it there: > > File a.py > --------- > import my_globals > ... > my_globals.a = 5 > > > File a1.py > ---------- > import my_globals > ... > x.show(my_globals.a) > -- > http://mail.python.org/mailman/listinfo/python-list From nikos.the.gr33k at gmail.com Mon Aug 2 16:13:21 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 2 Aug 2010 13:13:21 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: <40feea21-78ac-4bcc-903f-046a411c677e@l25g2000prn.googlegroups.com> Hello, any ideas?! From chare at labr.net Mon Aug 2 16:17:36 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 15:17:36 -0500 Subject: how best to clear objects from a frame In-Reply-To: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> References: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> Message-ID: On Aug 1, 2010, at 10:13 PM, rantingrick wrote: > On Aug 1, 7:12 pm, Chris Hare wrote: >> Here is the situation: >> >> I have a window with a bunch of widgets in it. I want to clear the objects in a given frame and recreate them to update them. > > You need to check out the "w.update" and "w.update_idletasks" methods > available on all Tkinter widgets. Just FYI: to remove a widget from > view without destroying it use "w.pack_forget" or "w.grid_forget". > However if you are simply trying to refresh a widget use one of the > update methods. > -- > http://mail.python.org/mailman/listinfo/python-list I will have a look at those. Consider a frame with a label and a button. How do I address the label to change it from another function in the class? From rantingrick at gmail.com Mon Aug 2 16:43:33 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 2 Aug 2010 13:43:33 -0700 (PDT) Subject: namespaces, scoping and variables References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> <4C572486.1030308@mrabarnett.plus.com> Message-ID: <48558d95-aaaa-4a6e-9ffb-68d4f2429c62@w15g2000pro.googlegroups.com> On Aug 2, 3:12?pm, Chris Hare wrote: > Thanks to everyone for answering my question. ?I think its clear now. ?I'll just go the "stuff 'em in a module and import that" route. Chris, first of all i want you to know that this message is not meant to offend but it may offend you -- hopefully your a rational person and can deal with criticism. This code is horrible. What are you trying to do exactly? Is this purely academic or are you actually using this code for a real purpose? The "Net" class looks like a dialog. Are you wishing to create a dialog? If so, then you would be better off subclassing tkSimpleDialog.Dialog instead of rolling your own. Please explain what you are trying to do from a users perspective so we can properly guide you. Also you should use 4 space indention and never use tabs. This is the accepted way. Although Python does allow freedom i would suggest that coding in a uniformly accepted manner is more productive for the entire community. Google "Python Style Guide" for more info. Thanks From thomas at jollans.com Mon Aug 2 16:48:18 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 22:48:18 +0200 Subject: Trying to set a cookie within a python script In-Reply-To: <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <1e287fba-b5e0-4f8e-a6a9-e992553cfc28@p11g2000prf.googlegroups.com> Message-ID: <4C572F12.2060003@jollans.com> On 08/02/2010 04:20 AM, ????? wrote: > Also my greek print appear in funny encoding although i do use # -*- > coding: utf-8 -*- That's because you never told the web browser which encoding you're using. Content-Type: text/html; charset=UTF-8 From thomas at jollans.com Mon Aug 2 16:57:15 2010 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 02 Aug 2010 22:57:15 +0200 Subject: Trying to set a cookie within a python script In-Reply-To: References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4C57312B.6070606@jollans.com> On 08/02/2010 10:13 PM, ????? wrote: > Hello, any ideas?! That's no way to treat a friendly volunteer mailing list like this one! On 08/02/2010 02:32 PM, ????? wrote: > As for the encoding Notepad++, which is what i use for an editor say > its UTF-8 without BOM. > > Isn't this what i'm supposed to use? > > My Python scripts only containes english and greek letters, so i > though usign UTF-8 is the way to go. No?! Please if you explain to me > in greater detail! As I said, you have to tell the browser what you're up to. Also, I just checked the link (shame on me), and you're not using UTF-8 at all. You're using some weird Windows-xyz or ISO-8859-xyz Greek codepage from the previous millennium. (which obviously my browser didn't know, it thought you were using ISO-8859-1, because that's what my browser does, which you weren't) So: tripple-check that * your file is * Python knows that * the web browser knows that From news1234 at free.fr Mon Aug 2 17:18:19 2010 From: news1234 at free.fr (News123) Date: Mon, 02 Aug 2010 23:18:19 +0200 Subject: let optionparse.Optionparser ignore unknown command line switches. In-Reply-To: <8948edfa-2beb-4295-808e-11755f3d9128@p22g2000pre.googlegroups.com> References: <4c5555c5$0$19337$426a74cc@news.free.fr> <4c555a04$0$18011$426a74cc@news.free.fr> <4c559628$0$28678$426a74cc@news.free.fr> <8948edfa-2beb-4295-808e-11755f3d9128@p22g2000pre.googlegroups.com> Message-ID: <4c57361b$0$23959$426a34cc@news.free.fr> On 08/01/2010 07:53 PM, Jon Clements wrote: > On 1 Aug, 16:43, News123 wrote: >> On 08/01/2010 05:34 PM, Steven W. Orr wrote: >> >> >> >>> On 08/01/10 07:27, quoth News123: >>>> On 08/01/2010 01:08 PM, News123 wrote: >>>>> I wondered, whether there's a simple/standard way to let >>>>> the Optionparser just ignore unknown command line switches. >> >>>> In order to illustrate, what I try to achieve: >> >>>> import optparse >>>> parser = optparse.OptionParser() >>>> parser.add_option("-t","--test",dest="test",action="store_true") >>>> argv=["tst.py","-t","--ignoreme_and_dont_fail"] >>>> try: >>>> (options,args)=parser.parse_args(argv) >>>> except: >>>> # due to --ignoreme_and_dont_fail >>>> # I will end up here and neither options nor >>>> # args will be populated >>>> print "parser error:" >>>> # However I would love to be able to see here >>>> # that options.test is true despite the >>>> # error, that occurred afterwards >>>> print "T",options.test >> >> in my case one imported module should parse some of the options (but >> only the one it understands) already during import. >> the main program will have to parse the same options again. > > Take it up a level. > > Dedicate a module (called app_configuration) or something to do the > option parsing -- everything the application can support is listed > there... It's a bad idea to ignore invalid options... Well the main application would abort the program. I'ts jsut one module which would like to pre-fetch some options. > > When that's imported it runs the parsing for sys.argv whatever... and > you guarantee a variable called app_settings (or whatever) is present > in that module. > > Any module that needs the settings, just imports app_configuration and > tries to take what it understands... > > Would that work for you? > It's not really what I'm looking for, though it might be what I'll end up doing. currently I have several apps all importing one module, but all parsing different options. There's one common option and I'd like to have one module behaving differently depending on this option. My idea was to just change this one module and leave everything else unmodified. Another not so nice solution, which could be a very quick and dirty hack (to be removed lateron) would be to just add to this one module if "--myoption" in sys.argv: dosomething but I'd have prefered a real Optionparser (ignoring unknown options) I could even make sure, that the unknown options follow the common options. From nagle at animats.com Mon Aug 2 17:22:25 2010 From: nagle at animats.com (John Nagle) Date: Mon, 02 Aug 2010 14:22:25 -0700 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <4c571f58$0$1674$742ec2ed@news.sonic.net> Message-ID: <4c57370f$0$1676$742ec2ed@news.sonic.net> On 8/2/2010 12:52 PM, Thomas Jollans wrote: > On 08/02/2010 09:41 PM, John Nagle wrote: >> On 8/2/2010 11:02 AM, MRAB wrote: >>> John Nagle wrote: >>>> The regular expression "split" behaves slightly differently than >>>> string split: >> occurrences of pattern", which is not too helpful. >>>> >>> It's the plain str.split() which is unusual in that: >>> >>> 1. it splits on sequences of whitespace instead of one per occurrence; >> >> That can be emulated with the obvious regular expression: >> >> re.compile(r'\W+') >> >>> 2. it discards leading and trailing sequences of whitespace. >> >> But that can't, or at least I can't figure out how to do it. > > [ s in rexp.split(long_s) if s ] Of course I can discard the blank strings afterward, but is there some way to do it in the "split" operation? If not, then the default case for "split()" is too non-standard. (Also, "if s" won't work; if s != '' might) John Nagle From zdenekmaxa at yahoo.co.uk Mon Aug 2 17:27:37 2010 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Mon, 02 Aug 2010 23:27:37 +0200 Subject: checking that process binds a port, fuser functionality Message-ID: <4C573849.7040804@yahoo.co.uk> Hello, I need to start a process (using subprocess.Popen()) and wait until the new process either fails or successfully binds a specified port. The fuser command seems to be indented exactly for this purpose. Could anyone please provided a hint to a handy Python library to do this or would the advice be to parse fuser command output? This needs to happen on Linux and Python 2.4. Thanks a lot in advance. Zdenek From breamoreboy at yahoo.co.uk Mon Aug 2 17:28:49 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 22:28:49 +0100 Subject: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all? In-Reply-To: <4C56F813.2080106@gmail.com> References: <89d63586-735b-4a39-910f-ef5b23ee9397@s17g2000prh.googlegroups.com> <54124b97-a1cb-49e9-9958-fd015bd62079@5g2000yqz.googlegroups.com> <8b1jgbFgbdU1@mid.individual.net> <4c4bb40b$0$28669$c3e8da3@news.astraweb.com> <4c517a58$0$11091$c3e8da3@news.astraweb.com> <4c520f45$0$11091$c3e8da3@news.astraweb.com> <8bfd8tF9gqU2@mid.individual.net> <4c52bfc4$0$11091$c3e8da3@news.astraweb.com> <4c5393bb$0$11091$c3e8da3@news.astraweb.com> <7xmxt5357h.fsf@ruckus.brouhaha.com> <4C568E92.50907@sequans.co m> <4C56F813.2080106@gmail.com> Message-ID: On 02/08/2010 17:53, donn wrote: > On 02/08/2010 17:35, Mark Lawrence wrote: >> aka the colon. :) > Ha. This is a case of the colon being the appendix! > > \d Is there a better newsgroup in the world than c.l.py? No! Kindest regards. Mark Lawrence. From benjamin.kaplan at case.edu Mon Aug 2 17:35:41 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 2 Aug 2010 14:35:41 -0700 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <4c57370f$0$1676$742ec2ed@news.sonic.net> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <4c571f58$0$1674$742ec2ed@news.sonic.net> <4c57370f$0$1676$742ec2ed@news.sonic.net> Message-ID: On Mon, Aug 2, 2010 at 2:22 PM, John Nagle wrote: > On 8/2/2010 12:52 PM, Thomas Jollans wrote: > >> On 08/02/2010 09:41 PM, John Nagle wrote: >> >>> On 8/2/2010 11:02 AM, MRAB wrote: >>> >>>> John Nagle wrote: >>>> >>>>> The regular expression "split" behaves slightly differently than >>>>> string split: >>>>> >>>> occurrences of pattern", which is not too helpful. >>> >>>> >>>>> It's the plain str.split() which is unusual in that: >>>> >>>> 1. it splits on sequences of whitespace instead of one per occurrence; >>>> >>> >>> That can be emulated with the obvious regular expression: >>> >>> re.compile(r'\W+') >>> >>> 2. it discards leading and trailing sequences of whitespace. >>>> >>> >>> But that can't, or at least I can't figure out how to do it. >>> >> >> [ s in rexp.split(long_s) if s ] >> > > Of course I can discard the blank strings afterward, but > is there some way to do it in the "split" operation? If > not, then the default case for "split()" is too non-standard. > > (Also, "if s" won't work; if s != '' might) > > John Nagle > -- > What makes it non-standard? The fact that it's not a 1-line regex? The default case for str.split is designed to handle the most common case: you want to break a string into words, where a word is defined as a sequence of non-whitespace characters. > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Aug 2 17:35:52 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 22:35:52 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On 02/08/2010 19:14, Benjamin Kaplan wrote: > On Mon, Aug 2, 2010 at 9:51 AM, David Robinow wrote: > >> On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan >> wrote: >>> ... >>> So these are the packages needed just to run Python in Ubuntu. It doesn't >>> include the packages required for the kernel, the desktop environment, >> the >>> window manager, the terminal, and whatever else you want running. In my >>> fairly clean Ubuntu VM (I use it almost exclusively for testing), I have >>> close to 1500 packages installed. >> As an admittedly stupid comparison, I have 1579 DLLs in my >> \windows\system32 directory. >> Some number of these have been upgraded by Windows Update. This is XP >> Service Pack 3. >> I'm not sure if this means that Windows is better because it has more >> packages or that it is worse because it's got too many. :) >> -- >> > > A package is usually more than one file. > http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist > > >> http://mail.python.org/mailman/listinfo/python-list >> > This is all very well, but what is the unladen airspeed velocity of a swallow in flight? Answers on a postcard please, given that I expect both direction and speed! Kindest regards. Mark Lawrence. From breamoreboy at yahoo.co.uk Mon Aug 2 17:42:32 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 22:42:32 +0100 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 02/08/2010 00:08, candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? > > C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > suitable to implement an OOL with another one. > > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? I can't understand why any serious programmer mentions C++. As soon as I read it, I have to rush either to the kitchen to find a bowl to throw up in, or head for the toilet so I can talk to the great white telephone. Kindest regards. Mark Lawrence. From breamoreboy at yahoo.co.uk Mon Aug 2 17:52:27 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Aug 2010 22:52:27 +0100 Subject: how best to clear objects from a frame In-Reply-To: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> References: <6a776679-ace6-43d4-aff7-bf2d93ce0075@z34g2000pro.googlegroups.com> Message-ID: On 02/08/2010 04:13, rantingrick wrote: > On Aug 1, 7:12 pm, Chris Hare wrote: >> Here is the situation: >> >> I have a window with a bunch of widgets in it. I want to clear the objects in a given frame and recreate them to update them. > > You need to check out the "w.update" and "w.update_idletasks" methods > available on all Tkinter widgets. Just FYI: to remove a widget from > view without destroying it use "w.pack_forget" or "w.grid_forget". > However if you are simply trying to refresh a widget use one of the > update methods. I don't understand the technical content of this thread, but I'm very pleased to see rantingrick being positive, well done!!! :) I know that we've crossed swords in the past but believe that bygones should be bygones. Can we call it quits and help to take Python forward? Kindest regards. Mark Lawrence. From peter.milliken at gmail.com Mon Aug 2 17:56:22 2010 From: peter.milliken at gmail.com (Peter) Date: Mon, 2 Aug 2010 14:56:22 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On Aug 3, 7:42?am, Mark Lawrence wrote: > On 02/08/2010 00:08, candide wrote: > > I can't understand why any serious programmer mentions C++. As soon as I > read it, I have to rush either to the kitchen to find a bowl to throw up > in, or head for the toilet so I can talk to the great white telephone. > > Kindest regards. > > Mark Lawrence. With you there Mark - IMO C++ is an abortion that should never have seen the light of day. The idea of experimenting with creating an OO language by extending C wasn't such a bad idea for a "play thing" (by Stroustrop) but the fact that it somehow escaped from the Lab and people picked it up and ran with it on a commercial basis is just plain wrong! Personally I liken it to one of those genetically engineered diseases they play around with in biological warfare labs - and unfortunately this one escaped! It has probably set the computing industry back untold years in terms of advancement... Unfortunately I am forced to use it in my day to day life, but at the end of every day I go home and use a purgative to get it out of my system. But there are many deluded youngsters out there who just don't seem to know any better, but then the signs of the breakdown of society surround us on a daily basis and I guess C++ is just another signpost on the way... Peter From torriem at gmail.com Mon Aug 2 18:06:00 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 02 Aug 2010 16:06:00 -0600 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4C574148.3090606@gmail.com> On 08/02/2010 03:42 PM, Mark Lawrence wrote: > I can't understand why any serious programmer mentions C++. As soon as I > read it, I have to rush either to the kitchen to find a bowl to throw up > in, or head for the toilet so I can talk to the great white telephone. Sometimes, C++ is just the right tool for the job, despite all its warts. For example, programming GTK apps with GTKmm in C++ is way more pleasant than using C (but nowhere as pleasant as Python). C++'s object semantics (guaranteed destruction, scoping, etc) can sometimes work very well when you need the speed of a compiled language, but don't want to be quite as low-level as C. In this case, C++ is certainly not a better tool for the job than C. But plenty of serious programmers know how to leverage C++ and do so quite successfully. Just because C++ makes you ill in no way proves that C++ is unfit for certain purposes. From thomas at jollans.com Mon Aug 2 18:07:58 2010 From: thomas at jollans.com (Thomas Jollans) Date: Tue, 03 Aug 2010 00:07:58 +0200 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <4c57370f$0$1676$742ec2ed@news.sonic.net> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <4c571f58$0$1674$742ec2ed@news.sonic.net> <4c57370f$0$1676$742ec2ed@news.sonic.net> Message-ID: <4C5741BE.4000503@jollans.com> On 08/02/2010 11:22 PM, John Nagle wrote: >> [ s in rexp.split(long_s) if s ] > > Of course I can discard the blank strings afterward, but > is there some way to do it in the "split" operation? If > not, then the default case for "split()" is too non-standard. > > (Also, "if s" won't work; if s != '' might) Of course it will work. Empty sequences are considered false in Python. Python 3.1.2 (release31-maint, Jul 8 2010, 09:18:08) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> sprexp = re.compile(r'\s+') >>> [s for s in sprexp.split(' spaces every where ! ') if s] ['spaces', 'every', 'where', '!'] >>> list(filter(bool, sprexp.split(' more spaces \r\n\t\t '))) ['more', 'spaces'] >>> (of course, the list comprehension I posted earlier was missing a couple of words, which was very careless of me) From troabarton69 at hotmail.com Mon Aug 2 18:07:59 2010 From: troabarton69 at hotmail.com (ben owen) Date: Mon, 2 Aug 2010 17:07:59 -0500 Subject: Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning Message-ID: Hi everyone, I'm new to this and was needing help with trying to learn/work with Python 2.7 on my computer. I'm running Windows 7 and trying to learn python programming from an older book from 1999 by Mark Lutz and David Ascher my boss gave me, and for some reason none of my script/modules for the exercises are working on my comp. Mostly they give either a syntax error on the python command line or something about the file/module not being found on the windows command line. Also, does anyone where i can find/get something similar to the book for my own? Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Mon Aug 2 18:18:30 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 15:18:30 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> On 2 Aug, 01:08, candide wrote: > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? OO programming is possible in C. Just take a look at GNOME and GTK. Perl is written in C++. That is not enough to make me want to use it ;) To be honest, C++ can be a great tool. But very few know how to use it correctly. C++ textbooks are also written by people who don't understand the language, and teach bad habits. The typical examples revealing incompetence are use of new[] instead of std::vector, and dynamic resourse allocation outside contructors. C++ compilers used to be bloatware generators; C++ compilers of 2010 are not comparable to those of 1990. C++ is also a PITA for portability. It is not sufficient for Python to only build with Microsoft Visual Studio. From no.email at nospam.invalid Mon Aug 2 18:27:25 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 02 Aug 2010 15:27:25 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <7x62zslkfm.fsf@ruckus.brouhaha.com> Michael Torrie writes: > Sometimes, C++ is just the right tool for the job, despite all its > warts.... C++'s object semantics (guaranteed destruction, scoping, > etc) can sometimes work very well when you need the speed of a > compiled language, but don't want to be quite as low-level as C. > > In this case, C++ is certainly not a better tool for the job than C. The stuff C++ adds to C is a mix of good and bad, and it's reasonably possible to use just the good stuff and ignore the bad. At that point you've got a pure improvement over C, although a lot of C's shortcomings can't be papered over and still remain. Certain folks in the functional-programming community consider OO to be a 1980's or 1990's approach that didn't work out, and that what it was really trying to supply was polymorphism. C++ programs these days apparently tend to use template-based generics rather than objects and inheritance for that purpose. I've never programmed in Ada but I'm intrigued by these articles: http://adahome.com/Ammo/cpp2ada.html http://www.adaic.org/whyada/ada-vs-c/cada_art.html I have the impression that Ada has an undeservedly bad rap because of its early implementations and its origins in military bureaucracy. I'd certainly consider it as an alternative to C or C++ if I had to write a big program in a traditional procedural language. From sturlamolden at yahoo.no Mon Aug 2 18:28:56 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 15:28:56 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <1280716447.927705.20.camel@paska> Message-ID: On 2 Aug, 05:04, Tomasz Rola wrote: > And one should not forget about performance. C++ was for a long time > behind C, and even now some parts (like iostreams) should be avoided in > fast code. For fast I/O one must use platform specific APIs, such as Windows' i/o completion ports and memory mapping. iostreams in C++ and stdio in C are ok for less demanding tasks. From prologic at shortcircuit.net.au Mon Aug 2 18:32:08 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 08:32:08 +1000 Subject: Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 8:07 AM, ben owen wrote: > Hi everyone, I'm new to this and was needing help with trying to learn/work > with Python 2.7 on my computer. I'm running Windows 7 and trying to learn > python programming from an older book from 1999 by Mark Lutz and David > Ascher my boss gave me, and for some reason none of my script/modules for > the exercises are working on my comp. Mostly they give either a syntax error > on the python command line or something about the file/module not being > found on the windows command line. Also, does anyone where i can find/get > something similar to the book for my own? Start with the mighty fine Python tutorial on the Python Documentation website (1) cheers James 1. http://docs.python.org/ -- -- James Mills -- -- "Problems are solved by method" From sturlamolden at yahoo.no Mon Aug 2 18:54:52 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 15:54:52 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> On 3 Aug, 00:27, Paul Rubin wrote: > Certain folks in the functional-programming community consider OO to be > a 1980's or 1990's approach that didn't work out, and that what it was > really trying to supply was polymorphism. ?C++ programs these days > apparently tend to use template-based generics rather than objects and > inheritance for that purpose. ? It avoids virtual function calls at the expense of unreable code and errors that are nearly impossible to trace. It seems many thinks this is a good idea because Microsoft did this with ATL and WTL. There are also those who thinks template metaprogramming is a good idea. But who uses a C++ compiler to dumb to unroll a for loop? In my experience, trying to outsmart a modern compiler is almost always a bad idea. > I have the impression that Ada has an undeservedly bad rap because of > its early implementations and its origins in military bureaucracy. ? It is annyingly verbose, reminds me of Pascal (I hate the looks of it), and is rumoured to produce slow bloatware. And don't forget Ariane 5 ;) > I'd > certainly consider it as an alternative to C or C++ if I had to write a > big program in a traditional procedural language. I still prefer Fortran 95 :-) From aahz at pythoncraft.com Mon Aug 2 19:03:10 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2010 16:03:10 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Peter wrote: >On Aug 3, 7:42=A0am, Mark Lawrence wrote: >> On 02/08/2010 00:08, candide wrote: >> >> I can't understand why any serious programmer mentions C++. As soon as I >> read it, I have to rush either to the kitchen to find a bowl to throw up >> in, or head for the toilet so I can talk to the great white telephone. > >With you there Mark - IMO C++ is an abortion that should never have >seen the light of day. The idea of experimenting with creating an OO >language by extending C wasn't such a bad idea for a "play thing" (by >Stroustrop) but the fact that it somehow escaped from the Lab and >people picked it up and ran with it on a commercial basis is just >plain wrong! http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From martin at address-in-sig.invalid Mon Aug 2 19:14:53 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Mon, 2 Aug 2010 23:14:53 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: On Mon, 02 Aug 2010 15:54:52 -0700, sturlamolden wrote: > On 3 Aug, 00:27, Paul Rubin wrote: > >> Certain folks in the functional-programming community consider OO to be >> a 1980's or 1990's approach that didn't work out, and that what it was >> really trying to supply was polymorphism. ?C++ programs these days >> apparently tend to use template-based generics rather than objects and >> inheritance for that purpose. > > It avoids virtual function calls at the expense of unreable code and > errors that are nearly impossible to trace. It seems many thinks this is > a good idea because Microsoft did this with ATL and WTL. There are also > those who thinks template metaprogramming is a good idea. But who uses a > C++ compiler to dumb to unroll a for loop? In my experience, trying to > outsmart a modern compiler is almost always a bad idea. > >> I have the impression that Ada has an undeservedly bad rap because of >> its early implementations and its origins in military bureaucracy. > > It is annyingly verbose, reminds me of Pascal (I hate the looks of it), > and is rumoured to produce slow bloatware. > And don't forget Ariane 5 ;) > This had nothing to do with Ada per se and everything to do with shortcuts: - re-use of an Ariane 4 component without changing its parameters to match the Ariane 5 flight profile - not removing Ariane 4-only code intended to handle launch holds and not used at all in Ariane 5 - a programming fault that allowed an exception code to be sent to another component as if it was valid data. Inadequate testing allowed all these to be flown without finding the errors. Bottom line: All this would still have happened regardless of the programming language used. However, don't just listen to me: read the final report on Ariane 501 here: http://www.di.unito.it/~damiani/ariane5rep.html -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From sturlamolden at yahoo.no Mon Aug 2 19:28:23 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 16:28:23 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: <74421501-4ad2-44a4-8ffd-ca1b40358c9d@i24g2000yqa.googlegroups.com> On 3 Aug, 01:14, Martin Gregorie wrote: > Bottom line: All this would still have happened regardless of the > programming language used. I am quite sure C and Fortran makes it unlikely for an unhandled exception to trigger the autodestruct sequence. But it's nice to know when flying that modern avionics is programmed in a language where this is possible. ;) From breamoreboy at yahoo.co.uk Mon Aug 2 19:31:38 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Aug 2010 00:31:38 +0100 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 03/08/2010 00:03, Aahz wrote: > In article, > Peter wrote: >> On Aug 3, 7:42=A0am, Mark Lawrence wrote: >>> On 02/08/2010 00:08, candide wrote: >>> >>> I can't understand why any serious programmer mentions C++. As soon as I >>> read it, I have to rush either to the kitchen to find a bowl to throw up >>> in, or head for the toilet so I can talk to the great white telephone. >> >> With you there Mark - IMO C++ is an abortion that should never have >> seen the light of day. The idea of experimenting with creating an OO >> language by extending C wasn't such a bad idea for a "play thing" (by >> Stroustrop) but the fact that it somehow escaped from the Lab and >> people picked it up and ran with it on a commercial basis is just >> plain wrong! > > http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html Haven't been able to read this properly as the stomach has been shaking too much to control the mouse and/or arrow keys/page up/down etc. Hum, marks out of 10, 1.649072354865927**trillions. For the cryptographers, is this a decent random number? Kindest regards. Mark Lawrence From breamoreboy at yahoo.co.uk Mon Aug 2 19:37:02 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Aug 2010 00:37:02 +0100 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: On 03/08/2010 00:14, Martin Gregorie wrote: > On Mon, 02 Aug 2010 15:54:52 -0700, sturlamolden wrote: > >> On 3 Aug, 00:27, Paul Rubin wrote: >> >>> Certain folks in the functional-programming community consider OO to be >>> a 1980's or 1990's approach that didn't work out, and that what it was >>> really trying to supply was polymorphism. C++ programs these days >>> apparently tend to use template-based generics rather than objects and >>> inheritance for that purpose. >> >> It avoids virtual function calls at the expense of unreable code and >> errors that are nearly impossible to trace. It seems many thinks this is >> a good idea because Microsoft did this with ATL and WTL. There are also >> those who thinks template metaprogramming is a good idea. But who uses a >> C++ compiler to dumb to unroll a for loop? In my experience, trying to >> outsmart a modern compiler is almost always a bad idea. >> >>> I have the impression that Ada has an undeservedly bad rap because of >>> its early implementations and its origins in military bureaucracy. >> >> It is annyingly verbose, reminds me of Pascal (I hate the looks of it), >> and is rumoured to produce slow bloatware. > >> And don't forget Ariane 5 ;) >> > This had nothing to do with Ada per se and everything to do with > shortcuts: > > - re-use of an Ariane 4 component without changing its parameters > to match the Ariane 5 flight profile > - not removing Ariane 4-only code intended to handle launch holds > and not used at all in Ariane 5 > - a programming fault that allowed an exception code to be sent > to another component as if it was valid data. > > Inadequate testing allowed all these to be flown without finding the > errors. > > Bottom line: All this would still have happened regardless of the > programming language used. However, don't just listen to me: read the > final report on Ariane 501 here: > > http://www.di.unito.it/~damiani/ariane5rep.html > > A bug is a bug is a bug? Except in my code. Never written a bug in my life. Cross my heart and hope to die. Of course I'm lying. :) Kindest regards. Mark Lawrence. From ben+python at benfinney.id.au Mon Aug 2 19:38:16 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 03 Aug 2010 09:38:16 +1000 Subject: Package management (was: Why is there no platform independent way of clearing a terminal?) References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: <87aap44mc7.fsf_-_@benfinney.id.au> Mark Lawrence writes: > How does any user or an admin cope with 500 packages? Operating systems with good package management come with tools that help the administrator do this job easily. Also, operating systems with good package management encourage the small-pieces-loosely-joined philosophy to apply to packages also: the packages tend to be smaller and more focussed, and fit together in more well-defined ways, than those on other OSen. This isn't automatic, but the support of a good package management system allows a robust policy to be implemented by the vendor for good quality packages in the OS. So ?installing 500 packages? is not an unusual nor onerous thing to do on such an OS. The job of making them all work well together is delegated upstream, to one's distribution vendor. But the fact that they're small pieces, loosely joined, means that if any one of them is causing a problem, it's far more likely that a motivated administrator can do something about it locally, rather than being at the mercy of the vendor. > Can Python help here, assume an eight hour working day? Sadly, Python's package management is rather lacking by these standards. The Distutils legacy assumption of ?package recipient, system administrator, and end user are all the same person?, among other design decisions, makes it unusually difficult to have the necessary separation of concerns between OS packaging, system administration, and end user. There have been great strides in recent years to improve the Distutils shortcomings (see the Distutils forum archives for the details), but the changes are in part backward-incompatible, and it will be some time before Python is on a par with, e.g., Perl in this area. > So every working day you have 57.6 seconds to use each package. Your mistaken assumption is that one would use these packages separate from each other. That's like assuming that the limit of usefulness of modules in a Python program is how much one can use each of them separate from all the others. In both cases, they're not used separately most of the time; they're used in conjunction, and their distinction is more to enable the people responsible for maintaining them to do so as distinct pieces when it makes sense to do so, and as larger aggregate collections when that makes sense. OS packages are not only applications. They are any discrete, coherent ?piece? of an operating system; applications usually encompass one or several packages, and most packages are not applications. -- \ ?We must respect the other fellow's religion, but only in the | `\ sense and to the extent that we respect his theory that his | _o__) wife is beautiful and his children smart.? ?Henry L. Mencken | Ben Finney From python at mrabarnett.plus.com Mon Aug 2 19:41:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Aug 2010 00:41:15 +0100 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: <4C57579B.8060405@mrabarnett.plus.com> Mark Lawrence wrote: > On 02/08/2010 19:14, Benjamin Kaplan wrote: >> On Mon, Aug 2, 2010 at 9:51 AM, David Robinow wrote: >> >>> On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan >>> wrote: >>>> ... >>>> So these are the packages needed just to run Python in Ubuntu. It >>>> doesn't >>>> include the packages required for the kernel, the desktop environment, >>> the >>>> window manager, the terminal, and whatever else you want running. In my >>>> fairly clean Ubuntu VM (I use it almost exclusively for testing), I >>>> have >>>> close to 1500 packages installed. >>> As an admittedly stupid comparison, I have 1579 DLLs in my >>> \windows\system32 directory. >>> Some number of these have been upgraded by Windows Update. This is XP >>> Service Pack 3. >>> I'm not sure if this means that Windows is better because it has more >>> packages or that it is worse because it's got too many. :) >>> -- >>> >> >> A package is usually more than one file. >> http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist >> >> >> >>> http://mail.python.org/mailman/listinfo/python-list >>> >> > > This is all very well, but what is the unladen airspeed velocity of a > swallow in flight? Answers on a postcard please, given that I expect > both direction and speed! > African or European? :-) From sturlamolden at yahoo.no Mon Aug 2 19:49:23 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 16:49:23 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: <44a35af9-3861-4538-948c-ca80e130802f@f33g2000yqe.googlegroups.com> On 3 Aug, 01:37, Mark Lawrence wrote: > A bug is a bug is a bug? According to Grace Hopper, a bug might be a moth, in which case the best debugger is a pair of forceps. From a.pfrengle at gmail.com Mon Aug 2 19:52:25 2010 From: a.pfrengle at gmail.com (Andreas Pfrengle) Date: Mon, 2 Aug 2010 16:52:25 -0700 (PDT) Subject: simple integer subclass Message-ID: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> I'm trying to define a subclass of int called int1. An int1-object shall behave exactly like an int-object, with the only difference that the displayed value shall be value + 1 (it will be used to display array indices starting at 1 instead of 0). Right now I have: class int1(int): def __str__(self): return int.__str__(self + 1) However, if I calculate with int1 and int- (or other number) objects, the result is always coerced to an int (or other number object), e.g: a = int1(5) b = 5 print a # "6" print a+b #"10" How can I tell int1 to be the "default integer object"? Do I need to overload *every* mathematical operation method of int, or is there an easier way? From lists at cheimes.de Mon Aug 2 19:55:22 2010 From: lists at cheimes.de (Christian Heimes) Date: Tue, 03 Aug 2010 01:55:22 +0200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: Am 03.08.2010 01:03, schrieb Aahz: > http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html I don't understand why the URL contains the word "joke". Every word is true. Hell yeah! :) Christian From carey.tilden at gmail.com Mon Aug 2 20:05:14 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Mon, 2 Aug 2010 17:05:14 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Mon, Aug 2, 2010 at 3:18 PM, sturlamolden wrote: > > Perl is written in C++. That is not enough to make me want to use > it ;) I realize this was meant to be funny, but it's not true, and detracts from the point you were trying to make. Maybe skip the pointless jabs at Perl and stick to things you know more about. From chare at labr.net Mon Aug 2 20:06:26 2010 From: chare at labr.net (Chris Hare) Date: Mon, 02 Aug 2010 19:06:26 -0500 Subject: calling a class method from a menu in a different class Message-ID: <425A7322-BD8E-48FC-80AE-0C0A3C423F70@labr.net> What I am trying to do is call a class function from a menu, for example displaySubMenu.add_radiobutton(label="Medium", variable=radarPanelSize, command=radarWidgets.refresh) class radarWidgets: def __init__(self,root): self.window = root def refresh(self): global radar global refreshTimer self.refreshTimer.cancel() logging.debug("handlesRadarRefreshByTimer()") # # destroy the existing frame the radar is in # self.w.destroy() self.lblLastUpdate.destroy() self.btnRefresh.destroy() # # rebuild the radarWidgets # self.createImage() self.refreshTimer = threading.Timer( 900, self.refresh) self.refreshTimer.start() This doesn't work because the instance of radarWidgets was defined in a different class ...... class mainDisplay: def __init__(self,root): self.window = root def show(self): # # Configure the base frame # base=Frame(self.window,bg=backColor,width=1200, height=800) base.grid() frameRadar = Frame(base, bd=0, bg=backColor) frameRadar.grid(row=2,column=1,sticky=N+E+S+W) # radar = radarWidgets(frameRadar) radar.show() so the actual instance is called "radar". If I put the instance name in the menu item, I get an error that "radar" is unknown. If I use RadarWidgets.refresh ins the command for the menu, I get the error: TypeError: unbound method refresh() must be called with radarWidgets instance as first argument (got nothing instead) Any ideas? Thanks! From peter.milliken at gmail.com Mon Aug 2 20:17:35 2010 From: peter.milliken at gmail.com (Peter) Date: Mon, 2 Aug 2010 17:17:35 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: On Aug 3, 8:27?am, Paul Rubin wrote: ... > > Certain folks in the functional-programming community consider OO to be > a 1980's or 1990's approach that didn't work out, and that what it was > really trying to supply was polymorphism. ?C++ programs these days > apparently tend to use template-based generics rather than objects and > inheritance for that purpose. ? > > I've never programmed in Ada but I'm intrigued by these articles: > > ?http://adahome.com/Ammo/cpp2ada.html > ?http://www.adaic.org/whyada/ada-vs-c/cada_art.html > > I have the impression that Ada has an undeservedly bad rap because of > its early implementations and its origins in military bureaucracy. ?I'd > certainly consider it as an alternative to C or C++ if I had to write a > big program in a traditional procedural language. I used to work for defence contractors - Ada (IMO :-)) is the very best OO language for real-time and embedded systems. It scales fantastically well to large, multi-platform jobs as well. If I had my way we would use it where I work now (biomedical field) but that isn't an option - too many folk are brought up on a steady diet of C/C++ and therefore don't know any better, plus there is a dearth of Ada compilers for the CPU's that we use here (all embedded work). I have used fortran, C, C++, some Java, Ada (and Python :-)), if I had my choice for the type of programming I do here at work, it would definitely go to Ada by a country mile. Having said that though, I won't replace Python with it on my desktop for the type of stuff I do around the fringes of my job (test scripts etc) and my personal programming :-) But for anyone who wants to expand their horizons, learning Ada would be an excellent choice (although like any learning activity, unless you have a concrete goal in mind you will probably just waste your time :-)). It is not an easy language to just pick up and run with because the strong type-checking FORCES you to think about and design your program very carefully from the very beginning - something that many programmers find an abhorrence for :-) But I always used to tell people - by the time I got a program to compile then I figured 99% of the bugs were already discovered! Try that with C/C++ or almost any other language you care to name :-) Peter From samwyse at gmail.com Mon Aug 2 20:19:46 2010 From: samwyse at gmail.com (samwyse) Date: Mon, 2 Aug 2010 17:19:46 -0700 (PDT) Subject: simple (I hope!) problem Message-ID: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> I'm writing for the Google app engine and have stubbed my toe yet again on a simple obstacle. Non-trivial app engines programs require the import of several modules that aren't normally in my PYTHONPATH. I'd like to be able to test my code outside of the app engine framework. I've tried several solutions in the past that worked but weren't particularly elegant or portable. Now I've had a new idea. Here's my latest attempt: import os, re if __name__ == '__main__': pass else from google.appengine.ext import webapp register = webapp.template.create_template_register() This works great, except my code makes use of the resister object in several places, like this: register.filter(emptylines) Fortunately, I don't need the functionality of the object, I just want something that won't generate an error when I use it. So, what is the quickest way to to create such an object (replacing the 'pass' in my first snippet). My solution is this: class C: def filter(self, *args, **kwds): pass register = C() but it seems like I should be able to do something "better", as measured by lines of code, faking more than just a 'filter' method, or both. Any ideas? Thanks! From samwyse at gmail.com Mon Aug 2 20:24:51 2010 From: samwyse at gmail.com (samwyse) Date: Mon, 2 Aug 2010 17:24:51 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> Message-ID: On Aug 2, 6:52?pm, Andreas Pfrengle wrote: > I'm trying to define a subclass of int called int1. An int1-object > shall behave exactly like an int-object, with the only difference that > the displayed value shall be value + 1 (it will be used to display > array indices starting at 1 instead of 0). Right now I have: > > class int1(int): > ? ? def __str__(self): > ? ? ? ? return int.__str__(self + 1) > > However, if I calculate with int1 and int- (or other number) objects, > the result is always coerced to an int (or other number object), e.g: > a = int1(5) > b = 5 > print a ? ? ?# "6" > print a+b ?#"10" > > How can I tell int1 to be the "default integer object"? Do I need to > overload *every* mathematical operation method of int, or is there an > easier way? I had a similar problem a few years ago, and couldn't find a solution then. The thread from back then may shed some light on your problem. http://groups.google.com/group/comp.lang.python/browse_thread/thread/10cfe2affc265ac/2ad03b121c1c6489 From no.email at nospam.invalid Mon Aug 2 20:31:24 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 02 Aug 2010 17:31:24 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <64500ebd-d5a5-45b0-82da-3ed85eee9fb6@t2g2000yqe.googlegroups.com> Message-ID: <7xy6cobkpv.fsf@ruckus.brouhaha.com> sturlamolden writes: > It is annyingly verbose, reminds me of Pascal (I hate the looks of > it), and is rumoured to produce slow bloatware. The earliest Ada compilers were terrible, but they are about like C compilers now, so the output code is ok (see Alioth shootout for example). I agree about the verbosity but I don't think that's too big a problem in the sorts of systems that need to be written in such languages. > And don't forget Ariane 5 ;) I have looked into that a few times and I do wonder whether the language or release process could have been of any help. One possibility is using something like SPARK to ensure the absence of overflow exceptions. Another is automatic test generation something like http://www.stanford.edu/~engler/klee-osdi-2008.pdf but that approach was probably unknown at the time. From roy at panix.com Mon Aug 2 20:47:42 2010 From: roy at panix.com (Roy Smith) Date: Mon, 02 Aug 2010 20:47:42 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: In article <0ed1fb16-87cb-4fb9-85b2-08d876445d5d at q22g2000yqm.googlegroups.com>, sturlamolden wrote: > The typical examples revealing incompetence are use of > new[] instead of std::vector To be fair, there were usable C++ compilers before there were usable STL implementations. Thus, it should not be surprising to find older C++ code bases eschewing the use of STL. That's not to say that this trend should be propagated in current educational material. > and dynamic resourse allocation outside contructors. This one I don't understand. Yes, I get RAII, but surely there are valid reasons to allocate memory outside of constructors. Containers which resize themselves (such as std::vector) are one obvious example. From samwyse at gmail.com Mon Aug 2 20:53:12 2010 From: samwyse at gmail.com (samwyse) Date: Mon, 2 Aug 2010 17:53:12 -0700 (PDT) Subject: Behavior of re.split on empty strings is unexpected References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: <52ae410e-789e-41ad-bf0a-1d060d03019d@x21g2000yqa.googlegroups.com> On Aug 2, 12:34?pm, John Nagle wrote: > The regular expression "split" behaves slightly differently than string > split: I'm going to argue that it's the string split that's behaving oddly. To see why, let's first look at some simple CSV values: cat,dog ,missing,,values, How many fields are on each line and what are they? Here's what re.split(',') says: >>> re.split(',', 'cat,dog') ['cat', 'dog'] >>> re.split(',', ',missing,,values,') ['', 'missing', '', 'values', ''] Note that the presence of missing values is clearly flagged via the presence of empty strings in the results. Now let's look at string split: >>> 'cat,dog'.split(',') ['cat', 'dog'] >>> ',missing,,values,'.split(',') ['', 'missing', '', 'values', ''] It's the same results. Let's try it again, but replacing the commas with spaces. >>> re.split(' ', 'cat dog') ['cat', 'dog'] >>> re.split(' ', ' missing values ') ['', 'missing', '', 'values', ''] >>> 'cat dog'.split(' ') ['cat', 'dog'] >>> ' missing values '.split(' ') ['', 'missing', '', 'values', ''] It's the same results; however many people don't like these results because they feel that whitespace occupies a privileged role. People generally agree that a string of consecutive commas means missing values, but a string of consecutive spaces just means someone held the space-bar down too long. To accommodate this viewpoint, the string split is special-cased to behave differently when None is passed as a separator. First, it splits on any number of whitespace characters, like this: >>> re.split('\s+', ' missing values ') ['', 'missing', 'values', ''] >>> re.split('\s+', 'cat dog') ['cat', 'dog'] But it also eliminates any empty strings from the head and tail of the list, because that's what people generally expect when splitting on whitespace: >>> 'cat dog'.split(None) ['cat', 'dog'] >>> ' missing values '.split(None) ['missing', 'values'] From roy at panix.com Mon Aug 2 21:03:55 2010 From: roy at panix.com (Roy Smith) Date: Mon, 02 Aug 2010 21:03:55 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html The same story has been floating around for eons, just with the names changed. I saw one where Wirth was ostensibly making fun of the people who didn't understand that Pascal was all just a joke. I'm sure if you go back far enough, you can find a McCarthy / Lisp version. It probably goes something like, "So, anyway, we tried to figure out what was the most absurd way to abuse punctuation we could imagine. Somebody suggested that every program would have to end with 37 close parentheses. When we finally stopped laughing, we started sketching out a grammar on the chalkboard that would let us do that". From pavlovevidence at gmail.com Mon Aug 2 21:22:48 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 2 Aug 2010 18:22:48 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> Message-ID: <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> On Aug 2, 4:52?pm, Andreas Pfrengle wrote: > I'm trying to define a subclass of int called int1. An int1-object > shall behave exactly like an int-object, with the only difference that > the displayed value shall be value + 1 (it will be used to display > array indices starting at 1 instead of 0). Right now I have: > > class int1(int): > ? ? def __str__(self): > ? ? ? ? return int.__str__(self + 1) > > However, if I calculate with int1 and int- (or other number) objects, > the result is always coerced to an int (or other number object), e.g: > a = int1(5) > b = 5 > print a ? ? ?# "6" > print a+b ?#"10" > > How can I tell int1 to be the "default integer object"? Do I need to > overload *every* mathematical operation method of int, or is there an > easier way? (Preface: I normally don't offer recommendations without answering the question as asked, but once in a while it has to be done.) I **highly** recommend against this approach. You are creating an object that differs from a built-in, int, in a highly misleading way that only makes sense in a very limited context, and this object's modified behavior gives no clue that it's been modified in such as way. (That is, it's not possible to tell if the object's not a regular int just by looking at __str__()'s return value.) To make matters worse, you want to program this object to coerce other integers, so there's a risk of these objects escaping from the context where they make sense. This is just a bad idea. The type is not the place to implement behavior that makes sense only in a limited context. Instead, do something like this: print "Item %d is %s." % (i+1, s[i]) Carl Banks From ldo at geek-central.gen.new_zealand Mon Aug 2 21:56:27 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 03 Aug 2010 13:56:27 +1200 Subject: Problem with Elementtree and XMLSchem instance type References: <96e47fd8-c939-48a2-9a2b-92afa720c8ac@k1g2000prl.googlegroups.com> <6627204c-d0b1-456d-94bd-76d946ad21d9@g6g2000pro.googlegroups.com> Message-ID: In message <6627204c-d0b1-456d-94bd-76d946ad21d9 at g6g2000pro.googlegroups.com>, Carl Banks wrote: > On Aug 1, 5:43 pm, Lawrence D'Oliveiro > wrote: > >> In message >> <96e47fd8-c939-48a2-9a2b-92afa720c... at k1g2000prl.googlegroups.com>, Carl >> Banks wrote: >> >>> My general feeling is that ElementTree is a lot handier for reading >>> and writing your own XML formats, than for handling XML files produced >>> by other tools. >> >> Why is that? I?ve successfully used it to parse SVG files produced by >> Inkscape . > > I said it was not handy, not that is was not useful. If you want to split hairs, I didn?t say it was ?useful?, and I certainly found it very ?handy? for that purpose. > And you don't *have* to try to start an argument over every tiny thing > you disagree with. What else is USENET for? :) From ldo at geek-central.gen.new_zealand Mon Aug 2 21:57:57 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 03 Aug 2010 13:57:57 +1200 Subject: Normalizing A Vector References: <877hkdhyl5.fsf@dpt-info.u-strasbg.fr> <6Dw5o.72330$Ds3.63060@hurricane> Message-ID: In message <6Dw5o.72330$Ds3.63060 at hurricane>, Bartc wrote: > There's a cost involved in using those fancy constructions. Sure. But at the point that starts to matter, you have to ask yourself why you?re not rewriting the CPU-intensive part in C. From sturlamolden at yahoo.no Mon Aug 2 22:03:09 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 19:03:09 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> On 3 Aug, 02:47, Roy Smith wrote: > This one I don't understand. ?Yes, I get RAII, but surely there are > valid reasons to allocate memory outside of constructors. ?Containers > which resize themselves (such as std::vector) are one obvious example. That is because an exception might skip an arbitrarily placed delete[] or std::fclose when it rewinds the stack, so to avoid resource leaks they must be places inside a destructor of an object on the stack (which will be called). This is unsafe, anyone who writes this in C++ should be flogged: void foobar() { std::FILE *fid = fopen("whatever"); // some code here std::fclose(fid); } This idiom is safer : struct File { std::FILE *fid; File(const char *name) { // acquire resource in constructor fid = std::fopen(name); if (!fid) throw some_exception; } ~File() { // free resource in destructor if(fid) std::flose(fid); } }; void foobar() { File file("whatever"); // some code here } It is for the very same reason we should use std::vector instead of new[] for arrays. It is why new and delete should only be used inside constructors/destructors. It also why C++ has references in addition to pointers. Which means this is bad in C++, as new and delete is arbitrarily placed: void foobar() { File *myfile = new File("whatever); // some code here delete myfile; } An object should go on the stack, because if an exception is thrown, we need the destructor call. Which is why this (as shown above) is ok: void foobar() { File file("whatever"); // some code here } This is the kind of gotchas that allows C++ to shoot your leg off. In comparison C is much more forgiving, because there is no exceptions (unless you use setjmp/longjmp). This is ok in C, but not in C++: void foobar() { FILE *fid = fopen("whatever"); // some code here fclose(fid); } For the same reason we can place malloc and free wherever we like in C code. But in C++ we must restrict std::malloc and std::free (as well as new and delete) to constructor and destructor pairs. This kind of design is mandatory to make safe C++ programs. But it is not enforced by the compiler. And since the majority of C++ programmers don't obey by these rules, Java and C# tends to produce far less runtime errors and memory/resource leaks. And C++ textbooks tends to avoid teaching these important details. I'm inclined to believe it is because the authors don't understand it themselves. Objects on the stack are also required for operator overloading in C+ +. A common novice mistake is this: std::vector *myvec = new std::vector(10); myvec[5] = 10.0; // why does the compiler complain????? And then the novice will spend hours contemplating why the stupid compiler claims the type of myvec[5] is std::vector. There was recently a post to the Cython mailing list claiming there is a bug in Cython's auto-generated C++ because of this. But this is how it should be: std::vector myvec(10); myvec[5] = 10.0; // ok And now we see why C++ has references, as that is how we can efficiently reference and object on the stack without getting the operator overloading problem above. C++ is good, but most programmers are better off with C. It has fewer gotchas. And if we need OOP, we have Python... Sturla From drsalists at gmail.com Mon Aug 2 22:22:03 2010 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 2 Aug 2010 19:22:03 -0700 Subject: constructing and using large lexicon in a program In-Reply-To: <119487.45857.qm@web113614.mail.gq1.yahoo.com> References: <119487.45857.qm@web113614.mail.gq1.yahoo.com> Message-ID: On Mon, Aug 2, 2010 at 10:46 AM, Majdi Sawalha wrote: > Dear List members, > > I am developing a morphological analyzer that depends on a large lexicon. i > construct a Lexicon class that reades a text file and construct a dictionary > of the lexicon entries. > the other class will use the lexicon class to chech if the word is found in > the lexicon. the problem that this takes long time as each time an object of > that class created, then it needs to call the lexicon many times. then when > the lexicon is called it re-construct the lexicon again. is there any way to > construct the lexicon one time during the execution of the program? and then > the other modules will search the already constructed lexicon. > > best regards > Majdi > > > Faculty of Engineering > School of Computing > University of Leeds > Leeds, LS2 9JT > UK > http://www.comp.leeds.ac.uk/sawalha > > > -- > http://mail.python.org/mailman/listinfo/python-list > > You want an object with a global lifetime. I often wish Python had a nice equivalent to static variables in C. Sometimes people suggest doing this with a function or method argument that takes a default value that looks like it would be different each time the function is called, but in reality, it's evaluated once when the function/method is created. EG: $ cat t #!/usr/local/cpython-2.7/bin/python import time def fn(x = time.time()): print x for i in xrange(5): fn() time.sleep(1) benchbox-dstromberg:~/src/global-lifetime i486-pc-linux-gnu 13955 - above cmd done 2010 Mon Aug 02 07:16 PM $ ./t 1280801789.33 1280801789.33 1280801789.33 1280801789.33 1280801789.33 benchbox-dstromberg:~/src/global-lifetime i486-pc-linux-gnu 13955 - above cmd done 2010 Mon Aug 02 07:16 PM IOW, it's printing the same time each iteration, despite having a 10 millisecond precision and a 1 second sleep between each call. BTW, for storing a truly large lexicon, you might be better off with a trie than a dictionary (AKA hash table), though I'm sure some lexicons aren't huge enough to require it. One simple way of doing a trie would be to mkdir an empty directory, and then for each ith subdirectory depth beneath that, have it correspond to the ith character of your word in your lexicon. That's probably not a terribly efficient trie, but I think it may get the point across - you're not storing common prefixes over and over. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Mon Aug 2 22:25:05 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 19:25:05 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> Message-ID: <2b473423-0a22-4f4d-943f-31ea2d6020e6@z10g2000yqb.googlegroups.com> On 3 Aug, 04:03, sturlamolden wrote: > struct File { > ? ? std::FILE *fid; > ? ? File(const char *name) { > ? ? ? ? // acquire resource in constructor > ? ? ? ? fid = std::fopen(name); > ? ? ? ? if (!fid) throw some_exception; > ? ? } > ? ? ~File() { > ? ? ? ? // free resource in destructor > ? ? ? ? if(fid) std::flose(fid); > ? ? } > > }; And since this is comp.lang.python, I'll add in that this sometimes applies to Python as well. Python, like C++, can have the call stack rewinded by an exception. If we call some raw OS resource allocation, e.g. malloc or fopen using ctypes, we have to place a deallocation in __del__ (and make sure the object is newer put in a reference cycle). The safer option, however, is to use a C extension object, which is guaranteed to have the destructor called (that is, __dealloc__ when using Cython or Pyrex). If we place raw resource allocation arbitrarily in Python code, it is just as bad as in C++. But in Python, programmers avoid this trap by mostly never allocating raw OS resources from within Python code. E.g. Python's file object is programmed to close itself on garbage collection, unlike a pointer retured from fopen using ctypes. Sturla From pavanhousework at gmail.com Mon Aug 2 22:28:20 2010 From: pavanhousework at gmail.com (pink) Date: Mon, 2 Aug 2010 19:28:20 -0700 (PDT) Subject: Get sony/dell laptaps 100% free Message-ID: <84f1e360-0843-489b-acd2-e5d027adf448@h40g2000pro.googlegroups.com> Free sony/dell laptops ?.no need money? No need registration fee?.no need shipping charges?..details available on my website. I have hidden the free laptap trick and registration form LINK in an BIG SIZE IMAGES at the TOP of my BLOG. .click any image and Get it free laptap within 2 days.. my website is http://femalebodies.co.cc/ From sturlamolden at yahoo.no Mon Aug 2 22:37:46 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 2 Aug 2010 19:37:46 -0700 (PDT) Subject: Normalizing A Vector References: Message-ID: On 30 Jul, 13:46, Lawrence D'Oliveiro wrote: > Say a vector V is a tuple of 3 numbers, not all zero. You want to normalize > it (scale all components by the same factor) so its magnitude is 1. > > The usual way is something like this: > > ? ? L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) > ? ? V = (V[0] / L, V[1] / L, V[2] / L) > > What I don?t like is having that intermediate variable L leftover after the > computation. L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]) V = (V[0] / L, V[1] / L, V[2] / L) del L But this is the kind of programming tasks where NumPy is nice: V[:] = V / np.sqrt((V**2).sum()) Sturla From jiazhao62 at yahoo.com Mon Aug 2 22:46:47 2010 From: jiazhao62 at yahoo.com (world-trade) Date: Mon, 2 Aug 2010 19:46:47 -0700 (PDT) Subject: paypal wholesale gucci shoes (paypal payment) Message-ID: <83151cc5-f578-4348-8dc8-f5cd587ff9d7@l32g2000prn.googlegroups.com> paypal wholesale d&g shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale gucci shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale lv shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale NBA shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale nike (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale adidas shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale chanel shoes (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale bape hoody (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale antick jeans (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale diesel jeans (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale artful dudger (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale bag(lv gucci coach chanel d&g dior ed fendi ) (paypal payment)(http://www.24hours-buy.com/ ) paypal wholesale clothing (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale lrg,jeans,hoody, (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale evisu jeans,hoody,shirt (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale Prada (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale Puma (paypal payment)( http://www.24hours-buy.com/ ) paypal wholesale Sand (paypal payment)( http://www.24hours-buy.com/ ) paypal wholesale Shox (paypal payment)( http://www.24hours-buy.com/ ) paypal wholesale soccer (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale LV (paypal payment)( http://www.24hours-buy.com/ ) paypal wholesale Versace (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale Women (paypal payment) ( http://www.24hours-buy.com/ ) paypal wholesale Y-3 (paypal payment)( http://www.24hours-buy.com/ ) From roy at panix.com Mon Aug 2 22:46:50 2010 From: roy at panix.com (Roy Smith) Date: Mon, 02 Aug 2010 22:46:50 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> Message-ID: In article <7d95c0d3-718d-4958-9364-263c833f1835 at i24g2000yqa.googlegroups.com>, sturlamolden wrote: > On 3 Aug, 02:47, Roy Smith wrote: > > > This one I don't understand. ?Yes, I get RAII, but surely there are > > valid reasons to allocate memory outside of constructors. ?Containers > > which resize themselves (such as std::vector) are one obvious example. > > That is because an exception might skip an arbitrarily placed delete[] > or std::fclose when it rewinds the stack... Well, OK, but there's still nothing wrong with allocating memory outside of constructors, as long as you make sure the destructor cleans it up. Or you have made some other arrangements to make sure it's cleaned up (try/catch, auto_pointer, etc). From jjposner at optimum.net Mon Aug 2 23:00:51 2010 From: jjposner at optimum.net (John Posner) Date: Mon, 02 Aug 2010 23:00:51 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C578663.8000804@optimum.net> On 7/31/2010 1:31 PM, John Posner wrote: > > Caveat -- there's another description of defaultdict here: > > http://docs.python.org/library/collections.html#collections.defaultdict > > ... and it's bogus. This other description claims that __missing__ is a > method of defaultdict, not of dict. Following is a possible replacement for the bogus description. Comments welcome. I intend to submit a Python doc bug, and I'd like to have a clean alternative to propose. -------------- class collections.defaultdict([default_factory[, ...]]) defaultdict is a dict subclass that can guarantee success on key lookups: if a key does not currently exist in a defaultdict object, a "default value factory" is called to provide a value for that key. The "default value factory" is a callable object (typically, a function) that takes no arguments. You specify this callable as the first argument to defaultdict(). Additional defaultdict() arguments are the same as for dict(). The "default value factory" callable is stored as an attribute, default_factory, of the newly created defaultdict object. If you call defaultdict() with no arguments, or with None as the first argument, the default_factory attribute is set to None. You can reassign the default_factory attribute of an existing defaultdict object to another callable, or to None. When a lookup of a non-existent key is performed in a defaultdict object, its default_factory attribute is evaluated, and the resulting object is called: * If the call produces a value, that value is returned as the result of the lookup. In addition, the key-value pair is inserted into the defaultdict. * If the call raises an exception, it is propagated unchanged. * If the default_factory attribute evaluates to None, a KeyError exception is raised, with the non-existent key as its argument. (The defaultdict behaves exactly like a standard dict in this case.) From rantingrick at gmail.com Mon Aug 2 23:31:20 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 2 Aug 2010 20:31:20 -0700 (PDT) Subject: calling a class method from a menu in a different class References: Message-ID: Chris, It looks as if you are calling a class object and not an instance object. However i cannot be for sure because you are using improper Python style. All classes should be capwords. But here again you have used camelcase for the class identifiers "radarWidgets" and "mainDisplay", which is bad bad bad!! You been asking multiple questions about this code for the last couple of days (and thats fine). However, maybe you would do everyone a favor by posting the entire code so we can offer suggestions. Just seeing seeing a snipit here and a snipit there is not helping because we don't know where else you may be screwing up that we cannot see. It seems you're committing many faux pas with not only your coding style but also your coding practices. I've seen overuse of globals and bad styles and on and on. So post the entire code so myself and others can go through this mess and get it sorted out. If you keep on with your bad habits you're never going to become proficient with Python. I am sorry if this post seems condescending because that is not the case. From rantingrick at gmail.com Mon Aug 2 23:36:48 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 2 Aug 2010 20:36:48 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> Message-ID: <052ff22f-c083-487f-9c97-b45f54754758@f33g2000yqe.googlegroups.com> On Aug 2, 6:52?pm, Andreas Pfrengle wrote: > I'm trying to define a subclass of int called int1. An int1-object > shall behave exactly like an int-object, with the only difference that > the displayed value shall be value + 1 (it will be used to display > array indices starting at 1 instead of 0) Is zero based indexing that bad for you? I also think this is a very bad idea unless you can offer a sensible use case -- for which i cannot imagine. From rantingrick at gmail.com Mon Aug 2 23:42:14 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 2 Aug 2010 20:42:14 -0700 (PDT) Subject: Behavior of re.split on empty strings is unexpected References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <52ae410e-789e-41ad-bf0a-1d060d03019d@x21g2000yqa.googlegroups.com> Message-ID: On Aug 2, 7:53?pm, samwyse wrote: > It's the same results; however many people don't like these results > because they feel that whitespace occupies a privileged role. ?People > generally agree that a string of consecutive commas means missing > values, but a string of consecutive spaces just means someone held the > space-bar down too long. ?To accommodate this viewpoint, the string > split is special-cased to behave differently when None is passed as a > separator. ?First, it splits on any number of whitespace characters, > like this: Well we could have created another method like "splitstrip()". However then folks would complain that they must remember two methods that are almost identical. Uggh, you just can't win. There is always the naysayers no matter what you do! PS: Great post by the way. Highly informative for the pynoobs. From aahz at pythoncraft.com Tue Aug 3 00:02:59 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2010 21:02:59 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Roy Smith wrote: >In article , aahz at pythoncraft.com (Aahz) >wrote: >> >> http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html > >The same story has been floating around for eons, just with the names >changed. I saw one where Wirth was ostensibly making fun of the people >who didn't understand that Pascal was all just a joke. > >I'm sure if you go back far enough, you can find a McCarthy / Lisp >version. It probably goes something like, "So, anyway, we tried to >figure out what was the most absurd way to abuse punctuation we could >imagine. Somebody suggested that every program would have to end with >37 close parentheses. When we finally stopped laughing, we started >sketching out a grammar on the chalkboard that would let us do that". http://www.netfunny.com/rhf/jokes/90q2/lispcode.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ (You knew I was going to post that, right?) From aahz at pythoncraft.com Tue Aug 3 00:05:29 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2010 21:05:29 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> <2b473423-0a22-4f4d-943f-31ea2d6020e6@z10g2000yqb.googlegroups.com> Message-ID: In article <2b473423-0a22-4f4d-943f-31ea2d6020e6 at z10g2000yqb.googlegroups.com>, sturlamolden wrote: > >And since this is comp.lang.python, I'll add in that this sometimes >applies to Python as well. Python, like C++, can have the call stack >rewinded by an exception. If we call some raw OS resource allocation, >e.g. malloc or fopen using ctypes, we have to place a deallocation in >__del__ (and make sure the object is newer put in a reference cycle). >The safer option, however, is to use a C extension object, which is >guaranteed to have the destructor called (that is, __dealloc__ when >using Cython or Pyrex). Actually, with Python 2.6 or later, the Pythonic solution is to use ``with``. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From hashah1985 at gmail.com Tue Aug 3 00:06:54 2010 From: hashah1985 at gmail.com (Hiral Shah) Date: Mon, 2 Aug 2010 21:06:54 -0700 Subject: Seeking help with urllib2 response reading Message-ID: Hi All, I am facing problem reading response from urllib2 request. i.e. with read() method. I am trying to access XMLAPI using python. I am getting weird behavior from server, when reading response.Code for calling XMLAPI is as follows: headers = {'Content-type': 'application/x-www-form-urlencoded'} request = urllib2.Request(siteXMLAPIURL,xmlStr,headers) response = urllib2.urlopen(request) print response.read() In above code: xmlStr: is String containing XML request siteXMLAPIURL: URL of the site to send request. It is in form " https://xxx.xxx.com/XXXService/XXXService Problem Description: I am calling URL for creating product by passing methodname(CreateProduct), productId, productCreateDate, productCreateTime etc in XML form. Call to XMLAPI always succeed and product is created on site. But when I call .read() method to print response, then "productCreateTimes" gets changed on server !! For example, Case 1: Not using .read() method. (i.e. commenting print line in above code) Calling API by passing productCreateTime = 08/02/10 08:00:00,and then product is being created with time 08/02/10 08:00:00. i.e. everything is fine here Now, Case 2: Using read() method (i.e. having print line is code) Calling API by passing productCreateTime = 08/02/10 08:00:00 and then product is being created with time 08/02/10 09:00:00. Here, server is adding one more hour to productCrateTime. Which is really strange for me!! FYI: If I access same API with java, everything is fine all time. I am unable to understand why read() method is changing server behavior!! Can anyone please guide me in same? Thank you so much for your time. Waiting for your reply. Thanks, Hiral -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Tue Aug 3 01:01:23 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 2 Aug 2010 22:01:23 -0700 Subject: Trying to run Python 2.7 on Windows 7 and any suggestions onbooks/websites for "dummies guide to python" type learning References: Message-ID: "ben owen" wrote in message news:SNT124-W51CDF963A687DD653CC804CCAD0 at phx.gbl... Hi everyone, I'm new to this and was needing help with trying to learn/work with Python 2.7 on my computer. I'm running Windows 7 and trying to learn python programming from an older book from 1999 by Mark Lutz and David Ascher my boss gave me, and for some reason none of my script/modules for the exercises are working on my comp. Mostly they give either a syntax error on the python command line or something about the file/module not being found on the windows command line. Also, does anyone where i can find/get something similar to the book for my own? Ben ---------------- Post actual code and actual results including error messages (cut-n-paste) and you'll get better answers. Google is your friend for finding books and tutorials. -Mark From sanjeeb25 at gmail.com Tue Aug 3 01:03:14 2010 From: sanjeeb25 at gmail.com (Sanjeeb) Date: Mon, 2 Aug 2010 22:03:14 -0700 (PDT) Subject: sending a file chunk by chunk instead as a whole to a web server References: Message-ID: On Aug 2, 11:52?am, Sanjeeb wrote: > Hi, > I have a web client which send a file to a server as multipart form > data, the sending of data is fromhttp://code.activestate.com/recipes/146306-http-client-to-post-using-.... > > I dont want to open the whole file to memory(at cliend end) and then > send, i just want to send part by part, say chunk of 1024 bytes to the > server and then assemble at the server end. > > Could some one suggest what would be the best way to do this? > > Regards > -Sanjeeb Hey any taker for this question??? From kushal.kumaran+python at gmail.com Tue Aug 3 01:15:27 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 3 Aug 2010 10:45:27 +0530 Subject: sending a file chunk by chunk instead as a whole to a web server In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 12:22 PM, Sanjeeb wrote: > Hi, > I have a web client which send a file to a server as multipart form > data, the sending of data is from > http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/. > > I dont want to open the whole file to memory(at cliend end) and then > send, i just want to send part by part, say chunk of 1024 bytes to the > server and then assemble at the server end. > > Could some one suggest what would be the best way to do this? > There's no reason why sending the whole file implies reading the whole file into memory at one time. You can just read your desired chunk size and send it, then read the next chunk, and so on. You might have to first find the total size to calculate what to set Content-Length to. ISTR questions of this nature have been asked in the past on this list. -- regards, kushal From michele.simionato at gmail.com Tue Aug 3 01:28:15 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 2 Aug 2010 22:28:15 -0700 (PDT) Subject: let optionparse.Optionparser ignore unknown command line switches. References: <4c5555c5$0$19337$426a74cc@news.free.fr> Message-ID: On Aug 1, 1:08?pm, News123 wrote: > I wondered, whether there's a simple/standard way to let > the Optionparser just ignore unknown command line switches. > > thanks in advance for any ideas I will plug in my own work on plac: http://pypi.python.org/pypi/plac Your problem would be solved as follows: import plac @plac.annotations(test=('a flag', 'flag', 't')) def main(test, *ignore): print test, ignore if __name__ == '__main__': plac.call(main, ["-t","--ignoreme_and_dont_fail"]) From ryan at rfk.id.au Tue Aug 3 01:52:32 2010 From: ryan at rfk.id.au (Ryan Kelly) Date: Tue, 03 Aug 2010 15:52:32 +1000 Subject: sending a file chunk by chunk instead as a whole to a web server In-Reply-To: References: Message-ID: <1280814752.2158.62.camel@durian> On Tue, 2010-08-03 at 10:45 +0530, Kushal Kumaran wrote: > On Mon, Aug 2, 2010 at 12:22 PM, Sanjeeb wrote: > > Hi, > > I have a web client which send a file to a server as multipart form > > data, the sending of data is from > > http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/. > > > > I dont want to open the whole file to memory(at cliend end) and then > > send, i just want to send part by part, say chunk of 1024 bytes to the > > server and then assemble at the server end. > > > > Could some one suggest what would be the best way to do this? > > > > There's no reason why sending the whole file implies reading the whole > file into memory at one time. You can just read your desired chunk > size and send it, then read the next chunk, and so on. You might have > to first find the total size to calculate what to set Content-Length > to. More concretely, you would restructure the encode_multipart_formdata() function as a generator, yielding chunks of data to send one at a time. Something like this: def post_multipart(host,selector,fields,files): ...snip... h.endheaders() for chunk in encode_multipart_formdata_chunks(fields,files): h.send(chunk) errcode, errmsg, headers = h.getreply() return h.file.read() def encode_multipart_formdata(fields,files): BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' for (key, value) in fields: yield '--' + BOUNDARY yield 'Content-Disposition: form-data; name="%s"' % key yield '' yield value for (key, filename, value) in files: yield '--' + BOUNDARY yield 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename) ...etc... ...etc... There are many improvements to make, but this should get you started. For example, you'll need to calculate the total content-length rather than just calling len(body) to obtain it. That's left as an exercise to the reader. Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From nikos.the.gr33k at gmail.com Tue Aug 3 02:03:18 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 2 Aug 2010 23:03:18 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> >On 2 ???, 23:57, Thomas Jollans wrote: > So: tripple-check that > > ?* your file is > ?* Python knows that > ?* the web browser knows that Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 / n''' and it worked. I'am still pretty confused about the encodings. Please tell me the difference between 3 things. a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 without BOM. b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed to tell browser that the contents of this python script as in UTF-8 and to handle it as such? c) print ''' Content-Type: text/html; charset=UTF-8 /n''' Please explain to me as simple as you can because from the time with php and perl encodings not only gave me a hard time but also caused my program to produce internal server errors so i need to understand the differences. ========================= Also in the other problem with the cookie iam trying to set: ========================= if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist print "Next time i will count you" cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire now else: print "I wont be counting you any more" cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year ========================= Why always the code block pertainign to 'else' get exectuted ane never the code of 'if' The idea is who ever runs 'koukos.py' to set/unset himself out of the counter count so i need i way to set/unset the browser cookie! Thanks you! From nikos.the.gr33k at gmail.com Tue Aug 3 02:03:18 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 2 Aug 2010 23:03:18 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> Message-ID: <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> >On 2 ???, 23:57, Thomas Jollans wrote: > So: tripple-check that > > ?* your file is > ?* Python knows that > ?* the web browser knows that Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 / n''' and it worked. I'am still pretty confused about the encodings. Please tell me the difference between 3 things. a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 without BOM. b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed to tell browser that the contents of this python script as in UTF-8 and to handle it as such? c) print ''' Content-Type: text/html; charset=UTF-8 /n''' Please explain to me as simple as you can because from the time with php and perl encodings not only gave me a hard time but also caused my program to produce internal server errors so i need to understand the differences. ========================= Also in the other problem with the cookie iam trying to set: ========================= if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist print "Next time i will count you" cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire now else: print "I wont be counting you any more" cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year ========================= Why always the code block pertainign to 'else' get exectuted ane never the code of 'if' The idea is who ever runs 'koukos.py' to set/unset himself out of the counter count so i need i way to set/unset the browser cookie! Thanks you! From steve-REMOVE-THIS at cybersource.com.au Tue Aug 3 02:20:12 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2010 06:20:12 GMT Subject: simple (I hope!) problem References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> Message-ID: <4c57b51c$0$28663$c3e8da3@news.astraweb.com> On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote: > Fortunately, I don't need the functionality of the object, I just want > something that won't generate an error when I use it. So, what is the > quickest way to to create such an object (replacing the 'pass' in my > first snippet). My solution is this: > > class C: > def filter(self, *args, **kwds): > pass > register = C() > > but it seems like I should be able to do something "better", as measured > by lines of code, faking more than just a 'filter' method, or both. Any > ideas? Thanks! You want a variation on the Null Object design pattern. class NullWithMethods(object): def __getattr__(self, name): return self def __call__(self, *args, **kwargs): pass And in action: >>> c = NullWithMethods() >>> c.spam("hello", "world") >>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42) -- Steven From alanwilter at gmail.com Tue Aug 3 02:35:30 2010 From: alanwilter at gmail.com (Alan) Date: Tue, 3 Aug 2010 07:35:30 +0100 Subject: please, help with python 3.1 Message-ID: Hello List, Please, can someone at least try this code below in python 3 and report me back whether it works or not? Because for me this code works in python 2.6 but not with python 3.1. Thanks! from __future__ import print_function import os, subprocess, signal def signal_handler( signum, frame ): print( "PID: %s" % pid ) print( "Timed out! Process %s killed, max exec time (%ss) exceeded" % (pid, timeTol ) ) os.kill( int( pid ), 15 ) raise Exception( "Taking too long to finish... aborting!" ) if __name__ == '__main__': timeTol = 5 cmd = 'find /' signal.signal(signal.SIGALRM, signal_handler) signal.alarm(timeTol) p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout = subprocess.PIPE) pid = p.pid out = str( p.communicate()[0].decode() ) print(out) Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Aug 3 03:11:35 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 00:11:35 -0700 Subject: please, help with python 3.1 In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 11:35 PM, Alan wrote: > Hello List, > Please, can someone at least try this code below in python 3 and report me > back whether it works or not? Because for me this code works in python 2.6 > but not with python 3.1. Thanks! Please specify *in exactly what way* the code is not working. Is an exception being thrown? Then include the full traceback. Is the behavior not what you expected/intended? Then say what it's doing vs. what you want it to do. Cheers, Chris -- Getting Debugging Help 101: Don't just say "there's a problem". Say what the problem is. http://blog.rebertia.com From rantingrick at gmail.com Tue Aug 3 03:23:36 2010 From: rantingrick at gmail.com (rantingrick) Date: Tue, 3 Aug 2010 00:23:36 -0700 (PDT) Subject: please, help with python 3.1 References: Message-ID: <49143c92-7011-436f-a0e7-072ed3ce0c4b@f33g2000yqe.googlegroups.com> On Aug 3, 2:11?am, Chris Rebert wrote: > On Mon, Aug 2, 2010 at 11:35 PM, Alan wrote: > > Hello List, > > Please, can someone at least try this code below in python 3 and report me > > back whether it works or not? Because for me this code works in python 2.6 > > but not with python 3.1. Thanks! Oh my Gawd! Python3x is not backwards compatible! 8^O You know it would be nice if you "esteemed" Pythonista's would send out a newsletter or something before making changes that could break code. We are trying to maintain a code base out here you know. Geez! From clp2 at rebertia.com Tue Aug 3 03:28:04 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 00:28:04 -0700 Subject: please, help with python 3.1 In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Alan Date: Tue, Aug 3, 2010 at 12:25 AM Subject: Re: please, help with python 3.1 To: Chris Rebert Sorry, I will explain. I am using for a task 'find /' expecting this to last longer, usually much longer than 5 sec. If you run the code I sent in python 2.6, it will stop after 5 sec and print messages. If you run the same code in python3 (and if your task last more than 5 sec as expected, otherwise replace "cmd = 'find /'" with something suitable), python3 alarm doesn't work and the job is not stopped after 5 sec, taking minutes to finish. I hope it may help you to help me. Thanks, Alan On Tue, Aug 3, 2010 at 08:11, Chris Rebert wrote: > > On Mon, Aug 2, 2010 at 11:35 PM, Alan wrote: > > Hello List, > > Please, can someone at least try this code below in python 3 and report me > > back whether it works or not? Because for me this code works in python 2.6 > > but not with python 3.1. Thanks! > > Please specify *in exactly what way* the code is not working. > Is an exception being thrown? Then include the full traceback. > Is the behavior not what you expected/intended? Then say what it's > doing vs. what you want it to do. > > Cheers, > Chris > -- > Getting Debugging Help 101: Don't just say "there's a problem". Say > what the problem is. > http://blog.rebertia.com -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< From rantingrick at gmail.com Tue Aug 3 03:36:40 2010 From: rantingrick at gmail.com (rantingrick) Date: Tue, 3 Aug 2010 00:36:40 -0700 (PDT) Subject: Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning References: Message-ID: <96774aef-5dba-4db8-8d96-65d731148ef4@q35g2000yqn.googlegroups.com> On Aug 2, 5:32?pm, James Mills wrote: > On Tue, Aug 3, 2010 at 8:07 AM, ben owen wrote: > > Hi everyone, I'm new to this and was needing help with trying to learn/work > > with Python 2.7 on my computer. I'm running Windows 7 and trying to learn > > python programming from an older book from 1999 by Mark Lutz and David > > Ascher my boss gave me, First of all why are you trusting your boss to provide adequate manuals? Your boss is obviously an idiot because if he knew anything about Python then why would need you? And why the heck would he give you reading material that is 11 years old? All you have to do is type "Python Tutorial" into any search engine to find tons of tuts available. > > and for some reason none of my script/modules for > > the exercises are working on my comp. Mostly they give either a syntax error > > on the python command line or something about the file/module not being > > found on the windows command line. Changes were made in Python3.0 that are not backwards compatible. What version of Python do you have installed currently and what version is the tutorial/book intended for? These would be good questions to ask yourself. Be aware that current releases of Python2.7 and Python3.1.2 are available for download free of charge (psst: all you have to do is sign over your soul to Guido, but who needs a soul anyway?). Heck, at one time they were even giving out free t-shirts and coffee mugs to first 100 downloads. From clp2 at rebertia.com Tue Aug 3 03:39:45 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 00:39:45 -0700 Subject: Trying to set a cookie within a python script In-Reply-To: <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: 2010/8/2 ????? : >>On 2 ???, 23:57, Thomas Jollans wrote: > >> So: tripple-check that >> >> ?* your file is >> ?* Python knows that >> ?* the web browser knows that > > Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 / > n''' and it worked. > I'am still pretty confused about the encodings. > > Please tell me the difference between 3 things. > > a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 > without BOM. That affects what encoding the text file comprising the source code itself is in. > b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed > to tell browser that the contents of this python script as in UTF-8 > and to handle it as such? This tells Python what encoding the text file comprising the source code itself is in. > c) print ''' Content-Type: text/html; charset=UTF-8 /n''' This tells the web browser what encoding the HTML you're sending it is in. Said HTML is output by your Python script and must match the encoding you specify in (c). Unless you have Unicode string literals in the source code itself, (a) and (b) don't matter much. (c) is quite crucial. Cheers, Chris -- http://blog.rebertia.com From rantingrick at gmail.com Tue Aug 3 03:42:49 2010 From: rantingrick at gmail.com (rantingrick) Date: Tue, 3 Aug 2010 00:42:49 -0700 (PDT) Subject: please, help with python 3.1 References: Message-ID: On Aug 3, 2:28?am, Chris Rebert wrote: > ---------- Forwarded message ---------- > From: Alan > Date: Tue, Aug 3, 2010 at 12:25 AM > Subject: Re: please, help with python 3.1 > To: Chris Rebert > > Sorry, > I will explain. Well it looks like he forgot to post the traceback! From __peter__ at web.de Tue Aug 3 04:00:26 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Aug 2010 10:00:26 +0200 Subject: constructing and using large lexicon in a program References: <119487.45857.qm@web113614.mail.gq1.yahoo.com> Message-ID: Majdi Sawalha wrote: > I am developing a morphological analyzer that depends on a large lexicon. > i construct a Lexicon class that reades a text file and construct a > dictionary of the lexicon entries. > the other class will use the lexicon class to chech if the word is found > in the lexicon. the problem that this takes long time as each time an > object of that class created, then it needs to call the lexicon many > times. then when the lexicon is called it re-construct the lexicon again. > is there any way to construct the lexicon one time during the execution of > the program? and then the other modules will search the already > constructed lexicon. Normally you just structure your application accordingly. Load the dictionary once and then pass it around explicitly: import loader import user_one import user_two filename = ... large_dict = loader.load(filename) user_one.use_dict(large_dict) user_two.use_dict(large_dict) You may also try a caching scheme to avoid parsing the text file unless it has changed. Here's a simple example: $ cat cachedemo.py import cPickle as pickle import os def load_from_text(filename): # replace with your code with open(filename) as instream: return dict(line.strip().split(None, 1) for line in instream) def load(filename, cached=None): if cached is None: cached = filename + ".pickle" if os.path.exists(cached) and os.path.getmtime(filename) <= os.path.getmtime(cached): print "using pickle" with open(cached, "rb") as instream: return pickle.load(instream) else: print "loading from text" d = load_from_text(filename) with open(cached, "wb") as out: pickle.dump(d, out, pickle.HIGHEST_PROTOCOL) return d if __name__ == "__main__": if not os.path.exists("tmp.txt"): print "creating example data" with open("tmp.txt", "w") as out: out.write("""\ alpha value for alpha beta BETA gamma GAMMA """) print load("tmp.txt") $ python cachedemo.py creating example data loading from text {'alpha': 'value for alpha', 'beta': 'BETA', 'gamma': 'GAMMA'} $ python cachedemo.py using pickle {'alpha': 'value for alpha', 'beta': 'BETA', 'gamma': 'GAMMA'} $ echo 'delta modified text' >> tmp.txt $ python cachedemo.py loading from text {'alpha': 'value for alpha', 'beta': 'BETA', 'gamma': 'GAMMA', 'delta': 'modified text'} $ python cachedemo.py using pickle {'alpha': 'value for alpha', 'beta': 'BETA', 'gamma': 'GAMMA', 'delta': 'modified text'} Peter From davea at ieee.org Tue Aug 3 04:10:15 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 03 Aug 2010 04:10:15 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: <4C57CEE7.2090407@ieee.org> ????????????????????????????????? wrote: >> On 2 ???, 23:57, Thomas Jollans wrote: >> > > >> So: tripple-check that >> >> * your file is >> * Python knows that >> * the web browser knows that >> > > Thank you! i used print ''' Content-Type: text/html; charset=F-8 / > n''' and it worked. > I'am still pretty confused about the encodings. > > Please tell me the difference between 3 things. > > a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 > without BOM. > b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed > to tell browser that the contents of this python script as in UTF-8 > and to handle it as such? > c) print ''' Content-Type: text/html; charset=F-8 /n''' > > Please explain to me as simple as you can because from the time with > php and perl encodings not only gave me a hard time but also caused my > program to produce internal server errors so i need to understand the > differences. > > There actually should be more than 3 things here. To understand the distinctions you have to see who handles which data, and how. a) a text editor takes keystrokes and cut/paste info and other data, and produces a stream of (unicode) characters. It then encodes each of those character into one or more bytes and saves it to a file. You have to tell Notepad++ how to do that encoding. Note that unless it's saving a BOM, there's no clue in the file what encoding it used. b) The python compiler has to interpret the bytes it finds (spec. within string literals and comments), and decode them into unicode for its own work. It uses the 'coding:' comment to decide how to do this. But once the file has been compiled, that comment is totally irrelevant, and ignored. c1) Your python code has to decide how to encode its information when writing to stdout. There are several ways to accomplish that. c2) The browser sees only what was sent to stdout, starting with the "Content-Type..." line. It uses that line to decide how to decode the rest of the stream. Let me reemphasize, the browser does not see any of the python code, or comments. DaveA From s.selvamsiva at gmail.com Tue Aug 3 04:15:44 2010 From: s.selvamsiva at gmail.com (S.Selvam) Date: Tue, 3 Aug 2010 13:45:44 +0530 Subject: web and standalone access Message-ID: Hi all, I have a case where my application needs to run as a standalone application and also allow web based access. What could the best python framework to implement it. Note : I found Openobject( openerp ) to be of this kind. I hope i can get more ideas here . -- Regards, S.Selvam " I am because we are " -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Tue Aug 3 04:25:08 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 18:25:08 +1000 Subject: web and standalone access In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 6:15 PM, S.Selvam wrote: > I have a case where my application needs to run as a standalone application > and also allow web based access. > > What could the best python framework to implement it. Both CherryPy and circuits.web sport a "single click 'n run" capability using python's webbrowser module. 1. http://tools.cherrypy.org/wiki/SingleClickAndRun 2. http://bitbucket.org/prologic/circuits/src/tip/examples/web/singleclickandrun.py I'm sure there are many other suitable frameworks and way of doing this. I've been experimenting myself with embedded circuits.web with pygtk and webkit with some success (similar to Adobe Air). cheers James -- -- James Mills -- -- "Problems are solved by method" From nobody at nowhere.com Tue Aug 3 04:32:58 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 03 Aug 2010 09:32:58 +0100 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 02 Aug 2010 17:17:35 -0700, Peter wrote: > But I always used to tell > people - by the time I got a program to compile then I figured 99% of > the bugs were already discovered! Try that with C/C++ or almost any > other language you care to name :-) ML and Haskell are also quite good for this (although I wish they supported integer subranges). Also, the statelessness of FP eliminates entire classes of bugs. From nobody at nowhere.com Tue Aug 3 04:36:16 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 03 Aug 2010 09:36:16 +0100 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Mon, 02 Aug 2010 15:18:30 -0700, sturlamolden wrote: >> Has it ever been planned to rewrite in C++ the historical implementation >> (of course in an object oriented design) ? > > OO programming is possible in C. Just take a look at GNOME and GTK. One feature which can't readily be implemented in C is the automatic clean-up side of the RAII idiom. From clp2 at rebertia.com Tue Aug 3 04:37:14 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 01:37:14 -0700 Subject: Performance ordered dictionary vs normal dictionary In-Reply-To: References: <899AA0B8-A382-4B07-BC1B-7E9704F42A66@gmail.com> <8E369CBF-A2D2-406C-8AD6-22A85258D449@gmail.com> Message-ID: On Fri, Jul 30, 2010 at 9:18 PM, Dan Stromberg wrote: > On Wed, Jul 28, 2010 at 11:11 PM, Chris Rebert wrote: >> (You are aware that the "ordered" in OrderedDict means that its keys >> are ordered, and not that, say, a list containing OrderedDicts can be >> sorted, right?) > > > Actually, a collections.OrderedDict saves things not in key order, but in > chronological order: Well yeah, that's why I specifically said "ordered" as opposed to the less awkward and more obvious but completely inaccurate "sorted" (== your "key order"). - Chris From parvini_navid at yahoo.com Tue Aug 3 04:45:29 2010 From: parvini_navid at yahoo.com (Navid Parvini) Date: Tue, 3 Aug 2010 01:45:29 -0700 (PDT) Subject: PIL Message-ID: <882435.39022.qm@web51008.mail.re2.yahoo.com> Dear All, I want to convert a .png file to .xpm using PIL. I used the following command: Image.open( "t1.png").save("a1.xpm"). But it doesn't work and I could not convert it. Would you please help me and let me know that how can I convert/save .xpm files in PIL. Thank you in advance. Thanks. Navid -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Aug 3 04:46:21 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 01:46:21 -0700 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Tue, Aug 3, 2010 at 1:36 AM, Nobody wrote: > On Mon, 02 Aug 2010 15:18:30 -0700, sturlamolden wrote: >>> Has it ever been planned to rewrite in C++ the historical implementation >>> (of course in an object oriented design) ? >> >> OO programming is possible in C. ?Just take a look at GNOME and GTK. > > One feature which can't readily be implemented in C is the automatic > clean-up side of the RAII idiom. That's not directly related to object-orientation though. Cheers, Chris From nobody at nowhere.com Tue Aug 3 04:47:55 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 03 Aug 2010 09:47:55 +0100 Subject: checking that process binds a port, fuser functionality References: Message-ID: On Mon, 02 Aug 2010 23:27:37 +0200, Zdenek Maxa wrote: > I need to start a process (using subprocess.Popen()) and wait until the > new process either fails or successfully binds a specified port. The > fuser command seems to be indented exactly for this purpose. Could > anyone please provided a hint to a handy Python library to do this or > would the advice be to parse fuser command output? > > This needs to happen on Linux and Python 2.4. fuser (when applied to a TCP socket) scans /proc/net/tcp to obtain the inode number, then scans /proc/[1-9]*/fd/* for a reference to the inode. This requires sufficient privileges to enumerate the /proc//fd directories (i.e. if you aren't running as root, fuser will ignore any processes which you don't own). If you just need to wait until *something* is listening on that port, you could try connect()ing to it. Alternatively, you can monitor /proc/net/tcp until the relevant port appears. If you know which process will be using the port, you can just scan the /proc//fd directory for that process, rather than checking all processes. You still need to use /proc/net/tcp to obtain the inode number. From prologic at shortcircuit.net.au Tue Aug 3 04:48:24 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 18:48:24 +1000 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Tue, Aug 3, 2010 at 6:36 PM, Nobody wrote: > One feature which can't readily be implemented in C is the automatic > clean-up side of the RAII idiom. C is a Turing-Complete Language is it not ? If so, therefore is it not true "anything" can be implemented ? Even the "automated clean-up side of the RAIL idiom" ? cheers James -- -- James Mills -- -- "Problems are solved by method" From prologic at shortcircuit.net.au Tue Aug 3 04:55:14 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 18:55:14 +1000 Subject: PIL In-Reply-To: <882435.39022.qm@web51008.mail.re2.yahoo.com> References: <882435.39022.qm@web51008.mail.re2.yahoo.com> Message-ID: On Tue, Aug 3, 2010 at 6:45 PM, Navid Parvini wrote: > I want to convert a .png file to .xpm using PIL. I used the following > command: > Image.open( "t1.png").save("a1.xpm"). But it doesn't work and I could not > convert it. > > Would you please help me and let me know that how can I convert/save .xpm > files in PIL. > Reading PIL's documentation might help. Try: $ pydoc Image cheers James -- -- James Mills -- -- "Problems are solved by method" -------------- next part -------------- An HTML attachment was scrubbed... URL: From landimatte at gmail.com Tue Aug 3 04:55:25 2010 From: landimatte at gmail.com (Matteo Landi) Date: Tue, 3 Aug 2010 10:55:25 +0200 Subject: PIL In-Reply-To: <882435.39022.qm@web51008.mail.re2.yahoo.com> References: <882435.39022.qm@web51008.mail.re2.yahoo.com> Message-ID: I don't think yours is a permitted conversion[1]. It seems that PIL supports xpm format only for reading, but I could be wrong. Regards. [1] http://www.daniweb.com/forums/thread260074.html On Tue, Aug 3, 2010 at 10:45 AM, Navid Parvini wrote: > Dear All, > > I want to convert a .png file to .xpm using PIL. I used the following > command: > Image.open( "t1.png").save("a1.xpm"). But it doesn't work and I could not > convert it. > > Would you please help me and let me know that how can I convert/save .xpm > files in PIL. > > Thank you in advance. > > Thanks. > Navid > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Matteo Landi http://www.matteolandi.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Aug 3 04:56:20 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 01:56:20 -0700 Subject: PIL In-Reply-To: <882435.39022.qm@web51008.mail.re2.yahoo.com> References: <882435.39022.qm@web51008.mail.re2.yahoo.com> Message-ID: On Tue, Aug 3, 2010 at 1:45 AM, Navid Parvini wrote: > Dear All, > > I want to convert a .png file to .xpm using PIL. I used the following command: > Image.open( "t1.png").save("a1.xpm"). But it doesn't work and I could not convert it. > > Would you please help me and let me know that how can I convert/save .xpm files in PIL. PIL only supports reading .XPM, not writing .XPM: http://www.pythonware.com/library/pil/handbook/format-xpm.htm Cheers, Chris -- http://blog.rebertia.com From steve-REMOVE-THIS at cybersource.com.au Tue Aug 3 05:04:08 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2010 09:04:08 GMT Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: <4c57db88$0$11101$c3e8da3@news.astraweb.com> On Tue, 03 Aug 2010 18:48:24 +1000, James Mills wrote: > On Tue, Aug 3, 2010 at 6:36 PM, Nobody wrote: >> One feature which can't readily be implemented in C is the automatic >> clean-up side of the RAII idiom. > > C is a Turing-Complete Language is it not ? > > If so, therefore is it not true "anything" can be implemented ? Even the > "automated clean-up side of the RAIL idiom" ? True, but Nobody said it can't *readily* be implemented, not that it can't be. -- Steven From nikos.the.gr33k at gmail.com Tue Aug 3 05:06:05 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Tue, 03 Aug 2010 12:06:05 +0300 Subject: Trying to set a cookie within a python script In-Reply-To: References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: <4C57DBFD.5040107@gmail.com> ???? 3/8/2010 10:39 ??, ?/? Chris Rebert ??????: >> Please tell me the difference between 3 things. >> >> a) Asking Notepad++(my editor) to save all my python scripts as UTF-8 >> without BOM. > That affects what encoding the text file comprising the source code > itself is in. What does this practically mean? Perhaps you mean that it affects the way this file will be stored in the hard disk? For example is it different to say to Notapad++ to save it as 'Asci'i and different to save it as 'UTF-8 without BOM'? What should i use? My script only containes python code(english) and greek chars inside print statemetns. >> b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed >> to tell browser that the contents of this python script as in UTF-8 >> and to handle it as such? > This tells Python what encoding the text file comprising the source > code itself is in. > What practically does this mean? What difference does it have with (a) ? >> c) print ''' Content-Type: text/html; charset=UTF-8 /n''' > This tells the web browser what encoding the HTML you're sending it is > in. Said HTML is output by your Python script and must match the > encoding you specify in (c). When a python script runs it produces html output or only after the python's output to the Web Server the html output is produced? From steve-REMOVE-THIS at cybersource.com.au Tue Aug 3 05:07:29 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2010 09:07:29 GMT Subject: please, help with python 3.1 References: Message-ID: <4c57dc50$0$11101$c3e8da3@news.astraweb.com> Hello Alan, I'm sorry, I can't see the code you say you posted. I can't see ANY of your posts, only the replies from Chris Rebert. Are you using Google Groups to post? If so, many people here will have difficulty seeing your posts, as Google Groups is notorious for allowing spammers, and in self-defence many mailing lists and newsgroups just ignore anything from Google Groups. Looking at the message Chris forwarded: [quote] I am using for a task 'find /' expecting this to last longer, usually much longer than 5 sec. If you run the code I sent in python 2.6, it will stop after 5 sec and print messages. If you run the same code in python3 (and if your task last more than 5 sec as expected, otherwise replace "cmd = 'find /'" with something suitable), python3 alarm doesn't work and the job is not stopped after 5 sec, taking minutes to finish. [end quote] I'm sorry, but I can't make heads or tails of that. At the very least, you need to explain what code you are using, and what the problem is. What do you mean "python3 alarm doesn't work"? What alarm? What do you mean it doesn't work? Just saying "it doesn't work" is pointless. Is the problem that your code runs in seconds under Python 2.6 and takes minutes under Python 3.1? Are you sure you are using 3.1 and not 3.0? 3.0 is VERY slow and should be avoided. We may need to see your code, and some sample data, in order to have any hope of helping you. Regards, Steven. On Tue, 03 Aug 2010 00:28:04 -0700, Chris Rebert wrote: > ---------- Forwarded message ---------- From: Alan > > Date: Tue, Aug 3, 2010 at 12:25 AM > Subject: Re: please, help with python 3.1 To: Chris Rebert > > > Sorry, > I will explain. I am using for a task 'find /' expecting this to last > longer, usually much longer than 5 sec. If you run the code I sent in > python 2.6, it will stop after 5 sec and print messages. > If you run the same code in python3 (and if your task last more than 5 > sec as expected, otherwise replace "cmd = 'find /'" with something > suitable), python3 alarm doesn't work and the job is not stopped after 5 > sec, taking minutes to finish. > I hope it may help you to help me. > Thanks, > Alan > > On Tue, Aug 3, 2010 at 08:11, Chris Rebert wrote: >> >> On Mon, Aug 2, 2010 at 11:35 PM, Alan wrote: >> > Hello List, >> > Please, can someone at least try this code below in python 3 and >> > report me back whether it works or not? Because for me this code >> > works in python 2.6 but not with python 3.1. Thanks! >> >> Please specify *in exactly what way* the code is not working. Is an >> exception being thrown? Then include the full traceback. Is the >> behavior not what you expected/intended? Then say what it's doing vs. >> what you want it to do. >> >> Cheers, >> Chris >> -- >> Getting Debugging Help 101: Don't just say "there's a problem". Say >> what the problem is. >> http://blog.rebertia.com -- Steven From prologic at shortcircuit.net.au Tue Aug 3 05:23:00 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 3 Aug 2010 19:23:00 +1000 Subject: Why is python not written in C++ ? In-Reply-To: <4c57db88$0$11101$c3e8da3@news.astraweb.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> <4c57db88$0$11101$c3e8da3@news.astraweb.com> Message-ID: On Tue, Aug 3, 2010 at 7:04 PM, Steven D'Aprano wrote: > True, but Nobody said it can't *readily* be implemented, not that it > can't be. So he did too :) I read that as "really" :/ --James -- -- James Mills -- -- "Problems are solved by method" From awilter at ebi.ac.uk Tue Aug 3 05:28:49 2010 From: awilter at ebi.ac.uk (Alan Wilter Sousa da Silva) Date: Tue, 3 Aug 2010 10:28:49 +0100 Subject: please, help with python 3.1 In-Reply-To: References: Message-ID: Ok: Here goes the code again and results: from __future__ import print_function import os, subprocess, signal def signal_handler( signum, frame ): print( "PID: %s" % pid ) print( "Timed out! Process %s killed, max exec time (%ss) exceeded" % (pid, timeTol ) ) os.kill( int( pid ), 15 ) raise Exception( "Taking too long to finish... aborting!" ) if __name__ == '__main__': timeTol = 5 cmd = 'find /' signal.signal(signal.SIGALRM, signal_handler) signal.alarm(timeTol) p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout = subprocess.PIPE) pid = p.pid out = str( p.communicate()[0].decode() ) print(out) ---------------------------------------------------- time python2.6 timout.py PID: 27644 Timed out! Process 27644 killed, max exec time (5s) exceeded Traceback (most recent call last): File "timout.py", line 23, in out = str( p.communicate()[0].decode() ) File "/sw/lib/python2.6/subprocess.py", line 693, in communicate stdout = self.stdout.read() File "timout.py", line 9, in signal_handler raise Exception( "Taking too long to finish... aborting!" ) Exception: Taking too long to finish... aborting! python2.6 timout.py 0.10s user 0.47s system 11% cpu 5.113 total #### WORKED as expected #### ---------------------------------------------------- Now with python3.1: ---------------------------------------------------- time python3.1 timout.py PID: 27687 Timed out! Process 27687 killed, max exec time (5s) exceeded Traceback (most recent call last): File "timout.py", line 23, in out = str( p.communicate()[0].decode() ) File "/sw/lib/python3.1/subprocess.py", line 719, in communicate stdout = self.stdout.read() File "timout.py", line 9, in signal_handler raise Exception( "Taking too long to finish... aborting!" ) Exception: Taking too long to finish... aborting! python3.1 timout.py 0.52s user 3.88s system 19% cpu 22.841 total #### It prints essentially the same thing with a *very* *big* difference it takes 22 seconds and actually the alarm only works when the whole task ('find /') is finished. ---------------------------------------------------- I hope it's better now. Thanks, Alan On Tue, Aug 3, 2010 at 08:42, rantingrick wrote: > On Aug 3, 2:28 am, Chris Rebert wrote: > > ---------- Forwarded message ---------- > > From: Alan > > Date: Tue, Aug 3, 2010 at 12:25 AM > > Subject: Re: please, help with python 3.1 > > To: Chris Rebert > > > > Sorry, > > I will explain. > > Well it looks like he forgot to post the traceback! > -- > http://mail.python.org/mailman/listinfo/python-list > -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at castleamber.com Tue Aug 3 05:29:35 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 04:29:35 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> Message-ID: <87d3u0niww.fsf@castleamber.com> Carl Banks writes: > On Aug 1, 6:09?pm, John Bokma wrote: >> Roy Smith writes: >> > In article <4c55fe82$0$9111$426a3... at news.free.fr>, >> > ?candide wrote: >> >> >> Python is an object oriented langage (OOL). The Python main >> >> implementation is written in pure and "old" C90. Is it for historical >> >> reasons? >> >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> >> suitable to implement an OOL with another one. >> >> > One thing that comes to mind is that it's much easier to distribute C >> > libraries than C++ libraries. >> >> In the beginning of C++ there were programs that just converted C++ to C >> (frontends). At least that is how the C++ compiler Acorn sold worked. >> So I don't think your argument was much true back then. > > No, it was that way back then too. They might all generate C code but > different C code by different backends wouldn't be able to call each > other natively. If you convert C++ to C, and compile the C code then that's not different from compiling the C code itself, correct? > For instnace the function > > int foo(int); > > might be name-mangled this way in one cfront: > > foo$d > > and this way in another: > > ____int_foo__int_i But they call both the C libraries in the same way. > The virtual table of this class: > > class Bar { > virtual int foo(int); > virtual int bar(int); > }; > > might be generated like this in one cfront: > > struct Bar$$Vtable$ { > int (*Bar$$bar$d)(int); > int (*Bar$$foo$d)(int); > }; > > and like this in another: > > struct ____class_Foo___vtable_ { > int (*foo)(int); > int (*bar)(int); > }; > > > So, just because they both generated C code, it doesn't mean they can > call one another. Why would they need to call each other? The compiled C++ code ends up as being compiled generated C code. It has been a while, but I am quite sure that the Acorn C++ front end I used could dump the actual generated C code. And this generated code should compile with a normal C compiler on a different platform. The only exception I can think of is if the front end comes with libraries you have to link against. But since this should be C as well (since there is no native C++), I don't see any problem to recreate those libraries. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From jeanmichel at sequans.com Tue Aug 3 05:33:36 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 03 Aug 2010 11:33:36 +0200 Subject: namespaces, scoping and variables In-Reply-To: <48558d95-aaaa-4a6e-9ffb-68d4f2429c62@w15g2000pro.googlegroups.com> References: <7058161A-1CF5-4175-A46F-5155F610AF93@labr.net> <4C572486.1030308@mrabarnett.plus.com> <48558d95-aaaa-4a6e-9ffb-68d4f2429c62@w15g2000pro.googlegroups.com> Message-ID: <4C57E270.7000201@sequans.com> rantingrick wrote: > On Aug 2, 3:12 pm, Chris Hare wrote: > > Also you should use 4 space indention and never use tabs. This is the > accepted way. Then ask yourself why tabs are still in python 3. Nice troll by the way. JM From john at castleamber.com Tue Aug 3 05:34:49 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 04:34:49 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <877hk8nio6.fsf@castleamber.com> Albert Hopkins writes: > But I wonder if someone has/has tried to write a programming language in > C++ and what were their experiences. The Low Level Virtual Machine (LLVM) is a compiler infrastructure, written in C++, which is designed for compile-time, link-time, run-time, and "idle-time" optimization of programs written in arbitrary programming languages. Originally implemented for C/C++, the language-independent design (and the success) of LLVM has since spawned a wide variety of front ends, including Objective-C, Fortran, Ada, Haskell, Java bytecode, Python, Ruby, ActionScript, GLSL, and others. http://en.wikipedia.org/wiki/LLVM Unladen Swallow is a branch of Python intended to be fully compatible and significantly faster. It uses LLVM's optimization passes and JIT compiler. http://llvm.org/ProjectsWithLLVM/#unladenswallow -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From john at castleamber.com Tue Aug 3 05:38:35 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 04:38:35 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> Message-ID: <8739uwnihw.fsf@castleamber.com> Michael Torrie writes: > On 08/01/2010 07:09 PM, John Bokma wrote: >>> One thing that comes to mind is that it's much easier to distribute C >>> libraries than C++ libraries. >> >> In the beginning of C++ there were programs that just converted C++ to C >> (frontends). At least that is how the C++ compiler Acorn sold worked. >> So I don't think your argument was much true back then. > > No, he is still right. Each C++ implementation did name mangling > differently leading to "C" libraries that had incompatible names and > signatures. Also each frontend could have generated incompatible > vtables and other C++ structures. So C code generated by one C++ > frontend could not easily call C code generated by another C++ frontend. > So the same arguments that are made about C++ now were just as valid > back then when C++ was merely a fancy preprocessor. See my other post: I understand that two C++ preprocessors can't call each others generated code, but if one uses C++ and knows that one can only use shared C libraries on target systems, and not C++ libraries that might be present (or more likely not: C++ was new in those days). -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From nobody at nowhere.com Tue Aug 3 05:45:06 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 03 Aug 2010 10:45:06 +0100 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: On Tue, 03 Aug 2010 18:48:24 +1000, James Mills wrote: >> One feature which can't readily be implemented in C is the automatic >> clean-up side of the RAII idiom. > > C is a Turing-Complete Language is it not ? > > If so, therefore is it not true "anything" can be implemented ? > Even the "automated clean-up side of the RAIL idiom" ? By "automated", I mean the fact that destructors get called automatically when a local variable goes out of scope, whether by reaching the end of the block, return, break, continue, or an exception. In C, the clean-up has to be made explicit, i.e. not "automated". From no.email at nospam.invalid Tue Aug 3 05:48:30 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 02:48:30 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: <7xy6co6n81.fsf@ruckus.brouhaha.com> Nobody writes: > One feature which can't readily be implemented in C is the automatic > clean-up side of the RAII idiom. I once did that by having an explicit stack of finalization records linked through the call stack. The "throw" routine would traverse the links to call the finalizers, until it found the matching "catch" which contained a longjmp target. It wasn't as crazy as this makes it sound. From jeanmichel at sequans.com Tue Aug 3 06:09:21 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 03 Aug 2010 12:09:21 +0200 Subject: simple (I hope!) problem In-Reply-To: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> Message-ID: <4C57EAD1.5090709@sequans.com> samwyse wrote: > I'm writing for the Google app engine and have stubbed my toe yet > again on a simple obstacle. Non-trivial app engines programs require > the import of several modules that aren't normally in my PYTHONPATH. > I'd like to be able to test my code outside of the app engine > framework. I've tried several solutions in the past that worked but > weren't particularly elegant or portable. Now I've had a new idea. > Here's my latest attempt: > > import os, re > if __name__ == '__main__': > pass > else > from google.appengine.ext import webapp > register = webapp.template.create_template_register() > > This works great, except my code makes use of the resister object in > several places, like this: > > register.filter(emptylines) > > Fortunately, I don't need the functionality of the object, I just want > something that won't generate an error when I use it. So, what is the > quickest way to to create such an object (replacing the 'pass' in my > first snippet). My solution is this: > > class C: > def filter(self, *args, **kwds): > pass > register = C() > > but it seems like I should be able to do something "better", as > measured by lines of code, faking more than just a 'filter' method, or > both. Any ideas? Thanks! > here is a class that accepts any method call without generating an error: class Stub(object): @staticmethod def stub(*arg, **kwarg): pass def __getattribute__(self, name): return Stub.stub s = Stub() s.foo('bar') s.bar s.bar('', '', 5) JM From a.pfrengle at gmail.com Tue Aug 3 06:15:56 2010 From: a.pfrengle at gmail.com (Andreas Pfrengle) Date: Tue, 3 Aug 2010 03:15:56 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> Message-ID: On 3 Aug., 03:22, Carl Banks wrote:> > You are creating an object that differs from a built-in, int, in a > highly misleading way that only makes sense in a very limited context, > and this object's modified behavior gives no clue that it's been > modified in such as way. ?(That is, it's not possible to tell if the > object's not a regular int just by looking at __str__()'s return > value.) ?To make matters worse, you want to program this object to > coerce other integers, so there's a risk of these objects escaping > from the context where they make sense. > > This is just a bad idea. ?The type is not the place to implement > behavior that makes sense only in a limited context. ?Instead, do > something like this: > > print "Item %d is %s." % (i+1, s[i]) I see your concerns. I started with the approach to add +1 directly before displaying the int. However, since there are some variables that shall be displayed normally and others that are indices I want to show starting at 1, I thought the easiest way would be to define a type that does the job, then I would only need to define it once and not take care everywhere whether I have a normal variable or a displayed index. Thinking about it, it might really be dangerous to coerce always to int1, since sometimes I might want a normal int as result (I can't tell yet for sure). I'm just thinking about only overloading the operations if the int1 is on the left-hand side (so __op__ coerces to int1, while __rop__ doesn't). This would make operations non-commutative - but I also would need to put more brains in every calculation, which could finally take more effort than only "upgrading" the display :-??? Seems I end up with your suggestion - if noone else has an idea ;-) The application will be a browsergame, and most gamers start counting at 1, so they would probably wonder about a "level 0 item" ;-) If there didn't already exist lots of code, I would redesign the whole data-structure - I think that's "lessons learned" for the next project -.- From jldunn2000 at gmail.com Tue Aug 3 06:21:07 2010 From: jldunn2000 at gmail.com (loial) Date: Tue, 3 Aug 2010 03:21:07 -0700 (PDT) Subject: Get name of file from directory into variable Message-ID: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> In a unix shell script I can do something like this to look in a directory and get the name of a file or files into a variable : MYFILE=`ls /home/mydir/JOHN*.xml` Can I do this in one line in python? From alex at moreati.org.uk Tue Aug 3 06:31:02 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 3 Aug 2010 03:31:02 -0700 (PDT) Subject: Get name of file from directory into variable References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: On Aug 3, 11:21?am, loial wrote: > In a unix shell script I can do something like this to look in a > directory and get the name of a file or files into a variable : > > MYFILE=`ls /home/mydir/JOHN*.xml` > > Can I do this in one line in python? Depends if you count imports. import glob my_files = glob.glob('/home/mydir/JOHN*.xml') Regards, Alex From landimatte at gmail.com Tue Aug 3 06:34:43 2010 From: landimatte at gmail.com (Matteo Landi) Date: Tue, 3 Aug 2010 12:34:43 +0200 Subject: Get name of file from directory into variable In-Reply-To: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: I suggest you to take a look at walk function inside the os module [1]; IIRC, on the list you would find a discussion on how to create a wrapper for os.walk with support for filters or wildcards. Regards. [1] http://docs.python.org/library/os.html?highlight=os.walk#os.walk On Tue, Aug 3, 2010 at 12:21 PM, loial wrote: > In a unix shell script I can do something like this to look in a > directory and get the name of a file or files into a variable : > > MYFILE=`ls /home/mydir/JOHN*.xml` > > > Can I do this in one line in python? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From jldunn2000 at gmail.com Tue Aug 3 06:41:00 2010 From: jldunn2000 at gmail.com (loial) Date: Tue, 3 Aug 2010 03:41:00 -0700 (PDT) Subject: Get name of file from directory into variable References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: <9aec7fa4-a8a5-4dfc-9376-a93e13e93d18@u26g2000yqu.googlegroups.com> On 3 Aug, 11:31, Alex Willmer wrote: > On Aug 3, 11:21?am, loial wrote: > > > In a unix shell script I can do something like this to look in a > > directory and get the name of a file or files into a variable : > > > MYFILE=`ls /home/mydir/JOHN*.xml` > > > Can I do this in one line in python? > > Depends if you count imports. > > import glob > my_files = glob.glob('/home/mydir/JOHN*.xml') > > Regards, Alex Cheers From rory at campbell-lange.net Tue Aug 3 06:44:10 2010 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Tue, 3 Aug 2010 11:44:10 +0100 Subject: Get name of file from directory into variable In-Reply-To: References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: <20100803104410.GA21889@campbell-lange.net> On 03/08/10, Alex Willmer (alex at moreati.org.uk) wrote: > On Aug 3, 11:21?am, loial wrote: > > In a unix shell script I can do something like this to look in a > > directory and get the name of a file or files into a variable : > > > > MYFILE=`ls /home/mydir/JOHN*.xml` > > > > Can I do this in one line in python? > > import glob > my_files = glob.glob('/home/mydir/JOHN*.xml') import os; my_files = [f for f in os.listdir('/home/mydir/') if 'JOHN' in f and 'xml' in f] But in fact glob uses os.listdir and fnmatch.fnmatch functions internally, so is definitely the way to go. http://docs.python.org/library/glob.html -- Rory Campbell-Lange rory at campbell-lange.net From roy at panix.com Tue Aug 3 07:06:27 2010 From: roy at panix.com (Roy Smith) Date: Tue, 03 Aug 2010 07:06:27 -0400 Subject: checking that process binds a port, fuser functionality References: Message-ID: In article , Nobody wrote: > On Mon, 02 Aug 2010 23:27:37 +0200, Zdenek Maxa wrote: > > > I need to start a process (using subprocess.Popen()) and wait until the > > new process either fails or successfully binds a specified port. > > If you just need to wait until *something* is listening on that port, you > could try connect()ing to it. This certainly seems like the logical way to me. It's straight-forward, simple, and portable. From landimatte at gmail.com Tue Aug 3 07:14:29 2010 From: landimatte at gmail.com (Matteo Landi) Date: Tue, 3 Aug 2010 13:14:29 +0200 Subject: Get name of file from directory into variable In-Reply-To: <20100803104410.GA21889@campbell-lange.net> References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> <20100803104410.GA21889@campbell-lange.net> Message-ID: Ops I miss the "one line" request, so my previous answer was definitely OT. glob seems to be your solution. On Tue, Aug 3, 2010 at 12:44 PM, Rory Campbell-Lange wrote: > On 03/08/10, Alex Willmer (alex at moreati.org.uk) wrote: >> On Aug 3, 11:21?am, loial wrote: >> > In a unix shell script I can do something like this to look in a >> > directory and get the name of a file or files into a variable : >> > >> > MYFILE=`ls /home/mydir/JOHN*.xml` >> > >> > Can I do this in one line in python? >> >> import glob >> my_files = glob.glob('/home/mydir/JOHN*.xml') > > import os; my_files = [f for f in os.listdir('/home/mydir/') if 'JOHN' in f and 'xml' in f] > > But in fact glob uses os.listdir and fnmatch.fnmatch functions > internally, so is definitely the way to go. > > http://docs.python.org/library/glob.html > > -- > Rory Campbell-Lange > rory at campbell-lange.net > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From magguru.chinnamnaidu at gmail.com Tue Aug 3 07:15:46 2010 From: magguru.chinnamnaidu at gmail.com (paypal cash) Date: Tue, 3 Aug 2010 04:15:46 -0700 (PDT) Subject: I GOT $2500 FROM PAYPAL.... Message-ID: <359ecaa3-ff1a-4939-873e-5555ee83d47b@f20g2000pro.googlegroups.com> I GOT $2500 FROM PAYPAL At http://2050videos.co.cc i have hidden the PayPal Form link in an image. in that website On Top Side Above search box , click on image and enter your PayPal id And Your name. From chare at labr.net Tue Aug 3 07:19:54 2010 From: chare at labr.net (Chris Hare) Date: Tue, 03 Aug 2010 06:19:54 -0500 Subject: calling a class method from a menu in a different class In-Reply-To: References: Message-ID: <778AE856-C4E8-4693-9159-537D3D0C7E6A@labr.net> No offense taken. I'll get getting the Google Python Style Guide today. I'll package up the code tonight and it to the group. Fortunately ( or unfortunately), it is all in one file right now. On Aug 2, 2010, at 10:31 PM, rantingrick wrote: > > Chris, > > It looks as if you are calling a class object and not an instance > object. However i cannot be for sure because you are using improper > Python style. All classes should be capwords. But here again you have > used camelcase for the class identifiers "radarWidgets" and > "mainDisplay", which is bad bad bad!! > > You been asking multiple questions about this code for the last couple > of days (and thats fine). However, maybe you would do everyone a favor > by posting the entire code so we can offer suggestions. Just seeing > seeing a snipit here and a snipit there is not helping because we > don't know where else you may be screwing up that we cannot see. > > It seems you're committing many faux pas with not only your coding > style but also your coding practices. I've seen overuse of globals and > bad styles and on and on. So post the entire code so myself and others > can go through this mess and get it sorted out. If you keep on with > your bad habits you're never going to become proficient with Python. > > I am sorry if this post seems condescending because that is not the > case. > -- > http://mail.python.org/mailman/listinfo/python-list From chare at labr.net Tue Aug 3 07:30:56 2010 From: chare at labr.net (Chris Hare) Date: Tue, 03 Aug 2010 06:30:56 -0500 Subject: calling a class method from a menu in a different class In-Reply-To: References: Message-ID: <2A9644F5-6668-4584-8D73-A99B13DBB144@labr.net> Oh and Risk, I know I was calling the class object. class 1 creates the instance object class 2 tries to use the instance object so the problem is how to make class 2 knowledgable of instance object? I guess I could pass the instance object into the class, since class1 creates the instance and also calls class 2. On Aug 2, 2010, at 10:31 PM, rantingrick wrote: > > Chris, > > It looks as if you are calling a class object and not an instance > object. However i cannot be for sure because you are using improper > Python style. All classes should be capwords. But here again you have > used camelcase for the class identifiers "radarWidgets" and > "mainDisplay", which is bad bad bad!! > > You been asking multiple questions about this code for the last couple > of days (and thats fine). However, maybe you would do everyone a favor > by posting the entire code so we can offer suggestions. Just seeing > seeing a snipit here and a snipit there is not helping because we > don't know where else you may be screwing up that we cannot see. > > It seems you're committing many faux pas with not only your coding > style but also your coding practices. I've seen overuse of globals and > bad styles and on and on. So post the entire code so myself and others > can go through this mess and get it sorted out. If you keep on with > your bad habits you're never going to become proficient with Python. > > I am sorry if this post seems condescending because that is not the > case. > -- > http://mail.python.org/mailman/listinfo/python-list From tania786786 at gmail.com Tue Aug 3 07:45:30 2010 From: tania786786 at gmail.com (tania tani) Date: Tue, 3 Aug 2010 04:45:30 -0700 (PDT) Subject: JUST TAKE 1 MIN ADD .AND GET 10 $ PER ADD $ 50 % OF THE REF.....ITS FREE Message-ID: <8e1a64ef-9e94-45ea-91ef-38e6b3ed2406@q16g2000prf.googlegroups.com> http://www.fineptc.com/index.php?ref=imranraza460 Hello my dear friend I hope you will be fine. i want to tell you the authentic way to make money with no investment . 1 just click on the obove link 2 create your account on the website. 3 then click on the "" view adds"" tab 4 There will be 6 or seven adds 5 click on a particular add and watch it for 1 min .. 6 this one minute add will give you 10 dollars 7 hence watch other adds one by one 8 finally you will find 60 dollars on you status by checking "' my account "' 9 You have earn 60 dollars you can repeat you view adds again on next day moreover if you introduce a new guy with your reffence you will be entitled to get 50% of the reffferl.....................trust me its free and its really works CLICK ON THE ABOVE LINK..........RIGHT NOW also try this link as anotherhttp://www.bigextracash.com/aft/9b6cc578.html From solipsis at pitrou.net Tue Aug 3 07:45:31 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Tue, 3 Aug 2010 13:45:31 +0200 Subject: please, help with python 3.1 References: Message-ID: <20100803134531.49ca4892@pitrou.net> On Tue, 3 Aug 2010 10:28:49 +0100 Alan Wilter Sousa da Silva wrote: > Now with python3.1: > > ---------------------------------------------------- > time python3.1 timout.py > PID: 27687 > Timed out! Process 27687 killed, max exec time (5s) exceeded > Traceback (most recent call last): > File "timout.py", line 23, in > out = str( p.communicate()[0].decode() ) > File "/sw/lib/python3.1/subprocess.py", line 719, in communicate > stdout = self.stdout.read() > File "timout.py", line 9, in signal_handler > raise Exception( "Taking too long to finish... aborting!" ) > Exception: Taking too long to finish... aborting! > python3.1 timout.py 0.52s user 3.88s system 19% cpu 22.841 total > > #### It prints essentially the same thing with a *very* *big* difference it > takes 22 seconds and actually the alarm only works when the whole task > ('find /') is finished. This seems to be a bug. Can you report it at http://bugs.python.org ? Thanks Antoine. From mohseni.aref at gmail.com Tue Aug 3 08:16:21 2010 From: mohseni.aref at gmail.com (Mohseniaref) Date: Tue, 3 Aug 2010 05:16:21 -0700 (PDT) Subject: how can I solve this erorr usr/lib/python2.6 : permisson denied References: <43e2d3fb-a0f9-468c-bd64-4516eed7dec5@u38g2000prh.googlegroups.com> <4c5617bc$0$11113$c3e8da3@news.astraweb.com> Message-ID: thanks I fix it and change path to bin folder From wherespythonmonks at gmail.com Tue Aug 3 08:46:16 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Tue, 3 Aug 2010 08:46:16 -0400 Subject: subclassing versus object redefinition Message-ID: Hi! I have a class (supposed to be an abstract base class): In python (as opposed to static languages like C++) I don't seed to subclass the base class, but instead I can simply override the behavior of stub methods and values. Is there a preference between between subclassing (C++ approach) and overriding methods/data in an instance? From a design perspective? I think I prefer the override/redefine approach because it result in a thinner class hierarchy. It seems like inheriting an ABC is needed only when I must share instances (between multiple parts of the code, or if the subclass is instantiated in different places...) Thoughts? W From rantingrick at gmail.com Tue Aug 3 09:06:14 2010 From: rantingrick at gmail.com (rantingrick) Date: Tue, 3 Aug 2010 06:06:14 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> Message-ID: <6d669b8a-f61d-4053-83e6-88ebae39770e@u26g2000yqu.googlegroups.com> > On Aug 3, 5:15?am, Andreas Pfrengle wrote: > > Seems I end up with your suggestion - if noone else has an idea ;-) START_COUNTING_FROM_HERE = 1 From fabiofz at gmail.com Tue Aug 3 09:12:26 2010 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 3 Aug 2010 10:12:26 -0300 Subject: Pydev 1.6.1 Released Message-ID: Hi All, Pydev 1.6.1 has been released Details on Pydev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: ------------------------------- * **Debugger** * **Critical Fix: issue that prevented the debugger from working with Python 3 solved** * Improving socket connection handling * **Launching** * Restart last launch and terminate all launches actions created * Restart last: **Ctrl+Shift+F9** (in pydev editor) * Terminate all: **Ctrl+Alt+F9** (in pydev editor) * Buttons were also added to pydev consoles * **Utilities** * **2to3**: Right-clicking a folder or file will show an option in the Pydev menu to convert from python 2 to python 3 (note that lib2to3 must available in the python installation). * Defining execfile in a Python 3 interactive console so that Ctrl+Alt+Enter works. * Fixed issue in the code style preferences page (switched value shown). * com.ziclix.python.sql added to the forced builtins in a Jython install by default. * Improved some icons when on a dark theme (patch from Kenneth Belitzky) What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer Aptana http://aptana.com/ Pydev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com From benedict.verheyen at gmail.com Tue Aug 3 09:16:11 2010 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Tue, 03 Aug 2010 15:16:11 +0200 Subject: cPickle error when caching data Message-ID: Hi i get the following error when trying to set data in the cache of a django application. The error is however a python error as it involves pickling and i can reproduce it in a shell. The error i get is this: cPickle.PicklingError: Can't pickle : attribute lookup management.views.Stats failed Stats is a class i use to hold a couple of values, a string (user) and a number (calls), that are then used in a template. These are pickable, right? The data i want to pickle is the return value of this function: def calc_stats_topcallers(): stats_all = {} # cPickle doesn't like this class class Stats(object): def __init__(self): self.calls = None self.user = None current_year = datetime.datetime.now().year archive_year = current_year - 4 years = xrange(archive_year, current_year+1) for year in years: stats_year = [] counts = {} # Initialize count dict # If we don't do this, we get a KeyError for user in User.objects.all(): counts[user]=0 # Count the times an initiator has been calling for i in Call.objects.filter(date_created__year=year): for _init in i.initiator.all(): counts[_init] += 1 # Sort the dictionary count_sorted = sorted(counts.items(), lambda x, y: cmp(x[1], y[1]), reverse=True) # Take top 30 callers for user_stat in count_sorted[0:30]: if ( user_stat[1] > 0 ): st = Stats() st.calls = user_stat[1] st.user = user_stat[0] stats_year.append(st) stats_all[year]=stats_year stats_sorted = sorted(stats_all.items(), lambda x, y: cmp(x[0], y[0]), reverse=True) return stats_sorted When i run the function and pickle the data using a python shell, i get the error. How do i solve this as i haven't got a clue. Thanks, Benedict From nikos.the.gr33k at gmail.com Tue Aug 3 09:24:44 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Tue, 3 Aug 2010 06:24:44 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: > On 3 ???, 11:10, Dave Angel wrote: > a) a text editor takes keystrokes and cut/paste info and other data, and > produces a stream of (unicode) characters. ?It then encodes each of ? > those character into one or more bytes and saves it to a file. ?You have > to tell Notepad++ how to do that encoding. ?Note that unless it's saving > a BOM, there's no clue in the file what encoding it used. So actually when i'm selecting an encoding from Notepad++'s options iam basically telling the editor the way the it's suppose to store those streams of characters to the hard disk drive. Different encodings equals different ways of storting the data to the media, correct? > b) The python compiler has to interpret the bytes it finds (spec. within > string literals and comments), and decode them into unicode for its own > work. ?It uses the 'coding:' comment to decide how to do this. ?But once > the file has been compiled, that comment is totally irrelevant, and ignored. What is a "String Literal" ? Basically if i understood you right, this line of code tells Python the opposite thign from (a). (a) told the editor how to store data to the media, while (b) tells the python compiler how to retrive these data from the media(how to read it, that is!) Right? > c1) Your python code has to decide how to encode its information when > writing to stdout. ?There are several ways to accomplish that. what other ways except the prin '''Content-Type blah blah... ''' ? > c2) The browser sees only what was sent to stdout, starting with the > "Content-Type..." line. ?It uses that line to decide how to decode the > rest of the stream. ?Let me reemphasize, the browser does not see any of > the python code, or comments. I was under the impression the the stdout of a cgi python script was the web server itself since this is the one app that awaits for the data to be displayed. When a python script runs it produces html output that time or only after the python's output to the Web Server the html output is produced? And something else please. My cgi python scripts contains english and greek letters, hence this is an indication of tellign the editor to save the file to disk as utf-8 right? Well i told Notepad++ to save ti as Ascii and also removed the '# -*- coding: utf-8 -*-' line. and only used print ''' Content-Type: text/html; charset=UTF-8 /n''' So, how the editor managed to save the file as ascii although my file coaniens characters that are beyond the usual 7-bit ascci set? and how could the python compiler 'read them and executed them' ? I shoulds have saved in utf-8 and have inside the script the line so the compiler knew to open it as utf-8. How come it dit work as ascii both in stroing and retreiving!! From jeanmichel at sequans.com Tue Aug 3 09:41:39 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 03 Aug 2010 15:41:39 +0200 Subject: simple integer subclass In-Reply-To: References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> Message-ID: <4C581C93.7070908@sequans.com> Andreas Pfrengle wrote: > On 3 Aug., 03:22, Carl Banks wrote:> > >> You are creating an object that differs from a built-in, int, in a >> highly misleading way that only makes sense in a very limited context, >> and this object's modified behavior gives no clue that it's been >> modified in such as way. (That is, it's not possible to tell if the >> object's not a regular int just by looking at __str__()'s return >> value.) To make matters worse, you want to program this object to >> coerce other integers, so there's a risk of these objects escaping >> from the context where they make sense. >> >> This is just a bad idea. The type is not the place to implement >> behavior that makes sense only in a limited context. Instead, do >> something like this: >> >> print "Item %d is %s." % (i+1, s[i]) >> > > I see your concerns. I started with the approach to add +1 directly > before displaying the int. However, since there are some variables > that shall be displayed normally and others that are indices I want to > show starting at 1, I thought the easiest way would be to define a > type that does the job, then I would only need to define it once and > not take care everywhere whether I have a normal variable or a > displayed index. > Thinking about it, it might really be dangerous to coerce always to > int1, since sometimes I might want a normal int as result (I can't > tell yet for sure). > I'm just thinking about only overloading the operations if the int1 is > on the left-hand side (so __op__ coerces to int1, while __rop__ > doesn't). This would make operations non-commutative - but I also > would need to put more brains in every calculation, which could > finally take more effort than only "upgrading" the display :-??? > Seems I end up with your suggestion - if noone else has an idea ;-) > > The application will be a browsergame, and most gamers start counting > at 1, so they would probably wonder about a "level 0 item" ;-) > If there didn't already exist lots of code, I would redesign the whole > data-structure - I think that's "lessons learned" for the next project > -.- > The level of an item is attribute of this item, not an index in a list. You may have an issue with your design, using an improper structure. In a more general manner, given your example I don't see why you should expose the index of an element in an internal list to the user. JM From jeanmichel at sequans.com Tue Aug 3 09:44:15 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 03 Aug 2010 15:44:15 +0200 Subject: simple integer subclass In-Reply-To: <4C581C93.7070908@sequans.com> References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> <4C581C93.7070908@sequans.com> Message-ID: <4C581D2F.8020101@sequans.com> Jean-Michel Pichavant wrote: > Andreas Pfrengle wrote: >> On 3 Aug., 03:22, Carl Banks wrote:> >> >>> You are creating an object that differs from a built-in, int, in a >>> highly misleading way that only makes sense in a very limited context, >>> and this object's modified behavior gives no clue that it's been >>> modified in such as way. (That is, it's not possible to tell if the >>> object's not a regular int just by looking at __str__()'s return >>> value.) To make matters worse, you want to program this object to >>> coerce other integers, so there's a risk of these objects escaping >>> from the context where they make sense. >>> >>> This is just a bad idea. The type is not the place to implement >>> behavior that makes sense only in a limited context. Instead, do >>> something like this: >>> >>> print "Item %d is %s." % (i+1, s[i]) >>> >> >> I see your concerns. I started with the approach to add +1 directly >> before displaying the int. However, since there are some variables >> that shall be displayed normally and others that are indices I want to >> show starting at 1, I thought the easiest way would be to define a >> type that does the job, then I would only need to define it once and >> not take care everywhere whether I have a normal variable or a >> displayed index. >> Thinking about it, it might really be dangerous to coerce always to >> int1, since sometimes I might want a normal int as result (I can't >> tell yet for sure). >> I'm just thinking about only overloading the operations if the int1 is >> on the left-hand side (so __op__ coerces to int1, while __rop__ >> doesn't). This would make operations non-commutative - but I also >> would need to put more brains in every calculation, which could >> finally take more effort than only "upgrading" the display :-??? >> Seems I end up with your suggestion - if noone else has an idea ;-) >> >> The application will be a browsergame, and most gamers start counting >> at 1, so they would probably wonder about a "level 0 item" ;-) >> If there didn't already exist lots of code, I would redesign the whole >> data-structure - I think that's "lessons learned" for the next project >> -.- >> > The level of an item is attribute of this item, not an index in a list. > You may have an issue with your design, using an improper structure. > > In a more general manner, given your example I don't see why you > should expose the index of an element in an internal list to the user. > > JM > "If there didn't already exist lots of code, I would redesign the whole data-structure" sorry I didn't get this one at first read, my comment is pretty much useless. JM From invalid at invalid.invalid Tue Aug 3 10:05:13 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 3 Aug 2010 14:05:13 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 2010-08-02, Aahz wrote: > In article , > Peter wrote: >>On Aug 3, 7:42=A0am, Mark Lawrence wrote: >>> On 02/08/2010 00:08, candide wrote: >>> >>> I can't understand why any serious programmer mentions C++. As soon >>> as I read it, I have to rush either to the kitchen to find a bowl to >>> throw up in, or head for the toilet so I can talk to the great white >>> telephone. >> >>With you there Mark - IMO C++ is an abortion that should never have >>seen the light of day. The idea of experimenting with creating an OO >>language by extending C wasn't such a bad idea for a "play thing" (by >>Stroustrop) but the fact that it somehow escaped from the Lab and >>people picked it up and ran with it on a commercial basis is just >>plain wrong! > > http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html It's funny (and sad) because it's so close to being true. (The effect, I mean, not necissarly the intent.) There's no computing problem so simple that it can't be solved in a complex and obtuse manner in C++. I know that's true of any language, but from what I've seen over the years, it "more true" in C++. -- Grant Edwards grant.b.edwards Yow! Should I get locked at in the PRINCICAL'S gmail.com OFFICE today -- or have a VASECTOMY?? From downaold at gmail.com Tue Aug 3 10:06:20 2010 From: downaold at gmail.com (Roald de Vries) Date: Tue, 3 Aug 2010 16:06:20 +0200 Subject: subclassing versus object redefinition In-Reply-To: References: Message-ID: <6D04E823-EBEB-452E-A4FE-DAE8F5F481C3@gmail.com> On Aug 3, 2010, at 2:46 PM, wheres pythonmonks wrote: > Hi! > > I have a class (supposed to be an abstract base class): > In python (as opposed to static languages like C++) I don't seed to > subclass the base class, but instead I can simply override the > behavior of stub methods and values. > Is there a preference between between subclassing (C++ approach) and > overriding methods/data in an instance? From a design perspective? > I think I prefer the override/redefine approach because it result in a > thinner class hierarchy. > > It seems like inheriting an ABC is needed only when I must share > instances (between multiple parts of the code, or if the subclass is > instantiated in different places...) > > Thoughts? 1) some things are just not possible in instances, like overriding operators 2) abstract base classes are not supposed to be instantiable, so if you are able to do it anyway, that is a hack 3) adding stuff to instances is less reusable that adding stuff to (sub)classes 4) if I'm reading your code and want to know what an object is like, I look at the class, not through your whole program to collect all bits and pieces of information spread out over it 5) why would you want a thinner class hierarchy? So I would go for inheritance. Cheers, Roald From invalid at invalid.invalid Tue Aug 3 10:11:41 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 3 Aug 2010 14:11:41 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-02, Paul Rubin wrote: > Michael Torrie writes: >> Sometimes, C++ is just the right tool for the job, despite all its >> warts.... C++'s object semantics (guaranteed destruction, scoping, >> etc) can sometimes work very well when you need the speed of a >> compiled language, but don't want to be quite as low-level as C. >> >> In this case, C++ is certainly not a better tool for the job than C. > > The stuff C++ adds to C is a mix of good and bad, and it's reasonably > possible to use just the good stuff and ignore the bad. Except nobody does. ;) > I've never programmed in Ada but I'm intrigued by these articles: > > http://adahome.com/Ammo/cpp2ada.html > http://www.adaic.org/whyada/ada-vs-c/cada_art.html > > I have the impression that Ada has an undeservedly bad rap because of > its early implementations and its origins in military bureaucracy. > I'd certainly consider it as an alternative to C or C++ if I had to > write a big program in a traditional procedural language. I've always thought Ada was a pretty nice embedded/systems languages, but some of the initial implementations were indede horrible. The one I used for a little while ran on VAX/VMS but didn't use the VMS filesystem, editors, or other utilities. The Ada enviroment was a completely closed, walled system. It kept it's "files" in some sort of opaque database and they could only be accessed, edited, compiled, etc. from within the Ada development enviornment (a system with really, really awful editing and build tools). There was a way to import/export files, but it wasn't easy. Still, the Ada-environment tools were _so_ bad that people exported a file, edited it using some VMS-based editor and the re-imported it whenever a change needed to be made. Apparently the intent was to provide the identically awful user-torturing-experience regardless of OS. -- Grant Edwards grant.b.edwards Yow! I represent a at sardine!! gmail.com From zdenekmaxa at yahoo.co.uk Tue Aug 3 10:32:45 2010 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Tue, 03 Aug 2010 16:32:45 +0200 Subject: checking that process binds a port, fuser functionality In-Reply-To: References: Message-ID: <4C58288D.6070606@yahoo.co.uk> -------- Original Message -------- Subject: Re: checking that process binds a port, fuser functionality From: Roy Smith To: python-list at python.org Date: Tue Aug 03 2010 13:06:27 GMT+0200 (CEST) > In article , > Nobody wrote: > >> On Mon, 02 Aug 2010 23:27:37 +0200, Zdenek Maxa wrote: >> >>> I need to start a process (using subprocess.Popen()) and wait until the >>> new process either fails or successfully binds a specified port. >> If you just need to wait until *something* is listening on that port, you >> could try connect()ing to it. > > This certainly seems like the logical way to me. It's straight-forward, > simple, and portable. Yes, but I need a check that certain known process's PID listens on a defined port. connect() would certainly work, but I may end up connecting to a different process. I forgot to mention that my master daemon starts processes in question as external applications, defines port they should bind but starts them via different user via sudo, which makes checking /proc/net/tcp not possible. Well, seems it's turning out not straight-forward, but thanks a lot for your thoughts anyway! Zdenek From wherespythonmonks at gmail.com Tue Aug 3 10:38:25 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Tue, 3 Aug 2010 10:38:25 -0400 Subject: subclassing versus object redefinition In-Reply-To: <6D04E823-EBEB-452E-A4FE-DAE8F5F481C3@gmail.com> References: <6D04E823-EBEB-452E-A4FE-DAE8F5F481C3@gmail.com> Message-ID: Roald: First, I must admit, I didn't know I could create an ABC in python. Now I see (http://docs.python.org/library/abc.html). Thank you. I think that the crux of the matter is in points #3, #4, and #5 that you raised: 3) adding stuff to instances is less reusable that adding stuff to (sub)classes 4) if I'm reading your code and want to know what an object is like, I look at the class, not through your whole program to collect all bits and pieces of information spread out over it On #3: Not clear that all possible specializations warrant factorization into a class. Indeed, this may result in "premature abstraction" -- and make the code less clear. Also, it will freeze in the base classes, making future refactoring a headache. On #4: Unless I misunderstood something, there is nothing in python that ensures that a class definition is localized. So, putting definitions in classes, does not guarantee that the definition is at a single location in the code. 5) why would you want a thinner class hierarchy? The yo-yo anti-patten: http://en.wikipedia.org/wiki/Yo-yo_problem I have a pretty strong preference for using a small number of useful objects, instead of having code littered with objects strewn across the namespace. Maybe there is a Python ABC tutorial out there that can enlighten me? W On Tue, Aug 3, 2010 at 10:06 AM, Roald de Vries wrote: > On Aug 3, 2010, at 2:46 PM, wheres pythonmonks wrote: >> >> Hi! >> >> I have a class (supposed to be an abstract base class): >> In python (as opposed to static languages like C++) I don't seed to >> subclass the base class, but instead I can simply override the >> behavior of stub methods and values. >> Is there a preference between between subclassing (C++ approach) and >> overriding methods/data in an instance? ?From a design perspective? >> I think I prefer the override/redefine approach because it result in a >> thinner class hierarchy. >> >> It seems like inheriting an ABC is needed only when I must share >> instances (between multiple parts of the code, or if the subclass is >> instantiated in different places...) >> >> Thoughts? > > 1) some things are just not possible in instances, like overriding operators > 2) abstract base classes are not supposed to be instantiable, so if you are > able to do it anyway, that is a hack > 3) adding stuff to instances is less reusable that adding stuff to > (sub)classes > 4) if I'm reading your code and want to know what an object is like, I look > at the class, not through your whole program to collect all bits and pieces > of information spread out over it > 5) why would you want a thinner class hierarchy? > > So I would go for inheritance. > > Cheers, Roald > > From roy at panix.com Tue Aug 3 10:43:13 2010 From: roy at panix.com (Roy Smith) Date: Tue, 3 Aug 2010 07:43:13 -0700 (PDT) Subject: checking that process binds a port, fuser functionality References: Message-ID: <6db6f26e-8447-4679-9f89-bf1a323b1845@q35g2000yqn.googlegroups.com> On Aug 3, 10:32?am, Zdenek Maxa wrote: > Yes, but I need a check that certain known process's PID listens on a > defined port. connect() would certainly work, but I may end up > connecting to a different process. Then you need to define your protocol such that the client and server engage in some sort of identification / authentication exchange when they connect. Client: Who are you? Server: I am PID 12345 Client: That's not who I was expecting, I'm going away! Depending on how secure you need this to be, the exchange might include some kind of cryptographic signature. From __peter__ at web.de Tue Aug 3 11:01:05 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Aug 2010 17:01:05 +0200 Subject: cPickle error when caching data References: Message-ID: Benedict Verheyen wrote: > i get the following error when trying to set data in the cache of a django > application. The error is however a python error as it involves pickling > and i can reproduce it in a shell. > The error i get is this: > cPickle.PicklingError: Can't pickle : > attribute lookup management.views.Stats failed > > Stats is a class i use to hold a couple of values, a string (user) and a > number (calls), that are then used in a template. These are pickable, > right? The data i want to pickle is the return value of this function: > > def calc_stats_topcallers(): > stats_all = {} > # cPickle doesn't like this class > class Stats(object): > def __init__(self): > self.calls = None > self.user = None You can only pickle instances of classes that are reachable by the import system as only the qualified name of the class is stored, not the bytecode to generate it. Move your class out of the function into the global module scope and you should be OK. Peter From downaold at gmail.com Tue Aug 3 11:31:07 2010 From: downaold at gmail.com (Roald de Vries) Date: Tue, 3 Aug 2010 17:31:07 +0200 Subject: subclassing versus object redefinition In-Reply-To: References: <6D04E823-EBEB-452E-A4FE-DAE8F5F481C3@gmail.com> Message-ID: <995E4DE8-6E33-4C12-8DF7-601D7B77A780@gmail.com> Hi W, On Aug 3, 2010, at 4:38 PM, wheres pythonmonks wrote: > I think that the crux of the matter is in points #3, #4, and #5 that > you raised: I think #2 is important too: a program is supposed to do what you expect, and I don't expect instantiation of an ABC. > On #3: Not clear that all possible specializations warrant > factorization into a class. Indeed, this may result in "premature > abstraction" -- and make the code less clear. Also, it will freeze in > the base classes, making future refactoring a headache. I agree (for small specializations only). > On #4: Unless I misunderstood something, there is nothing in python > that ensures that a class definition is localized. So, putting > definitions in classes, does not guarantee that the definition is at a > single location in the code. That's right, but with classes it is possible (and encouraged) to keep things in a single location. The other option necessarily puts things where I don't expect them. > 5) why would you want a thinner class hierarchy? > > The yo-yo anti-patten: > http://en.wikipedia.org/wiki/Yo-yo_problem > > I have a pretty strong preference for using a small number of useful > objects, instead of having code littered with objects strewn across > the namespace. I see the point, but I would like to remark that if a program does what you expect, you won't need to understand the whole inheritance graph. > Maybe there is a Python ABC tutorial out there that can enlighten me? http://docs.python.org/library/abc.html http://www.doughellmann.com/PyMOTW/abc/ Cheers, Roald PS: most people in this list prefer not top posting From benedict.verheyen at gmail.com Tue Aug 3 11:37:22 2010 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Tue, 03 Aug 2010 17:37:22 +0200 Subject: cPickle error when caching data In-Reply-To: References: Message-ID: On 3/08/2010 17:01, Peter Otten wrote: > You can only pickle instances of classes that are reachable by the import > system as only the qualified name of the class is stored, not the bytecode > to generate it. Move your class out of the function into the global module > scope and you should be OK. > > Peter Thanks Peter, that solved the problem ! Regards, Benedict From davea at ieee.org Tue Aug 3 11:41:36 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 03 Aug 2010 11:41:36 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: <4C5838B0.9030305@ieee.org> ????? wrote: >> On 3 ???, 11:10, Dave Angel wrote: >> > > >> a) a text editor takes keystrokes and cut/paste info and other data, and >> produces a stream of (unicode) characters. It then encodes each of >> those character into one or more bytes and saves it to a file. You have >> to tell Notepad++ how to do that encoding. Note that unless it's saving >> a BOM, there's no clue in the file what encoding it used. >> > > So actually when i'm selecting an encoding from Notepad++'s options > iam basically telling the editor the way the it's suppose to store > those streams of characters to the hard disk drive. > > Different encodings equals different ways of storting the data to the > media, correct? > > Exactly. The file is a stream of bytes, and Unicode has more than 256 possible characters. Further, even the subset of characters that *do* take one byte are different for different encodings. So you need to tell the editor what encoding you want to use. > >> b) The python compiler has to interpret the bytes it finds (spec. within >> string literals and comments), and decode them into unicode for its own >> work. It uses the 'coding:' comment to decide how to do this. But once >> the file has been compiled, that comment is totally irrelevant, and ignored. >> > > What is a "String Literal" ? > > In python, a string literal is enclosed by single quotes, double quotes, or triples. myvar = u"tell me more" myvar = u'hello world' The u prefix is used in python 2.x to convert to Unicode; it's not needed in 3.x and I forget which one you're using. these are affected by the coding comment, but myvar = myfile.readline() is not. > Basically if i understood you right, this line of code tells Python > the opposite thign from (a). > (a) told the editor how to store data to the media, while (b) tells > the python compiler how to retrive these data from the media(how to > read it, that is!) Right? > > > >> c1) Your python code has to decide how to encode its information when >> writing to stdout. There are several ways to accomplish that. >> > > what other ways except the prin '''Content-Type blah blah... ''' ? > > > You can use the write() method of sys.stdout, or various equivalents, such as the one produced by io.open(). You can probably also use fdopen(1, "w") But probably the easiest is to do something like: sys.stdout = codecs.getwriter('utf8')(sys.stdout) and then print to stdout will use the utf8 encoding for its output. >> c2) The browser sees only what was sent to stdout, starting with the >> "Content-Type..." line. It uses that line to decide how to decode the >> rest of the stream. Let me reemphasize, the browser does not see any of >> the python code, or comments. >> > > I was under the impression the the stdout of a cgi python script was > the web server itself since this is the one app that awaits for the > data to be displayed. > > When a python script runs it produces html output that time or only > after the > python's output to the Web Server the html output is produced? > > > I don't understand your wording. Certainly the server launches the python script, and captures stdout. It then sends that stream of bytes out over tcp/ip to the waiting browser. You ask when does it become html ? I don't think the question has meaning. > And something else please. > My cgi python scripts contains english and greek letters, hence this > is an indication of tellign the editor to save the file to disk as > utf-8 right? > > Well i told Notepad++ to save ti as Ascii and also removed the '# -*- > coding: utf-8 -*-' line. > > and only used print ''' Content-Type: text/html; charset=UTF-8 /n''' > > So, how the editor managed to save the file as ascii although my file > coaniens characters that are beyond the usual 7-bit ascci set? > > I don't know Notepad++, so I don't know how it handles a character outside the legal ASCII range. So I'd only be guessing. But I'm guessing it ignored the ASCII restriction, and just wrote the bottom 8 bits of each character. That'll work for some of the non-ASCII characters. > and how could the python compiler 'read them and executed them' ? > > I'd only be speculating, since I've seen only a few lines of your source. Perhaps you're using Python 2.x, and not specifying u"" for those literals, which is unreasonable, but does tend to work for *some* of the second 128 characters. > I shoulds have saved in utf-8 and have inside the script the line so > the compiler knew to open it as utf-8. How come it dit work as ascii > both in stroing and retreiving!! > > > Since you have the setup that shows this effect, why not take a look at the file, and see whether there are any non-ASCII characters (codes above hex 7f) in it ? And whether there's a BOM. Then you can examine the unicode characters produced. by changing your source code. The more I think about it, the more I suspect your confusion comes because maybe you're not using the u-prefix on your literals. That can lead to some very subtle bugs, and code that works for a while, then fails in inexplicable ways. DaveA From downaold at gmail.com Tue Aug 3 11:43:21 2010 From: downaold at gmail.com (Roald de Vries) Date: Tue, 3 Aug 2010 17:43:21 +0200 Subject: simple integer subclass In-Reply-To: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> Message-ID: Hi Andreas, On Aug 3, 2010, at 1:52 AM, Andreas Pfrengle wrote: > I'm trying to define a subclass of int called int1. An int1-object > shall behave exactly like an int-object, with the only difference that > the displayed value shall be value + 1 (it will be used to display > array indices starting at 1 instead of 0). Right now I have: > > class int1(int): > def __str__(self): > return int.__str__(self + 1) > > However, if I calculate with int1 and int- (or other number) objects, > the result is always coerced to an int (or other number object), e.g: > a = int1(5) > b = 5 > print a # "6" > print a+b #"10" > > How can I tell int1 to be the "default integer object"? Do I need to > overload *every* mathematical operation method of int, or is there an > easier way? Maybe you could use: 1) a dict with keys 1..n 2) a simple list (or iterable) subclass with 1-based indices. class list1(list): def __new__(cls, *args, **kwargs): return list.__new__(cls, *args, **kwargs) def __getitem__(self, key): return list.__getitem__(self, key-1) ... etcetera Cheers, Roald From pavlovevidence at gmail.com Tue Aug 3 12:15:14 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 3 Aug 2010 09:15:14 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> <87d3u0niww.fsf@castleamber.com> Message-ID: <14050e2d-50b2-4f21-bcef-9c2b56bd5755@i18g2000pro.googlegroups.com> On Aug 3, 2:29?am, John Bokma wrote: > Carl Banks writes: > > On Aug 1, 6:09?pm, John Bokma wrote: > >> Roy Smith writes: > >> > In article <4c55fe82$0$9111$426a3... at news.free.fr>, > >> > ?candide wrote: > > >> >> Python is an object oriented langage (OOL). The Python main > >> >> implementation is written in pure and "old" C90. Is it for historical > >> >> reasons? > > >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more > >> >> suitable to implement an OOL with another one. > > >> > One thing that comes to mind is that it's much easier to distribute C > >> > libraries than C++ libraries. > > >> In the beginning of C++ there were programs that just converted C++ to C > >> (frontends). At least that is how the C++ compiler Acorn sold worked. > >> So I don't think your argument was much true back then. > > > No, it was that way back then too. ?They might all generate C code but > > different C code by different backends wouldn't be able to call each > > other natively. > > If you convert C++ to C, and compile the C code then that's not > different from compiling the C code itself, correct? > > > > For instnace the function > > > int foo(int); > > > might be name-mangled this way in one cfront: > > > foo$d > > > and this way in another: > > > ____int_foo__int_i > > But they call both the C libraries in the same way. Go look at the original claim, the one that you responded to. "It's much easier to distribute C libraries than C++ libraries." Of course they can both call C libraries. All modern C++ compilers can too, not just cfronts. What almost no C++ compiler or C++ front can do is call a C++ library that a different C++ compiler or C++ front generated. (Unless they export function calls with C linkage, but that's not too helpful since the ostensible benefit of C++ is function overloading and subclassing and such, which you can't do at all between different compilers or fronts.) Hence, "It's much easier to distribute C libraries than C++ libraries." [snip rest of post that misses the point] Carl Banks From rushikesh.busetty at gmail.com Tue Aug 3 12:53:50 2010 From: rushikesh.busetty at gmail.com (RUSHIKESH BUSETTY) Date: Tue, 3 Aug 2010 09:53:50 -0700 (PDT) Subject: FULLY HOT ENTERTAINMENT Message-ID: AMISHAPATEL HOT BOOBS http://babes-devi.blogspot.com/2010/07/amishpatel-latest-photos.html ARCHANA UNSEENED EXPOSING PHOTOS http://babes-devi.blogspot.com/2010/07/archana-unseened-photos.html KATRINA KAIF HOT SEXY PHOTOS http://babes-devi.blogspot.com/2010/07/katrina-sexy-looking-photos.html THISHA HOT WET PHOTOS http://babes-devi.blogspot.com/2010/06/thrisha-hot-wet-photos.html SEXY CHARMI IN A BATHROOM http://babes-devi.blogspot.com/2010/06/charmi-in-bath.html KAJALAGARWAL IN A ROMANTIC FEEL http://babes-devi.blogspot.com/2010/06/kajal-hot-photos.html NAMITHA IN A BEACH http://babes-devi.blogspot.com/2010/06/nayagarala-namitha.html From ethan at stoneleaf.us Tue Aug 3 12:54:46 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 09:54:46 -0700 Subject: default behavior In-Reply-To: <4C578663.8000804@optimum.net> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> Message-ID: <4C5849D6.4060809@stoneleaf.us> John Posner wrote: > On 7/31/2010 1:31 PM, John Posner wrote: >> >> Caveat -- there's another description of defaultdict here: >> >> http://docs.python.org/library/collections.html#collections.defaultdict >> >> ... and it's bogus. This other description claims that __missing__ is a >> method of defaultdict, not of dict. > > Following is a possible replacement for the bogus description. Comments > welcome. I intend to submit a Python doc bug, and I'd like to have a > clean alternative to propose. > > -------------- > > class collections.defaultdict([default_factory[, ...]]) > > defaultdict is a dict subclass that can guarantee success on key > lookups: if a key does not currently exist in a defaultdict object, a > "default value factory" is called to provide a value for that key. The > "default value factory" is a callable object (typically, a function) > that takes no arguments. You specify this callable as the first argument > to defaultdict(). Additional defaultdict() arguments are the same as for > dict(). > > The "default value factory" callable is stored as an attribute, > default_factory, of the newly created defaultdict object. If you call > defaultdict() with no arguments, or with None as the first argument, the > default_factory attribute is set to None. You can reassign the > default_factory attribute of an existing defaultdict object to another > callable, or to None. > > When a lookup of a non-existent key is performed in a defaultdict > object, its default_factory attribute is evaluated, and the resulting > object is called: > > * If the call produces a value, that value is returned as the result of > the lookup. In addition, the key-value pair is inserted into the > defaultdict. > > * If the call raises an exception, it is propagated unchanged. > > * If the default_factory attribute evaluates to None, a KeyError > exception is raised, with the non-existent key as its argument. (The > defaultdict behaves exactly like a standard dict in this case.) I think mentioning how __missing__ plays into all this would be helpful. Perhaps in the first paragraph, after the colon: if a key does not currently exist in a defaultdict object, __missing__ will be called with that key, which in turn will call a "default value factory" to provide a value for that key. ~Ethan~ From ethan at stoneleaf.us Tue Aug 3 13:02:10 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 10:02:10 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <8739uwnihw.fsf@castleamber.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <8739uwnihw.fsf@castleamber.com> Message-ID: <4C584B92.8070601@stoneleaf.us> John Bokma wrote: > Michael Torrie writes: > >> On 08/01/2010 07:09 PM, John Bokma wrote: >>>> One thing that comes to mind is that it's much easier to distribute C >>>> libraries than C++ libraries. >>> In the beginning of C++ there were programs that just converted C++ to C >>> (frontends). At least that is how the C++ compiler Acorn sold worked. >>> So I don't think your argument was much true back then. >> No, he is still right. Each C++ implementation did name mangling >> differently leading to "C" libraries that had incompatible names and >> signatures. Also each frontend could have generated incompatible >> vtables and other C++ structures. So C code generated by one C++ >> frontend could not easily call C code generated by another C++ frontend. >> So the same arguments that are made about C++ now were just as valid >> back then when C++ was merely a fancy preprocessor. > > See my other post: I understand that two C++ preprocessors can't call > each others generated code, but if one uses C++ and knows that one can > only use shared C libraries on target systems, and not C++ libraries > that might be present (or more likely not: C++ was new in those days). So if Python were written in C++, and an extension was written in C++, how could the two call each other? ~Ethan~ From nikos.the.gr33k at gmail.com Tue Aug 3 13:17:28 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Tue, 3 Aug 2010 10:17:28 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> Message-ID: <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> >On 3 ???, 18:41, Dave Angel wrote: > > Different encodings equal different ways of storing the data to the > > media, correct? > > Exactly. The file is a stream of bytes, and Unicode has more than 256 > possible characters. Further, even the subset of characters that *do* > take one byte are different for different encodings. So you need to tell > the editor what encoding you want to use. For example an 'a' char in iso-8859-1 is stored different than an 'a' char in iso-8859-7 and an 'a' char of utf-8 ? > > What is a "String Literal" ? > > In python, a string literal is enclosed by single quotes, double quotes, > or triples. > myvar = u"tell me more" > myvar = u'hello world' > The u prefix is used in python 2.x to convert to Unicode; it's not > needed in 3.x and I forget which one you're using. I use Python 2.4 and never used the u prefix. i Still don't understand the difference between a 'string' and a 'string literal' If i save a file as iso-8859-1 but in some of my variabels i use greek characters instead of telling the browser to change encoding and save the file as utf-8 i can just use the u prefix like your examples to save the variables as iso-8859-1 ? > I don't understand your wording. Certainly the server launches the > python script, and captures stdout. It then sends that stream of bytes > out over tcp/ip to the waiting browser. You ask when does it become html > ? I don't think the question has meaning. http cliens send request to http server(apache) , apache call python interpreter python call mysql to handle SQL queries right? My question is what is the difference of the python's script output and the web server's output to the http client? Who is producing the html code? the python output or the apache web server after it receive the python's output? > The more I think about it, the more I suspect your confusion comes > because maybe you're not using the u-prefix on your literals. That can > lead to some very subtle bugs, and code that works for a while, then > fails in inexplicable ways. I'm not sure whatr exaclty the do just yet. For example if i say mymessage = "????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the 2nd its a utf-8 one? So one script can be in some encoding and some parts of the script like th2 2nd varible can be in another? ============================== Also can you please help me in my cookie problem as to why only the else block executed each time and never the if? here is the code: [code] if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist print "??? ??? ??????? ???????? ??? ?? ?? ????????? ?? ????????? ?????????? ??? ???????!" cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire now else: print "??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? ?? ??????! ?? ????? ????? ? ??????? ??????????!!" cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year [/code] How do i check if the cookie is set and why if set never gets unset?! From lesande at gmail.com Tue Aug 3 13:34:48 2010 From: lesande at gmail.com (Lee Sander) Date: Tue, 3 Aug 2010 10:34:48 -0700 (PDT) Subject: finding homopolymers in both directions Message-ID: Hi, Suppose I have a string such as this 'aabccccccefggggghiiijkr' I would like to print out all the positions that are flanked by a run of symbols. So for example, I would like to the output for the above input as follows: 2 b 1 aa 2 b -1 cccccc 10 e -1 cccccc 11 f 1 ggggg 17 h 1 iii 17 h -1 ggggg where the first column is the position of interest, the next column is the entry at that position, 1 if the following column refers to a runs that come after and -1 if the runs come before I can do this easily for forward (shown below) but not clear how to do this backwards. I would really appreciate it if someone can help with this problem. I feel like a regex solution would be possible but I am not too good with regex. The code for forward is as follows: def homopolymericSites(Seq): Seq=Seq.upper() i=0 len_seq=len(Seq)-1# hack to prevent boundary condition while i < len_seq: bi=Seq[i] k=1 # go to the start of a homopolymer while 1: if i+k >= len_seq: break # no more sequence left if bi==Seq[i+k]: k+=1 else: break if k>1: # homopolymer length i=i+k id_of_chr_which_proceeds_homopolymer=Seq[i] # note not i+1 pos_of_chr_which_proceeds_homopolymer=i+1 # +1 to convert it to 1- index notation id_of_homopolymer=Seq[i-1] length_of_homopolymer=k print "%s\t%s/%s\t%s" %(pos_of_chr_which_proceeds_homopolymer, id_of_chr_which_proceeds_homopolymer, id_of_homopolymer, length_of_homopolymer) else: i+=1 From nagle at animats.com Tue Aug 3 13:41:57 2010 From: nagle at animats.com (John Nagle) Date: Tue, 03 Aug 2010 10:41:57 -0700 Subject: Behavior of re.split on empty strings is unexpected In-Reply-To: <52ae410e-789e-41ad-bf0a-1d060d03019d@x21g2000yqa.googlegroups.com> References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> <52ae410e-789e-41ad-bf0a-1d060d03019d@x21g2000yqa.googlegroups.com> Message-ID: <4c5854e8$0$1608$742ec2ed@news.sonic.net> On 8/2/2010 5:53 PM, samwyse wrote: > On Aug 2, 12:34 pm, John Nagle wrote: >> The regular expression "split" behaves slightly differently than string >> split: > > I'm going to argue that it's the string split that's behaving oddly. I tend to agree. It doesn't seem to be possible to get the same semantics with any regular expression split. The default "split" has a special case for head and tail whitespace, and there's no way to express that with a regular expression split. Applying "strip" first will work, of course. The documentation should reflect that. John Nagle From nagle at animats.com Tue Aug 3 13:44:03 2010 From: nagle at animats.com (John Nagle) Date: Tue, 03 Aug 2010 10:44:03 -0700 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4c585565$0$1608$742ec2ed@news.sonic.net> On 8/1/2010 5:36 PM, Roy Smith wrote: > In article<4c55fe82$0$9111$426a34cc at news.free.fr>, > candide wrote: > >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. > > One thing that comes to mind is that it's much easier to distribute C > libraries than C++ libraries. > > If I compile a main program with one C compiler and you compile a > dynamically loaded library with another C compiler on the same box, the > odds are pretty good they'll interoperate without any problems. Not for Python. Extensions have to be built with essentially the same version of the same C compiler used for building Python. This is a major headache. John Nagle From bazwal at ftml.net Tue Aug 3 13:56:55 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 03 Aug 2010 18:56:55 +0100 Subject: regular expressions and the LOCALE flag Message-ID: <4C585867.8090207@ftml.net> the python docs say that re.LOCALE makes certain character classes "dependent on the current locale". here's what i currently see on my system: >>> import re, locale >>> locale.getdefaultlocale() ('en_GB', 'UTF8') >>> locale.getlocale() (None, None) >>> re.findall(r'\w', u'a b c \xe5 \xe6 \xe7', re.L) [u'a', u'b', u'c'] >>> locale.setlocale(locale.LC_ALL, 'en_GB.ISO 8859-1') 'en_GB.ISO 8859-1' >>> re.findall(r'\w', u'\xe5 \xe6 \xe7 a b c', re.L) [u'\xe5', u'\xe6', u'\xe7', u'a', u'b', u'c'] >>> locale.setlocale(locale.LC_ALL, 'en_GB.UTF-8') 'en_GB.UTF-8' >>> re.findall(r'\w', u'a b c \xe5 \xe6 \xe7', re.L) [u'a', u'b', u'c'] it seems wrong to me that re.LOCALE fails to give the "right" result when the local encoding is utf8 - i think it should give the same result as re.UNICODE. is this a bug, or does the documentation just need to be made clearer? From davea at ieee.org Tue Aug 3 14:00:17 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 03 Aug 2010 14:00:17 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> Message-ID: <4C585931.6060401@ieee.org> ????? wrote: >> On 3 ???, 18:41, Dave Angel wrote: >> >>> Different encodings equal different ways of storing the data to the >>> media, correct? >>> >> Exactly. The file is a stream of bytes, and Unicode has more than 256 >> possible characters. Further, even the subset of characters that *do* >> take one byte are different for different encodings. So you need to tell >> the editor what encoding you want to use. >> > > For example an 'a' char in iso-8859-1 is stored different than an 'a' > char in iso-8859-7 and an 'a' char of utf-8 ? > > > Nope, the ASCII subset is identical. It's the ones between 80 and ff that differ, and of course not all of those. Further, some of the codes that are one byte in 8859 are two bytes in utf-8. You *could* just decide that you're going to hardwire the assumption that you'll be dealing with a single character set that does fit in 8 bits, and most of this complexity goes away. But if you do that, do *NOT* use utf-8. But if you do want to be able to handle more than 256 characters, or more than one encoding, read on. Many people confuse encoding and decoding. A unicode character is an abstraction which represents a raw character. For convenience, the first 128 code points map directly onto the 7 bit encoding called ASCII. But before Unicode there were several other extensions to 256, which were incompatible with each other. For example, a byte which might be a European character in one such encoding might be a kata-kana character in another one. Each encoding was 8 bits, but it was difficult for a single program to handle more than one such encoding. So along comes unicode, which is typically implemented in 16 or 32 bit cells. And it has an 8 bit encoding called utf-8 which uses one byte for the first 192 characters (I think), and two bytes for some more, and three bytes beyond that. You encode unicode to utf-8, or to 8859, or to ... You decode utf-8 or 8859, or cp1252 , or ... to unicode >>> What is a "String Literal" ? >>> >> In python, a string literal is enclosed by single quotes, double quotes, >> or triples. >> myvar ="tell me more" >> myvar ='hello world' >> The u prefix is used in python 2.x to convert to Unicode; it's not >> needed in 3.x and I forget which one you're using. >> > > I use Python 2.4 and never used the u prefix. > > Then you'd better hope you never manipulate those literals. For example, the second character of some international characters expressed in utf8 may be a percent symbol, which would mess up string formatting. > i Still don't understand the difference between a 'string' and a > 'string literal' > > A string is an object containing characters. A string literal is one of the ways you create such an object. When you create it that way, you need to make sure the compiler knows the correct encoding, by using the encoding: line at beginning of file. > If i save a file as iso-8859-1 but in some of my variabels i use greek > characters instead of telling the browser to change encoding and save > the file as utf-8 i can just use the u prefix like your examples to > save the variables as iso-8859-1 ? > > >> I don't understand your wording. Certainly the server launches the >> python script, and captures stdout. It then sends that stream of bytes >> out over tcp/ip to the waiting browser. You ask when does it become html >> ? I don't think the question has meaning. >> > > http cliens send request to http server(apache) , apache call python > interpreter python call mysql to handle SQL queries right? > > My question is what is the difference of the python's script output > and the web server's output to the http client? > > The web server wraps a few characters before and after your html stream, but it shouldn't touch the stream itself. > Who is producing the html code? the python output or the apache web > server after it receive the python's output? > > > see above. >> The more I think about it, the more I suspect your confusion comes >> because maybe you're not using the u-prefix on your literals. That can >> lead to some very subtle bugs, and code that works for a while, then >> fails in inexplicable ways. >> > > I'm not sure whatr exaclty the do just yet. > > For example if i say mymessage = "????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the > 2nd its a utf-8 one? > > No, the first is an 8 bit copy of whatever bytes your editor happened to save. The second is unicode, which may be either 16 or 32 bits per character, depending on OS platform. Neither is utf-8. > So one script can be in some encoding and some parts of the script > like th2 2nd varible can be in another? > > mymessage = u"????????" creates an object that is *not* encoded. Encoding is taking the unicode stream and representing it as a stream of bytes, which may or may have more bytes than the original has characters. > ============================ > Also can you please help me in my cookie problem as to why only the > else block executed each time and never the if? > > here is the code: > > [code] > if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') = > 'nikos': #if visitor cookie exist > print "??? ??? ??????? ???????? ??? ?? ?? ????????? ?? ????????? > ?????????? ??? ???????!" > cookie['visitor'] = 'nikos', time() - 1 ) #this cookie will expire > now > else: > print "??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? ?? ??????! > ?? ????? ????? ? ??????? ??????????!!" > cookie['visitor'] = 'nikos', time() + 60*60*24*365 ) #this cookie > will expire in an year > [/code] > > How do i check if the cookie is set and why if set never gets unset?! > > I personally haven't done any cookie code. If I were debugging this, I'd factor out the multiple parts of that if statement, and find out which one isn't true. From here I can't guess. DaveA From benjamin.kaplan at case.edu Tue Aug 3 14:16:25 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 3 Aug 2010 11:16:25 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <4c585565$0$1608$742ec2ed@news.sonic.net> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4c585565$0$1608$742ec2ed@news.sonic.net> Message-ID: On Tue, Aug 3, 2010 at 10:44 AM, John Nagle wrote: > On 8/1/2010 5:36 PM, Roy Smith wrote: > >> In article<4c55fe82$0$9111$426a34cc at news.free.fr>, >> candide wrote: >> >> Python is an object oriented langage (OOL). The Python main >>> implementation is written in pure and "old" C90. Is it for historical >>> reasons? >>> >>> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >>> suitable to implement an OOL with another one. >>> >> >> One thing that comes to mind is that it's much easier to distribute C >> libraries than C++ libraries. >> >> If I compile a main program with one C compiler and you compile a >> dynamically loaded library with another C compiler on the same box, the >> odds are pretty good they'll interoperate without any problems. >> > > Not for Python. Extensions have to be built with essentially the > same version of the same C compiler used for building Python. This > is a major headache. > > John Nagle > -- > Pretty sure that's only one Windows, and only because they need to be linked to the same version of MSVC. It's not a compiler issue, it's incompatible library versions. > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 3 14:31:35 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Aug 2010 20:31:35 +0200 Subject: finding homopolymers in both directions References: Message-ID: Lee Sander wrote: > Hi, > Suppose I have a string such as this > 'aabccccccefggggghiiijkr' > > I would like to print out all the positions that are flanked by a run > of symbols. > So for example, I would like to the output for the above input as > follows: > > 2 b 1 aa > 2 b -1 cccccc > 10 e -1 cccccc > 11 f 1 ggggg > 17 h 1 iii > 17 h -1 ggggg > > where the first column is the position of interest, the next column is > the entry at that position, > 1 if the following column refers to a runs that come after and -1 if > the runs come before Trying to follow your spec I came up with from itertools import groupby from collections import namedtuple Item = namedtuple("Item", "pos key size") def compact(seq): pos = 0 for key, group in groupby(seq): size = len(list(group)) yield Item(pos, key, size) pos += size def window(items): items = iter(items) prev = None cur = next(items) for nxt in items: yield prev, cur, nxt prev = cur cur = nxt yield prev, cur, None items = compact("aabccccccefggggghiiijkr") for prev, cur, nxt in window(items): if cur.size == 1: if prev is not None: if prev.size > 1: print cur.pos, cur.key, -1, prev.key*prev.size if nxt is not None: if nxt.size > 1: print cur.pos, cur.key, 1, nxt.key*nxt.size However, this gives a slightly differenct output: $ python homopolymers.py 2 b -1 aa 2 b 1 cccccc 9 e -1 cccccc 10 f 1 ggggg 16 h -1 ggggg 16 h 1 iii 20 j -1 iii Peter From no.email at nospam.invalid Tue Aug 3 14:35:45 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 11:35:45 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <7xvd7rh7cu.fsf@ruckus.brouhaha.com> Grant Edwards writes: > There's no computing problem so simple that it can't be solved in a > complex and obtuse manner in C++. > > I know that's true of any language, but from what I've seen over the > years, it "more true" in C++. http://www.willamette.edu/~fruehr/haskell/evolution.html From python at mrabarnett.plus.com Tue Aug 3 14:40:38 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Aug 2010 19:40:38 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C585867.8090207@ftml.net> References: <4C585867.8090207@ftml.net> Message-ID: <4C5862A6.6030101@mrabarnett.plus.com> Baz Walter wrote: > the python docs say that re.LOCALE makes certain character classes > "dependent on the current locale". > > here's what i currently see on my system: > > >>> import re, locale > >>> locale.getdefaultlocale() > ('en_GB', 'UTF8') > >>> locale.getlocale() > (None, None) > >>> re.findall(r'\w', u'a b c \xe5 \xe6 \xe7', re.L) > [u'a', u'b', u'c'] > >>> locale.setlocale(locale.LC_ALL, 'en_GB.ISO 8859-1') > 'en_GB.ISO 8859-1' > >>> re.findall(r'\w', u'\xe5 \xe6 \xe7 a b c', re.L) > [u'\xe5', u'\xe6', u'\xe7', u'a', u'b', u'c'] > >>> locale.setlocale(locale.LC_ALL, 'en_GB.UTF-8') > 'en_GB.UTF-8' > >>> re.findall(r'\w', u'a b c \xe5 \xe6 \xe7', re.L) > [u'a', u'b', u'c'] > > it seems wrong to me that re.LOCALE fails to give the "right" result > when the local encoding is utf8 - i think it should give the same result > as re.UNICODE. > > is this a bug, or does the documentation just need to be made clearer? re.LOCALE just passes the character to the underlying C library. It really only works on bytestrings which have 1 byte per character. UTF-8 encodes codepoints outside the ASCII range to multiple bytes per codepoint, and the re module will treat each of those bytes as a separate character. And, BTW, none of your examples pass a UTF-8 bytestring to re.findall: all those string literals starting with the 'u' prefix are Unicode strings! Locale encodings are more trouble than they're worth. Unicode is better. :-) From dotancohen at gmail.com Tue Aug 3 14:53:00 2010 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 3 Aug 2010 21:53:00 +0300 Subject: Trying to set a cookie within a python script In-Reply-To: <4C5838B0.9030305@ieee.org> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <4C5838B0.9030305@ieee.org> Message-ID: On Tue, Aug 3, 2010 at 18:41, Dave Angel wrote: > I don't understand your wording. Certainly the server launches the python > script, and captures stdout. It then sends that stream of bytes out over > tcp/ip to the waiting browser. You ask when does it become html ? I don't > think the question has meaning. > ?HTML is just plain text. So the answer to the question is that ideally, the plain text that is sent to stdout would already be HTML. print ( "My Greek Page\n" ) -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From joe at goldthwaites.com Tue Aug 3 14:59:16 2010 From: joe at goldthwaites.com (Joe Goldthwaite) Date: Tue, 3 Aug 2010 11:59:16 -0700 Subject: locale and number formatting. Message-ID: <8462203B6D4F4122B98E6131F573C2CB@NewMBP> I've been working with some developers on a project. Our standard number formatting for the entire web site is comma separated with no decimals. Currency is formatted with the dollar sign. This is basically how they did it; import locale def currency(value): return locale.currency(value, grouping=True) def formatnumber(value): value = locale.currency(value, grouping=True) value = value.replace('$',''); try: value = value[:-3]; except: value = value; return value; The "formatnumber" function looks awkward. I'm not even sure what exactly they're trying to accomplish. They're stripping off the last three characters but since the number is formatted by the currency function, it might have parenthesis. I don't see this working correctly with negative numbers. That got me looking in to the locale module again. I'm having trouble understanding some of the python documentation on the subject. I've searched the web and even searched through all my safaribooksonline to see if I could get more information on how to improve the code but I'm just not getting it. Lets take the first step; def currency(value): return locale.currency(value, grouping=True) This is pretty simple. My problem is that I want all my currency numbers formatted with zero decimal places. There doesn't seem to be an option to round the value down. I thought that maybe I could change the 'frac_digits' setting to zero but I can't seem to find a way to change it. I've found a number of different functions that accomplish this but they're written from scratch. I'd really like to use a standard library function to do it if possible. With the 'formatnumber" function could be replaced with; def formatnumber(value): return locale.format('%0.0f', value, 1) This inserts the commas and rounds off the decimals. It doesn't handle putting parens around the negative numbers. Is there a better way to do this? I tried looking up the options for local.format_string which seems to allow custom "C" formatting but I couldn't find any examples of what the custom "C" formatting would look like. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 3 15:04:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Aug 2010 20:04:07 +0100 Subject: Trying to set a cookie within a python script In-Reply-To: <4C585931.6060401@ieee.org> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <4C585931.6060401@ieee.org> Message-ID: <4C586827.1030903@mrabarnett.plus.com> Dave Angel wrote: > ????? wrote: >>> On 3 ???, 18:41, Dave Angel wrote: >>> >>>> Different encodings equal different ways of storing the data to the >>>> media, correct? >>>> >>> Exactly. The file is a stream of bytes, and Unicode has more than 256 >>> possible characters. Further, even the subset of characters that *do* >>> take one byte are different for different encodings. So you need to tell >>> the editor what encoding you want to use. >>> >> >> For example an 'a' char in iso-8859-1 is stored different than an 'a' >> char in iso-8859-7 and an 'a' char of utf-8 ? >> >> >> > Nope, the ASCII subset is identical. It's the ones between 80 and ff > that differ, and of course not all of those. Further, some of the codes > that are one byte in 8859 are two bytes in utf-8. > > You *could* just decide that you're going to hardwire the assumption > that you'll be dealing with a single character set that does fit in 8 > bits, and most of this complexity goes away. But if you do that, do > *NOT* use utf-8. > > But if you do want to be able to handle more than 256 characters, or > more than one encoding, read on. > > Many people confuse encoding and decoding. A unicode character is an > abstraction which represents a raw character. For convenience, the first > 128 code points map directly onto the 7 bit encoding called ASCII. But > before Unicode there were several other extensions to 256, which were > incompatible with each other. For example, a byte which might be a > European character in one such encoding might be a kata-kana character > in another one. Each encoding was 8 bits, but it was difficult for a > single program to handle more than one such encoding. > One encoding might be ASCII + accented Latin, another ASCII + Greek, another ASCII + Cyrillic, etc. If you wanted ASCII + accented Latin + Greek then you'd need more than 1 byte per character. If you're working with multiple alphabets it gets very messy, which is where Unicode comes in. It contains all those characters, and UTF-8 can encode all of them in a straightforward manner. > So along comes unicode, which is typically implemented in 16 or 32 bit > cells. And it has an 8 bit encoding called utf-8 which uses one byte for > the first 192 characters (I think), and two bytes for some more, and > three bytes beyond that. > [snip] In UTF-8 the first 128 codepoints are encoded to 1 byte. From bazwal at ftml.net Tue Aug 3 15:40:01 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 03 Aug 2010 20:40:01 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C5862A6.6030101@mrabarnett.plus.com> References: <4C585867.8090207@ftml.net> <4C5862A6.6030101@mrabarnett.plus.com> Message-ID: <4C587091.8040901@ftml.net> On 03/08/10 19:40, MRAB wrote: > Baz Walter wrote: >> the python docs say that re.LOCALE makes certain character classes >> "dependent on the current locale". > > re.LOCALE just passes the character to the underlying C library. It > really only works on bytestrings which have 1 byte per character. the re docs don't specify 8-bit encodings: they just refer to the 'current locale'. > And, BTW, none of your examples pass a UTF-8 bytestring to re.findall: > all those string literals starting with the 'u' prefix are Unicode > strings! not sure what you mean by this: if the string was encoded as utf8, '\w' still wouldn't match any of the non-ascii characters. > Locale encodings are more trouble than they're worth. Unicode is better. > :-) yes, i'm really just trying to decide whether i should offer 'locale' as an option in my program. given the unintuitive way re.LOCALE works, i'm not sure that i should. are you saying that it only really makes sense for *bytestrings* to be used with re.LOCALE? if so, the re docs certainly don't make that clear. From wherespythonmonks at gmail.com Tue Aug 3 16:17:04 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Tue, 3 Aug 2010 16:17:04 -0400 Subject: None is negative? Message-ID: I did the google search... I must be blind as I don't see any hits... None is negative in Python? (v2.6) http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >>> if None < -9999999.99: print "hi" hi >>> >>> if -9999999 > None: print "hi" hi >>> Is there a way to have the comparison raise an exception? W From benjamin.kaplan at case.edu Tue Aug 3 16:24:22 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 3 Aug 2010 13:24:22 -0700 Subject: None is negative? In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 1:17 PM, wheres pythonmonks wrote: > > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? ?(v2.6) > > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > > >>> if None < -9999999.99: print "hi" > > hi > >>> > > >>> if -9999999 > None: print "hi" > > hi > >>> > > Is there a way to have the comparison raise an exception? > > W Use Python 3. One of the (backwards-incompatible) changes was to have comparisons of incompatible types raise exceptions. The behavior in Python 2 (not just with None, but with other built-in types as well) was to return an arbitrary but consistent result. From python at mrabarnett.plus.com Tue Aug 3 16:24:55 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Aug 2010 21:24:55 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C587091.8040901@ftml.net> References: <4C585867.8090207@ftml.net> <4C5862A6.6030101@mrabarnett.plus.com> <4C587091.8040901@ftml.net> Message-ID: <4C587B17.7050905@mrabarnett.plus.com> Baz Walter wrote: > On 03/08/10 19:40, MRAB wrote: >> Baz Walter wrote: >>> the python docs say that re.LOCALE makes certain character classes >>> "dependent on the current locale". >> >> re.LOCALE just passes the character to the underlying C library. It >> really only works on bytestrings which have 1 byte per character. > > the re docs don't specify 8-bit encodings: they just refer to the > 'current locale'. > >> And, BTW, none of your examples pass a UTF-8 bytestring to re.findall: >> all those string literals starting with the 'u' prefix are Unicode >> strings! > > not sure what you mean by this: if the string was encoded as utf8, '\w' > still wouldn't match any of the non-ascii characters. > Strings with the 'u' prefix are Unicode strings, not bytestrings. They don't have an encoding. A UTF-8 string is a bytestring in which the bytes represent Unicode codepoints encoded as UTF-8. >> Locale encodings are more trouble than they're worth. Unicode is better. >> :-) > > yes, i'm really just trying to decide whether i should offer 'locale' as > an option in my program. given the unintuitive way re.LOCALE works, i'm > not sure that i should. > > are you saying that it only really makes sense for *bytestrings* to be > used with re.LOCALE? > > if so, the re docs certainly don't make that clear. The re module can match against 3 types of string: 1. ASCII (default in Python 2): bytestring with characters in the ASCII range (1 byte per character). However, it doesn't complain if it sees bytes/characters outside the ASCII range. 2. LOCALE: bytestring with characters in the current locale (but only 1 byte per character). Characters are categorised according to the underlying C library; for example, 'a' is a letter if isalpha('a') returns true. 3. UNICODE (default in Python 3): Unicode string. From mithrandiragainwiki at mailinator.com Tue Aug 3 16:28:49 2010 From: mithrandiragainwiki at mailinator.com (Mithrandir) Date: Tue, 03 Aug 2010 13:28:49 -0700 Subject: None is negative? References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 08/03/2010 01:17 PM, wheres pythonmonks wrote: > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? (v2.6) > > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > >>>> if None < -9999999.99: print "hi" > > hi >>>> > >>>> if -9999999 > None: print "hi" > > hi >>>> > > Is there a way to have the comparison raise an exception? > > W I believe it's also because None lacks any binary value at all, whereas - -99999999.99 or 0 have a value in binary. For example: if None < 0: print "hi" >>> hi if None > 0: print "hi" >>> But in human terms, None == 0 and None > -9999999.99. - -- People should read more. https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain "All that is gold does not glitter, not all those who wander are lost; the old that is strong does not wither, deep roots are not reached by the frost. - From the ashes a fire shall be woken, a light from the shadows shall spring; renewed shall be blade that was broken, the crownless again shall be king." -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJMWHwBAAoJEKo37V1xH7gTgvYH/j1j0fgKI5mlzIp4urxhh6Ki 49LVsZjVsISyD+NzvgV5b8hk0S9Ad+gpqaf8fBQJS36Ye1KtupA7W7CTr54roaK0 ZBN3o4XxPdRjxXeHnBUNi3bqjGMzDdIIFZbE/qKalxTj0ZYgtlCgnMiYXLEeeY5z L0dzfn/qoMr6PjAtdlB9yp5amHcUeRzDos3hp13flsAj9Vq/pHyJmlPazME/vE0f 381bMXP52ud71BGcm8gRWdDqhJOUdJ52NZeEk0fKcxHsRvscjt1nQmCRp4IMDtFl ws++tXcl0pY7KSAATb5dzzkhr/BJnKGb1JHRlQMMB0EEdtNOzJaDh63qbvSzTJI= =9jHw -----END PGP SIGNATURE----- From invalid at invalid.invalid Tue Aug 3 16:29:17 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 3 Aug 2010 20:29:17 +0000 (UTC) Subject: None is negative? References: Message-ID: On 2010-08-03, wheres pythonmonks wrote: > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? (v2.6) Not really. > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > >>>> if None < -9999999.99: print "hi" > > hi >>>> > >>>> if -9999999 > None: print "hi" > > hi >>>> > > Is there a way to have the comparison raise an exception? Use Python 3.x. Or perhaps there's a "from future import xxxx" way to do that as well... Is there a list of available "from future" features somewhere? I can't seem to figure out how to get Python itself to give me a list -- my copy of Python 2.6 insists there's not module named future. -- Grant Edwards grant.b.edwards Yow! I have a very good at DENTAL PLAN. Thank you. gmail.com From nad at acm.org Tue Aug 3 16:30:08 2010 From: nad at acm.org (Ned Deily) Date: Tue, 03 Aug 2010 13:30:08 -0700 Subject: None is negative? References: Message-ID: In article , wheres pythonmonks wrote: > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? (v2.6) > > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > > >>> if None < -9999999.99: print "hi" > > hi > >>> > > >>> if -9999999 > None: print "hi" > > hi > >>> > > Is there a way to have the comparison raise an exception? This is a well-known wart in Python 2. The behavior has been changed in Python 3. $ python Python 2.6.5 (r265:79063, Jul 15 2010, 01:53:46) [GCC 4.2.1 (Apple Inc. build 5659)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> None < -9.9 True >>> $ python3 Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> None < -9.9 Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: NoneType() < float() >>> -- Ned Deily, nad at acm.org From invalid at invalid.invalid Tue Aug 3 16:32:46 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 3 Aug 2010 20:32:46 +0000 (UTC) Subject: None is negative? References: Message-ID: On 2010-08-03, Grant Edwards wrote: > On 2010-08-03, wheres pythonmonks wrote: > >> I did the google search... I must be blind as I don't see any hits... >> >> None is negative in Python? (v2.6) > > Not really. > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >> >>>>> if None < -9999999.99: print "hi" >> >> hi >>>>> >> >>>>> if -9999999 > None: print "hi" >> >> hi >>>>> >> >> Is there a way to have the comparison raise an exception? > > Use Python 3.x. Or perhaps there's a "from future import xxxx" way to > do that as well... Is there a list of available "from future" > features somewhere? I can't seem to figure out how to get Python > itself to give me a list -- my copy of Python 2.6 insists there's not > module named future. Doh! It's "__future__" not "future". And it doesn't appear that you can import the "unorderable types" behavior. -- Grant Edwards grant.b.edwards Yow! Uh-oh!! I'm having at TOO MUCH FUN!! gmail.com From mithrandiragainwiki at mailinator.com Tue Aug 3 16:34:40 2010 From: mithrandiragainwiki at mailinator.com (Mithrandir) Date: Tue, 03 Aug 2010 13:34:40 -0700 Subject: None is negative? References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 08/03/2010 01:28 PM, Mithrandir wrote: > On 08/03/2010 01:17 PM, wheres pythonmonks wrote: >> I did the google search... I must be blind as I don't see any hits... > >> None is negative in Python? (v2.6) > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > >>>>> if None < -9999999.99: print "hi" > >> hi >>>>> > >>>>> if -9999999 > None: print "hi" > >> hi >>>>> > >> Is there a way to have the comparison raise an exception? > >> W > > I believe it's also because None lacks any binary value at all, whereas > -99999999.99 or 0 have a value in binary. > > For example: > > if None < 0: print "hi" > >>>> hi > > if None > 0: print "hi" > >>>> > > But in human terms, None == 0 and None > -9999999.99. > That and/or it works out better in Python 3. :) - -- People should read more. https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain "All that is gold does not glitter, not all those who wander are lost; the old that is strong does not wither, deep roots are not reached by the frost. - From the ashes a fire shall be woken, a light from the shadows shall spring; renewed shall be blade that was broken, the crownless again shall be king." -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJMWH1gAAoJEKo37V1xH7gTPSIH/igigROvz8NOy/Km5SEAPtUE 08Brr46qeqZzkKPxV/r8wH2uD4eIhHoaBUN0oOv+7FT1UoP89eg7E0eC7U8FtzXY 5uwgEXG4xHTLPCERK4UkX799zD6oVQ7eeoSmnKmbotXEbUEjZ6TONq3ErXZBn6g0 FqHX6S/GdrVvIvqjuePYNJYYC/CsF3qXDpkM69Iye0MqGsZGPaKsrmsCa2cPVI+P ZZ67nXeHEsgYZ91utu4Hb4yOtmZf8MFqFqyD8aYF2Tr1P3uEBe8WOUqIPGRkwrFF Nxw1Ne/pw2v++CDLbJUS6+rpN52IYEeBLawtUarc/iG4RG+KFE7Z0ss8jSr75+c= =uXl5 -----END PGP SIGNATURE----- From davea at ieee.org Tue Aug 3 16:41:54 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 03 Aug 2010 16:41:54 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: <4C586827.1030903@mrabarnett.plus.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <4C585931.6060401@ieee.org> <4C586827.1030903@mrabarnett.plus.com> Message-ID: <4C587F12.3000507@ieee.org> MRAB wrote: >
Dave > Angel wrote: >> ????? wrote: >>>> On 3 ???, 18:41, Dave Angel wrote: >>>>> Different encodings equal different ways of storing the data to the >>>>> media, correct? >>>> Exactly. The file is a stream of bytes, and Unicode has more than 256 >>>> possible characters. Further, even the subset of characters that *do* >>>> take one byte are different for different encodings. So you need to >>>> tell >>>> the editor what encoding you want to use. >>> >>> For example an 'a' char in iso-8859-1 is stored different than an 'a' >>> char in iso-8859-7 and an 'a' char of utf-8 ? >>> >>> >> Nope, the ASCII subset is identical. It's the ones between 80 and ff >> that differ, and of course not all of those. Further, some of the >> codes that are one byte in 8859 are two bytes in utf-8. >> >> You *could* just decide that you're going to hardwire the assumption >> that you'll be dealing with a single character set that does fit in 8 >> bits, and most of this complexity goes away. But if you do that, do >> *NOT* use utf-8. >> >> But if you do want to be able to handle more than 256 characters, or >> more than one encoding, read on. >> >> Many people confuse encoding and decoding. A unicode character is an >> abstraction which represents a raw character. For convenience, the >> first 128 code points map directly onto the 7 bit encoding called >> ASCII. But before Unicode there were several other extensions to 256, >> which were incompatible with each other. For example, a byte which >> might be a European character in one such encoding might be a >> kata-kana character in another one. Each encoding was 8 bits, but it >> was difficult for a single program to handle more than one such >> encoding. >> > One encoding might be ASCII + accented Latin, another ASCII + Greek, > another ASCII + Cyrillic, etc. If you wanted ASCII + accented Latin + > Greek then you'd need more than 1 byte per character. > > If you're working with multiple alphabets it gets very messy, which is > where Unicode comes in. It contains all those characters, and UTF-8 can > encode all of them in a straightforward manner. > >> So along comes unicode, which is typically implemented in 16 or 32 >> bit cells. And it has an 8 bit encoding called utf-8 which uses one >> byte for the first 192 characters (I think), and two bytes for some >> more, and three bytes beyond that. >> > [snip] > In UTF-8 the first 128 codepoints are encoded to 1 byte. > > Thanks for the correction. As I said, I wasn't sure. I did utf-8 encoder and decoder about a dozen years ago, and I remember parts of it use the top two bits specially. But I've checked now, and you're right, the cutoff is 7f. DaveA From clp2 at rebertia.com Tue Aug 3 16:42:21 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 3 Aug 2010 13:42:21 -0700 Subject: None is negative? In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 1:29 PM, Grant Edwards wrote: > On 2010-08-03, wheres pythonmonks wrote: > >> I did the google search... I must be blind as I don't see any hits... >> >> None is negative in Python? ?(v2.6) > > Not really. > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >> >>>>> if None < -9999999.99: print "hi" >> >> hi >>>>> >> >>>>> if -9999999 > None: print "hi" >> >> hi >>>>> >> >> Is there a way to have the comparison raise an exception? > > Use Python 3.x. ?Or perhaps there's a "from future import xxxx" way to > do that as well... ?Is there a list of available "from future" > features somewhere? ?I can't seem to figure out how to get Python > itself to give me a list -- my copy of Python 2.6 insists there's not > module named future. The module is named __future__. But there's no __future__ import to change the comparison behavior: Python 2.7 (r27:82500, Jul 27 2010, 23:28:51) >>> __future__.all_feature_names ['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals'] Cheers, Chris -- http://blog.rebertia.com From ethan at stoneleaf.us Tue Aug 3 16:43:44 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 13:43:44 -0700 Subject: None is negative? In-Reply-To: References: Message-ID: <4C587F80.4070605@stoneleaf.us> Grant Edwards wrote: > On 2010-08-03, wheres pythonmonks wrote: > >> I did the google search... I must be blind as I don't see any hits... >> >> None is negative in Python? (v2.6) > > Not really. > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >> >>>>> if None < -9999999.99: print "hi" >> hi >>>>> if -9999999 > None: print "hi" >> hi >> Is there a way to have the comparison raise an exception? > > Use Python 3.x. Or perhaps there's a "from future import xxxx" way to > do that as well... Is there a list of available "from future" > features somewhere? I can't seem to figure out how to get Python > itself to give me a list -- my copy of Python 2.6 insists there's not > module named future. > In 2.5 & 2.6 it's __future__. ~Ethan~ From benjamin.kaplan at case.edu Tue Aug 3 16:45:04 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 3 Aug 2010 13:45:04 -0700 Subject: None is negative? In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 1:29 PM, Grant Edwards wrote: > On 2010-08-03, wheres pythonmonks wrote: > >> I did the google search... I must be blind as I don't see any hits... >> >> None is negative in Python? ?(v2.6) > > Not really. > >> http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python >> >>>>> if None < -9999999.99: print "hi" >> >> hi >>>>> >> >>>>> if -9999999 > None: print "hi" >> >> hi >>>>> >> >> Is there a way to have the comparison raise an exception? > > Use Python 3.x. ?Or perhaps there's a "from future import xxxx" way to > do that as well... ?Is there a list of available "from future" > features somewhere? ?I can't seem to figure out how to get Python > itself to give me a list -- my copy of Python 2.6 insists there's not > module named future. > > -- That would be because it's __future__, not future. >>> import __future___ >>> help(__future__) Help on module __future__: NAME __future__ - Record of phased-in incompatible language changes. FILE c:\program files (x86)\ironpython 2.6 for .net 4.0\lib\__future__.py DESCRIPTION Each line is of the form: FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease "," CompilerFlag ")" where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples of the same form as sys.version_info: (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int PY_MINOR_VERSION, # the 1; an int PY_MICRO_VERSION, # the 0; an int PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string PY_RELEASE_SERIAL # the 3; an int ) OptionalRelease records the first release in which from __future__ import FeatureName was accepted. In the case of MandatoryReleases that have not yet occurred, MandatoryRelease predicts the release in which the feature will become par of the language. Else MandatoryRelease records when the feature became part of the language in releases at or after that, modules no longer need from __future__ import FeatureName to use the feature in question, but may continue to use such imports. MandatoryRelease may also be None, meaning that a planned feature got dropped. Instances of class _Feature have two corresponding methods, .getOptionalRelease() and .getMandatoryRelease(). CompilerFlag is the (bitfield) flag that should be passed in the fourth argument to the builtin function compile() to enable the feature in dynamically compiled code. This flag is stored in the .compiler_flag attribute on _Future instances. These values must match the appropriate #defines of CO_xxx flags in Include/compile.h. No feature line is ever to be deleted from this file. DATA __all__ = ['all_feature_names', 'nested_scopes', 'generators', 'divisi... absolute_import = _Feature((2, 5, 0, 'alpha', 1), (2, 7, 0, 'alpha', 0... all_feature_names = ['nested_scopes', 'generators', 'division', 'absol... division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192... generators = _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), 0) nested_scopes = _Feature((2, 1, 0, 'beta', 1), (2, 2, 0, 'alpha', 0), ... print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)... unicode_literals = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', ... with_statement = _Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0)... Hm, looks like whatever IronPython is using to display the text is cutting the lines short. That could be a problem. Anyway, you get the idea. From jjposner at optimum.net Tue Aug 3 17:24:53 2010 From: jjposner at optimum.net (John Posner) Date: Tue, 03 Aug 2010 17:24:53 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> Message-ID: <4C588925.1060505@optimum.net> On 8/3/2010 12:54 PM, Ethan Furman wrote: > I think mentioning how __missing__ plays into all this would be helpful. > Perhaps in the first paragraph, after the colon: > > if a key does not currently exist in a defaultdict object, __missing__ > will be called with that key, which in turn will call a "default value > factory" to provide a value for that key. Thanks, Ethan. As I said (or at least implied) to Christian earlier in this thread, I don't want to repeat the mistake of the current description: confusing the functionality provided *by* the defaultdict class with underlying functionality (the dict type's __missing__ protocol) that is used in the definition of the class. So I'd rather not mention __missing__ in the first paragraph, which describes the functionality provided *by* the defaultdict class. How about adding this para at the end: defaultdict is defined using functionality that is available to *any* subclass of dict: a missing-key lookup automatically causes the subclass's __missing__ method to be called, with the non-existent key as its argument. The method's return value becomes the result of the lookup. BTW, I couldn't *find* the coding of defaultdict in the Python 2.6 library. File collections.py contains this code: from _abcoll import * import _abcoll __all__ += _abcoll.__all__ from _collections import deque, defaultdict ... but I ran into a dead end after that. :-( I believe that the following *could be* the definition of defaultdict: class defaultdict(dict): def __init__(self, factory, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.default_factory = factory def __missing__(self, key): """provide value for missing key""" value = self.default_factory() # call factory with no args self[key] = value return value -John From lists at cheimes.de Tue Aug 3 17:47:23 2010 From: lists at cheimes.de (Christian Heimes) Date: Tue, 03 Aug 2010 23:47:23 +0200 Subject: default behavior In-Reply-To: <4C588925.1060505@optimum.net> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> Message-ID: > So I'd rather not mention __missing__ in the first paragraph, which > describes the functionality provided *by* the defaultdict class. How > about adding this para at the end: > > defaultdict is defined using functionality that is available to *any* > subclass of dict: a missing-key lookup automatically causes the > subclass's __missing__ method to be called, with the non-existent key > as its argument. The method's return value becomes the result of the > lookup. Your proposal sounds like a good idea. By the way do you have a CS degree? Your wording sounds like you are used write theses on a CS degree level. No offense. ;) > BTW, I couldn't *find* the coding of defaultdict in the Python 2.6 > library. File collections.py contains this code: > > from _abcoll import * > import _abcoll > __all__ += _abcoll.__all__ > > from _collections import deque, defaultdict defaultdict is implemented in C. You can read up the source code at http://svn.python.org/view/python/trunk/Modules/_collectionsmodule.c?revision=81029&view=markup . Search for "defaultdict type". The C code isn't complicated. You should understand the concept even if you are not familiar with the C API of Python. > class defaultdict(dict): > def __init__(self, factory, *args, **kwargs): > dict.__init__(self, *args, **kwargs) > self.default_factory = factory > > def __missing__(self, key): > """provide value for missing key""" > value = self.default_factory() # call factory with no args > self[key] = value > return value The type also implements __repr__(), copy() and __reduce__(). The latter is used by the pickle protocol. Without a new __reduce__ method, the default_factory would no survive a pickle/unpickle cycle. For a pure Python implementation you'd have to add __slots__ = "default_factory", too. Otherwise every defaultdict instance would gain an unncessary __dict__ attribute, too. Christian From jjposner at optimum.net Tue Aug 3 18:04:27 2010 From: jjposner at optimum.net (John Posner) Date: Tue, 03 Aug 2010 18:04:27 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> Message-ID: <4C58926B.6000108@optimum.net> On 8/3/2010 5:47 PM, Christian Heimes wrote: >> So I'd rather not mention __missing__ in the first paragraph, which >> describes the functionality provided *by* the defaultdict class. How >> about adding this para at the end: >> >> defaultdict is defined using functionality that is available to *any* >> subclass of dict: a missing-key lookup automatically causes the >> subclass's __missing__ method to be called, with the non-existent key >> as its argument. The method's return value becomes the result of the >> lookup. > > Your proposal sounds like a good idea. Tx. > By the way do you have a CS degree? Your wording sounds like you are > used write theses on a CS degree level. No offense. ;) No CS degree (coulda, woulda, shoulda). I think what you're hearing is 30+ years of tech writing for computer software companies. -John From ethan at stoneleaf.us Tue Aug 3 18:07:01 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 15:07:01 -0700 Subject: default behavior In-Reply-To: <4C588925.1060505@optimum.net> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> Message-ID: <4C589305.40903@stoneleaf.us> John Posner wrote: > On 8/3/2010 12:54 PM, Ethan Furman wrote: > > > >> I think mentioning how __missing__ plays into all this would be helpful. >> Perhaps in the first paragraph, after the colon: >> >> if a key does not currently exist in a defaultdict object, __missing__ >> will be called with that key, which in turn will call a "default value >> factory" to provide a value for that key. > > Thanks, Ethan. As I said (or at least implied) to Christian earlier in > this thread, I don't want to repeat the mistake of the current > description: confusing the functionality provided *by* the defaultdict > class with underlying functionality (the dict type's __missing__ > protocol) that is used in the definition of the class. I just went and read the entry that had the bogus claim -- personally, I didn't see any confusion. I would like to point out the __missing__ is *not* part of dicts (tested on 2.5 and 2.6 -- don't have 2.7 installed yet). Having said that, I think your final paragraph is better than my first paragraph edit. > So I'd rather not mention __missing__ in the first paragraph, which > describes the functionality provided *by* the defaultdict class. How > about adding this para at the end: > > defaultdict is defined using functionality that is available to *any* > subclass of dict: a missing-key lookup automatically causes the > subclass's __missing__ method to be called, with the non-existent key > as its argument. The method's return value becomes the result of the > lookup. > > BTW, I couldn't *find* the coding of defaultdict in the Python 2.6 > library. File collections.py contains this code: > > from _abcoll import * > import _abcoll > __all__ += _abcoll.__all__ > > from _collections import deque, defaultdict > > ... but I ran into a dead end after that. :-( I believe that the > following *could be* the definition of defaultdict: > > class defaultdict(dict): > def __init__(self, factory, *args, **kwargs): > dict.__init__(self, *args, **kwargs) > self.default_factory = factory > > def __missing__(self, key): > """provide value for missing key""" > value = self.default_factory() # call factory with no args > self[key] = value > return value I think it's more along these lines: class defaultdict(dict): def __init__(self, factory=None, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.default_factory = factory def __missing__(self, key): "provide value for missing key" if self.default_factory is None: raise KeyError("blah blah blah") value = self.default_factory() self[key] = value return value ~Ethan~ From ethan at stoneleaf.us Tue Aug 3 18:15:40 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 15:15:40 -0700 Subject: default behavior In-Reply-To: <4C578663.8000804@optimum.net> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> Message-ID: <4C58950C.3060906@stoneleaf.us> John Posner wrote: > On 7/31/2010 1:31 PM, John Posner wrote: >> >> Caveat -- there's another description of defaultdict here: >> >> http://docs.python.org/library/collections.html#collections.defaultdict >> >> ... and it's bogus. This other description claims that __missing__ is a >> method of defaultdict, not of dict. __missing__ isn't a method of dict: --> print dir(dict()) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] I will agree that the current defaultdict description does not make it clear that __missing__ can be defined for *any* subclass of dict, although the dict description does go over this... is that the confusion you are talking about? If not, could you explain? ~Ethan~ From john at castleamber.com Tue Aug 3 18:19:36 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 17:19:36 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> <87d3u0niww.fsf@castleamber.com> <14050e2d-50b2-4f21-bcef-9c2b56bd5755@i18g2000pro.googlegroups.com> Message-ID: <87aap3uyo7.fsf@castleamber.com> Carl Banks writes: > On Aug 3, 2:29?am, John Bokma wrote: [..] >> But they call both the C libraries in the same way. > > Go look at the original claim, the one that you responded to. "It's > much easier to distribute C libraries than C++ libraries." Yup, and if I read it correctly the claim was: and that's why C++ was not chosen. I doubt it. > Hence, "It's much easier to distribute C libraries than C++ > libraries." Yup, but still doesn't exclude C++ from being used to implement a programming language. And I would appreciate some respect, especially from someone who's too lazy to do some editing before posting, thank you. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From john at castleamber.com Tue Aug 3 18:20:49 2010 From: john at castleamber.com (John Bokma) Date: Tue, 03 Aug 2010 17:20:49 -0500 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <8739uwnihw.fsf@castleamber.com> Message-ID: <8762zruym6.fsf@castleamber.com> Ethan Furman writes: > John Bokma wrote: >> Michael Torrie writes: >> >>> On 08/01/2010 07:09 PM, John Bokma wrote: >>>>> One thing that comes to mind is that it's much easier to >>>>> distribute C libraries than C++ libraries. >>>> In the beginning of C++ there were programs that just converted C++ to C >>>> (frontends). At least that is how the C++ compiler Acorn sold worked. >>>> So I don't think your argument was much true back then. >>> No, he is still right. Each C++ implementation did name mangling >>> differently leading to "C" libraries that had incompatible names and >>> signatures. Also each frontend could have generated incompatible >>> vtables and other C++ structures. So C code generated by one C++ >>> frontend could not easily call C code generated by another C++ frontend. >>> So the same arguments that are made about C++ now were just as valid >>> back then when C++ was merely a fancy preprocessor. >> >> See my other post: I understand that two C++ preprocessors can't call >> each others generated code, but if one uses C++ and knows that one can >> only use shared C libraries on target systems, and not C++ libraries >> that might be present (or more likely not: C++ was new in those days). > > So if Python were written in C++, and an extension was written in C++, > how could the two call each other? Via C. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From lists at cheimes.de Tue Aug 3 18:35:30 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 04 Aug 2010 00:35:30 +0200 Subject: default behavior In-Reply-To: <4C589305.40903@stoneleaf.us> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> Message-ID: > I just went and read the entry that had the bogus claim -- personally, I > didn't see any confusion. I would like to point out the __missing__ is > *not* part of dicts (tested on 2.5 and 2.6 -- don't have 2.7 installed yet). I beg your pardon but you are wrong. __missing__ is available for all *subclasses* of dict since Python 2.5. See http://svn.python.org/view/python/branches/release25-maint/Objects/dictobject.c?revision=81031&view=markup >>> class mydict(dict): ... def __missing__(self, key): ... print "__missing__", key ... raise KeyError(key) ... >>> m = mydict() >>> m[1] __missing__ 1 Traceback (most recent call last): File "", line 1, in File "", line 4, in __missing__ KeyError: 1 Christian From ethan at stoneleaf.us Tue Aug 3 18:48:02 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 15:48:02 -0700 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> Message-ID: <4C589CA2.1040709@stoneleaf.us> Christian Heimes wrote: >> I just went and read the entry that had the bogus claim -- personally, I >> didn't see any confusion. I would like to point out the __missing__ is >> *not* part of dicts (tested on 2.5 and 2.6 -- don't have 2.7 installed yet). > > I beg your pardon but you are wrong. __missing__ is available for all > *subclasses* of dict since Python 2.5. See > http://svn.python.org/view/python/branches/release25-maint/Objects/dictobject.c?revision=81031&view=markup > >>>> class mydict(dict): > ... def __missing__(self, key): > ... print "__missing__", key > ... raise KeyError(key) > ... >>>> m = mydict() >>>> m[1] > __missing__ 1 > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in __missing__ > KeyError: 1 Perhaps punctuation will help clarify my intent: __missing__ is *not* part of (dict)s, as shown by dir(dict()): ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] And, just to state what is hopefully obvious, if you don't create __missing__ yourself, it still isn't in the subclass: --> class somedict(dict): ... "Is __missing__ defined if I don't define it? Nope." ... --> sd = somedict() --> sd[1] Traceback (most recent call last): File "", line 1, in KeyError: 1 --> dir(sd) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] ~Ethan~ From ethan at stoneleaf.us Tue Aug 3 18:52:34 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 15:52:34 -0700 Subject: Why is python not written in C++ ? In-Reply-To: <8762zruym6.fsf@castleamber.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <8739uwnihw.fsf@castleamber.com> <8762zruym6.fsf@castleamber.com> Message-ID: <4C589DB2.6060108@stoneleaf.us> John Bokma wrote: > Ethan Furman writes: > >> John Bokma wrote: >>> Michael Torrie writes: >>> >>>> On 08/01/2010 07:09 PM, John Bokma wrote: >>>>>> One thing that comes to mind is that it's much easier to >>>>>> distribute C libraries than C++ libraries. >>>>> In the beginning of C++ there were programs that just converted C++ to C >>>>> (frontends). At least that is how the C++ compiler Acorn sold worked. >>>>> So I don't think your argument was much true back then. >>>> No, he is still right. Each C++ implementation did name mangling >>>> differently leading to "C" libraries that had incompatible names and >>>> signatures. Also each frontend could have generated incompatible >>>> vtables and other C++ structures. So C code generated by one C++ >>>> frontend could not easily call C code generated by another C++ frontend. >>>> So the same arguments that are made about C++ now were just as valid >>>> back then when C++ was merely a fancy preprocessor. >>> See my other post: I understand that two C++ preprocessors can't call >>> each others generated code, but if one uses C++ and knows that one can >>> only use shared C libraries on target systems, and not C++ libraries >>> that might be present (or more likely not: C++ was new in those days). >> So if Python were written in C++, and an extension was written in C++, >> how could the two call each other? > > Via C. Huh? Presumably Python itself is not a library, and the extension may not be a library, at some point they will have different name mangling schemes... are you suggesting that after going through the effort if writing all this in C++ you would then have to write a wrapper in C so the two could talk to each other? ~Ethan~ From pavlovevidence at gmail.com Tue Aug 3 18:56:17 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 3 Aug 2010 15:56:17 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> <87d3u0niww.fsf@castleamber.com> <14050e2d-50b2-4f21-bcef-9c2b56bd5755@i18g2000pro.googlegroups.com> <87aap3uyo7.fsf@castleamber.com> Message-ID: <45daa26c-80d2-44a9-a804-651eb984990a@y11g2000yqm.googlegroups.com> On Aug 3, 3:19?pm, John Bokma wrote: > Carl Banks writes: > > On Aug 3, 2:29?am, John Bokma wrote: > > [..] > > >> But they call both the C libraries in the same way. > > > Go look at the original claim, the one that you responded to. ?"It's > > much easier to distribute C libraries than C++ libraries." > > Yup, and if I read it correctly the claim was: and that's why C++ was > not chosen. I doubt it. I think it was. Not necessarily that GvR made a list of reasons to choose C over C++. But the fact that C++ has almost no interoperability between compilers except via regular C linkage is a major cultural reason why it's avoided for programs that need extensible APIs like Python, which is why language implementors try to avoid it. The availability of C++ fronts that translate to C isn't the slightest bit relevant to this. > > Hence, "It's much easier to distribute C libraries than C++ > > libraries." > > Yup, but still doesn't exclude C++ from being used to implement a > programming language. Well, if you want to write a language that people can write extensions for using something other than the same C++ compiler you used, then your only option is to use "C" external linkage which means that whatever OOP advantages C++ gives you aren't going to be available to extensions. This is true even if you use a C++ front instead of a compiler. Carl Banks From roy at panix.com Tue Aug 3 19:05:23 2010 From: roy at panix.com (Roy Smith) Date: Tue, 03 Aug 2010 19:05:23 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <87lj8p4y77.fsf@castleamber.com> <693a31be-b7f7-473d-a709-55c691d00b92@h17g2000pri.googlegroups.com> <87d3u0niww.fsf@castleamber.com> <14050e2d-50b2-4f21-bcef-9c2b56bd5755@i18g2000pro.googlegroups.com> <87aap3uyo7.fsf@castleamber.com> Message-ID: In article <87aap3uyo7.fsf at castleamber.com>, John Bokma wrote: > > Go look at the original claim, the one that you responded to. "It's > > much easier to distribute C libraries than C++ libraries." > > Yup, and if I read it correctly the claim was: and that's why C++ was > not chosen. I doubt it. I didn't intend to claim quite that much. I'm just saying it's a consideration. I was not privy to the original design decisions. From martin at v.loewis.de Tue Aug 3 19:13:11 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 04 Aug 2010 01:13:11 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <4c55fe82$0$9111$426a34cc@news.free.fr> References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: > Has it ever been planned to rewrite in C++ the historical implementation > (of course in an object oriented design) ? Around the time Guido coined the term "Python 3000" (i.e. in 2000), he also said at a few occasions that it would be written in C++. He subsequently dropped the idea, for the reasons that people have been discussing. Regards, Martin From bazwal at ftml.net Tue Aug 3 19:27:55 2010 From: bazwal at ftml.net (Baz Walter) Date: Wed, 04 Aug 2010 00:27:55 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C587B17.7050905@mrabarnett.plus.com> References: <4C585867.8090207@ftml.net> <4C5862A6.6030101@mrabarnett.plus.com> <4C587091.8040901@ftml.net> <4C587B17.7050905@mrabarnett.plus.com> Message-ID: <4C58A5FB.2010606@ftml.net> On 03/08/10 21:24, MRAB wrote: >>> And, BTW, none of your examples pass a UTF-8 bytestring to re.findall: >>> all those string literals starting with the 'u' prefix are Unicode >>> strings! >> >> not sure what you mean by this: if the string was encoded as utf8, >> '\w' still wouldn't match any of the non-ascii characters. >> > Strings with the 'u' prefix are Unicode strings, not bytestrings. They > don't have an encoding. well, they do if they are given one, as i suggested! to be explicit, if the local encoding is 'utf8', none of the following will get a hit: (1) re.findall(r'\w', '\xe5 \xe6 \xe7', re.L) (2) re.findall(r'\w', u'\xe5 \xe6 \xe7'.encode('utf8'), re.L) (3) re.findall(r'\w', u'\xe5 \xe6 \xe7', re.L) so i still don't know what you meant about passing a 'UTF-8 bytestring' in your first comment :) only (3) could feasibly get a hit - and then only if the re module was smart enough to fall back to re.UNICODE for utf8 (and any other encodings of unicode it might know about). > 2. LOCALE: bytestring with characters in the current locale (but only 1 > byte per character). Characters are categorised according to the > underlying C library; for example, 'a' is a letter if isalpha('a') > returns true. this is actually what my question was about. i suspected something like this might be the case, but i can't actually see it stated anywhere in the docs. maybe it's just me, but 'current locale' doesn't naturally imply 'only 8-bit encodings'. i would have thought it implied 'whatever encoding is discovered on the local system' - and these days, that's very commonly utf8. is there actually a use case for it working the way it currently does? it seems just broken to have it depending so heavily on implementation details. > 3. UNICODE (default in Python 3): Unicode string. i've just read the python3 re docs, and they do now make an explicit distinction between matching bytes (with the new re.ASCII flag) and matching textual characters (i.e. unicode, the default). the re.LOCALE flag is still there, and there are now warnings about it's unreliability - but it still doesn't state that it can only work properly if the local encoding is 8-bit. From greg.ewing at canterbury.ac.nz Tue Aug 3 19:54:45 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 04 Aug 2010 11:54:45 +1200 Subject: The untimely dimise of a weak-reference In-Reply-To: <4c568b59$0$14545$426a34cc@news.free.fr> References: <8bhi2fFifjU1@mid.individual.net> <4c568b59$0$14545$426a34cc@news.free.fr> Message-ID: <8bro1bFcucU1@mid.individual.net> Bruno Desthuilliers wrote: > Would be better with : > > return self.func(obj, *args, *kwds) Thanks -- well spotted! -- Greg From borg at gone.com Tue Aug 3 20:05:04 2010 From: borg at gone.com (THE BORG) Date: Wed, 4 Aug 2010 01:05:04 +0100 Subject: Air force one shoes ( http://www.brandtrade99.com/ In-Reply-To: References: Message-ID: Now don't all rush, and form an ordery queue PLEASE! We are sure you all want Air force one shoes. From ldo at geek-central.gen.new_zealand Tue Aug 3 20:11:17 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 12:11:17 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: In message , Grant Edwards wrote: > I've always thought Ada was a pretty nice embedded/systems languages, > but some of the initial implementations were indede horrible. Well, there?s GNAT, the GNU Ada implementation. Seems pretty robust and complete, while offering backward compatibility with some of those ?initial implementations?, presumably because people have so much code already written for them. Disclaimer: the most complicated Ada program I?ve ever written is this . Or maybe this . :) From lists at cheimes.de Tue Aug 3 20:16:32 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 04 Aug 2010 02:16:32 +0200 Subject: default behavior In-Reply-To: <4C589CA2.1040709@stoneleaf.us> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> <4C589CA2.1040709@stoneleaf.us> Message-ID: > Perhaps punctuation will help clarify my intent: > > __missing__ is *not* part of (dict)s, as shown by dir(dict()): Indeed, that's correct. Can we agree, that __missing__ is an optional feature of the dict interface, that can be implemented in subclasses of dict? Christian From python at mrabarnett.plus.com Tue Aug 3 20:24:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 04 Aug 2010 01:24:59 +0100 Subject: regular expressions and the LOCALE flag In-Reply-To: <4C58A5FB.2010606@ftml.net> References: <4C585867.8090207@ftml.net> <4C5862A6.6030101@mrabarnett.plus.com> <4C587091.8040901@ftml.net> <4C587B17.7050905@mrabarnett.plus.com> <4C58A5FB.2010606@ftml.net> Message-ID: <4C58B35B.4040206@mrabarnett.plus.com> Baz Walter wrote: > On 03/08/10 21:24, MRAB wrote: >>>> And, BTW, none of your examples pass a UTF-8 bytestring to >>>> re.findall: all those string literals starting with the 'u' prefix >>>> are Unicode strings! >>> >>> not sure what you mean by this: if the string was encoded as utf8, >>> '\w' still wouldn't match any of the non-ascii characters. >>> >> Strings with the 'u' prefix are Unicode strings, not bytestrings. >> They don't have an encoding. > > well, they do if they are given one, as i suggested! > > to be explicit, if the local encoding is 'utf8', none of the following > will get a hit: > > (1) re.findall(r'\w', '\xe5 \xe6 \xe7', re.L) This passes, for example, 0xE5 to the C library function isalnum() to check whether it's alphanumeric. Apparently it's returning false when the locale is set to UTF-8. > (2) re.findall(r'\w', u'\xe5 \xe6 \xe7'.encode('utf8'), re.L) u'\xe5' is encoded to '\xc3\xa5'. Both 0xC3 and 0xA5 are passed to the C library function isalnum() to check whether they're alphanumeric. Apparently it's returning false for both when the locale is set to UTF-8. > (3) re.findall(r'\w', u'\xe5 \xe6 \xe7', re.L) > Same as (1) above. > so i still don't know what you meant about passing a 'UTF-8 > bytestring' in your first comment :) > > only (3) could feasibly get a hit - and then only if the re module was > smart enough to fall back to re.UNICODE for utf8 (and any other > encodings of unicode it might know about). > LOCALE was really intended for all those 1-byte-per-character character sets like CP1252. Trying to implement regex when different characters occupy different numbers of bytes is, well, challenging! :-) >> 2. LOCALE: bytestring with characters in the current locale (but only >> 1 byte per character). Characters are categorised according to the >> underlying C library; for example, 'a' is a letter if isalpha('a') >> returns true. > > this is actually what my question was about. i suspected something > like this might be the case, but i can't actually see it stated > anywhere in the docs. maybe it's just me, but 'current locale' doesn't > naturally imply 'only 8-bit encodings'. i would have thought it > implied 'whatever encoding is discovered on the local system' - and > these days, that's very commonly utf8. > > is there actually a use case for it working the way it currently does? > it seems just broken to have it depending so heavily on implementation > details. > As I said, it's for old-style 1-byte-per-character character sets. If you have UTF-8, then you can decode to Unicode. Is it broken? Well, it works well enough for its intended use. Could the re module work with bytes which represent characters in an arbitrary encoding? Would you like to have a go at implementing it? I wouldn't... It would be easier to just decode to Unicode and work with that. >> 3. UNICODE (default in Python 3): Unicode string. > > i've just read the python3 re docs, and they do now make an explicit > distinction between matching bytes (with the new re.ASCII flag) and > matching textual characters (i.e. unicode, the default). the re.LOCALE > flag is still there, and there are now warnings about it's > unreliability - but it still doesn't state that it can only work > properly if the local encoding is 8-bit. The recommendation for text is to use UTF-8 externally (input, output and storage in files) and Unicode internally when processing. From ethan at stoneleaf.us Tue Aug 3 21:09:32 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 03 Aug 2010 18:09:32 -0700 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> <4C589CA2.1040709@stoneleaf.us> Message-ID: <4C58BDCC.1030407@stoneleaf.us> Christian Heimes wrote: >> Perhaps punctuation will help clarify my intent: >> >> __missing__ is *not* part of (dict)s, as shown by dir(dict()): > > Indeed, that's correct. Can we agree, that __missing__ is an optional > feature of the dict interface, that can be implemented in subclasses of > dict? Absolutely. ~Ethan~ From howe.steven at gmail.com Tue Aug 3 21:34:30 2010 From: howe.steven at gmail.com (GrayShark) Date: Tue, 03 Aug 2010 20:34:30 -0500 Subject: PIL References: <882435.39022.qm@web51008.mail.re2.yahoo.com> Message-ID: As we seem to be at an impasse with respect to PIL and xpm, I know gimp does support saving as xpm and that gimp has a python language console. Perhaps parvini_navid at yahoo.com, could look to the gimp mailing list for help? Steven On Tue, 03 Aug 2010 01:56:20 -0700, Chris Rebert wrote: > On Tue, Aug 3, 2010 at 1:45 AM, Navid Parvini > wrote: >> Dear All, >> >> I want to convert a .png file to .xpm using PIL. I used the following >> command: Image.open( "t1.png").save("a1.xpm"). But it doesn't work and >> I could not convert it. >> >> Would you please help me and let me know that how can I convert/save >> .xpm files in PIL. > > PIL only supports reading .XPM, not writing .XPM: > http://www.pythonware.com/library/pil/handbook/format-xpm.htm > > Cheers, > Chris From nikos.the.gr33k at gmail.com Tue Aug 3 21:41:42 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Tue, 3 Aug 2010 18:41:42 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> Message-ID: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> >On 3 ???, 21:00, Dave Angel wrote: > A string is an object containing characters. A string literal is one of > the ways you create such an object. When you create it that way, you > need to make sure the compiler knows the correct encoding, by using the > encoding: line at beginning of file. mymessage = "????????" <==== string mymessage = u"????????" <==== string literal? So, a string literal is one of the encodings i use to create a string object? Can the encodign of a python script file be in iso-8859-7 which means the file contents is saved to the hdd as greek-iso but the part of this variabel value mymessage = u"????????" is saved as utf-8 ot the opposite? have the file saved as utf-8 but one variuable value as greek encoding? Encodings still give me headaches. I try to understand them as different ways to store data in a media. Tell me something. What encoding should i pick for my scripts knowing that only contain english + greek chars?? iso-8859-7 or utf-8 and why? Can i save the sting lets say "?????" in different encodings and still print out correctly in browser? ascii = the standard english character set only, right? > The web server wraps a few characters before and after your html stream, > but it shouldn't touch the stream itself. So the pythoon compiler using the cgi module is the one that is producing the html output that immediately after send to the web server, right? > > For example if i say mymessage = "????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the > > 2nd its a utf-8 one? > > No, the first is an 8 bit copy of whatever bytes your editor happened to > save. But since mymessage = "????????" is a string containing greek characaters why the editor doesn't save it as such? It reminds me of varibles an valeus where if you say a = 5 , a var becomes instantly an integer variable while a = 'hello' , become instantly a string variable > mymessage = u"????????" > > creates an object that is *not* encoded. Because it isn't saved by the editor yet? In what satet is this object in before it gets encoded? And it egts encoded the minute i tell the editor to save the file? > Encoding is taking the unicode > stream and representing it as a stream of bytes, which may or may have > more bytes than the original has characters. So this line mymessage = u"????????" what it does is tell the browser thats when its time to save the whole file to save this string as utf-8? If yes, then if were to save the above string as greek encoding how was i suppose to right it? Also if u ise the 'coding line' in the beggining of the file is there a need for using the u literal? > I personally haven't done any cookie code. If I were debugging this, I'd > factor out the multiple parts of that if statement, and find out which > one isn't true. From here I can't guess. I did what you say and foudn out that both of the if condition parts were always false thast why the if code blck never got executed. And it is alwsy wrong because the cookie never gets set. So can you please tell me why this line cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie will expire in an year never created a cookie? From invalid at invalid.invalid Tue Aug 3 21:57:09 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 01:57:09 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> I've always thought Ada was a pretty nice embedded/systems languages, >> but some of the initial implementations were indede horrible. > > Well, there?s GNAT, the GNU Ada implementation. Seems pretty robust and > complete, while offering backward compatibility with some of those ?initial > implementations?, presumably because people have so much code already > written for them. Yep, I've installed Gnat a couple times with the intention of playing around with it, but there's pretty much zero chance I could sell it at the office in place of C/C++ for embedded stuff, and for desktop stuff it's just way to easy to get programs done using Python. I also looked at Modula-3 once, and thought it had some real promise, but I think it's probably deader than Ada now. -- Grant From no.email at nospam.invalid Tue Aug 3 22:07:26 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 19:07:26 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> Message-ID: <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Grant Edwards writes: > Yep, I've installed Gnat a couple times with the intention of playing > around with it, but there's pretty much zero chance I could sell it at > the office in place of C/C++ for embedded stuff, I wonder what the issues are. From everything I've heard, it's a pretty good compiler. It does ok against C/C++ in the Alioth shootouts. I haven't written anything in it beyond "hello world" but I've looked at the wikibook about it and that intro piece that I linked earlier. It's more verbose than C, so coding in it takes more keystrokes, but it looks to me like the general coding approach (modulo the extra keystrokes) should be similar to that of C, Algol, and so on, and the results should be quite a bit more reliable. Mozilla is fed up with C++ and seems to be working on its own language, called Rust: http://lambda-the-ultimate.org/node/4009 From kerensaelise at hotmail.com Tue Aug 3 22:14:30 2010 From: kerensaelise at hotmail.com (elsa) Date: Tue, 3 Aug 2010 19:14:30 -0700 (PDT) Subject: parsing tab and newline delimited text Message-ID: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Hi, I have a large file of text I need to parse. Individual 'entries' are separated by newline characters, while fields within each entry are separated by tab characters. So, an individual entry might have this form (in printed form): Title date position data with each field separated by tabs, and a newline at the end of data. So, I thought I could simply open a file, read each line in in turn, and parse it.... f=open('MyFile') line=f.readline() parts=line.split('\t') etc... However, 'data' is a fairly random string of characters. Because the files I'm processing are large, there is a good chance that in every file, there is a data field that might look like this: 899998dlKKlS\lk3#kdf\nllllKK99 or like this: LLLSDKJJJdkkf334$\ttttks)))K99 so, you see the random strings '\n' and '\t' are stopping me from being able to parse my file correctly. Any suggestions on how to overcome this problem would be greatly appreciated. Many thanks, Elsa From prologic at shortcircuit.net.au Tue Aug 3 22:32:10 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 4 Aug 2010 12:32:10 +1000 Subject: parsing tab and newline delimited text In-Reply-To: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: On Wed, Aug 4, 2010 at 12:14 PM, elsa wrote: > I have a large file of text I need to parse. Individual 'entries' are > separated by newline characters, while fields within each entry are > separated by tab characters. Sounds to me like a job of the csv module. cheers James -- -- James Mills -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Tue Aug 3 22:36:20 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 3 Aug 2010 19:36:20 -0700 Subject: Trying to set a cookie within a python script In-Reply-To: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: 2010/8/3 ????? : >>On 3 ???, 21:00, Dave Angel wrote: > >> A string is an object containing characters. A string literal is one of >> the ways you create such an object. When you create it that way, you >> need to make sure the compiler knows the correct encoding, by using the >> encoding: line at beginning of file. > > > mymessage = "????????" ? <==== string > mymessage = u"????????" ?<==== string literal? Not quite. A literal is the actual string in the file, those letters between the quotes: "????????" <=== String literal (a literal value of the string/str type) u"????????" <=== Unicode literal (a literal value of the Unicode type. The bytes on the page will be converted to unicode using the file's encoding) mymessage <==== String (not literal, because it's a value) > > So, a string literal is one of the encodings i use to create a string > object? > > Can the encodign of a python script file be in iso-8859-7 which means > the file contents is saved to the hdd as greek-iso but the part of > this variabel value mymessage = u"????????" is saved as utf-8 ot the > opposite? > The compiler does not see u"????????" on the page. All it sees is the bytes ['0x75', '0x22', '0xea', '0xe1', '0xeb', '0xe7', '0xec', '0xdd', '0xf1', '0xe1', '0x22'] Now the compiler knows that the sequence 0x75 0x22 (Stuff) 0x22 means to create a Unicode literal. So it takes those bytes ('0xea', '0xe1', '0xeb', '0xe7', '0xec', '0xdd', '0xf1', '0xe1') and decodes them using the pages encoding, in your case ISO-8859-7. At this point, they don't have an encoding. They aren't bytes as far as you are concerned, they are code points. Internally, they're stored as either UTF-16 or UTF-32 depending on how Python was compiled, but that doesn't matter. You can treat them as if they are characters. > have the file saved as utf-8 but one variuable value as greek > encoding? > Sure you can. A unicode literal will always have the encoding of the file. But a string is just a sequence of bytes (forget about the characters that show up on the page for now). If you do "\xce\xba\xce\xb1\xce\xbb\xce\xb7\xce\xbc\xce\xad\xcf\x81\xce\xb1".encode('UTF-8') Then Python will take that sequence of bytes and interpret them as UTF-8. That will give you the same Unicode string you started out with: u"????????" > Encodings still give me headaches. I try to understand them as > different ways to store data in a media. > > Tell me something. What encoding should i pick for my scripts knowing > that only contain english + greek chars?? > iso-8859-7 or utf-8 and why? > > Can i save the sting lets say "?????" in different encodings and still > print out correctly in browser? > > ascii = the standard english character set only, right? > Yes. >> The web server wraps a few characters before and after your html stream, >> but it shouldn't touch the stream itself. > > So the pythoon compiler using the cgi module is the one that is > producing the html output that immediately after send to the web > server, right? > > >> > For example if i say mymessage = "????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the >> > 2nd its a utf-8 one? No. They both are in whatever encoding your file is using. But the first one will be interpreted as a sequence of bytes. the second one will be interpreted as a sequence of characters. For a single-byte encoding like ISO-8859-7, it doesn't make a difference. But if you were to encode it in UTF-8, the first one would have a length of 16 (because the Greek characters are all 2 bytes) and the 2nd one would have a length of 8. >> >> No, the first is an 8 bit copy of whatever bytes your editor happened to >> save. > > But since mymessage = "????????" is a string containing greek > characaters why the editor doesn't save it as such? > Because you don't save characters, you save bytes. \xce\xba\xce\xb1\xce\xbb\xce\xb7\xce\xbc\xce\xad\xcf\x81\xce\xb1 is your String in UTF-8 \xea\xe1\xeb\xe7\xec\xdd\xf1\xe1 is that exact same string in ISO-8859-7 They are two different ways of representing the same characters > It reminds me of varibles an valeus where if you say > > a = 5 , a var becomes instantly an integer variable > while > a = 'hello' , become instantly a string variable > > >> mymessage = u"????????" >> >> creates an object that is *not* encoded. > > Because it isn't saved by the editor yet? In what satet is this object > in before it gets encoded? > And it egts encoded the minute i tell the editor to save the file? > >> Encoding is taking the unicode >> stream and representing it as a stream of bytes, which may or may have >> more bytes than the original has characters. > > > So this line mymessage = u"????????" what it does is tell the browser > thats when its time to save the whole file to save this string as > utf-8? > > If yes, then if were to save the above string as greek encoding how > was i suppose to right it? > > Also if u ise the 'coding line' in the beggining of the file is there > a need for using the u literal? > >> I personally haven't done any cookie code. If I were debugging this, I'd >> factor out the multiple parts of that if statement, and find out which >> one isn't true. From here I can't guess. > > I did what you say and foudn out that both of the if condition parts > were always false thast why the if code blck never got executed. > > And it is alwsy wrong because the cookie never gets set. > > So can you please tell me why this line > > cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) ? ? ? ? ?#this cookie > will expire in an year > > never created a cookie? > -- > http://mail.python.org/mailman/listinfo/python-list > From invalid at invalid.invalid Tue Aug 3 22:41:01 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 02:41:01 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Paul Rubin wrote: > Grant Edwards writes: > >> Yep, I've installed Gnat a couple times with the intention of playing >> around with it, but there's pretty much zero chance I could sell it >> at the office in place of C/C++ for embedded stuff, > > I wonder what the issues are. The issue that would prevent its use where I work is the inability to hire anybody who knows Ada. You can't hire anybody who knows C++ either, but you can hire lots of people who claim they do. [I'm not convinced that there are more than about 6 people on the planet who know C++ well enough that they should be writing real projects in it.] That said, the last time I looked the Ada spec was only something like 100 pages long, so a case could be made that it won't take long to learn. I don't know how long the C++ language spec is, but I'm betting it's closer to 1000 than 100. But I failed when I tried to get people to use Python, so I doubt I'd have any better luck with Ada. > From everything I've heard, it's a pretty good compiler. I think it's probably a very good compiler. It's the compiler users that are the issue. > It does ok against C/C++ in the Alioth shootouts. I haven't written > anything in it beyond "hello world" but I've looked at the wikibook > about it and that intro piece that I linked earlier. It's more > verbose than C, The verbosity always bugged me a little. To my eyes all the sugar gets in the way of seeing the code. Somebody should invent a language where indentation defines the blocks. > so coding in it takes more keystrokes, but it looks to me like the > general coding approach (modulo the extra keystrokes) should be > similar to that of C, Algol, and so on, and the results should be > quite a bit more reliable. Indeed. > Mozilla is fed up with C++ and seems to be working on its own language, > called Rust: > > http://lambda-the-ultimate.org/node/4009 Great! The world needs one more computer language... -- Grant From jjposner at optimum.net Tue Aug 3 22:49:06 2010 From: jjposner at optimum.net (John Posner) Date: Tue, 03 Aug 2010 22:49:06 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4C578663.8000804@optimum.net> <4C588925.1060505@optimum.net> <4C589305.40903@stoneleaf.us> Message-ID: <4C58D522.9070509@optimum.net> On 8/3/2010 6:48 PM, Ethan Furman wrote: > Christian Heimes wrote: >>> I just went and read the entry that had the bogus claim -- >>> personally, I didn't see any confusion. I would like to point out the >>> __missing__ is *not* part of dicts (tested on 2.5 and 2.6 -- don't >>> have 2.7 installed yet). >> >> I beg your pardon but you are wrong. __missing__ is available for all >> *subclasses* of dict since Python 2.5. See >> http://svn.python.org/view/python/branches/release25-maint/Objects/dictobject.c?revision=81031&view=markup >> >> >>>>> class mydict(dict): >> ... def __missing__(self, key): >> ... print "__missing__", key >> ... raise KeyError(key) >> ... >>>>> m = mydict() >>>>> m[1] >> __missing__ 1 >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 4, in __missing__ >> KeyError: 1 > > Perhaps punctuation will help clarify my intent: > > __missing__ is *not* part of (dict)s, as shown by dir(dict()): > > ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', > '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', > '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', > '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', > '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', > 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', > 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', > 'values'] > > And, just to state what is hopefully obvious, if you don't create > __missing__ yourself, it still isn't in the subclass: Right, a __missing__ method does not magically appear in the subclass. Rather, the subclass is allowed (but not required) to define a method named __missing__, which will "magically" be called in certain situations. Here's a dict subclass that uses the "magic" for a purpose that has nothing to do with default values: class BadKeyTrackerDict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.bad_keys = set([]) def __missing__(self, key): """ add missing key to "bad keys" set """ self.bad_keys.add(key) raise KeyError Note that "defaultdict" is nowhere in sight here. It's the dict class (or type) itself that provides the magic -- but only for its subclasses. > > --> class somedict(dict): > ... "Is __missing__ defined if I don't define it? Nope." > ... > --> sd = somedict() > --> sd[1] > Traceback (most recent call last): > File "", line 1, in > KeyError: 1 > --> dir(sd) > ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', > '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__', > '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', > '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', > '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', > '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', > 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', > 'setdefault', 'update', 'values'] > > ~Ethan~ -John From python at mrabarnett.plus.com Tue Aug 3 22:49:22 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 04 Aug 2010 03:49:22 +0100 Subject: Trying to set a cookie within a python script In-Reply-To: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: <4C58D532.3010709@mrabarnett.plus.com> ????? wrote: >> On 3 ???, 21:00, Dave Angel wrote: > >> A string is an object containing characters. A string literal is one of >> the ways you create such an object. When you create it that way, you >> need to make sure the compiler knows the correct encoding, by using the >> encoding: line at beginning of file. > [snip] > Tell me something. What encoding should i pick for my scripts knowing > that only contain english + greek chars?? > iso-8859-7 or utf-8 and why? > This is easy to answer: UTF-8 with the: # -*- coding: UTF-8 -*- comment to tell Python that your script file is encoded in UTF-8. I was once given a file in a language I don't know (translations for display messages). Some of the text didn't look quite right. It took me a while to figure out that it was written on a machine which used CP1250 and my machine used CP1252. If everybody used the same encoding then such problems wouldn't occur, and UTF-8 can handle any characters which are in Unicode: Latin, Greek, Cyrillic, Arabic, etc. From python.list at tim.thechases.com Tue Aug 3 22:49:57 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 03 Aug 2010 21:49:57 -0500 Subject: parsing tab and newline delimited text In-Reply-To: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: <4C58D555.3000307@tim.thechases.com> On 08/03/10 21:14, elsa wrote: > I have a large file of text I need to parse. Individual 'entries' are > separated by newline characters, while fields within each entry are > separated by tab characters. > > So, an individual entry might have this form (in printed form): > > Title date position data > > with each field separated by tabs, and a newline at the end of data. > So, I thought I could simply open a file, read each line in in turn, > and parse it.... > > f=open('MyFile') > line=f.readline() > parts=line.split('\t') > > etc... > > However, 'data' is a fairly random string of characters. Because the > files I'm processing are large, there is a good chance that in every > file, there is a data field that might look like this: > > 899998dlKKlS\lk3#kdf\nllllKK99 My first question is whether the line contains actual newline/tab characters within the field data, or the string-representation of the line. For one of the lines in question, what does print repr(line) (or "print line.encode('hex')") produce? If the line has extra literal tabs, then you may be stuck; if the line has escaped text (a backslash followed by an "n" or "t", i.e. 2 characters) then it's pretty straight-forward. Ideally, you'd see something like >>> print repr(line) 'MyTitle\t2010-08-02\t42\t89998dlKKlS\\lk3#kdf\\nlllKK99' ^tab ^tab ^tab ^backslash^ where the backslashes are literal. If you know that it's the last ("data") field that can contain such characters, you can at least catch non-newline characters by only splitting the first N splits: parts = line.split('\t', 3) That doesn't solve the newline problem, but your file's definition prevents you from being able to discern filedata = 'title1\tdate1\tpos1\tdata1\nxxxx\tyyyy\tzzzz\twwww\n' Would xxxx/yyyy/zzzz/wwww be a continuation of data1 or are they the items in the next row? -tkc From no.email at nospam.invalid Tue Aug 3 23:02:09 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 20:02:09 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: <7xfwyvw05q.fsf@ruckus.brouhaha.com> Grant Edwards writes: > The issue that would prevent its use where I work is the inability to > hire anybody who knows Ada. ... > That said, the last time I looked the Ada spec was only something like > 100 pages long, so a case could be made that it won't take long to > learn. Well, I don't know Ada (I've read about it but not written actual code), so maybe I shouldn't be the one saying this, but geez, it's another imperative, procedural language, like Algol or Pascal or even C. Its type is much more serious than C's but shouldn't be a problem for anyone who uses C++ or Java generics. It also has a real module system unlike more commonly used languages, but 1) that part seems easy to understand; and 2) usually that's used for multi-programmer projects, so as long as there's some reasonable proportion of experienced users on the team, the inter-module interfaces should be sensible and less experienced users can just program to existing interfaces and/or get some help from others. Ada's module system is much simpler than (say) ML's. > I don't know how long the C++ language spec is, but I'm > betting it's closer to 1000 than 100. I don't know about an official spec. Stroustrup's "The C++ programming language" is about 1000 pp, but it's a textbook, with lots of examples, exercises, etc. I read through an earlier (shorter) edition in a couple of evenings a long time ago and it all made sense. It has some hairy aspects like the notorious template metaprogramming, but most users simply won't get involved with that. Python has its own obscure and confusing features if that matters. I think I'm a reasonably good Python programmer but I've never written a special metaclass and wouldn't really know how to. From python at mrabarnett.plus.com Tue Aug 3 23:05:56 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 04 Aug 2010 04:05:56 +0100 Subject: parsing tab and newline delimited text In-Reply-To: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: <4C58D914.6090907@mrabarnett.plus.com> elsa wrote: > Hi, > > I have a large file of text I need to parse. Individual 'entries' are > separated by newline characters, while fields within each entry are > separated by tab characters. > > So, an individual entry might have this form (in printed form): > > Title date position data > > with each field separated by tabs, and a newline at the end of data. > So, I thought I could simply open a file, read each line in in turn, > and parse it.... > > f=open('MyFile') > line=f.readline() > parts=line.split('\t') > > etc... > > However, 'data' is a fairly random string of characters. Because the > files I'm processing are large, there is a good chance that in every > file, there is a data field that might look like this: > > 899998dlKKlS\lk3#kdf\nllllKK99 > > or like this: > > LLLSDKJJJdkkf334$\ttttks)))K99 > > so, you see the random strings '\n' and '\t' are stopping me from > being able to parse my file correctly. Any > suggestions on how to overcome this problem would be greatly > appreciated. > When you say random strings '\n', etc, are they the backslash character \ followed by the letter n? If so, then you don't have a problem. They are \ followed by n. If, on the other hand, by '\n' you mean the newline character, then, well, that's a newline character, and there's (probably) nothing you can do about it. From sturlamolden at yahoo.no Tue Aug 3 23:08:03 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 3 Aug 2010 20:08:03 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: On 4 Aug, 04:41, Grant Edwards wrote: > The issue that would prevent its use where I work is the inability to > hire anybody who knows Ada. ?You can't hire anybody who knows C++ > either, but you can hire lots of people who claim they do. ? That is very true. From nikos.the.gr33k at gmail.com Tue Aug 3 23:08:46 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Tue, 3 Aug 2010 20:08:46 -0700 (PDT) Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: <0c4d0b86-b5b6-48f9-ba26-b8c344df2d83@t20g2000yqa.googlegroups.com> For the cookie problem iam tryign houts now and even this aint working: ======================================== cookie = Cookie.SimpleCookie() if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') == 'nikos': #if visitor cookie exist print "Cookie Unset" cookie['visitor'] = 'nikos' cookie['visitor']['expires'] = -1 #this cookie will expire now else: print "Cookie is set!" cookie['visitor'] = 'nikos' cookie['visitor']['expires'] = 1000 #this cookie will expire now ======================================== i tried in IDLE enviroment as well and for some reason even with a single number isnated of time() function the cookie is never set, because the print of >>>print os.environ.get('HTTP_COOKIE') result to None :( From kerensaelise at hotmail.com Tue Aug 3 23:35:34 2010 From: kerensaelise at hotmail.com (elsa) Date: Tue, 3 Aug 2010 20:35:34 -0700 (PDT) Subject: parsing tab and newline delimited text References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: <5ac28f2f-a751-4856-ba4d-c766eafe80e2@s17g2000prh.googlegroups.com> On Aug 4, 12:49?pm, Tim Chase wrote: > On 08/03/10 21:14, elsa wrote: > > > > > I have a large file of text I need to parse. Individual 'entries' are > > separated by newline characters, while fields within each entry are > > separated by tab characters. > > > So, an individual entry might have this form (in printed form): > > > Title ? ?date ? position ? data > > > with each field separated by tabs, and a newline at the end of data. > > So, I thought I could simply open a file, read each line in in turn, > > and parse it.... > > > f=open('MyFile') > > line=f.readline() > > parts=line.split('\t') > > > etc... > > > However, 'data' is a fairly random string of characters. Because the > > files I'm processing are large, there is a good chance that in every > > file, there is a data field that might look like this: > > > 899998dlKKlS\lk3#kdf\nllllKK99 > > My first question is whether the line contains actual newline/tab > characters within the field data, or the string-representation of > the line. ?For one of the lines in question, what does > > ? ?print repr(line) here is what I get at the interactive prompt: >>> line = """IIIIIIIIIIIIIIIIIIIIIG=4448>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIG666HIIIIII;;;IIIIIIEIIII??55 ... :E?IEEEEFHGCACIIIII699;66IG11G???IIIIIIIIIIIIG???GGGII@@@@GG?;; 9>CCIIIIIIIIIIICCCCGHHIIIGEEDBB?9951//////6=ABB=EEGII98AEIECCC>>;A=F@;; 44//11::=<>> line 'IIIIIIIIIIIIIIIIIIIIIG=4448>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIG666HIIIIII;;;IIIIIIEIIII?? 55\n:E?IEEEEFHGCACIIIII699;66IG11G???IIIIIIIIIIIIG???GGGII@@@@GG?;; 9>CCIIIIIIIIIIICCCCGHHIIIGEEDBB?9951//////6=ABB=EEGII98AEIECCC>>;A=F@;; 44//11::=<>> print repr(line) 'IIIIIIIIIIIIIIIIIIIIIG=4448>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIG666HIIIIII;;;IIIIIIEIIII?? 55\n:E?IEEEEFHGCACIIIII699;66IG11G???IIIIIIIIIIIIG???GGGII@@@@GG?;; 9>CCIIIIIIIIIIICCCCGHHIIIGEEDBB?9951//////6=ABB=EEGII98AEIECCC>>;A=F@;; 44//11::=< <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: On Aug 3, 7:07?pm, Paul Rubin wrote: > Mozilla is fed up with C++ and seems to be working on its own language, > called Rust: > > ? ?http://lambda-the-ultimate.org/node/4009 That looks much better than Go. It's like all the cool features of Go without the annoying polemics. I'm starting to get the feeling one of these languages is going to hit a sweet spot and turn C into the next Cobol. Carl Banks From murraywk at gmail.com Tue Aug 3 23:39:22 2010 From: murraywk at gmail.com (wazza) Date: Tue, 3 Aug 2010 20:39:22 -0700 (PDT) Subject: Loading pyd fails with "The operating system cannot run %1" Message-ID: <65b65b69-a5e9-4356-a2a9-85c4a508edb7@g6g2000pro.googlegroups.com> Running python 2.6 (r26:66714) on Win Xp Pro SP3, I receive the following message: python -v -v -v >>> import functions . . # trying U:\wss\v72212\components\trm\python\lib\lib\site-packages \_fk_cl.pyd # clear[2] __file__ # clear[2] __package__ # clear[2] __path__ # clear[2] __name__ # clear[2] __doc__ # clear[2] __name__ # clear[2] __file__ Traceback (most recent call last): File "", line 1, in File "u:\wss\v72212\components\trm\python\lib\lib\site-packages \functions.py", line 1, in import FK.Core File "U:\wss\v72212\components\trm\python\lib\lib\site-packages\FK \Core\__init__.py", line 19, in from _fk_cl import * ImportError: DLL load failed: The operating system cannot run %1. Tracking this back, this represents an error code in windows: ERROR_INVALID_ORDINAL 182 (0xB6) The web has been unhelpful on what this represents. This works for people on other computers with the same configuration. I have python 2.6 loaded locally. Any ideas? I thought perhaps file associations in windows, but there are none for .pyd files. From navkirats at gmail.com Wed Aug 4 00:00:22 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 09:30:22 +0530 Subject: Global variables problem Message-ID: Hey guys, I am using a multiprocessing program, where the new process is supposed to change a variable in the main class that it branches out from. This is somehow not working, following is an approximate code. Would really appreciate any insight into this matter: var = {} class Something(): def set_var(self): global var var = somevalue def get_var(self): return var def newprocess(self): self.set_var() def do_multiprocessing(self): while true: self.get_var() new_process = process(target=newprocess) new_process.start() I am really confused here ! Any help would be awesome : ) Regards, Nav From roy at panix.com Wed Aug 4 00:00:41 2010 From: roy at panix.com (Roy Smith) Date: Wed, 04 Aug 2010 00:00:41 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In article , sturlamolden wrote: > On 4 Aug, 04:41, Grant Edwards wrote: > > > The issue that would prevent its use where I work is the inability to > > hire anybody who knows Ada. ?You can't hire anybody who knows C++ > > either, but you can hire lots of people who claim they do. ? > > That is very true. I suspect there are less than 100 people in the world who "know C++" in the sense that they know every feature, every detail, every quirk. These are the people who sit on the standards committee, write the books we all buy, etc. There are, however, a lot of people who know a large enough subset of C++ to be productive and to write effective, safe, quality code within those boundaries. These people know what they don't know and either avoid using those features, or know where (and when) to look it up. I put myself in that camp. The problem is, there are also a very large number of people who put "expert C++" on their resumes and know just enough to be dangerous. The real problem is that it's sometimes difficult to distinguish between the members of the latter two groups in an interview. From cbrauchli at gmail.com Wed Aug 4 00:01:38 2010 From: cbrauchli at gmail.com (Chris Brauchli) Date: Tue, 3 Aug 2010 21:01:38 -0700 (PDT) Subject: Python Script Cannot Write to Directory Message-ID: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> Hi, I am writing a script that, at one point, copies a file from directory A to directory B. Directory B can only be written to by root, but the script is always called with sudo, so this shouldn't be an issue, but it is. I have tried using shutil.copy() and calling "sudo cp " with os.popen to no avail. I cannot get the script to copy a file to directory B. The strange thing is if I run the python interpreter (as sudo) and type in shutil.copy it works. It also works if I try to copy the file to a less protected directory. It only happens when I try to copy a file to directory B from a python script. Any ideas why this is happening? If more information is needed or something isn't clear let me know. Thanks for helping. Chris From ddasilva at umd.edu Wed Aug 4 00:16:51 2010 From: ddasilva at umd.edu (Daniel da Silva) Date: Tue, 3 Aug 2010 21:16:51 -0700 Subject: Global variables problem In-Reply-To: References: Message-ID: Please post approximate code that actually works and displays the problem. On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: > Hey guys, > > I am using a multiprocessing program, where the new process is supposed to > change a variable in the main class that it branches out from. This is > somehow not working, following is an approximate code. Would really > appreciate any insight into this matter: > > > var = {} > > class Something(): > > def set_var(self): > global var > var = somevalue > > def get_var(self): > return var > > def newprocess(self): > self.set_var() > > def do_multiprocessing(self): > while true: > self.get_var() > new_process = process(target=newprocess) > new_process.start() > > > I am really confused here ! > > Any help would be awesome : ) > > Regards, > Nav > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From navkirats at gmail.com Wed Aug 4 00:48:52 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 10:18:52 +0530 Subject: Global variables problem In-Reply-To: References: Message-ID: On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: > Please post approximate code that actually works and displays the problem. > > On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: > Hey guys, > > I am using a multiprocessing program, where the new process is supposed to change a variable in the main class that it branches out from. This is somehow not working, following is an approximate code. Would really appreciate any insight into this matter: > > > var = {} > > class Something(): > > def set_var(self): > global var > var = somevalue > > def get_var(self): > return var > > def newprocess(self): > self.set_var() > > def do_multiprocessing(self): > while true: > self.get_var() > new_process = process(target=newprocess) > new_process.start() > > > I am really confused here ! > > Any help would be awesome : ) > > Regards, > Nav > > -- > http://mail.python.org/mailman/listinfo/python-list > This is a working code, streamlined, but it is where the problem is: from multiprocessing import * dicts = 0 print('global ', dicts) class WebServer(): def set_sessionInfo(self): global dicts dicts = dicts + 1 def get_sessionInfo(self): return dicts def handle_connection(self): self.set_sessionInfo() def serve_forever(self): for x in range(10): p = Process(target=self.handle_connection) p.start() print(self.get_sessionInfo()) ws = WebServer() ws.serve_forever() print(dicts) -------------- next part -------------- An HTML attachment was scrubbed... URL: From marduk at letterboxes.org Wed Aug 4 00:57:33 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 04 Aug 2010 00:57:33 -0400 Subject: Python Script Cannot Write to Directory In-Reply-To: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> Message-ID: <1280897853.161893.0.camel@paska> On Tue, 2010-08-03 at 21:01 -0700, Chris Brauchli wrote: > Hi, > > I am writing a script that, at one point, copies a file from directory > A to directory B. Directory B can only be written to by root, but the > script is always called with sudo, so this shouldn't be an issue, but > it is. I have tried using shutil.copy() and calling "sudo cp " with > os.popen to no avail. I cannot get the script to copy a file to > directory B. The strange thing is if I run the python interpreter (as > sudo) and type in shutil.copy it works. It also works if I try to copy > the file to a less protected directory. It only happens when I try to > copy a file to directory B from a python script. > > Any ideas why this is happening? If more information is needed or > something isn't clear let me know. Thanks for helping. > > Chris Code? Traceback? From ldo at geek-central.gen.new_zealand Wed Aug 4 01:36:31 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 17:36:31 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In message <7xmxt3uo4h.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > It's more verbose than C, so coding in it takes more keystrokes, but it > looks to me like the general coding approach (modulo the extra keystrokes) > should be similar to that of C, Algol, and so on, and the results should > be quite a bit more reliable. I believe the life-support software on the International Space Station is written in Ada. Would anybody feel happier if that had been done in C++? From ldo at geek-central.gen.new_zealand Wed Aug 4 01:44:00 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 17:44 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In message , Grant Edwards wrote: > That said, the last time I looked the Ada spec was only something like > 100 pages long, so a case could be made that it won't take long to > learn. I don't know how long the C++ language spec is, but I'm > betting it's closer to 1000 than 100. I have a copy of ?The C++ Standard (Incorporating Technical Corrigendum No. 1)? on my bookshelf. Let?s see ... flip-flip ... the highest page number is 782. Definitely closer to 1000 than 100. As for Ada ... I don?t have any printed manual, but dpkg-query -L ada-reference-manual | grep -c html/aarm95tc1 counts 353 HTML pages for the annotated reference. I found it fairly tedious to read the lot. But then, I didn?t even try to do that with the C++ spec... From ldo at geek-central.gen.new_zealand Wed Aug 4 01:45:03 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 17:45:03 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In message , Roy Smith wrote: > There are, however, a lot of people who know a large enough subset of > C++ to be productive ... I think there are some language features, knowledge of which has a negative impact on productivity. :) From murraywk at gmail.com Wed Aug 4 01:45:31 2010 From: murraywk at gmail.com (wazza) Date: Tue, 3 Aug 2010 22:45:31 -0700 (PDT) Subject: Loading pyd fails with "The operating system cannot run %1" References: <65b65b69-a5e9-4356-a2a9-85c4a508edb7@g6g2000pro.googlegroups.com> Message-ID: <5e20ece0-e056-42b0-a2c4-3b3bc9cfff36@s24g2000pri.googlegroups.com> On Aug 4, 1:39?pm, wazza wrote: > Running python 2.6 (r26:66714) ?on Win Xp Pro SP3, I receive the > following message: > python -v -v -v>>> import functions > > . > . > > # trying U:\wss\v72212\components\trm\python\lib\lib\site-packages > \_fk_cl.pyd > # ? clear[2] __file__ > # ? clear[2] __package__ > # ? clear[2] __path__ > # ? clear[2] __name__ > # ? clear[2] __doc__ > # ? clear[2] __name__ > # ? clear[2] __file__ > Traceback (most recent call last): > ? File "", line 1, in > ? File "u:\wss\v72212\components\trm\python\lib\lib\site-packages > \functions.py", line 1, in > ? ? import FK.Core > ? File "U:\wss\v72212\components\trm\python\lib\lib\site-packages\FK > \Core\__init__.py", line 19, in > ? ? from _fk_cl import * > ImportError: DLL load failed: The operating system cannot run %1. > > Tracking this back, this represents an error code in windows: > > ERROR_INVALID_ORDINAL > 182 (0xB6) > > The web has been unhelpful on what this represents. > > This works for people on other computers with the same configuration. > I have python 2.6 loaded locally. > > Any ideas? I thought perhaps file associations in windows, but there > are none for .pyd files. OK Fixed it myself (maybe I should have looked deeper ebfore raising this post. I used dependency walker to check the dependencies of the pyd file. It indicated that libeay.dll had a problem (at least one module has an unresolved improt due to a missing export function in an implicity dependent module. Looked and sure enough it was in /windows/system32, dated 4/3/2008. There were 5 other instances on the box, from things like Yahoo widget engine, Landesk and vmware infrastructure server libeay.dll is part of the ssl library and must mismatch with some other parts of the application. In time honored manner, deleted from /windows/system32 (did not bother unregistering) and the problem is solved. From no.email at nospam.invalid Wed Aug 4 01:58:45 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 03 Aug 2010 22:58:45 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: <7xeieevrze.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > I believe the life-support software on the International Space Station is > written in Ada. Would anybody feel happier if that had been done in C++? Take a look at the articles on C bug-finding on Dawson Engler's page: http://www.stanford.edu/~engler/ They are about tools that found 100's of bugs in various large C programs including Linux and OpenBSD. Most of those bugs would probably not have been possible in Ada. Program bugs are generally either subtle errors or dumb ones. Humans always will make dumb errors from time to time, and C does almost nothing to prevent them (C++ used properly is somewhat better). Ada doesn't prevent the subtle ones but appears much better than C or C++ at preventing the dumb kind. I'm not sure what the hiring issue is. I think anyone skilled in C++ or Java can pick up Ada pretty easily. It's mostly a subset of C++ with different surface syntax. From ddasilva at umd.edu Wed Aug 4 02:02:25 2010 From: ddasilva at umd.edu (Daniel da Silva) Date: Tue, 3 Aug 2010 23:02:25 -0700 Subject: simple (I hope!) problem In-Reply-To: <4C57EAD1.5090709@sequans.com> References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> <4C57EAD1.5090709@sequans.com> Message-ID: Why not just add the google app engine lib subdirectories to your python path? On Tue, Aug 3, 2010 at 3:09 AM, Jean-Michel Pichavant < jeanmichel at sequans.com> wrote: > samwyse wrote: > >> I'm writing for the Google app engine and have stubbed my toe yet >> again on a simple obstacle. Non-trivial app engines programs require >> the import of several modules that aren't normally in my PYTHONPATH. >> I'd like to be able to test my code outside of the app engine >> framework. I've tried several solutions in the past that worked but >> weren't particularly elegant or portable. Now I've had a new idea. >> Here's my latest attempt: >> >> import os, re >> if __name__ == '__main__': >> pass >> else >> from google.appengine.ext import webapp >> register = webapp.template.create_template_register() >> >> This works great, except my code makes use of the resister object in >> several places, like this: >> >> register.filter(emptylines) >> >> Fortunately, I don't need the functionality of the object, I just want >> something that won't generate an error when I use it. So, what is the >> quickest way to to create such an object (replacing the 'pass' in my >> first snippet). My solution is this: >> >> class C: >> def filter(self, *args, **kwds): >> pass >> register = C() >> >> but it seems like I should be able to do something "better", as >> measured by lines of code, faking more than just a 'filter' method, or >> both. Any ideas? Thanks! >> >> > > here is a class that accepts any method call without generating an error: > > class Stub(object): > @staticmethod > def stub(*arg, **kwarg): > pass > def __getattribute__(self, name): > return Stub.stub > > > s = Stub() > s.foo('bar') > s.bar > s.bar('', '', 5) > > > JM > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nyamatongwe+thunder at gmail.com Wed Aug 4 02:10:29 2010 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 04 Aug 2010 16:10:29 +1000 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: Grant Edwards: > That said, the last time I looked the Ada spec was only something like > 100 pages long, so a case could be made that it won't take long to > learn. I don't know how long the C++ language spec is, but I'm > betting it's closer to 1000 than 100. The Ada 2012 Language Reference Manual is 860 pages and the Ada 2005 LRM was 790 pages. The annotated versions are even longer http://www.ada-auth.org/standards/ada12.html Neil From ddasilva at umd.edu Wed Aug 4 02:12:22 2010 From: ddasilva at umd.edu (Daniel da Silva) Date: Tue, 3 Aug 2010 23:12:22 -0700 Subject: Global variables problem In-Reply-To: References: Message-ID: Your problem lies somewhere in the use of the Process class, not with global variables. If you replace your "p = ..." and "p.start()" lines with a direct call to self.handle_connection(), your code works as expected. I don't know much about the multiprocessing module, so I can't really comment on what you're doing wrong, but I hope this points you in the right direction. Sorry I couldn't be of more help, Daniel On Tue, Aug 3, 2010 at 9:48 PM, Navkirat Singh wrote: > > On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: > > Please post approximate code that actually works and displays the problem. > > On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: > >> Hey guys, >> >> I am using a multiprocessing program, where the new process is supposed to >> change a variable in the main class that it branches out from. This is >> somehow not working, following is an approximate code. Would really >> appreciate any insight into this matter: >> >> >> var = {} >> >> class Something(): >> >> def set_var(self): >> global var >> var = somevalue >> >> def get_var(self): >> return var >> >> def newprocess(self): >> self.set_var() >> >> def do_multiprocessing(self): >> while true: >> self.get_var() >> new_process = process(target=newprocess) >> new_process.start() >> >> >> I am really confused here ! >> >> Any help would be awesome : ) >> >> Regards, >> Nav >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > This is a working code, streamlined, but it is where the problem is: > > from multiprocessing import * > > dicts = 0 > print('global ', dicts) > > class WebServer(): > def set_sessionInfo(self): > global dicts > dicts = dicts + 1 > def get_sessionInfo(self): > return dicts > > def handle_connection(self): > self.set_sessionInfo() > def serve_forever(self): > for x in range(10): > p = Process(target=self.handle_connection) > p.start() > print(self.get_sessionInfo()) > ws = WebServer() > ws.serve_forever() > print(dicts) > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Wed Aug 4 02:34:19 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 3 Aug 2010 23:34:19 -0700 (PDT) Subject: parsing tab and newline delimited text References: <3a9345a8-3799-472d-8eeb-e598997e91cf@v6g2000prd.googlegroups.com> Message-ID: On Aug 4, 12:14?pm, elsa wrote: > So, an individual entry might have this form (in printed form): > > Title ? ?date ? position ? data > > with each field separated by tabs, and a newline at the end of data. As James posted, the csv module is ideal for this sort of thing. Dealing with delimited text seems obvious but, as with most things, there are some edge cases that can bite you, so it's generally best to use utility code that has already dealt with them. If you're using Python 2.6+ you can use it in conjunction with namedtuple for some very easy record retrieval: >>> import csv >>> from collections import namedtuple >>> Record = namedtuple('Record', 'title date position data') >>> tabReader = csv.reader(open('test.txt','rb'), delimiter='\t') >>> for record in (Record(*row) for row in tabReader): ... print record.title, record.data ... title1 data1\t\n\n\t title2 data2\t\t\t\t title3 data3\n\n\n\n Hope this helps. From navkirats at gmail.com Wed Aug 4 03:11:48 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 12:41:48 +0530 Subject: Global variables problem In-Reply-To: References: Message-ID: <10BD3E87-FCC3-4C93-BD72-B8D3BBA4544B@gmail.com> Thanks a lot guys !! I solved the problem: In the lines: >> new_process = process(target=newprocess) >> new_process.start() The target=newprocess is pointing towards a variable, instead of a function. So, appending a () will make it goto that function, thereby changing the global variable : ) Thanks, Nav On 04-Aug-2010, at 11:42 AM, Daniel da Silva wrote: > Your problem lies somewhere in the use of the Process class, not with global variables. > > If you replace your "p = ..." and "p.start()" lines with a direct call to self.handle_connection(), your code works as expected. I don't know much about the multiprocessing module, so I can't really comment on what you're doing wrong, but I hope this points you in the right direction. > > Sorry I couldn't be of more help, > > Daniel > > > On Tue, Aug 3, 2010 at 9:48 PM, Navkirat Singh wrote: > > On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: > >> Please post approximate code that actually works and displays the problem. >> >> On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: >> Hey guys, >> >> I am using a multiprocessing program, where the new process is supposed to change a variable in the main class that it branches out from. This is somehow not working, following is an approximate code. Would really appreciate any insight into this matter: >> >> >> var = {} >> >> class Something(): >> >> def set_var(self): >> global var >> var = somevalue >> >> def get_var(self): >> return var >> >> def newprocess(self): >> self.set_var() >> >> def do_multiprocessing(self): >> while true: >> self.get_var() >> new_process = process(target=newprocess) >> new_process.start() >> >> >> I am really confused here ! >> >> Any help would be awesome : ) >> >> Regards, >> Nav >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > This is a working code, streamlined, but it is where the problem is: > > from multiprocessing import * > > dicts = 0 > print('global ', dicts) > > class WebServer(): > > def set_sessionInfo(self): > global dicts > dicts = dicts + 1 > > def get_sessionInfo(self): > return dicts > > def handle_connection(self): > self.set_sessionInfo() > > def serve_forever(self): > for x in range(10): > p = Process(target=self.handle_connection) > p.start() > print(self.get_sessionInfo()) > > ws = WebServer() > ws.serve_forever() > print(dicts) > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From news1234 at free.fr Wed Aug 4 03:21:20 2010 From: news1234 at free.fr (News123) Date: Wed, 04 Aug 2010 09:21:20 +0200 Subject: Python Script Cannot Write to Directory In-Reply-To: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> Message-ID: <4c5914f0$0$9192$426a74cc@news.free.fr> On 08/04/2010 06:01 AM, Chris Brauchli wrote: > Hi, > > I am writing a script that, at one point, copies a file from directory > A to directory B. Directory B can only be written to by root, but the > script is always called with sudo, so this shouldn't be an issue, but > it is. I have tried using shutil.copy() and calling "sudo cp " with > os.popen to no avail. I cannot get the script to copy a file to > directory B. The strange thing is if I run the python interpreter (as > sudo) and type in shutil.copy it works. It also works if I try to copy > the file to a less protected directory. It only happens when I try to > copy a file to directory B from a python script. > > Any ideas why this is happening? If more information is needed or > something isn't clear let me know. Thanks for helping. > a fiew suggestions suggestions: 1,) open a terminal window with sudo -s and make ALL of the following tests from this window. 2.) tell use the exact permissions of your destination directory ls -ld DESTINATION_DIRECTORY 3.) verify, whether the file you want to copy exists already in the destination directory ls -l DESTINATION_DIRECTORY/DSTNTN_FILE_NAME 3.) try following python import os print os.getcwd() import shutil shutil("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") 4.) try the same from a shell window cp YOUR_SOURCE_FILE_NAME DESTINATION_DIRECTORY/DSTNTN_FILE_NAME From clp2 at rebertia.com Wed Aug 4 03:27:53 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 4 Aug 2010 00:27:53 -0700 Subject: Python Script Cannot Write to Directory In-Reply-To: <4c5914f0$0$9192$426a74cc@news.free.fr> References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> Message-ID: On Wed, Aug 4, 2010 at 12:21 AM, News123 wrote: > 3.) try following python > > import os > print os.getcwd() > import shutil > shutil("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") WTF; modules aren't callable. Typo? Cheers, Chris -- http://blog.rebertia.com From navkirats at gmail.com Wed Aug 4 03:47:27 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 13:17:27 +0530 Subject: Global variables problem In-Reply-To: <10BD3E87-FCC3-4C93-BD72-B8D3BBA4544B@gmail.com> References: <10BD3E87-FCC3-4C93-BD72-B8D3BBA4544B@gmail.com> Message-ID: <9BEC53A5-C8AD-43A0-8901-99F9143FA764@gmail.com> : ( False alarm, the earlier solution breaks multiprocessing. Whats happening here is the child needs to change a variable in the parent process, So I think I am looking at shared memory (maybe). Any suggestions? Regards, Nav On 04-Aug-2010, at 12:41 PM, Navkirat Singh wrote: > Thanks a lot guys !! > > I solved the problem: > > In the lines: > >>> new_process = process(target=newprocess) >>> new_process.start() > > > > The target=newprocess is pointing towards a variable, instead of a function. So, appending a () will make it goto that function, thereby changing the global variable : ) > > Thanks, > Nav > > > On 04-Aug-2010, at 11:42 AM, Daniel da Silva wrote: > >> Your problem lies somewhere in the use of the Process class, not with global variables. >> >> If you replace your "p = ..." and "p.start()" lines with a direct call to self.handle_connection(), your code works as expected. I don't know much about the multiprocessing module, so I can't really comment on what you're doing wrong, but I hope this points you in the right direction. >> >> Sorry I couldn't be of more help, >> >> Daniel >> >> >> On Tue, Aug 3, 2010 at 9:48 PM, Navkirat Singh wrote: >> >> On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: >> >>> Please post approximate code that actually works and displays the problem. >>> >>> On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh wrote: >>> Hey guys, >>> >>> I am using a multiprocessing program, where the new process is supposed to change a variable in the main class that it branches out from. This is somehow not working, following is an approximate code. Would really appreciate any insight into this matter: >>> >>> >>> var = {} >>> >>> class Something(): >>> >>> def set_var(self): >>> global var >>> var = somevalue >>> >>> def get_var(self): >>> return var >>> >>> def newprocess(self): >>> self.set_var() >>> >>> def do_multiprocessing(self): >>> while true: >>> self.get_var() >>> new_process = process(target=newprocess) >>> new_process.start() >>> >>> >>> I am really confused here ! >>> >>> Any help would be awesome : ) >>> >>> Regards, >>> Nav >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> This is a working code, streamlined, but it is where the problem is: >> >> from multiprocessing import * >> >> dicts = 0 >> print('global ', dicts) >> >> class WebServer(): >> >> def set_sessionInfo(self): >> global dicts >> dicts = dicts + 1 >> >> def get_sessionInfo(self): >> return dicts >> >> def handle_connection(self): >> self.set_sessionInfo() >> >> def serve_forever(self): >> for x in range(10): >> p = Process(target=self.handle_connection) >> p.start() >> print(self.get_sessionInfo()) >> >> ws = WebServer() >> ws.serve_forever() >> print(dicts) >> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Aug 4 03:53:00 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 4 Aug 2010 00:53:00 -0700 (PDT) Subject: Urrlib2 IncompleteRead error References: <4c0a0495-4728-40f9-ba2e-660466129a06@v23g2000vbi.googlegroups.com> Message-ID: <915a7702-8ae2-4b61-922e-45ca490c4183@u26g2000yqu.googlegroups.com> On 27 jul, 11:00, dirknbr wrote: > I am running urllib2.request and get this response when I do the read. > Any ideas what causes this? > > return response.read() > ? File "C:\Python26\lib\socket.py", line 329, in read > ? ? data = self._sock.recv(rbufsize) > ? File "C:\Python26\lib\httplib.py", line 518, in read > ? ? return self._read_chunked(amt) > ? File "C:\Python26\lib\httplib.py", line 561, in _read_chunked > ? ? raise IncompleteRead(''.join(value)) > IncompleteRead: IncompleteRead(3235 bytes read) Looks like a server error; a chunked transfer encoding finished before reaching the expected size. -- Gabriel Genellina From dotancohen at gmail.com Wed Aug 4 04:01:25 2010 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 4 Aug 2010 11:01:25 +0300 Subject: Trying to set a cookie within a python script In-Reply-To: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: 2010/8/4 ????? : > Encodings still give me headaches. I try to understand them as > different ways to store data in a media. > > Tell me something. What encoding should i pick for my scripts knowing > that only contain english + greek chars?? > iso-8859-7 or utf-8 and why? > Always use UTF-8, every modern system supports it, and it will let you use any arbitrary character that you need, such as maybe a smiley or a Euro sign. You will avoid headaches with databases and files and all sorts of other things that you don't yet expect. Declare it in the HTTP header, and in the HTML meta tag. Trust me, I maintain gibberish.co.il which specializes in encoding problems. Just use UTF-8 everywhere and you will save a lot of headaches. > Can i save the sting lets say "?????" in different encodings and still > print out correctly in browser? > No. > ascii = the standard english character set only, right? > Pretty much, plus the numbers, some symbols, and a few nonprinting characters. Read here: http://en.wikipedia.org/wiki/Ascii -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From ldo at geek-central.gen.new_zealand Wed Aug 4 04:17:03 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 20:17:03 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: In message , Neil Hodgson wrote: > The Ada 2012 Language Reference Manual is 860 pages and the Ada 2005 > LRM was 790 pages. The annotated versions are even longer > http://www.ada-auth.org/standards/ada12.html Yeah, unfortunately the language was designed by a committee which was trying to meet a specification laid down by another committee set up by the US military. It seems apt to describe the resulting design as ?bulletproof?, but ?elegant? or ?concise? ... not so much. From landimatte at gmail.com Wed Aug 4 04:18:06 2010 From: landimatte at gmail.com (Matteo Landi) Date: Wed, 4 Aug 2010 10:18:06 +0200 Subject: Global variables problem In-Reply-To: <9BEC53A5-C8AD-43A0-8901-99F9143FA764@gmail.com> References: <10BD3E87-FCC3-4C93-BD72-B8D3BBA4544B@gmail.com> <9BEC53A5-C8AD-43A0-8901-99F9143FA764@gmail.com> Message-ID: Usually, modify global variables in a multi-thread/multi-process scenario is not the right to operate: you better re-implement your solution in a way that the shared resource is either protected with synchronized objects or accessed by a single thread/process (and in this case, it won't be a shared resource anymore). Think about the the needs of the shared resources: in this extremely simple example, you can see that the increment of the session number could be done by the server before spawning the child, but obviously this is not a real scenario. If you can't give up with shared resources, I recommend you to create a synchronized object owned by the server but shared with the children (take a look at the args keywords of the Process constructor). Regards. On Wed, Aug 4, 2010 at 9:47 AM, Navkirat Singh wrote: > ?: ( > False alarm, the earlier solution breaks multiprocessing. Whats happening > here is the child needs to change a variable in the parent process, So I > think I am looking at shared memory (maybe). Any suggestions? > Regards, > Nav > > > On 04-Aug-2010, at 12:41 PM, Navkirat Singh wrote: > > Thanks a lot guys !! > I solved the problem: > In the lines: >>> >>> new_process = process(target=newprocess) >>> ? ? ? ? ? ? ? ? ? ? ? ?new_process.start() > > The target=newprocess is pointing towards a variable, instead of a function. > So, appending a () will make it goto that function, thereby changing the > global variable : ) > Thanks, > Nav > > On 04-Aug-2010, at 11:42 AM, Daniel da Silva wrote: > > Your problem lies somewhere in the use of the Process class, not with global > variables. > > If you replace your "p = ..." and "p.start()" lines with a direct call to > self.handle_connection(), your code works as expected. I don't know much > about the multiprocessing module, so I can't really comment on what you're > doing wrong, but I hope this points you in the right direction. > > Sorry I couldn't be of more help, > > Daniel > > > On Tue, Aug 3, 2010 at 9:48 PM, Navkirat Singh wrote: >> >> On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: >> >> Please post approximate code that actually works and displays the problem. >> >> On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh >> wrote: >>> >>> Hey guys, >>> >>> I am using a multiprocessing program, where the new process is supposed >>> to change a variable in the main class that it branches out from. This is >>> somehow not working, following is an approximate code. Would really >>> appreciate any insight into this matter: >>> >>> >>> var = {} >>> >>> class Something(): >>> >>> ? ? ? ?def set_var(self): >>> ? ? ? ? ? ? ? ?global var >>> ? ? ? ? ? ? ? ?var = somevalue >>> >>> ? ? ? ?def get_var(self): >>> ? ? ? ? ? ? ? ?return var >>> >>> ? ? ? ?def newprocess(self): >>> ? ? ? ? ? ? ? ?self.set_var() >>> >>> ? ? ? ?def do_multiprocessing(self): >>> ? ? ? ? ? ? ? ?while true: >>> ? ? ? ? ? ? ? ? ? ? ? ?self.get_var() >>> ? ? ? ? ? ? ? ? ? ? ? ?new_process = process(target=newprocess) >>> ? ? ? ? ? ? ? ? ? ? ? ?new_process.start() >>> >>> >>> I am really confused here ! >>> >>> Any help would be awesome : ) >>> >>> Regards, >>> Nav >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> >> This is a working code, streamlined, but it is where the problem is: >> from multiprocessing import * >> dicts = 0 >> print('global ', dicts) >> class WebServer(): >> def set_sessionInfo(self): >> global dicts >> dicts = dicts + 1 >> def get_sessionInfo(self): >> return dicts >> def handle_connection(self): >> self.set_sessionInfo() >> def serve_forever(self): >> for x in range(10): >> p = Process(target=self.handle_connection) >> p.start() >> print(self.get_sessionInfo()) >> ws = WebServer() >> ws.serve_forever() >> print(dicts) >> > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Matteo Landi http://www.matteolandi.net/ From ldo at geek-central.gen.new_zealand Wed Aug 4 04:19:37 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 20:19:37 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> Message-ID: In message , Nobody wrote: > One feature which can't readily be implemented in C is the automatic > clean-up side of the RAII idiom. Use do-once blocks . From landimatte at gmail.com Wed Aug 4 04:20:50 2010 From: landimatte at gmail.com (Matteo Landi) Date: Wed, 4 Aug 2010 10:20:50 +0200 Subject: Python Script Cannot Write to Directory In-Reply-To: References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> Message-ID: On Wed, Aug 4, 2010 at 9:27 AM, Chris Rebert wrote: > On Wed, Aug 4, 2010 at 12:21 AM, News123 wrote: > >> 3.) try following python >> >> import os >> print os.getcwd() >> import shutil >> shutil("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") > > WTF; modules aren't callable. Typo? I suppose he/she would have written: shutil.copyfile("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") Cheers. > > Cheers, > Chris > -- > http://blog.rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From ldo at geek-central.gen.new_zealand Wed Aug 4 04:20:51 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 04 Aug 2010 20:20:51 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <0ed1fb16-87cb-4fb9-85b2-08d876445d5d@q22g2000yqm.googlegroups.com> <7d95c0d3-718d-4958-9364-263c833f1835@i24g2000yqa.googlegroups.com> Message-ID: In message <7d95c0d3-718d-4958-9364-263c833f1835 at i24g2000yqa.googlegroups.com>, sturlamolden wrote: > This is unsafe, anyone who writes this in C++ should be flogged: Only if they?re using exceptions. Otherwise, it?s fine. From maral.nikfar at gmail.com Wed Aug 4 05:12:44 2010 From: maral.nikfar at gmail.com (sarah) Date: Wed, 4 Aug 2010 02:12:44 -0700 (PDT) Subject: error: (113, 'Software caused connection abort')0 Message-ID: hi i face with this problem when i want to run this command on cygwin: python httpd.py 8000 example-300-1k-rigid.py Dfghfji12d52s35s2sswee9E with this error :0 Exception happened during processing of request from ('127.0.0.1', 35868) Traceback (most recent call last): File "/usr/local/lib/python2.5/SocketServer.py", line 222, in handle_reque self.process_request(request, client_address) File "/usr/local/lib/python2.5/SocketServer.py", line 241, in process_requ self.finish_request(request, client_address) File "/usr/local/lib/python2.5/SocketServer.py", line 254, in finish_reque self.RequestHandlerClass(request, client_address, self) File "/usr/local/lib/python2.5/SocketServer.py", line 522, in __init__ self.handle() File "/usr/local/lib/python2.5/BaseHTTPServer.py", line 316, in handle self.handle_one_request() File "/usr/local/lib/python2.5/BaseHTTPServer.py", line 310, in handle_one uest method() File "/usr/local/lib/python2.5/SimpleHTTPServer.py", line 46, in do_GET self.copyfile(f, self.wfile) File "/usr/local/lib/python2.5/SimpleHTTPServer.py", line 175, in copyfile shutil.copyfileobj(source, outputfile) File "/usr/local/lib/python2.5/shutil.py", line 29, in copyfileobj fdst.write(buf) File "/usr/local/lib/python2.5/socket.py", line 274, in write self.flush() File "/usr/local/lib/python2.5/socket.py", line 261, in flush self._sock.sendall(buffer) error: (104, 'Connection reset by peer') please help me i am hurry!1 From jeanmichel at sequans.com Wed Aug 4 05:15:44 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 04 Aug 2010 11:15:44 +0200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: <4C592FC0.5080603@sequans.com> Carl Banks wrote: > On Aug 3, 7:07 pm, Paul Rubin wrote: > >> Mozilla is fed up with C++ and seems to be working on its own language, >> called Rust: >> >> http://lambda-the-ultimate.org/node/4009 >> > > That looks much better than Go. > > It's like all the cool features of Go without the annoying polemics. > I'm starting to get the feeling one of these languages is going to hit > a sweet spot and turn C into the next Cobol. > > > Carl Banks > I hope you're right, for our children sanity :) JM From navkirats at gmail.com Wed Aug 4 05:20:59 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Wed, 4 Aug 2010 14:50:59 +0530 Subject: Difference between queues and pipes in multiprocessing Message-ID: <5E121D65-6150-4CC6-A35D-7834A81131AC@gmail.com> Hi, I was wondering what are the differences between queues and pipes implemented using multiprocessing python module. Am I correct if I say, in pipes, if another process writes to one receiving end concurrently, then an error will be raised and in queues the later processes data will just queued up? Thanks Nav From jeanmichel at sequans.com Wed Aug 4 05:24:30 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 04 Aug 2010 11:24:30 +0200 Subject: Global variables problem In-Reply-To: References: Message-ID: <4C5931CE.6010400@sequans.com> Navkirat Singh wrote: > > On 04-Aug-2010, at 9:46 AM, Daniel da Silva wrote: > >> Please post approximate code that actually works and displays the >> problem. >> >> On Tue, Aug 3, 2010 at 9:00 PM, Navkirat Singh > > wrote: >> >> Hey guys, >> >> I am using a multiprocessing program, where the new process is >> supposed to change a variable in the main class that it branches >> out from. This is somehow not working, following is an >> approximate code. Would really appreciate any insight into this >> matter: >> >> >> var = {} >> >> class Something(): >> >> def set_var(self): >> global var >> var = somevalue >> >> def get_var(self): >> return var >> >> def newprocess(self): >> self.set_var() >> >> def do_multiprocessing(self): >> while true: >> self.get_var() >> new_process = process(target=newprocess) >> new_process.start() >> >> >> I am really confused here ! >> >> Any help would be awesome : ) >> >> Regards, >> Nav >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > This is a working code, streamlined, but it is where the problem is: > > from multiprocessing import * > > dicts = 0 > print('global ', dicts) > > class WebServer(): > def set_sessionInfo(self): > global dicts > dicts = dicts + 1 > def get_sessionInfo(self): > return dicts > > def handle_connection(self): > self.set_sessionInfo() > def serve_forever(self): > for x in range(10): > p = Process(target=self.handle_connection) > p.start() > print(self.get_sessionInfo()) > ws = WebServer() > ws.serve_forever() > print(dicts) > > "As mentioned above, when doing concurrent programming it is usually best to avoid using shared state as far as possible. This is particularly true when using multiple processes. However, if you really do need to use some shared data then multiprocessing provides a couple of ways of doing so." source : http://docs.python.org/library/multiprocessing.html Read it, everything is explained with examples, including how to properly solve your problem. "When using multiple processes, one generally uses message passing for communication between processes and avoids having to use any synchronization primitives like locks." JM From steve at REMOVE-THIS-cybersource.com.au Wed Aug 4 05:29:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2010 09:29:37 GMT Subject: Python Script Cannot Write to Directory References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> Message-ID: <4c593301$0$28669$c3e8da3@news.astraweb.com> On Tue, 03 Aug 2010 21:01:38 -0700, Chris Brauchli wrote: > Hi, > > I am writing a script that, at one point, copies a file from directory A > to directory B. Directory B can only be written to by root, but the > script is always called with sudo, so this shouldn't be an issue, but it > is. I have tried using shutil.copy() and calling "sudo cp " with > os.popen to no avail. I cannot get the script to copy a file to > directory B. [...] > Any ideas why this is happening? If more information is needed or > something isn't clear let me know. Thanks for helping. Without seeing the traceback and the actual line of code that fails, and preferably the full set of permissions on the directory, we'd be guessing. Now, I love to play "debug the program by making wild guesses" with other people's code, but you might not like my suggestions :) -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Aug 4 05:33:38 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2010 09:33:38 GMT Subject: Trying to set a cookie within a python script References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> <0c4d0b86-b5b6-48f9-ba26-b8c344df2d83@t20g2000yqa.googlegroups.com> Message-ID: <4c5933f2$0$28669$c3e8da3@news.astraweb.com> On Tue, 03 Aug 2010 20:08:46 -0700, ????? wrote: > i tried in IDLE enviroment as well and for some reason even with a > single number isnated of time() function the cookie is never set, > because the print of > >>>>print os.environ.get('HTTP_COOKIE') > > result to > > None What happens if you open up a NEW xterm and do this? echo $HTTP_COOKIE Or, to put it another way... are you sure that the environment variable is actually being set? -- Steven From prologic at shortcircuit.net.au Wed Aug 4 05:44:01 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 4 Aug 2010 19:44:01 +1000 Subject: Difference between queues and pipes in multiprocessing In-Reply-To: <5E121D65-6150-4CC6-A35D-7834A81131AC@gmail.com> References: <5E121D65-6150-4CC6-A35D-7834A81131AC@gmail.com> Message-ID: On Wed, Aug 4, 2010 at 7:20 PM, Navkirat Singh wrote: > I was wondering what are the differences between queues and pipes implemented using multiprocessing python module. Am I correct if I say, in pipes, if another process writes to one receiving end concurrently, then an error will be raised and in queues the later processes data will just queued up? basically a Queue is a syncronization primitive used to share and pass data to and from parent/child processes. A pipe is as the name suggests, a socket pair connected end-to-end allowing for full-duplex communications. cheers James -- -- James Mills -- -- "Problems are solved by method" From jldunn2000 at gmail.com Wed Aug 4 06:13:52 2010 From: jldunn2000 at gmail.com (loial) Date: Wed, 4 Aug 2010 03:13:52 -0700 (PDT) Subject: lpr via subprocess in 2.4 Message-ID: <5adbfea2-3154-4dbf-90a6-a2a81d38a287@l14g2000yql.googlegroups.com> I am am trying to run the following command via subprocess lpr -P printqueue filetoprint I cannot seem to get it to work and return stderr I think the issue is how to specify the arguments I am trying subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) but get error : Traceback (most recent call last): File "testopen.py", line 6, in ? subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) File "/usr/python2.4/lib/python2.4/subprocess.py", line 558, in __in it__ errread, errwrite) File "/usr/python2.4/lib/python2.4/subprocess.py", line 991, in _exe cute_child raise child_exception OSError: [Errno 2] No such file or directory From h.b.furuseth at usit.uio.no Wed Aug 4 06:15:14 2010 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Wed, 04 Aug 2010 12:15:14 +0200 Subject: Python package to read .7z archives? Message-ID: Is there an equivalent of zipfile.py for .7z archives? I have one which extracts an archive member by running 7z e -so, but that's a *slow* way to read one file at a time. Google found me some python interfaces to lzma, but apparently they only handle single compressed files, not .7z archives. (Actually another archive format would be fine if it is competitive. I'm just looking to compress my .zips better. I need a Python module to extract members reasonably fast, but slow compression would be OK.) -- Hallvard From __peter__ at web.de Wed Aug 4 07:08:39 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Aug 2010 13:08:39 +0200 Subject: lpr via subprocess in 2.4 References: <5adbfea2-3154-4dbf-90a6-a2a81d38a287@l14g2000yql.googlegroups.com> Message-ID: loial wrote: > I am am trying to run the following command via subprocess > > lpr -P printqueue filetoprint > > I cannot seem to get it to work and return stderr > > I think the issue is how to specify the arguments > > I am trying > > subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) This looks for an executable called "lpr -P"; try subprocess.Popen(['lpr', '-P' ,'laserlpr','/etc/hosts'], shell=False) > but get error : > > Traceback (most recent call last): > File "testopen.py", line 6, in ? > subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) > File "/usr/python2.4/lib/python2.4/subprocess.py", line 558, in __in > it__ > errread, errwrite) > File "/usr/python2.4/lib/python2.4/subprocess.py", line 991, in _exe > cute_child > raise child_exception > OSError: [Errno 2] No such file or directory From g.rodola at gmail.com Wed Aug 4 07:32:23 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Wed, 4 Aug 2010 13:32:23 +0200 Subject: Python package to read .7z archives? In-Reply-To: References: Message-ID: 2010/8/4 Hallvard B Furuseth : > Is there an equivalent of zipfile.py for .7z archives? > I have one which extracts an archive member by running 7z e -so, > but that's a *slow* way to read one file at a time. > > Google found me some python interfaces to lzma, but apparently they > only handle single compressed files, not .7z archives. > > (Actually another archive format would be fine if it is competitive. > I'm just looking to compress my .zips better. ?I need a Python module > to extract members reasonably fast, but slow compression would be OK.) > > -- > Hallvard > -- > http://mail.python.org/mailman/listinfo/python-list > http://bugs.python.org/issue5689 --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ From carrierphasejitter at yahoo.com Wed Aug 4 07:33:58 2010 From: carrierphasejitter at yahoo.com (Aitor Garcia) Date: Wed, 4 Aug 2010 04:33:58 -0700 (PDT) Subject: parsing a c project Message-ID: <410079.5090.qm@web51608.mail.re2.yahoo.com> Hi, I need to know the memory locations of all variables in a C project including variables allocated inside structs. What I want to do in to expand the structs into its basic elements (floats, int16 and int8). In a header file (example.h) I have the following definitions. struct house{ float area; int8 rooms; int16 visits; }; struct car{ float price; int8 color; }; I have been able to extract from the project the name of every struct, the type of the struct and the beginning address of each struct. example_list=[] example_list.append(['house1','struct house','000082d0') example_list.append(['house2','struct house','00003000') example_list.append(['car1','struct car','00004000') I need an output like this. house1_struct_house_area float 000082d0 house1_struct_house_rooms int8 000082d4 house1_struct_house_visits int16 000082d5 house2_struct_house_area float 00003000 house2_struct_house_rooms int8 00003004 house2_struct_house_visits int16 00003005 car1_struct_car_price float 00004000 car1_struct_car_color int8 00004004 How can I efficiently do this in Python ? I do not have very clear which element of Python should I use to store the struct list or class I would be very grateful if someone could give me some pointers. Aitor From jldunn2000 at gmail.com Wed Aug 4 07:38:18 2010 From: jldunn2000 at gmail.com (loial) Date: Wed, 4 Aug 2010 04:38:18 -0700 (PDT) Subject: lpr via subprocess in 2.4 References: <5adbfea2-3154-4dbf-90a6-a2a81d38a287@l14g2000yql.googlegroups.com> Message-ID: Thanks...that worked. I have also been trying to get the return code and standard error. How do I access these? #!/usr/bin/python import os import subprocess process=subprocess.Popen(['lpr', '-P' ,'raserlpr','/etc/hosts'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print process.communicate() On 4 Aug, 12:08, Peter Otten <__pete... at web.de> wrote: > loial wrote: > > I am am trying to run the following command via subprocess > > > lpr -P printqueue filetoprint > > > I cannot seem to get it to work and return stderr > > > I think the issue is how to specify the arguments > > > I am trying > > > subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) > > This looks for an executable called "lpr -P"; try > > subprocess.Popen(['lpr', '-P' ,'laserlpr','/etc/hosts'], shell=False) > > > > > but get error : > > > Traceback (most recent call last): > > ? File "testopen.py", line 6, in ? > > ? ? subprocess.Popen(['lpr -P' ,'laserlpr','/etc/hosts'], shell=False) > > ? File "/usr/python2.4/lib/python2.4/subprocess.py", line 558, in __in > > it__ > > ? ? errread, errwrite) > > ? File "/usr/python2.4/lib/python2.4/subprocess.py", line 991, in _exe > > cute_child > > ? ? raise child_exception > > OSError: [Errno 2] No such file or directory- Hide quoted text - > > - Show quoted text - From prologic at shortcircuit.net.au Wed Aug 4 07:50:24 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 4 Aug 2010 21:50:24 +1000 Subject: lpr via subprocess in 2.4 In-Reply-To: References: <5adbfea2-3154-4dbf-90a6-a2a81d38a287@l14g2000yql.googlegroups.com> Message-ID: On Wed, Aug 4, 2010 at 9:38 PM, loial wrote: > I have also been trying to get the return code and standard error. p = Popen("..., stderr=PIPE) Look up the docs for subprocess.Popen cheers James -- -- James Mills -- -- "Problems are solved by method" From h.b.furuseth at usit.uio.no Wed Aug 4 08:11:38 2010 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Wed, 04 Aug 2010 14:11:38 +0200 Subject: Python package to read .7z archives? References: Message-ID: Giampaolo Rodol? writes: > 2010/8/4 Hallvard B Furuseth : >> Is there an equivalent of zipfile.py for .7z archives? >> I have one which extracts an archive member by running 7z e -so, >> but that's a *slow* way to read one file at a time. >> >> Google found me some python interfaces to lzma, but apparently they >> only handle single compressed files, not .7z archives. >> >> (Actually another archive format would be fine if it is competitive. >> I'm just looking to compress my .zips better. ?I need a Python module >> to extract members reasonably fast, but slow compression would be OK.) > > http://bugs.python.org/issue5689 [For lzma/xz compressed tar archives] Thanks, but extraction of individual members from .tar.xz looks inherently slow. To locate the member, you need to decompress the entire portion of the archive preceding the member. -- Hallvard From bob.aalsma at aalsmacons.nl Wed Aug 4 09:10:09 2010 From: bob.aalsma at aalsmacons.nl (BobAalsma) Date: Wed, 4 Aug 2010 06:10:09 -0700 (PDT) Subject: newbie problem with str.replace Message-ID: I'm working on a set of scripts and I can't get a replace to work in the script - please help. The scripts show no errors, work properly apart from the replace, all variables are filled as expected, the scripts works properly when the commands are copied to the Python shell. Text Main: .. from LeadDevice_klant_nieuw_bewerken_bestanden import omkattenBoom, omkattenNaam ... # # (3) omkatten bestandsnamen: # print 'Omkatten bestandsnamen' omkattenNaam(AANGRIJPINGSPUNT, KLANTNAAM_OUT, KLANTNAAM_IN, ZOEKSET1_OUT, ZOEKSET1_IN, ZOEKSET2_OUT, ZOEKSET2_IN) # .... Text LeadDevice_klant_nieuw_bewerken_bestanden: import os import distutils.core ... def omkattenNaam(AANGRIJPINGSPUNT, KLANTNAAM_OUT, KLANTNAAM_IN, ZOEKSET1_OUT, ZOEKSET1_IN, ZOEKSET2_OUT, ZOEKSET2_IN): # # Strings opbouwen voordat aan de lussen gewerkt wordt: # beginpunt = AANGRIJPINGSPUNT + KLANTNAAM_IN + '/' # ZOEKSET1_OUT_LOWER = ZOEKSET1_OUT.lower() ZOEKSET1_IN_LOWER = ZOEKSET1_IN.lower() ZOEKSET2_OUT_LOWER = ZOEKSET2_OUT.lower() ZOEKSET2_IN_LOWER = ZOEKSET2_IN.lower() # # Lussen: # for root, dirs, files in os.walk(beginpunt, topdown = False): for bestandsnaam in dirs and files: # bestandsnaam_nieuw = bestandsnaam bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) From __peter__ at web.de Wed Aug 4 09:22:22 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Aug 2010 15:22:22 +0200 Subject: newbie problem with str.replace References: Message-ID: BobAalsma wrote: Although [it] may not be obvious at first unless you're Dutch... > bestandsnaam_nieuw = bestandsnaam > bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) str.replace() does not modify a string, it creates a new one. This doesn't work: >>> s = "that's all folks" >>> s.replace("all", "nothing") "that's nothing folks" >>> s "that's all folks" But this does: >>> old = "that's all folks" >>> new = old.replace("all", "nothing") >>> new "that's nothing folks" Peter From anthony.tolle at gmail.com Wed Aug 4 09:22:51 2010 From: anthony.tolle at gmail.com (Anthony Tolle) Date: Wed, 4 Aug 2010 06:22:51 -0700 (PDT) Subject: newbie problem with str.replace References: Message-ID: On Aug 4, 9:10?am, BobAalsma wrote: > ? ? ? ? ? ? ? ? ? ? ? ? # > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw = bestandsnaam > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) The replace method does not modify the string (strings are immutable). You need to use the retun value of the method in an assignment, like so: bestandsnaam_nieuw = bestandsnaam.replace(KLANTNAAM_OUT,KLANTNAAM_IN) This will not change the value of bestandsnaam From bob.aalsma at aalsmacons.nl Wed Aug 4 09:25:31 2010 From: bob.aalsma at aalsmacons.nl (BobAalsma) Date: Wed, 4 Aug 2010 06:25:31 -0700 (PDT) Subject: newbie problem with str.replace References: Message-ID: On Aug 4, 3:22?pm, Anthony Tolle wrote: > On Aug 4, 9:10?am, BobAalsma wrote: > > > ? ? ? ? ? ? ? ? ? ? ? ? # > > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw = bestandsnaam > > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) > > The replace method does not modify the string (strings are immutable). > > You need to use the retun value of the method in an assignment, like > so: > > bestandsnaam_nieuw = bestandsnaam.replace(KLANTNAAM_OUT,KLANTNAAM_IN) > > This will not change the value of bestandsnaam YESS! Thanks, this is what I wanted to achieve but could not find Regards, Bob From mrmakent at cox.net Wed Aug 4 09:30:13 2010 From: mrmakent at cox.net (Mike Kent) Date: Wed, 4 Aug 2010 06:30:13 -0700 (PDT) Subject: newbie problem with str.replace References: Message-ID: <0ece6c99-1c8f-4055-9ed9-4f63b4ed4b2d@j8g2000yqd.googlegroups.com> On Aug 4, 9:10?am, BobAalsma wrote: > I'm working on a set of scripts and I can't get a replace to work in > the script - please help. > ? ? ? ? ? ? ? ? ? ? ? ? bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) I'm not sure what you are intending to do here, but string.replace does not do its replacement in-place. It returns a copy of the original string, with the replacement done in the copy. You are not assigning the string returned by string.replace to anything, therefore, it is immediately thrown away. Secondly, and this is just a guess, but since you are doing the string.replace inside of an os.walk loop, you appear to be trying to do a filename change. I hope you realize that this will in no way change the name of the file *on disk*; it will only change it in memory. From vicente.soler at gmail.com Wed Aug 4 09:35:35 2010 From: vicente.soler at gmail.com (vsoler) Date: Wed, 4 Aug 2010 06:35:35 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) Message-ID: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> Hi all, I just installed python 3.1.2 where I used to have python 2.6.4. I'm working on Win7. The IDLE GUI works, but I get the following message when trying to open *.py files written for py 2.6 The Application cannot locate win32ui.pyd (or Python) (126) Should I change the PATH in Windows? Should I change the PYTHONPATH? I am a bit lost. Everything worked fine with 2.6. Moreover, when I try to open an old *.py file, I sometimes get a message saying that the file should be converted to UTF-8. What does this mean? I'm also trying to use the 2to3 converter, but I cannot see where the converted files are written to! Any help is highly appreciated. Vicente Soler From joncle at googlemail.com Wed Aug 4 09:36:34 2010 From: joncle at googlemail.com (Jon Clements) Date: Wed, 4 Aug 2010 06:36:34 -0700 (PDT) Subject: parsing a c project References: Message-ID: <74a5afa7-f4df-486b-9424-a3f680222026@q35g2000yqn.googlegroups.com> On 4 Aug, 12:33, Aitor Garcia wrote: > Hi, > > I need to know the memory locations of all variables in a C project including > variables allocated inside structs. Pray tell us why? > > What I want to do in to expand the structs into its basic elements (floats, > int16 and int8). > > In a ?header file (example.h) I have the following definitions. > > struct house{ > ? float area; > > ? int8 rooms; > ? int16 visits; > > }; > > struct car{ > ? float price; > ? int8 color; > > }; > > I have been able to extract from the project the name of every struct, the type of the struct and the beginning address of each struct. How have you done this? What compiler and debugger/profiler are you using? etc... The memory address is going to possibly change every time, unless you're talking static variables within an applications own address space (even then I'm not 100% sure -- I haven't had to touch C in 2 years, so I'd declare myself rusty). > > example_list=[] > example_list.append(['house1','struct house','000082d0') > example_list.append(['house2','struct house','00003000') > example_list.append(['car1','struct car','00004000') > > I need an output like this. > > house1_struct_house_area float 000082d0 > house1_struct_house_rooms int8 000082d4 > house1_struct_house_visits int16 000082d5 > house2_struct_house_area float 00003000 > house2_struct_house_rooms int8 00003004 > house2_struct_house_visits int16 00003005 > car1_struct_car_price float 00004000 > car1_struct_car_color int8 00004004 > > How can I efficiently do this in Python ? Well using the pyparsing library, it's extremely easy to parse the C grammar. But that's not what you're asking. > > I do not have very clear which element of Python should I use > to store the struct list or class > > I would be very grateful if someone could give me some pointers. An un-intended C pun :) ? If you let the list know the use-case, then we might stand a chance of giving you some reference (C++ pun?) Jon. From invalid at invalid.invalid Wed Aug 4 10:11:29 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 14:11:29 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Paul Rubin wrote: > Grant Edwards writes: >> The issue that would prevent its use where I work is the inability to >> hire anybody who knows Ada. ... >> That said, the last time I looked the Ada spec was only something like >> 100 pages long, so a case could be made that it won't take long to >> learn. > > Well, I don't know Ada (I've read about it but not written actual > code), so maybe I shouldn't be the one saying this, but geez, it's > another imperative, procedural language, like Algol or Pascal or even > C. Its type is much more serious than C's but shouldn't be a problem > for anyone who uses C++ or Java generics. I agree 100%. > It also has a real module system unlike more commonly used languages, > but 1) that part seems easy to understand; and 2) usually that's used > for multi-programmer projects, so as long as there's some reasonable > proportion of experienced users on the team, the inter-module > interfaces should be sensible and less experienced users can just > program to existing interfaces and/or get some help from others. > Ada's module system is much simpler than (say) ML's. > >> I don't know how long the C++ language spec is, but I'm betting it's >> closer to 1000 than 100. > > I don't know about an official spec. Stroustrup's "The C++ > programming language" is about 1000 pp, but it's a textbook, with > lots of examples, exercises, etc. I read through an earlier > (shorter) edition in a couple of evenings a long time ago and it all > made sense. It has some hairy aspects like the notorious template > metaprogramming, but most users simply won't get involved with that. > Python has its own obscure and confusing features if that matters. I couldn't get anybody to use Python either. :/ The problem has nothing to do with the relative merits of the languages. The problem is inertia. > I think I'm a reasonably good Python programmer but I've never > written a special metaclass and wouldn't really know how to. -- Grant Edwards grant.b.edwards Yow! I would like to at urinate in an OVULAR, gmail.com porcelain pool -- From invalid at invalid.invalid Wed Aug 4 10:14:07 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 14:14:07 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Paul Rubin wrote: > I'm not sure what the hiring issue is. I think anyone skilled in C++ > or Java can pick up Ada pretty easily. It's mostly a subset of C++ > with different surface syntax. In my experience, the hiring issue is "we're already behind schedule and short-handed, we don't have the time or resources to teach people a new language." -- Grant Edwards grant.b.edwards Yow! Did YOU find a at DIGITAL WATCH in YOUR box gmail.com of VELVEETA? From invalid at invalid.invalid Wed Aug 4 10:15:40 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 14:15:40 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Neil Hodgson wrote: > Grant Edwards: > >> That said, the last time I looked the Ada spec was only something like >> 100 pages long, so a case could be made that it won't take long to >> learn. I don't know how long the C++ language spec is, but I'm >> betting it's closer to 1000 than 100. > > The Ada 2012 Language Reference Manual is 860 pages and the Ada 2005 > LRM was 790 pages. The annotated versions are even longer > http://www.ada-auth.org/standards/ada12.html Wow. That's grown a lot over the years. I used to have a paper copy, (single-sided), and it was only about 1cm thick. Ok, I guess that was probably 20 years ago... -- Grant Edwards grant.b.edwards Yow! I wonder if I ought at to tell them about my gmail.com PREVIOUS LIFE as a COMPLETE STRANGER? From davea at ieee.org Wed Aug 4 11:30:40 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 04 Aug 2010 11:30:40 -0400 Subject: Trying to set a cookie within a python script In-Reply-To: <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> Message-ID: <4C5987A0.1090903@ieee.org> ????? wrote: >> On 3 ???, 21:00, Dave Angel wrote: >> > > >> A string is an object containing characters. A string literal is one of >> the ways you create such an object. When you create it that way, you >> need to make sure the compiler knows the correct encoding, by using the >> encoding: line at beginning of file. >> > > > mymessage = "????????" <==== string > mymessage = u"????????" <==== string literal? > > So, a string literal is one of the encodings i use to create a string > object? > > No, both lines take a string literal, create an object, and bind a name to that object. In the first case, the object is a string, and in the second it's a unicode-string. But the literal is the stuff after the equals sign in both these cases. Think about numbers for a moment. When you say salary = 4.1 you've got a numeric literal that's three characters long, and a name that's six characters long. When the interpreter encounters this line, it builds an object of type float, whose value approximates 4.1, according to the language rules. It then binds the name salary to this object. > Can the encodign of a python script file be in iso-8859-7 which means > the file contents is saved to the hdd as greek-iso but the part of > this variabel value mymessage ="????????" is saved as utf-8 ot the > opposite? > > A given file needs to have a single encoding, or you're in big trouble. So a script file is encoded by the text editor in a single encoding method, which is not saved to the file (except indirectly if you specify BOM). It's up to you to add a line to the beginning to tell Python how to decode the file. One decoding for one file. > have the file saved as utf-8 but one variuable value as greek > encoding? > > Variables are not saved to source (script) files. Literals are in the file. > Encodings still give me headaches. I try to understand them as > different ways to store data in a media. > > Tell me something. What encoding should i pick for my scripts knowing > that only contain english + greek chars?? > iso-8859-7 or utf-8 and why? > > Depends on how sure you are that your program will never need characters outside your greek character set. Remember Y2K? > Can i save the sting lets say "?????" in different encodings and still > print out correctly in browser? > > ascii =he standard english character set only, right? > > >> The web server wraps a few characters before and after your html stream, >> but it shouldn't touch the stream itself. >> > > So the pythoon compiler using the cgi module is the one that is > producing the html output that immediately after send to the web > server, right? > > > >>> For example if i say mymessage =????????" and the i say mymessage = u"????????" then the 1st one is a greek encoding variable while the >>> 2nd its a utf-8 one? >>> >> No, the first is an 8 bit copy of whatever bytes your editor happened to >> save. >> > > But since mymessage =????????" is a string containing greek > characaters why the editor doesn't save it as such? > > Because the editor is editing text, not python objects. It's job is solely to represent all your keystrokes in some consistent manner so that they can be interpreted later by some other program, possibly a compiler. > It reminds me of varibles an valeus where if you say > > a = 5, a var becomes instantly an integer variable > while > a = 'hello' , become instantly a string variable > > > >> mymessage = u"????????" >> >> creates an object that is *not* encoded. >> > > Because it isn't saved by the editor yet? In what satet is this object > in before it gets encoded? > And it egts encoded the minute i tell the editor to save the file? > > You're confusing timeframes here. Notepad++ doesn't know Python, and it's long gone by the time the compiler deals with that line. In Notepad++, there are no python objects, encoded or not. >> Encoding is taking the unicode >> stream and representing it as a stream of bytes, which may or may have >> more bytes than the original has characters. >> > > > So this line mymessage = u"????????" what it does is tell the browser > thats when its time to save the whole file to save this string as > utf-8? > > No idea what you mean. The browser isn't saving anything; it doesn't even get involved till after the python code has completed. > If yes, then if were to save the above string as greek encoding how > was i suppose to right it? > > Also if u ise the 'coding line' in the beggining of the file is there > a need for using the u literal? > > If you don't use the u literal, then don't even try to use utf-8. You'll find that strings have the wrong lengths, and therefore subscripts and formatting will sometimes fail in strange ways. >> I personally haven't done any cookie code. If I were debugging this, I'd >> factor out the multiple parts of that if statement, and find out which >> one isn't true. From here I can't guess. >> > > I did what you say and foudn out that both of the if condition parts > were always false thast why the if code blck never got executed. > > And it is alwsy wrong because the cookie never gets set. > > So can you please tell me why this line > > cookie['visitor'] = 'nikos', time() + 60*60*24*365 ) #this cookie > will expire in an year > > never created a cookie? > > As I said, I've never coded with cookies. But to create a cookie, you have to communicate with a browser, and that takes lots more than just adding an item to a map. Further, your getenv() will normally give you the state of the environment at the time your program was launched, so I wouldn't expect it to change. If I had to guess how cookies are done in CGI, I'd say that you probably have to talk to the CGI server and terminate, and that afterwards there'd be a new launch of your code, from which you could check that environment variable to see the results of the cookie. DaveA From alex at moreati.org.uk Wed Aug 4 11:41:49 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Wed, 4 Aug 2010 08:41:49 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) References: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> Message-ID: <0c661f1a-2b71-473b-90f7-133ab195bbaf@g19g2000yqc.googlegroups.com> On Aug 4, 2:35?pm, vsoler wrote: > Hi all, > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > working on Win7. > > The IDLE GUI works, but I get the following message when trying to > open *.py files written for py 2.6 > > ? ? ? ? The Application cannot locate win32ui.pyd (or Python) (126) > win32ui is part of the PyWin32 package. Most likely you have a version of PyWin32 for Python 2.6 installed, you should uninstall that and install PyWin32 for Python 3.1. Downloads are at http://sourceforge.net/projects/pywin32/files/ You should do the same for any other third party packages that are installed. > Moreover, when I try to open an old *.py file, I sometimes get a > message saying that the file should be converted to UTF-8. What does > this mean? Those files contain non-ascii characters (e.g. ?, ?, ?). Non-ascii characters must be encoded when saved using and encoding. UTF-8 is one such encoding, and it was chosen as the default .py encoding for Python 3.x. Those files are probably in iso8859, cp432, or perhaps UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite text editor, or declare the encoding so Python 3 knows it. More info: http://www.joelonsoftware.com/articles/Unicode.html http://docs.python.org/howto/unicode > I'm also trying to use the 2to3 converter, but I cannot see where the > converted files are written to! I think 2to3 prints a diff of the file changes to the console. The -w command line option should modify files in place. From steveo at syslang.net Wed Aug 4 11:44:12 2010 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 04 Aug 2010 11:44:12 -0400 Subject: Get name of file from directory into variable In-Reply-To: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> References: <37ee8786-d395-4e99-8fce-138fa848d1cb@t20g2000yqa.googlegroups.com> Message-ID: <4C598ACC.6050509@syslang.net> On 08/03/10 06:21, quoth loial: > In a unix shell script I can do something like this to look in a > directory and get the name of a file or files into a variable : > > MYFILE=`ls /home/mydir/JOHN*.xml` > > > Can I do this in one line in python? > Sorry, but I just can't help myself. Yeah, it's one shell line, but why the extra process, setup of pipes, teardown, and all the rest when you can just say MYFILE=/home/mydir/JOHN*.xml After all, your way just starts a subshell which runs ls in a grandchild process and creates a pipe to read back what the subshell writes. All the subhell does is to run ls on what the shell globs. And without any options to the ls command, you're just as well off by using echo instead of ls. MYFILE=`echo /home/mydir/JOHN*.xml` Since echo is probably a builtin, you'd be creating a child but no grandchild. Other than that, the use of glob in python answers your question well (unless someone wants to write up how to do it in python by use of the subprocess module along with the glob module...) -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From aahz at pythoncraft.com Wed Aug 4 12:01:32 2010 From: aahz at pythoncraft.com (Aahz) Date: 4 Aug 2010 09:01:32 -0700 Subject: error: (113, 'Software caused connection abort')0 References: Message-ID: In article , sarah wrote: > > i face with this problem when i want to run this command on cygwin: > python httpd.py 8000 example-300-1k-rigid.py Make sure the webclient service is running. (May not have anything to do with your problem, but it's something I had a problem with recently.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From vicente.soler at gmail.com Wed Aug 4 12:19:01 2010 From: vicente.soler at gmail.com (vsoler) Date: Wed, 4 Aug 2010 09:19:01 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) References: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> <0c661f1a-2b71-473b-90f7-133ab195bbaf@g19g2000yqc.googlegroups.com> Message-ID: <2308f42f-a92d-49ea-819c-f12eba5c8c24@l14g2000yql.googlegroups.com> On Aug 4, 5:41?pm, Alex Willmer wrote: > On Aug 4, 2:35?pm, vsoler wrote: > > > Hi all, > > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > > working on Win7. > > > The IDLE GUI works, but I get the following message when trying to > > open *.py files written for py 2.6 > > > ? ? ? ? The Application cannot locate win32ui.pyd (or Python) (126) > > win32ui is part of the PyWin32 package. Most likely you have a version > of PyWin32 for Python 2.6 installed, you should uninstall that and > install PyWin32 for Python 3.1. Downloads are athttp://sourceforge.net/projects/pywin32/files/ > > You should do the same for any other third party packages that are > installed. > > > Moreover, when I try to open an old *.py file, I sometimes get a > > message saying that the file should be converted to UTF-8. What does > > this mean? > > Those files contain non-ascii characters (e.g. ?, ?, ?). Non-ascii > characters must be encoded when saved using and encoding. UTF-8 is one > such encoding, and it was chosen as the default .py encoding for > Python 3.x. Those files are probably in iso8859, cp432, or perhaps > UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite > text editor, or declare the encoding so Python 3 knows it. More info: > > http://www.joelonsoftware.com/articles/Unicode.htmlhttp://docs.python.org/howto/unicode > > > I'm also trying to use the 2to3 converter, but I cannot see where the > > converted files are written to! > > I think 2to3 prints a diff of the file changes to the console. The -w > command line option should modify files in place. Thank you Alex for your detailes reply. Before switching to Python 3.1.2 I removed all my Python 2.6 packages (python, pywin32, numpy, wxpython). However, the removal was not complete since some files could not be removed. Additionally, I still see my C:\python26 directory which is suposed not to exist any longer. If I go to the Control Panel, I cannot see any of the above suposedly removed programs as pending of removal, so I really do not know what more to do. I was even thinking of removing the C:\python26 directory with the Supr key, but I always heard that it is not a good idea, the Registry could become inconsistent. Additionally, I have not found in my Win7 system nay utility for fixing it, should it become corrupt. Perhaps my questions concern a bit more the Operating system (windows) than they do python, but since I am fond of python and I definitely would like to become somehow proficient at it, I would like to solve the problem that I have. I would not like to take a lot of your time, but, do you have any hints as to what I should do to 'tune' my PC? Thank you very much for your help. Vicente Soler From chare at labr.net Wed Aug 4 12:40:32 2010 From: chare at labr.net (Chris Hare) Date: Wed, 04 Aug 2010 11:40:32 -0500 Subject: problem adding a scrollbar to a text widget Message-ID: <4A9BB587-E1EF-4272-8E65-6511415CAEE5@labr.net> Here is my chunk of code. I can't figure out what I am doing wrong to put my scrollbar on the right hand side of the text box. from Tkinter import * def showLogFile(): top = Toplevel() f = Frame(top, bd=0, bg="Gray") top.title = "netcomm log file" f.grid() sc = Scrollbar(top) sc.grid() t = Text(f, yscrollcommand = sc.set) sc.config(command=t.yview) t.insert(END,"This is a line of text") t.config(height=20,width=80,bg="Gray") button = Button(f, text="Dismiss", command=top.destroy, highlightbackground="Red") t.grid() button.grid() showLogFile() mainloop() From eliben at gmail.com Wed Aug 4 12:40:37 2010 From: eliben at gmail.com (Eli Bendersky) Date: Wed, 4 Aug 2010 19:40:37 +0300 Subject: parsing a c project In-Reply-To: <410079.5090.qm@web51608.mail.re2.yahoo.com> References: <410079.5090.qm@web51608.mail.re2.yahoo.com> Message-ID: On Wed, Aug 4, 2010 at 14:33, Aitor Garcia wrote: > Hi, > > I need to know the memory locations of all variables in a C project > including > variables allocated inside structs. > Aitor, try the pycparser project (http://code.google.com/p/pycparser/) - it's a complete ISO C parser in pure Python. It has been used for tasks similar to this one (parsing of struct/union declarations for various purposes). Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.post Wed Aug 4 13:13:59 2010 From: no.email at please.post (kj) Date: Wed, 4 Aug 2010 17:13:59 +0000 (UTC) Subject: XML parsing: SAX/expat & yield Message-ID: I want to write code that parses a file that is far bigger than the amount of memory I can count on. Therefore, I want to stay as far away as possible from anything that produces a memory-resident DOM tree. The top-level structure of this xml is very simple: it's just a very long list of "records". All the complexity of the data is at the level of the individual records, but these records are tiny in size (relative to the size of the entire file). So the ideal would be a "parser-iterator", which parses just enough of the file to "yield" (in the generator sense) the next record, thereby returning control to the caller; the caller can process the record, delete it from memory, and return control to the parser-iterator; once parser-iterator regains control, it repeats this sequence starting where it left off. The problem, as I see it, is that SAX-type parsers like expat want to do everything with callbacks, which is not readily compatible with the generator paradigm I just described. Is there a way to get an xml.parsers.expat parser (or any other SAX-type parser) to stop at a particular point to yield a value? The only approach I can think of is to have the appropriate parser callbacks throw an exception wherever a yield would have been. The exception-handling code would have the actual yield statement, followed by code that restarts the parser where it left off. Additional logic would be necessary to implement the piecemeal reading of the input file into memory. But I'm not very conversant with SAX parsers, and even less with generators, so all this may be unnecessary, or way off. Any other tricks/suggestions for turning a SAX parsers into a generator, please let me know. ~K From __peter__ at web.de Wed Aug 4 13:22:54 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Aug 2010 19:22:54 +0200 Subject: XML parsing: SAX/expat & yield References: Message-ID: kj wrote: > I want to write code that parses a file that is far bigger than > the amount of memory I can count on. Therefore, I want to stay as > far away as possible from anything that produces a memory-resident > DOM tree. > > The top-level structure of this xml is very simple: it's just a > very long list of "records". All the complexity of the data is at > the level of the individual records, but these records are tiny in > size (relative to the size of the entire file). > > So the ideal would be a "parser-iterator", which parses just enough > of the file to "yield" (in the generator sense) the next record, > thereby returning control to the caller; the caller can process > the record, delete it from memory, and return control to the > parser-iterator; once parser-iterator regains control, it repeats > this sequence starting where it left off. How about http://effbot.org/zone/element-iterparse.htm#incremental-parsing Peter From alex at moreati.org.uk Wed Aug 4 13:52:22 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Wed, 4 Aug 2010 10:52:22 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) References: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> <0c661f1a-2b71-473b-90f7-133ab195bbaf@g19g2000yqc.googlegroups.com> <2308f42f-a92d-49ea-819c-f12eba5c8c24@l14g2000yql.googlegroups.com> Message-ID: <1075909d-a727-4145-90ca-4b5444144816@k19g2000yqc.googlegroups.com> On Aug 4, 5:19?pm, vsoler wrote: > On Aug 4, 5:41?pm, Alex Willmer wrote: > > > > > > > On Aug 4, 2:35?pm, vsoler wrote: > > > > Hi all, > > > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > > > working on Win7. > > > > The IDLE GUI works, but I get the following message when trying to > > > open *.py files written for py 2.6 > > > > ? ? ? ? The Application cannot locate win32ui.pyd (or Python) (126) > > > win32ui is part of the PyWin32 package. Most likely you have a version > > of PyWin32 for Python 2.6 installed, you should uninstall that and > > install PyWin32 for Python 3.1. Downloads are athttp://sourceforge.net/projects/pywin32/files/ > > > You should do the same for any other third party packages that are > > installed. > > > > Moreover, when I try to open an old *.py file, I sometimes get a > > > message saying that the file should be converted to UTF-8. What does > > > this mean? > > > Those files contain non-ascii characters (e.g. ?, ?, ?). Non-ascii > > characters must be encoded when saved using and encoding. UTF-8 is one > > such encoding, and it was chosen as the default .py encoding for > > Python 3.x. Those files are probably in iso8859, cp432, or perhaps > > UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite > > text editor, or declare the encoding so Python 3 knows it. More info: > > >http://www.joelonsoftware.com/articles/Unicode.htmlhttp://docs.python... > > > > I'm also trying to use the 2to3 converter, but I cannot see where the > > > converted files are written to! > > > I think 2to3 prints a diff of the file changes to the console. The -w > > command line option should modify files in place. > > Thank you Alex for your detailes reply. > > Before switching to Python 3.1.2 I removed all my Python 2.6 packages > (python, pywin32, numpy, wxpython). However, the removal was not > complete since some files could not be removed. Additionally, I still > see my C:\python26 directory which is suposed not to exist any longer. It probably contains one or two files the installers weren't aware of. E.g. a module you added manually, a log, a .pyc > I would not like to take a lot of your time, but, do you have any > hints as to what I should do to 'tune' my PC? Take a backup then either delete the Python26 directory, or rename it. Any problems, reverse the process. From dotancohen at gmail.com Wed Aug 4 14:09:35 2010 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 4 Aug 2010 21:09:35 +0300 Subject: Trying to set a cookie within a python script In-Reply-To: <4C5987A0.1090903@ieee.org> References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> <4C5987A0.1090903@ieee.org> Message-ID: On Wed, Aug 4, 2010 at 18:30, Dave Angel wrote: > Depends on how sure you are that your program will never need characters > outside your greek character set. Remember Y2K? > Don't forget that the Euro symbol is outside the Greek character set. -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From donn.ingle at gmail.com Wed Aug 4 14:22:14 2010 From: donn.ingle at gmail.com (donn) Date: Wed, 04 Aug 2010 20:22:14 +0200 Subject: Trying to set a cookie within a python script In-Reply-To: References: <9525b3a2-92c7-47c3-bbff-75a99f50e41d@a4g2000prm.googlegroups.com> <4c5616bf$0$11113$c3e8da3@news.astraweb.com> <4c5639b1$0$11113$c3e8da3@news.astraweb.com> <1c041e8a-bcc3-43b9-b6a0-890d6331be3e@m17g2000prl.googlegroups.com> <4c569382$0$28655$c3e8da3@news.astraweb.com> <87095b8a-fdf4-48f4-80d4-4e1cf9a706ab@i31g2000yqm.googlegroups.com> <2fa1b4c8-c639-4769-87df-40fb6bd0a9a0@v15g2000yqe.googlegroups.com> <3cf1109f-208b-4a8b-8048-20e3a153ce09@f42g2000yqn.googlegroups.com> <4C5987A0.1090903@ieee.org> Message-ID: <4C59AFD6.4020206@gmail.com> On 04/08/2010 20:09, Dotan Cohen wrote: > Don't forget that the Euro symbol is outside the Greek character set. I could make some kind of economic joke here, but I'm also broke :D \d From steve.ferg.bitbucket at gmail.com Wed Aug 4 14:28:48 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Wed, 4 Aug 2010 11:28:48 -0700 (PDT) Subject: python terminology on classes References: Message-ID: <8e60e2db-205d-4b8b-9c19-1d46e2318cb8@h20g2000vbs.googlegroups.com> > Seriously, we can't keep doing your thinking for you. ?The answers > to all your questions are section 9 of the tutorial. This is is just the kind of newbie-hostile smart-ass reply that we do not want to see on comp.lang.python. Let's try again: I think that the answers to all your questions are section 9 of the tutorial. http://docs.python.org/py3k/tutorial/index.html Why don't you take a look at it, and then come back again if you still have questions. From vicente.soler at gmail.com Wed Aug 4 14:50:08 2010 From: vicente.soler at gmail.com (vsoler) Date: Wed, 4 Aug 2010 11:50:08 -0700 (PDT) Subject: The Application cannot locate win32ui.pyd (or Python) (126) References: <09d9b279-7307-41a4-b057-07d9d9556efb@f6g2000yqa.googlegroups.com> <0c661f1a-2b71-473b-90f7-133ab195bbaf@g19g2000yqc.googlegroups.com> <2308f42f-a92d-49ea-819c-f12eba5c8c24@l14g2000yql.googlegroups.com> <1075909d-a727-4145-90ca-4b5444144816@k19g2000yqc.googlegroups.com> Message-ID: <27fc4dce-238f-4498-a5c4-a9a6514ee4c0@y11g2000yqm.googlegroups.com> On Aug 4, 7:52?pm, Alex Willmer wrote: > On Aug 4, 5:19?pm, vsoler wrote: > > > > > On Aug 4, 5:41?pm, Alex Willmer wrote: > > > > On Aug 4, 2:35?pm, vsoler wrote: > > > > > Hi all, > > > > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > > > > working on Win7. > > > > > The IDLE GUI works, but I get the following message when trying to > > > > open *.py files written for py 2.6 > > > > > ? ? ? ? The Application cannot locate win32ui.pyd (or Python) (126) > > > > win32ui is part of the PyWin32 package. Most likely you have a version > > > of PyWin32 for Python 2.6 installed, you should uninstall that and > > > install PyWin32 for Python 3.1. Downloads are athttp://sourceforge.net/projects/pywin32/files/ > > > > You should do the same for any other third party packages that are > > > installed. > > > > > Moreover, when I try to open an old *.py file, I sometimes get a > > > > message saying that the file should be converted to UTF-8. What does > > > > this mean? > > > > Those files contain non-ascii characters (e.g. ?, ?, ?). Non-ascii > > > characters must be encoded when saved using and encoding. UTF-8 is one > > > such encoding, and it was chosen as the default .py encoding for > > > Python 3.x. Those files are probably in iso8859, cp432, or perhaps > > > UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite > > > text editor, or declare the encoding so Python 3 knows it. More info: > > > >http://www.joelonsoftware.com/articles/Unicode.htmlhttp://docs.python... > > > > > I'm also trying to use the 2to3 converter, but I cannot see where the > > > > converted files are written to! > > > > I think 2to3 prints a diff of the file changes to the console. The -w > > > command line option should modify files in place. > > > Thank you Alex for your detailes reply. > > > Before switching to Python 3.1.2 I removed all my Python 2.6 packages > > (python, pywin32, numpy, wxpython). However, the removal was not > > complete since some files could not be removed. Additionally, I still > > see my C:\python26 directory which is suposed not to exist any longer. > > It probably contains one or two files the installers weren't aware of. > E.g. a module you added manually, a log, a .pyc > > > I would not like to take a lot of your time, but, do you have any > > hints as to what I should do to 'tune' my PC? > > Take a backup then either delete the Python26 directory, or rename it. > Any problems, reverse the process. Thank you very much Alex From chare at labr.net Wed Aug 4 15:44:13 2010 From: chare at labr.net (Chris Hare) Date: Wed, 04 Aug 2010 14:44:13 -0500 Subject: running a piece of code at specific intervals? Message-ID: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> Don't say cron : I want to have a section of my code executed at 15 minute intervals. I am using Threading.timer, but it is causing a problem sinxe I am using sqlite3 and the thread support gives me an error, which aborts part of my code. So, is there an alternative to threading.timer? From ericjvandervelden at gmail.com Wed Aug 4 15:58:18 2010 From: ericjvandervelden at gmail.com (Eric J. Van der Velden) Date: Wed, 4 Aug 2010 12:58:18 -0700 (PDT) Subject: __init__ as a lambda Message-ID: Hello, Suppose class C: def __init__(self,name):self.name=name I was wondering if I could make the __init__ a lambda function, but class C: __init__=lambda self,self.name:None and then later, C('Hello') does not work; the first argument, self, is assigned all rigth, but you cannot write the second argument with a dot, self.name . Or can I somehow? Thanks, Eric J. From davea at ieee.org Wed Aug 4 16:07:41 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 04 Aug 2010 16:07:41 -0400 Subject: running a piece of code at specific intervals? In-Reply-To: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> References: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> Message-ID: <4C59C88D.5090707@ieee.org> Chris Hare wrote: > Don't say cron : > > I want to have a section of my code executed at 15 minute intervals. I am using Threading.timer, but it is causing a problem sinxe I am using sqlite3 and the thread support gives me an error, which aborts part of my code. > > So, is there an alternative to threading.timer? > > Depends on how that "section of code" relates to the rest of your code. If it's independent of the rest, then you can use subprocess to launch a separate process. That won't interfere with your main code. But of course if your main code is blocked for 20 minutes, it'll never get to the part which should run the subprocess. If your main code is running wxPython, you can set a timer, and just trigger an event like all the others. But without knowing more about your two pieces of code, the only reliable answer is 'cron'. DaveA From jyoung79 at kc.rr.com Wed Aug 4 16:08:20 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Wed, 4 Aug 2010 20:08:20 +0000 Subject: BundleBuilder Question Message-ID: <20100804200820.1IR1H.80013.root@cdptpa-web19-z02> I stumbled upon an article about bundlebuilder, so I was testing it a little. At first it wouldn't work and had this in the error: IOError: [Errno 2] No such file or directory: '/System/Library/Frameworks/Python.framework/Versions/2.6/Resources/English.lproj' I'm currently running OS X 10.6 with python2.6 as the default (looks to be 64 bit). I followed that path and found that the 'English.lproj' directory was not there. I admit I'm not sure what I'm doing, but I went to a 10.5 Leopard machine and found that Python2.5 had this 'English.lproj' directory so I copied it over to my Python2.6 on OS 10.6. Bundlebuilder then successfully created a standalone app. I'm just wondering if it's a good idea to copy that English.lproj directory from Python2.5 to Python2.6? What exactly is this directory for? Looks like it only contains a "InfoPlist.strings" file. Thanks. Jay From jhjaggars at gmail.com Wed Aug 4 16:10:47 2010 From: jhjaggars at gmail.com (Jesse Jaggars) Date: Wed, 4 Aug 2010 15:10:47 -0500 Subject: running a piece of code at specific intervals? In-Reply-To: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> References: <8AE647FD-CBC4-488B-A56B-1B1089D9C0EF@labr.net> Message-ID: On Wed, Aug 4, 2010 at 2:44 PM, Chris Hare wrote: > Don't say cron : > > I want to have a section of my code executed at 15 minute intervals. ?I am using Threading.timer, but it is causing a problem sinxe I am using sqlite3 and the thread support gives me an error, which aborts part of my code. > > So, is there an alternative to threading.timer? > > > -- > http://mail.python.org/mailman/listinfo/python-list > Take a look at sched. http://docs.python.org/library/sched.html From jfine at pytex.org Wed Aug 4 16:15:33 2010 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 04 Aug 2010 21:15:33 +0100 Subject: A new syntax for writing tests Message-ID: Hi I just discovered today a new syntax for writing tests. The basic idea is to write a function that contains some statements, and run it via a decorator. I wonder if anyone had seen this pattern before, and how you feel about it. For myself, I quite like it. Let's suppose we want to test this trivial (of course) class. class Adder(object): def __init__(self): self.value = 0 def plus(self, delta): self.value += delta The test the class you need a runner. In this case it is quite simple. def runner(script, expect): '''Create an adder, run script, expect value.''' adder = Adder() script(adder) return adder.value We can now create (and run if we wish) a test. To do this we write @testit(runner, 4) def whatever(a): '''Two plus two is four.''' a.plus(2) a.plus(2) Depending on the exact value of the testit decorator (which in the end is up to you) we can store the test, or execute it immediately, or do something else. The simplest implementation prints: OK: Two plus two is four. for this passing test, and Fail: Two plus four is five. expect 5 actual 6 for a test that fails. Here is the testit decorator used to produce the above output: def testit(runner, expect): '''Test statements decorator.''' def next(script): actual = runner(script, expect) if actual == expect: print 'OK:', script.__doc__ else: print 'Fail:', script.__doc__ print ' expect', expect print ' actual', actual return next You can pick this code, for at least the next 30 days, at http://dpaste.com/hold/225056/ For me the key benefit is that writing the test is really easy. Here's a test I wrote earlier today. @testit(runner, '''''') def whatever(tb): tb.start('a', {'att': 'value'}) tb.start('b') tb.end('b') tb.end('a') If the test has a set-up and tear-down, this can be handled in the runner, as can the test script raising an expected or unexpected exception. -- Jonathan From thomas at jollans.com Wed Aug 4 16:17:28 2010 From: thomas at jollans.com (Thomas Jollans) Date: Wed, 04 Aug 2010 22:17:28 +0200 Subject: None is negative? In-Reply-To: References: Message-ID: <4C59CAD8.20904@jollans.com> On 08/03/2010 10:17 PM, wheres pythonmonks wrote: > I did the google search... I must be blind as I don't see any hits... > > None is negative in Python? (v2.6) > > http://www.google.com/search?ie=UTF-8&q=%22none+is+negative%22+python > >>>> if None < -9999999.99: print "hi" > > hi >>>> > >>>> if -9999999 > None: print "hi" > > hi >>>> > > Is there a way to have the comparison raise an exception? > > W Not only was it negative, it was, in fact: >>> None < float('-Inf') True From nad at acm.org Wed Aug 4 16:34:50 2010 From: nad at acm.org (Ned Deily) Date: Wed, 04 Aug 2010 13:34:50 -0700 Subject: BundleBuilder Question References: <20100804200820.1IR1H.80013.root@cdptpa-web19-z02> Message-ID: In article <20100804200820.1IR1H.80013.root at cdptpa-web19-z02>, wrote: > I stumbled upon an article about bundlebuilder, so I was testing it a little. > At first it wouldn't work and had this in the error: > > IOError: [Errno 2] No such file or directory: > '/System/Library/Frameworks/Python.framework/Versions/2.6/Resources/English.lp > roj' > [...] This was a bug that has been fixed in subsequent maintenance releases of Python 2.6. See http://bugs.python.org/issue4937 -- Ned Deily, nad at acm.org From sschwarzer at sschwarzer.net Wed Aug 4 16:41:42 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 04 Aug 2010 22:41:42 +0200 Subject: [ANN] Websourcebrowser 0.4a released Message-ID: Hello, I'm happy to announce the release of Websourcebrowser 0.4a. Websourcebrowser is a program intended to get a quick overview of a project's source code. The program is controlled from a web browser which displays a directory tree and a source code file side by side. The homepage of the project is at http://websourcebrowser.sschwarzer.net/ The download of version 0.4a is at http://websourcebrowser.sschwarzer.net/download *** Note that this is still an alpha release. *** I use the program regularly to dive into new projects, but I consider it in the alpha stage because it has been used and tested by only a few other people than me. On Windows, this version doesn't seem to work with IE 8.0 whereas it works with Firefox 3.6.8. I know the software could be improved a lot. For some ideas, look at http://websourcebrowser.sschwarzer.net/trac/wiki/Ideas http://websourcebrowser.sschwarzer.net/trac/browser/todo.txt If I implement this alone, it'll probably take years, given that Websourcebrowser is a spare time project (beside my other project, ftputil). So it would be great to get more developers on board. Of course, I'm thankful for feedback on the mailing list (subscription required to avoid spam, sorry), http://codespeak.net/mailman/listinfo/websourcebrowser or via private e-mail. If you encounter problems, you may also file a bug report at http://websourcebrowser.sschwarzer.net/trac/newticket *** You need to log in as user wsbuser with password wsb . *** Stefan From no.email at please.post Wed Aug 4 17:49:53 2010 From: no.email at please.post (kj) Date: Wed, 4 Aug 2010 21:49:53 +0000 (UTC) Subject: XML parsing: SAX/expat & yield References: Message-ID: In Peter Otten <__peter__ at web.de> writes: >How about >http://effbot.org/zone/element-iterparse.htm#incremental-parsing Exactly! Thanks! ~K From christopherbl at gmail.com Wed Aug 4 18:08:11 2010 From: christopherbl at gmail.com (Christopher Barrington-Leigh) Date: Wed, 4 Aug 2010 15:08:11 -0700 (PDT) Subject: scipy / stats : quantiles using sample weights from survey data Message-ID: <94bb6313-1b09-4eeb-9969-07d76048a361@m35g2000prn.googlegroups.com> There is a function scipy.stats.mstats.mquantiles that returns quantiles for a vector of data. But my data should not be uniformly weighted in an estimate of the distribution, since they are from a survey and come with estimated sampling weights based on the stratification used in sampling. Is there a routine to calculate these quantiles taking into account the survey weights? I can find nothing, so maybe you have had the same problem and written something. Thanks! From no.email at please.post Wed Aug 4 18:15:04 2010 From: no.email at please.post (kj) Date: Wed, 4 Aug 2010 22:15:04 +0000 (UTC) Subject: how to pretty-print Python dict with unicode? Message-ID: Is there a simple way to get Python to pretty-print a dict whose values contain Unicode? (Of course, the goal here is that these printed values are human-readable.) If I run the following simple script: from pprint import pprint x = u'\u6c17\u304c\u9055\u3046' print '{%s: %s}' % (u'x', x) print {u'x': x} pprint({u'x': x}) The first print statement produces perfectly readable Japanese, but the remaining statements both produce the line {u'x': u'\u6c17\u304c\u9055\u3046'} I've tried everything I can think of (including a lot of crazy stuff) short of re-writing pprint from scratch (which I think would be faster than grokking it and hacking at it). Isn't there an easier way to do this? Thanks! ~K From aahz at pythoncraft.com Wed Aug 4 18:20:32 2010 From: aahz at pythoncraft.com (Aahz) Date: 4 Aug 2010 15:20:32 -0700 Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c4c4e6f$0$11094$c3e8da3@news.astraweb.com> Message-ID: In article , Nobody wrote: > >Java's checked exception mechanism was based on real-world experience of >the pitfalls of abstract types. And that experience was gained in >environments where interface specifications were far more detailed than is >the norm in the Python world. There are a number of people who claim that checked exceptions are the wrong answer: http://www.mindview.net/Etc/Discussions/CheckedExceptions -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From barry at python.org Wed Aug 4 18:27:44 2010 From: barry at python.org (Barry Warsaw) Date: Wed, 4 Aug 2010 18:27:44 -0400 Subject: Python 2.6.6 release candidate 1 now available Message-ID: <20100804182744.4a473a38@heresy> Hello fellow Pythoneers and Pythonistas, The source tarballs and Windows installers for the first (and hopefully only) Python 2.6.6 release candidate is now available: http://www.python.org/download/releases/2.6.6/ As usual, we would love it if you could download, install, and test these with your favorite projects and environments. A truly impressive number of bug have been fixed since Python 2.6.5, with the full NEWS file available here: http://www.python.org/download/releases/2.6.6/NEWS.txt Barring complications, we expect to release Python 2.6.6 final on August 16, 2010. Please note that with the release of Python 2.7 final on July 3, 2010, and in accordance with Python policy, Python 2.6.6 is the last scheduled bug fix maintenance release of the 2.6 series. Because of this, your testing of this release candidate will help immensely. We will of course continue to support security fixes in Python 2.6 for quite some time. My thanks go out to everyone who has helped contribute fixes great and small, and much testing and bug tracker gardening for Python 2.6.6. The excellent folks on #python-dev are true Pythonic heros too. Enjoy, -Barry (on behalf of the Python development community) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: not available URL: From rhodri at wildebst.demon.co.uk Wed Aug 4 18:33:17 2010 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Wed, 04 Aug 2010 23:33:17 +0100 Subject: python terminology on classes References: <8e60e2db-205d-4b8b-9c19-1d46e2318cb8@h20g2000vbs.googlegroups.com> Message-ID: On Wed, 04 Aug 2010 19:28:48 +0100, Steve Ferg wrote: >> Seriously, we can't keep doing your thinking for you. The answers >> to all your questions are section 9 of the tutorial. > > This is is just the kind of newbie-hostile smart-ass reply that we do > not want to see on comp.lang.python. > > Let's try again: > > I think that the answers to all your questions are section 9 of the > tutorial. > http://docs.python.org/py3k/tutorial/index.html > > Why don't you take a look at it, and then come back again if you still > have questions. With Peng Yu, we've been through that quite a lot. It seemed time to be a little sharper in the hope that learning might emerge. -- Rhodri James *-* Wildebeest Herder to the Masses From sschwarzer at sschwarzer.net Wed Aug 4 18:36:46 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 05 Aug 2010 00:36:46 +0200 Subject: __init__ as a lambda In-Reply-To: References: Message-ID: <4C59EB7E.30905@sschwarzer.net> Hi Eric, On 2010-08-04 21:58, Eric J. Van der Velden wrote: > class C: > def __init__(self,name):self.name=name > > I was wondering if I could make the __init__ a lambda function, but > > class C: > __init__=lambda self,self.name:None > > and then later, > > C('Hello') > > does not work; the first argument, self, is assigned all rigth, but > you cannot write the second argument with a dot, self.name . The "problem" is that in a lambda function the part after the colon has to be an expression. However, you have used an assignment there which isn't an expression in Python but a statement. For example, you can use f = lambda x: sys.stdout.write(str(x)) (sys.stdout.write(str(x)) is an expression) but not f = lambda x: print x (print x is a statement in Python versions < 3) Stefan From ldo at geek-central.gen.new_zealand Wed Aug 4 18:44:10 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 10:44:10 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: In message , Grant Edwards wrote: > In my experience, the hiring issue is "we're already behind schedule > and short-handed, we don't have the time or resources to teach people > a new language." Most people seem to need tutorials or handholding of some sort. Look at the number of questions in this group which could be answered just by reading the reference manual. From ldo at geek-central.gen.new_zealand Wed Aug 4 18:45:30 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 10:45:30 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In message , Grant Edwards wrote: > The problem has nothing to do with the relative merits of the > languages. The problem is inertia. So how was C++ able to get popular in the first place? And how was Java able to grab some share from it? From ldo at geek-central.gen.new_zealand Wed Aug 4 18:47:10 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 10:47:10 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , David Robinow wrote: > As an admittedly stupid comparison, I have 1579 DLLs in my > \windows\system32 directory. > Some number of these have been upgraded by Windows Update. What about the ones that aren?t? How do you maintain those? From ldo at geek-central.gen.new_zealand Wed Aug 4 18:50:03 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 10:50:03 +1200 Subject: Package management (was: Why is there no platform independent way of clearing a terminal?) References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <87aap44mc7.fsf_-_@benfinney.id.au> Message-ID: In message <87aap44mc7.fsf_-_ at benfinney.id.au>, Ben Finney wrote: > Sadly, Python's package management is rather lacking by these standards. > The Distutils legacy assumption of ?package recipient, system > administrator, and end user are all the same person?, among other design > decisions, makes it unusually difficult to have the necessary separation > of concerns between OS packaging, system administration, and end user. Doesn?t matter. I?m pretty sure Debian has a way of automatically turning a distutils build into a .deb package with all the right dependencies. :) From ben+python at benfinney.id.au Wed Aug 4 19:00:08 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 05 Aug 2010 09:00:08 +1000 Subject: Questions, newbies, and community (was: python terminology on classes) References: <8e60e2db-205d-4b8b-9c19-1d46e2318cb8@h20g2000vbs.googlegroups.com> Message-ID: <87tyna2dc7.fsf_-_@benfinney.id.au> "Rhodri James" writes: > On Wed, 04 Aug 2010 19:28:48 +0100, Steve Ferg > wrote: > > >> Seriously, we can't keep doing your thinking for you. The answers > >> to all your questions are section 9 of the tutorial. > > > > This is is just the kind of newbie-hostile smart-ass reply that we do > > not want to see on comp.lang.python. [?] > With Peng Yu, we've been through that quite a lot. It seemed time to > be a little sharper in the hope that learning might emerge. As someone who generally deplores sharp replies to newbies for the negative effect on the community as a whole and on later newcomers in particular: I have to agree with Rhodri here. This specific case has reached a point where some sharpness is warranted, in my opinion. Peng Yu, please take Rhodri's reply in a spirit of mentoring. You have all the tools at your disposal and they have been pointed out to you numerous times. When asking a question of others, please demonstrate that you have exhausted the existing resources you clearly know you have available to you. -- \ ?What we usually pray to God is not that His will be done, but | `\ that He approve ours.? ?Helga Bergold Gross | _o__) | Ben Finney From no.email at nospam.invalid Wed Aug 4 19:02:46 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 04 Aug 2010 16:02:46 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> Message-ID: <7xocdi56cp.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > > The Ada 2012 Language Reference Manual is 860 pages ... > Yeah, unfortunately the language was designed by a committee ... > It seems apt to describe the resulting design as ?bulletproof?, but > ?elegant? or ?concise? ... not so much. I'd say the Ada standardizers went to a great deal of trouble to specify and document stuff that other languages simply leave undefined, leaving developers relying on implementation-specific behavior that's not part of the standard. Ada itself is not necessarily more complicated. From pavlovevidence at gmail.com Wed Aug 4 19:03:11 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Aug 2010 16:03:11 -0700 (PDT) Subject: __init__ as a lambda References: Message-ID: <512aefcc-dea0-41ad-bc08-e9594b545870@y11g2000yqm.googlegroups.com> On Aug 4, 12:58?pm, "Eric J. Van der Velden" wrote: > Hello, > > Suppose > > class C: > ?def __init__(self,name):self.name=name > > I was wondering if I could make the __init__ a lambda function, but > > class C: > ?__init__=lambda self,self.name:None > > and then later, > > C('Hello') > > does not work; the first argument, self, is assigned all rigth, but > you cannot write the second argument with a dot, ?self.name . > Or can I somehow? __init__=lambda self,name:setattr(self,'name',name) However if you actually do this, you need to be smacked upside the head. Carl Banks From invalid at invalid.invalid Wed Aug 4 19:04:50 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 4 Aug 2010 23:04:50 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-04, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> The problem has nothing to do with the relative merits of the >> languages. The problem is inertia. > > So how was C++ able to get popular in the first place? Building on C's popularity helped. > And how was Java able to grab some share from it? Good question. Both IBM and Sun put a lot of effort/money behind Java. -- Grant From chare at labr.net Wed Aug 4 19:22:03 2010 From: chare at labr.net (Chris Hare) Date: Wed, 04 Aug 2010 18:22:03 -0500 Subject: adding optionMenu items in code Message-ID: <346DD2AA-04A4-49B6-94DD-31B6DEFCB3A0@labr.net> I have an option menu self.w = OptionMenu(self.frameNewNet, self.variable, "one", "two", "three") Is there a way to add items to this programmatically, i.e. using values from a database? From no.email at nospam.invalid Wed Aug 4 19:23:52 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 04 Aug 2010 16:23:52 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: <7xk4o655dj.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > So how was C++ able to get popular in the first place? And how was > Java able to grab some share from it? C++ made improvements over C that were necessary and welcome for controlling the complexity of large programs, while remaining mostly upward compatible with C. Java abandoned C compatibility and added memory safety and GC. That got rid of legacy-related pain and improved program reliability and eased debugging considerably, at some cost in performance. Java was also on the OO bandwagon of the 1990's, which translated into good marketing back then, but is part of the cause of the massive bureaucracy and bloat in the Java runtime environment. C++ seems to have made something of a comeback because of this, and Java now has generics patterned after C++'s. From benjamin.kaplan at case.edu Wed Aug 4 19:24:29 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 4 Aug 2010 16:24:29 -0700 Subject: how to pretty-print Python dict with unicode? In-Reply-To: References: Message-ID: On Wed, Aug 4, 2010 at 3:15 PM, kj wrote: > > > > Is there a simple way to get Python to pretty-print a dict whose > values contain Unicode? ?(Of course, the goal here is that these > printed values are human-readable.) > > If I run the following simple script: > > from pprint import pprint > x = u'\u6c17\u304c\u9055\u3046' > print '{%s: %s}' % (u'x', x) > print {u'x': x} > pprint({u'x': x}) > > The first print statement produces perfectly readable Japaneuse, > but the remaining statements both produce the line > > {u'x': u'\u6c17\u304c\u9055\u3046'} > > I've tried everything I can think of (including a lot of crazy > stuff) short of re-writing pprint from scratch (which I think would > be faster than grokking it and hacking at it). > > Isn't there an easier way to do this? > > Thanks! > > ~K use Python 3? http://www.python.org/dev/peps/pep-3138/ Or just iterate over the items and print them out yourself. The reason you see the escaped values is that str(dict()) calls repr on all the items. If you convert them to strings using str instead of repr(), it will work the way you want. From vlastimil.brom at gmail.com Wed Aug 4 19:28:01 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 5 Aug 2010 01:28:01 +0200 Subject: how to pretty-print Python dict with unicode? In-Reply-To: References: Message-ID: 2010/8/5 kj : > > Is there a simple way to get Python to pretty-print a dict whose > values contain Unicode? (Of course, the goal here is that these > printed values are human-readable.) > > If I run the following simple script: > > from pprint import pprint > x = u'\u6c17\u304c\u9055\u3046' > print '{%s: %s}' % (u'x', x) > print {u'x': x} > pprint({u'x': x}) > > The first print statement produces perfectly readable Japanese, > but the remaining statements both produce the line > > {u'x': u'\u6c17\u304c\u9055\u3046'} > > I've tried everything I can think of (including a lot of crazy > stuff) short of re-writing pprint from scratch (which I think would > be faster than grokking it and hacking at it). > > Isn't there an easier way to do this? > > Thanks! > > ~K > -- > http://mail.python.org/mailman/listinfo/python-list > I am not sure it helps, others will probably offer more elegant suggestions, but if the dict is one-dimensional (i.e. it doesn't contain any other containers or mappings - dicts, lists etc., but only strings, numbers, you can use a simple print with a string conversion in a loop or join the dict to a single printable string. Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> d = {1: u'\u6c17\u304c\u9055\u3046', 2: u'\u6c17\u304c\u9055\u3046', 3: u'\u6c17\u304c\u9055\u3046', } >>> for k, v in d.items(): print "%s: %s" % (k, v) 1: ???? 2: ???? 3: ???? >>> for k, v in d.items(): print "%s: %s," % (k, v), 1: ????, 2: ????, 3: ????, >>> >>> print "".join("%s: %s, " % (k, v) for k, v in d.iteritems()) 1: ????, 2: ????, 3: ????, >>> Or you can use python 3, where repr() behaves directly like you would need (also for arbitrarily nested data structers, unlike the simple approach above): Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> d = {1: '\u6c17\u304c\u9055\u3046', 2: '\u6c17\u304c\u9055\u3046', 3: '\u6c17\u304c\u9055\u3046', } >>> d {1: '????', 2: '????', 3: '????'} >>> (It might be possible to replace the sys.stdout to use str() as needed on python 2.x too, but I am not sure if it would be worth it.) vbr From nagle at animats.com Wed Aug 4 19:28:29 2010 From: nagle at animats.com (John Nagle) Date: Wed, 04 Aug 2010 16:28:29 -0700 Subject: __init__ as a lambda In-Reply-To: References: Message-ID: <4c59f79f$0$1590$742ec2ed@news.sonic.net> On 8/4/2010 12:58 PM, Eric J. Van der Velden wrote: > Hello, > > Suppose > > class C: > def __init__(self,name):self.name=name > > I was wondering if I could make the __init__ a lambda Python is not a functional language. Attempts to make it one make it worse. There's this mindset that loops are somehow "bad". This leads to list comprehensions, multiline lambdas, more elaborate generators, weird conditional expression syntax, and related cruft. Most of these features are of marginal, if not negative, value. Unfortunately, some of them have gone into Python. John Nagle From nikos.the.gr33k at gmail.com Wed Aug 4 19:40:45 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Wed, 4 Aug 2010 16:40:45 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format Message-ID: Okey, i have many hours now struggling to convert a mysql datetime field that i retreive to a string of this format '%d %b, %H:%M' I google a lot but couldnt found out how to format it being a string Here si the code so far: try: cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) except MySQLdb.Error: print( "Error %d: %s" % (e.args[0], e.args[1]) ) else: #display results print ( '''

( ?????????? ) ----- ( ?????????? ) ----- ( ?????????? )


''' ) print ( '''

%s %s %s
%s %s %s
%s %s %s
%s") Though I think I'd make it a bit clearer by naming the fields: for host, hits, dt in dataset: print ("
%s
%s
%s
%s
Some Date String SomeTag A Title Some Comment
Some Date String SomeTag > ? ? ? ? A Title > ? ? ? > ? ? ? ? ? ? ? ? ? Click > ? ? ? ? > ? ? ? Some Comment
Some Date String SomeTag > A Title > > Click > > Some Comment
Some Date String SomeTag > ? ? ? ? A Title > ? ? ? > ? ? ? ? ? ? ? ? ?Click > ? ? ? ? > ? ? ? Some Comment
Some Date String SomeTag >> A Title >> >> > Click >> >> Some Comment
Some Date String SomeTag > A Title > > Click > > Some Comment
Some Date String SomeTag > A Title > > Click > > Some Comment
Some Date String SomeTag > >> ? ? ? ? A Title > >> ? ? ? > >> ? ? ? ? >> ? ? ? ? ? Click > >> ? ? ? ? > >> ? ? ? Some Comment
''' ) results = cursor.fetchall() for row in results: print ( ''' ''' ) for entry in row: entry = datetime.datetime.strftime( entry, '%d %b, %H:%M' ) #!!! this is wrong! print ( ''' ''' % entry ) sys.exit(0) Apart from that i don't know how iam supposed to print it, because the date string is the 3rd string in every row of the dataset. Please help me out! From ben+python at benfinney.id.au Wed Aug 4 19:56:26 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 05 Aug 2010 09:56:26 +1000 Subject: Package management References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <87aap44mc7.fsf_-_@benfinney.id.au> Message-ID: <87pqxy2aqd.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > In message <87aap44mc7.fsf_-_ at benfinney.id.au>, Ben Finney wrote: > > > Sadly, Python's package management is rather lacking by these > > standards. The Distutils legacy assumption of ?package recipient, > > system administrator, and end user are all the same person?, among > > other design decisions, makes it unusually difficult to have the > > necessary separation of concerns between OS packaging, system > > administration, and end user. > > Doesn?t matter. I?m pretty sure Debian has a way of automatically > turning a distutils build into a .deb package with all the right > dependencies. :) Your certainty is no comfort to those who have to do the work of actually making those packages. Have you ever tried to make such a package and get it into Debian? The automation you speak of must be made and maintained by people, and they can only automate to the extent that the Distutils output allows. Have you spoken about this with the people who did that work, and what did they say to give you your certainty? If not, on what do you base your certainty? -- \ ?Any sufficiently advanced bug is indistinguishable from a | `\ feature.? ?Rich Kulawiec | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Wed Aug 4 20:19:20 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 12:19:20 +1200 Subject: Package management References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> <87aap44mc7.fsf_-_@benfinney.id.au> <87pqxy2aqd.fsf@benfinney.id.au> Message-ID: In message <87pqxy2aqd.fsf at benfinney.id.au>, Ben Finney wrote: > Have you ever tried to make such a package and get it into Debian? I have found it very easy to recreate the same steps used by the package maintainers. For instance, ?apt-get source ? brings down the exact same source files used by the maintainer to build the package. Also, ?apt- get build-dep ? will make sure you have the right development tools installed to do the build. Then dpkg-buildpackage will build your own version of the package, in exactly the same way that the maintainers do it. > The automation you speak of must be made and maintained by people, and > they can only automate to the extent that the Distutils output allows. They seem to manage it OK. Just for fun, I tried building the python-cairo package from source, and among the output that flew by was for i in 2.5 2.6; do \ python$i-dbg ./setup.py build; \ done So they have found a way to automate the package build using distutils, rather than bypassing it. Also it manages to perform useful-looking checks like dpkg-shlibdeps: warning: dependency on libpthread.so.0 could be avoided if "debian/python-cairo/usr/lib/pyshared/python2.6/cairo/_cairo.so debian/python-cairo/usr/lib/pyshared/python2.5/cairo/_cairo.so" were not uselessly linked against it (they use none of its symbols). Oversight in the upstream build procedure, perhaps? Anyway, now I have my own .deb files, ready for installation. From pavlovevidence at gmail.com Wed Aug 4 21:07:44 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Aug 2010 18:07:44 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On Aug 4, 4:04?pm, Grant Edwards wrote: > On 2010-08-04, Lawrence D'Oliveiro wrote: > > > In message , Grant Edwards wrote: > > >> The problem has nothing to do with the relative merits of the > >> languages. ?The problem is inertia. > > > So how was C++ able to get popular in the first place? > > Building on C's popularity helped. AT&T + Money + C backward compatibility > > And how was Java able to grab some share from it? > > Good question. ?Both IBM and Sun put a lot of effort/money behind > Java. Sun + IBM + Money + 90s Web trinkets Carl Banks (haven't seen a Java applet in ages) From pavlovevidence at gmail.com Wed Aug 4 21:19:38 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Aug 2010 18:19:38 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> <7xk4o655dj.fsf@ruckus.brouhaha.com> Message-ID: <96e7627b-47f8-49e2-9aff-3ed74267b2cb@l14g2000yql.googlegroups.com> On Aug 4, 4:23?pm, Paul Rubin wrote: >?Java was also on the OO bandwagon of the 1990's, which > translated into good marketing back then, but is part of the cause of > the massive bureaucracy and bloat in the Java runtime environment. ?C++ > seems to have made something of a comeback because of this, and Java now > has generics patterned after C++'s. When I first studied Java, my first impression of the language was that it had a Prime Directive that, "other than single inheritance and being kinda like C, don't do anything C++ did". Not a bad policy, actually. However, omitting generics was probably the second worst thing about Java (the worst thing being the awful AWT design). Carl Banks From drobinow at gmail.com Wed Aug 4 22:20:44 2010 From: drobinow at gmail.com (David Robinow) Date: Wed, 4 Aug 2010 22:20:44 -0400 Subject: Why is there no platform independent way of clearing a terminal? In-Reply-To: References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: On Wed, Aug 4, 2010 at 6:47 PM, Lawrence D'Oliveiro wrote: > In message , David > Robinow wrote: > >> ?As an admittedly stupid comparison, I have 1579 DLLs in my >> \windows\system32 directory. >> Some number of these have been upgraded by Windows Update. > > What about the ones that aren?t? How do you maintain those? Lawrence, you've been asking a lot of off-topic questions about Microsoft Windows. I think it's wonderful that you're so open to new ideas, but suggest that you take it to a Windows group, where I'm sure you'll get a friendly response. From roy at panix.com Wed Aug 4 22:56:41 2010 From: roy at panix.com (Roy Smith) Date: Wed, 04 Aug 2010 22:56:41 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > > > The problem has nothing to do with the relative merits of the > > languages. The problem is inertia. > > So how was C++ able to get popular in the first place? And how was Java able > to grab some share from it? C++, for all its flaws, had one powerful feature which made it very popular. It is a superset of C. Whatever that may mean from a technical standpoint, it made the language feel safe and comfortable and low-risk to managers. From a more technical standpoint, it had the very real advantage of being able to include all the C system headers and link against C system libraries. As for Java, that's easy. You could launch Java applets from inside a web browser. In those days, anything related to the web was a one-way express ticket to fame and fortune. From steve-REMOVE-THIS at cybersource.com.au Wed Aug 4 23:18:39 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 05 Aug 2010 03:18:39 GMT Subject: __init__ as a lambda References: Message-ID: <4c5a2d8e$0$11096$c3e8da3@news.astraweb.com> On Wed, 04 Aug 2010 12:58:18 -0700, Eric J. Van der Velden wrote: > Hello, > > Suppose > > class C: > def __init__(self,name):self.name=name > > I was wondering if I could make the __init__ a lambda function, Of course you can. Lambdas aren't special types of functions, they are *syntax* for creating a function consisting of a single expression, and your __init__ function is a single expression. These two are almost identical: def spam(a, b): return a+b spam = lambda a, b: a+b The only(?) differences are spam.func_name or spam.__name__. > but > > class C: > __init__=lambda self,self.name:None > > and then later, > > C('Hello') > > does not work; the first argument, self, is assigned all rigth, but you > cannot write the second argument with a dot, self.name . That gives a syntax error no matter whether you use it in a lambda form or an ordinary function: >>> def f(self,self.name): File "", line 1 def f(self,self.name): ^ SyntaxError: invalid syntax So the problem has nothing to do with lambda. What you want is: lambda self: self.name = None but of course that doesn't work either, because self.name = None is not an expression, it's a statement. So: class C: __init__ = lambda self: setattr(self, 'name', None) But don't do this. Seriously. Just because it is syntactically valid and does what you want, doesn't mean you should do it. Unless you have really good reason, and saving a single line of source code is a *bad* reason, just stick to the standard idiom that everyone can read without going "WTF is this guy doing this for???". class C: def __init__(self): self.name = None -- Steven From thatiumeshchandra at gmail.com Thu Aug 5 00:14:06 2010 From: thatiumeshchandra at gmail.com (rosy us) Date: Wed, 4 Aug 2010 21:14:06 -0700 (PDT) Subject: 100% without investment online part time jobs..(adsense, datawork, neobux..more jobs) Message-ID: 100% without investment?.no registration fee?no need money? Online part time jobs?(googleadsense, dataentry?etc)all type of jobs? work from home..daily 2-3 hours?earn more money without any risk.. Full details at http://adsensejobworkfulldetails.co.cc/ More adsense tips,secrets,increasing money ,seo..also available? From nagle at animats.com Thu Aug 5 00:33:31 2010 From: nagle at animats.com (John Nagle) Date: Wed, 04 Aug 2010 21:33:31 -0700 Subject: A useful, but painful, one-liner to edit money amounts Message-ID: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> There's got to be a better way to do this: def editmoney(n) : return((",".join(reduce(lambda lst, item : (lst + [item]) if item else lst, re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) >>> editmoney(0) '0' >>> editmoney(13535) '13,535' >>> editmoney(-14535) '-14,535' >>> editmoney(123456) '123,456' >>> editmoney(1234567890) '1,234,567,890' >>> editmoney(-1234) '-1,234' The basic idea here is that we want to split the string of digits into groups of 3 digits, aligned at the right. Because regular expressions are right to left, we have to reverse the string to do that, then reverse again at the end. s[::-1} reverses an interable. "split" with a capturing group introduces empty strings into the list. Hence the "reduce" and lambda to get rid of them. Any better ideas? (Yes, I know there's a built-in feature for this scheduled for Python 2.7.) John Nagle From samwyse at gmail.com Thu Aug 5 01:43:25 2010 From: samwyse at gmail.com (samwyse) Date: Wed, 4 Aug 2010 22:43:25 -0700 (PDT) Subject: simple (I hope!) problem References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> <4c57b51c$0$28663$c3e8da3@news.astraweb.com> Message-ID: On Aug 3, 1:20?am, Steven D'Aprano wrote: > On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote: > > Fortunately, I don't need the functionality of the object, I just want > > something that won't generate an error when I use it. ?So, what is the > > quickest way to to create such an object (replacing the 'pass' in my > > first snippet). ?My solution is this: > > > ? ? class C: > > ? ? ? ? def filter(self, *args, **kwds): > > ? ? ? ? ? ? pass > > ? ? register = C() > > > but it seems like I should be able to do something "better", as measured > > by lines of code, faking more than just a 'filter' method, or both. ?Any > > ideas? ?Thanks! > > You want a variation on the Null Object design pattern. > > class NullWithMethods(object): > ? ? def __getattr__(self, name): > ? ? ? ? return self > ? ? def __call__(self, *args, **kwargs): > ? ? ? ? pass > > And in action: > > >>> c = NullWithMethods() > >>> c.spam("hello", "world") > >>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42) > > -- > Steven JM emailed me a good solution, but yours is great! Thanks! From no.email at nospam.invalid Thu Aug 5 02:03:02 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 04 Aug 2010 23:03:02 -0700 Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <7xocdha961.fsf@ruckus.brouhaha.com> John Nagle writes: > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) Too obscure. I usually use something like this: def editmoney(n): if n < 0: return '-' + editmoney(-n) if n >= 1000: return editmoney(n // 1000) + ',%03d'% (n % 1000) return '%d'% n From steve-REMOVE-THIS at cybersource.com.au Thu Aug 5 02:20:58 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 05 Aug 2010 06:20:58 GMT Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <4c5a584a$0$11096$c3e8da3@news.astraweb.com> On Wed, 04 Aug 2010 21:33:31 -0700, John Nagle wrote: > There's got to be a better way to do this: > > > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) What does the name "editmoney" mean? Why the obfuscated one-liner? It's not like you're using it in-line, you're putting it in a function, so who cares if it's one line or twenty? def group_digits(n, size=3, sep=','): """Group int n in groups of size digits separated by sep.""" s = str(n) m = len(s) % size head = s[0:m] tail = s[m:] groups = [tail[i*size:(i+1)*size] for i in range(len(tail)//size)] tail = sep.join(groups) if head and tail: return head + sep + tail elif tail: return tail else: return head >>> group_digits(0) '0' >>> group_digits(1234567890) '1,234,567,890' >>> group_digits(1234567890, 4, ';') '12;3456;7890' Additional error checking, a better docstring, and extending it to support negative numbers is left as an exercise. -- Steven From ddasilva at umd.edu Thu Aug 5 02:26:01 2010 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 4 Aug 2010 23:26:01 -0700 Subject: newbie problem with str.replace In-Reply-To: <0ece6c99-1c8f-4055-9ed9-4f63b4ed4b2d@j8g2000yqd.googlegroups.com> References: <0ece6c99-1c8f-4055-9ed9-4f63b4ed4b2d@j8g2000yqd.googlegroups.com> Message-ID: Also, for bestandsnaam in dirs and files: is probably not doing what you want. Use + to concatenate lists. Daniel On Wed, Aug 4, 2010 at 6:30 AM, Mike Kent wrote: > On Aug 4, 9:10 am, BobAalsma wrote: > > I'm working on a set of scripts and I can't get a replace to work in > > the script - please help. > > > > bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) > > I'm not sure what you are intending to do here, but string.replace > does not do its replacement in-place. It returns a copy of the > original string, with the replacement done in the copy. You are not > assigning the string returned by string.replace to anything, > therefore, it is immediately thrown away. > > Secondly, and this is just a guess, but since you are doing the > string.replace inside of an os.walk loop, you appear to be trying to > do a filename change. I hope you realize that this will in no way > change the name of the file *on disk*; it will only change it in > memory. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Aug 5 02:30:09 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Aug 2010 08:30:09 +0200 Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > There's got to be a better way to do this: > > > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) > > > >>> editmoney(0) > '0' > >>> editmoney(13535) > '13,535' > >>> editmoney(-14535) > '-14,535' > >>> editmoney(123456) > '123,456' > >>> editmoney(1234567890) > '1,234,567,890' > >>> editmoney(-1234) > '-1,234' > > The basic idea here is that we want to split the string of digits > into groups of 3 digits, aligned at the right. Because regular > expressions are right to left, we have to reverse the string to > do that, then reverse again at the end. s[::-1} reverses an > interable. > > "split" with a capturing group introduces empty strings into the > list. Hence the "reduce" and lambda to get rid of them. > > Any better ideas? > > (Yes, I know there's a built-in feature for this scheduled for > Python 2.7.) >>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) 'en_US.UTF8' >>> print locale.currency(13535, grouping=True) $13,535.00 >>> print locale.format("%d", 13535, grouping=True) 13,535 >>> locale.setlocale(locale.LC_ALL, "") 'de_DE.UTF-8' >>> print locale.currency(13535, grouping=True) 13.535,00 ? >>> print locale.format("%d", 13535, grouping=True) 13.535 Peter From debatem1 at gmail.com Thu Aug 5 03:22:57 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 5 Aug 2010 00:22:57 -0700 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: On Wed, Aug 4, 2010 at 11:30 PM, Peter Otten <__peter__ at web.de> wrote: > John Nagle wrote: > >> There's got to be a better way to do this: >> >> >> def editmoney(n) : >> ? ? ?return((",".join(reduce(lambda lst, item : (lst + [item]) if >> ? ? ? ? ?item else lst, >> ? ? ? ? ?re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) >> >> >> ?>>> editmoney(0) >> '0' >> ?>>> editmoney(13535) >> '13,535' >> ?>>> editmoney(-14535) >> '-14,535' >> ?>>> editmoney(123456) >> '123,456' >> ?>>> editmoney(1234567890) >> '1,234,567,890' >> ?>>> editmoney(-1234) >> '-1,234' >> >> The basic idea here is that we want to split the string of digits >> into groups of 3 digits, aligned at the right. ?Because regular >> expressions are right to left, we have to reverse the string to >> do that, then reverse again at the end. ?s[::-1} reverses an >> interable. >> >> "split" with a capturing group introduces empty strings into the >> list. ?Hence the "reduce" and lambda to get rid of them. >> >> Any better ideas? >> >> (Yes, I know there's a built-in feature for this scheduled for >> Python 2.7.) > > >>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) > 'en_US.UTF8' >>>> print locale.currency(13535, grouping=True) > $13,535.00 >>>> print locale.format("%d", 13535, grouping=True) > 13,535 > >>>> locale.setlocale(locale.LC_ALL, "") > 'de_DE.UTF-8' >>>> print locale.currency(13535, grouping=True) > 13.535,00 ? >>>> print locale.format("%d", 13535, grouping=True) > 13.535 > > Peter I had literally no idea this existed. Thanks. Geremy Condra From none at none.com Thu Aug 5 03:25:36 2010 From: none at none.com (Brandon McCombs) Date: Thu, 05 Aug 2010 03:25:36 -0400 Subject: new to python - trouble calling a function from another function Message-ID: Hello, I'm building an elevator simulator for a class assignment. I recently ran into a roadblock and don't know how to fix it. For some reason, in my checkQueue function below, the call to self.goUp() is never executed. It is on the last line of code I pasted in. I can put print statements before and after the call and I have a print statement in goUp() itself. Only the print statements before and after the call are executed. The one inside goUp() is never executed because goUp() never seems to be executed. How can that be? I don't get any errors when the script executes. Surely this isn't some limitation I'm encountering? thanks sorry about the formatting --------------------------------------------- class Elevator(Process): def __init__(self,name): Process.__init__(self,name=name) self.numPassengers = 0 self.passengerList = [] self.passengerWaitQ = [] self.currentFloor = 1 self.idle = 1 self.newPassengers = 0 def goUp(self): print "here" bubbleSort(self.passengerList, len(self.passengerList)) self.currentFloor += 1 if len(self.passengerList) > 0: for p in self.passengerList: if self.currentFloor == p.destination: yield (p.destination - self.currenteFloor) * TRAVELTIME, self reactivate(p) p.inBuilding() else: self.goUp() def checkQueue(self): if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < MAXCAPACITY: if len(self.passengerWaitQ) < MAXCAPACITY: self.newPassengers = len(self.passengerWaitQ) else: self.newPassengers = MAXCAPACITY - len(self.passengerList) for i in range(0,self.newPassengers): self.passengerList.append(self.passengerWaitQ.pop()) self.goUp() From navkirats at gmail.com Thu Aug 5 03:36:12 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 5 Aug 2010 13:06:12 +0530 Subject: new to python - trouble calling a function from another function In-Reply-To: References: Message-ID: <2D98CECE-39EF-4972-9AD9-F856B07FB9D1@gmail.com> I was looking at the code, I dont have much time to go through it, but I might have found a typo - yield (p.destination - self.currenteFloor) , I think it should be currentFloor.Maybe thats your problem. Will look into the code more later. Regards, Nav On 05-Aug-2010, at 12:55 PM, Brandon McCombs wrote: > Hello, > > I'm building an elevator simulator for a class assignment. I recently ran into a roadblock and don't know how to fix it. For some reason, in my checkQueue function below, the call to self.goUp() is never executed. It is on the last line of code I pasted in. I can put print statements before and after the call and I have a print statement in goUp() itself. Only the print statements before and after the call are executed. The one inside goUp() is never executed because goUp() never seems to be executed. How can that be? I don't get any errors when the script executes. Surely this isn't some limitation I'm encountering? > > thanks > > sorry about the formatting > > --------------------------------------------- > class Elevator(Process): > def __init__(self,name): > Process.__init__(self,name=name) > self.numPassengers = 0 > self.passengerList = [] > self.passengerWaitQ = [] > self.currentFloor = 1 > self.idle = 1 > self.newPassengers = 0 > def goUp(self): > print "here" > bubbleSort(self.passengerList, len(self.passengerList)) > self.currentFloor += 1 > if len(self.passengerList) > 0: > for p in self.passengerList: > if self.currentFloor == p.destination: > yield (p.destination - self.currenteFloor) * TRAVELTIME, self > reactivate(p) > p.inBuilding() > else: > self.goUp() > > def checkQueue(self): > if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < MAXCAPACITY: > if len(self.passengerWaitQ) < MAXCAPACITY: > self.newPassengers = len(self.passengerWaitQ) > else: > self.newPassengers = MAXCAPACITY - len(self.passengerList) > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() > -- > http://mail.python.org/mailman/listinfo/python-list From news1234 at free.fr Thu Aug 5 03:49:20 2010 From: news1234 at free.fr (News123) Date: Thu, 05 Aug 2010 09:49:20 +0200 Subject: Python Script Cannot Write to Directory In-Reply-To: References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> Message-ID: <4c5a6d00$0$29614$426a34cc@news.free.fr> On 08/04/2010 09:27 AM, Chris Rebert wrote: > On Wed, Aug 4, 2010 at 12:21 AM, News123 wrote: > >> 3.) try following python >> >> import os >> print os.getcwd() >> import shutil >> shutil("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") > > WTF; modules aren't callable. Typo? > Indeed. This is a typo and Matteo Landi's right about what I meant: shutil.copyfile("YOUR_SOURCE_FILE_NAME","DESTINATION_DIRECTORY/DSTNTN_FILE_NAME") What remains is: I think the answers to my questions will help to reveal the cause of the problem. The original question lacks necessary information as file permissions / directory permissions etc. / the exact error message. From steve-REMOVE-THIS at cybersource.com.au Thu Aug 5 04:29:54 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 05 Aug 2010 08:29:54 GMT Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <4c5a7682$0$11096$c3e8da3@news.astraweb.com> On Thu, 05 Aug 2010 00:22:57 -0700, geremy condra wrote: >>>>> locale.setlocale(locale.LC_ALL, "") >> 'de_DE.UTF-8' >>>>> print locale.currency(13535, grouping=True) >> 13.535,00 ? >>>>> print locale.format("%d", 13535, grouping=True) >> 13.535 >> >> Peter > > I had literally no idea this existed. Thanks. I knew it existed, but completely forgot about it. Thanks also Peter. -- Steven From jeanmichel at sequans.com Thu Aug 5 05:17:05 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 11:17:05 +0200 Subject: A new syntax for writing tests In-Reply-To: References: Message-ID: <4C5A8191.1090907@sequans.com> Jonathan Fine wrote: > Hi > > I just discovered today a new syntax for writing tests. The basic > idea is to write a function that contains some statements, and run it > via a decorator. I wonder if anyone had seen this pattern before, and > how you feel about it. For myself, I quite like it. > > Let's suppose we want to test this trivial (of course) class. > class Adder(object): > > def __init__(self): > self.value = 0 > > def plus(self, delta): > self.value += delta > > The test the class you need a runner. In this case it is quite simple. > > def runner(script, expect): > '''Create an adder, run script, expect value.''' > > adder = Adder() > script(adder) > return adder.value > > We can now create (and run if we wish) a test. To do this we write > > @testit(runner, 4) > def whatever(a): > '''Two plus two is four.''' > > a.plus(2) > a.plus(2) > > Depending on the exact value of the testit decorator (which in the end > is up to you) we can store the test, or execute it immediately, or do > something else. > > The simplest implementation prints: > OK: Two plus two is four. > for this passing test, and > Fail: Two plus four is five. > expect 5 > actual 6 > for a test that fails. > > Here is the testit decorator used to produce the above output: > > def testit(runner, expect): > '''Test statements decorator.''' > > def next(script): > actual = runner(script, expect) > if actual == expect: > print 'OK:', script.__doc__ > else: > print 'Fail:', script.__doc__ > print ' expect', expect > print ' actual', actual > > return next > > > You can pick this code, for at least the next 30 days, at > http://dpaste.com/hold/225056/ > > For me the key benefit is that writing the test is really easy. > Here's a test I wrote earlier today. > > @testit(runner, '''''') > def whatever(tb): > tb.start('a', {'att': 'value'}) > tb.start('b') > tb.end('b') > tb.end('a') > > If the test has a set-up and tear-down, this can be handled in the > runner, as can the test script raising an expected or unexpected > exception. > Hi, "The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users." source http://docs.python.org/library/unittest.html As you can see, a much more featured test framework already exists. There's nothing wrong in a new test framework, but it has to be better than the existing one in some situations. JM From jeanmichel at sequans.com Thu Aug 5 05:32:06 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 11:32:06 +0200 Subject: simple (I hope!) problem In-Reply-To: References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> <4c57b51c$0$28663$c3e8da3@news.astraweb.com> Message-ID: <4C5A8516.3070201@sequans.com> samwyse wrote: > On Aug 3, 1:20 am, Steven D'Aprano T... at cybersource.com.au> wrote: > >> On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote: >> >>> Fortunately, I don't need the functionality of the object, I just want >>> something that won't generate an error when I use it. So, what is the >>> quickest way to to create such an object (replacing the 'pass' in my >>> first snippet). My solution is this: >>> >>> class C: >>> def filter(self, *args, **kwds): >>> pass >>> register = C() >>> >>> but it seems like I should be able to do something "better", as measured >>> by lines of code, faking more than just a 'filter' method, or both. Any >>> ideas? Thanks! >>> >> You want a variation on the Null Object design pattern. >> >> class NullWithMethods(object): >> def __getattr__(self, name): >> return self >> def __call__(self, *args, **kwargs): >> pass >> >> And in action: >> >> >>>>> c = NullWithMethods() >>>>> c.spam("hello", "world") >>>>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42) >>>>> >> -- >> Steven >> > > JM emailed me a good solution, but yours is great! Thanks! > The version I gave you overrides __getattribute__. To be honest, overriding __getattr__ is a better solution.Just in case you don't know the difference, __getattr__ is called only if the attribute is not found while __getattribute__ is actually called to find the attribute. JM From sschwarzer at sschwarzer.net Thu Aug 5 05:49:48 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 05 Aug 2010 11:49:48 +0200 Subject: simple integer subclass In-Reply-To: References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> Message-ID: <4C5A893C.6060807@sschwarzer.net> Hi Andreas, On 2010-08-03 12:15, Andreas Pfrengle wrote: > On 3 Aug., 03:22, Carl Banks wrote:> > Thinking about it, it might really be dangerous to coerce always to > int1, since sometimes I might want a normal int as result (I can't > tell yet for sure). Yes, that way your problem may shift from inconvenient to outright hairy. ;-) > The application will be a browsergame, and most gamers start counting > at 1, so they would probably wonder about a "level 0 item" ;-) > If there didn't already exist lots of code, I would redesign the whole > data-structure - I think that's "lessons learned" for the next project What about def _index_to_level(index): return index + 1 with this or a different name? This admittedly is longer than writing `something + 1` but in the latter case you might wonder what the addition is for, i. e. if it's really a level offset calculation or something else. Stefan From joncle at googlemail.com Thu Aug 5 05:50:05 2010 From: joncle at googlemail.com (Jon Clements) Date: Thu, 5 Aug 2010 02:50:05 -0700 (PDT) Subject: new to python - trouble calling a function from another function References: Message-ID: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> On 5 Aug, 08:25, Brandon McCombs wrote: > Hello, > > I'm building an elevator simulator for a class assignment. I recently > ran into a roadblock and don't know how to fix it. For some reason, in > my checkQueue function below, the call to self.goUp() is never executed. > It is on the last line of code I pasted in. I can put print statements > before and after the call and I have a print statement in goUp() itself. > ? Only the print statements before and after the call are executed. The > one inside goUp() is never executed because goUp() never seems to be > executed. How can that be? I don't get any errors when the script > executes. Surely this isn't some limitation I'm encountering? > > thanks > > sorry about the formatting > > --------------------------------------------- > class Elevator(Process): > def __init__(self,name): > ? ? ? ? Process.__init__(self,name=name) > ? ? ? ? self.numPassengers = 0 > ? ? ? ? self.passengerList = [] > ? ? ? ? self.passengerWaitQ = [] > ? ? ? ? self.currentFloor = 1 > ? ? ? ? self.idle = 1 > ? ? ? ? self.newPassengers = 0 > def goUp(self): > ? ? ? ? print "here" > ? ? ? ? bubbleSort(self.passengerList, len(self.passengerList)) > ? ? ? ? self.currentFloor += 1 > ? ? ? ? if len(self.passengerList) > 0: > ? ? ? ? ? ?for p in self.passengerList: > ? ? ? ? ? ? ? if self.currentFloor == p.destination: > ? ? ? ? ? ? ? ? yield (p.destination - self.currenteFloor) * TRAVELTIME, self > ? ? ? ? ? ? ? ? reactivate(p) > ? ? ? ? ? ? ? ? p.inBuilding() > ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? self.goUp() > > def checkQueue(self): > ? ? ? ? if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < > MAXCAPACITY: > ? ? ? ? if len(self.passengerWaitQ) < MAXCAPACITY: > ? ? ? ? ? ? self.newPassengers = len(self.passengerWaitQ) > ? ? ? ? else: > ? ? ? ? ? ? ?self.newPassengers = MAXCAPACITY - len(self.passengerList) > ? ? ? ? for i in range(0,self.newPassengers): > ? ? ? ? ? self.passengerList.append(self.passengerWaitQ.pop()) > ? ? ? ? self.goUp() Hi Brandon, Nice one at having a good crack at coding before posting! >From your posted code, I'm struggling to see what's trying to be taught to you for this class assignment. As a note it'll be worth reading PEP 8 regarding naming conventions, because it looks very Java-ish to me! (I might be taking too much a real-world approach in the following, but do with it as you will...) I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere. Although what I'm thinking is that different Elevators will have different capacities and different floors they service. An Elevator is *not* going to know its number of passengers (the most it could do is capacity based on weight restrictions) therefore it's not going to know the number of new passengers on each floor either. A couple of things that'd be worthwhile: 1) Post the requirements for your assignment - what's it supposed to output etc... 2) Go find an elevator, take a pen and pad with you, and stand in it for 30 mins or so, and see how the real thing deals with situations and make notes. ie, does it queue requests, or decide to take the next nearest floor, when does it stop and open etc...? hth Jon. From Juergen.Hermann at 1und1.de Thu Aug 5 06:07:55 2010 From: Juergen.Hermann at 1und1.de (jhermann) Date: Thu, 5 Aug 2010 03:07:55 -0700 (PDT) Subject: Behavior of re.split on empty strings is unexpected References: <4c5701a0$0$1638$742ec2ed@news.sonic.net> Message-ID: <110d416f-858b-4568-bea2-3471f5dcfae9@x25g2000yqj.googlegroups.com> On Aug 2, 7:34?pm, John Nagle wrote: > ?>>> s2 = " ? HELLO ? THERE ?" > ?>>> kresplit4 = re.compile(r'\W+', re.UNICODE) > ?>>> kresplit4.split(s2) > ['', 'HELLO', 'THERE', ''] > > I still get empty strings. >>> re.findall(r"\w+", " a b c ") ['a', 'b', 'c'] From lie.1296 at gmail.com Thu Aug 5 06:27:15 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 05 Aug 2010 20:27:15 +1000 Subject: Nice way to cast a homogeneous tuple In-Reply-To: <5lp5i7-f5u.ln1@satorlaser.homedns.org> References: <4C50305E.3010603@otenet.gr> <4C503122.3060208@otenet.gr> <5lp5i7-f5u.ln1@satorlaser.homedns.org> Message-ID: On Wed, 28 Jul 2010 15:58:29 +0200, Ulrich Eckhardt wrote: > wheres pythonmonks wrote: > > Thanks ... I thought int was a type-cast (like in C++) so I assumed I > > couldn't reference it. > Firstly, "int" is a class. Python doesn't make a distinction between builtin > types and class types like C++, where you e.g. can't derive from builtin > types. That wasn't true until recently with class and type unification. In some older versions of python you cannot derive from build in types either. From ldo at geek-central.gen.new_zealand Thu Aug 5 06:33:39 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 22:33:39 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xocdi56cp.fsf@ruckus.brouhaha.com> Message-ID: In message <7xocdi56cp.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > I'd say the Ada standardizers went to a great deal of trouble to specify > and document stuff that other languages simply leave undefined, leaving > developers relying on implementation-specific behavior that's not part > of the standard. OK, I have a copy of K&R 2nd Ed on a shelf within reach here. Can you point out some behaviour that C programmers might need to rely on, that is not specified in that document? > Ada itself is not necessarily more complicated. It is. Look at its baroque type structure. Hint: why is type A is B; a syntax error? From ldo at geek-central.gen.new_zealand Thu Aug 5 06:34:31 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 22:34:31 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In message , Roy Smith wrote: > C++, for all its flaws, had one powerful feature which made it very > popular. It is a superset of C. Actually, it never was. From eckhardt at satorlaser.com Thu Aug 5 06:35:50 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 05 Aug 2010 12:35:50 +0200 Subject: new to python - trouble calling a function from another function References: Message-ID: <6pgqi7-unn.ln1@satorlaser.homedns.org> Brandon McCombs wrote: > I'm building an elevator simulator for a class assignment. I recently > ran into a roadblock and don't know how to fix it. For some reason, in > my checkQueue function below, the call to self.goUp() is never executed. [...] > sorry about the formatting While I can certainly forgive you the formatting (my problem is rather that you didn't reduce the code to the smallest possible example), Python wont. Python is a language where whitespace is significant and can subtly change the meaning of your code. Example: > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() The formatting here is completely removed, but there are two conceivable ways this could be formatted: # variant 1 for i in range(0,self.newPassengers): self.passengerList.append(self.passengerWaitQ.pop()) self.goUp() #variant 2 for i in range(0,self.newPassengers): self.passengerList.append(self.passengerWaitQ.pop()) self.goUp() Someone already mentioned PEP 8 (search the web!). These PEPs could be called the standards governing Python behaviour, and PEP 8 actually defines several things concerning the formatting of sourcecode. Apply it unless you have a good reason not to. Further, you should run Python with "-t" as argument on the commandline. This will give you warnings when it encounters inconsistent tab/spaces usage. This can make a difference. Example: #variant 3 for i in range(0,self.newPassengers): self.passengerList.append(self.passengerWaitQ.pop()) self.goUp() If your editor is set to four spaces per tab, this will look like variant 2, with 8 spaces it will look like variant 1. I don't know (and don't care, since PEP-8 mandates four spaces) which interpretation Python actually uses. Lastly, you can simplify your check_queue() function. First, determine the number of free places inside the elevator. Then, you simply append that many passengers from the waiting list to the passenger list: free = MAX_CAPACITY - len(self.passengers) new_passengers = self.passenger_wait_queue[:free] self.passenger_wait_queue = self.passenger_wait_queue[free:] self.passengers += new_passengers This uses the fact that list indices are automatically truncated to a valid range, so requesting the elements 0 to 10 from a 5-element list will only yield those five elements, not raise an exception. It's up to you though which version is clearer to you. I would perhaps bail out if "free == 0" and then also not call go_up() lateron. Cheers and good luck! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From ldo at geek-central.gen.new_zealand Thu Aug 5 06:36:10 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 05 Aug 2010 22:36:10 +1200 Subject: Why is there no platform independent way of clearing a terminal? References: <4c4ee6e8$0$20965$426a74cc@news.free.fr> <67f0a4af61f6f83afccff2af8bfc0b94@localhost> <8k15i7-jhs.ln1@satorlaser.homedns.org> <6e6bf2ea-7d98-4af8-8613-6320a8a2d1cc@5g2000yqz.googlegroups.com> Message-ID: In message , David Robinow wrote: > Lawrence, you've been asking a lot of off-topic questions about > Microsoft Windows. You?ve got to be kidding. Look at the number of Windows-specific questions this groups is already full of. From lie.1296 at gmail.com Thu Aug 5 06:39:25 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 05 Aug 2010 20:39:25 +1000 Subject: Nice way to cast a homogeneous tuple In-Reply-To: References: Message-ID: On Wed, 28 Jul 2010 09:15:24 -0400, wheres pythonmonks wrote: > A new python convert is now looking for a replacement for another perl idiom. A functional alternative: l = ... seqint = compose(map, int) print f(seqint(l)) From chris at simplistix.co.uk Thu Aug 5 07:06:17 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 12:06:17 +0100 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <4C5A9B29.2020901@simplistix.co.uk> Peter Otten wrote: >>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) > 'en_US.UTF8' >>>> print locale.currency(13535, grouping=True) > $13,535.00 Okay, so if I'm writing a wsgi app, and I want to format depending on the choices of the currently logged in users, what would you recommend? I can't do setlocale, since that would affect all users, and in a mult-threaded environment that would be bad. Does that mean the whole locale package is useless to all web-app builders? Chris From chris at simplistix.co.uk Thu Aug 5 07:16:33 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 12:16:33 +0100 Subject: subprocess escaping POpen?! Message-ID: <4C5A9D91.9000504@simplistix.co.uk> Hi All, I have a script that does the following: from subprocess import Popen,PIPE,STDOUT def execute(command,cwd): return Popen( command, stderr=STDOUT, stdout=PIPE, universal_newlines=True, cwd=cwd, shell=True, ).communicate()[0] captured = execute('svn up .') Now, if the subversion update requires authentication credentials, it manages to write to the console running the above script, *and* read input from it too. This is a bit baffling to me, I thought Popen.communicate() was happily hoovering all the output to stdout and stderr into the result returned from communicate? And, indeed, if I change the script instead to do: import sys f = open('test.py','w') f.write('import sys; sys.stderr.write("Hello!\\n")') f.close() captured = execute('test.py') ...then the output is indeed captured. So, what is svn doing differently? How is it escaping its jail? Chris From paul.nospam at rudin.co.uk Thu Aug 5 07:20:14 2010 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 05 Aug 2010 12:20:14 +0100 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: <8739utnw5t.fsf@rudin.co.uk> Lawrence D'Oliveiro writes: > In message , Roy Smith wrote: > >> C++, for all its flaws, had one powerful feature which made it very >> popular. It is a superset of C. > > Actually, it never was. Wondering off topic a bit - I am reminded of something I once read in some MS blurb... it described something as an "extended subset" of some standard or another. (Think about it :)) From wolfgang at rohdewald.de Thu Aug 5 07:22:11 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Thu, 5 Aug 2010 13:22:11 +0200 Subject: subprocess escaping POpen?! In-Reply-To: <4C5A9D91.9000504@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> Message-ID: <201008051322.11456.wolfgang@rohdewald.de> On Donnerstag 05 August 2010, Chris Withers wrote: > ...then the output is indeed captured. So, what is svn doing > differently? How is it escaping its jail? maybe it does not read from stdin but directly from /dev/tty -- Wolfgang From chris at simplistix.co.uk Thu Aug 5 07:23:35 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 12:23:35 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <201008051322.11456.wolfgang@rohdewald.de> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> Message-ID: <4C5A9F37.80708@simplistix.co.uk> Wolfgang Rohdewald wrote: > On Donnerstag 05 August 2010, Chris Withers wrote: >> ...then the output is indeed captured. So, what is svn doing >> differently? How is it escaping its jail? > > maybe it does not read from stdin but directly from /dev/tty But why only the request for auth credentials? Chris From jeanmichel at sequans.com Thu Aug 5 07:38:32 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 13:38:32 +0200 Subject: subprocess escaping POpen?! In-Reply-To: <4C5A9D91.9000504@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> Message-ID: <4C5AA2B8.3020806@sequans.com> Chris Withers wrote: > Hi All, > > I have a script that does the following: > > from subprocess import Popen,PIPE,STDOUT > > def execute(command,cwd): > return Popen( > command, > stderr=STDOUT, > stdout=PIPE, > universal_newlines=True, > cwd=cwd, > shell=True, > ).communicate()[0] > > captured = execute('svn up .') > > Now, if the subversion update requires authentication credentials, it > manages to write to the console running the above script, *and* read > input from it too. > > This is a bit baffling to me, I thought Popen.communicate() was > happily hoovering all the output to stdout and stderr into the result > returned from communicate? > > And, indeed, if I change the script instead to do: > > import sys > f = open('test.py','w') > f.write('import sys; sys.stderr.write("Hello!\\n")') > f.close() > captured = execute('test.py') > > ...then the output is indeed captured. So, what is svn doing > differently? How is it escaping its jail? > > Chris > You did not redirect stdin, so it is expected you can still read input from the console. And it looks like svn is writting the credentials prompt on stderr. You may want to look at http://pysvn.tigris.org/docs/pysvn.html though. JM From pict100 at gmail.com Thu Aug 5 07:56:38 2010 From: pict100 at gmail.com (DarkBlue) Date: Thu, 5 Aug 2010 04:56:38 -0700 (PDT) Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <9b4bd0c2-8912-4a60-9a12-b7b8586aba84@i4g2000prf.googlegroups.com> On Aug 5, 7:06?pm, Chris Withers wrote: > Peter Otten wrote: > >>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) > > 'en_US.UTF8' > >>>> print locale.currency(13535, grouping=True) > > $13,535.00 > > Okay, so if I'm writing a wsgi app, and I want to format depending on > the choices of the currently logged in users, what would you recommend? > > I can't do setlocale, since that would affect all users, and in a > mult-threaded environment that would be bad. > > Does that mean the whole locale package is useless to all web-app builders? > > Chris from re import * class editmoney(float): def __init__(self,mymoney): self.mymoney = mymoney def __str__(self): temp = "%.2f" % self.mymoney profile = compile(r"(\d)(\d\d\d[.,])") while 1: temp, count = subn(profile,r"\1,\2",temp) if not count: break return temp From chris at simplistix.co.uk Thu Aug 5 07:58:20 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 12:58:20 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AA2B8.3020806@sequans.com> References: <4C5A9D91.9000504@simplistix.co.uk> <4C5AA2B8.3020806@sequans.com> Message-ID: <4C5AA75C.3080700@simplistix.co.uk> Jean-Michel Pichavant wrote: > You did not redirect stdin, so it is expected you can still read input > from the console. Okay, so if I definitely wanted no input, what should I pass as the stdin parameter to the POpen constructor? > And it looks like svn is writting the credentials > prompt on stderr. ...which, as you can see from the code I posted, is piped to STDOUT, which is then PIPE'd through to the calling python so that communicate()'s return value will contain the output. As I explained, I can't reproduce this by replacing svn with a simple python script that writes to stderr. So, what is svn doing? > You may want to look at http://pysvn.tigris.org/docs/pysvn.html though. Yeah, we were using that, but found it excruciatingly painful due to its dependency on a subversion source install due to its c extension. cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From christoffer at viken.me Thu Aug 5 08:01:32 2010 From: christoffer at viken.me (Christoffer Viken) Date: Thu, 5 Aug 2010 14:01:32 +0200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: C++ is actually not that bad. Can't compare it to C, but nothing compares to C... I think the bad reputation it got (and still has) is from Microsoft's visual studio IDE (that was and still is horrible) A lot of good applications are written in C++, but many bad ones as well. Sorry for swearing in the church, but I'm pulling out PHP as an example. Easy on beginners, the fat that you can jump in and out of PHP mode helps too. It attracts a lot of beginner developers, and most of them write bad code. It does not make the language a bad language, in fact PHP5 is pretty good, but it means that there is a lot of bad code out there, but then we have gems like MediaWiki and Drupal that is really good software. You can write bad code in any language, and many languages get a bad reputation because a lot of bad code is written in it. The real test is not how bad code you can write, but the limit for how good code you can write without jumping trough (too manny) hoops. On Thu, Aug 5, 2010 at 12:34 PM, Lawrence D'Oliveiro wrote: > In message , Roy Smith wrote: > > > C++, for all its flaws, had one powerful feature which made it very > > popular. It is a superset of C. > > Actually, it never was. > -- > http://mail.python.org/mailman/listinfo/python-list > -- ----------Desktop Browser, Google Apps --------- Christoffer Viken / CVi i=0 str="kI4dJMtXAv0m3cUiPKx8H" while i<=20: if i%3 and not i%4: print str[i], i=i+1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From markken at gmail.com Thu Aug 5 08:04:36 2010 From: markken at gmail.com (Marcos Prieto) Date: Thu, 5 Aug 2010 05:04:36 -0700 (PDT) Subject: PyInt_FromLong gives segfault on small numbers (<257) Message-ID: <5db89057-3281-495a-80e4-2e76d7235da6@d17g2000yqb.googlegroups.com> Hi, I'm trying to call python (python 2.6) functions from C++ using MS VC+ + 6.0 and any calls to PyInt_FromLong with numbers below 257 give me exceptions, no problems with bigger numbers PyObject *pValue; pValue = PyInt_FromLong(1L); (or pValue = PyInt_FromLong(1); Any ideas of what can I be doing wrong? Thanks, Marcos. From ryan at rfk.id.au Thu Aug 5 08:11:05 2010 From: ryan at rfk.id.au (Ryan Kelly) Date: Thu, 05 Aug 2010 22:11:05 +1000 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AA75C.3080700@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <4C5AA2B8.3020806@sequans.com> <4C5AA75C.3080700@simplistix.co.uk> Message-ID: <1281010265.1554.2.camel@durian> On Thu, 2010-08-05 at 12:58 +0100, Chris Withers wrote: > Jean-Michel Pichavant wrote: > > You did not redirect stdin, so it is expected you can still read input > > from the console. > > Okay, so if I definitely wanted no input, what should I pass as the > stdin parameter to the POpen constructor? The cross-platform equivalent of /dev/null: Popen(...,stdin=open(os.devnull,"r")...) > > And it looks like svn is writting the credentials > > prompt on stderr. > > ...which, as you can see from the code I posted, is piped to STDOUT, > which is then PIPE'd through to the calling python so that > communicate()'s return value will contain the output. > > As I explained, I can't reproduce this by replacing svn with a simple > python script that writes to stderr. So, what is svn doing? Many programs prompt for auth credentials on the controlling tty instead of standard input/output. I believe SSH also does this, which suggests that it's considered more secure. No idea why, but I trust the authors of SSH to know their stuff in this regard. Cheers, Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details From wolfgang at rohdewald.de Thu Aug 5 08:23:08 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Thu, 5 Aug 2010 14:23:08 +0200 Subject: subprocess escaping POpen?! In-Reply-To: <4C5A9F37.80708@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> Message-ID: <201008051423.08319.wolfgang@rohdewald.de> On Donnerstag 05 August 2010, Chris Withers wrote: > But why only the request for auth credentials? for security reasons I suppose - make sure a human enters the password -- Wolfgang From __peter__ at web.de Thu Aug 5 08:27:44 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Aug 2010 14:27:44 +0200 Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: Chris Withers wrote: > Peter Otten wrote: >>>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) >> 'en_US.UTF8' >>>>> print locale.currency(13535, grouping=True) >> $13,535.00 > > Okay, so if I'm writing a wsgi app, and I want to format depending on > the choices of the currently logged in users, what would you recommend? > > I can't do setlocale, since that would affect all users, and in a > mult-threaded environment that would be bad. > > Does that mean the whole locale package is useless to all web-app Blame it on the C guys ;) I've seen http://babel.edgewall.org/wiki/Documentation/intro.html http://babel.edgewall.org/wiki/ApiDocs/babel.numbers http://babel.edgewall.org/wiki/BabelFaq#WhatalternativesexistforPythonprojects mentioned here but not yet tried it myself. Peter From solipsis at pitrou.net Thu Aug 5 08:34:37 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 5 Aug 2010 14:34:37 +0200 Subject: PyInt_FromLong gives segfault on small numbers (<257) References: <5db89057-3281-495a-80e4-2e76d7235da6@d17g2000yqb.googlegroups.com> Message-ID: <20100805143437.1af3a184@pitrou.net> On Thu, 5 Aug 2010 05:04:36 -0700 (PDT) Marcos Prieto wrote: > Hi, > > I'm trying to call python (python 2.6) functions from C++ using MS VC+ > + 6.0 and any calls to PyInt_FromLong with numbers below 257 give me > exceptions, no problems with bigger numbers > > PyObject *pValue; > > pValue = PyInt_FromLong(1L); (or pValue = PyInt_FromLong(1); Have you called Py_Initialize() before? From chris at simplistix.co.uk Thu Aug 5 08:47:10 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 13:47:10 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <201008051423.08319.wolfgang@rohdewald.de> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> Message-ID: <4C5AB2CE.7040903@simplistix.co.uk> Wolfgang Rohdewald wrote: > On Donnerstag 05 August 2010, Chris Withers wrote: >> But why only the request for auth credentials? > > for security reasons I suppose - make sure a human enters > the password Well yes, but what if you actually want to script it? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From smallpox911 at gmail.com Thu Aug 5 08:50:53 2010 From: smallpox911 at gmail.com (small Pox) Date: Thu, 5 Aug 2010 05:50:53 -0700 (PDT) Subject: *** Project for New American Python, Scheme, Emacs, Unix Century - TUTORIAL VIDEOS *** Message-ID: http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1 http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related http://www.youtube.com/watch?v=eVJxzJAU0nE From jonathan.fine1 at googlemail.com Thu Aug 5 09:07:32 2010 From: jonathan.fine1 at googlemail.com (jfine) Date: Thu, 5 Aug 2010 06:07:32 -0700 (PDT) Subject: A new syntax for writing tests References: Message-ID: On 5 Aug, 10:17, Jean-Michel Pichavant wrote: > Jonathan Fine wrote: > > Hi > > > I just discovered today anewsyntaxfor writing tests. ?The basic > > idea is to write a function that contains some statements, and run it > > via a decorator. ?I wonder if anyone had seen this pattern before, and > > how you feel about it. ?For myself, I quite like it. > > > Let's suppose we want to test this trivial (of course) class. > > ? ? class Adder(object): > > > ? ? ? ? def __init__(self): > > ? ? ? ? ? ? self.value = 0 > > > ? ? ? ? def plus(self, delta): > > ? ? ? ? ? ? self.value += delta > > > The test the class you need a runner. ?In this case it is quite simple. > > > ? ? def runner(script, expect): > > ? ? ? ? '''Create an adder, run script, expect value.''' > > > ? ? ? ? adder = Adder() > > ? ? ? ? script(adder) > > ? ? ? ? return adder.value > > > We can now create (and run if we wish) a test. ?To do this we write > > > ? ? @testit(runner, 4) > > ? ? def whatever(a): > > ? ? ? ? '''Two plus two is four.''' > > > ? ? ? ? a.plus(2) > > ? ? ? ? a.plus(2) > > > Depending on the exact value of the testit decorator (which in the end > > is up to you) we can store the test, or execute it immediately, or do > > something else. > > > The simplest implementation prints: > > ? ? OK: Two plus two is four. > > for this passing test, and > > ? ? Fail: Two plus four is five. > > ? ? ? expect 5 > > ? ? ? actual 6 > > for a test that fails. > > > Here is the testit decorator used to produce the above output: > > > ? ? def testit(runner, expect): > > ? ? ? ? '''Test statements decorator.''' > > > ? ? ? ? def next(script): > > ? ? ? ? ? ? actual = runner(script, expect) > > ? ? ? ? ? ? if actual == expect: > > ? ? ? ? ? ? ? ? print 'OK:', script.__doc__ > > ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? print 'Fail:', script.__doc__ > > ? ? ? ? ? ? ? ? print ' ?expect', expect > > ? ? ? ? ? ? ? ? print ' ?actual', actual > > > ? ? ? ? return next > > > You can pick this code, for at least the next 30 days, at > > ? ?http://dpaste.com/hold/225056/ > > > For me the key benefit is that writing the test is really easy. ? > > Here's a test I wrote earlier today. > > > @testit(runner, '''''') > > def whatever(tb): > > ? ? tb.start('a', {'att': 'value'}) > > ? ? tb.start('b') > > ? ? tb.end('b') > > ? ? tb.end('a') > > > If the test has a set-up and tear-down, this can be handled in the > > runner, as can the test script raising an expected or unexpected > > exception. > > Hi, > > "The unittest module provides a rich set of tools for constructing and > running tests. This section demonstrates that a small subset of the > tools suffice to meet the needs of most users." > > sourcehttp://docs.python.org/library/unittest.html > > As you can see, a much more featured test framework already exists. > > There's nothing wrong in anewtest framework, but it has to be better > than the existing one in some situations. Chalk and cheese. My concern is to make tests easy to write, and that is something that unittest is, in my view, not good at. It is, as you say, a *test framework*. I've not written a test framework. I've found what seems to be a new *syntax* for writing tests. Tests written in the new syntax can be run in the unittest (or any other) framework. -- Jonathan From gurudatta97 at gmail.com Thu Aug 5 09:12:48 2010 From: gurudatta97 at gmail.com (guru datta) Date: Thu, 5 Aug 2010 06:12:48 -0700 (PDT) Subject: ATTRACTIVE HOT PHOTOS&VIDEOS Message-ID: <4ca483a5-b928-4dab-9123-7e09bc26cbfb@l32g2000prn.googlegroups.com> AMISHAPATEL HOT BOOBS http://babes-devi.blogspot.com/2010/07/amishpatel-latest-photos.html ARCHANA UNSEENED EXPOSING PHOTOS http://babes-devi.blogspot.com/2010/07/archana-unseened-photos.html KATRINA KAIF HOT SEXY PHOTOS http://babes-devi.blogspot.com/2010/07/katrina-sexy-looking-photos.html THISHA HOT WET PHOTOS http://babes-devi.blogspot.com/2010/06/thrisha-hot-wet-photos.html SEXY CHARMI IN A BATHROOM http://babes-devi.blogspot.com/2010/06/charmi-in-bath.html KAJALAGARWAL IN A ROMANTIC FEEL http://babes-devi.blogspot.com/2010/06/kajal-hot-photos.html NAMITHA IN A BEACH http://babes-devi.blogspot.com/2010/06/nayagarala-namitha.html From invalid at invalid.invalid Thu Aug 5 09:32:26 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 5 Aug 2010 13:32:26 +0000 (UTC) Subject: subprocess escaping POpen?! References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> Message-ID: On 2010-08-05, Chris Withers wrote: > Wolfgang Rohdewald wrote: >> On Donnerstag 05 August 2010, Chris Withers wrote: >>> But why only the request for auth credentials? >> >> for security reasons I suppose - make sure a human enters >> the password > > Well yes, but what if you actually want to script it? Scripting passwords is considered a huge security hole, so people who care about security try to prevent it by doing things like reading passwords from /dev/tty instead of stdin. -- Grant Edwards grant.b.edwards Yow! I want my nose in at lights! gmail.com From jeanmichel at sequans.com Thu Aug 5 09:36:29 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 15:36:29 +0200 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AA75C.3080700@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <4C5AA2B8.3020806@sequans.com> <4C5AA75C.3080700@simplistix.co.uk> Message-ID: <4C5ABE5D.3040609@sequans.com> Chris Withers wrote: > Jean-Michel Pichavant wrote: >> You did not redirect stdin, so it is expected you can still read >> input from the console. > > Okay, so if I definitely wanted no input, what should I pass as the > stdin parameter to the POpen constructor? You do want an input don't you ? 'cause there is a password to enter. from subprocess doc page: "Note that if you want to send data to the process?s stdin, you need to create the Popen object with stdin=PIPE." > >> And it looks like svn is writting the credentials prompt on stderr. > > ...which, as you can see from the code I posted, is piped to STDOUT, > which is then PIPE'd through to the calling python so that > communicate()'s return value will contain the output. > > As I explained, I can't reproduce this by replacing svn with a simple > python script that writes to stderr. So, what is svn doing? You're right, then that means than svn is writing credentials neither on stdout nor stderr. > >> You may want to look at http://pysvn.tigris.org/docs/pysvn.html though. > > Yeah, we were using that, but found it excruciatingly painful due to > its dependency on a subversion source install due to its c extension. I can't argue with that. > > cheers, > > Chris > If you want to scriptly interract with svn or anything else, you may look at the pexpect module. JM From samwyse at gmail.com Thu Aug 5 09:44:30 2010 From: samwyse at gmail.com (samwyse) Date: Thu, 5 Aug 2010 06:44:30 -0700 (PDT) Subject: simple (I hope!) problem References: <63d429dd-ad13-4214-a955-687241b4e2d3@w30g2000yqw.googlegroups.com> <4c57b51c$0$28663$c3e8da3@news.astraweb.com> Message-ID: On Aug 5, 4:32?am, Jean-Michel Pichavant wrote: > samwyse wrote: > > On Aug 3, 1:20 am, Steven D'Aprano > T... at cybersource.com.au> wrote: > > >> On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote: > > >>> Fortunately, I don't need the functionality of the object, I just want > >>> something that won't generate an error when I use it. ?So, what is the > >>> quickest way to to create such an object (replacing the 'pass' in my > >>> first snippet). ?My solution is this: > > >>> ? ? class C: > >>> ? ? ? ? def filter(self, *args, **kwds): > >>> ? ? ? ? ? ? pass > >>> ? ? register = C() > > >>> but it seems like I should be able to do something "better", as measured > >>> by lines of code, faking more than just a 'filter' method, or both. ?Any > >>> ideas? ?Thanks! > > >> You want a variation on the Null Object design pattern. > > >> class NullWithMethods(object): > >> ? ? def __getattr__(self, name): > >> ? ? ? ? return self > >> ? ? def __call__(self, *args, **kwargs): > >> ? ? ? ? pass > > >> And in action: > > >>>>> c = NullWithMethods() > >>>>> c.spam("hello", "world") > >>>>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42) > > >> -- > >> Steven > > > JM emailed me a good solution, but yours is great! Thanks! > > The version I gave you overrides __getattribute__. To be honest, > overriding __getattr__ is a better solution.Just in case you don't know > the difference, __getattr__ is called only if the attribute is not found > while __getattribute__ is actually called to find the attribute. > > JM I have to apologize for not replying as soon as I got your email. It did everything I needed, so I implemented it in my code and went to town. Then, when I did finally return to the c.l.py, there was an solution that exceeded my needs by letting me chain together arbitrary lists of attributes. Now that I've slept on it, I've come up with a solution that I like even more: >>> class Placeholder(object): def __getattr__(self, name): return self def __getitem__(self, index): return self def __call__(self, *args, **kwargs): return self >>> x = Placeholder() >>> x('hello, world').y[42].z <__main__.Placeholder object at 0x01E46490> Yes, running it from the prompt looks ugly, but within a program the return value is silently discarded. From python.list at tim.thechases.com Thu Aug 5 09:46:28 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 05 Aug 2010 08:46:28 -0500 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xocdi56cp.fsf@ruckus.brouhaha.com> Message-ID: <4C5AC0B4.40604@tim.thechases.com> On 08/05/10 05:33, Lawrence D'Oliveiro wrote: > OK, I have a copy of K&R 2nd Ed on a shelf within reach here. Can you point > out some behaviour that C programmers might need to rely on, that is not > specified in that document? "need to" is considerably different from "might". Size of an int, assumptions that int=pointer, evaluation order of postfix increment/decrement... http://stackoverflow.com/questions/625333/how-to-limit-the-impact-of-implementation-dependent-language-features-in-c or http://tinyurl.com/263jayy if mailers between here & there break the URL) Just because facilities (macros, best-practices, etc) have been established for some of these things doesn't mean a programmer will reach for them if their code happens to work locally without them. Trust me...I've encountered PLENTY of such code in production before I left behind (for the most part) the world of C. -tkc From downaold at gmail.com Thu Aug 5 09:46:29 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 5 Aug 2010 15:46:29 +0200 Subject: abstract metaclass Message-ID: <1B034596-7B57-4950-8070-7685176A824E@gmail.com> Hi all, I'm trying to create a metaclass that keeps track of its objects, and implement this as a collections.MutableMapping. That is, something like this: class type2(type, MutableMapping): ... /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/abc.pyc in __new__(mcls, name, bases, namespace) 83 if getattr(value, "__isabstractmethod__", False)) 84 for base in bases: ---> 85 for name in getattr(base, "__abstractmethods__", set()): 86 value = getattr(cls, name, None) 87 if getattr(value, "__isabstractmethod__", False): TypeError: Error when calling the metaclass bases 'getset_descriptor' object is not iterable Anybody knows why? Every type is just an object, isn't it? Thanks in advance, cheers, Roald From kushal.kumaran at gmail.com Thu Aug 5 09:47:32 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 05 Aug 2010 19:17:32 +0530 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AB2CE.7040903@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> Message-ID: <1281016052.15056.5.camel@Nokia-N900> ----- Original message ----- > Wolfgang Rohdewald wrote: > > On Donnerstag 05 August 2010, Chris Withers wrote: > > > But why only the request for auth credentials? > > > > for security reasons I suppose - make sure a human enters > > the password > > Well yes, but what if you actually want to script it? > Then you use expect. See http://pexpect.sf.net for a python version. -- regards, kushal -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Thu Aug 5 09:52:24 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 15:52:24 +0200 Subject: A new syntax for writing tests In-Reply-To: References: Message-ID: <4C5AC218.4040803@sequans.com> jfine wrote: > On 5 Aug, 10:17, Jean-Michel Pichavant wrote: > >> Jonathan Fine wrote: >> >>> Hi >>> >>> I just discovered today anewsyntaxfor writing tests. The basic >>> idea is to write a function that contains some statements, and run it >>> via a decorator. I wonder if anyone had seen this pattern before, and >>> how you feel about it. For myself, I quite like it. >>> >>> Let's suppose we want to test this trivial (of course) class. >>> class Adder(object): >>> >>> def __init__(self): >>> self.value = 0 >>> >>> def plus(self, delta): >>> self.value += delta >>> >>> The test the class you need a runner. In this case it is quite simple. >>> >>> def runner(script, expect): >>> '''Create an adder, run script, expect value.''' >>> >>> adder = Adder() >>> script(adder) >>> return adder.value >>> >>> We can now create (and run if we wish) a test. To do this we write >>> >>> @testit(runner, 4) >>> def whatever(a): >>> '''Two plus two is four.''' >>> >>> a.plus(2) >>> a.plus(2) >>> >>> Depending on the exact value of the testit decorator (which in the end >>> is up to you) we can store the test, or execute it immediately, or do >>> something else. >>> >>> The simplest implementation prints: >>> OK: Two plus two is four. >>> for this passing test, and >>> Fail: Two plus four is five. >>> expect 5 >>> actual 6 >>> for a test that fails. >>> >>> Here is the testit decorator used to produce the above output: >>> >>> def testit(runner, expect): >>> '''Test statements decorator.''' >>> >>> def next(script): >>> actual = runner(script, expect) >>> if actual == expect: >>> print 'OK:', script.__doc__ >>> else: >>> print 'Fail:', script.__doc__ >>> print ' expect', expect >>> print ' actual', actual >>> >>> return next >>> >>> You can pick this code, for at least the next 30 days, at >>> http://dpaste.com/hold/225056/ >>> >>> For me the key benefit is that writing the test is really easy. >>> Here's a test I wrote earlier today. >>> >>> @testit(runner, '''''') >>> def whatever(tb): >>> tb.start('a', {'att': 'value'}) >>> tb.start('b') >>> tb.end('b') >>> tb.end('a') >>> >>> If the test has a set-up and tear-down, this can be handled in the >>> runner, as can the test script raising an expected or unexpected >>> exception. >>> >> Hi, >> >> "The unittest module provides a rich set of tools for constructing and >> running tests. This section demonstrates that a small subset of the >> tools suffice to meet the needs of most users." >> >> sourcehttp://docs.python.org/library/unittest.html >> >> As you can see, a much more featured test framework already exists. >> >> There's nothing wrong in anewtest framework, but it has to be better >> than the existing one in some situations. >> > > Chalk and cheese. > > My concern is to make tests easy to write, and that is something that > unittest is, in my view, not good at. It is, as you say, a *test > framework*. > > I've not written a test framework. I've found what seems to be a new > *syntax* for writing tests. Tests written in the new syntax can be > run in the unittest (or any other) framework. > > -- > Jonathan > > Well, I never used unittest, but the given example in the doc is pretty much simple. I'm still scratching my head. JM PS : I think your usage of 'syntax' is inapropriate. From jjposner at optimum.net Thu Aug 5 10:01:59 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 05 Aug 2010 10:01:59 -0400 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: <4C5AC457.6010709@optimum.net> On 8/5/2010 12:33 AM, John Nagle wrote: > There's got to be a better way to do this: > > > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) > Here's a more elegant variant, using regexp lookahead: def thous_format(integer_string): """ add comma thousands separator(s) to an integer-valued string """ return re.sub(r'(\d{3})(?=\d)', r'\1,', integer_string[::-1])[::-1] I *thought* that I had found this on python-list on or about July 5, but I didn't find the thread after a search through the archives. -John From nanothermite911fbibustards at gmail.com Thu Aug 5 10:22:19 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Thu, 5 Aug 2010 07:22:19 -0700 (PDT) Subject: A portable LISP interpreter that includes all the major list-processing functions is described. A complete, annotated listing of the program's code, written in PASCAL, is included. References: <006adcc5-9b71-44d2-91b4-9a82e895aeb1@k19g2000yqc.googlegroups.com> <3616c873-bc13-4bb1-a7d9-fd3357f9f2b1@y32g2000prc.googlegroups.com> Message-ID: <95a6fab2-171f-4b69-a2b3-1494a5929eb1@w30g2000yqw.googlegroups.com> On Jul 24, 3:42?pm, Emmy Noether wrote: > On Jul 23, 9:27?pm, TheFlyingDutchman wrote: > > > > > On Jul 23, 12:06?pm, Emmy Noether wrote: > > > > Title ? PortableLISPinterpreter > > > Creator/Author ?Cox, L.A. Jr. ; Taylor, W.P. > > > Publication Date ? ? ? ?1978 May 31 > > > OSTI Identifier OSTI ID: 7017786 > > > Report Number(s) ? ? ? ?UCRL-52417 > > > DOE Contract Number ? ? W-7405-ENG-48 > > > Resource Type ? Technical Report > > > Research Org ? ?California Univ., Livermore (USA). Lawrence Livermore > > > Lab. > > > Subject 99 GENERAL AND MISCELLANEOUS//MATHEMATICS, COMPUTING, AND > > > INFORMATION SCIENCE; COMPUTER CODES; L CODES; COMPUTERS; PROGRAMMING; > > > PROGRAMMING LANGUAGES > > > Description/Abstract ? ?A portableLISPinterpreter that includes all the > > > major list-processing functions is described. A complete, annotated > > > listing of the program's code, written inPASCAL, is included. > > > Country of Publication ?United States > > > Language ? ? ? ?English > > > Format ?Medium: X; Size: Pages: 21 > > > Availability ? ?Dep. NTIS, PC A02/MF A01. > > > System Entry Date ? ? ? 2008 Feb 12 > > > Is this available online? If only in hardcopy form, do they lend it > > out? > > I am glad to share with everyone. However its useless without the > ability to compile and run. Also with text, its easy to read and > discuss the code which has a listing of 900 lines. > > I have already spent 4 hours scanning/processing to a stage where I > got a decent OCR which needs hand-verification of pages. I need 4 or 8 > volunteers depending on whether one want to do two pages each or 1 > page each. Its an hour of joyful work each for two pages. Explanation > are good quality. We will re-write to C, python etc. > > It must be edited in emacs in fundamental mode to overridepascalmode > indentation. Go topascalmode periodically to colorize to indicate > errors, and then revert before inserting anything. Stay close to the > original page. > > Email me to receive image and initial ocr and lots of fixes I did by > hand for more than 4hrs. Send only plain text message or it goes to > spam. > > Then we share with everyone here or put it on some site. > > E.N. http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1 http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related http://www.youtube.com/watch?v=eVJxzJAU0nE The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From chare at labr.net Thu Aug 5 10:26:14 2010 From: chare at labr.net (Chris Hare) Date: Thu, 05 Aug 2010 09:26:14 -0500 Subject: assigning variables from list data Message-ID: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> I have a database query result (see code below). In PHP, I would have said list(var1,var2,var) = $result and each element in the list would be assigned to each of the named variables. I have my data coming out of the database, and I can see it is a list. so my question is, instead of having to do the variable assignment as I have it here, is there a way more like PHP or am I stuck with it? import sqlite3 as sqlite try: print "connecting to disk db ..." conn = sqlite.connect("netcomm.db") except: print "oops" print "retrieving data" cursor = conn.cursor() cursor.execute('select * from net where NetNumber > 0') list = cursor.fetchone() print list print len(list) for item in list: print item netNumber = list[0] netType = list[1] netConditions = list[2] netStartLocal = list[3] NCS = list[4] NCS1 = list[5] RADAR = list[6] NetFreq = list[7] Repeater = list[8] Notes = list[9] From nanothermite911fbibustards at gmail.com Thu Aug 5 10:26:15 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Thu, 5 Aug 2010 07:26:15 -0700 (PDT) Subject: Fascinating interview by Richard Stallman on Russia TV References: <4db5e9a2-1d00-4b02-b988-17829a537aab@x27g2000yqb.googlegroups.com> <1f6bd9bb-f7c6-4d0c-9936-d51b881da156@s24g2000pri.googlegroups.com> <87iq4dmcsh.fsf@temporary-address.org.uk> <6MOdnZERJ9-Zd9_RnZ2dnUVZ7rSdnZ2d@bt.com> Message-ID: <4a0c24a8-1619-4ca9-93ea-ff6d8d9da1ec@c10g2000yqi.googlegroups.com> On Jul 18, 4:48?am, Richard Heathfield wrote: > Richard Heathfield > Email: -http://www. +rjh@ > "Usenet is a strange place" - dmr 29 July 1999 > Sig line vacant - apply within http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1 http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related http://www.youtube.com/watch?v=eVJxzJAU0nE The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From chris at simplistix.co.uk Thu Aug 5 10:38:27 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 15:38:27 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <1281016052.15056.5.camel@Nokia-N900> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> Message-ID: <4C5ACCE3.3080800@simplistix.co.uk> Kushal Kumaran wrote: > > ----- Original message ----- > > Wolfgang Rohdewald wrote: > > > On Donnerstag 05 August 2010, Chris Withers wrote: > > > > But why only the request for auth credentials? > > > > > > for security reasons I suppose - make sure a human enters > > > the password > > > > Well yes, but what if you actually want to script it? > > > > Then you use expect. > > See http://pexpect.sf.net for a python version. ...which doesn't work on Windows. Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From mail at timgolden.me.uk Thu Aug 5 10:48:53 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Aug 2010 15:48:53 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5ACCE3.3080800@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> Message-ID: <4C5ACF55.4090900@timgolden.me.uk> On 05/08/2010 15:38, Chris Withers wrote: > Kushal Kumaran wrote: >> >> ----- Original message ----- >> > Wolfgang Rohdewald wrote: >> > > On Donnerstag 05 August 2010, Chris Withers wrote: >> > > > But why only the request for auth credentials? >> > > >> > > for security reasons I suppose - make sure a human enters >> > > the password >> > >> > Well yes, but what if you actually want to script it? >> > >> >> Then you use expect. >> >> See http://pexpect.sf.net for a python version. > > ...which doesn't work on Windows. There is a winpexpect: http://pypi.python.org/pypi/winpexpect/1.3 TJG From chris at simplistix.co.uk Thu Aug 5 10:49:53 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 15:49:53 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5ACF55.4090900@timgolden.me.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> <4C5ACF55.4090900@timgolden.me.uk> Message-ID: <4C5ACF91.1050109@simplistix.co.uk> Tim Golden wrote: >>> See http://pexpect.sf.net for a python version. >> >> ...which doesn't work on Windows. > > There is a winpexpect: > > http://pypi.python.org/pypi/winpexpect/1.3 Are the two api-identical? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From benjamin.kaplan at case.edu Thu Aug 5 10:54:50 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 5 Aug 2010 07:54:50 -0700 Subject: assigning variables from list data In-Reply-To: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> References: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> Message-ID: On Thu, Aug 5, 2010 at 7:26 AM, Chris Hare wrote: > > I have a database query result (see code below). ?In PHP, I would have said > > list(var1,var2,var) = $result > > and each element in the list would be assigned to each of the named variables. ?I have my data coming out of the database, and I can see it is a list. ?so my question is, instead of having to do the variable assignment as I have it here, is there a way more like PHP or am I stuck with it? > > import sqlite3 as sqlite > > try: > ? ? ? ?print "connecting to disk db ..." > ? ? ? ?conn = sqlite.connect("netcomm.db") > except: > ? ? ? ?print "oops" > > print "retrieving data" > cursor = conn.cursor() > cursor.execute('select * from net where NetNumber > 0') > list = cursor.fetchone() > print list > print len(list) > for item in list: > ? ?print item > netNumber = list[0] > netType = list[1] > netConditions = list[2] > netStartLocal = list[3] > NCS = list[4] > NCS1 = list[5] > RADAR = list[6] > NetFreq = list[7] > Repeater = list[8] > Notes = list[9] > -- netNumber, netType, netConditions, netStartLocal, NCS, NCS1, RADAR, NetFreq, Repeater, Notes = list by the way, don't call the list "list". It will hide the built-in with the same name. > http://mail.python.org/mailman/listinfo/python-list > From mail at timgolden.me.uk Thu Aug 5 10:55:25 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Aug 2010 15:55:25 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5ACF91.1050109@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> <4C5ACF55.4090900@timgolden.me.uk> <4C5ACF91.1050109@simplistix.co.uk> Message-ID: <4C5AD0DD.4010809@timgolden.me.uk> On 05/08/2010 15:49, Chris Withers wrote: > Tim Golden wrote: >>>> See http://pexpect.sf.net for a python version. >>> >>> ...which doesn't work on Windows. >> >> There is a winpexpect: >> >> http://pypi.python.org/pypi/winpexpect/1.3 > > Are the two api-identical? From the bitbucket page: http://bitbucket.org/geertj/winpexpect/wiki/Home """ The API of winpexpect is identical to that of pexpect. The only difference is that you must use the class "winspawn" instead of "spawn" """ TJG From chris at simplistix.co.uk Thu Aug 5 10:56:20 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 05 Aug 2010 15:56:20 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AD0DD.4010809@timgolden.me.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> <4C5ACF55.4090900@timgolden.me.uk> <4C5ACF91.1050109@simplistix.co.uk> <4C5AD0DD.4010809@timgolden.me.uk> Message-ID: <4C5AD114.1030004@simplistix.co.uk> Tim Golden wrote: > On 05/08/2010 15:49, Chris Withers wrote: >> Tim Golden wrote: >>>>> See http://pexpect.sf.net for a python version. >>>> >>>> ...which doesn't work on Windows. >>> >>> There is a winpexpect: >>> >>> http://pypi.python.org/pypi/winpexpect/1.3 >> >> Are the two api-identical? > > From the bitbucket page: > > http://bitbucket.org/geertj/winpexpect/wiki/Home > > """ > The API of winpexpect is identical to that of pexpect. > The only difference is that you must use the class "winspawn" > instead of "spawn" ...then why aren't they in the same fs&@ing package? ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From mail at timgolden.me.uk Thu Aug 5 10:56:51 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Aug 2010 15:56:51 +0100 Subject: subprocess escaping POpen?! In-Reply-To: <4C5AD114.1030004@simplistix.co.uk> References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> <4C5AB2CE.7040903@simplistix.co.uk> <1281016052.15056.5.camel@Nokia-N900> <4C5ACCE3.3080800@simplistix.co.uk> <4C5ACF55.4090900@timgolden.me.uk> <4C5ACF91.1050109@simplistix.co.uk> <4C5AD0DD.4010809@timgolden.me.uk> <4C5AD114.1030004@simplistix.co.uk> Message-ID: <4C5AD133.6010107@timgolden.me.uk> On 05/08/2010 15:56, Chris Withers wrote: > Tim Golden wrote: >> On 05/08/2010 15:49, Chris Withers wrote: >>> Tim Golden wrote: >>>>>> See http://pexpect.sf.net for a python version. >>>>> >>>>> ...which doesn't work on Windows. >>>> >>>> There is a winpexpect: >>>> >>>> http://pypi.python.org/pypi/winpexpect/1.3 >>> >>> Are the two api-identical? >> >> From the bitbucket page: >> >> http://bitbucket.org/geertj/winpexpect/wiki/Home >> >> """ >> The API of winpexpect is identical to that of pexpect. >> The only difference is that you must use the class "winspawn" >> instead of "spawn" > > ...then why aren't they in the same fs&@ing package? ;-) He does explain there that he hopes to have the changes merged upstream. Presumably it hasn't happened yet... TJG From python.list at tim.thechases.com Thu Aug 5 10:59:16 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 05 Aug 2010 09:59:16 -0500 Subject: assigning variables from list data In-Reply-To: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> References: <6B86E55E-F5C3-4264-AE4C-711DE43C4DE9@labr.net> Message-ID: <4C5AD1C4.6030900@tim.thechases.com> On 08/05/10 09:26, Chris Hare wrote: > I have a database query result (see code below). In PHP, I > would have said > > list(var1,var2,var) = $result > > and each element in the list would be assigned to each of the > named variables. I have my data coming out of the database, > and I can see it is a list. so my question is, instead of > having to do the variable assignment as I have it here, is > there a way more like PHP or am I stuck with it? > > cursor.execute('select * from net where NetNumber> 0') > list = cursor.fetchone() First off, I'd not mask the built-in "list", but you can use row = cursor.fetchone() if row: (netNumber, netType, netCond, netStLo, NCS, NCS1) = row else: print "No results" (just add in the right number of variables to which you want to assign to) -tkc From jonathan.fine1 at googlemail.com Thu Aug 5 11:06:03 2010 From: jonathan.fine1 at googlemail.com (jfine) Date: Thu, 5 Aug 2010 08:06:03 -0700 (PDT) Subject: A new syntax for writing tests References: Message-ID: <8ea4f012-d986-4936-af09-b3e08ee3d9f3@o19g2000yqb.googlegroups.com> On 5 Aug, 14:52, Jean-Michel Pichavant wrote: > jfine wrote: > > On 5 Aug, 10:17, Jean-Michel Pichavant wrote: > > >> Jonathan Fine wrote: > > >>> Hi > > >>> I just discovered today anewsyntaxfor writing tests. ?The basic > >>> idea is to write a function that contains some statements, and run it > >>> via a decorator. ?I wonder if anyone had seen this pattern before, and > >>> how you feel about it. ?For myself, I quite like it. > > >>> Let's suppose we want to test this trivial (of course) class. > >>> ? ? class Adder(object): > > >>> ? ? ? ? def __init__(self): > >>> ? ? ? ? ? ? self.value = 0 > > >>> ? ? ? ? def plus(self, delta): > >>> ? ? ? ? ? ? self.value += delta > > >>> The test the class you need a runner. ?In this case it is quite simple. > > >>> ? ? def runner(script, expect): > >>> ? ? ? ? '''Create an adder, run script, expect value.''' > > >>> ? ? ? ? adder = Adder() > >>> ? ? ? ? script(adder) > >>> ? ? ? ? return adder.value > > >>> We can now create (and run if we wish) a test. ?To do this we write > > >>> ? ? @testit(runner, 4) > >>> ? ? def whatever(a): > >>> ? ? ? ? '''Two plus two is four.''' > > >>> ? ? ? ? a.plus(2) > >>> ? ? ? ? a.plus(2) > > >>> Depending on the exact value of the testit decorator (which in the end > >>> is up to you) we can store the test, or execute it immediately, or do > >>> something else. > > >>> The simplest implementation prints: > >>> ? ? OK: Two plus two is four. > >>> for this passing test, and > >>> ? ? Fail: Two plus four is five. > >>> ? ? ? expect 5 > >>> ? ? ? actual 6 > >>> for a test that fails. > > >>> Here is the testit decorator used to produce the above output: > > >>> ? ? def testit(runner, expect): > >>> ? ? ? ? '''Test statements decorator.''' > > >>> ? ? ? ? def next(script): > >>> ? ? ? ? ? ? actual = runner(script, expect) > >>> ? ? ? ? ? ? if actual == expect: > >>> ? ? ? ? ? ? ? ? print 'OK:', script.__doc__ > >>> ? ? ? ? ? ? else: > >>> ? ? ? ? ? ? ? ? print 'Fail:', script.__doc__ > >>> ? ? ? ? ? ? ? ? print ' ?expect', expect > >>> ? ? ? ? ? ? ? ? print ' ?actual', actual > > >>> ? ? ? ? return next > > >>> You can pick this code, for at least the next 30 days, at > >>> ? ?http://dpaste.com/hold/225056/ > > >>> For me the key benefit is that writing the test is really easy. ? > >>> Here's a test I wrote earlier today. > > >>> @testit(runner, '''''') > >>> def whatever(tb): > >>> ? ? tb.start('a', {'att': 'value'}) > >>> ? ? tb.start('b') > >>> ? ? tb.end('b') > >>> ? ? tb.end('a') > > >>> If the test has a set-up and tear-down, this can be handled in the > >>> runner, as can the test script raising an expected or unexpected > >>> exception. > > >> Hi, > > >> "The unittest module provides a rich set of tools for constructing and > >> running tests. This section demonstrates that a small subset of the > >> tools suffice to meet the needs of most users." > > >> sourcehttp://docs.python.org/library/unittest.html > > >> As you can see, a much more featured test framework already exists. > > >> There's nothing wrong in anewtest framework, but it has to be better > >> than the existing one in some situations. > > > Chalk and cheese. > > > My concern is to make tests easy to write, and that is something that > > unittest is, in my view, not good at. ?It is, as you say, a *test > > framework*. > > > I've not written a test framework. ?I've found what seems to be anew > > *syntax* for writing tests. ?Tests written in thenewsyntaxcan be > > run in the unittest (or any other) framework. > > > -- > > Jonathan > > Well, I never used unittest, but the given example in the doc is pretty > much simple. > I'm still scratching my head. I think you'd understand better if you used unittest. For example, try coding my test (with say 10 distinct tests of a class more complicated than Adder) using unittest. I think you'll see the point when you get to number 5. Here, for reference, is my complete code for one test. See how it scales. http://dpaste.com/hold/225056/ (available for at least 30 days). -- Jonathan From pfinane at gmail.com Thu Aug 5 11:07:13 2010 From: pfinane at gmail.com (hrdublin) Date: Thu, 5 Aug 2010 08:07:13 -0700 (PDT) Subject: Are you Searching for a New IT or Telecoms Job? Message-ID: <664cd08f-1de3-4d33-bcd9-c4aacce14f8a@t20g2000yqa.googlegroups.com> Then start your Search here at JobPIMP JobPIMP is a Customised Search Engine that is crawling over 800+ Local and International Job Boards so you don't have to. JobPIMP is searching well known mainstream, niche, and less well known specialist job portals (your search results on one page). Click Link and Try JobPIMP Today http://www.directsource-network.com/jobpimphome.html It is 100% FREE!!! Or do a Google Search for "jobpimp" Find Us on Facebook http://www.facebook.com/DSN.ExpatJobs From none at none.com Thu Aug 5 11:15:48 2010 From: none at none.com (Brandon McCombs) Date: Thu, 05 Aug 2010 11:15:48 -0400 Subject: new to python - trouble calling a function from another function In-Reply-To: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> References: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> Message-ID: Jon Clements wrote: > On 5 Aug, 08:25, Brandon McCombs wrote: >> Hello, >> >> I'm building an elevator simulator for a class assignment. I recently >> ran into a roadblock and don't know how to fix it. For some reason, in >> my checkQueue function below, the call to self.goUp() is never executed. >> It is on the last line of code I pasted in. I can put print statements >> before and after the call and I have a print statement in goUp() itself. >> Only the print statements before and after the call are executed. The >> one inside goUp() is never executed because goUp() never seems to be >> executed. How can that be? I don't get any errors when the script >> executes. Surely this isn't some limitation I'm encountering? >> >> thanks >> >> sorry about the formatting >> >> --------------------------------------------- >> class Elevator(Process): >> def __init__(self,name): >> Process.__init__(self,name=name) >> self.numPassengers = 0 >> self.passengerList = [] >> self.passengerWaitQ = [] >> self.currentFloor = 1 >> self.idle = 1 >> self.newPassengers = 0 >> def goUp(self): >> print "here" >> bubbleSort(self.passengerList, len(self.passengerList)) >> self.currentFloor += 1 >> if len(self.passengerList) > 0: >> for p in self.passengerList: >> if self.currentFloor == p.destination: >> yield (p.destination - self.currenteFloor) * TRAVELTIME, self >> reactivate(p) >> p.inBuilding() >> else: >> self.goUp() >> >> def checkQueue(self): >> if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < >> MAXCAPACITY: >> if len(self.passengerWaitQ) < MAXCAPACITY: >> self.newPassengers = len(self.passengerWaitQ) >> else: >> self.newPassengers = MAXCAPACITY - len(self.passengerList) >> for i in range(0,self.newPassengers): >> self.passengerList.append(self.passengerWaitQ.pop()) >> self.goUp() > > Hi Brandon, > > Nice one at having a good crack at coding before posting! > > From your posted code, I'm struggling to see what's trying to be > taught to you for this class assignment. not relevant at this point > > As a note it'll be worth reading PEP 8 regarding naming conventions, > because it looks very Java-ish to me! ok but not relevant > > (I might be taking too much a real-world approach in the following, > but do with it as you will...) > > I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere. > Although what I'm thinking is that different Elevators will have > different capacities and different floors they service. An Elevator is > *not* going to know its number of passengers (the most it could do is > capacity based on weight restrictions) therefore it's not going to > know the number of new passengers on each floor either. okay but not relevant to the problem at hand > > A couple of things that'd be worthwhile: > > 1) Post the requirements for your assignment - what's it supposed to > output etc... that isn't relevant for determining at the python level why a function simply isn't being called > 2) Go find an elevator, take a pen and pad with you, and stand in it > for 30 mins or so, and see how the real thing deals with situations > and make notes. ie, does it queue requests, or decide to take the next > nearest floor, when does it stop and open etc...? > > hth > > Jon. > actually it doesn't help at all since you decided to focus on everything but my actual question of why a function call wasn't working but rather question the validity of the program itself From none at none.com Thu Aug 5 11:20:22 2010 From: none at none.com (Brandon McCombs) Date: Thu, 05 Aug 2010 11:20:22 -0400 Subject: new to python - trouble calling a function from another function In-Reply-To: <6pgqi7-unn.ln1@satorlaser.homedns.org> References: <6pgqi7-unn.ln1@satorlaser.homedns.org> Message-ID: Ulrich Eckhardt wrote: > Brandon McCombs wrote: >> I'm building an elevator simulator for a class assignment. I recently >> ran into a roadblock and don't know how to fix it. For some reason, in >> my checkQueue function below, the call to self.goUp() is never executed. > [...] >> sorry about the formatting > > While I can certainly forgive you the formatting (my problem is rather that > you didn't reduce the code to the smallest possible example so I missed a few lines, so sue me. ), Python wont. > Python is a language where whitespace is significant and can subtly change > the meaning of your code. > > Example: > >> for i in range(0,self.newPassengers): >> self.passengerList.append(self.passengerWaitQ.pop()) >> self.goUp() > > The formatting here is completely removed, but there are two conceivable > ways this could be formatted: already aware. I reformatted tabs to reduce the line wrap so it was easier for readers to read it. > > # variant 1 > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() > > #variant 2 > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() either one of those should still execute self.goUp(). I'm not getting anything though no matter where I place the function call. > > Someone already mentioned PEP 8 (search the web!). These PEPs could be > called the standards governing Python behaviour, and PEP 8 actually defines > several things concerning the formatting of sourcecode. Apply it unless you > have a good reason not to. > > > Further, you should run Python with "-t" as argument on the commandline. > This will give you warnings when it encounters inconsistent tab/spaces > usage. This can make a difference. Yeah I already tried that using 'tabnanny' I think it was called to diagnose one function that I decided to create and the -t option gave me false information. I determined that I had a tab in front of the function name (just like many others) however the actual fix was to put in spaces until it lined up with all the other 'def' lines. > > Example: > > #variant 3 > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() > > If your editor is set to four spaces per tab, this will look like variant 2, > with 8 spaces it will look like variant 1. I don't know (and don't care, > since PEP-8 mandates four spaces) which interpretation Python actually > uses. > > > Lastly, you can simplify your check_queue() function. First, determine the > number of free places inside the elevator. Then, you simply append that > many passengers from the waiting list to the passenger list: > > free = MAX_CAPACITY - len(self.passengers) > new_passengers = self.passenger_wait_queue[:free] > self.passenger_wait_queue = self.passenger_wait_queue[free:] > self.passengers += new_passengers > > This uses the fact that list indices are automatically truncated to a valid > range, so requesting the elements 0 to 10 from a 5-element list will only > yield those five elements, not raise an exception. It's up to you though > which version is clearer to you. I would perhaps bail out if "free == 0" > and then also not call go_up() lateron. > > so you made other recommendations but didn't address my original question unless I missed it somewhere. From eldiener at tropicsoft.invalid Thu Aug 5 11:31:08 2010 From: eldiener at tropicsoft.invalid (Edward Diener) Date: Thu, 05 Aug 2010 11:31:08 -0400 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On 8/2/2010 5:42 PM, Mark Lawrence wrote: > On 02/08/2010 00:08, candide wrote: >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. >> >> Has it ever been planned to rewrite in C++ the historical implementation >> (of course in an object oriented design) ? > > I can't understand why any serious programmer mentions C++. As soon as I > read it, I have to rush either to the kitchen to find a bowl to throw up > in, or head for the toilet so I can talk to the great white telephone. It must be because we can not be as phenomenally intelligent as you evidently are from your comment. From tgrav at me.com Thu Aug 5 11:40:07 2010 From: tgrav at me.com (Tommy Grav) Date: Thu, 05 Aug 2010 11:40:07 -0400 Subject: new to python - trouble calling a function from another function In-Reply-To: References: <6pgqi7-unn.ln1@satorlaser.homedns.org> Message-ID: On Aug 5, 2010, at 11:20 AM, Brandon McCombs wrote: > so I missed a few lines, so sue me. The problem is that when you don't post a self contained example there is no proper way to answer your question, since the problem could be outside the part you posted. > already aware. I reformatted tabs to reduce the line wrap so it was easier for readers to read it. Never format code after you copy-paste it to your browser. This may change the behavior of your example making it impossible for people to help you. > either one of those should still execute self.goUp(). I'm not getting anything though no matter where I place the function call. Like someone said before. Try to create the smallest subset of your code that shows this behavior and copy-paste it to the list and people will try to help. Right now there is no clear answer from what you posted. Tommy From wherespythonmonks at gmail.com Thu Aug 5 11:42:06 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 5 Aug 2010 11:42:06 -0400 Subject: easy question on parsing python: "is not None" Message-ID: How does "x is not None" make any sense? "not x is None" does make sense. I can only surmise that in this context (preceding is) "not" is not a unary right-associative operator, therefore: x is not None === IS_NOTEQ(X, None) Beside "not in" which seems to work similarly, is there other syntactical sugar like this that I should be aware of? W From neilc at norwich.edu Thu Aug 5 11:42:48 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 5 Aug 2010 15:42:48 GMT Subject: new to python - trouble calling a function from another function References: Message-ID: <8c04foFkkuU1@mid.individual.net> On 2010-08-05, Brandon McCombs wrote: > class Elevator(Process): > def __init__(self,name): > Process.__init__(self,name=name) > self.numPassengers = 0 > self.passengerList = [] > self.passengerWaitQ = [] > self.currentFloor = 1 > self.idle = 1 > self.newPassengers = 0 > def goUp(self): > print "here" > bubbleSort(self.passengerList, len(self.passengerList)) > self.currentFloor += 1 > if len(self.passengerList) > 0: > for p in self.passengerList: > if self.currentFloor == p.destination: > yield (p.destination - self.currenteFloor) * TRAVELTIME, self > reactivate(p) > p.inBuilding() > else: > self.goUp() > > def checkQueue(self): > if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < > MAXCAPACITY: > if len(self.passengerWaitQ) < MAXCAPACITY: > self.newPassengers = len(self.passengerWaitQ) > else: > self.newPassengers = MAXCAPACITY - len(self.passengerList) > for i in range(0,self.newPassengers): > self.passengerList.append(self.passengerWaitQ.pop()) > self.goUp() Does your program call checkQueue? -- Neil Cerutti From downaold at gmail.com Thu Aug 5 11:56:37 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 5 Aug 2010 17:56:37 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: > How does "x is not None" make any sense? "not x is None" does make > sense. > > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator, therefore: > > x is not None === IS_NOTEQ(X, None) > > Beside "not in" which seems to work similarly, is there other > syntactical sugar like this that I should be aware of? 'not None' first casts None to a bool, and then applies 'not', so 'x is not None' means 'x is True'. 'not x is None' is the same as 'not (x is None)' Cheers, Roald From jeanmichel at sequans.com Thu Aug 5 11:58:54 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 05 Aug 2010 17:58:54 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: <4C5ADFBE.5090308@sequans.com> wheres pythonmonks wrote: > How does "x is not None" make any sense? "not x is None" does make sense. > > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator, therefore: > > x is not None === IS_NOTEQ(X, None) > > Beside "not in" which seems to work similarly, is there other > syntactical sugar like this that I should be aware of? > > W > x is not None === not (x is None). "is not" is an operator, not the combination of 2. JM From ben+python at benfinney.id.au Thu Aug 5 11:59:01 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 06 Aug 2010 01:59:01 +1000 Subject: easy question on parsing python: "is not None" References: Message-ID: <87sk2t1262.fsf@benfinney.id.au> wheres pythonmonks writes: > How does "x is not None" make any sense? In two ways: partly from the fact that Python syntax is preferentially designed to be reasonably readable to a native English reader; and partly because it makes for more obvious semantics. ?is not? is a single operator which makes operator precedence clear, and also ?x is not None? is gramatically good English. > "not x is None" does make sense. It unfortunately makes for awkward English, and it also makes for two separate operators and hence non-obvious operator precedence. > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator Rather than surmise, you can read the language reference which makes clear that ?is not? is one operator. -- \ ?I am amazed, O Wall, that you have not collapsed and fallen, | `\ since you must bear the tedious stupidities of so many | _o__) scrawlers.? ?anonymous graffiti, Pompeii, 79 CE | Ben Finney From wherespythonmonks at gmail.com Thu Aug 5 12:07:53 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 5 Aug 2010 12:07:53 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: Well, I am not convinced of the equivalence of not None and true: >>> not None True >>> 3 is True; False >>> 3 is not None True >>> P.S. Sorry for the top-post -- is there a way to not do top posts from gmail? I haven't used usenet since tin. On Thu, Aug 5, 2010 at 11:56 AM, Roald de Vries wrote: > On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: >> >> How does "x is not None" make any sense? ?"not x is None" does make sense. >> >> I can only surmise that in this context (preceding is) "not" is not a >> unary right-associative operator, therefore: >> >> x is not None === IS_NOTEQ(X, None) >> >> Beside "not in" which seems to work similarly, is there other >> syntactical sugar like this that I should be aware of? > > 'not None' first casts None to a bool, and then applies 'not', so 'x is not > None' means 'x is True'. > 'not x is None' is the same as 'not (x is None)' > > Cheers, Roald > -- > http://mail.python.org/mailman/listinfo/python-list > From carey.tilden at gmail.com Thu Aug 5 12:10:53 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Thu, 5 Aug 2010 09:10:53 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 8:42 AM, wheres pythonmonks wrote: > How does "x is not None" make any sense? ?"not x is None" does make sense. > > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator, therefore: > > x is not None === IS_NOTEQ(X, None) > > Beside "not in" which seems to work similarly, is there other > syntactical sugar like this that I should be aware of? In addition to all the other fine responses, you also might want to take a look at the python grammar [1]. The relevant line is: comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' Cheers, Carey [1] http://docs.python.org/reference/grammar.html From clp2 at rebertia.com Thu Aug 5 12:11:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 5 Aug 2010 09:11:59 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Thu, Aug 5, 2010 at 8:56 AM, Roald de Vries wrote: > On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: >> How does "x is not None" make any sense? ?"not x is None" does make sense. >> >> I can only surmise that in this context (preceding is) "not" is not a >> unary right-associative operator, therefore: >> >> x is not None === IS_NOTEQ(X, None) >> >> Beside "not in" which seems to work similarly, is there other >> syntactical sugar like this that I should be aware of? > > 'not None' first casts None to a bool, and then applies 'not', so 'x is not > None' means 'x is True'. Absolutely incorrect. Read the final paragraph of http://docs.python.org/reference/expressions.html#notin Cheers, Chris -- http://blog.rebertia.com From a.pfrengle at gmail.com Thu Aug 5 12:18:49 2010 From: a.pfrengle at gmail.com (Andreas Pfrengle) Date: Thu, 5 Aug 2010 09:18:49 -0700 (PDT) Subject: simple integer subclass References: <8d5e3b7c-9605-4af4-a9fb-5f17dd771404@w12g2000yqj.googlegroups.com> <0ed61075-ae73-445a-8e86-56123734f629@i28g2000yqa.googlegroups.com> <4C5A893C.6060807@sschwarzer.net> Message-ID: <7e8d94eb-7313-4f31-84b5-95874602697c@q22g2000yqm.googlegroups.com> Hello everyone, thanks for all the suggestions. I did effort to redesign parts of the data structure the last days, but not all (only those I could easily keep track of in my code). For the rest I add +1 before the presentation and comment it. Seems the easiest way now. Andreas From nikos.the.gr33k at gmail.com Thu Aug 5 12:31:18 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Thu, 5 Aug 2010 09:31:18 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format References: Message-ID: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> On 5 ???, 11:55, Dennis Lee Bieber wrote: > On Wed, 4 Aug 2010 16:40:45 -0700 (PDT), ????? > declaimed the following in > gmane.comp.python.general: > > > ? ? ? ? ? ? ? ? ? ?for entry in row: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ?entry = datetime.datetime.strftime( entry, '%d %b, %H:%M' ) #!!! > > this is wrong! > > ? ? ? ? ? ? ? ? ? ? ? ? ? ?print ( ''' ''' % entry ) > > > Apart from that i don't know how iam supposed to print it, because the > > date string is the 3rd string in every row of the dataset. > > ? ? ? ? As you state, it is the third item in each returned row... So why > are you trying to treat EVERY item in the row as a date? Because when i try to prin the 3 items liek that print row[0], row[1], row[2] it gives me an error, so i dont knwo how to tell it how to print the 3rd item differently. > > ? ? ? ? Since MySQLdb appears to return datetime objects (my quick test is > showing datetime.date for dates in a test database) you should be > probably be using > > ? ? ? ? formatted_entry = entry.strftime("%d... %M") I tried that myself yesterday but look it fails to the following message /home/webville/public_html/cgi-bin/index.py 63 64 for entry in row: 65 formatted_entry = entry.strftime('%d %b, %H:%M') 66 print ( ''' ''' % entry ) 67 formatted_entry undefined, entry = '178-124-186.dynamic.cyta.gr', entry.strftime undefined AttributeError: 'str' object has no attribute 'strftime' args = ("'str' object has no attribute 'strftime'",) From daniel.eliason at excite.com Thu Aug 5 12:31:30 2010 From: daniel.eliason at excite.com (fortunatus) Date: Thu, 5 Aug 2010 09:31:30 -0700 (PDT) Subject: A portable LISP interpreter that includes all the major list-processing functions is described. A complete, annotated listing of the program's code, written in PASCAL, is included. References: <006adcc5-9b71-44d2-91b4-9a82e895aeb1@k19g2000yqc.googlegroups.com> <3616c873-bc13-4bb1-a7d9-fd3357f9f2b1@y32g2000prc.googlegroups.com> Message-ID: On Jul 24, 6:42?pm, Emmy Noether wrote: > I have already spent 4 hours scanning/processing to a stage where I > got a decent OCR which needs hand-verification of pages. I need 4 or 8 > volunteers depending on whether one want to do two pages each or 1 > page each. Its an hour of joyful work each for two pages. Sheesh, if you just focussed on typing in, you could be done by now instead of fooling around with OCR and enlisting volunteers for something that amounts to the same beginner experiment that has been done 10,000 times: a fundamental Lisp interpreter. Don't get me wrong, it's a good experiment, but it really needn't require so much trouble... For that matter, why not write your own? Start by replicating McCarthy's group's initial interpreter... From clp2 at rebertia.com Thu Aug 5 12:32:47 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 5 Aug 2010 09:32:47 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 8:42 AM, wheres pythonmonks wrote: > How does "x is not None" make any sense? ?"not x is None" does make sense. > > I can only surmise that in this context (preceding is) "not" is not a > unary right-associative operator, therefore: > > x is not None === IS_NOTEQ(X, None) > > Beside "not in" which seems to work similarly, is there other > syntactical sugar like this that I should be aware of? It's not quite the same type of sugar as that, but people sometimes forget that comparisons can be chained: if x < y <= z: Same as: if x < y and y <= z: # but y is only evaluated once Cheers, Chris From downaold at gmail.com Thu Aug 5 12:35:53 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 5 Aug 2010 18:35:53 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Aug 5, 2010, at 6:11 PM, Chris Rebert wrote: > On Thu, Aug 5, 2010 at 8:56 AM, Roald de Vries > wrote: >> On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: >>> How does "x is not None" make any sense? "not x is None" does >>> make sense. >>> >>> I can only surmise that in this context (preceding is) "not" is >>> not a >>> unary right-associative operator, therefore: >>> >>> x is not None === IS_NOTEQ(X, None) >>> >>> Beside "not in" which seems to work similarly, is there other >>> syntactical sugar like this that I should be aware of? >> >> 'not None' first casts None to a bool, and then applies 'not', so >> 'x is not >> None' means 'x is True'. > > Absolutely incorrect. Read the final paragraph of > http://docs.python.org/reference/expressions.html#notin Oops, sorry :$. From python at mrabarnett.plus.com Thu Aug 5 12:36:50 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 05 Aug 2010 17:36:50 +0100 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: <4C5AC457.6010709@optimum.net> References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <4C5AC457.6010709@optimum.net> Message-ID: <4C5AE8A2.1010902@mrabarnett.plus.com> John Posner wrote: > On 8/5/2010 12:33 AM, John Nagle wrote: >> There's got to be a better way to do this: >> >> >> def editmoney(n) : >> return((",".join(reduce(lambda lst, item : (lst + [item]) if >> item else lst, >> re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) >> > > Here's a more elegant variant, using regexp lookahead: > > def thous_format(integer_string): > """ > add comma thousands separator(s) to an integer-valued string > """ > return re.sub(r'(\d{3})(?=\d)', r'\1,', integer_string[::-1])[::-1] > > I *thought* that I had found this on python-list on or about July 5, but > I didn't find the thread after a search through the archives. > You don't need to reverse the string: def thous_format(integer_string): """ add comma thousands separator(s) to an integer-valued string """ return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string) From davea at ieee.org Thu Aug 5 13:03:41 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 05 Aug 2010 13:03:41 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <4C5AEEED.40409@ieee.org> Roald de Vries wrote: >
On Aug 5, > 2010, at 5:42 PM, wheres pythonmonks wrote: >> How does "x is not None" make any sense? "not x is None" does make >> sense. >> >> I can only surmise that in this context (preceding is) "not" is not a >> unary right-associative operator, therefore: >> >> x is not None === IS_NOTEQ(X, None) >> >> Beside "not in" which seems to work similarly, is there other >> syntactical sugar like this that I should be aware of? > > 'not None' first casts None to a bool, and then applies 'not', so 'x > is not None' means 'x is True'. > 'not x is None' is the same as 'not (x is None)' > > Cheers, Roald > Did you try it? Python 2.6.4 (r264:75706, Jan 22 2010, 16:41:54) [MSC v.1500 32 bit win32 Type "help", "copyright", "credits" or "license" for more informatio >>> 4 is not None True >>> True is not None True >>> False is not None True >>> None is not None False >>> Looks to me like x is not None is equivalent to not (x is None) (I get same results for 3.1) DaveA From ethan at stoneleaf.us Thu Aug 5 13:09:04 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 05 Aug 2010 10:09:04 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <4C5AF030.8000408@stoneleaf.us> Roald de Vries wrote: > On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: >> How does "x is not None" make any sense? "not x is None" does make >> sense. >> >> I can only surmise that in this context (preceding is) "not" is not a >> unary right-associative operator, therefore: >> >> x is not None === IS_NOTEQ(X, None) >> >> Beside "not in" which seems to work similarly, is there other >> syntactical sugar like this that I should be aware of? > > 'not None' first casts None to a bool, and then applies 'not', so 'x is > not None' means 'x is True'. This is not correct. 'is not' is a single operator, and in this case is checking that the object 'x' is not the same as the object 'None'. No boolean conversions are done -- False and True have nothing to do with this example. Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. --> x = 5 --> x is not None True --> x = True --> x is not None True --> x = ('this','is','a','tuple') --> x is not None True --> x = None --> x is not None False ~Ethan~ From landa.martin at gmail.com Thu Aug 5 13:50:21 2010 From: landa.martin at gmail.com (Martin Landa) Date: Thu, 5 Aug 2010 10:50:21 -0700 (PDT) Subject: ctypes: pointer to method Message-ID: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Hi, is it possible to pass pointer to a method using ctypes. Sample code: ... G_set_error_routine(byref(self._print_error)) ... def _print_error(self, msg, type): """!Redirect stderr""" self.log.write(msg) gives me G_set_error_routine(byref(self._print_error)) TypeError: byref() argument must be a ctypes instance, not 'instancemethod' C function G_set_error_routine is defined as void G_set_error_routine(int (*error_routine) (const char *, int)) Thanks in advance for any pointers. Martin From urban.dani at gmail.com Thu Aug 5 14:01:37 2010 From: urban.dani at gmail.com (Daniel Urban) Date: Thu, 5 Aug 2010 20:01:37 +0200 Subject: new to python - trouble calling a function from another function In-Reply-To: References: Message-ID: > I'm building an elevator simulator for a class assignment. I recently ran > into a roadblock and don't know how to fix it. For some reason, in my > checkQueue function below, the call to self.goUp() is never executed. It is > on the last line of code I pasted in. I can put print statements before and > after the call and I have a print statement in goUp() itself. ?Only the > print statements before and after the call are executed. The one inside > goUp() is never executed because goUp() never seems to be executed. How can > that be? I don't get any errors when the script executes. Surely this isn't > some limitation I'm encountering? I think the self.goUp() call is executed, the goUp function gets called, returns a generator object (because goUp is a generator function), then you don't use that generator object for anything. Daniel From no.email at nospam.invalid Thu Aug 5 14:10:04 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Thu, 05 Aug 2010 11:10:04 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xocdi56cp.fsf@ruckus.brouhaha.com> Message-ID: <7xmxt1kk1v.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > OK, I have a copy of K&R 2nd Ed on a shelf within reach here. Can you point > out some behaviour that C programmers might need to rely on, that is not > specified in that document? C has all kinds of undefined behavior. "Might need to rely on" is not relevant for this kind of issue. Ada's designers had the goal that that Ada programs should have NO undefined behavior. As a famous example of C's underspecification, the behavior of a[i++] = i; is undefined in C99. See: https://www.securecoding.cert.org/confluence/display/seccode/EXP30-C.+Do+not+depend+on+order+of+evaluation+between+sequence+points From andresen.nils at googlemail.com Thu Aug 5 14:26:52 2010 From: andresen.nils at googlemail.com (Nils) Date: Thu, 5 Aug 2010 11:26:52 -0700 (PDT) Subject: pre-uninstall script in bdist_wininst Message-ID: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> Hi. I am using a postinstall-script like this: setup( ... scripts=['scripts\install.py'], options = { ... "bdist_wininst" : { "install_script" : "install.py", ... }, } ) According to the docs in [1] this script is a) called after install (with the "-install" parameter) - this works fine for me... b) called before uninstall (with tho "-remove" parameter) - this however does not work. Can someone please point me to the direction on how to get a pre- uninstall script working? btw: With that I am trying to register a com-server on install and de- register on uninstall - so if other ideas are around I'd love to hear them, too... Nils From andresen.nils at googlemail.com Thu Aug 5 14:31:31 2010 From: andresen.nils at googlemail.com (Nils) Date: Thu, 5 Aug 2010 11:31:31 -0700 (PDT) Subject: pre-uninstall script in bdist_wininst References: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> Message-ID: On 5 Aug., 20:26, Nils wrote: > According to the docs in [1] [...] and with [1] I meant http://docs.python.org/distutils/builtdist.html#the-postinstallation-script Nils From jjposner at optimum.net Thu Aug 5 14:31:40 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 05 Aug 2010 14:31:40 -0400 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <4C5AC457.6010709@optimum.net> Message-ID: <4C5B038C.8000208@optimum.net> On 8/5/2010 12:36 PM, MRAB wrote: > You don't need to reverse the string: > > def thous_format(integer_string): > """ > add comma thousands separator(s) to an integer-valued string > """ > return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string) Nice! My first encounter with a look-behind! It appears that a slight simplification is possible: return re.sub(r"(?<=\d)(?=(\d\d\d)+$)", ",", integer_string) There no harm in putting \d\d\d into a group, though the group is never used. -John From jjposner at optimum.net Thu Aug 5 14:31:40 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 05 Aug 2010 14:31:40 -0400 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <4C5AC457.6010709@optimum.net> Message-ID: <4C5B038C.8000208@optimum.net> On 8/5/2010 12:36 PM, MRAB wrote: > You don't need to reverse the string: > > def thous_format(integer_string): > """ > add comma thousands separator(s) to an integer-valued string > """ > return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string) Nice! My first encounter with a look-behind! It appears that a slight simplification is possible: return re.sub(r"(?<=\d)(?=(\d\d\d)+$)", ",", integer_string) There no harm in putting \d\d\d into a group, though the group is never used. -John From nikos.the.gr33k at gmail.com Thu Aug 5 14:52:58 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Thu, 5 Aug 2010 11:52:58 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> Message-ID: <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> Hey i made it! :-) dataset = cursor.fetchall() for row in dataset: print ( '''
''' ) date = row[2].strftime( '%d %b, %H:%M' ) print ( ''' ''' % ( row[0], row[1], date ) ) Unfortunately had to ditch the 'for entry in row' line because couldn't iterate over the items of the row. Could you please shoe me how could i do the same thing with iteration?! Thanks! From python.list at tim.thechases.com Thu Aug 5 15:09:52 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 05 Aug 2010 14:09:52 -0500 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> Message-ID: <4C5B0C80.6080406@tim.thechases.com> On 08/05/10 13:52, ????? wrote: > dataset = cursor.fetchall() > > for row in dataset: > print ( ''' ''' ) > > date = row[2].strftime( '%d %b, %H:%M' ) > > print ( ''' ''' % > ( row[0], row[1], date ) ) > > Unfortunately had to ditch the 'for entry in row' line because > couldn't iterate over the items of the row. > > Could you please shoe me how could i do the same thing with > iteration?! Well, depending on whether "row" is a tuple or a list, you can do either row[2] = row[2].strftime(...) # if it's a list # the assignment will fail if it's a tuple or you can just iterate over a predefined list/tuple: for row in dataset: print ("") for item in (row[0], row[1], row[2].strftime(...)): print ("") for item in (host, hits, dt.strftime(...)): print ("" % item) print ("") Or perhaps even just print ("".join("" % item for item in (host, hits, dt.strftime(...)) ) Whichever you prefer. I think I'm partial to the 2nd-from-last version, especially as the list of fields may grow. -tkc From nobody at nowhere.com Thu Aug 5 15:19:42 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 05 Aug 2010 20:19:42 +0100 Subject: subprocess escaping POpen?! References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> Message-ID: On Thu, 05 Aug 2010 12:23:35 +0100, Chris Withers wrote: >>> ...then the output is indeed captured. So, what is svn doing >>> differently? How is it escaping its jail? >> >> maybe it does not read from stdin but directly from /dev/tty > > But why only the request for auth credentials? So that you can do e.g.: ssh remotehost command arg arg ... outfile From nobody at nowhere.com Thu Aug 5 15:32:25 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 05 Aug 2010 20:32:25 +0100 Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Message-ID: On Thu, 05 Aug 2010 10:50:21 -0700, Martin Landa wrote: > is it possible to pass pointer to a method using ctypes. I don't know about methods, but it works for functions. > Sample code: > > ... > G_set_error_routine(byref(self._print_error)) This won't work; you have to be more explicit, e.g.: errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int)) errfunc = errtype(print_error) G_set_error_routine(errfunc) NOTE: be sure to keep a reference to the wrapper, as ctypes doesn't hold references itself. IOW, you can't replace the above with: errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int)) G_set_error_routine(errtype(print_error)) If you do this, the wrapper is eligible for garbage collection as soon as G_set_error_routine() returns, and will probably have vanished by the time that G_fatal_error() gets called. For more information see: http://docs.python.org/library/ctypes.html#callback-functions From britt.snodgrass at gmail.com Thu Aug 5 16:35:01 2010 From: britt.snodgrass at gmail.com (Britt) Date: Thu, 5 Aug 2010 13:35:01 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: On Aug 1, 9:34?pm, Albert Hopkins wrote: > On Mon, 2010-08-02 at 01:08 +0200, candide wrote: > > I would propose that in fact most programming languages are implemented > in C. ?Sun's (Oracle's) Java compiler and runtime are written in ANSI C. > The core of the Gnu Compiler Collection (which includes C++ and > Objective-C compilers) is written in C. The open-source GCC Ada compiler (GNAT) is written in Ada. The GPL'd compiler source code is available at http://libre.adacore.com/libre/ From nikos.the.gr33k at gmail.com Thu Aug 5 17:01:28 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Thu, 5 Aug 2010 14:01:28 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> Message-ID: >On 5 ???, 22:09, Tim Chase wrote: > On 08/05/10 13:52, ????? wrote: > > > dataset = cursor.fetchall() > > > for row in dataset: > > ? ? ?print ( ''' ?''' ) As i have it the returned 'dataset' is stored line per line to 'row'. So, 'dataset' in here is a 'list of tuples' right? and 'row' in here is a tuple form the above list of tuples right? Am i understanding this correctly?! > Well, depending on whether "row" is a tuple or a list, you can do > either It was a tuple. But it migth as well be a list too?!?! Could 'dataset' be a 'list of lists' as well? How one would know in which way the returned mysql data is saved in? > Though I think I'd make it a bit clearer by naming the fields: > > ? ?for host, hits, dt in dataset: > ? ? ?print ("") > ? ? ?for item in (host, hits, dt.strftime(...)): > ? ? ? ?print ("" % item) > ? ? ?print ("") Cool! I myself like this solution best over the all working other! very nice approach thank you very much! Is what i anted and couldn't write myself! But please tell me if in my example 'row' was a tuple, what kind of objects is 'host', 'hits', 'dt' here and how do they sore the data? Thanks again for the cool examples! From __peter__ at web.de Thu Aug 5 17:13:10 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Aug 2010 23:13:10 +0200 Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <4c5a7682$0$11096$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Thu, 05 Aug 2010 00:22:57 -0700, geremy condra wrote: > >>>>>> locale.setlocale(locale.LC_ALL, "") >>> 'de_DE.UTF-8' >>>>>> print locale.currency(13535, grouping=True) >>> 13.535,00 ? >>>>>> print locale.format("%d", 13535, grouping=True) >>> 13.535 >>> >>> Peter >> >> I had literally no idea this existed. Thanks. > > I knew it existed, but completely forgot about it. > > Thanks also Peter. You're welcome! From cs at zip.com.au Thu Aug 5 18:10:12 2010 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 6 Aug 2010 08:10:12 +1000 Subject: avoiding top posts in gmail [was easy question on parsing python: "is not None"] In-Reply-To: References: Message-ID: <20100805221012.GA30332@cskk.homeip.net> On 05Aug2010 12:07, wheres pythonmonks wrote: | P.S. Sorry for the top-post -- is there a way to not do top posts from | gmail? I haven't used usenet since tin. The standard way is with attitude: view having your cursor at the top not as forcing you to top post but as an opportunity to start pruning the quoted text to leave only the relevant bits. And as you prune, you stick your reply text below the relevant quoted text that remains, with a blank line between. I spent a few months in a strongly GMail workplace with technical people who produced nicely interleaved/pruned/bottom posted conversations this way all the time. Works well. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ To be or not to be? Not to be. - John Slater (Arnold Schwartzenegger), _Macbeth_ (_The_Last_Action_Hero_) From chare at labr.net Thu Aug 5 18:41:36 2010 From: chare at labr.net (Chris Hare) Date: Thu, 05 Aug 2010 17:41:36 -0500 Subject: defining, raising and catching exceptions Message-ID: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> I have a block of test code, where I am trying to raise and catch my own user defined exception class NetActiveError(RuntimeError): def __init__(self,error): self.args = error def a(): try: fh = open("me.txt", "r") except Exception as (errno, errText): print errText try: b() except NetActiveError as (errono, errText): print errno, errText def b(): print "def b" raise NetActiveError,"net already running" a() When I run it though, I get the following error: chare$ python z No such file or directory def b Traceback (most recent call last): File "z", line 20, in a() File "z", line 12, in a except NetActiveError as (errono, errText): ValueError: too many values to unpack What am I doing wrong here? From benjamin.kaplan at case.edu Thu Aug 5 18:44:07 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 5 Aug 2010 15:44:07 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Thu, Aug 5, 2010 at 9:07 AM, wheres pythonmonks wrote: > Well, I am not convinced of the equivalence of not None and true: > >>>> not None > True >>>> 3 is True; > False >>>> 3 is not None > True >>>> > > P.S. Sorry for the top-post -- is there a way to not do top posts from > gmail? ?I haven't used usenet since tin. > Scroll down in the email and press enter a few times. From benjamin.kaplan at case.edu Thu Aug 5 18:49:38 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 5 Aug 2010 15:49:38 -0700 Subject: defining, raising and catching exceptions In-Reply-To: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> Message-ID: What makes you think it has to do with user-defined exceptions? >>> try : ... raise Exception("hello") ... except Exception as (errno, errText) : ... print "whatever" ... Traceback (most recent call last): ValueError: need more than 1 values to unpack An Exception is an object, not a tuple of number and text. Raise an instance of the exception, not the class: raise NetActiveError("net already running") And then catch the exception object except NetActiveError as err: print err.args On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare wrote: > > I have a block of test code, where I am trying to raise and catch my own user defined exception > > class NetActiveError(RuntimeError): > ? ?def __init__(self,error): > ? ? ? ?self.args = error > > def a(): > ? ?try: > ? ? ? ?fh = open("me.txt", "r") > ? ?except Exception as (errno, errText): > ? ? ? ?print errText > ? ?try: > ? ? ? ?b() > ? ?except NetActiveError as (errono, errText): > ? ? ? ?print errno, errText > > def b(): > ? ?print "def b" > ? ?raise NetActiveError,"net already running" > > > a() > > > When I run it though, I get the following error: > > chare$ python z > No such file or directory > def b > Traceback (most recent call last): > ?File "z", line 20, in > ? ?a() > ?File "z", line 12, in a > ? ?except NetActiveError as (errono, errText): > ValueError: too many values to unpack > > > What am I doing wrong here? > > > -- > http://mail.python.org/mailman/listinfo/python-list > From nyamatongwe+thunder at gmail.com Thu Aug 5 18:59:28 2010 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 06 Aug 2010 08:59:28 +1000 Subject: Why is python not written in C++ ? In-Reply-To: <7xmxt1kk1v.fsf@ruckus.brouhaha.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xocdi56cp.fsf@ruckus.brouhaha.com> <7xmxt1kk1v.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > C has all kinds of undefined behavior. "Might need to rely on" is not > relevant for this kind of issue. Ada's designers had the goal that that > Ada programs should have NO undefined behavior. Ada achieves this by describing a long list of implementation defined behaviour (Annex M). http://oopweb.com/Ada/Documents/Ada95RM/Volume/m.htm > As a famous example of C's underspecification, the behavior of > > a[i++] = i; > > is undefined in C99. Ada does not define ordering in all cases either. For example the order of elaboration of library_items (essentially the order in which modules are run in the absence of explicit declarations) is defined for GNAT as """ first elaborating bodies as early as possible (i.e. in preference to specs where there is a choice), and second by evaluating the immediate with clauses of a unit to determine the probably best choice, and third by elaborating in alphabetical order of unit names where a choice still remains """ Other compilers use different orders. I just love that "probably". Neil From rhodri at wildebst.demon.co.uk Thu Aug 5 19:15:38 2010 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Fri, 06 Aug 2010 00:15:38 +0100 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks wrote: > Well, I am not convinced of the equivalence of not None and true: > >>>> not None > True >>>> 3 is True; > False >>>> 3 is not None > True >>>> You're not testing for equivalence there, you're testing for identity. "is" and "is not" test whether the two objects concerned are (or are not) the same object. Two objects can have the same value, but be different objects. The interpreter can fool you by caching and reusing objects which have the same value when it happens to know about it, in particular for small integers, but this is just a happy accident of the implementation and in no way guaranteed by the language. For example: >>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" True >>> a = "spam, eggs, chips and spam" >>> b = "spam, eggs, chips and spam" >>> a is b False >>> a == b True Also, remember that "is not" is a single operator, *not* the concatenation of "is" and "not". Your last test is probably not checking what you think it is :-) >>> 3 is (not None) False -- Rhodri James *-* Wildebeest Herder to the Masses From chare at labr.net Thu Aug 5 19:21:27 2010 From: chare at labr.net (Chris Hare) Date: Thu, 05 Aug 2010 18:21:27 -0500 Subject: defining, raising and catching exceptions In-Reply-To: References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> Message-ID: <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> okay - but why does the response come back like No such file or directory def b ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 'n', 'i', 'n', 'g') On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote: > What makes you think it has to do with user-defined exceptions? > >>>> try : > ... raise Exception("hello") > ... except Exception as (errno, errText) : > ... print "whatever" > ... > Traceback (most recent call last): > ValueError: need more than 1 values to unpack > > An Exception is an object, not a tuple of number and text. > > Raise an instance of the exception, not the class: > > raise NetActiveError("net already running") > > And then catch the exception object > > except NetActiveError as err: > print err.args > > On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare wrote: >> >> I have a block of test code, where I am trying to raise and catch my own user defined exception >> >> class NetActiveError(RuntimeError): >> def __init__(self,error): >> self.args = error >> >> def a(): >> try: >> fh = open("me.txt", "r") >> except Exception as (errno, errText): >> print errText >> try: >> b() >> except NetActiveError as (errono, errText): >> print errno, errText >> >> def b(): >> print "def b" >> raise NetActiveError,"net already running" >> >> >> a() >> >> >> When I run it though, I get the following error: >> >> chare$ python z >> No such file or directory >> def b >> Traceback (most recent call last): >> File "z", line 20, in >> a() >> File "z", line 12, in a >> except NetActiveError as (errono, errText): >> ValueError: too many values to unpack >> >> >> What am I doing wrong here? >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list From roy at panix.com Thu Aug 5 19:45:50 2010 From: roy at panix.com (Roy Smith) Date: Thu, 05 Aug 2010 19:45:50 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message , Roy Smith wrote: > > > C++, for all its flaws, had one powerful feature which made it very > > popular. It is a superset of C. > > Actually, it never was. Yes, there are a few corner cases where valid C syntax has different semantics in C and C++. But, they are very few. Calling C++ a superset of C is essentially correct. It is certainly correct from the level of a risk-averse development manager deciding if he or she is willing to use C++ for the first time. Fear of the unknown is a powerful deterrent. It's a lot easier to accept something like C++ because "it's just a superset of C, and we've been using C for years". I suspect the same effect contributed to Java's success as well. "Look, it's got curly braces and semicolons. It's just like C!" From python.list at tim.thechases.com Thu Aug 5 19:46:54 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 05 Aug 2010 18:46:54 -0500 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> Message-ID: <4C5B4D6E.1070501@tim.thechases.com> On 08/05/10 16:01, ????? wrote: >> On 5 ???, 22:09, Tim Chase wrote: >>> dataset = cursor.fetchall() >> >>> for row in dataset: >>> print ( ''' ''' ) > > So, 'dataset' in here is a 'list of tuples' right? and 'row' > in here is a tuple form the above list of tuples right? > > Am i understanding this correctly?! > > It was a tuple. But it migth as well be a list too?!?! > > Could 'dataset' be a 'list of lists' as well? Pretty much...it's either a list-of-tuples or a list-of-lists (I'm not sure if is part of the DB-API spec to mandate one or the other). For the most part, you can treat them as the same thing. However, tuples are immutable, so you can't say my_tuple[3] = some_value but with a list you can: my_list[3] = some_value > How one would know in which way the returned mysql data is saved in? Well, you can ask: print type(row) (I *suspect* it's a tuple) or you can just tell it what to be: for row in dataset: row = list(row) row[3] = row[3].strftime(...) for item in row: ... I don't usually have cause to write a value back into the data I'm reading from the DB, so it's never really mattered to me whether the DB gives me tuples or lists. >> Though I think I'd make it a bit clearer by naming the fields: >> >> for host, hits, dt in dataset: >> print ("") >> for item in (host, hits, dt.strftime(...)): >> print ("" % item) >> print ("") > > Cool! I myself like this solution best over the all working other! > very nice approach thank you very much! Is what i anted and couldn't > write myself! > > But please tell me if in my example 'row' was a tuple, what kind of > objects is 'host', 'hits', 'dt' here and how do they sore the data? Python supports "tuple assignment" which means that the following are about[*] the same: # variant A for row in dataset: host = row[0] hits = row[1] dt = row[2] # rest of your code here # variant B for row in dataset: host, hits, dt = row # rest of your code here # variant C for host, hits, dt in row: # rest of your code here The data-type of the individual values would be whatever comes back from the database as translated into Python (string, float/Decimal, boolean, datetime, etc). In your example, it's likely a string+integer+datetime as the 3 values. You can see why I prefer the elegance of just performing the assignment in the for-loop (variant C). Hope this helps, -tkc [*] "about" the same because in #1 and #2, you also have access to the whole row; whereas in #3, you don't have something called "row", but you could reassemble it if you needed: row = (host, hits, dt) From python at mrabarnett.plus.com Thu Aug 5 20:37:17 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 06 Aug 2010 01:37:17 +0100 Subject: defining, raising and catching exceptions In-Reply-To: <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> Message-ID: <4C5B593D.3090505@mrabarnett.plus.com> Chris Hare wrote: > okay - but why does the response come back like > > No such file or directory > def b > ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 'n', 'i', 'n', 'g') > The class Exception saves its arguments in the 'args' instance attribute, and when it prints the exception it prints those arguments: >>> e = Exception(1, 2, 3) >>> print e.args (1, 2, 3) >>> print e (1, 2, 3) >>> print repr(e) Exception(1, 2, 3) NetActiveError inherits from RuntimeError, and ultimately from Exception. NetActiveError sets the 'args' attribute to its single string argument, and when the exception is printed out it thinks it's the arguments: >>> e.args = "string" >>> print e ('s', 't', 'r', 'i', 'n', 'g') >>> print repr(e) Exception('s', 't', 'r', 'i', 'n', 'g') The correct way to create your own exceptions is to call the superclass's __init__ method: >>> class NetActiveError(RuntimeError): ... def __init__(self, error): ... RuntimeError.__init__(self, error) ... >>> e = NetActiveError("string") >>> print e string >>> print repr(e) NetActiveError('string',) > > On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote: > >> What makes you think it has to do with user-defined exceptions? >> >>>>> try : >> ... raise Exception("hello") >> ... except Exception as (errno, errText) : >> ... print "whatever" >> ... >> Traceback (most recent call last): >> ValueError: need more than 1 values to unpack >> >> An Exception is an object, not a tuple of number and text. >> >> Raise an instance of the exception, not the class: >> >> raise NetActiveError("net already running") >> >> And then catch the exception object >> >> except NetActiveError as err: >> print err.args >> >> On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare wrote: >>> I have a block of test code, where I am trying to raise and catch my own user defined exception >>> >>> class NetActiveError(RuntimeError): >>> def __init__(self,error): >>> self.args = error >>> >>> def a(): >>> try: >>> fh = open("me.txt", "r") >>> except Exception as (errno, errText): >>> print errText >>> try: >>> b() >>> except NetActiveError as (errono, errText): >>> print errno, errText >>> >>> def b(): >>> print "def b" >>> raise NetActiveError,"net already running" >>> >>> >>> a() >>> >>> >>> When I run it though, I get the following error: >>> >>> chare$ python z >>> No such file or directory >>> def b >>> Traceback (most recent call last): >>> File "z", line 20, in >>> a() >>> File "z", line 12, in a >>> except NetActiveError as (errono, errText): >>> ValueError: too many values to unpack >>> >>> >>> What am I doing wrong here? >>> From wolftracks at invalid.com Thu Aug 5 20:55:30 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 17:55:30 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem Message-ID: It's been awhile since I've used python, and I recall there is a way to find the version number from the IDLE command line prompt. dir, help, __version.__? I made the most minimal change to a program, and it works for me, but not my partner. He gets Traceback (most recent call last): File "C:\Documents and Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", line 40, in from scipy import stats as stats # scoreatpercentile File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, in from stats import * File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, in import scipy.special as special File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 22, in from numpy.testing import NumpyTest ImportError: cannot import name NumpyTest Here are the first few lines of code. import sys, os, glob import string from numpy import * from datetime import datetime, timedelta import time from scipy import stats as stats # scoreatpercentile I'm pretty sure he has the same version of Python, 2.5, but perhaps not the numpy or scipy modules. I need to find out his version numbers. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet From steve at REMOVE-THIS-cybersource.com.au Thu Aug 5 21:13:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 01:13:11 GMT Subject: [Tutor] Finding the version # of a module, and py module problem References: Message-ID: <4c5b61a7$0$28666$c3e8da3@news.astraweb.com> On Thu, 05 Aug 2010 17:55:30 -0700, W. eWatson wrote: > I'm pretty sure he has the same version of Python, 2.5, but perhaps not > the numpy or scipy modules. I need to find out his version numbers. It's only a convention, but the usual way is to check the __version__ attribute. It works for Numpy: >>> import numpy >>> numpy.__version__ '1.0.3' -- Steven From python at mrabarnett.plus.com Thu Aug 5 21:23:51 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 06 Aug 2010 02:23:51 +0100 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: <4C5B6427.6000001@mrabarnett.plus.com> W. eWatson wrote: > It's been awhile since I've used python, and I recall there is a way to > find the version number from the IDLE command line prompt. dir, help, > __version.__? > > I made the most minimal change to a program, and it works for me, but > not my partner. He gets > > Traceback (most recent call last): > File "C:\Documents and > Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", > line 40, in > from scipy import stats as stats # scoreatpercentile > File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, > in > from stats import * > File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, > in > import scipy.special as special > File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line > 22, in > from numpy.testing import NumpyTest > ImportError: cannot import name NumpyTest > > Here are the first few lines of code. > > import sys, os, glob > import string > from numpy import * > from datetime import datetime, timedelta > import time > from scipy import stats as stats # scoreatpercentile > > I'm pretty sure he has the same version of Python, 2.5, but perhaps not > the numpy or scipy modules. I need to find out his version numbers. > Try: import numpy help(numpy.version) BTW, on Python 2.6 I can see that there's "numpytest" but not "NumpyTest". From steve at REMOVE-THIS-cybersource.com.au Thu Aug 5 21:26:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 01:26:42 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: > P.S. Sorry for the top-post -- is there a way to not do top posts from > gmail? I haven't used usenet since tin. Er, surely you can just move the cursor before you start typing??? -- Steven From chare at labr.net Thu Aug 5 21:28:45 2010 From: chare at labr.net (Chris Hare) Date: Thu, 05 Aug 2010 20:28:45 -0500 Subject: defining, raising and catching exceptions In-Reply-To: <4C5B593D.3090505@mrabarnett.plus.com> References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> <4C5B593D.3090505@mrabarnett.plus.com> Message-ID: On Aug 5, 2010, at 7:37 PM, MRAB wrote: > Chris Hare wrote: >> okay - but why does the response come back like >> No such file or directory >> def b >> ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 'n', 'i', 'n', 'g') > The class Exception saves its arguments in the 'args' instance > attribute, and when it prints the exception it prints those arguments: > > > >>> e = Exception(1, 2, 3) > >>> print e.args > (1, 2, 3) > >>> print e > (1, 2, 3) > >>> print repr(e) > Exception(1, 2, 3) > > > NetActiveError inherits from RuntimeError, and ultimately from > Exception. > > NetActiveError sets the 'args' attribute to its single string argument, > and when the exception is printed out it thinks it's the arguments: > > > >>> e.args = "string" > >>> print e > ('s', 't', 'r', 'i', 'n', 'g') > >>> print repr(e) > Exception('s', 't', 'r', 'i', 'n', 'g') > > > The correct way to create your own exceptions is to call the > superclass's __init__ method: > > > >>> class NetActiveError(RuntimeError): > ... def __init__(self, error): > ... RuntimeError.__init__(self, error) > ... > >>> e = NetActiveError("string") > >>> print e > string > >>> print repr(e) > NetActiveError('string',) > > >> On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote: >>> What makes you think it has to do with user-defined exceptions? >>> >>>>>> try : >>> ... raise Exception("hello") >>> ... except Exception as (errno, errText) : >>> ... print "whatever" >>> ... >>> Traceback (most recent call last): >>> ValueError: need more than 1 values to unpack >>> >>> An Exception is an object, not a tuple of number and text. >>> >>> Raise an instance of the exception, not the class: >>> >>> raise NetActiveError("net already running") >>> >>> And then catch the exception object >>> >>> except NetActiveError as err: >>> print err.args >>> >>> On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare wrote: >>>> I have a block of test code, where I am trying to raise and catch my own user defined exception >>>> >>>> class NetActiveError(RuntimeError): >>>> def __init__(self,error): >>>> self.args = error >>>> >>>> def a(): >>>> try: >>>> fh = open("me.txt", "r") >>>> except Exception as (errno, errText): >>>> print errText >>>> try: >>>> b() >>>> except NetActiveError as (errono, errText): >>>> print errno, errText >>>> >>>> def b(): >>>> print "def b" >>>> raise NetActiveError,"net already running" >>>> >>>> >>>> a() >>>> >>>> >>>> When I run it though, I get the following error: >>>> >>>> chare$ python z >>>> No such file or directory >>>> def b >>>> Traceback (most recent call last): >>>> File "z", line 20, in >>>> a() >>>> File "z", line 12, in a >>>> except NetActiveError as (errono, errText): >>>> ValueError: too many values to unpack >>>> >>>> >>>> What am I doing wrong here? >>>> > > -- > http://mail.python.org/mailman/listinfo/python-list okay - thanks for the tutorial -- you explained what I couldn't find in the docs I looked at. I appreciate your help From steve at REMOVE-THIS-cybersource.com.au Thu Aug 5 21:38:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 01:38:42 GMT Subject: defining, raising and catching exceptions References: <42EFFB8E-CA1C-49B8-96D0-8505E5D81188@labr.net> <91973B92-6B5A-42CF-939C-7A2471C9C3E9@labr.net> Message-ID: <4c5b67a2$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 01:37:17 +0100, MRAB wrote: > The correct way to create your own exceptions is to call the > superclass's __init__ method: > > > >>> class NetActiveError(RuntimeError): > ... def __init__(self, error): > ... RuntimeError.__init__(self, error) As given, that's pointless since you're neither overriding (replacing) nor overloading the base class method. Since NetActiveError inherits ALL behaviour and state from RuntimeError, there's no need to overload anything at all, so the correct way to subclass is to simply give the subclass a name and (optionally) a docstring: class NetActiveError(RuntimeError): """Description of error goes here.""" The only change from the OP's code is that instead of defining a non- standard error attribute, it uses the standard message and args attributes: >>> e = NetActiveError('network already running') >>> e.message 'network already running' >>> e.args ('network already running',) -- Steven From wolftracks at invalid.com Thu Aug 5 21:40:02 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 18:40:02 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: <4c5b61a7$0$28666$c3e8da3@news.astraweb.com> References: <4c5b61a7$0$28666$c3e8da3@news.astraweb.com> Message-ID: On 8/5/2010 6:13 PM, Steven D'Aprano wrote: > On Thu, 05 Aug 2010 17:55:30 -0700, W. eWatson wrote: > >> I'm pretty sure he has the same version of Python, 2.5, but perhaps not >> the numpy or scipy modules. I need to find out his version numbers. > > It's only a convention, but the usual way is to check the __version__ > attribute. It works for Numpy: > >>>> import numpy >>>> numpy.__version__ > '1.0.3' > > > It is now written in my Py book. Thanks. From wolftracks at invalid.com Thu Aug 5 21:42:04 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 18:42:04 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On 8/5/2010 6:23 PM, MRAB wrote: > W. eWatson wrote: >> It's been awhile since I've used python, and I recall there is a way >> to find the version number from the IDLE command line prompt. dir, >> help, __version.__? >> >> I made the most minimal change to a program, and it works for me, but >> not my partner. He gets >> >> Traceback (most recent call last): >> File "C:\Documents and >> Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", >> line 40, in >> from scipy import stats as stats # scoreatpercentile >> File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, >> in >> from stats import * >> File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, >> in >> import scipy.special as special >> File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line >> 22, in >> from numpy.testing import NumpyTest >> ImportError: cannot import name NumpyTest >> >> Here are the first few lines of code. >> >> import sys, os, glob >> import string >> from numpy import * >> from datetime import datetime, timedelta >> import time >> from scipy import stats as stats # scoreatpercentile >> >> I'm pretty sure he has the same version of Python, 2.5, but perhaps >> not the numpy or scipy modules. I need to find out his version numbers. >> > Try: > > import numpy > help(numpy.version) > > BTW, on Python 2.6 I can see that there's "numpytest" but not > "NumpyTest". I have to stick with 2.5 for comparability with my partner. He's non-Python but was able to get Python 2.5 working. I think he somehow bumped ahead to a later version of numpy than I have. From philip at semanchuk.com Thu Aug 5 21:47:48 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 5 Aug 2010 21:47:48 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Aug 5, 2010, at 8:55 PM, W. eWatson wrote: > It's been awhile since I've used python, and I recall there is a way > to find the version number from the IDLE command line prompt. dir, > help, __version.__? Hi Wayne, FYI it's got nothing to do with IDLE, it's just a question of whether or not the module in question exposes any kind of a version attribute. There's no standard, unfortunately. The most popular convention seems to be via an attribute called __version__, but I've also seen __VERSION__, VERSION, and version. Here's some code that I wrote that you might find useful. It's from a setup.py and it checks a list of modules on which our project depends to see if (a) they're installed and (b) if the version installed is adequate. In the snippet below, dependencies is a list of custom classes that represent modules we need (e.g. numpy). # Try each module for dependency in dependencies: try: __import__(dependency.name) except ImportError: # Uh oh! dependency.installed = None else: # The module loaded OK. Get a handle to it and try to extract # version info. # Many Python modules follow the convention of providing their # version as a string in a __version__ attribute. module = sys.modules[dependency.name] # This is what I default to. dependency.installed = "[version unknown]" for attribute_name in ("__version__", "__VERSION__", "VERSION", "version"): if hasattr(module, attribute_name): dependency.installed = getattr(module, attribute_name) break Hope this helps a little, Philip From wolftracks at invalid.com Thu Aug 5 21:50:14 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 18:50:14 -0700 Subject: Python Portability--Not very portable? Message-ID: In my on-again-off-again experience with Python for 18 months, portability seems an issue. As an example, my inexperienced Python partner 30 miles away has gotten out of step somehow. I think by installing a different version of numpy than I use. I gave him a program we both use months ago, and he had no trouble. (We both use IDLE on 2.5). I made a one character change to it and sent him the new py file. He can't execute it. I doubt he has changed anything in the intervening period. A further example. Months ago I decided to see if I could compile a program to avoid such problems as above. I planned to satisfy that need, and see if I could distribute some simple programs to non-Python friends. I pretty well understand the idea,and got it working with a small program. It seemed like a lot of manual labor to do it. From skippy.hammond at gmail.com Thu Aug 5 22:02:50 2010 From: skippy.hammond at gmail.com (Mark Hammond) Date: Fri, 06 Aug 2010 12:02:50 +1000 Subject: pre-uninstall script in bdist_wininst In-Reply-To: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> References: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> Message-ID: <4C5B6D4A.3000702@gmail.com> On 6/08/2010 4:26 AM, Nils wrote: > Hi. > I am using a postinstall-script like this: > setup( > ... > scripts=['scripts\install.py'], > options = { > ... > "bdist_wininst" : { > "install_script" : "install.py", > ... > }, > } > ) > > According to the docs in [1] this script is > a) called after install (with the "-install" parameter) - this works > fine for me... > b) called before uninstall (with tho "-remove" parameter) - this > however does not work. According to a comment in pywin32's post-install script: elif arg == "-remove": # bdist_msi calls us before uninstall, so we can undo what we # previously did. Sadly, bdist_wininst calls us *after*, so # we can't do much at all. So it seems possible your script is failing due to an import error as your module has already been removed. Maybe a .msi would work better for you. > btw: With that I am trying to register a com-server on install and de- > register on uninstall - so if other ideas are around I'd love to hear > them, too... I'd suggest using py2exe to package the object and inno installer or similar to handle the install and uninstall parts. Mark From wuwei23 at gmail.com Thu Aug 5 22:42:28 2010 From: wuwei23 at gmail.com (alex23) Date: Thu, 5 Aug 2010 19:42:28 -0700 (PDT) Subject: Why is there no platform independent way of clearing a terminal? References: Message-ID: <6fdf65db-ab65-4891-9e3b-253896245326@h40g2000pro.googlegroups.com> Lawrence D'Oliveiro wrote: > You?ve got to be kidding. Look at the number of Windows-specific questions > this groups is already full of. Are you really unable to tell the difference between questions about Windows-related modules and snarky, off-topic sniping at Windows itself? From debatem1 at gmail.com Thu Aug 5 22:45:12 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 5 Aug 2010 19:45:12 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson wrote: > In my on-again-off-again experience with Python for 18 months, portability > seems an issue. > > As an example, my inexperienced Python partner 30 miles away has gotten out > of step somehow. I think by installing a different version of numpy than I > use. I gave him a program we both use months ago, and he had no trouble. (We > both use IDLE on 2.5). I made a one character change to it and sent him the > new py file. He can't execute it. I doubt he has changed anything in the > intervening period. Portability doesn't mean you can use different versions of your dependencies and be A-OK. It should be fairly obvious that if the behavior of your dependencies changes, your code needs to change to ensure that it demonstrates the same behavior. Portability also doesn't mean that any given one-character change is valid, so that may be your issue as well. > A further example. Months ago I decided to see if I could compile a program > to avoid such problems as above. I planned to satisfy that need, and see if > I could distribute some simple programs to non-Python friends. I pretty well > understand the idea,and got it working with a small program. It seemed like > a lot of manual labor to do it. What, why were you compiling a program? And why not just use distutils? Geremy Condra From wolftracks at invalid.com Thu Aug 5 23:28:40 2010 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 05 Aug 2010 20:28:40 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On 8/5/2010 7:45 PM, geremy condra wrote: > On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson wrote: >> In my on-again-off-again experience with Python for 18 months, portability >> seems an issue. >> >> As an example, my inexperienced Python partner 30 miles away has gotten out >> of step somehow. I think by installing a different version of numpy than I >> use. I gave him a program we both use months ago, and he had no trouble. (We >> both use IDLE on 2.5). I made a one character change to it and sent him the >> new py file. He can't execute it. I doubt he has changed anything in the >> intervening period. > > Portability doesn't mean you can use different versions of your > dependencies and be A-OK. It should be fairly obvious that if the > behavior of your dependencies changes, your code needs to change to > ensure that it demonstrates the same behavior. Portability also > doesn't mean that any given one-character change is valid, so that may > be your issue as well. > >> A further example. Months ago I decided to see if I could compile a program >> to avoid such problems as above. I planned to satisfy that need, and see if >> I could distribute some simple programs to non-Python friends. I pretty well >> understand the idea,and got it working with a small program. It seemed like >> a lot of manual labor to do it. > > What, why were you compiling a program? And why not just use distutils? > > Geremy Condra I checked the one char change on my system thoroughly. I looked around on some forums and NGs 4 months ago, and found no one even had a simple "compiled program" available to even demonstrate some simple example. I would think there are some small time and big time Python players who sell executable versions of their programs for profit? disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils might have been part of it. So how does one keep a non-Python user in lock step with my setup, so these problems don't arise? I don't even want to think about having him uninstall and re-install. :-) Although maybe he could do it without making matters worse. From debatem1 at gmail.com Thu Aug 5 23:50:57 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 5 Aug 2010 20:50:57 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 8:28 PM, W. eWatson wrote: > On 8/5/2010 7:45 PM, geremy condra wrote: >> >> On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson ?wrote: >>> >>> In my on-again-off-again experience with Python for 18 months, >>> portability >>> seems an issue. >>> >>> As an example, my inexperienced Python partner 30 miles away has gotten >>> out >>> of step somehow. I think by installing a different version of numpy than >>> I >>> use. I gave him a program we both use months ago, and he had no trouble. >>> (We >>> both use IDLE on 2.5). I made a one character change to it and sent him >>> the >>> new py file. He can't execute it. I doubt he has changed anything in the >>> intervening period. >> >> Portability doesn't mean you can use different versions of your >> dependencies and be A-OK. It should be fairly obvious that if the >> behavior of your dependencies changes, your code needs to change to >> ensure that it demonstrates the same behavior. Portability also >> doesn't mean that any given one-character change is valid, so that may >> be your issue as well. >> >>> A further example. Months ago I decided to see if I could compile a >>> program >>> to avoid such problems as above. I planned to satisfy that need, and see >>> if >>> I could distribute some simple programs to non-Python friends. I pretty >>> well >>> understand the idea,and got it working with a small program. It seemed >>> like >>> a lot of manual labor to do it. >> >> What, why were you compiling a program? And why not just use distutils? >> >> Geremy Condra > > I checked the one char change on my system thoroughly. I looked around on > some forums and NGs 4 months ago, and found no one even had a simple > "compiled program" available to even demonstrate some simple example. That would be because Python is an interpreted language. > I would think there are some small time and big time Python players who sell > executable versions of their programs for profit? Yes. What's your point? > disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils > might have been part of it. distutils. http://docs.python.org/library/distutils.html > So how does one keep a non-Python user in lock step with my setup, so these > problems don't arise? I don't even want to think about having him uninstall > and re-install. :-) Although maybe he could do it without making matters > worse. That's going to hinge on what your dependencies are. Geremy Condra From nagle at animats.com Fri Aug 6 01:13:26 2010 From: nagle at animats.com (John Nagle) Date: Thu, 05 Aug 2010 22:13:26 -0700 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: References: Message-ID: <4c5b99f6$0$1613$742ec2ed@news.sonic.net> On 8/4/2010 4:40 PM, ????? wrote: > cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page > = '%s' ORDER BY date DESC ''' % (page) ) Don't do string substitution ("%") on SQL statements. Let MySQLdb do it for you, with proper escaping: cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s ORDER BY date DESC''', (page,)) The difference is that if some external source can control "page", and they put in a value like 100 ; DELETE FROM visitors; SELECT * FROM visitors you just lost your data. John Nagle From navkirats at gmail.com Fri Aug 6 01:14:36 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 6 Aug 2010 10:44:36 +0530 Subject: Import python modules from sub-directories Message-ID: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> Hi guys, I am new to python and would like to import certain classes in sub-directories of the working directory. I was wondering how will I be able to achieve this? Regards, Nav From navkirats at gmail.com Fri Aug 6 01:41:51 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 6 Aug 2010 11:11:51 +0530 Subject: Import python modules from sub-directories In-Reply-To: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> References: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> Message-ID: <00C202DF-A4CB-44AA-8C1C-C3A422317830@gmail.com> On 06-Aug-2010, at 10:44 AM, Navkirat Singh wrote: > Hi guys, > > I am new to python and would like to import certain classes in sub-directories of the working directory. I was wondering how will I be able to achieve this? > > Regards, > Nav Thanks. I got it. I just put an empty __init__.py file in the subdirectories and it worked. From ralf at schoenian-online.de Fri Aug 6 02:05:33 2010 From: ralf at schoenian-online.de (Ralf Schoenian) Date: Fri, 06 Aug 2010 08:05:33 +0200 Subject: Import python modules from sub-directories In-Reply-To: References: Message-ID: <4c5ba0d1$0$7656$9b4e6d93@newsspool1.arcor-online.net> Navkirat Singh wrote: > Hi guys, > > I am new to python and would like to import certain classes in sub-directories of the working directory. I was wondering how will I be able to achieve this? > > Regards, > Nav Hi, put an empty file with the name __init__.py in your subdirectory. I call it sub1 here. Assuming your filename is importme.py and your classname is Test you can do the following imports: from sub1.importme import Test import sub1.importme You can find further explainations in the official tutorial http://docs.python.org/tutorial/modules.html Regards, Ralf From cournape at gmail.com Fri Aug 6 02:22:10 2010 From: cournape at gmail.com (David Cournapeau) Date: Fri, 6 Aug 2010 15:22:10 +0900 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On Fri, Aug 6, 2010 at 8:45 AM, Roy Smith wrote: > In article , > ?Lawrence D'Oliveiro wrote: > >> In message , Roy Smith wrote: >> >> > C++, for all its flaws, had one powerful feature which made it very >> > popular. ?It is a superset of C. >> >> Actually, it never was. > > Yes, there are a few corner cases where valid C syntax has different > semantics in C and C++. ?But, they are very few. ?Calling C++ a superset > of C is essentially correct. This is only true if you limit yourself to C89 (as python seems to do). If you start using C99 (and lot of people do, if only because they don't realize it because gcc is quite relax about it), then almost no non trivial C code is valid C++ in my experience. David From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 6 03:25:37 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Aug 2010 09:25:37 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: Message-ID: <4c5bb8ec$0$14667$426a74cc@news.free.fr> Roald de Vries a ?crit : > > 'not None' first casts None to a bool, and then applies 'not', so 'x is > not None' means 'x is True'. Obviously plain wrong : Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 42 is not None True >>> 42 is True False >>> Please check your facts before posting !-) From rdmoores at gmail.com Fri Aug 6 03:26:49 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 6 Aug 2010 00:26:49 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: On Thu, Aug 5, 2010 at 16:15, Rhodri James wrote: > On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks > wrote: > You're not testing for equivalence there, you're testing for identity. ?"is" > and "is not" test whether the two objects concerned are (or are not) the > same object. ?Two objects can have the same value, but be different objects. > ?The interpreter can fool you by caching and reusing objects which have the > same value when it happens to know about it, in particular for small > integers, but this is just a happy accident of the implementation and in no > way guaranteed by the language. ?For example: > >>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" > > True >>>> >>>> a = "spam, eggs, chips and spam" >>>> b = "spam, eggs, chips and spam" >>>> a is b > > False >>>> >>>> a == b > > True > I'm wondering if there isn't considerable predictability to that "happy accident". Note how 1 'word' is treated versus 2: >>> x = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>> y = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>> x is y True >>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>> x is y False >>> (Python 3.1 on Vista.) Dick Moores From ldo at geek-central.gen.new_zealand Fri Aug 6 03:38:43 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Aug 2010 19:38:43 +1200 Subject: subprocess escaping POpen?! References: <4C5A9D91.9000504@simplistix.co.uk> <201008051322.11456.wolfgang@rohdewald.de> <4C5A9F37.80708@simplistix.co.uk> <201008051423.08319.wolfgang@rohdewald.de> Message-ID: In message , Chris Withers wrote: > Wolfgang Rohdewald wrote: > >> On Donnerstag 05 August 2010, Chris Withers wrote: >> >>> But why only the request for auth credentials? >> >> for security reasons I suppose - make sure a human enters >> the password > > Well yes, but what if you actually want to script it? Set up a public/private key pair. From zhxia at njnet.edu.cn Fri Aug 6 03:43:11 2010 From: zhxia at njnet.edu.cn (=?gb2312?Q?=CF=C4=D5=F0?=) Date: Fri, 6 Aug 2010 15:43:11 +0800 (CST) Subject: =?gb2312?B?UmU6IEltcG9ydCBweXRob24gbW9kdWxlcyBmcm9tIHN1Yi1kaXJlY3Rvcmllcw==?= In-Reply-To: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> References: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> Message-ID: <55296.202.112.23.199.1281080591.squirrel@carnation.njnet.edu.cn> > Hi guys, > > I am new to python and would like to import certain classes in sub-directories of the > working directory. I was wondering how will I be able to achieve this? > > Regards, > Nav > -- > http://mail.python.org/mailman/listinfo/python-list > Please try "touch __init__.py" in sub-directories. From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 6 03:49:32 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Aug 2010 09:49:32 +0200 Subject: assigning variables from list data In-Reply-To: References: Message-ID: <4c5bbe87$0$9222$426a74cc@news.free.fr> Chris Hare a ?crit : > I have a database query result (see code below). In PHP, I would have said > > list(var1,var2,var) = $result Other already answered on the Python equivalent. But there's an IMHO better way, which is to use (if the DB-API connector provides it) a DictCursor, that yields dicts instead of tuples. > > import sqlite3 as sqlite > > try: > print "connecting to disk db ..." > conn = sqlite.connect("netcomm.db") > except: > print "oops" OT, but do yourself a favor and remove this try/except. Sorry to have to say but it's about the most stupidiest error handling scheme you could think of. Seriously. Ask yourself : what will happens if sqlite.connect raises AND you don't catch the exception ? Yes, the script will stop right here - which is what you want anyway - AND you will have an error message giving you informations about what went wrong, and a full traceback. IOW, you'll have as much helpful debugging infos as possible at this point. Now what will happen with your current code ? Instead of an informative error message, you have a "oops". Well, really helps. Then your script will go on, print "retrieving data", and you can bet your ass it'll crash on the next line - "cursor = conn.cursor()", that is - with a very less informative error message, and you'll wonder why. Also, be warned that SysExit and KeyboardInterrupt are also exceptions. The one you may NOT want to catch and dismiss. To make a long story short: 1/ only catch exceptions you can *and* want to handle 2/ never assume anything about what caused the exception 3/ not exception handling is better than a wrong exception handling. HTH From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 6 04:32:00 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Aug 2010 10:32:00 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <4c5bc87b$0$10004$426a34cc@news.free.fr> Richard D. Moores a ?crit : > On Thu, Aug 5, 2010 at 16:15, Rhodri James wrote: >> On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks >> wrote: > >> You're not testing for equivalence there, you're testing for identity. "is" >> and "is not" test whether the two objects concerned are (or are not) the >> same object. Two objects can have the same value, but be different objects. >> The interpreter can fool you by caching and reusing objects which have the >> same value when it happens to know about it, in particular for small >> integers, but this is just a happy accident of the implementation and in no >> way guaranteed by the language. For example: >> >>>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" >> True >>>>> a = "spam, eggs, chips and spam" >>>>> b = "spam, eggs, chips and spam" >>>>> a is b >> False >>>>> a == b >> True >> > > I'm wondering if there isn't considerable predictability to that > "happy accident". There is, indeed, but that's really implementation details. > Note how 1 'word' is treated versus 2: > >>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>> x is y > True >>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>> x is y > False CPython caches strings that happen to be valid Python identifiers. But once again, this is an implementation-specific optimization. From jldunn2000 at gmail.com Fri Aug 6 05:06:29 2010 From: jldunn2000 at gmail.com (loial) Date: Fri, 6 Aug 2010 02:06:29 -0700 (PDT) Subject: How to read large amounts of output via popen Message-ID: <9fe7d6b5-7bbd-4453-8cf3-99d6e1260325@i31g2000yqm.googlegroups.com> I need to read a large amount of data that is being returned in standard output by a shell script I am calling. (I think the script should really be writing to a file but I have no control over that) Currently I have the following code. It seeems to work, however I suspect this may not work with large amounts of standard output. What is the best way to read a large amount of data from standard output and write to a file? Here is my code. process=subprocess.Popen(['myscript', 'param1'], shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) cmdoutput=process.communicate() myfile = open('/home/john/myoutputfile','w') myfile.write(cmdoutput[0]) myfile.close() From nawabadeel at gmail.com Fri Aug 6 05:07:32 2010 From: nawabadeel at gmail.com (Muhammad Adeel) Date: Fri, 6 Aug 2010 02:07:32 -0700 (PDT) Subject: Byte Offsets of Tokens, Ngrams and Sentences? Message-ID: <4b6077cf-d921-4f25-99ac-b74e6bc66056@d17g2000yqb.googlegroups.com> Hi, Does any one know how to tokenize a string in python that returns the byte offsets and tokens? Moreover, the sentence splitter that returns the sentences and byte offsets? Finally n-grams returned with byte offsets. Input: This is a string. Output: This 0 is 5 a 8 string. 10 thanks From ldo at geek-central.gen.new_zealand Fri Aug 6 05:23:37 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Aug 2010 21:23:37 +1200 Subject: Python Portability References: Message-ID: In message , W. eWatson wrote: > I made a one character change to it and sent him the new py file. He can't > execute it. What exactly was the problem? From ldo at geek-central.gen.new_zealand Fri Aug 6 05:25:23 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Aug 2010 21:25:23 +1200 Subject: Python Script Cannot Write to Directory References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> <4c5a6d00$0$29614$426a34cc@news.free.fr> Message-ID: In message <4c5a6d00$0$29614$426a34cc at news.free.fr>, News123 wrote: > The original question lacks necessary information That seems to be very common in this newsgroup. From rdmoores at gmail.com Fri Aug 6 05:27:11 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 6 Aug 2010 02:27:11 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5bc87b$0$10004$426a34cc@news.free.fr> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On Fri, Aug 6, 2010 at 01:32, Bruno Desthuilliers wrote: > Richard D. Moores a ?crit : >> >> On Thu, Aug 5, 2010 at 16:15, Rhodri James >> wrote: >>> >>> On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks >>> wrote: >> >>> You're not testing for equivalence there, you're testing for identity. >>> ?"is" >>> and "is not" test whether the two objects concerned are (or are not) the >>> same object. ?Two objects can have the same value, but be different >>> objects. >>> ?The interpreter can fool you by caching and reusing objects which have >>> the >>> same value when it happens to know about it, in particular for small >>> integers, but this is just a happy accident of the implementation and in >>> no >>> way guaranteed by the language. ?For example: >>> >>>>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" >>> >>> True >>>>>> >>>>>> a = "spam, eggs, chips and spam" >>>>>> b = "spam, eggs, chips and spam" >>>>>> a is b >>> >>> False >>>>>> >>>>>> a == b >>> >>> True >>> >> >> I'm wondering if there isn't considerable predictability to that >> "happy accident". > > There is, indeed, but that's really implementation details. > >> Note how 1 'word' is treated versus 2: >> >>>>> x = >>>>> 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>>> y = >>>>> 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>>> x is y >> >> True >>>>> >>>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj >>>>> hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj >>>>> hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' >>>>> x is y >> >> False > > > CPython caches strings that happen to be valid Python identifiers. But once > again, this is an implementation-specific optimization. So there would be a different implementation for each operating system? One for Windows, one for linux? Or one for Vista and one for XP? I'm just trying to clarify what is meant by "implementation". Thanks, Dick Moores From jeanmichel at sequans.com Fri Aug 6 05:42:39 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 06 Aug 2010 11:42:39 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4C5BD90F.6020000@sequans.com> Steven D'Aprano wrote: > On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: > > >> P.S. Sorry for the top-post -- is there a way to not do top posts from >> gmail? I haven't used usenet since tin. >> > > Er, surely you can just move the cursor before you start typing??? > > > > CTRL+END will bring the cursor at the end of the file (for most the the mail clients). JM From gagsl-py2 at yahoo.com.ar Fri Aug 6 05:49:33 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Aug 2010 06:49:33 -0300 Subject: Byte Offsets of Tokens, Ngrams and Sentences? References: <4b6077cf-d921-4f25-99ac-b74e6bc66056@d17g2000yqb.googlegroups.com> Message-ID: En Fri, 06 Aug 2010 06:07:32 -0300, Muhammad Adeel escribi?: > Does any one know how to tokenize a string in python that returns the > byte offsets and tokens? Moreover, the sentence splitter that returns > the sentences and byte offsets? Finally n-grams returned with byte > offsets. > > Input: > This is a string. > > Output: > This 0 > is 5 > a 8 > string. 10 Like this? py> import re py> s = "This is a string." py> for g in re.finditer("\S+", s): ... print g.group(), g.start() ... This 0 is 5 a 8 string. 10 -- Gabriel Genellina From jeanmichel at sequans.com Fri Aug 6 05:57:00 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 06 Aug 2010 11:57:00 +0200 Subject: Python Script Cannot Write to Directory In-Reply-To: References: <8c1f79cf-46ef-412f-8982-36c5f9e5a067@v15g2000yqe.googlegroups.com> <4c5914f0$0$9192$426a74cc@news.free.fr> <4c5a6d00$0$29614$426a34cc@news.free.fr> Message-ID: <4C5BDC6C.4040703@sequans.com> Lawrence D'Oliveiro wrote: > In message <4c5a6d00$0$29614$426a34cc at news.free.fr>, News123 wrote: > > >> The original question lacks necessary information >> > > That seems to be very common in this newsgroup. > ... JM From downaold at gmail.com Fri Aug 6 06:01:23 2010 From: downaold at gmail.com (Roald de Vries) Date: Fri, 6 Aug 2010 12:01:23 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5bb8ec$0$14667$426a74cc@news.free.fr> References: <4c5bb8ec$0$14667$426a74cc@news.free.fr> Message-ID: <7783CEA7-C451-4DB5-8161-D2E6D3800D42@gmail.com> On Aug 6, 2010, at 9:25 AM, Bruno Desthuilliers wrote: > Roald de Vries a ?crit : >> 'not None' first casts None to a bool, and then applies 'not', so >> 'x is not None' means 'x is True'. > > Obviously plain wrong : > > Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 42 is not None > True > >>> 42 is True > False > >>> I know. I'm sorry. I'm embarrassed. I will check my facts better before posting in the future. And I'm sorry. Cheers, Roald From gagsl-py2 at yahoo.com.ar Fri Aug 6 06:02:07 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Aug 2010 07:02:07 -0300 Subject: How to read large amounts of output via popen References: <9fe7d6b5-7bbd-4453-8cf3-99d6e1260325@i31g2000yqm.googlegroups.com> Message-ID: En Fri, 06 Aug 2010 06:06:29 -0300, loial escribi?: > I need to read a large amount of data that is being returned in > standard output by a shell script I am calling. > > (I think the script should really be writing to a file but I have no > control over that) > > Currently I have the following code. It seeems to work, however I > suspect this may not work with large amounts of standard output. > > What is the best way to read a large amount of data from standard > output and write to a file? > > Here is my code. > > process=subprocess.Popen(['myscript', 'param1'], > shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > cmdoutput=process.communicate() > > myfile = open('/home/john/myoutputfile','w') > > myfile.write(cmdoutput[0]) > > myfile.close() If all you do with the process' output is to write it to the output file, you can avoid the intermediate step: myfile = open('/home/john/myoutputfile','w') myerror = open('/home/john/myerrorfile','w') process=subprocess.Popen(['myscript', 'param1'], shell=False,stdout=myfile,stderr=myerror) process.wait() (untested) -- Gabriel Genellina From nawabadeel at gmail.com Fri Aug 6 06:06:18 2010 From: nawabadeel at gmail.com (Muhammad Adeel) Date: Fri, 6 Aug 2010 03:06:18 -0700 (PDT) Subject: Byte Offsets of Tokens, Ngrams and Sentences? References: <4b6077cf-d921-4f25-99ac-b74e6bc66056@d17g2000yqb.googlegroups.com> Message-ID: <76ea31b5-4591-4183-aedc-0cf40a809b37@m1g2000yqo.googlegroups.com> On Aug 6, 10:49?am, "Gabriel Genellina" wrote: > En Fri, 06 Aug 2010 06:07:32 -0300, Muhammad Adeel ? > escribi?: > > > Does any one know how to tokenize a string in python that returns the > > byte offsets and tokens? Moreover, the sentence splitter that returns > > the sentences and byte offsets? Finally n-grams returned with byte > > offsets. > > > Input: > > This is a string. > > > Output: > > This ?0 > > is ? ? ?5 > > a ? ? ? 8 > > string. ? 10 > > Like this? > > py> import re > py> s = "This is a string." > py> for g in re.finditer("\S+", s): > ... ? print g.group(), g.start() > ... > This 0 > is 5 > a 8 > string. 10 > > -- > Gabriel Genellina Hi, Thanks. Can you please tell me how to do for n-grams and sentences as well? From gagsl-py2 at yahoo.com.ar Fri Aug 6 06:13:17 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Aug 2010 07:13:17 -0300 Subject: abstract metaclass References: <1B034596-7B57-4950-8070-7685176A824E@gmail.com> Message-ID: En Thu, 05 Aug 2010 10:46:29 -0300, Roald de Vries escribi?: > I'm trying to create a metaclass that keeps track of its objects, and > implement this as a collections.MutableMapping. That is, something like > this: > > > class type2(type, MutableMapping): > ... > > /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/abc.pyc in __new__(mcls, name, bases, namespace) > 83 if getattr(value, "__isabstractmethod__", > False)) > 84 for base in bases: > ---> 85 for name in getattr(base, "__abstractmethods__", > set()): > 86 value = getattr(cls, name, None) > 87 if getattr(value, "__isabstractmethod__", > False): > > TypeError: Error when calling the metaclass bases > 'getset_descriptor' object is not iterable > > > Anybody knows why? Every type is just an object, isn't it? This may be an oversight in ABCMeta implementation - please file a bug report at http://bugs.python.org/ -- Gabriel Genellina From zak.mc.kraken at libero.it Fri Aug 6 07:12:44 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Fri, 06 Aug 2010 13:12:44 +0200 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: Richard D. Moores wrote: > So there would be a different implementation for each operating > system? One for Windows, one for linux? Or one for Vista and one for > XP? I'm just trying to clarify what is meant by "implementation". there are dozillions of "implementation" of python: one for each release of CPython (2.0, 2.1.2, 2.6.1, 3.x.y...), multiplied for each OS multiplied for IronPython, Jython, Pypy... etc... (obviously the "implementation details" between, say, CPython 2.6.1 and 2.6.2 are really minor vs Pypy X.Y.Z and IronPython A.B.C) -- By ZeD From no.email at please.post Fri Aug 6 07:23:50 2010 From: no.email at please.post (kj) Date: Fri, 6 Aug 2010 11:23:50 +0000 (UTC) Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> Message-ID: In Nobody writes: >On Fri, 23 Jul 2010 10:42:26 +0000, Steven D'Aprano wrote: >> Don't write bare excepts, always catch the error you want and nothing >> else. >That advice would make more sense if it was possible to know which >exceptions could be raised. In practice, that isn't possible, as the >documentation seldom provides this information. Even for the built-in >classes, the documentation is weak in this regard; for less important >modules and third-party libraries, it's entirely absent. I don't get your point. Even when I *know* that a certain exception may happen, I don't necessarily catch it. I catch only those exceptions for which I can think of a suitable response that is *different* from just letting the program fail. (After all, my own code raises its own exceptions with the precise intention of making the program fail.) If an unexpected exception occurs, then by definition, I had no better response in mind for that situation than just letting the program fail, so I'm happy to let that happen. If, afterwards, I think of a different response for a previously uncaught exception, I'll modify the code accordingly. I find this approach far preferable to the alternative of knowing a long list of possible exceptions (some of which may never happen in actual practice), and think of ways to keep the program still alive no-matter-what. "No memory? No disk space? No problem! Just a flesh wound!" What's the point of that? (If I want the final error message to be something other than a bare stack trace, I may wrap the whole execution in a global/top-level try/catch block so that I can fashion a suitable error message right before calling exit, but that's just "softening the fall": the program still will go down.) From katcipis at inf.ufsc.br Fri Aug 6 07:37:59 2010 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Fri, 6 Aug 2010 08:37:59 -0300 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 12:28 AM, W. eWatson wrote: > On 8/5/2010 7:45 PM, geremy condra wrote: > >> On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson >> wrote: >> >>> In my on-again-off-again experience with Python for 18 months, >>> portability >>> >>> seems an issue. >>> >>> As an example, my inexperienced Python partner 30 miles away has gotten >>> out >>> of step somehow. I think by installing a different version of numpy than >>> I >>> use. I gave him a program we both use months ago, and he had no trouble. >>> (We >>> both use IDLE on 2.5). I made a one character change to it and sent him >>> the >>> new py file. He can't execute it. I doubt he has changed anything in the >>> intervening period. >>> >> >> Portability doesn't mean you can use different versions of your >> dependencies and be A-OK. It should be fairly obvious that if the >> behavior of your dependencies changes, your code needs to change to >> ensure that it demonstrates the same behavior. Portability also >> doesn't mean that any given one-character change is valid, so that may >> be your issue as well. >> >> A further example. Months ago I decided to see if I could compile a >>> program >>> to avoid such problems as above. I planned to satisfy that need, and see >>> if >>> I could distribute some simple programs to non-Python friends. I pretty >>> well >>> understand the idea,and got it working with a small program. It seemed >>> like >>> a lot of manual labor to do it. >>> >> >> What, why were you compiling a program? And why not just use distutils? >> >> Geremy Condra >> > > I checked the one char change on my system thoroughly. I looked around on > some forums and NGs 4 months ago, and found no one even had a simple > "compiled program" available to even demonstrate some simple example. > > I would think there are some small time and big time Python players who > sell executable versions of their programs for profit? > > disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils > might have been part of it. > And what was hard to do with Py2Exe? i used it on relatively complex college work using QT and the worse i had to do was include a "sip" option to make Py2Exe work with PyQT. But the setup.py script that generates the .exe (automatically) was ridiculously small and simple ( https://svn.inf.ufsc.br/katcipis/python/FormaisGUI/src/setup.py). For me compiling a python program into an .exe always was pretty easy (already made it at my work with a prototype, that one was quite complex, i just had some problem with the netifaces module). > > So how does one keep a non-Python user in lock step with my setup, so these > problems don't arise? I don't even want to think about having him uninstall > and re-install. :-) Although maybe he could do it without making matters > worse. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.getgnulinux.org/windows -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Fri Aug 6 07:39:06 2010 From: roy at panix.com (Roy Smith) Date: Fri, 06 Aug 2010 07:39:06 -0400 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In article , David Cournapeau wrote: > > Yes, there are a few corner cases where valid C syntax has different > > semantics in C and C++. ??But, they are very few. ??Calling C++ a superset > > of C is essentially correct. > > This is only true if you limit yourself to C89 (as python seems to > do). If you start using C99 (and lot of people do, if only because > they don't realize it because gcc is quite relax about it), then > almost no non trivial C code is valid C++ in my experience. I'm not following you. If anything, C99 makes C closer to C++. Can you give me some examples of valid C99 which is not also valid C++? From dangets at gmail.com Fri Aug 6 08:28:40 2010 From: dangets at gmail.com (DG) Date: Fri, 6 Aug 2010 05:28:40 -0700 (PDT) Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On Aug 6, 2:32?am, Bruno Desthuilliers wrote: > Richard D. Moores a ?crit : > > > > > On Thu, Aug 5, 2010 at 16:15, Rhodri James wrote: > >> On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks > >> wrote: > > >> You're not testing for equivalence there, you're testing for identity. ?"is" > >> and "is not" test whether the two objects concerned are (or are not) the > >> same object. ?Two objects can have the same value, but be different objects. > >> ?The interpreter can fool you by caching and reusing objects which have the > >> same value when it happens to know about it, in particular for small > >> integers, but this is just a happy accident of the implementation and in no > >> way guaranteed by the language. ?For example: > > >>>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" > >> True > >>>>> a = "spam, eggs, chips and spam" > >>>>> b = "spam, eggs, chips and spam" > >>>>> a is b > >> False > >>>>> a == b > >> True > > > I'm wondering if there isn't considerable predictability to that > > "happy accident". > > There is, indeed, but that's really implementation details. > > > Note how 1 'word' is treated versus 2: > > >>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' > >>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' > >>>> x is y > > True > >>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' > >>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk' > >>>> x is y > > False > > CPython caches strings that happen to be valid Python identifiers. But > once again, this is an implementation-specific optimization. I've always thought of it as you don't compare strings with "is", you *should* use == The reasoning is that you don't know if that string instance is the only one in memory. I've heard as an implementation detail, since strings are immutable, that Python will only create one actual instance and just assign new references to it (your first x is y example), but to compare equality it just makes sense to use "==", not to ask if it is the same object in memory. Plus, I believe the "==" operator will check if the variables point to the same object. Using is/is not with None works well, because I believe there will always only be 1 None object. From nobody at nowhere.com Fri Aug 6 08:44:48 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 06 Aug 2010 13:44:48 +0100 Subject: How to read large amounts of output via popen References: <9fe7d6b5-7bbd-4453-8cf3-99d6e1260325@i31g2000yqm.googlegroups.com> Message-ID: On Fri, 06 Aug 2010 02:06:29 -0700, loial wrote: > I need to read a large amount of data that is being returned in > standard output by a shell script I am calling. > > (I think the script should really be writing to a file but I have no > control over that) If the script is writing to stdout, you get to decide whether its stdout is a pipe, file, tty, etc. > Currently I have the following code. It seeems to work, however I > suspect this may not work with large amounts of standard output. > process=subprocess.Popen(['myscript', 'param1'], > shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > cmdoutput=process.communicate() It's certainly not the best way to read large amounts of output. Unfortunately, better solutions get complicated when you need to read more than one of stdout and stderr, or if you also need to write to stdin. If you only need stdout, you can just read from process.stdout in a loop. You can leave stderr going to wherever the script's stderr goes (e.g. the terminal), or redirect it to a file. If you really do need both stdout and stderr, then you either need to enable non-blocking I/O, or use a separate thread for each stream, or redirect at least one of them to a file. FWIW, Popen.communicate() uses non-blocking I/O on Unix and separate threads on Windows (the standard library doesn't include a mechanism to enable non-blocking I/O on Windows). > What is the best way to read a large amount of data from standard > output and write to a file? For this case, the best way is to just redirect stdout to a file, rather than passing it through the script, i.e.: outfile = open('outputfile', 'w') process = subprocess.call(..., stdout = outfile) outfile.close() From landimatte at gmail.com Fri Aug 6 08:49:04 2010 From: landimatte at gmail.com (Matteo Landi) Date: Fri, 6 Aug 2010 14:49:04 +0200 Subject: pylint scores In-Reply-To: <4c554c01$0$6122$426a34cc@news.free.fr> References: <4C532577.8010906@free.fr> <4c554c01$0$6122$426a34cc@news.free.fr> Message-ID: On Sun, Aug 1, 2010 at 12:27 PM, News123 wrote: > Hi, > > > On 07/31/2010 11:04 AM, Matteo Landi wrote: >> What are the messages one should really care about while evaluating >> its code using pylint? It's easy to get 5 scored with a "lot of public >> methods" or bad named variables such as 'x' or 'y' .. Have you got any >> config file to share? > > > The most important ones are of course the errors. > Some of them might be false, but in our team we agreed, that no file is > allowed to report pylint errors. > This means > - just fixing errors (in most cases) > - rewriting code (in a few cases) > - masking errors with pylint directives in the source (some other few > errrors) > > > > > If you only want to see the errros, then just run > pylint -E filename.py > > Note: This is a rather new but very useful switch.. It doesn't exist > ? ?on Ubuntu 10.4's release pylint 0.19.0, but exists on pylint 0.21.1 > > > > Apart from that. You should discuss within your team, which > errors you'd like to have ignored and adapt the pylintrc. This > is a rather personal decision. > For one project we disiabled for example following warnings: > ## C0322 = "Operator not preceded by a space" > ## C0323 = "Operator not followed by a space" > ## C0324 = "Comma not followed by a space" > As we did not have time to rewrite all of the existing code, that > violated these rules. > We prefered to 'hide' these warnings in order to sett the more important > ones. > > On another new project however we did NOT comment therese rules > and decided, that all new code should follow these rules > > > We disabled some special global variables, which we'd like to have in > lower case > > const-rgx ==((specialvar)|(v_[a-z_][a-z0-9_]*)|([A-Z_][A-Z0-9_]*)|(__.*__))$ > > > you could also modify variables like > # Maximum number of attributes for a class (see R0902). > max-attributes=7 > > # Minimum number of public methods for a class (see R0903). > min-public-methods=2 > > # Maximum number of public methods for a class (see R0904). > max-public-methods=20 > > > For some graphics module functions for example we wanted to > be allowed to use variable names like x,y as they are > completely meaningful names for pixel coordinates. > > > so change the entry good-names > good-names=x,y,ex,Run,_ Thank you so much, these are very precious settings. > > > Hope, that this gave you some ideas > > > >> >> On Sat, Jul 31, 2010 at 2:48 AM, Dan Stromberg wrote: >>> >>> On Fri, Jul 30, 2010 at 12:18 PM, News123 wrote: >>>> >>>> On 07/30/2010 03:12 PM, wheres pythonmonks wrote: >>>>> I am starting to use pylint to look at my code and I see that it gives a >>>>> rating. >>>>> What values do experienced python programmers get on code not >>>>> targeting the benchmark? >>>>> >>>>> I wrote some code, tried to keep it under 80 characters per line, >>>>> reasonable variable names, and I got: >>>>> >>>>> 0.12 / 10. >>>>> >>>>> Is this a good score for one not targeting the benchmark? ?(pylint >>>>> running in default mode) >>>>> >>>> It's not a goodf core, but arrives easily if you never ran pylint before. >>>> With very little effort you should be able to be above 5 >>>> with a little more effort above 7 >>>> >>>> >>>>> Somewhat related: ?Is the backslash the only way to extend arguments >>>>> to statements over multiple lines? ?(e.g.) >>>> >>>> if you have an opening parenthesis, or bracked, then you don't need a >>>> backslash >>>> >>>> so instead of >>>> if longlonglonglonglonglonglonglongvar == \ >>>> ? ? ? ?otherlonglonglonglongvar: >>>> >>>> you could also write: >>>> >>>> if (longlonglonglonglonglonglonglongvar == >>>> ? ? ? ?otherlonglonglonglongvar): >>>> >>>> >>>> same works of course with asserts. >>>> >>>>> >>>>>>>> def f(x,y,z): return(x+y+z); >>>>> ... >>>>>>>> f(1,2, >>>>> ... 3) >>>>> 6 >>>>>>>> assert f(1,2,3)>0, >>>>> ? File "", line 1 >>>>> ? ? assert f(1,2,3)>0, >>>>> ? ? ? ? ? ? ? ? ? ? ?^ >>>>> SyntaxError: invalid syntax >>>>>>>> >>>>> >>>>> In the above, I could split the arguments to f (I guess b/c of the >>>>> parens) but not for assert. ?I could use a backslash, but I find this >>>>> ugly -- it that my only (best?) option? >>>>> >>>>> [I really like to assert my code to correctness and I like using the >>>>> second argument to assert, but this resulted in a lot of long lines >>>>> that I was unable to break except with an ugly backslash.] >>>>> >>>>> W >>>> >>> IMO, the important thing about pylint's scoring is that it's but one way of >>> many of producing good Python code. ?However, it's also one of the easier >>> ways of producing good python code. >>> I personally like to get my scores up near 10, by annotating in comments >>> about the few things that pylint flags that I can't just code around. ?This >>> requires jumping through some slightly silly hoops (EG the previously >>> mentioned "too few public methods", which my various container classes >>> always trip over), but going through this process is worthwhile for >>> highlighting the hoops pylint can detect that -aren't- so silly. >>> The one thing I like to leave unfixed is FIXME's - otherwise my preference >>> would be to go for a score of 10 for production code. >>> I also like to create a ./this-pylint script for my various projects, that >>> have global overrides - things like identifier rules, line length, and... ?I >>> don't get blanks instead of tabs. ?Blanks are fine if you don't understand >>> tabs (or think someone in the future who doesn't understand tabs will need >>> to work on your code), but tabs allow everyone to see code indented the way >>> -they- want to see it, not just the way the original author wanted to see >>> it. >>> This script (./this-pylint) will also save output from the test in a text >>> file, for make (or other dependency handling program) to use to avoid >>> re-pylint'ing unmodified code. ?It'll give an error typically, if pytlint >>> detects any errors other than FIXME's (excluding ones, as I mentioned >>> before, that have a comment disabling the warning, of course). >>> I'm more than a little sad that pylint doesn't seem to be moving to python 3 >>> in any big hurry. >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From navkirats at gmail.com Fri Aug 6 09:15:42 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 6 Aug 2010 18:45:42 +0530 Subject: Import python modules from sub-directories In-Reply-To: <55296.202.112.23.199.1281080591.squirrel@carnation.njnet.edu.cn> References: <53208D3C-40C5-46D6-BDF0-C03CD87994F8@gmail.com> <55296.202.112.23.199.1281080591.squirrel@carnation.njnet.edu.cn> Message-ID: On 06-Aug-2010, at 1:13 PM, ?? wrote: > > >> Hi guys, >> >> I am new to python and would like to import certain classes in sub-directories of the >> working directory. I was wondering how will I be able to achieve this? >> >> Regards, >> Nav >> -- >> http://mail.python.org/mailman/listinfo/python-list > >> > > Please try "touch __init__.py" in sub-directories. > > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks, that worked : ) From sschwarzer at sschwarzer.net Fri Aug 6 09:37:04 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 06 Aug 2010 15:37:04 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <4C5C1000.3050102@sschwarzer.net> Hi DG, On 2010-08-06 14:28, DG wrote: > I've always thought of it as you don't compare strings with "is", you > *should* use == The reasoning is that you don't know if that string > instance is the only one in memory. I've heard as an implementation > detail, since strings are immutable, that Python will only create one > actual instance and just assign new references to it (your first x is > y example), but to compare equality it just makes sense to use "==", > not to ask if it is the same object in memory. Yes, you'd usually use == to compare strings. The use in the post presumably was to show the behavior when you use `is`; I guess it wasn't meant as an example for production code. :) I can imagine a case where you might want to compare a string with `is`: FORWARD = "forward" BACKWARD = "backward" ... def func(direction=FORWARD): if direction is FORWARD: ... elif direction is BACKWARD: ... else: ... in case you expect people to specifically use the constants you provided in the module. Here, the fact that FORWARD actually is the string "forward" might be considered an implementation detail. Using a string instead of an `object()` has the advantage that it makes usage in error messages easier. Actually, I've never seen such a use, as far as I remember. What do other people here think? Is the code above, which compares strings with `is`, bad style, and if yes, why? How would you write the code instead? > Plus, I believe the > "==" operator will check if the variables point to the same object. No, that's what `is` is for. > Using is/is not with None works well, because I believe there will > always only be 1 None object. Yes, and it avoids subtle bugs if someone overwrites `__eq__` in some class: >>> class AlwaysEqual(object): ... def __eq__(self, other): ... return True ... >>> always_equal = AlwaysEqual() >>> always_equal == None True >>> None == always_equal True >>> always_equal is None False Stefan From cournape at gmail.com Fri Aug 6 09:55:49 2010 From: cournape at gmail.com (David Cournapeau) Date: Fri, 6 Aug 2010 22:55:49 +0900 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: On Fri, Aug 6, 2010 at 8:39 PM, Roy Smith wrote: > In article , > ?David Cournapeau wrote: > >> > Yes, there are a few corner cases where valid C syntax has different >> > semantics in C and C++. ?But, they are very few. ?Calling C++ a superset >> > of C is essentially correct. >> >> This is only true if you limit yourself to C89 (as python seems to >> do). If ?you start using C99 (and lot of people do, if only because >> they don't realize it because gcc is quite relax about it), then >> almost no non trivial C code is valid C++ in my experience. > > I'm not following you. ?If anything, C99 makes C closer to C++. ?Can you > give me some examples of valid C99 which is not also valid C++? variable size array, the meaning of inline, etc... In addition to int f(void) vs int f(), legality vs illegality of p = malloc(n);, type of enum, keyword incompatibility (new, delete, etc...) which are already there in C89. I have yet seen a project where you could build C code with a C++ compiler - the only ones I know are specifically designed that way and it is painful. David From aleksandar27 at BRISIOVOnet.hr Fri Aug 6 09:58:02 2010 From: aleksandar27 at BRISIOVOnet.hr (alejandro) Date: Fri, 6 Aug 2010 15:58:02 +0200 Subject: Need help from someone that have PIL installed Message-ID: Can please someone run this little script that should output characters like ????? in an image. If it does it correctly can you tell me what OS, python version & PIL version you have? Or better if someone can tell me why this is not working properly on my PC? (Win XP, PIL 1.1.6., Python 2.6...) I don't recive any error it's just that the characters outputed in the image are not characters... more like symbols... # encoding:utf-8 from PIL import Image import ImageDraw import ImageFont img = Image.new("RGBA",(250,40)) #----------------------------------- making the image transparent pixdata = img.load() for y in xrange(img.size[1]): for x in xrange(img.size[0]): if pixdata[x, y] == (255, 255, 255, 255): pixdata[x, y] = (255, 255, 255, 0) #--------------------------------- drawing text draw = ImageDraw.Draw(img) arial = ImageFont.truetype("arial.ttf",32) # needs path to font, my font was in the same folder as the script string = "proba test ?????" draw.text((20,8),string ,font=arial, fill="red") # write img.save("img2.png", "PNG") From rdmoores at gmail.com Fri Aug 6 10:20:38 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 6 Aug 2010 07:20:38 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 18:47, Philip Semanchuk wrote: > > it's just a question of whether or not > the module in question exposes any kind of a version attribute. There's no > standard, unfortunately. The most popular convention seems to be via an > attribute called __version__, but I've also seen __VERSION__, VERSION, and > version. > Here's one more way: >>> import gmpy >>> gmpy.__version__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__version__' >>> >>> gmpy.version() '1.12' >>> Dick Moores From __peter__ at web.de Fri Aug 6 10:26:52 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 16:26:52 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: alejandro wrote: > Can please someone run this little script that should output characters > like ????? in an image. > If it does it correctly can you tell me what OS, python version & PIL > version you have? > Or better if someone can tell me why this is not working properly on my > PC? (Win XP, PIL 1.1.6., Python 2.6...) > I don't recive any error it's just that the characters outputed in the > image are not characters... more like symbols... > > # encoding:utf-8 > > from PIL import Image > import ImageDraw > import ImageFont # the last tuple is the background color img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) > draw = ImageDraw.Draw(img) > arial = ImageFont.truetype("arial.ttf",32) # needs path to font, my font > was in the same folder as the script # I think that the PIL can cope with unicode, so add a u-prefix here: text = u"proba test ?????" draw.text((20,8), text ,font=arial, fill="red") > # write > img.save("img2.png", "PNG") Peter From jldunn2000 at gmail.com Fri Aug 6 10:32:57 2010 From: jldunn2000 at gmail.com (loial) Date: Fri, 6 Aug 2010 07:32:57 -0700 (PDT) Subject: How to read large amounts of output via popen References: <9fe7d6b5-7bbd-4453-8cf3-99d6e1260325@i31g2000yqm.googlegroups.com> Message-ID: Ok, thats great. Thanks for the very elegant solution(s) On 6 Aug, 13:44, Nobody wrote: > On Fri, 06 Aug 2010 02:06:29 -0700, loial wrote: > > I need to read a large amount of data that is being returned in > > standard output by a shell script I am calling. > > > (I think the script should really be writing to a file but I have no > > control over that) > > If the script is writing to stdout, you get to decide whether its stdout > is a pipe, file, tty, etc. > > > Currently I have the following code. It seeems to work, however I > > suspect this may not work with large amounts of standard output. > > process=subprocess.Popen(['myscript', 'param1'], > > shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > > cmdoutput=process.communicate() > > It's certainly not the best way to read large amounts of output. > Unfortunately, better solutions get complicated when you need to read more > than one of stdout and stderr, or if you also need to write to stdin. > > If you only need stdout, you can just read from process.stdout in a loop. > You can leave stderr going to wherever the script's stderr goes (e.g. the > terminal), or redirect it to a file. > > If you really do need both stdout and stderr, then you either need to > enable non-blocking I/O, or use a separate thread for each stream, or > redirect at least one of them to a file. > > FWIW, Popen.communicate() uses non-blocking I/O on Unix and separate > threads on Windows (the standard library doesn't include a mechanism to > enable non-blocking I/O on Windows). > > > What is the best way to read a large amount of data from standard > > output and write to a file? > > For this case, the best way is to just redirect stdout to a file, rather > than passing it through the script, i.e.: > > ? ? ? ? outfile = open('outputfile', 'w') > ? ? ? ? process = subprocess.call(..., stdout = outfile) > ? ? ? ? outfile.close() From aleksandar27 at BRISIOVOnet.hr Fri Aug 6 10:37:01 2010 From: aleksandar27 at BRISIOVOnet.hr (alejandro) Date: Fri, 6 Aug 2010 16:37:01 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: > # the last tuple is the background color > img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) Thank you for this.... > # I think that the PIL can cope with unicode, so add a u-prefix here: > text = u"proba test ?????" > draw.text((20,8), text ,font=arial, fill="red") Nope i gives: SyntaxError: (unicode error) 'utf8' codec can't decode byte 0x9e in position 0: unexpected code byte and without the encoding : SyntaxError: Non-ASCII character '\x9e' in file C:\Documents and Settings\Perc\My Documents\NetBeansProjects\venus_header\src\venus_header.py on line 16, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details From __peter__ at web.de Fri Aug 6 10:51:16 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 16:51:16 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: alejandro wrote: >> # the last tuple is the background color >> img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) > Thank you for this.... > >> # I think that the PIL can cope with unicode, so add a u-prefix here: >> text = u"proba test ?????" >> draw.text((20,8), text ,font=arial, fill="red") > > Nope i gives: > SyntaxError: (unicode error) 'utf8' codec can't decode byte 0x9e in > position 0: unexpected code byte > > and without the encoding : > SyntaxError: Non-ASCII character '\x9e' in file C:\Documents and > Settings\Perc\My > Documents\NetBeansProjects\venus_header\src\venus_header.py on line 16, > but no encoding declared; see http://www.python.org/peps/pep-0263.html for > details Make sure that # encoding:utf-8 is the first line of your script, details and fineprint here: http://www.python.org/dev/peps/pep-0263/ Peter From pruebauno at latinmail.com Fri Aug 6 10:51:22 2010 From: pruebauno at latinmail.com (nn) Date: Fri, 6 Aug 2010 07:51:22 -0700 (PDT) Subject: new to python - trouble calling a function from another function References: Message-ID: <3f1c8f38-931c-4da7-83d8-d2c2f14e6611@i24g2000yqa.googlegroups.com> On Aug 5, 2:01?pm, Daniel Urban wrote: > > I'm building an elevator simulator for a class assignment. I recently ran > > into a roadblock and don't know how to fix it. For some reason, in my > > checkQueue function below, the call to self.goUp() is never executed. It is > > on the last line of code I pasted in. I can put print statements before and > > after the call and I have a print statement in goUp() itself. ?Only the > > print statements before and after the call are executed. The one inside > > goUp() is never executed because goUp() never seems to be executed. How can > > that be? I don't get any errors when the script executes. Surely this isn't > > some limitation I'm encountering? > > I think the self.goUp() call is executed, the goUp function gets > called, returns a generator object (because goUp is a generator > function), then you don't use that generator object for anything. > > Daniel Brandon, this example might help you understand the problem: >>> def g(): print('p1') yield 2 print('p3') >>> g() >>> b=g() >>> next(b) p1 2 >>> next(b) p3 Traceback (most recent call last): File "", line 1, in next(b) StopIteration >>> From wolftracks at invalid.com Fri Aug 6 11:00:55 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 08:00:55 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: >> I would think there are some small time and big time Python players who sell >> executable versions of their programs for profit? > > Yes. What's your point? That someone must know how to distribute them without having the source code ripped off. > >> disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils >> might have been part of it. > > distutils. > > http://docs.python.org/library/distutils.html I don't see ;how distutils is going to solve this problem. Are you suggesting the program should be packaged? Why? I can just send it to him as py code. distutils looks like it's for library modules, e.g., functions like math. > >> So how does one keep a non-Python user in lock step with my setup, so these >> problems don't arise? I don't even want to think about having him uninstall >> and re-install. :-) Although maybe he could do it without making matters >> worse. > > That's going to hinge on what your dependencies are. > > Geremy Condra From philip at semanchuk.com Fri Aug 6 11:09:17 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Fri, 6 Aug 2010 11:09:17 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: <6DA63311-7A1B-4C80-B8C0-5F89CA217B03@semanchuk.com> On Aug 6, 2010, at 10:20 AM, Richard D. Moores wrote: > On Thu, Aug 5, 2010 at 18:47, Philip Semanchuk > wrote: >> >> it's just a question of whether or not >> the module in question exposes any kind of a version attribute. >> There's no >> standard, unfortunately. The most popular convention seems to be >> via an >> attribute called __version__, but I've also seen __VERSION__, >> VERSION, and >> version. >> > Here's one more way: >>>> import gmpy >>>> gmpy.__version__ > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '__version__' >>>> >>>> gmpy.version() > '1.12' That's the nice thing about standards -- there are so many to choose from! =) Thanks for pointing that out; I'll update my code. bye Philip From __peter__ at web.de Fri Aug 6 11:14:07 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 17:14:07 +0200 Subject: Python Portability--Not very portable? References: Message-ID: W. eWatson wrote: >>> I would think there are some small time and big time Python players who >>> sell executable versions of their programs for profit? >> >> Yes. What's your point? > That someone must know how to distribute them without having the source > code ripped off. Yes, but he won't tell for fear of getting ripped off of his knowledge. From aleksandar27 at BRISIOVOnet.hr Fri Aug 6 11:22:32 2010 From: aleksandar27 at BRISIOVOnet.hr (alejandro) Date: Fri, 6 Aug 2010 17:22:32 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: > > Make sure that > > # encoding:utf-8 > > is the first line of your script, details and fineprint here: > > http://www.python.org/dev/peps/pep-0263/ > > Peter Tryed that... What was the output of my script on your computer? From wolftracks at invalid.com Fri Aug 6 11:27:43 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 08:27:43 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: I can't respond to otten directly, since he uses gmane. Here's my response. W. eWatson wrote: >>> >>> I would think there are some small time and big time Python players who >>> >>> sell executable versions of their programs for profit? >> >> >> >> Yes. What's your point? > > That someone must know how to distribute them without having the source > > code ripped off. Ott wrote? Yes, but he won't tell for fear of getting ripped off of his knowledge. Who won't tell? Why would I send you the py code, for example, if I wanted to protect it because of its importance? I'd put it in exe form and send it and allow you to input data to produce the desired result of the program. From __peter__ at web.de Fri Aug 6 11:44:05 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 17:44:05 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: alejandro wrote: >> Make sure that >> >> # encoding:utf-8 >> >> is the first line of your script, details and fineprint here: >> >> http://www.python.org/dev/peps/pep-0263/ >> >> Peter > > Tryed that... What happened? > What was the output of my script on your computer? $ python -V Python 2.6.4 $ python -c "import Image; print Image.VERSION" 1.1.6 $ cat draw_text.py # encoding:utf-8 from PIL import Image import ImageDraw import ImageFont img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) draw = ImageDraw.Draw(img) FONT = "/usr/share/fonts/truetype/msttcorefonts/arial.ttf" arial = ImageFont.truetype(FONT, 32) text = u"proba test ?????" print repr(text) draw.text((20,8), text, font=arial, fill="red") img.save("tmp.png") $ python draw_text.py u'proba test \xbe\xe6\xe8\xf0\xb9' The image looks as expected. Peter From __peter__ at web.de Fri Aug 6 12:03:04 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 18:03:04 +0200 Subject: Python Portability--Not very portable? References: Message-ID: W. eWatson wrote: > I can't respond to otten directly, since he uses gmane. Here's my > response. > > W. eWatson wrote: > > >>> >>> I would think there are some small time and big time Python > players who > >>> >>> sell executable versions of their programs for profit? > >> >> > >> >> Yes. What's your point? > > > That someone must know how to distribute them without having the > > > source code ripped off. > Ott wrote? > Yes, but he won't tell for fear of getting ripped off of his knowledge. > > > Who won't tell? The the guy who knows how to distribute the source code without having it ripped off... Seriously, I try to make a joke once in a while, usually with devastating results. The idea you were meant to take away was that once you start thinking about a protection scheme there is always a next step until you reach the point where your software, say, is completely safe, but also completely unusable. Had Guido started the language in that mindset there would be no Python for you to worry about its ripp-off safety. > Why would I send you the py code, for example, if I > wanted to protect it because of its importance? Because if you think again you may find that it's not as important as you think? > I'd put it in exe form > and send it and allow you to input data to produce the desired result of > the program. There is no analog in python, and if you cannot concentrate on your honest customers the only option that offers reasonable "safety" would be to turn your application into web service. Peter From aahz at pythoncraft.com Fri Aug 6 12:10:24 2010 From: aahz at pythoncraft.com (Aahz) Date: 6 Aug 2010 09:10:24 -0700 Subject: Checking that 2 pdf are identical (md5 a solution?) References: <58d8ce50-35b1-4a0a-8588-ed7c19a7d349@w30g2000yqw.googlegroups.com> Message-ID: In article , rlevesque wrote: > >Given your expertise I will not be able to 'repay' you by helping on >Python problems but if you ever need help with SPSS related problems I >will be pleased to provide the assistance you need. Generally speaking, the community philosophy is "pay forward" -- help someone else who needs it (either here or somewhere else). When everyone helps other people, it all evens out. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From nawabadeel at gmail.com Fri Aug 6 12:14:00 2010 From: nawabadeel at gmail.com (Muhammad Adeel) Date: Fri, 6 Aug 2010 09:14:00 -0700 (PDT) Subject: Smith-Waterman Algorithm in Python Message-ID: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> Hi, Does any one about any implementation of classical Smith Waterman local alignment algorithm and it's variants for aligning natural language text? thanks From fetchinson at googlemail.com Fri Aug 6 12:54:14 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 6 Aug 2010 18:54:14 +0200 Subject: Smith-Waterman Algorithm in Python In-Reply-To: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> Message-ID: > Does any one about any implementation of classical Smith Waterman > local alignment algorithm and it's variants for aligning natural > language text? Please see http://tinyurl.com/2wy43fh Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From thomas at jollans.com Fri Aug 6 12:55:46 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 06 Aug 2010 18:55:46 +0200 Subject: Need help from someone that have PIL installed In-Reply-To: References: Message-ID: <4C5C3E92.9090008@jollans.com> On 08/06/2010 04:37 PM, alejandro wrote: > >> # the last tuple is the background color >> img = Image.new("RGBA",(300, 50), (0, 0, 0, 0)) > Thank you for this.... > >> # I think that the PIL can cope with unicode, so add a u-prefix here: >> text = u"proba test ?????" >> draw.text((20,8), text ,font=arial, fill="red") > > Nope i gives: > SyntaxError: (unicode error) 'utf8' codec can't decode byte 0x9e in position > 0: unexpected code byte Is the file, which you claim is UTF-8 encoded, actually UTF-8 encoded? If you're not sure, explicitly tell your text editor to save the file as UTF-8, and then try again. > > and without the encoding : > SyntaxError: Non-ASCII character '\x9e' in file C:\Documents and > Settings\Perc\My Documents\NetBeansProjects\venus_header\src\venus_header.py > on line 16, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details > > > From ppearson at nowhere.invalid Fri Aug 6 13:20:30 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 6 Aug 2010 17:20:30 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> Message-ID: <8c2uiuFg9bU1@mid.individual.net> On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: [snip] > I can imagine a case where you might want to compare a > string with `is`: > > FORWARD = "forward" > BACKWARD = "backward" > > ... > > def func(direction=FORWARD): > if direction is FORWARD: > ... > elif direction is BACKWARD: > ... > else: > ... > > in case you expect people to specifically use the constants > you provided in the module. Here, the fact that FORWARD > actually is the string "forward" might be considered an > implementation detail. Using a string instead of an > `object()` has the advantage that it makes usage in error > messages easier. > > Actually, I've never seen such a use, as far as I remember. > What do other people here think? Is the code above, which > compares strings with `is`, bad style, and if yes, why? How > would you write the code instead? Hey, that's a cute example, but . . . what a trap! Is it possible to document the use-the-object-not-the-string requirement loudly enough that people won't get caught? -- To email me, substitute nowhere->spamcop, invalid->net. From debatem1 at gmail.com Fri Aug 6 13:31:16 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 10:31:16 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 8:00 AM, W. eWatson wrote: > >>> I would think there are some small time and big time Python players who >>> sell >>> executable versions of their programs for profit? >> >> Yes. What's your point? > > That someone must know how to distribute them without having the source code > ripped off. I've never seen a code obfuscation scheme I thought did the job the whole way, including compiling C, and Python bytecode is significantly easier to turn back into something resembling the original source (YMMV, I suppose). Also, if you don't know about common tools like distutils, the odds are pretty good that it isn't your code itself that is valuable to you- you're probably more interested in protecting your idea about what the code should do. At least for now, that's outside of the scope of technical solutions- discuss it with a lawyer, not a programmer. >> >>> disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and >>> disutils >>> might have been part of it. >> >> distutils. >> >> http://docs.python.org/library/distutils.html > > I don't see ;how distutils is going to solve this problem. Are you > suggesting the program should be packaged? Why? I can just send it to him as > py code. distutils looks like it's for library modules, e.g., functions like > math. ...no. Distutils is handy because you could just bundle your dependencies and hand them an easy-to-install package, which would be a quick way to get everybody on the same page. Of course, depending on the licenses those dependencies are under you might want to do even more talking to a lawyer than I've previously suggested before you go about trying to sell that bundle- I'm sure you wouldn't want to 'rip off' great free projects like python and numpy. Geremy Condra From wolftracks at invalid.com Fri Aug 6 13:35:38 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 10:35:38 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On 8/6/2010 9:03 AM, Peter Otten wrote: ... > > Seriously, I try to make a joke once in a while, usually with devastating > results. The idea you were meant to take away was that once you start > thinking about a protection scheme there is always a next step until you > reach the point where your software, say, is completely safe, but also > completely unusable. Had Guido started the language in that mindset there > would be no Python for you to worry about its ripp-off safety. > >> Why would I send you the py code, for example, if I >> wanted to protect it because of its importance? > > Because if you think again you may find that it's not as important as you > think? > >> I'd put it in exe form >> and send it and allow you to input data to produce the desired result of >> the program. > > There is no analog in python, and if you cannot concentrate on your honest > customers the only option that offers reasonable "safety" would be to turn > your application into web service. > > Peter So you think Python is part of open software in terms of distributing a "product"? So I should stick to C, where one can distribute programs w/o revealing code details, and having a customer compile the code? It's been awhile since I've used Linux or Unix, but I think there's a lot of commercial code out there dependent upon it, and the users do not have to compile anything. From prakash.stack at gmail.com Fri Aug 6 13:44:35 2010 From: prakash.stack at gmail.com (prakash jp) Date: Fri, 6 Aug 2010 23:14:35 +0530 Subject: python interview quuestions Message-ID: Hi all, I would like to aquint myself with Python Interview questions . I am a Python Scripter, so if u could orient the pointers in the same direction it would be very handy Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Fri Aug 6 13:47:48 2010 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 06 Aug 2010 10:47:48 -0700 Subject: python interview quuestions In-Reply-To: References: Message-ID: <4C5C4AC4.6070005@islandtraining.com> On 08/06/2010 10:44 AM, prakash jp wrote: > Hi all, > I would like to aquint myself with Python Interview questions . I am a > Python Scripter, so if u could orient the pointers in the same > direction it would be very handy > Regards Huh??? From wolftracks at invalid.com Fri Aug 6 13:54:04 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 10:54:04 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On 8/5/2010 6:47 PM, Philip Semanchuk wrote: > > On Aug 5, 2010, at 8:55 PM, W. eWatson wrote: > >> It's been awhile since I've used python, and I recall there is a way >> to find the version number from the IDLE command line prompt. dir, >> help, __version.__? > > Hi Wayne, > FYI it's got nothing to do with IDLE, it's just a question of whether or > not the module in question exposes any kind of a version attribute. > There's no standard, unfortunately. The most popular convention seems to > be via an attribute called __version__, but I've also seen __VERSION__, > VERSION, and version. > > Here's some code that I wrote that you might find useful. It's from a > setup.py and it checks a list of modules on which our project depends to > see if (a) they're installed and (b) if the version installed is > adequate. In the snippet below, dependencies is a list of custom classes > that represent modules we need (e.g. numpy). > > > # Try each module > for dependency in dependencies: > try: > __import__(dependency.name) > except ImportError: > # Uh oh! > dependency.installed = None > else: > # The module loaded OK. Get a handle to it and try to extract > # version info. > # Many Python modules follow the convention of providing their > # version as a string in a __version__ attribute. > module = sys.modules[dependency.name] > > # This is what I default to. > dependency.installed = "[version unknown]" > > for attribute_name in ("__version__", "__VERSION__", "VERSION", > "version"): > if hasattr(module, attribute_name): > dependency.installed = getattr(module, attribute_name) > break > > Hope this helps a little, > Philip > Thanks. I'll look into it. From wolftracks at invalid.com Fri Aug 6 13:58:24 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 10:58:24 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On 8/6/2010 10:31 AM, geremy condra wrote: > On Fri, Aug 6, 2010 at 8:00 AM, W. eWatson wrote: >> >>>> I would think there are some small time and big time Python players who >>>> sell >>>> executable versions of their programs for profit? >>> >>> Yes. What's your point? >> >> That someone must know how to distribute them without having the source code >> ripped off. > > I've never seen a code obfuscation scheme I thought did the job the > whole way, including compiling C, and Python bytecode is significantly > easier to turn back into something resembling the original source > (YMMV, I suppose). Also, if you don't know about common tools like > distutils, the odds are pretty good that it isn't your code itself > that is valuable to you- you're probably more interested in protecting > your idea about what the code should do. At least for now, that's > outside of the scope of technical solutions- discuss it with a lawyer, > not a programmer. > >>> >>>> disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and >>>> disutils >>>> might have been part of it. >>> >>> distutils. >>> >>> http://docs.python.org/library/distutils.html >> >> I don't see ;how distutils is going to solve this problem. Are you >> suggesting the program should be packaged? Why? I can just send it to him as >> py code. distutils looks like it's for library modules, e.g., functions like >> math. > > ...no. Distutils is handy because you could just bundle your > dependencies and hand them an easy-to-install package, which would be > a quick way to get everybody on the same page. Of course, depending on > the licenses those dependencies are under you might want to do even > more talking to a lawyer than I've previously suggested before you go > about trying to sell that bundle- I'm sure you wouldn't want to 'rip > off' great free projects like python and numpy. > > Geremy Condra Yes, code reversal programs have been around for many, many decades. Try one on MS Word or Adobe Acrobat. :-) Is there a complete illustration of using disutils? Our only dependencies are on Python Org material. We use no commercial or licensed code. From __peter__ at web.de Fri Aug 6 14:05:17 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Aug 2010 20:05:17 +0200 Subject: Python Portability--Not very portable? References: Message-ID: W. eWatson wrote: > So you think Python is part of open software in terms of distributing a > "product"? So I should stick to C, where one can distribute programs w/o > revealing code details, and having a customer compile the code? It's No, I'm trying to make you reconsider what you're going to protect rather than how. Aren't your customers more interested in using your software rather than tinker with it? From tjreedy at udel.edu Fri Aug 6 14:20:45 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 06 Aug 2010 14:20:45 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On 8/6/2010 5:27 AM, Richard D. Moores wrote: > So there would be a different implementation for each operating > system? One for Windows, one for linux? Or one for Vista and one for > XP? I'm just trying to clarify what is meant by "implementation". Different version of CPython (that string caching bit has changed in the past) and CPython versus Jython, PyPy, IronPython, Cython, etc. -- Terry Jan Reedy From cmpython at gmail.com Fri Aug 6 14:22:28 2010 From: cmpython at gmail.com (CM) Date: Fri, 6 Aug 2010 11:22:28 -0700 (PDT) Subject: Python Portability--Not very portable? References: Message-ID: On Aug 5, 9:50?pm, "W. eWatson" wrote: > In my on-again-off-again experience with Python for 18 months, > portability seems an issue. > > As an example, my inexperienced Python partner 30 miles away has gotten > out of step somehow. I think by installing a different version of numpy > than I use. I gave him a program we both use months ago, and he had no > trouble. (We both use IDLE on 2.5). I made a one character change to it > and sent him the new py file. He can't execute it. I doubt he has > changed anything in the intervening period. I'm curious: what was the one character change? And does your original program still work for him? Why did he install a different version of numpy if things were working for him? By the way, posting "x doesn't work" on a forum never gets you any help, because clairvoyance is not real :D. Posting actual error messages sample code does. > A further example. Months ago I decided to see if I could compile a > program to avoid such problems as above. I planned to satisfy that need, > and see if I could distribute some simple programs to non-Python > friends. I pretty well understand the idea,and got it working with a > small program. It seemed like a lot of manual labor to do it. As someone mentioned, you don't "compile" anything in Python. You can make a .exe file, though, using, as you know, py2exe. I find using GUI2Exe (which requires you have wxPython) to make things much easier and then if you want to be even fancier, use InnoSetup to make an installer. Once you get a working script in py2exe/GUI2Exe, it is usually a snap to make a new version of your .exe after changing your code a bit. As far as then updating your .exe files with your non-Python friends, you should search this newsgroup for Esky, which seems like a very nice idea for doing this very thing. Che From cmpython at gmail.com Fri Aug 6 14:24:57 2010 From: cmpython at gmail.com (CM) Date: Fri, 6 Aug 2010 11:24:57 -0700 (PDT) Subject: Python Portability--Not very portable? References: Message-ID: <9bf7870e-d0c8-492a-bcba-bfa018ffc159@x21g2000yqa.googlegroups.com> > As an example, my inexperienced Python partner 30 miles away has gotten > out of step somehow. I think by installing a different version of numpy > than I use. I gave him a program we both use months ago, and he had no > trouble. (We both use IDLE on 2.5). I made a one character change to it > and sent him the new py file. He can't execute it. I doubt he has > changed anything in the intervening period. I'm curious: what was the one character change? And does your original program still work for him? Why did he install a different version of numpy if things were working for him? By the way, posting "x doesn't work" on a forum never gets you any help, because clairvoyance is not real :D. Posting actual error messages sample code does. > A further example. Months ago I decided to see if I could compile a > program to avoid such problems as above. I planned to satisfy that need, > and see if I could distribute some simple programs to non-Python > friends. I pretty well understand the idea,and got it working with a > small program. It seemed like a lot of manual labor to do it. As someone mentioned, you don't "compile" anything in Python. You can make a .exe file, though, using, as you know, py2exe. I find using GUI2Exe (which requires you have wxPython) to make things much easier and then if you want to be even fancier, use InnoSetup to make an installer. Once you get a working script in py2exe/GUI2Exe, it is usually a snap to make a new version of your .exe after changing your code a bit. As far as then updating your .exe files with your non-Python friends, you should search this newsgroup for Esky, which seems like a very nice idea for doing this very thing. Che From prologic at shortcircuit.net.au Fri Aug 6 14:30:53 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 04:30:53 +1000 Subject: Perl -> Python unpack Message-ID: Hey all, Quick question for you Python enthusiasts that also happen to know Perl quite well... What does a* or A* translate to in Python when unpacking binary data with struct.unpack(...) ? cheers James -- -- James Mills -- -- "Problems are solved by method" From python.list at tim.thechases.com Fri Aug 6 14:32:08 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 06 Aug 2010 13:32:08 -0500 Subject: python interview quuestions In-Reply-To: References: Message-ID: <4C5C5528.5060608@tim.thechases.com> > I would like to aquint myself with Python Interview questions This came up a while ago: http://www.mail-archive.com/python-list at python.org/msg168961.html Most of that thread is still relevant (perhaps throw in some py3l questions too) -tkc From sschwarzer at sschwarzer.net Fri Aug 6 14:36:26 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 06 Aug 2010 20:36:26 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <8c2uiuFg9bU1@mid.individual.net> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> Message-ID: <4C5C562A.90702@sschwarzer.net> Hello Peter, On 2010-08-06 19:20, Peter Pearson wrote: > On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: > [snip] >> I can imagine a case where you might want to compare a >> string with `is`: >> >> FORWARD = "forward" >> BACKWARD = "backward" >> >> ... >> >> def func(direction=FORWARD): >> if direction is FORWARD: >> ... >> elif direction is BACKWARD: >> ... >> else: >> ... >> [...] > Hey, that's a cute example, Thanks! > but . . . what a trap! Is it > possible to document the use-the-object-not-the-string requirement > loudly enough that people won't get caught? That's a good question, actually that's the nagging problem I also have with the approach. In production code I might write # Use _these_ objects to indicate directions, not string # constants with the same value. FORWARD = "forward" BACKWARD = "backward" However, that won't help if people import the module and see the strings under "global data" and so assume they're "just strings". Moreover, if you have to write such a comment for every use of the idiom the conciseness of the approach vanishes. Another view at the matter would be to let clients of the module find out their mistake by unit tests. But of course that's somewhat doubtful as the intention should be to write robust instead of bug-inviting code. I wonder if there's a way to have both the "cuteness" of the string constants _and_ more robustness. Stefan From prologic at shortcircuit.net.au Fri Aug 6 14:45:11 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 04:45:11 +1000 Subject: python interview quuestions In-Reply-To: <4C5C5528.5060608@tim.thechases.com> References: <4C5C5528.5060608@tim.thechases.com> Message-ID: On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >> I would like to aquint myself with Python Interview questions > > This came up a while ago: > > http://www.mail-archive.com/python-list at python.org/msg168961.html > > Most of that thread is still relevant (perhaps throw in some py3l questions > too) A common thing you can do in interviews is ask your interviewee to write (in Python) a solution to the "FizzBuzz" problem. Any good competent Python programmer should be able to do this in 5-10mins (5 if you're good). cheers james -- -- James Mills -- -- "Problems are solved by method" From debatem1 at gmail.com Fri Aug 6 14:50:10 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 11:50:10 -0700 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 10:58 AM, W. eWatson wrote: > Is there a complete illustration of using disutils? Our only dependencies > are on Python Org material. We use no commercial or licensed code. http://tinyurl.com/3yhwjfj Geremy Condra From chris at simplistix.co.uk Fri Aug 6 15:06:00 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 06 Aug 2010 20:06:00 +0100 Subject: A useful, but painful, one-liner to edit money amounts In-Reply-To: <9b4bd0c2-8912-4a60-9a12-b7b8586aba84@i4g2000prf.googlegroups.com> References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> <9b4bd0c2-8912-4a60-9a12-b7b8586aba84@i4g2000prf.googlegroups.com> Message-ID: <4C5C5D18.3090101@simplistix.co.uk> DarkBlue wrote: > On Aug 5, 7:06 pm, Chris Withers wrote: >> Peter Otten wrote: >>>>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) >>> 'en_US.UTF8' >>>>>> print locale.currency(13535, grouping=True) >>> $13,535.00 >> Okay, so if I'm writing a wsgi app, and I want to format depending on >> the choices of the currently logged in users, what would you recommend? >> >> I can't do setlocale, since that would affect all users, and in a >> mult-threaded environment that would be bad. >> >> Does that mean the whole locale package is useless to all web-app builders? >> >> Chris > > from re import * > > class editmoney(float): > def __init__(self,mymoney): What does this have to do with my question about locales in multi-threaded environments? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From python.list at tim.thechases.com Fri Aug 6 15:11:54 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 06 Aug 2010 14:11:54 -0500 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <4C5C5E7A.5050203@tim.thechases.com> On 08/06/10 13:45, James Mills wrote: > On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >>> I would like to aquint myself with Python Interview questions >> >> This came up a while ago: >> >> http://www.mail-archive.com/python-list at python.org/msg168961.html >> >> Most of that thread is still relevant (perhaps throw in some py3l questions >> too) > > A common thing you can do in interviews is ask > your interviewee to write (in Python) a solution > to the "FizzBuzz" problem. Any good competent > Python programmer should be able to do this > in 5-10mins (5 if you're good). Another common thing you can do on a newsgroup is mention the "FizzBuzz" problem. Any good competent newsgroup will produce a multitude of proposed solutions, the majority of which will be wrong. ;-) -tkc From wolftracks at invalid.com Fri Aug 6 15:14:53 2010 From: wolftracks at invalid.com (W. eWatson) Date: Fri, 06 Aug 2010 12:14:53 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: I must be missing something. I tried this. (Windows, IDLE, Python 2.5) # Try each module import sys import numpy import scipy import string dependencies = "numyp", "scipy" for dependency in dependencies: try: __import__(dependency.name) except ImportError: # Uh oh! dependency.installed = None else: # The module loaded OK. Get a handle to it and try to extract # version info. # Many Python modules follow the convention of providing their # version as a string in a __version__ attribute. module = sys.modules[dependency.name] # This is what I default to. dependency.installed = "[version unknown]" for attribute_name in ("__version__", "__VERSION__", "VERSION", "version"): if hasattr(module, attribute_name): dependency.installed = getattr(module, attribute_name) break The result was this. Traceback (most recent call last): File "C:/Users/Wayne/Sandia_Meteors/Trajectory_Estimation/dependency_code", line 10, in __import__(dependency.name) AttributeError: 'str' object has no attribute 'name' From prologic at shortcircuit.net.au Fri Aug 6 15:19:16 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 05:19:16 +1000 Subject: python interview quuestions In-Reply-To: <4C5C5E7A.5050203@tim.thechases.com> References: <4C5C5528.5060608@tim.thechases.com> <4C5C5E7A.5050203@tim.thechases.com> Message-ID: On Sat, Aug 7, 2010 at 5:11 AM, Tim Chase wrote: > Another common thing you can do on a newsgroup is mention the "FizzBuzz" > problem. ?Any good competent newsgroup will produce a multitude of proposed > solutions, the majority of which will be wrong. ;-) That's actually a very good point! Someone should post this very problem to this newsgroups/list and see how many active python programmers here actually "get it right" :) *evil grin* --james -- -- James Mills -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Fri Aug 6 15:28:39 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 6 Aug 2010 12:28:39 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 12:14 PM, W. eWatson wrote: > I must be missing something. I tried this. (Windows, IDLE, Python 2.5) > # Try each module > import sys > import numpy > import scipy > import string > > dependencies = "numyp", "scipy" > for dependency in dependencies: > ? ?try: > ? ? ? ?__import__(dependency.name) > ? ?except ImportError: > ? ? ? ?# Uh oh! > ? ? ? ?dependency.installed = None > ? ?else: > ? ? ? ?# The module loaded OK. Get a handle to it and try to extract > ? ? ? ?# version info. > ? ? ? ?# Many Python modules follow the convention of providing their > ? ? ? ?# version as a string in a __version__ attribute. > ? ? ? ?module = sys.modules[dependency.name] > > ? ? ? ?# This is what I default to. > ? ? ? ?dependency.installed = "[version unknown]" > > ? ? ? ?for attribute_name in ("__version__", "__VERSION__", "VERSION", > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "version"): > ? ? ? ? ? ?if hasattr(module, attribute_name): > ? ? ? ? ? ? ? ?dependency.installed = getattr(module, attribute_name) > ? ? ? ? ? ? ? ?break > > The result was this. > Traceback (most recent call last): > ?File "C:/Users/Wayne/Sandia_Meteors/Trajectory_Estimation/dependency_code", > line 10, in > ? ?__import__(dependency.name) > AttributeError: 'str' object has no attribute 'name' > -- Try reading the code, not just copying and pasting. dependencies isn't supposed to be a list of strings. It's a list of objects (at least) a name and an installed attribute. > http://mail.python.org/mailman/listinfo/python-list > From tgrav at mac.com Fri Aug 6 15:31:36 2010 From: tgrav at mac.com (Tommy Grav) Date: Fri, 06 Aug 2010 15:31:36 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Aug 6, 2010, at 3:14 PM, W. eWatson wrote: > I must be missing something. I tried this. (Windows, IDLE, Python 2.5) > # Try each module > import sys > import numpy > import scipy > import string > > dependencies = "numyp", "scipy" > for dependency in dependencies: > try: > __import__(dependency.name) > except ImportError: > # Uh oh! > dependency.installed = None > else: > # The module loaded OK. Get a handle to it and try to extract > # version info. > # Many Python modules follow the convention of providing their > # version as a string in a __version__ attribute. > module = sys.modules[dependency.name] > > # This is what I default to. > dependency.installed = "[version unknown]" > > for attribute_name in ("__version__", "__VERSION__", "VERSION", > "version"): > if hasattr(module, attribute_name): > dependency.installed = getattr(module, attribute_name) > break > > The result was this. > Traceback (most recent call last): > File "C:/Users/Wayne/Sandia_Meteors/Trajectory_Estimation/dependency_code", line 10, in > __import__(dependency.name) > AttributeError: 'str' object has no attribute 'name' > -- > http://mail.python.org/mailman/listinfo/python-list dependencies = "numpy", "scipy" is a tuple of two strings, when you do your for loop you first get "numpy" (a string) and it does not have a .name attribute. Tommy From ethan at stoneleaf.us Fri Aug 6 15:34:24 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 06 Aug 2010 12:34:24 -0700 Subject: easy question on parsing python: "is not None" In-Reply-To: <4C5C562A.90702@sschwarzer.net> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <4C5C562A.90702@sschwarzer.net> Message-ID: <4C5C63C0.9060508@stoneleaf.us> Stefan Schwarzer wrote: > Hello Peter, > > On 2010-08-06 19:20, Peter Pearson wrote: >> On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: >> [snip] >>> I can imagine a case where you might want to compare a >>> string with `is`: >>> >>> FORWARD = "forward" >>> BACKWARD = "backward" >>> >>> ... >>> >>> def func(direction=FORWARD): >>> if direction is FORWARD: >>> ... >>> elif direction is BACKWARD: >>> ... >>> else: >>> ... >>> [...] > >> Hey, that's a cute example, > > Thanks! > >> but . . . what a trap! Is it >> possible to document the use-the-object-not-the-string requirement >> loudly enough that people won't get caught? > > That's a good question, actually that's the nagging problem > I also have with the approach. > > In production code I might write > > # Use _these_ objects to indicate directions, not string > # constants with the same value. > FORWARD = "forward" > BACKWARD = "backward" > > However, that won't help if people import the module and see > the strings under "global data" and so assume they're "just > strings". Moreover, if you have to write such a comment for > every use of the idiom the conciseness of the approach > vanishes. > > Another view at the matter would be to let clients of the > module find out their mistake by unit tests. But of course > that's somewhat doubtful as the intention should be to write > robust instead of bug-inviting code. > > I wonder if there's a way to have both the "cuteness" of the > string constants _and_ more robustness. > > Stefan Instead of using 'is' use '=='. Maybe not as cute, but definitely more robust! ~Ethan~ From albert at spenarnc.xs4all.nl Fri Aug 6 15:41:28 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 06 Aug 2010 19:41:28 GMT Subject: Easy questions from a python beginner References: <4c495b50$0$28634$c3e8da3@news.astraweb.com> Message-ID: In article <4c495b50$0$28634$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Thu, 22 Jul 2010 21:23:05 -0700, Stephen Hansen wrote: > >> On 7/22/10 7:47 PM, wheres pythonmonks wrote: >[...] >>> The truth is that I don't intend to use these approaches in anything >>> serious. However, I've been known to do some metaprogramming from time >>> to time. >> >> Depending on how you define "metaprogramming", Python is pretty >> notoriously ill-suited towards the task (more, its basically considered >> a feature it doesn't let you go there) -- or, it allows you to do vast >> amounts of stuff with its few dark magic hooks. I've never had a >> satisfying definition of metaprogramming that more then 50% of any group >> agree with, so I'm not sure which you're looking for. :) > >I disagree strongly at your characterisation that Python is notorious for >being ill-suited towards metaprogramming. I'd say the complete opposite >-- what is considered dark and scary metaprogramming tasks in other >languages is considered too ordinary to even mention in Python. > >If you have a class that defines a single member (or attribute in Python >terminology) "spam", and you want to add a second "ham" to a specific >instance, such a thing is either deep, dark metaprogramming in some >languages, if not outright impossible. In Python it is not even >noteworthy: > >instance.ham = "something" # *yawns* > >Recently there was a thread started by some Java or C++ refugee who was >distressed about attribute access in Python, because it made >metaprogramming frighteningly easy: > >http://mail.python.org/pipermail/python-list/2010-June/1248029.html > >My response at the time was: Python makes metaprogramming *easy*: > >http://mail.python.org/pipermail/python-list/2010-June/1248053.html > >I can't imagine how he would have reacted if we had showed him how easy >it is to monkey-patch built-in functions... > >[...] >> But! What it doesn't let you do is get clever with syntax and write a >> sort of "simplified" or domain specific language to achieve certain >> sorts of repetitive tasks quickly. You always end up writing normal >> Python that looks like all other Python. > >Exactly... 90% of the time that you think you want a DSL, Python beat you >to it. > >It is true that other languages (like Lisp, or Forth) allow you to write >your own syntax. That's incredibly powerful, but it also has serious >costs. If you can define your own syntax, that means every piece of code >you look at is potentially a different language. The answer is, of course, discipline. I'm a Forth programmer and I morf Forth into an assembler. Now some sources become assembler sources and one should be very adamant about it. I've written a Perl interpreter for those sources, and a Python interpreter would be even easier. If I'm doing Python, I don't miss macro possibilities, but sometimes my code gets repetitive. If I ever get bored by repetition, there is m4. m4 < aap.pym > aap.py python aap.py (See my site below for Forth assemblers, and non-trivial m4 usage.) >-- >Steven Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From jjposner at optimum.net Fri Aug 6 16:07:42 2010 From: jjposner at optimum.net (John Posner) Date: Fri, 06 Aug 2010 16:07:42 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C5C6B8E.1070300@optimum.net> On 8/2/2010 11:00 PM, John Posner wrote: > On 7/31/2010 1:31 PM, John Posner wrote: >> >> Caveat -- there's another description of defaultdict here: >> >> http://docs.python.org/library/collections.html#collections.defaultdict >> >> ... and it's bogus. This other description claims that __missing__ is a >> method of defaultdict, not of dict. > > Following is a possible replacement for the bogus description. Comments > welcome. I intend to submit a Python doc bug, and I'd like to have a > clean alternative to propose. After some off-list discussion with Ethan Furman (many thanks!), the Python Doc bug is submitted: #9536 at bugs.python.org. -John From landa.martin at gmail.com Fri Aug 6 16:10:42 2010 From: landa.martin at gmail.com (Martin Landa) Date: Fri, 6 Aug 2010 13:10:42 -0700 (PDT) Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Message-ID: <8e7cd90c-1053-44e0-b0ce-ea95e2025a2c@d17g2000yqb.googlegroups.com> Hi, On Aug 5, 9:32?pm, Nobody wrote: > I don't know about methods, but it works for functions. > > > Sample code: > > > ? ? ... > > ? ? G_set_error_routine(byref(self._print_error)) > > This won't work; you have to be more explicit, e.g.: > > ? ? ? ? errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int)) > ? ? ? ? errfunc = errtype(print_error) > ? ? ? ? G_set_error_routine(errfunc) the C function is defined as G_set_error_routine = _libs['grass_gis. 7.0.svn'].G_set_error_routine G_set_error_routine.restype = None G_set_error_routine.argtypes = [CFUNCTYPE(UNCHECKED(c_int), String, c_int)] I defined in Python function print_error() def print_error(self, msg, type): print msg, type and errtype = CFUNCTYPE(UNCHECKED(c_int), String, c_int) errfunc = errtype(print_error) G_set_error_routine(errfunc) unfortunately the application crashes when print_error() is called from C library static void vfprint_error(int type, const char *template, va_list ap) { char buffer[2000]; /* G_asprintf does not work */ vsprintf(buffer, template, ap); G_debug(5, "print_error(): msg = \"%s\" type = %d", buffer, type); print_error(buffer, type); } Any idea how to solve it. Thanks, Martin From landa.martin at gmail.com Fri Aug 6 16:18:37 2010 From: landa.martin at gmail.com (Martin Landa) Date: Fri, 6 Aug 2010 13:18:37 -0700 (PDT) Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> <8e7cd90c-1053-44e0-b0ce-ea95e2025a2c@d17g2000yqb.googlegroups.com> Message-ID: <98c10bcc-40f9-4a2a-a187-1f1997aab7d4@z10g2000yqb.googlegroups.com> Hi, On Aug 6, 10:10?pm, Martin Landa wrote: > Any idea how to solve it. Thanks, Martin I overlooked note """ Make sure you keep references to CFUNCTYPE objects as long as they are used from C code. ctypes doesn?t, and if you don?t, they may be garbage collected, crashing your program when a callback is made. """ If I defined errtype and errfunc as global variable everything works. Thanks again for your help. Martin From debatem1 at gmail.com Fri Aug 6 16:28:53 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 13:28:53 -0700 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: On Fri, Aug 6, 2010 at 11:45 AM, James Mills wrote: > On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >>> I would like to aquint myself with Python Interview questions >> >> This came up a while ago: >> >> http://www.mail-archive.com/python-list at python.org/msg168961.html >> >> Most of that thread is still relevant (perhaps throw in some py3l questions >> too) > > A common thing you can do in interviews is ask > your interviewee to write (in Python) a solution > to the "FizzBuzz" problem. Any good competent > Python programmer should be able to do this > in 5-10mins (5 if you're good). > > cheers > james If I had to wait 5 minutes while a candidate tried to solve this problem I would not hire them. One minute, fine- maybe you're just a little rusty or nervous, or the rare person who has to back away from real-world programming concerns to deal with a trivial problem like this. If English isn't your native tongue I might double or even triple that. Otherwise, no way- I'm going to spend more time hanging over your head than you'll save me. Geremy Condra From prologic at shortcircuit.net.au Fri Aug 6 16:37:05 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 06:37:05 +1000 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: On Sat, Aug 7, 2010 at 6:28 AM, geremy condra wrote: > If I had to wait 5 minutes while a candidate tried to solve this > problem I would not hire them. Yes you do raise a valid point. It should really only take you a mere few seconds or so to write a solution to this. More over, it can be done in just a single line of Python. 7 if you're not very familiar with Python. cheers James -- -- James Mills -- -- "Problems are solved by method" From joncle at googlemail.com Fri Aug 6 17:10:35 2010 From: joncle at googlemail.com (Jon Clements) Date: Fri, 6 Aug 2010 14:10:35 -0700 (PDT) Subject: new to python - trouble calling a function from another function References: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> Message-ID: On 5 Aug, 16:15, Brandon McCombs wrote: > Jon Clements wrote: > > On 5 Aug, 08:25, Brandon McCombs wrote: > >> Hello, > > >> I'm building an elevator simulator for a class assignment. I recently > >> ran into a roadblock and don't know how to fix it. For some reason, in > >> my checkQueue function below, the call to self.goUp() is never executed. > >> It is on the last line of code I pasted in. I can put print statements > >> before and after the call and I have a print statement in goUp() itself. > >> ? Only the print statements before and after the call are executed. The > >> one inside goUp() is never executed because goUp() never seems to be > >> executed. How can that be? I don't get any errors when the script > >> executes. Surely this isn't some limitation I'm encountering? > > >> thanks > > >> sorry about the formatting > > >> --------------------------------------------- > >> class Elevator(Process): > >> def __init__(self,name): > >> ? ? ? ? Process.__init__(self,name=name) > >> ? ? ? ? self.numPassengers = 0 > >> ? ? ? ? self.passengerList = [] > >> ? ? ? ? self.passengerWaitQ = [] > >> ? ? ? ? self.currentFloor = 1 > >> ? ? ? ? self.idle = 1 > >> ? ? ? ? self.newPassengers = 0 > >> def goUp(self): > >> ? ? ? ? print "here" > >> ? ? ? ? bubbleSort(self.passengerList, len(self.passengerList)) > >> ? ? ? ? self.currentFloor += 1 > >> ? ? ? ? if len(self.passengerList) > 0: > >> ? ? ? ? ? ?for p in self.passengerList: > >> ? ? ? ? ? ? ? if self.currentFloor == p.destination: > >> ? ? ? ? ? ? ? ? yield (p.destination - self.currenteFloor) * TRAVELTIME, self > >> ? ? ? ? ? ? ? ? reactivate(p) > >> ? ? ? ? ? ? ? ? p.inBuilding() > >> ? ? ? ? ? ? ? else: > >> ? ? ? ? ? ? ? ? self.goUp() > > >> def checkQueue(self): > >> ? ? ? ? if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < > >> MAXCAPACITY: > >> ? ? ? ? if len(self.passengerWaitQ) < MAXCAPACITY: > >> ? ? ? ? ? ? self.newPassengers = len(self.passengerWaitQ) > >> ? ? ? ? else: > >> ? ? ? ? ? ? ?self.newPassengers = MAXCAPACITY - len(self.passengerList) > >> ? ? ? ? for i in range(0,self.newPassengers): > >> ? ? ? ? ? self.passengerList.append(self.passengerWaitQ.pop()) > >> ? ? ? ? self.goUp() > > > Hi Brandon, > > > Nice one at having a good crack at coding before posting! > > > From your posted code, I'm struggling to see what's trying to be > > taught to you for this class assignment. > > not relevant at this point > > > > > As a note it'll be worth reading PEP 8 regarding naming conventions, > > because it looks very Java-ish to me! > > ok but not relevant > > > > > (I might be taking too much a real-world approach in the following, > > but do with it as you will...) > > > I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere. > > Although what I'm thinking is that different Elevators will have > > different capacities and different floors they service. An Elevator is > > *not* going to know its number of passengers (the most it could do is > > capacity based on weight restrictions) therefore it's not going to > > know the number of new passengers on each floor either. > > okay but not relevant to the problem at hand > > > > > A couple of things that'd be worthwhile: > > > 1) Post the requirements for your assignment - what's it supposed to > > output etc... > > that isn't relevant for determining at the python level why a function > simply isn't being called > > > 2) Go find an elevator, take a pen and pad with you, and stand in it > > for 30 mins or so, and see how the real thing deals with situations > > and make notes. ie, does it queue requests, or decide to take the next > > nearest floor, when does it stop and open etc...? > > > hth > > > Jon. > > actually it doesn't help at all since you decided to focus on everything > but my actual question of why a function call wasn't working but rather > question the validity of the program itself Heard of something called 'sentences' that start with a capital letter that end with (mostly) a full stop? Anyway, what I suggested was that your design is massively flawed. You ask a group, that's friendly to newbies for help, and you receive advice... then "bitch" about it. Indeed, the intention was to make you re-think the whole program -- then you'd have learnt more. Focusing on one thing when it's the wrong design anyway is a *bad thing*. Remember, you've posted to a list that have members that have done 30+ years of programming in a professional role. Just my 2c, Jon. From luke.leighton at gmail.com Fri Aug 6 17:32:31 2010 From: luke.leighton at gmail.com (Luke Kenneth Casson Leighton) Date: Fri, 6 Aug 2010 22:32:31 +0100 Subject: HL7 v3 (XML) importer Message-ID: an HL7 v2 importer was written by john paulett, and it has been enhanced to support some of the HL7 v3 standard, which is XML-based. no dependencies are required: xml.sax is used so as to reduce the dependencies to purely python. additionally, as HL7 has versions/revisions, published data specifications were pulled from mirthcorp.com and transformed into python, automatically. HL7v3 revisions 2.1, 2.2, 2.3, 2.31, 2.4 and 2.5 are supported. there is still work to be carried out: MSH, PID, NTE, ORC, ORB and OBX are the presently supported segmentss, with a hard-coded assumption about the data hierarchy instead of using the same MessageFormat specifications that mirthcorp.com have written. this is likely to be corrected soon, but the project for which the code is being updated only requires "lab data imports", so support for other MessageFormats is not a high priority. in case anyone is interested, this hl7 library is to be used in gnumed, to be able to import laboratory data reports into the gnumed database. code is at: http://github.com/lkcl/hl7 i realise that this code is pretty specialist, but if you're looking around for free software libraries or applications that support HL7, http://mirthcorp.com is pretty much it, and mirth is pretty heavy-duty and forces a dependency of java and javascript for scripting, which may be of concern to some. hence, this smaller library is being created, in python. l. From debatem1 at gmail.com Fri Aug 6 17:47:10 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 14:47:10 -0700 Subject: new to python - trouble calling a function from another function In-Reply-To: References: <54ad7c8f-c2cc-4d00-a017-347ecaf401a5@k19g2000yqc.googlegroups.com> Message-ID: On Thu, Aug 5, 2010 at 8:15 AM, Brandon McCombs wrote: > Jon Clements wrote: >> >> On 5 Aug, 08:25, Brandon McCombs wrote: >>> >>> Hello, >>> >>> I'm building an elevator simulator for a class assignment. I recently >>> ran into a roadblock and don't know how to fix it. For some reason, in >>> my checkQueue function below, the call to self.goUp() is never executed. >>> It is on the last line of code I pasted in. I can put print statements >>> before and after the call and I have a print statement in goUp() itself. >>> ?Only the print statements before and after the call are executed. The >>> one inside goUp() is never executed because goUp() never seems to be >>> executed. How can that be? I don't get any errors when the script >>> executes. Surely this isn't some limitation I'm encountering? >>> >>> thanks >>> >>> sorry about the formatting >>> >>> --------------------------------------------- >>> class Elevator(Process): >>> def __init__(self,name): >>> ? ? ? ?Process.__init__(self,name=name) >>> ? ? ? ?self.numPassengers = 0 >>> ? ? ? ?self.passengerList = [] >>> ? ? ? ?self.passengerWaitQ = [] >>> ? ? ? ?self.currentFloor = 1 >>> ? ? ? ?self.idle = 1 >>> ? ? ? ?self.newPassengers = 0 >>> def goUp(self): >>> ? ? ? ?print "here" >>> ? ? ? ?bubbleSort(self.passengerList, len(self.passengerList)) >>> ? ? ? ?self.currentFloor += 1 >>> ? ? ? ?if len(self.passengerList) > 0: >>> ? ? ? ? ? for p in self.passengerList: >>> ? ? ? ? ? ? ?if self.currentFloor == p.destination: >>> ? ? ? ? ? ? ? ?yield (p.destination - self.currenteFloor) * TRAVELTIME, >>> self >>> ? ? ? ? ? ? ? ?reactivate(p) >>> ? ? ? ? ? ? ? ?p.inBuilding() >>> ? ? ? ? ? ? ?else: >>> ? ? ? ? ? ? ? ?self.goUp() >>> >>> def checkQueue(self): >>> ? ? ? ?if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < >>> MAXCAPACITY: >>> ? ? ? ?if len(self.passengerWaitQ) < MAXCAPACITY: >>> ? ? ? ? ? ?self.newPassengers = len(self.passengerWaitQ) >>> ? ? ? ?else: >>> ? ? ? ? ? ? self.newPassengers = MAXCAPACITY - len(self.passengerList) >>> ? ? ? ?for i in range(0,self.newPassengers): >>> ? ? ? ? ?self.passengerList.append(self.passengerWaitQ.pop()) >>> ? ? ? ?self.goUp() >> >> Hi Brandon, >> >> Nice one at having a good crack at coding before posting! >> >> From your posted code, I'm struggling to see what's trying to be >> taught to you for this class assignment. > > not relevant at this point > >> >> As a note it'll be worth reading PEP 8 regarding naming conventions, >> because it looks very Java-ish to me! > > ok but not relevant > >> >> (I might be taking too much a real-world approach in the following, >> but do with it as you will...) >> >> I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere. >> Although what I'm thinking is that different Elevators will have >> different capacities and different floors they service. An Elevator is >> *not* going to know its number of passengers (the most it could do is >> capacity based on weight restrictions) therefore it's not going to >> know the number of new passengers on each floor either. > > okay but not relevant to the problem at hand > >> >> A couple of things that'd be worthwhile: >> >> 1) Post the requirements for your assignment - what's it supposed to >> output etc... > > that isn't relevant for determining at the python level why a function > simply isn't being called > >> 2) Go find an elevator, take a pen and pad with you, and stand in it >> for 30 mins or so, and see how the real thing deals with situations >> and make notes. ie, does it queue requests, or decide to take the next >> nearest floor, when does it stop and open etc...? >> >> hth >> >> Jon. >> > > actually it doesn't help at all since you decided to focus on everything but > my actual question of why a function call wasn't working but rather question > the validity of the program itself This is too bad. You looked like you were all set to be the poster child for how to ask a good question here, and now you've blown it. Geremy Condra From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:13:50 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:13:50 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> Message-ID: <4c5c891d$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 17:20:30 +0000, Peter Pearson wrote: > On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: [snip] >> I can imagine a case where you might want to compare a string with >> `is`: >> >> FORWARD = "forward" >> BACKWARD = "backward" [...] >> Actually, I've never seen such a use, as far as I remember. What do >> other people here think? Is the code above, which compares strings with >> `is`, bad style, and if yes, why? How would you write the code instead? > > Hey, that's a cute example, but . . . what a trap! Is it possible to > document the use-the-object-not-the-string requirement loudly enough > that people won't get caught? Nope. People don't read documentation :) That's why I prefer to test for human-readable constants using equality, so if the caller prefers to call func(x, "forward") instead of func(x, FORWARD) it will still work. Or I use FOWARD = object() BACKWARDS = object() and force them to use my constants. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:23:05 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:23:05 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <4c5c8b49$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 05:28:40 -0700, DG wrote: > I've always thought of it as you don't compare strings with "is", you > *should* use == The reasoning is that you don't know if that string > instance is the only one in memory. This is excellent advice. I won't say that there is "never" a use-case for testing strings for identity, but I can't think of one that isn't contrived and artificial. > I've heard as an implementation > detail, since strings are immutable, that Python will only create one > actual instance and just assign new references to it (your first x is y > example), but to compare equality it just makes sense to use "==", not > to ask if it is the same object in memory. Plus, I believe the "==" > operator will check if the variables point to the same object. Yes, that is an optimization that CPython performs. Other implementations may do different, but the optimization is so obvious and so cheap that I would be shocked if any of the major implementations fail to do so. > Using is/is not with None works well, because I believe there will > always only be 1 None object. Yes, that is correct, but there's also a semantic difference. Generally, when testing for None, you actually want None and not some look-alike that merely tests equal to None. You want to "accept no substitutes", and so an identity test is necessary. -- Steven From wolfram.hinderer at googlemail.com Fri Aug 6 18:24:21 2010 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Fri, 6 Aug 2010 15:24:21 -0700 (PDT) Subject: default behavior References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> Message-ID: On 6 Aug., 22:07, John Posner wrote: > On 8/2/2010 11:00 PM, John Posner wrote: > > > On 7/31/2010 1:31 PM, John Posner wrote: > > >> Caveat -- there's another description of defaultdict here: > > >>http://docs.python.org/library/collections.html#collections.defaultdict > > >> ... and it's bogus. This other description claims that __missing__ is a > >> method of defaultdict, not of dict. > > > Following is a possible replacement for the bogus description. Comments > > welcome. I intend to submit a Python doc bug, and I'd like to have a > > clean alternative to propose. > > After some off-list discussion with Ethan Furman (many thanks!), the > Python Doc bug is submitted: #9536 at bugs.python.org. > > -John This is probably nitpicking, but the patch calls __missing__ a special method. However, unlike special methods, it is not invoked by "special syntax" but by the dict's __getitem__ method. (len() invokes __len__ on any object - you can't do something similar with __missing__.) __missing__ is also not listed as a special method on http://docs.python.org/py3k/reference/datamodel.html#special-method-names However, "normal" special method lookup seems to be used. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:26:59 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:26:59 GMT Subject: Python Portability--Not very portable? References: Message-ID: <4c5c8c33$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 08:00:55 -0700, W. eWatson wrote: >>> I would think there are some small time and big time Python players >>> who sell executable versions of their programs for profit? >> >> Yes. What's your point? > That someone must know how to distribute them without having the source > code ripped off. That's what copyright law is for. If you think that distributing object code (instead of source code) is going to deter a serious hacker, you're deluded. Besides, I don't mean to be rude, but what makes you think anyone would care about stealing your code? If you think people are interested in stealing your code, you're almost certainly wrong. The world is full of coders who think their two-bit text editor or re-implementation of PacMan is the most precious, precious software in existence. The vast majority of them are wrong. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:28:52 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:28:52 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> Message-ID: <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: >> Plus, I believe the >> "==" operator will check if the variables point to the same object. > > No, that's what `is` is for. Actually, yes, equality is implemented with a short-cut that checks for identity first. That makes something like: s = "abc"*1000*1000*10 s == s nice and quick, as Python can immediately recognise that a string is always equal to itself without having to walk the entire string comparing each character with itself. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:29:28 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:29:28 GMT Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> Message-ID: <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 11:23:50 +0000, kj wrote: > I don't get your point. Even when I *know* that a certain exception may > happen, I don't necessarily catch it. I catch only those exceptions for > which I can think of a suitable response that is *different* from just > letting the program fail. (After all, my own code raises its own > exceptions with the precise intention of making the program fail.) If > an unexpected exception occurs, then by definition, I had no better > response in mind for that situation than just letting the program fail, > so I'm happy to let that happen. If, afterwards, I think of a different > response for a previously uncaught exception, I'll modify the code > accordingly. > > I find this approach far preferable to the alternative of knowing a long > list of possible exceptions (some of which may never happen in actual > practice), and think of ways to keep the program still alive > no-matter-what. "No memory? No disk space? No problem! Just a flesh > wound!" What's the point of that? /me cheers wildly! Well said! -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:31:45 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:31:45 GMT Subject: Python Portability--Not very portable? References: Message-ID: <4c5c8d51$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 10:35:38 -0700, W. eWatson wrote: > So you think Python is part of open software in terms of distributing a > "product"? Python itself *is* open source software. It doesn't *require* you to write open source software. > So I should stick to C, where one can distribute programs w/o > revealing code details No you can't. That's the point that you are missing. When you ship a compiled exe, you are still shipping code, and anyone serious about "ripping off" your ideas will not find that even the tiniest barrier to doing so. Microsoft never ship their code to Windows, and yet virus and malware authors regularly and rapidly analyse it well enough to not only work out what it does and how it does it, but to discover vulnerabilities that even Microsoft don't know about. If MS can't protect their code, what makes you think your .exe file is going to any better protected? -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:32:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:32:11 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4c5c8d6b$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 11:42:39 +0200, Jean-Michel Pichavant wrote: > Steven D'Aprano wrote: >> On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: >> >>> P.S. Sorry for the top-post -- is there a way to not do top posts from >>> gmail? I haven't used usenet since tin. >>> >> Er, surely you can just move the cursor before you start typing??? >> > CTRL+END will bring the cursor at the end of the file (for most the the > mail clients). Bottom-posting is just as annoying as top-posting, except for very short posts like this. Posting in-line, where you trim the excess quoting to leave enough to give context, is most recommended. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:46:17 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:46:17 GMT Subject: Python Portability--Not very portable? References: Message-ID: <4c5c90b8$0$28666$c3e8da3@news.astraweb.com> On Thu, 05 Aug 2010 18:50:14 -0700, W. eWatson wrote: > As an example, my inexperienced Python partner 30 miles away has gotten > out of step somehow. I think by installing a different version of numpy > than I use. I gave him a program we both use months ago, and he had no > trouble. (We both use IDLE on 2.5). I made a one character change to it > and sent him the new py file. He can't execute it. I doubt he has > changed anything in the intervening period. What does that mean? It crashes? It raises an exception? He double-clicks on it and nothing happens? What error does he get? What was the one character change? Have you tested it and are you sure it works, or are you just assuming it works? What OS are you using? How did you send it to him? Can he open the file in a text editor, and what does he see? > A further example. Months ago I decided to see if I could compile a > program to avoid such problems as above. I planned to satisfy that need, > and see if I could distribute some simple programs to non-Python > friends. I pretty well understand the idea,and got it working with a > small program. It seemed like a lot of manual labor to do it. I'm sorry, I don't fully understand what you think this is going to accomplish. A program compiled to object code is going to be dependent on the hardware platform, the operating system, and any libraries that may or may not be installed. Most likely the *exact* version of the libraries. Do the words "DLL Hell" mean anything to you? How is that an advantage of Python's source-code distribution? -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 18:47:36 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Aug 2010 22:47:36 GMT Subject: Python Portability--Not very portable? References: Message-ID: <4c5c9107$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 10:58:24 -0700, W. eWatson wrote: > Is there a complete illustration of using disutils? Our only > dependencies are on Python Org material. We use no commercial or > licensed code. Oh my, the sheer ignorance that sentence reveals. Python and the standard library *is* licensed. I mean, good grief, when you start up Python's interpreter, it even says: Type "help", "copyright", "credits" or "license" for more information. Similarly any C compiler you use will also be licensed. If it's not, you have no right to use it! (Unless you can find a public domain compiler, which I doubt exists, and even if one does, I doubt it will be very good.) -- Steven From jjposner at optimum.net Fri Aug 6 19:29:22 2010 From: jjposner at optimum.net (John Posner) Date: Fri, 06 Aug 2010 19:29:22 -0400 Subject: default behavior In-Reply-To: References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C5C9AD2.6010308@optimum.net> On 8/6/2010 6:24 PM, Wolfram Hinderer wrote: > > This is probably nitpicking, but the patch calls __missing__ a special > method. However, unlike special methods, it is not invoked by "special > syntax" but by the dict's __getitem__ method. (len() invokes __len__ > on any object - you can't do something similar with __missing__.) > > __missing__ is also not listed as a special method on > http://docs.python.org/py3k/reference/datamodel.html#special-method-names > > However, "normal" special method lookup seems to be used. Fair enough. Please add your comment to #9536 at bugs.python.org. Tx, John From ritchy_gato at hotmail.com Fri Aug 6 19:47:58 2010 From: ritchy_gato at hotmail.com (Ritchy lelis) Date: Fri, 6 Aug 2010 16:47:58 -0700 (PDT) Subject: How to implement a pipeline...??? Please help Message-ID: <5242b005-31b6-4a9c-afd9-6fbb82e28db7@l14g2000yql.googlegroups.com> Hi guys In the development of my ADC project i have a new new challenge. First i need to implement a 10 Bit pipelineADC that will be the basis to later implement any kind of pipeline arquitecture (i mean, with 10 Bit, 16 Bit or any other configuration i want) i wish to... What's a 10 Bit pipiline ADC? This link with a draw will help have a perfect view of what is it: http://t3.gstatic.com/images?q=tbn:ANd9GcQK_Pwz3ssk1yoDDFwGjJ5FWAwcqr1mV9EwdndlHCEvOMdTOa4&t=1&usg=__-TsH7dnNdJm4GZTuWCxjvajZhfk= To have a 10 Bit pipiline ADC we need 9 stages, where 8 of them are a 1.5 bit configuration and the last one have a 2 Bit configuration. How it works? When we inject a input voltage (at the first block), it will be computed in the first 1.5 Bit stage and when finished the compute it will generate a output voltage who served of input voltage for the second 1.5 Bit stage which in his turn generate also a output voltage who served of input voltage in the third stage ... and successively continuing until the ninth stage. The ninth stage it's a 2 Bit stage and it will receive the last output voltage from the eighth stage and in his turn it will compute a final output signal. I already implemented the 1.5 Bit/stage and the 2 Bit/stage functions with good results (i already watch their plot's and they are cool to me) but my Pipeline function try don't seems that good. After the 2 Bit compute i expect a output signal like the drawing on the link below but more stretched. http://t3.gstatic.com/images?q=tbn:ANd9GcQGQYDW0iLCSXfMMurIksWsgklsvtj26IBtQRacFtY7ifu9RQA&t=1&usg=__-yHJFMatnCPcf9jWQv3kaxM0brE= Instead of have a lot of steps one after the another, it will have something like a single step only. Why? That it's because when we have a pipeline with a lot of stage's the final output voltage until the 2 Bit stage it's very "dense" and long and that nearly saturating the last block ( the 2 Bit stage). Next i will leave the code that I have done so far for my Pipeline function: ------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------- from flash1b5 import flash1b5 from flash1b5 import * from flash2b import flash2b from flash2b import * import matplotlib.pyplot as plt import numpy as np from pylab import * if __name__ == "__main__": Inc = raw_input("Valor do Incrimento = ") Vref = np.linspace(1,1, Inc) Vi = np.linspace(-1,1, Inc) Cs = np.linspace(3e-12, 3e-12, Inc) Cf = np.linspace(3e-12, 3e-12, Inc) f1 = flash1b5(Vi, Vref, Cs, Cf) Vin1 = f1[0] Vt1 = f1[1] Vd1 = f1[2] f2b = flash2b(Vt1, Vref) Vin2 = f2b[0] Vd2 = f2b[1] hold(True) fig2 = figure(1,figsize=(8,5)) ax2 = fig2.add_subplot(111, autoscale_on=False, xlim=(-1,1), ylim=(-0.5,2.5)) ax2.plot(Vin2, Vd2, lw=2, color='blue') grid (True); xlabel('V_ent');ylabel('Vout_Digital') plt.show() ------------------------------------------------------------------------------------------------------------------------------------------------------------------- The 1.5 Bit function: import numpy as np from pylab import * def flash1b5(Vi, Vref, Cs, Cf): Vin = np.zeros(Vi.shape, dtype=np.float) Vt = np.zeros(Vi.shape, dtype=np.float) Vd = np.zeros(Vi.shape, dtype=np.float) if any(Vi > Vref/4): mask1 = (Vi > Vref/4) np.putmask(Vin, mask1, Vi) Vs= (1+Cs/Cf)*Vin - (Cs/Cf)*Vref np.putmask(Vd, mask1, [2]) np.putmask(Vt, mask1, Vs) ## if any(-Vref/4 <= Vi) and any( Vi<= Vref/4): mask2 = (-Vref/4 <= Vi) & (Vi <= Vref/4) np.putmask(Vin, mask2, Vi) Vs = (1+(Cs/Cf))*Vin np.putmask(Vd, mask2, [1]) np.putmask(Vt, mask2, Vs) ## if any(Vi < -Vref/4): mask3 = (Vi < -Vref/4) np.putmask(Vin, mask3, Vi) Vs= (1+Cs/Cf)*Vin + (Cs/Cf)*Vref np.putmask(Vd, mask3, [0]) np.putmask(Vt, mask3, Vs) ## out = [Vin, Vt, Vd] return out ------------------------------------------------------------------------------------------------------------------------------------------------------------------- The 2 Bit function: import numpy as np from pylab import * def flash2b(Vi, Vref): Vin = np.zeros(Vi.shape, dtype=np.float) Vt = np.zeros(Vi.shape, dtype=np.float) Vd = np.zeros(Vi.shape, dtype=np.float) if any(Vi > Vref/2): mask1 = (Vi > Vref/2) np.putmask(Vin, mask1, Vi) np.putmask(Vd, mask1, [3]) if any(Vi > 0) and any(Vref/2 >= Vi): mask2 = (Vref/2 >= Vi) & (Vi > 0) np.putmask(Vin, mask2, Vi) np.putmask(Vd, mask2, [2]) if any(Vi <= 0) and any(-Vref/2 < Vi): mask3 = (-Vref/2 < Vi) & (Vi <= 0) np.putmask(Vin, mask3, Vi) np.putmask(Vd, mask3, [1]) if any(Vi <= -Vref/2): mask4 = (Vi < -Vref/2) np.putmask(Vin, mask4, Vi) np.putmask(Vd, mask4, [0]) S_Out = [Vin, Vd] return S_Out --------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------- Guys i'm asking if it's possible for a generic function for a pipeline, all the suggestions ideas are welcome. Also if you have a specific solution for my problem I will be grateful for it here. Thanks for reading my post. Cheers From nyamatongwe+thunder at gmail.com Fri Aug 6 20:05:09 2010 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 07 Aug 2010 10:05:09 +1000 Subject: Microsoft lessening commitment to IronPython and IronRuby Message-ID: There is a blog post from Jimmy Schementi who previously worked at Microsoft on IronRuby about the state of dynamic language work there. http://blog.jimmy.schementi.com/2010/08/start-spreading-news-future-of-jimmy.html Neil From dchichkov at gmail.com Fri Aug 6 20:45:31 2010 From: dchichkov at gmail.com (dmtr) Date: Fri, 6 Aug 2010 17:45:31 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? Message-ID: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> I'm running into some performance / memory bottlenecks on large lists. Is there any easy way to minimize/optimize memory usage? Simple str() and unicode objects() [Python 2.6.4/Linux/x86]: >>> sys.getsizeof('') 24 bytes >>> sys.getsizeof('0') 25 bytes >>> sys.getsizeof(u'') 28 bytes >>> sys.getsizeof(u'0') 32 bytes Lists of str() and unicode() objects (see ref. code below): >>> [str(i) for i in xrange(0, 10000000)] 370 Mb (37 bytes/item) >>> [unicode(i) for i in xrange(0, 10000000)] 613 Mb (63 bytes/item) Well... 63 bytes per item for very short unicode strings... Is there any way to do better than that? Perhaps some compact unicode objects? -- Regards, Dmitry ---- import os, time, re start = time.time() l = [unicode(i) for i in xrange(0, 10000000)] dt = time.time() - start vm = re.findall("(VmPeak.*|VmSize.*)", open('/proc/%d/status' % os.getpid()).read()) print "%d keys, %s, %f seconds, %f keys per second" % (len(l), vm, dt, len(l) / dt) From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 21:02:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 01:02:01 GMT Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: <4c5cb088$0$28666$c3e8da3@news.astraweb.com> On Fri, 06 Aug 2010 17:45:31 -0700, dmtr wrote: > I'm running into some performance / memory bottlenecks on large lists. > Is there any easy way to minimize/optimize memory usage? Yes, lots of ways. For example, do you *need* large lists? Often a better design is to use generators and iterators to lazily generate data when you need it, rather than creating a large list all at once. An optimization that sometimes may help is to intern strings, so that there's only a single copy of common strings rather than multiple copies of the same one. Can you compress the data and use that? Without knowing what you are trying to do, and why, it's really difficult to advise a better way to do it (other than vague suggestions like "use generators instead of lists"). Very often, it is cheaper and faster to just put more memory in the machine than to try optimizing memory use. Memory is cheap, your time and effort is not. [...] > Well... 63 bytes per item for very short unicode strings... Is there > any way to do better than that? Perhaps some compact unicode objects? If you think that unicode objects are going to be *smaller* than byte strings, I think you're badly informed about the nature of unicode. Python is not a low-level language, and it trades off memory compactness for ease of use. Python strings are high-level rich objects, not merely a contiguous series of bytes. If all else fails, you might have to use something like the array module, or even implement your own data type in C. But as a general rule, as I mentioned above, the best way to minimize the memory used by a large list is to not use a large list. I can't emphasise that enough -- look into generators and iterators, and lazily handle your data whenever possible. -- Steven From thomas at jollans.com Fri Aug 6 21:08:55 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 03:08:55 +0200 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: <4C5CB227.4070402@jollans.com> On 08/07/2010 02:45 AM, dmtr wrote: > I'm running into some performance / memory bottlenecks on large lists. > Is there any easy way to minimize/optimize memory usage? > > Simple str() and unicode objects() [Python 2.6.4/Linux/x86]: >>>> sys.getsizeof('') 24 bytes >>>> sys.getsizeof('0') 25 bytes >>>> sys.getsizeof(u'') 28 bytes >>>> sys.getsizeof(u'0') 32 bytes > > Lists of str() and unicode() objects (see ref. code below): >>>> [str(i) for i in xrange(0, 10000000)] 370 Mb (37 bytes/item) >>>> [unicode(i) for i in xrange(0, 10000000)] 613 Mb (63 bytes/item) > > Well... 63 bytes per item for very short unicode strings... Is there > any way to do better than that? Perhaps some compact unicode objects? There is a certain price you pay for having full-feature Python objects. What are you trying to accomplish anyway? Maybe the array module can be of some help. Or numpy? > > -- Regards, Dmitry > > ---- > import os, time, re > start = time.time() > l = [unicode(i) for i in xrange(0, 10000000)] > dt = time.time() - start > vm = re.findall("(VmPeak.*|VmSize.*)", open('/proc/%d/status' % > os.getpid()).read()) > print "%d keys, %s, %f seconds, %f keys per second" % (len(l), vm, dt, > len(l) / dt) From steve at REMOVE-THIS-cybersource.com.au Fri Aug 6 21:25:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 01:25:01 GMT Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <4c5cb5ec$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 06:37:05 +1000, James Mills wrote: > On Sat, Aug 7, 2010 at 6:28 AM, geremy condra > wrote: >> If I had to wait 5 minutes while a candidate tried to solve this >> problem I would not hire them. > > Yes you do raise a valid point. It should really only take you a mere > few seconds or so to write a solution to this. Yes, but the point is to come up with a solution that is *correct*, not merely a solution. *wink* Just the mere typing time will be "a few seconds or so", so you're leaving zero time for actual thought, let alone running the code at least once to test it. Personally, I'd rather see how a potential hire *tests* his code than how he writes it. Writing code is easy. Testing code is harder. Testing it properly is harder still -- it's amazing how many people forget that it's not just necessary to test the function on data that *works*, but also on data that fails as well (unless, of course, you're happy with function behaviour that is unspecified in the face of errors). I also want to see when the coder thinks she's done. If I say "Write a function that does fizzbuzz", does she assume I want *just* the function, or does she ask questions like "Do you want documentation and tests? What sort of tests?". Does she assume that because the fizzbuzz function is small it doesn't need documentation or testing? The Fizzbuzz algorithm itself is the simple part. If I'm hiring a coder, I care more about their attitude to documentation and testing than their ability to code up a tiny algorithm in five seconds time. I want to see if they are a careful coder, or a cowboy. > More over, it can be done in just a single line of Python. > > 7 if you're not very familiar with Python. Or if you value readability over conserving newlines. Some months ago I wrote a version of FizzBuzz. By the time I read the description of the problem, re-read it to make sure I understood it and looking for any hidden traps ("seems too simple to me, what have I missed?"), wrote a first draft, tested it, fixed a silly typo, and then tested it again, it took about 3-5 minutes. I don't believe I have anything to be ashamed about that, especially not when I look at the number of comments by people who claimed the exercise was so trivial that they did it in ten seconds, AND GOT IT WRONG. Then I added error checking, tests and documentation, and the whole exercise took about 20 minutes. That was probably overkill, but I was bored :) (At least I didn't turn it into a class.) -- Steven From greg.ewing at canterbury.ac.nz Fri Aug 6 21:36:30 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 07 Aug 2010 13:36:30 +1200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <4C5C562A.90702@sschwarzer.net> Message-ID: <8c3r45FsveU1@mid.individual.net> Ethan Furman wrote: > Instead of using 'is' use '=='. Maybe not as cute, but definitely more > robust! It's also just as efficient if you use strings that resemble identifiers, because they will be interned, so the comparison will end up just doing an indentity test anyway. -- Greg From dchichkov at gmail.com Fri Aug 6 21:39:27 2010 From: dchichkov at gmail.com (dmtr) Date: Fri, 6 Aug 2010 18:39:27 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Steven, thank you for answering. See my comments inline. Perhaps I should have formulated my question a bit differently: Are there any *compact* high performance containers for unicode()/str() objects in Python? By *compact* I don't mean compression. Just optimized for memory usage, rather than performance. What I'm really looking for is a dict() that maps short unicode strings into tuples with integers. But just having a *compact* list container for unicode strings would help a lot (because I could add a __dict__ and go from it). > Yes, lots of ways. For example, do you *need* large lists? Often a better > design is to use generators and iterators to lazily generate data when > you need it, rather than creating a large list all at once. Yes. I do need to be able to process large data sets. No, there is no way I can use an iterator or lazily generate data when I need it. > An optimization that sometimes may help is to intern strings, so that > there's only a single copy of common strings rather than multiple copies > of the same one. Unfortunately strings are unique (think usernames on facebook or wikipedia). And I can't afford storing them in db/memcached/redis/ etc... Too slow. > Can you compress the data and use that? Without knowing what you are > trying to do, and why, it's really difficult to advise a better way to do > it (other than vague suggestions like "use generators instead of lists"). Yes. I've tried. But I was unable to find a good, unobtrusive way to do that. Every attempt either adds some unnecessary pesky code, or slow, or something like that. See more at: http://bugs.python.org/issue9520 > Very often, it is cheaper and faster to just put more memory in the > machine than to try optimizing memory use. Memory is cheap, your time and > effort is not. Well... I'd really prefer to use say 16 bytes for 10 chars strings and fit data into 8Gb Rather than paying extra $1k for 32Gb. > > Well... ?63 bytes per item for very short unicode strings... Is there > > any way to do better than that? Perhaps some compact unicode objects? > > If you think that unicode objects are going to be *smaller* than byte > strings, I think you're badly informed about the nature of unicode. I don't think that that unicode objects are going to be *smaller*! But AFAIK internally CPython uses UTF-8? No? And 63 bytes per item seems a bit excessive. My question was - is there any way to do better than that.... > Python is not a low-level language, and it trades off memory compactness > for ease of use. Python strings are high-level rich objects, not merely a > contiguous series of bytes. If all else fails, you might have to use > something like the array module, or even implement your own data type in > C. Are there any *compact* high performance containers (with dict, list interface) in Python? -- Regards, Dmitry From greg.ewing at canterbury.ac.nz Fri Aug 6 21:41:03 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 07 Aug 2010 13:41:03 +1200 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5c8b49$0$28666$c3e8da3@news.astraweb.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4c5c8b49$0$28666$c3e8da3@news.astraweb.com> Message-ID: <8c3rcoF2tpU1@mid.individual.net> Steven D'Aprano wrote: > Generally, > when testing for None, you actually want None and not some look-alike > that merely tests equal to None. That's true, although I can't think of a use case for an object that compares equal to None but isn't -- except for obfuscated code competition entries and making obscure points in usenet discussions. :-) -- Greg From dchichkov at gmail.com Fri Aug 6 21:56:55 2010 From: dchichkov at gmail.com (dmtr) Date: Fri, 6 Aug 2010 18:56:55 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: > > Well... ?63 bytes per item for very short unicode strings... Is there > > any way to do better than that? Perhaps some compact unicode objects? > > There is a certain price you pay for having full-feature Python objects. Are there any *compact* Python objects? Optimized for compactness? > What are you trying to accomplish anyway? Maybe the array module can be > of some help. Or numpy? Ultimately a dict that can store ~20,000,000 entries: (u'short string' : (int, int, int, int, int, int, int)). -- Regards, Dmitry From clp2 at rebertia.com Fri Aug 6 22:03:46 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 6 Aug 2010 19:03:46 -0700 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Message-ID: On Fri, Aug 6, 2010 at 6:39 PM, dmtr wrote: >> > Well... ?63 bytes per item for very short unicode strings... Is there >> > any way to do better than that? Perhaps some compact unicode objects? >> >> If you think that unicode objects are going to be *smaller* than byte >> strings, I think you're badly informed about the nature of unicode. > > I don't think that that unicode objects are going to be *smaller*! > But AFAIK internally CPython uses UTF-8? Nope. unicode objects internally use UCS-2 or UCS-4, depending on how CPython was ./configure-d; the former is the default. See PEP 261. Cheers, Chris -- http://blog.rebertia.com From roy at panix.com Fri Aug 6 22:04:10 2010 From: roy at panix.com (Roy Smith) Date: Fri, 06 Aug 2010 22:04:10 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <4c5cb5ec$0$28666$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Personally, I'd rather see how a potential hire *tests* his code than how > he writes it. Writing code is easy. Testing code is harder. Testing it > properly is harder still -- it's amazing how many people forget that it's > not just necessary to test the function on data that *works*, but also on > data that fails as well (unless, of course, you're happy with function > behaviour that is unspecified in the face of errors). > > I also want to see when the coder thinks she's done. Perhaps I'm reading more into your choice of words than you intended, but I'm curious what you envision a "coder" does. I think of "coder" and a rather low-level job. Somebody who just writes code. I'm generally looking for somebody who is more of a software engineer. Somebody who is not just writing some code, but who is building a product. That means, as you suggest, that it's documented, tested, robust, maintainable, portable, all that good stuff. > If I say "Write a function that does fizzbuzz", does she assume I > want *just* the function, or does she ask questions like "Do you want > documentation and tests? What sort of tests?". I think this depends on the situation. For writing code at a whiteboard while i watched, I'd expect the candidate to concentrate just on the code itself. If it was an assigment, as in, "Write a program to do X, and mail it to me by tomorrow", I'd expect a much more complete treatment. From ldo at geek-central.gen.new_zealand Fri Aug 6 22:05:16 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 07 Aug 2010 14:05:16 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: In message , David Cournapeau wrote: > I have yet seen a project where you could build C code with a C++ > compiler - the only ones I know are specifically designed that way and > it is painful. I seem to recall a FAQ entry, might have been on kernelnewbies.org, asking why the Linux kernel wasn?t written in C++. The answer explained that at one time there was an experiment to make the kernel compilable with a C++ compiler, without actually using any C++ features. The result: they lost about 10% in speed. That was enough to put the kernel developers off taking the experiment any further. From lists at cheimes.de Fri Aug 6 22:07:13 2010 From: lists at cheimes.de (Christian Heimes) Date: Sat, 07 Aug 2010 04:07:13 +0200 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: > I'm running into some performance / memory bottlenecks on large lists. > Is there any easy way to minimize/optimize memory usage? > > Simple str() and unicode objects() [Python 2.6.4/Linux/x86]: >>>> sys.getsizeof('') 24 bytes >>>> sys.getsizeof('0') 25 bytes >>>> sys.getsizeof(u'') 28 bytes >>>> sys.getsizeof(u'0') 32 bytes A Python str object contains much more than just the raw string. On a 32bit system it contains: * a pointer to its type (ptr with 4 bytes) * a reference counter (ssize_t, 4 bytes) * the length of the string (ssize_t, 4 bytes) * the cached hash of the string (long, 8 bytes) * interning state (int, 4 bytes) * a null terminated char array for its data. Christian From philip at semanchuk.com Fri Aug 6 22:18:13 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Fri, 6 Aug 2010 22:18:13 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On Aug 6, 2010, at 3:14 PM, W. eWatson wrote: > I must be missing something. I tried this. (Windows, IDLE, Python 2.5) Yes, as Benjamin Kaplan pointed out and as I said in the email where I posted this code snippet, "dependencies is a list of custom classes that represent modules we need (e.g. numpy)." The code I posted was not meant to be a complete working example. It's part of a larger piece of code that I didn't have time to cook down to a simpler, self- sufficient whole. Also, in your list you've got "numyp" instead of "numpy". Also, at the top of your code you have "import numpy" and "import scipy" which defeats the purpose of this code. Try this (untested): import sys dependencies = ("numpy", "scipy", "some_other_module") for dependency in dependencies: try: __import__(dependency) except ImportError: # Uh oh! print "%s is not installed" % dependency else: # The module loaded OK. Get a handle to it and try to extract # version info. # Many Python modules follow the convention of providing their # version as a string in a __version__ attribute. module = sys.modules[dependency] for attribute_name in ("__version__", "__VERSION__", "VERSION", "version"): if hasattr(module, attribute_name): version = getattr(module, attribute_name) print "module %s has version %s" % (dependency, version) break bye Philip > # Try each module > import sys > import numpy > import scipy > import string > > dependencies = "numyp", "scipy" > for dependency in dependencies: > try: > __import__(dependency.name) > except ImportError: > # Uh oh! > dependency.installed = None > else: > # The module loaded OK. Get a handle to it and try to extract > # version info. > # Many Python modules follow the convention of providing their > # version as a string in a __version__ attribute. > module = sys.modules[dependency.name] > > # This is what I default to. > dependency.installed = "[version unknown]" > > for attribute_name in ("__version__", "__VERSION__", "VERSION", > "version"): > if hasattr(module, attribute_name): > dependency.installed = getattr(module, attribute_name) > break > > The result was this. > Traceback (most recent call last): > File "C:/Users/Wayne/Sandia_Meteors/Trajectory_Estimation/ > dependency_code", line 10, in > __import__(dependency.name) > AttributeError: 'str' object has no attribute 'name' > -- > http://mail.python.org/mailman/listinfo/python-list From nyamatongwe+thunder at gmail.com Fri Aug 6 22:18:35 2010 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 07 Aug 2010 12:18:35 +1000 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Message-ID: dmtr: > What I'm really looking for is a dict() that maps short unicode > strings into tuples with integers. But just having a *compact* list > container for unicode strings would help a lot (because I could add a > __dict__ and go from it). Add them all into one string or array and use indexes into that string. Neil From debatem1 at gmail.com Fri Aug 6 22:26:52 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 6 Aug 2010 19:26:52 -0700 Subject: python interview quuestions In-Reply-To: <4c5cb5ec$0$28666$c3e8da3@news.astraweb.com> References: <4C5C5528.5060608@tim.thechases.com> <4c5cb5ec$0$28666$c3e8da3@news.astraweb.com> Message-ID: On Fri, Aug 6, 2010 at 6:25 PM, Steven D'Aprano wrote: > On Sat, 07 Aug 2010 06:37:05 +1000, James Mills wrote: > >> On Sat, Aug 7, 2010 at 6:28 AM, geremy condra >> wrote: >>> If I had to wait 5 minutes while a candidate tried to solve this >>> problem I would not hire them. >> >> Yes you do raise a valid point. It should really only take you a mere >> few seconds or so to write a solution to this. > > Yes, but the point is to come up with a solution that is *correct*, not > merely a solution. *wink* > > Just the mere typing time will be "a few seconds or so", so you're > leaving zero time for actual thought, let alone running the code at least > once to test it. I wouldn't let them have access to an interpreter for this either. The goal is to see if they can put out something that looks reasonably close to a solution; if so, they're probably trainable. Otherwise, GTFO. > Personally, I'd rather see how a potential hire *tests* his code than how > he writes it. Writing code is easy. Testing code is harder. Testing it > properly is harder still -- it's amazing how many people forget that it's > not just necessary to test the function on data that *works*, but also on > data that fails as well (unless, of course, you're happy with function > behaviour that is unspecified in the face of errors). Absolutely. A great problem for this is the ACM programming challenge pig latin translator- it contains a logic error that makes a certain case ambiguous. Hire the ones that spot the problem before they touch the keyboard on the spot, and put the ones that test for it at the top of the heap. > I also want to see when the coder thinks she's done. If I say "Write a > function that does fizzbuzz", does she assume I want *just* the function, > or does she ask questions like "Do you want documentation and tests? What > sort of tests?". Does she assume that because the fizzbuzz function is > small it doesn't need documentation or testing? The Fizzbuzz algorithm > itself is the simple part. If I'm hiring a coder, I care more about their > attitude to documentation and testing than their ability to code up a > tiny algorithm in five seconds time. I want to see if they are a careful > coder, or a cowboy. I have things I'd rather do than sit around and watch a candidate write tests. If I wanted them to write tests, I'd send them the problem before the interview and have them sell me on their way of solving it during the interview. > >> More over, it can be done in just a single line of Python. >> >> 7 if you're not very familiar with Python. > > Or if you value readability over conserving newlines. I was thinking the same thing. > Some months ago I wrote a version of FizzBuzz. By the time I read the > description of the problem, re-read it to make sure I understood it and > looking for any hidden traps ("seems too simple to me, what have I > missed?"), wrote a first draft, tested it, fixed a silly typo, and then > tested it again, it took about 3-5 minutes. I don't believe I have > anything to be ashamed about that, especially not when I look at the > number of comments by people who claimed the exercise was so trivial that > they did it in ten seconds, AND GOT IT WRONG. Given the expectation of interpreter-ready code rather than just logically correct and close enough, 3 minutes isn't insane. 5 minutes is still pretty out there, though. Of course, getting it wrong doesn't win anybody points. > Then I added error checking, tests and documentation, and the whole > exercise took about 20 minutes. That was probably overkill, but I was > bored :) Just maybe ;) Geremy Condra From python.list at tim.thechases.com Fri Aug 6 22:31:30 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 06 Aug 2010 21:31:30 -0500 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <4C5CC582.5080005@tim.thechases.com> On 08/06/10 15:37, James Mills wrote: > On Sat, Aug 7, 2010 at 6:28 AM, geremy condra wrote: >> If I had to wait 5 minutes while a candidate tried to solve this >> problem I would not hire them. > > Yes you do raise a valid point. It should really only take > you a mere few seconds or so to write a solution to this. > > More over, it can be done in just a single line of Python. > > 7 if you're not very familiar with Python. While it *can* be done in one line, I'm not sure it's the most legible solution. Though I must say I like this one-line python version: for i in range(1, 101): print ((i%3==0 and 'fizz' or '') + (i%5==0 and 'buzz' or '')) or i (adjust "3" and "5" for your local flavor of fizzbuzz) I'm not sure I'd hire a candidate that proposed this as a solution in earnest, but I'd have fun chatting with them :) -tkc From hunguponcontent at gmail.com Fri Aug 6 23:05:56 2010 From: hunguponcontent at gmail.com (Default User) Date: Fri, 6 Aug 2010 22:05:56 -0500 Subject: Python "why" questions Message-ID: >From "the emperor's new clothes" department: 1) Why do Python lists start with element [0], instead of element [1]? "Common sense" would seem to suggest that lists should start with [1]. 2) In Python 3, why is print a function only, so that: print "Hello, World" is not okay, but it must be print("Hello, World") instead? (Yeah, I know: picky, picky . . . ) 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but 8 * 3.57 displays as 28.56 (rounded off to 2 decimal places)? And yet, in Python 2.6, 8 * 3.57 displays as 28.559999999999999? And we wonder why kids don't want to learn to program. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryan at rfk.id.au Fri Aug 6 23:36:03 2010 From: ryan at rfk.id.au (Ryan Kelly) Date: Sat, 07 Aug 2010 13:36:03 +1000 Subject: Python "why" questions In-Reply-To: References: Message-ID: <1281152163.2089.6.camel@durian> On Fri, 2010-08-06 at 22:05 -0500, Default User wrote: > >From "the emperor's new clothes" department: > > 1) Why do Python lists start with element [0], instead of element > [1]? "Common sense" would seem to suggest that lists should start > with [1]. "Common sense" is wrong. There are many compelling advantages to numbering from zero instead of one: http://lambda-the-ultimate.org/node/1950 > 2) In Python 3, why is print a function only, so that: print "Hello, > World" is not okay, but it must be print("Hello, World") instead? > (Yeah, I know: picky, picky . . . ) The real question is, why was print so special in Python 2 that is can be called without parentheses? The answer was "no reason" and it was fixed in Python 3 to be consistent with the rest of the language. > 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but > 8 * 3.57 displays as 28.56 (rounded off to 2 decimal places)? And > yet, in Python 2.6, 8 * 3.57 displays as 28.559999999999999? Because the code for displaying floats was improved in python 3. You can follow the fascinating discussion on issue 7117: http://bugs.python.org/issue7117 I can't defend the rounding issues of floating point numbers in general - it's just "one of those things" that you have to deal with. But show me a language where floats don't have this problem. > And we wonder why kids don't want to learn to program. Yeah, obscure language warts, that must be the reason. Note to self: DNFTT... Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details From chare at labr.net Fri Aug 6 23:37:26 2010 From: chare at labr.net (Chris Hare) Date: Fri, 06 Aug 2010 22:37:26 -0500 Subject: sched() function questions Message-ID: <172F5EAB-7A0B-4FB9-AF53-4899B19027C5@labr.net> I am currently using threading.timer to execute an event in my big chunk of code. This is causing a problem with sqlite, so I am trying to figure out the sched function import sched import time def timerfunc(): print "hello", time.time() return(time.time()) def delay(period): time.sleep(period) def some(): s.enterabs(900,1, timerfunc, () ) s.run() s = sched.scheduler(timerfunc, delay) print time.time() some() x = 0 while 1: print x x = x + 1 time.sleep(60) print str(s.queue()) What I am trying to do is mimic the Timer function, where my code will continue to function while my scheduled function executes in 15 minutes or 900 seconds. This doesn't do it though. Any help? From zak.mc.kraken at libero.it Fri Aug 6 23:46:23 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Sat, 07 Aug 2010 05:46:23 +0200 Subject: Python "why" questions References: Message-ID: Default User wrote: >>From "the emperor's new clothes" department: > > 1) Why do Python lists start with element [0], instead of element [1]? > "Common sense" would seem to suggest that lists should start with [1]. http://userweb.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html > 2) In Python 3, why is print a function only, so that: print "Hello, > World" > is not okay, but it must be print("Hello, World") instead? (Yeah, I know: > picky, picky . . . ) "There should be one-- and preferably only one --obvious way to do it." > 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but 8 * > 3.57 displays as 28.56 (rounded off to 2 decimal places)? And yet, in > Python 2.6, 8 * 3.57 displays as 28.559999999999999? http://mail.python.org/pipermail/python-dev/2009-October/092958.html and replies -- By ZeD From ben+python at benfinney.id.au Sat Aug 7 00:28:19 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 07 Aug 2010 14:28:19 +1000 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> Message-ID: <87k4o311y4.fsf@benfinney.id.au> Steven D'Aprano writes: > On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: > > > P.S. Sorry for the top-post -- is there a way to not do top posts > > from gmail? I haven't used usenet since tin. > > Er, surely you can just move the cursor before you start typing??? I like to think that the cursor is placed at the top by default so that is easy: just travel down through the quoted material, removing it if not relevant and inserting one's responses where needed. -- \ ?Two hands working can do more than a thousand clasped in | `\ prayer.? ?Anonymous | _o__) | Ben Finney From pavlovevidence at gmail.com Sat Aug 7 00:55:26 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 6 Aug 2010 21:55:26 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: On Aug 6, 6:56?pm, dmtr wrote: > > > Well... ?63 bytes per item for very short unicode strings... Is there > > > any way to do better than that? Perhaps some compact unicode objects? > > > There is a certain price you pay for having full-feature Python objects. > > Are there any *compact* Python objects? Optimized for compactness? Yes, but probably not in the way that'd be useful to you. Look at the array module, and also consider the third-party numpy library. They store compact arrays of numeric types (mostly) but they have character type storage as well. That probably won't help you, though, since you have variable-length strings. I don't know of any third-party types that can do what you want, but there might be some. Search PyPI. > > What are you trying to accomplish anyway? Maybe the array module can be > > of some help. Or numpy? > > Ultimately a dict that can store ~20,000,000 entries: (u'short > string' : (int, int, int, int, int, int, int)). My recommendation would be to use sqlite3. Only if you know for sure that it's too slow--meaning that you've actually tried it and it was too slow, and nothing else--then should you bother with a For that I'd probably go with a binary tree rather than a hash. So you have a huge numpy character array that stores all 20 million short strings end-to-end (in lexical order, so that you can look up the strings with a binary search), then you have an numpy integer array that stores the indices into this string where the word boundaries are, and then an Nx7 numpy integer array storing the int return vslues. That's three compact arrays. Carl Banks From clp2 at rebertia.com Sat Aug 7 01:33:55 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 6 Aug 2010 22:33:55 -0700 Subject: Python "why" questions In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 8:05 PM, Default User wrote: > >From "the emperor's new clothes" department: > > 1)? Why do Python lists start with element [0], instead of element [1]? > "Common sense" would seem to suggest that lists should start with [1]. (In addition to the other good answers already given) Well, "tradition" (originating from C) suggests otherwise. *Very* few languages use 1-based indexing: http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(array)#Array_system_cross-reference_list > 2)? In Python 3, why is print a function only, so that: print "Hello, World" > is not okay, but it must be print("Hello, World") instead?? (Yeah, I know: > picky, picky . . . ) One less special case to learn; makes the language more regular and easier to learn. It also lets one write: f = lambda x: print(x) Which is not possible if print is a statement. Cheers, Chris -- http://blog.rebertia.com From torriem at gmail.com Sat Aug 7 01:56:04 2010 From: torriem at gmail.com (Michael Torrie) Date: Fri, 06 Aug 2010 23:56:04 -0600 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? In-Reply-To: References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: <4C5CF574.20702@gmail.com> On 08/06/2010 07:56 PM, dmtr wrote: > Ultimately a dict that can store ~20,000,000 entries: (u'short > string' : (int, int, int, int, int, int, int)). I think you really need a real database engine. With the proper indexes, MySQL could be very fast storing and retrieving this information for you. And it will use your RAM to cache as it sees fit. Don't try to reinvent the wheel here. From torriem at gmail.com Sat Aug 7 02:10:05 2010 From: torriem at gmail.com (Michael Torrie) Date: Sat, 07 Aug 2010 00:10:05 -0600 Subject: new to python - trouble calling a function from another function In-Reply-To: References: Message-ID: <4C5CF8BD.6040609@gmail.com> On 08/05/2010 01:25 AM, Brandon McCombs wrote: > How can that be? I don't get any errors when the script > executes. Surely this isn't some limitation I'm encountering? > > > yield (p.destination - self.currenteFloor) * TRAVELTIME, self ^^^^^^^^^ To be succinct, goUp() is apparently a generator function. "yield" means the function needs to be iterated over; calling it just sets up the generator and returns a generator object. So yeah your goUp() call will appear (and actually does) do nothing at all. From dchichkov at gmail.com Sat Aug 7 02:27:46 2010 From: dchichkov at gmail.com (dmtr) Date: Fri, 6 Aug 2010 23:27:46 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: On Aug 6, 10:56?pm, Michael Torrie wrote: > On 08/06/2010 07:56 PM, dmtr wrote: > > > Ultimately a dict that can store ~20,000,000 entries: (u'short > > string' : (int, int, int, int, int, int, int)). > > I think you really need a real database engine. ?With the proper > indexes, MySQL could be very fast storing and retrieving this > information for you. ?And it will use your RAM to cache as it sees fit. > ?Don't try to reinvent the wheel here. No, I've tried. DB solutions are not even close in terms of the speed. Processing would take weeks :( Memcached or REDIS sort of work, but they are still a bit on the slow side, to be a pleasure to work with. The standard dict() container is *a lot* faster. It is also hassle free (accepting unicode keys/etc). I just wish there was a bit more compact dict container, optimized for large dataset and memory, not for speed. And with the default dict() I'm also running into some kind of nonlinear performance degradation, apparently after 10,000,000-13,000,000 keys. But I can't recreate this with a solid test case (see http://bugs.python.org/issue9520 ) :( -- Dmitry From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sat Aug 7 02:36:29 2010 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sat, 7 Aug 2010 06:36:29 +0000 (UTC) Subject: Is there any way to minimize str()/unicode() objects memory usage ?[Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Message-ID: dmtr wrote: > > What I'm really looking for is a dict() that maps short unicode > strings into tuples with integers. But just having a *compact* list > container for unicode strings would help a lot (because I could add a > __dict__ and go from it). > At this point, I'd suggest to use one of the dbm modules, and pack the integers with struct.pack into a short string(s). Depending on your usage pattern, there are marked performance differences between dbhash, gdbm, and dbm implementations, so perhaps it would pay off to invest sometime in benchmarking. If your data are write-once, then cdb has excellent performance (but a different API). The file will be usually cached in RAM, so no need to worry about I/O bottlenecks... and if small enough, you can always put it into a ramdisk. If your strings are long enough, you can improve memory usage with a use of zlib.compress (dumb and unoptimal way of using compression, but easy and present in the std library) - but always verify if the compressed strings are _shorter_ than originals. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From prologic at shortcircuit.net.au Sat Aug 7 02:43:39 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 16:43:39 +1000 Subject: Perl -> Python unpack In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 4:30 AM, James Mills wrote: > What does a* or A* translate to in Python when unpacking > binary data with struct.unpack(...) ? Fine I"ll answer my own question. Python _does not_ support implicit size in struct formatting rules. sizes are explicit meaning that you must "compute" the size you require. a* or A* would translate to 10s for example where you want a string with a size of 10. cheers James -- -- James Mills -- -- "Problems are solved by method" From macgyver at cyta.gr Sat Aug 7 02:45:28 2010 From: macgyver at cyta.gr (=?ISO-8859-7?Q?=CD=E9=EA=FC=EB=E1=EF=F2_=CA=EF=FD=F1=E1=F2?=) Date: Sat, 07 Aug 2010 09:45:28 +0300 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: <4C5B4D6E.1070501@tim.thechases.com> References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> <4C5B4D6E.1070501@tim.thechases.com> Message-ID: <4C5D0108.2090401@cyta.gr> ???? 6/8/2010 2:46 ??, ?/? Tim Chase ??????: > # variant B > for row in dataset: > host, hits, dt = row > # rest of your code here So, row is a tuple comprising of 3 fields, and host, hist, dt are variables assigned each one of row's tuple values by breaking it to it's elements. But what kind of objects is host, hits, dt that containes the row's tuple data themselves? tuples or lists and why? > # variant C > for host, hits, dt in row: > # rest of your code here > host, hits, data each and every one of them hold a piece of the row's tuple values. But what happens in here? 'for host, hits, dt in dataset:' Here we don't have the row tuple. So what tthose variabels store, and in what datatype they strore info in and what is the difference between this and 'for host, hits, dt in row:' What datatypes are these vars here and what data each one hold? > The data-type of the individual values would be whatever comes back > from the database as translated into Python (string, float/Decimal, > boolean, datetime, etc). In your example, it's likely a > string+integer+datetime as the 3 values. You can see why I prefer the > elegance of just performing the assignment in the for-loop (variant C). > If the fieds datatypes returned form the database are for exmaple page varchar(50) , hits inteeger[11], date datetime then the when python grabs those results fields it would translate them to 'page as string' , (hits as int) , 'date as string' respectively? Whcih emans it translated those fileds returned to the most appropriate-most close to prototype stored in database' datatypes automatically? > > [*] "about" the same because in #1 and #2, you also have access to the > whole row; whereas in #3, you don't have something called "row", but > you could reassemble it if you needed: > > row = (host, hits, dt Would that be a row or a tuple when joined? Again, thanks for ALL your preciosu help you provide me! From __peter__ at web.de Sat Aug 7 02:50:35 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Aug 2010 08:50:35 +0200 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: dmtr wrote: >> > Well... 63 bytes per item for very short unicode strings... Is there >> > any way to do better than that? Perhaps some compact unicode objects? >> >> There is a certain price you pay for having full-feature Python objects. > > Are there any *compact* Python objects? Optimized for compactness? > >> What are you trying to accomplish anyway? Maybe the array module can be >> of some help. Or numpy? > > Ultimately a dict that can store ~20,000,000 entries: (u'short > string' : (int, int, int, int, int, int, int)). I don't know to what extent it still applys but switching off cyclic garbage collection with import gc gc.disable() while building large datastructures used to speed up things significantly. That's what I would try first with your real data. Encoding your unicode strings as UTF-8 could save some memory. When your integers fit into two bytes, say, you can use an array.array() instead of the tuple. Peter From sschwarzer at sschwarzer.net Sat Aug 7 03:04:06 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 07 Aug 2010 09:04:06 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4C5D0566.8090801@sschwarzer.net> Hi Steven, On 2010-08-07 00:28, Steven D'Aprano wrote: > On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: >>> Plus, I believe the >>> "==" operator will check if the variables point to the same object. >> >> No, that's what `is` is for. > > Actually, yes, equality is implemented with a short-cut that checks for > identity first. That makes something like: > [...] Oops, I didn't realize that the OP had mentioned the identity check as an optimization in case the objects are the same. I thought he was confusing the operator with `is`. > s = "abc"*1000*1000*10 > s == s > > nice and quick, as Python can immediately recognise that a string is > always equal to itself without having to walk the entire string comparing > each character with itself. Yes, that definitely makes sense. I guess I would have implemented it this way as well. :) Stefan From nikos.the.gr33k at gmail.com Sat Aug 7 03:09:59 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 00:09:59 -0700 (PDT) Subject: Struggling to convert a mysql datetime object to a python string of a different format References: <4c5b99f6$0$1613$742ec2ed@news.sonic.net> Message-ID: <04b47c50-8d69-43e5-bdff-12d5526ddc17@s9g2000yqd.googlegroups.com> On 6 ???, 08:13, John Nagle wrote: > On 8/4/2010 4:40 PM, ????? wrote: > > > ? ? ? ? ? ?cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page > > = '%s' ORDER BY date DESC ''' % (page) ) > > Don't do string substitution ("%") on SQL statements. ?Let MySQLdb do it > for you, with proper escaping: > > ? ? cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s > ? ? ? ? ORDER BY date DESC''', (page,)) Thanks i didn't know. But you also do use '%s' here as well. Just without the quotes? Why? How is this valid? And also what's the comma after the (page,) ? What does the comam do? > > The difference is that if some external source can control "page", and > they put in a value like > > ? ? ? ? 100 ; DELETE FROM visitors; SELECT * FROM visitors > > you just lost your data. Thanks iam trying to test this because its very interesting and when i try: http://webville.gr/index.html?show=log&page="index.html ; DELETE FROM visitors; SELECT * FROM visitors" cgitb gives me an error 53 except MySQLdb.Error: 54 print ( "Error %d: %s" % (e.args[0], e.args[1]) ) 55 else: 56 #display dataset e undefined NameError: name 'e' is not defined args = ("name 'e' is not defined",) How can i try it successfully? Have to ssay here that i use mod_rewrite in my remote web server and every incoming html request gets treated by counter.py with this rule RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^/?(.+\.html) /cgi-bin/counter.py?page=$1 [L,PT,QSA] Also for the program exectuion to reach the: cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) statement i expect the user to: # ================================================================================================================= # if extra string is attached to the URL is 'log' then show excplicit page log and exit # ================================================================================================================= if form.getvalue('show') == 'log': Please help me reproduce what you suggest. I beleive its called MySQL injection and i very like want to see this in action! :-) From greg.ewing at canterbury.ac.nz Sat Aug 7 03:28:56 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 07 Aug 2010 19:28:56 +1200 Subject: Unicode error In-Reply-To: <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> Message-ID: <8c4fouF1bdU1@mid.individual.net> Steven D'Aprano wrote: > "No memory? No disk space? No problem! Just a flesh > wound!" What's the point of that? +1 QOTW From dchichkov at gmail.com Sat Aug 7 03:30:35 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 7 Aug 2010 00:30:35 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: On Aug 6, 11:50?pm, Peter Otten <__pete... at web.de> wrote: > I don't know to what extent it still applys but switching off cyclic garbage > collection with > > import gc > gc.disable() Haven't tried it on the real dataset. On the synthetic test it (and sys.setcheckinterval(100000)) gave ~2% speedup and no change in memory usage. Not significant. I'll try it on the real dataset though. > while building large datastructures used to speed up things significantly. > That's what I would try first with your real data. > > Encoding your unicode strings as UTF-8 could save some memory. Yes... In fact that's what I'm trying now... .encode('utf-8') definitely creates some clutter in the code, but I guess I can subclass dict... And it does saves memory! A lot of it. Seems to be a bit faster too.... > When your integers fit into two bytes, say, you can use an array.array() > instead of the tuple. Excellent idea. Thanks! And it seems to work too, at least for the test code. Here are some benchmarks (x86 desktop): Unicode key / tuple: >>> for i in xrange(0, 1000000): d[unicode(i)] = (i, i+1, i+2, i+3, i+4, i+5, i+6) 1000000 keys, ['VmPeak:\t 224704 kB', 'VmSize:\t 224704 kB'], 4.079240 seconds, 245143.698209 keys per second >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) 1000000 keys, ['VmPeak:\t 201440 kB', 'VmSize:\t 201440 kB'], 4.985136 seconds, 200596.331486 keys per second >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = (i, i+1, i+2, i+3, i+4, i+5, i+6) 1000000 keys, ['VmPeak:\t 125652 kB', 'VmSize:\t 125652 kB'], 3.572301 seconds, 279931.625282 keys per second Almost halved the memory usage. And faster too. Nice. -- Dmitry From greg.ewing at canterbury.ac.nz Sat Aug 7 03:33:44 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 07 Aug 2010 19:33:44 +1200 Subject: Why is python not written in C++ ? In-Reply-To: References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> Message-ID: <8c4g22F5ljU1@mid.individual.net> Lawrence D'Oliveiro wrote: > at one > time there was an experiment to make the kernel compilable with a C++ > compiler, without actually using any C++ features. The result: they lost > about 10% in speed. That was enough to put the kernel developers off taking > the experiment any further. FWIW, certain parts of the Darwin kernel are written in a carefully-selected subset of C++. So Apple evidently think that it makes sense to use some C++ in a Unix kernel under some circumstances. -- Greg From dchichkov at gmail.com Sat Aug 7 03:33:54 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 7 Aug 2010 00:33:54 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: Correction. I've copy-pasted it wrong! array.array('i', (i, i+1, i+2, i +3, i+4, i+5, i+6)) was the best. >>> for i in xrange(0, 1000000): d[unicode(i)] = (i, i+1, i+2, i+3, i+4, i+5, i+6) 1000000 keys, ['VmPeak:\t 224704 kB', 'VmSize:\t 224704 kB'], 4.079240 seconds, 245143.698209 keys per second >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = (i, i+1, i+2, i+3, i+4, i+5, i+6) 1000000 keys, ['VmPeak:\t 201440 kB', 'VmSize:\t 201440 kB'], 4.985136 seconds, 200596.331486 keys per second >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) 1000000 keys, ['VmPeak:\t 125652 kB', 'VmSize:\t 125652 kB'], 3.572301 seconds, 279931.625282 keys per second -- Dmitry From gagsl-py2 at yahoo.com.ar Sat Aug 7 03:44:19 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 07 Aug 2010 04:44:19 -0300 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> <4C5D0566.8090801@sschwarzer.net> Message-ID: En Sat, 07 Aug 2010 04:04:06 -0300, Stefan Schwarzer escribi?: > On 2010-08-07 00:28, Steven D'Aprano wrote: >> Actually, yes, equality is implemented with a short-cut that checks for >> identity first. That makes something like: >> [...] > > Oops, I didn't realize that the OP had mentioned the > identity check as an optimization in case the objects are > the same. I thought he was confusing the operator with `is`. > >> s = "abc"*1000*1000*10 >> s == s >> >> nice and quick, as Python can immediately recognise that a string is >> always equal to itself without having to walk the entire string >> comparing >> each character with itself. > > Yes, that definitely makes sense. I guess I would have > implemented it this way as well. :) For strings and other internal types this optimization certainly makes sense. For user-defined types it gets in the way and prevents defining an object such x==x is False (like NANs). -- Gabriel Genellina From __peter__ at web.de Sat Aug 7 04:16:47 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Aug 2010 10:16:47 +0200 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: dmtr wrote: > On Aug 6, 11:50 pm, Peter Otten <__pete... at web.de> wrote: >> I don't know to what extent it still applys but switching off cyclic >> garbage collection with >> >> import gc >> gc.disable() > > > Haven't tried it on the real dataset. On the synthetic test it (and > sys.setcheckinterval(100000)) gave ~2% speedup and no change in memory > usage. Not significant. I'll try it on the real dataset though. > > >> while building large datastructures used to speed up things >> significantly. That's what I would try first with your real data. >> >> Encoding your unicode strings as UTF-8 could save some memory. > > Yes... In fact that's what I'm trying now... .encode('utf-8') > definitely creates some clutter in the code, but I guess I can > subclass dict... And it does saves memory! A lot of it. Seems to be a > bit faster too.... > >> When your integers fit into two bytes, say, you can use an array.array() >> instead of the tuple. > > Excellent idea. Thanks! And it seems to work too, at least for the > test code. Here are some benchmarks (x86 desktop): > > Unicode key / tuple: >>>> for i in xrange(0, 1000000): d[unicode(i)] = (i, i+1, i+2, i+3, i+4, >>>> i+5, i+6) > 1000000 keys, ['VmPeak:\t 224704 kB', 'VmSize:\t 224704 kB'], > 4.079240 seconds, 245143.698209 keys per second > >>>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = >>>> array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) > 1000000 keys, ['VmPeak:\t 201440 kB', 'VmSize:\t 201440 kB'], > 4.985136 seconds, 200596.331486 keys per second > >>>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = (i, i+1, >>>> i+2, i+3, i+4, i+5, i+6) > 1000000 keys, ['VmPeak:\t 125652 kB', 'VmSize:\t 125652 kB'], > 3.572301 seconds, 279931.625282 keys per second > > Almost halved the memory usage. And faster too. Nice. > def benchmark_dict(d, N): > start = time.time() > > for i in xrange(N): > length = lengths[random.randint(0, 255)] > word = ''.join([ letters[random.randint(0, 255)] for i in xrange(length) ]) > d[word] += 1 > > dt = time.time() - start > vm = re.findall("(VmPeak.*|VmSize.*)", open('/proc/%d/status' % os.getpid()).read()) > print "%d keys (%d unique), %s, %f seconds, %f keys per second" % (N, len(d), vm, dt, N / dt) > Looking at your benchmark, random.choice(letters) has probably less overhead than letters[random.randint(...)]. You might even try to inline it as letters[int(random.random())*256)] Peter From dchichkov at gmail.com Sat Aug 7 04:32:45 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 7 Aug 2010 01:32:45 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: > Looking at your benchmark, random.choice(letters) has probably less overhead > than letters[random.randint(...)]. You might even try to inline it as Right... random.choice()... I'm a bit new to python, always something to learn. But anyway in that benchmark (from http://bugs.python.org/issue9520 ) the code that generate 'words' takes 90% of the time. And I'm really looking at deltas between different methods, not the absolute value. I was also using different code to get benchmarks for my previous message... Here's the code: #!/usr/bin/python # -*- coding: utf-8 -*- import os, time, re, array start = time.time() d = dict() for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) dt = time.time() - start vm = re.findall("(VmPeak.*|VmSize.*)", open('/proc/%d/status' % os.getpid()).read()) print "%d keys, %s, %f seconds, %f keys per second" % (len(d), vm, dt, len(d) / dt) From dchichkov at gmail.com Sat Aug 7 04:45:45 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 7 Aug 2010 01:45:45 -0700 (PDT) Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: I guess with the actual dataset I'll be able to improve the memory usage a bit, with BioPython::trie. That would probably be enough optimization to continue working with some comfort. On this test code BioPython::trie gives a bit of improvement in terms of memory. Not much though... >>> d = dict() >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) 1000000 keys, ['VmPeak:\t 125656 kB', 'VmSize:\t 125656 kB'], 3.525858 seconds, 283618.896034 keys per second >>> from Bio import trie >>> d = trie.trie() >>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) 1000000 keys, ['VmPeak:\t 108932 kB', 'VmSize:\t 108932 kB'], 4.142797 seconds, 241382.814950 keys per second From aleksandar27 at BRISIOVOnet.hr Sat Aug 7 05:09:01 2010 From: aleksandar27 at BRISIOVOnet.hr (alejandro) Date: Sat, 7 Aug 2010 11:09:01 +0200 Subject: Need help from someone that have PIL installed References: Message-ID: > > Is the file, which you claim is UTF-8 encoded, actually UTF-8 encoded? > If you're not sure, explicitly tell your text editor to save the file as > UTF-8, and then try again. I feel like an idiot... haven't used Python for some time... my editor was set for utf-8 on PHP projects and other... but somehow i forgot to set for py files too... thanks both of you! From nawabadeel at gmail.com Sat Aug 7 05:32:27 2010 From: nawabadeel at gmail.com (Sohail) Date: Sat, 7 Aug 2010 02:32:27 -0700 (PDT) Subject: Python library for Sequence Matching/Comparison Message-ID: Hi, Is there any sequence matching library in (apart from difflib) to compare sequences of natural text? thanks From r3831110n at gmail.com Sat Aug 7 05:53:04 2010 From: r3831110n at gmail.com (Rebel Lion) Date: Sat, 7 Aug 2010 02:53:04 -0700 (PDT) Subject: A useful, but painful, one-liner to edit money amounts References: <4c5a3f1c$0$1601$742ec2ed@news.sonic.net> Message-ID: On Aug 5, 12:33?pm, John Nagle wrote: > There's got to be a better way to do this: > > def editmoney(n) : > ? ? ?return((",".join(reduce(lambda lst, item : (lst + [item]) if > ? ? ? ? ?item else lst, > ? ? ? ? ?re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) > > ?>>> editmoney(0) > '0' > ?>>> editmoney(13535) > '13,535' > ?>>> editmoney(-14535) > '-14,535' > ?>>> editmoney(123456) > '123,456' > ?>>> editmoney(1234567890) > '1,234,567,890' > ?>>> editmoney(-1234) > '-1,234' > > The basic idea here is that we want to split the string of digits > into groups of 3 digits, aligned at the right. ?Because regular > expressions are right to left, we have to reverse the string to > do that, then reverse again at the end. ?s[::-1} reverses an > interable. > > "split" with a capturing group introduces empty strings into the > list. ?Hence the "reduce" and lambda to get rid of them. > > Any better ideas? > > (Yes, I know there's a built-in feature for this scheduled for > Python 2.7.) > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle In [1]: '{:,}'.format(-12345678) Out[1]: '-12,345,678' From downaold at gmail.com Sat Aug 7 06:03:05 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 12:03:05 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <1CED8AC9-25D8-44C4-A20D-DE6B3570ECAB@gmail.com> On Aug 7, 2010, at 5:46 AM, Vito 'ZeD' De Tullio wrote: > Default User wrote: > >>> From "the emperor's new clothes" department: >> >> 1) Why do Python lists start with element [0], instead of element >> [1]? >> "Common sense" would seem to suggest that lists should start with >> [1]. > > http://userweb.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html I think the reason why is just historical; C uses zero-based indices. In C, an array index is an offset with respect to the pointer that the array variable actually is, so 0 makes sense (my_array[0] == *my_array). I'm not convinceed (yet) by Dijkstra's reasoning. *Maybe* if you want to describe a range with two References: Message-ID: On Sat, Aug 7, 2010 at 12:32, Sohail wrote: > Hi, > > Is there any sequence matching library in (apart from difflib) to > compare sequences of natural text? > > thanks > -- > http://mail.python.org/mailman/listinfo/python-list > Are you aware of NLTK? It has a lot of sub-libraries for almost anything you might need with processing natural text. Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: From sschwarzer at sschwarzer.net Sat Aug 7 06:41:12 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 07 Aug 2010 12:41:12 +0200 Subject: default behavior In-Reply-To: <4c539ce4$0$11091$c3e8da3@news.astraweb.com> References: <4c52c368$0$11091$c3e8da3@news.astraweb.com> <4c539ce4$0$11091$c3e8da3@news.astraweb.com> Message-ID: <4C5D3848.6070708@sschwarzer.net> On 2010-07-31 05:47, Steven D'Aprano wrote: > On Fri, 30 Jul 2010 08:34:52 -0400, wheres pythonmonks wrote: > It does re-use the same underlying data. > > >>> from collections import defaultdict as dd > >>> x = dd(list) > >>> x[1].append(1) > >>> x > defaultdict(, {1: [1]}) > >>> y = dict(x) > >>> x[1].append(42) > >>> y > {1: [1, 42]} One thing to keep in mind: dict(some_defaultdict) doesn't store a reference to the defaultdict; instead it makes a shallow copy, so key/value pairs added _after_ the "cast" aren't included in the new dict: >>> y[2] = 17 >>> y {1: [1, 42], 2: 17} >>> x defaultdict(, {1: [1, 42]}) Stefan From landa.martin at gmail.com Sat Aug 7 06:46:57 2010 From: landa.martin at gmail.com (Martin Landa) Date: Sat, 7 Aug 2010 03:46:57 -0700 (PDT) Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Message-ID: Hi, On Aug 5, 9:32?pm, Nobody wrote: > ? ? ? ? errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int)) > ? ? ? ? errfunc = errtype(print_error) > ? ? ? ? G_set_error_routine(errfunc) the problem occurs when restype is not None, but c_int. E.g. if hasattr(_libs['grass_gis'], 'G_set_error_routine'): G_set_error_routine = _libs['grass_gis'].G_set_error_routine G_set_error_routine.restype = c_int G_set_error_routine.argtypes = [CFUNCTYPE(UNCHECKED(c_int), String, c_int)] errtype = CFUNCTYPE(UNCHECKED(c_int), String, c_int) errfunc = errtype(print_error) or errtype = CFUNCTYPE(c_int, String, c_int) errfunc = errtype(print_error) ends up with error G_set_error_routine(errfunc) TypeError: in method 'G_set_error_routine', argument 1 of type 'int (*) (char const *,int)' The first argument of CFUNCTYPE defines result type (restype), AFAIU that should work. Thanks in advance again, Martin From shambhu.1980 at gmail.com Sat Aug 7 07:10:45 2010 From: shambhu.1980 at gmail.com (Shambhu Sharma) Date: Sat, 7 Aug 2010 16:40:45 +0530 Subject: os.unlink on Windows Message-ID: Hi, I am new to Python. I was trying to use os.unlink function in windows. But i am getting error: OSError: [Errno 2] No such file or directory: 'C:\\SHAMBHU\\tmp\\text_delete.txt' Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But os.unlink is adding extra backslash with pathname. I tried with Python2.5 and Python3.1 but got same error. Please suggest how to remove this error. -- If linux doesn't have a solution, then u have a wrong problem. Shambhu Kumar Sharma 91-98864 91913 -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Sat Aug 7 07:16:01 2010 From: chare at labr.net (Chris Hare) Date: Sat, 07 Aug 2010 06:16:01 -0500 Subject: sched() function questions In-Reply-To: References: <172F5EAB-7A0B-4FB9-AF53-4899B19027C5@labr.net> Message-ID: <55105A92-0B0D-4C67-8639-7CD8D0DA06C6@labr.net> On Aug 7, 2010, at 1:30 AM, Dennis Lee Bieber wrote: > On Fri, 06 Aug 2010 22:37:26 -0500, Chris Hare > declaimed the following in gmane.comp.python.general: > > >> print str(s.queue()) >> > I don't find a queue method defined for scheduler objects in the > documentation for my version of Python (2.5) > >> What I am trying to do is mimic the Timer function, where my code will continue to function while my scheduled function executes in 15 minutes or 900 seconds. This doesn't do it though. Any help? > > And what IS it doing? On my system, I'd expect the program to fail > when trying to print whatever that queue() method is supposed to return. > > However, here is the key item you seem to have missed -- from the > documentation: > > -=-=-=-=- > run( ) > > Run all scheduled events. This function will wait (using the delayfunc > function passed to the constructor) for the next event, then execute it > and so on until there are no more scheduled events. > -=-=-=-=- > > As soon as you call s.run() the entire PROGRAM goes into a wait > state until the first of the queued events time expires. AND won't > return until ALL events have happened. > > To have scheduled events happen asynchronously you will have to > instantiate a THREAD which runs the scheduler... Of course, for your > simple example, who needs the scheduler -- a simple sleep() in the > thread will do what you attempted... The scheduler is useful when you > want to queue a whole bunch of timed events and have them run in order > at the set times... maybe even have events add more events to the > system. > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-listThanks Dennis. I guess I will have to figure out how to resolve the sqlite error From thomas at jollans.com Sat Aug 7 07:46:13 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 13:46:13 +0200 Subject: os.unlink on Windows In-Reply-To: References: Message-ID: <4C5D4785.7030401@jollans.com> On 08/07/2010 01:10 PM, Shambhu Sharma wrote: > Hi, > > I am new to Python. I was trying to use os.unlink function in > windows. But i am getting error: > OSError: [Errno 2] No such file or directory: > 'C:\\SHAMBHU\\tmp\\text_delete.txt' > > Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But > os.unlink is adding extra backslash with pathname. No, it isn't. What you're seeing is simply the repr() of the path name string. >>> p = r'C:\SHAMBHU\tmp\text_delete.txt' >>> p 'C:\\SHAMBHU\\tmp\\text_delete.txt' >>> print(p) C:\SHAMBHU\tmp\text_delete.txt >>> I think the file you're trying to delete probably doesn't exist. Why don't you double-check that. > I tried with > Python2.5 and Python3.1 but got same error. > Please suggest how to remove this error. > > -- > If linux doesn't have a solution, then u have a wrong problem. > > Shambhu Kumar Sharma > 91-98864 91913 > From news1234 at free.fr Sat Aug 7 07:48:32 2010 From: news1234 at free.fr (News123) Date: Sat, 07 Aug 2010 13:48:32 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4c5d4810$0$1426$426a74cc@news.free.fr> On 08/07/2010 05:36 AM, Ryan Kelly wrote: > On Fri, 2010-08-06 at 22:05 -0500, Default User wrote: >> >From "the emperor's new clothes" department: >> >> 1) Why do Python lists start with element [0], instead of element >> [1]? "Common sense" would seem to suggest that lists should start >> with [1]. > > "Common sense" is wrong. There are many compelling advantages to > numbering from zero instead of one: > > http://lambda-the-ultimate.org/node/1950 It makes sense in assembly language and even in many byte code languages. It makes sense if you look at the internal representation of unsigned numbers (which might become an index) For a complete beginner common sense dictates differently and there might be confusion why the second element in a list has index 1. However I seriously doubt, that this is a real problem. You learn things like this on the first day of learning a programming language. > >> 2) In Python 3, why is print a function only, so that: print "Hello, >> World" is not okay, but it must be print("Hello, World") instead? >> (Yeah, I know: picky, picky . . . ) > > The real question is, why was print so special in Python 2 that is can > be called without parentheses? The answer was "no reason" and it was > fixed in Python 3 to be consistent with the rest of the language. > >> 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but >> 8 * 3.57 displays as 28.56 (rounded off to 2 decimal places)? And >> yet, in Python 2.6, 8 * 3.57 displays as 28.559999999999999? > > Because the code for displaying floats was improved in python 3. You > can follow the fascinating discussion on issue 7117: > > http://bugs.python.org/issue7117 > > I can't defend the rounding issues of floating point numbers in general > - it's just "one of those things" that you have to deal with. But show > me a language where floats don't have this problem. > >> And we wonder why kids don't want to learn to program. > I did not see the original post, but this statement sounds rather trollish to me. It might just be, that you can do so many things on a computer without having to program. Watching youtube or browsing the web, chatting about favourite PC games, the amount of SW, that you can download for almost every task make it much less attractive to write own programs. When my parents had their first computer there were very little games and PC's weren't connected to the net. so if I wanted to play with the computer I had mostly the choice between the games called: - basic - pascal - word star - super calc Syntax details are barely a reason to frighten children. children start very often with typing in small programs without understanding them, lookin at the results and changing what they believe to understand. Non native english speakers can write programs, before they even knew what the english words 'if' 'else' 'while' 'list' mean. They don't care. They learn that if 'starts' a condition and that 'else' is the beginning of the section to be executed if the condition is not true. > Yeah, obscure language warts, that must be the reason. > > Note to self: DNFTT... > > > Ryan > From __peter__ at web.de Sat Aug 7 07:53:58 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Aug 2010 13:53:58 +0200 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> Message-ID: Tim Chase wrote: > On 08/06/10 15:37, James Mills wrote: >> On Sat, Aug 7, 2010 at 6:28 AM, geremy condra wrote: >>> If I had to wait 5 minutes while a candidate tried to solve this >>> problem I would not hire them. >> >> Yes you do raise a valid point. It should really only take >> you a mere few seconds or so to write a solution to this. >> >> More over, it can be done in just a single line of Python. >> >> 7 if you're not very familiar with Python. > > While it *can* be done in one line, I'm not sure it's the most > legible solution. Though I must say I like this one-line python > version: > > for i in range(1, 101): print ((i%3==0 and 'fizz' or '') + > (i%5==0 and 'buzz' or '')) or i > > (adjust "3" and "5" for your local flavor of fizzbuzz) > > I'm not sure I'd hire a candidate that proposed this as a > solution in earnest, but I'd have fun chatting with them :) You mean you'd go for the candidate who took the conservative approach and got it right: print 1 print 2 print 'Fizz' print 4 print 'Buzz' print 'Fizz' print 7 print 8 print 'Fizz' print 'Buzz' print 11 print 'Fizz' print 13 print 14 print 'FizzBuzz' print 16 print 17 print 'Fizz' print 19 print 'Buzz' print 'Fizz' print 22 print 23 print 'Fizz' print 'Buzz' print 26 print 'Fizz' print 28 print 29 print 'FizzBuzz' print 31 print 32 print 'Fizz' print 34 print 'Buzz' print 'Fizz' print 37 print 38 print 'Fizz' print 'Buzz' print 41 print 42 print 43 print 44 print 'FizzBuzz' print 46 print 47 print 'Fizz' print 49 print 'Buzz' print 'Fizz' print 52 print 53 print 'Fizz' print 'Buzz' print 56 print 'Fizz' print 58 print 59 print 'FizzBuzz' print 61 print 62 print 'Fizz' print 64 print 'Buzz' print 'Fizz' print 67 print 68 print 'Fizz' print 'Buzz' print 71 print 'Fizz' print 73 print 74 print 'FizzBuzz' print 76 print 77 print 'Fizz' print 79 print 'Buzz' print 'Fizz' print 82 print 83 print 'Fizz' print 'Buzz' print 86 print 'Fizz' print 88 print 89 print 'FizzBuzz' print 91 print 92 print 'Fizz' print 94 print 'Buzz' print 'Fizz' print 97 print 98 print 'Fizz' print 'Buzz' Well, almost right, but one error per 100 lines at the first try is near- genius anyway... Peter From steve at REMOVE-THIS-cybersource.com.au Sat Aug 7 08:00:25 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 12:00:25 GMT Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> <8c4fouF1bdU1@mid.individual.net> Message-ID: <4c5d4ad9$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 19:28:56 +1200, Gregory Ewing wrote: > Steven D'Aprano wrote: >> "No memory? No disk space? No problem! Just a flesh wound!" What's >> the point of that? > > +1 QOTW While I'm always happy to be nominated for QOTW, in this case I didn't say it, and the nomination should go to KJ. -- Steven From thomas at jollans.com Sat Aug 7 08:00:59 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 14:00:59 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4C5D4AFB.90204@jollans.com> On 08/07/2010 05:05 AM, Default User wrote: >>From "the emperor's new clothes" department: > > 1) Why do Python lists start with element [0], instead of element [1]? > "Common sense" would seem to suggest that lists should start with [1]. As others have pointed out, there is a nice argument to be made for zero-based indices. However, the killer reason is: "it's what everybody else does." As it stands, the only perceived problem with zero-based indices is that it's one of the many tiny confusions that new programmers face. On the other hand, it's the way nearly every other popular programming language does it, and therefore, it's the way almost every programmer likes to think about sequences. Also, it has the nice property that, for an infinite sequence, every integer makes sense as an index (in Python). > > 2) In Python 3, why is print a function only, so that: print "Hello, > World" is not okay, but it must be print("Hello, World") instead? > (Yeah, I know: picky, picky . . . ) > > 3) In Python 3, why does 2.0 / 3.0 display as 0.6666666666666666, but 8 > * 3.57 displays as 28.56 (rounded off to 2 decimal places)? And yet, in > Python 2.6, 8 * 3.57 displays as 28.559999999999999? 0:pts/3:~% python3.1 Python 3.1.2 (release31-maint, Jul 8 2010, 09:18:08) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 28.56 28.56 >>> 0:pts/3:~% python2.6 Python 2.6.6rc1+ (r266rc1:83691, Aug 5 2010, 17:07:04) [GCC 4.4.5 20100728 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 28.56 28.559999999999999 >>> 0:pts/3:~% same number - why use more digits if you can avoid it? Python 3 is smart enough to avoid it. > > And we wonder why kids don't want to learn to program. Don't kids want to learn to program? Many don't, a fair bunch do. It's the same for any other art. Also, the only people that realize this kind of "issue" are those that have already learned programming. From gnusiva at gmail.com Sat Aug 7 08:04:43 2010 From: gnusiva at gmail.com (siva moorthy) Date: Sat, 7 Aug 2010 15:04:43 +0300 Subject: Need Translation library Message-ID: hi all, i wish to code for translation in python i want to parse a python program itself and make some keyword changes (replacement) tell me any library to parse python source code and another library to change some words phonetically to other language thanks in advance Siva -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 7 08:05:02 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 12:05:02 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5b64d2$0$28666$c3e8da3@news.astraweb.com> <87k4o311y4.fsf@benfinney.id.au> Message-ID: <4c5d4bed$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 14:28:19 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote: >> >> > P.S. Sorry for the top-post -- is there a way to not do top posts >> > from gmail? I haven't used usenet since tin. >> >> Er, surely you can just move the cursor before you start typing??? > > I like to think that the cursor is placed at the top by default so that > is > easy: just travel down through the quoted material, removing it if not > relevant and inserting one's responses where needed. Yes, but apparently millions of Internet users have keyboards where neither the cursor keys nor backspace/delete works. Being unable to interleave their reply with the quoted text, they end up quoting the entire week-long thread at the bottom of every email they send. I blame Manservant Neville. -- Steven From thomas at jollans.com Sat Aug 7 08:28:48 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 14:28:48 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <4c5c8ca3$0$28666$c3e8da3@news.astraweb.com> <4C5D0566.8090801@sschwarzer.net> Message-ID: <4C5D5180.6020200@jollans.com> On 08/07/2010 09:44 AM, Gabriel Genellina wrote: > En Sat, 07 Aug 2010 04:04:06 -0300, Stefan Schwarzer > escribi?: >> On 2010-08-07 00:28, Steven D'Aprano wrote: > >>> Actually, yes, equality is implemented with a short-cut > that checks for >>> identity first. That makes something like: >>> [...] >> >> Oops, I didn't realize that the OP had mentioned the >> identity check as an optimization in case the objects are >> the same. I thought he was confusing the operator with `is`. >> >>> s = "abc"*1000*1000*10 >>> s == s >>> >>> nice and quick, as Python can immediately recognise that a string is >>> always equal to itself without having to walk the entire string >>> comparing >>> each character with itself. >> >> Yes, that definitely makes sense. I guess I would have >> implemented it this way as well. :) > > For strings and other internal types this optimization certainly makes > sense. For user-defined types it gets in the way and prevents defining > an object such x==x is False (like NANs). > That's probably why this optimisation doesn't exist for user-defined types: Python 3.1.2 (release31-maint, Jul 8 2010, 09:18:08) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> class A: ... def __eq__(self, x): ... if self is x: return False ... else: return True ... >>> >>> A() == A() True >>> a = A() >>> a == a False >>> From hobson42 at gmaiil.com Sat Aug 7 08:34:06 2010 From: hobson42 at gmaiil.com (Ian) Date: Sat, 07 Aug 2010 13:34:06 +0100 Subject: Smith-Waterman Algorithm in Python In-Reply-To: References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> Message-ID: <4C5D52BE.302@gmaiil.com> On 06/08/2010 17:54, Daniel Fetchinson wrote: >> Does any one about any implementation of classical Smith Waterman >> local alignment algorithm and it's variants for aligning natural >> language text? >> > > Please see http://tinyurl.com/2wy43fh > > Every one of the first 20 entries is either the OP questions or your reply. Daniel - you are no help at all, and no funny. Ian From darcy at druid.net Sat Aug 7 08:54:28 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 7 Aug 2010 08:54:28 -0400 Subject: Python "why" questions In-Reply-To: <4c5d4810$0$1426$426a74cc@news.free.fr> References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <20100807085428.48664a76.darcy@druid.net> On Sat, 07 Aug 2010 13:48:32 +0200 News123 wrote: > It makes sense in assembly language and even in many byte code languages. > It makes sense if you look at the internal representation of unsigned > numbers (which might become an index) > > For a complete beginner common sense dictates differently and there > might be confusion why the second element in a list has index 1. Would said beginner also be surprised that a newborn baby is zero years old or would it be more natural to call them a one year old? Zero based counting is perfectly natural. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From __peter__ at web.de Sat Aug 7 08:58:14 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Aug 2010 14:58:14 +0200 Subject: Smith-Waterman Algorithm in Python References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> <4C5D52BE.302@gmaiil.com> Message-ID: Ian wrote: > On 06/08/2010 17:54, Daniel Fetchinson wrote: >>> Does any one about any implementation of classical Smith Waterman >>> local alignment algorithm and it's variants for aligning natural >>> language text? >>> >> >> Please see http://tinyurl.com/2wy43fh >> >> > Every one of the first 20 entries is either the OP questions or your > reply. > > Daniel - you are no help at all, and no funny. Maybe, but the OP would have had the advantage of not seeing these entries had he googled before asking. The first hit for Smith Waterman in Python is still http://narnia.cs.ttu.edu/drupal/node/104 and finding it and evaluating it before posting here should have been doable. Peter From downaold at gmail.com Sat Aug 7 09:37:23 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 15:37:23 +0200 Subject: Python "why" questions In-Reply-To: <20100807085428.48664a76.darcy@druid.net> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> Message-ID: <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> On Aug 7, 2010, at 2:54 PM, D'Arcy J.M. Cain wrote: > On Sat, 07 Aug 2010 13:48:32 +0200 > News123 wrote: >> It makes sense in assembly language and even in many byte code >> languages. >> It makes sense if you look at the internal representation of unsigned >> numbers (which might become an index) >> >> For a complete beginner common sense dictates differently and there >> might be confusion why the second element in a list has index 1. > > Would said beginner also be surprised that a newborn baby is zero > years > old or would it be more natural to call them a one year old? Zero > based counting is perfectly natural. A new born baby is in his/her first year. It's year 1 of his/her life. For this reason, also "the year 0" doesn't exist. From the fact that a baby can be half a year old, you derive that arrays should have floats as indices? From steve at REMOVE-THIS-cybersource.com.au Sat Aug 7 09:38:20 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 13:38:20 GMT Subject: Python "why" questions References: Message-ID: <4c5d61cc$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 14:00:59 +0200, Thomas Jollans wrote: > On 08/07/2010 05:05 AM, Default User wrote: >>>From "the emperor's new clothes" department: >> >> 1) Why do Python lists start with element [0], instead of element [1]? >> "Common sense" would seem to suggest that lists should start with [1]. > > As others have pointed out, there is a nice argument to be made for > zero-based indices. However, the killer reason is: "it's what everybody > else does." I'll have you know that there are still some Pascal programmers in the world, thank you. > As it stands, the only perceived problem with zero-based > indices is that it's one of the many tiny confusions that new > programmers face. On the other hand, it's the way nearly every other > popular programming language does it, and therefore, it's the way almost > every programmer likes to think about sequences. It didn't take me long to get used to thinking in zero-based indexes, but years later, I still find it hard to *talk* in zero-based indexes. It's bad enough saying that the first element in a list in the zeroth element, but that the second element is the first makes my head explode... > Also, it has the nice property that, for an infinite sequence, every > integer makes sense as an index (in Python). Er, what's the -1th element of an infinite sequence? -- Steven From darcy at druid.net Sat Aug 7 09:53:48 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 7 Aug 2010 09:53:48 -0400 Subject: Python "why" questions In-Reply-To: <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> Message-ID: <20100807095348.073cd803.darcy@druid.net> On Sat, 7 Aug 2010 15:37:23 +0200 Roald de Vries wrote: > > Would said beginner also be surprised that a newborn baby is zero > > years > > old or would it be more natural to call them a one year old? Zero > > based counting is perfectly natural. > > A new born baby is in his/her first year. It's year 1 of his/her life. > For this reason, also "the year 0" doesn't exist. From the fact that a > baby can be half a year old, you derive that arrays should have floats > as indices? No. You are giving me math and logic but the subject was common sense. Common usage counts ages as years with the second year called "one year old" so zero based counting is common. We don't tell Aunt Martha that little Jimmy is in his third year. We say that he is two years old and Aunt Martha, a non-programmer, understands exactly what we mean. Using one-based counting (first year, second year, etc.) would be the unnatural thing, would confuse Aunt Martha and make her spoil her apple pie and no one wants that. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From albert at spenarnc.xs4all.nl Sat Aug 7 09:54:28 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 07 Aug 2010 13:54:28 GMT Subject: Nice way to cast a homogeneous tuple References: <4c50eb46$0$28664$c3e8da3@news.astraweb.com> <1pm7i7-473.ln1@satorlaser.homedns.org> Message-ID: In article <1pm7i7-473.ln1 at satorlaser.homedns.org>, Ulrich Eckhardt wrote: >Steven D'Aprano wrote: >> Perhaps I have been misinformed, but my understanding of C type-casts is >> that (where possible), a cast like `int(var)` merely tells the compiler >> to temporarily disregard the type of var and treat it as if it were an >> int. In other words, it's a compiler instruction rather than a conversion >> function. > >You are misinformed. The result of a cast in C or C++ behaves as if a >temporary was created: > > int x = 0; > unsigned(x)--; // invalid, compiler error > >Now, where this distinction gets blurred is when you are casting pointers: > > (*(unsigned*)&x)--; > >or, in C++, references: > > reinterpret_cast(x)--; > >Technically, these are still invalid though, only that they give you >undefined behaviour at runtime instead of a compiler error, but those are >already very fine details of the according standards. There is just one conclusion that should remain from this. If you're ever going to program in in c or c++, casts are to be avoided like the plague. (And recently they have been thought over in C++ to be split in different names with the reinterpret_cast the most dangerous, but at least it is a big read flag.) I see an analogy with goto's in my experience. Once you understand how bad they are, you discover there is always a better solution. It is unfortunate that cast's in Python share the same name, but it is kind of unavoidable because it is about the proper CS name to use. >Uli Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From downaold at gmail.com Sat Aug 7 09:57:00 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 15:57:00 +0200 Subject: iterators and continuing after a StopIteration Message-ID: Hi all, I have a list that I'm iterating over, and during the iteration items are appended. Moreover, it is iterated over in two nested loops. If the inner loop comes to the end, I want the outer loop to append an item. Is there a way to do this? Because once an iterator has raised a StopIteration, it can not go to a next item anymore. Aside question: is there a rationale for the current behavior? To me it seems more natural to continue iteration after appending new items. I want to use it for a graph walk. nodes is a list of all nodes, edges is an on the fly constructed list of edges in the order of visiting, initial_nodes is a list of (root) nodes edges = [] edge_it = iter(edges) for node in initial_nodes: edges += node.leaving_edges try: while True: edge = edge_it.next() edges += edge.head.leaving_edges except StopIteration: pass Thanks in advance, cheers, Roald From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sat Aug 7 10:04:48 2010 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sat, 7 Aug 2010 14:04:48 +0000 (UTC) Subject: Is there any way to minimize str()/unicode() objects memory usage ?[Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> Message-ID: dmtr wrote: > I guess with the actual dataset I'll be able to improve the memory > usage a bit, with BioPython::trie. That would probably be enough > optimization to continue working with some comfort. On this test code > BioPython::trie gives a bit of improvement in terms of memory. Not > much though... > >>>> d = dict() >>>> for i in xrange(0, 1000000): d[unicode(i).encode('utf-8')] = array.array('i', (i, i+1, i+2, i+3, i+4, i+5, i+6)) > Using struct.pack('7i',i, i+1, i+2, i+3, i+4, i+5, i+6) instead of array.array gives 20% improvement in time with (not surprisingly) the same memory usage. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From downaold at gmail.com Sat Aug 7 10:05:07 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 16:05:07 +0200 Subject: Python "why" questions In-Reply-To: <20100807095348.073cd803.darcy@druid.net> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <20100807095348.073cd803.darcy@druid.net> Message-ID: On Aug 7, 2010, at 3:53 PM, D'Arcy J.M. Cain wrote: > On Sat, 7 Aug 2010 15:37:23 +0200 > Roald de Vries wrote: >>> Would said beginner also be surprised that a newborn baby is zero >>> years >>> old or would it be more natural to call them a one year old? Zero >>> based counting is perfectly natural. >> >> A new born baby is in his/her first year. It's year 1 of his/her >> life. >> For this reason, also "the year 0" doesn't exist. From the fact >> that a >> baby can be half a year old, you derive that arrays should have >> floats >> as indices? > > No. You are giving me math and logic but the subject was common > sense. Common usage counts ages as years with the second year called > "one year old" so zero based counting is common. We don't tell Aunt > Martha that little Jimmy is in his third year. We say that he is two > years old and Aunt Martha, a non-programmer, understands exactly what > we mean. Using one-based counting (first year, second year, etc.) > would be the unnatural thing, would confuse Aunt Martha and make her > spoil her apple pie and no one wants that. My point is that "0" in "Jimmy is 0" doesn't play the same role as in "item 0 of a sequence". From steve at REMOVE-THIS-cybersource.com.au Sat Aug 7 10:10:29 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Aug 2010 14:10:29 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <4c5d6955$0$28666$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 08:54:28 -0400, D'Arcy J.M. Cain wrote: > On Sat, 07 Aug 2010 13:48:32 +0200 > News123 wrote: >> It makes sense in assembly language and even in many byte code >> languages. It makes sense if you look at the internal representation of >> unsigned numbers (which might become an index) >> >> For a complete beginner common sense dictates differently and there >> might be confusion why the second element in a list has index 1. > > Would said beginner also be surprised that a newborn baby is zero years > old or would it be more natural to call them a one year old? Zero based > counting is perfectly natural. There's nothing natural about saying that a baby is zero years old. A newborn baby is "a newborn baby", then it's "one day old", "two days old", ... "one month old", "two months old", ... "one year old". In any case, we're discussing *ordinals*, not cardinal numbers. The ordinals in common English are first, second, third, ... but in computing frequently zeroth, first, second, third, ... There is a reason why mathematicians describe the integers 1, 2, 3, ... as the "Natural Numbers". It took thousands of years of human civilization before people accepted that zero was a number. In fact, for the ancient Greeks, one wasn't a number either. We still reserve the term "a number of X" to refer to more than one X, and would feel cheated if somebody offered us a number of gifts and then gave us only a single one. "Number" refers to a plurality, and one is singular. According to Euclid, one was the monad, the indivisible unit from which the numbers were formed. As late as 1537, the German mathematician Jacob Kobel wrote "1 is no number, but it is a generatrix, beginning and foundation for all other numbers". In short, there's nothing natural about counting numbers at all, let alone whether we should start at 0 or 1. P.S. I don't know if I should be gratified or disappointed that nobody has yet quoted Stan Kelly-Bootle: "Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." -- Steven From thomas at jollans.com Sat Aug 7 10:29:16 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 16:29:16 +0200 Subject: Python "why" questions In-Reply-To: <4c5d61cc$0$28666$c3e8da3@news.astraweb.com> References: <4c5d61cc$0$28666$c3e8da3@news.astraweb.com> Message-ID: <4C5D6DBC.7050508@jollans.com> On 08/07/2010 03:38 PM, Steven D'Aprano wrote: > On Sat, 07 Aug 2010 14:00:59 +0200, Thomas Jollans wrote: > >> On 08/07/2010 05:05 AM, Default User wrote: >>> >From "the emperor's new clothes" department: >>> >>> 1) Why do Python lists start with element [0], instead of element [1]? >>> "Common sense" would seem to suggest that lists should start with [1]. >> >> As others have pointed out, there is a nice argument to be made for >> zero-based indices. However, the killer reason is: "it's what everybody >> else does." > > I'll have you know that there are still some Pascal programmers in the > world, thank you. > > > >> As it stands, the only perceived problem with zero-based >> indices is that it's one of the many tiny confusions that new >> programmers face. On the other hand, it's the way nearly every other >> popular programming language does it, and therefore, it's the way almost >> every programmer likes to think about sequences. > > It didn't take me long to get used to thinking in zero-based indexes, but > years later, I still find it hard to *talk* in zero-based indexes. It's > bad enough saying that the first element in a list in the zeroth element, > but that the second element is the first makes my head explode... zeroth oneth twoth ;-) (element no. one is a better way of pronouncing it.) > > >> Also, it has the nice property that, for an infinite sequence, every >> integer makes sense as an index (in Python). > > Er, what's the -1th element of an infinite sequence? well, it's the first from the other end. The infinite bit is in between, thank you very much. ;-) From no.email at please.post Sat Aug 7 10:37:24 2010 From: no.email at please.post (kj) Date: Sat, 7 Aug 2010 14:37:24 +0000 (UTC) Subject: Unicode error References: <44aaebca-d5b2-4efa-a9e8-83a29dc159d3@k19g2000yqc.googlegroups.com> <4c497212$0$28634$c3e8da3@news.astraweb.com> <4c5c8cc8$0$28666$c3e8da3@news.astraweb.com> <8c4fouF1bdU1@mid.individual.net> <4c5d4ad9$0$28666$c3e8da3@news.astraweb.com> Message-ID: In <4c5d4ad9$0$28666$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >On Sat, 07 Aug 2010 19:28:56 +1200, Gregory Ewing wrote: >> Steven D'Aprano wrote: >>> "No memory? No disk space? No problem! Just a flesh wound!" What's >>> the point of that? >> >> +1 QOTW >While I'm always happy to be nominated for QOTW, in this case I didn't >say it, and the nomination should go to KJ. (The ol' "insert Monty Python reference" move: it never fails...) From nobody at nowhere.com Sat Aug 7 10:41:56 2010 From: nobody at nowhere.com (Nobody) Date: Sat, 07 Aug 2010 15:41:56 +0100 Subject: Is there any way to minimize str()/unicode() objects memory usage [Python 2.6.4] ? References: <756473de-1ba7-4a11-9dd5-1d4703dacd75@b4g2000pra.googlegroups.com> <4c5cb088$0$28666$c3e8da3@news.astraweb.com> <4953a3d3-4163-4f13-9fe7-e52ccf3dd49f@q21g2000prm.googlegroups.com> Message-ID: On Fri, 06 Aug 2010 18:39:27 -0700, dmtr wrote: > Steven, thank you for answering. See my comments inline. Perhaps I > should have formulated my question a bit differently: Are there any > *compact* high performance containers for unicode()/str() objects in > Python? By *compact* I don't mean compression. Just optimized for > memory usage, rather than performance. > > What I'm really looking for is a dict() that maps short unicode > strings into tuples with integers. Use UTF-8 encoded strings (str/bytes) as keys rather than unicode objects. From nobody at nowhere.com Sat Aug 7 10:48:17 2010 From: nobody at nowhere.com (Nobody) Date: Sat, 07 Aug 2010 15:48:17 +0100 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> Message-ID: On Sat, 07 Aug 2010 09:53:48 -0400, D'Arcy J.M. Cain wrote: >> A new born baby is in his/her first year. It's year 1 of his/her life. >> For this reason, also "the year 0" doesn't exist. From the fact that a >> baby can be half a year old, you derive that arrays should have floats >> as indices? > > No. You are giving me math and logic but the subject was common > sense. Common usage counts ages as years with the second year called > "one year old" so zero based counting is common. We don't tell Aunt > Martha that little Jimmy is in his third year. Apparently, the Japanese used to (before they started adopting western conventions). I.e. ages were given as "in his tenth year" (meaning nine years old). From albert at spenarnc.xs4all.nl Sat Aug 7 10:48:29 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 07 Aug 2010 14:48:29 GMT Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Roy Smith wrote: >In article <4c55fe82$0$9111$426a34cc at news.free.fr>, > candide wrote: > >> Python is an object oriented langage (OOL). The Python main >> implementation is written in pure and "old" C90. Is it for historical >> reasons? >> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more >> suitable to implement an OOL with another one. > >One thing that comes to mind is that it's much easier to distribute C >libraries than C++ libraries. > >If I compile a main program with one C compiler and you compile a >dynamically loaded library with another C compiler on the same box, the >odds are pretty good they'll interoperate without any problems. > >Not at all so with C++ compilers. The linkage is *way* more >complicated. Not just how the two compilers do name mangling, but how >they handle exceptions, RVO, and a zillion other details. Pretty much >the only way to make it work is to compile everything with exactly the >same compiler. That would make it pretty close to impossible for people >to take a Python core distribution and add their own extension modules >to it. We had a similar discussion on comp.lang.forth. The bottom line is that to implement a programming language you want to use a simpler programming language, not a more complicated one. Then there is a secondary requirement, that language must allow sufficient access to low level features to allow decent performance. A third aspect is that Linux/Unices as well as Windows assume OS interaction in terms of c-libraries. Any intermediary is inconvenient at least. Or in one catch phrase: " To implement a programming language you need a high level assembler like C." (We went on whether Forth would be a suitable high level assembler for Haskell. It would beat C++ -- not C -- for implementing Python, that much I'm sure.) Undoubtedly C is the right choice to implement Python. Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From albert at spenarnc.xs4all.nl Sat Aug 7 11:13:00 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 07 Aug 2010 15:13:00 GMT Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Roy Smith wrote: >In article , > Lawrence D'Oliveiro wrote: > >> In message , Roy Smith wrote: >> >> > C++, for all its flaws, had one powerful feature which made it very >> > popular. It is a superset of C. >> >> Actually, it never was. > >Yes, there are a few corner cases where valid C syntax has different >semantics in C and C++. But, they are very few. Calling C++ a superset >of C is essentially correct. One aspect of C++ is that all standard functions of C are called in the same way. A large part of programs consists of stringing API calls together. Those require little work to upgrade to C++. So from a practical point of view this is very much true. > >It is certainly correct from the level of a risk-averse development >manager deciding if he or she is willing to use C++ for the first time. >Fear of the unknown is a powerful deterrent. It's a lot easier to >accept something like C++ because "it's just a superset of C, and we've >been using C for years". Even if it is overhyped, the C++ compiler vendors certainly tried to make it happen. > >I suspect the same effect contributed to Java's success as well. "Look, >it's got curly braces and semicolons. It's just like C!" Of course! Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From nobody at nowhere.com Sat Aug 7 11:24:09 2010 From: nobody at nowhere.com (Nobody) Date: Sat, 07 Aug 2010 16:24:09 +0100 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: On Sat, 07 Aug 2010 13:48:32 +0200, News123 wrote: >> "Common sense" is wrong. There are many compelling advantages to >> numbering from zero instead of one: >> >> http://lambda-the-ultimate.org/node/1950 > > It makes sense in assembly language and even in many byte code languages. > It makes sense if you look at the internal representation of unsigned > numbers (which might become an index) It also makes sense mathematically. E.g. for an MxN array stored as a 1-dimensional array, the element a[j][i] is at index j * N + i with zero-based indices but: (j-1) * N + (i-1) + 1 = j * N + i - N with one-based indices. IOW, if a language uses one-based indices, it will inevitably end up converting to and from zero-based indices under the hood, and may end up forcing the user to do likewise if they need to do their own array manipulation. From downaold at gmail.com Sat Aug 7 11:38:37 2010 From: downaold at gmail.com (Roald de Vries) Date: Sat, 7 Aug 2010 17:38:37 +0200 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <48C30F62-B3AE-4F59-A9F3-E9DE54C39CCE@gmail.com> On Aug 7, 2010, at 5:24 PM, Nobody wrote: > On Sat, 07 Aug 2010 13:48:32 +0200, News123 wrote: > >>> "Common sense" is wrong. There are many compelling advantages to >>> numbering from zero instead of one: >>> >>> http://lambda-the-ultimate.org/node/1950 >> >> It makes sense in assembly language and even in many byte code >> languages. >> It makes sense if you look at the internal representation of unsigned >> numbers (which might become an index) > > It also makes sense mathematically. E.g. for an MxN array stored as a > 1-dimensional array, the element a[j][i] is at index > > j * N + i Nice example! From pengyu.ut at gmail.com Sat Aug 7 11:48:47 2010 From: pengyu.ut at gmail.com (Peng Yu) Date: Sat, 7 Aug 2010 10:48:47 -0500 Subject: How to match patterns like XX YY XX YY? (regex) Message-ID: Hi, Suppose that I have strings like the following test(a b)a b test(xy uv)xy uv ... I want to change them to test(a)a test(b)b test(xy)xy test(uv)uv ... The problem is that I don't know how to capture pattern that repeat itself (like 'a' and 'xy' in the example). I could use 'test\((\w+) (\w+)\)(\w) (\w)', but it will capture something like 'test(a b)x y', which I don't want to. I'm wondering if there is way to capture recurring patterns. -- Regards, Peng From wolftracks at invalid.com Sat Aug 7 12:12:50 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 09:12:50 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: Message-ID: On 8/6/2010 7:18 PM, Philip Semanchuk wrote: > > On Aug 6, 2010, at 3:14 PM, W. eWatson wrote: > >> I must be missing something. I tried this. (Windows, IDLE, Python 2.5) > > Yes, as Benjamin Kaplan pointed out and as I said in the email where I > posted this code snippet, "dependencies is a list of custom classes that > represent modules we need (e.g. numpy)." The code I posted was not meant > to be a complete working example. It's part of a larger piece of code > that I didn't have time to cook down to a simpler, self-sufficient whole. > > Also, in your list you've got "numyp" instead of "numpy". > > Also, at the top of your code you have "import numpy" and "import scipy" > which defeats the purpose of this code. > Good. It worked. Are there other attributes of a module that can help identify it further? Release date, ...? From alex at moreati.org.uk Sat Aug 7 12:15:26 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Sat, 7 Aug 2010 09:15:26 -0700 (PDT) Subject: How to match patterns like XX YY XX YY? (regex) References: Message-ID: <9af8026e-322c-4ca3-9afc-aafda85bfac3@j8g2000yqd.googlegroups.com> On Aug 7, 4:48?pm, Peng Yu wrote: > The problem is that I don't know how to capture pattern that repeat > itself (like 'a' and 'xy' in the example). I could use 'test\((\w+) > (\w+)\)(\w) (\w)', but it will capture something like 'test(a b)x y', > which I don't want to. > > I'm wondering if there is way to capture recurring patterns. Back references can deal with repetition. Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> re.match(r'test\((\w+) (\w+)\)\1 \2', 'test(xy uv)xy uv').groups() ('xy', 'uv') >>> re.match(r'test\((\w+) (\w+)\)\1 \2', 'test(a b)x y') >>> From zyzhu2000 at gmail.com Sat Aug 7 12:26:39 2010 From: zyzhu2000 at gmail.com (GZ) Date: Sat, 7 Aug 2010 09:26:39 -0700 (PDT) Subject: Sequential Object Store Message-ID: <6e21725a-e5c4-45be-81c4-5a9fd79df413@d8g2000yqf.googlegroups.com> Hi All, I need to store a large number of large objects to file and then access them sequentially. I am talking about a few thousands of objects and each with size of a few hundred kilobytes, and total file size a few gigabytes. I tried shelve, but it is not good at sequentially accessing the data. In essence, shelve.keys() takes forever. I am wondering if there is a module that can persist a stream of objects without having to load everything into memory. (For this reason, I think Pickle is out, too, because it needs everything to be in memory.) Thanks, GZ From albert at spenarnc.xs4all.nl Sat Aug 7 13:02:54 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 07 Aug 2010 17:02:54 GMT Subject: measuring a function time References: <831343.82061.qm@web50006.mail.re2.yahoo.com> <4c5178ae$0$11091$c3e8da3@news.astraweb.com> Message-ID: In article <4c5178ae$0$11091$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Thu, 29 Jul 2010 14:42:58 +0200, Matteo Landi wrote: > >> This should be enough >> >>>>>import time >>>>>tic = time.time() >>>>>function() >>>>>toc = time.time() >>>>>print toc - tic > >You're typing that in the interactive interpreter, which means the timer >is counting the seconds while you're typing subsequent commands. At the >very least, you need to put that code into a function. There is an alternative, for once the semicolon comes in handy: >>>from time import * >>> x=time(); function(); print time()-x 6.551980773430 > >The best way to time small code snippets and fast functions is with the >timeit module. > >-- >Steven Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From python.list at tim.thechases.com Sat Aug 7 13:12:04 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 07 Aug 2010 12:12:04 -0500 Subject: Struggling to convert a mysql datetime object to a python string of a different format In-Reply-To: <4C5D0108.2090401@cyta.gr> References: <48a03ccb-4933-4eff-be9e-94bf1d098181@i24g2000yqa.googlegroups.com> <8799d586-39d3-44bc-bb2f-86e4e720f7fe@o19g2000yqb.googlegroups.com> <4C5B4D6E.1070501@tim.thechases.com> <4C5D0108.2090401@cyta.gr> Message-ID: <4C5D93E4.9090605@tim.thechases.com> On 08/07/10 01:45, ???????? ?????? wrote: >> # variant B >> for row in dataset: >> host, hits, dt = row >> # rest of your code here > > So, row is a tuple comprising of 3 fields, and host, hist, dt > are variables assigned each one of row's tuple values by > breaking it to it's elements. > > But what kind of objects is host, hits, dt that containes the > row's tuple data themselves? tuples or lists and why? They contain the data of each respective element. E.g.: >>> dataset = [ ... (1, 'a', True), ... (2, 'b', False), ... ] >>> >>> for one, two, three in dataset: ... print 'one%s = %r' % (type(one), one) ... print 'two%s = %r' % (type(two), two) ... print 'three%s = %r' % (type(three), three) ... print '-' * 10 ... one = 1 two = 'a' three = True ---------- one = 2 two = 'b' three = False ---------- So likely in your case, "host" is a string, "hits" is an int, and "dt" is a datetime.datetime object. The three of them together are the row as represented as a tuple: >>> type( (host, hits, dt) ) which you can see in your own code by changing it temporarily to: for row in dataset: print type(row), len(row) >> # variant C >> for host, hits, dt in row: >> # rest of your code here >> > host, hits, data each and every one of them hold a piece of the row's > tuple values. > > But what happens in here? The same as Variant B, only it doesn't use the intermediate tuple "row". > 'for host, hits, dt in dataset:' > > Here we don't have the row tuple. So what tthose variabels store, and in > what datatype they strore info in and what is the difference between this > and > > 'for host, hits, dt in row:' The second one will fail because it would be the same as for tpl in row: host, hits, dt = tpl The 1st time through the loop, tpl=host; the 2nd time through the loop, tpl=hits; and the 3rd time through the loop, tpl=dt Attempting to do a tuple assignment (that 2nd line) will attempt to do something like host, hits, dt = "example.com" # 1st pass through the loop host, hits, dt = 42 # 2nd pass through the loop host, hits, dt = datetime(2010,7,5)# 3rd pass through the loop In most cases, it will fail on the first pass through the loop (except in the freak case your string value happens to have 3 characters: >>> host, hits, dt = "abc" #exactly 3 letters >>> host 'a' ) > If the fieds datatypes returned form the database are for exmaple page > varchar(50) , hits inteeger[11], date datetime then > the when python grabs those results fields it would translate them to > 'page as string' , (hits as int) , 'date as string' respectively? > Whcih emans it translated those fileds returned to the most > appropriate-most close to prototype stored in database' datatypes > automatically? Yes, except the internals (of the DB module...in this case mysql) are smart enough to translate the date into a datetime.datetime object, instead of a string. >> row = (host, hits, dt > > Would that be a row or a tuple when joined? A "row" is a conceptual thing -- one row of data from your query. It can be represented as either a tuple or a list (or any iteratable that represents "things in this row"). In this case (and I believe each row returned by a cursor.fetch*() call), it was tuple. I hope that helps...it would behoove you to experiment with tuple-assignments such as the example code above so that you understand what it's doing in each case. -tkc From nikos.the.gr33k at gmail.com Sat Aug 7 13:29:09 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 10:29:09 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex Message-ID: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Hello guys! Need your precious help again! In every html file i have in the very first line a page_id fro counetr countign purpsoes like in a format of a comment like this: and so on. every html file has its one page_id How can i grab that string representaion of a number from inside the .html file using regex and convert it to an integer value? # ============================== # open current html template and get the page ID number # ============================== f = open( '/home/webville/public_html/' + page ) #read first line of the file firstline = f.readline() page_id = re.match( '', firstline ) print ( page_id ) From nikos.the.gr33k at gmail.com Sat Aug 7 13:31:38 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 10:31:38 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: i also dont know what wrong with this line: host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] hostmatch = re.search('cyta', host) if cookie.has_key('visitor') != 'nikos' or hostmatch is None: # do stuff the 'stuff' never gets executed, while i ant them to be as long as i dont have regex match! From fetchinson at googlemail.com Sat Aug 7 13:43:11 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 7 Aug 2010 19:43:11 +0200 Subject: Smith-Waterman Algorithm in Python In-Reply-To: <4C5D52BE.302@gmaiil.com> References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> <4C5D52BE.302@gmaiil.com> Message-ID: >>> Does any one about any implementation of classical Smith Waterman >>> local alignment algorithm and it's variants for aligning natural >>> language text? >>> >> >> Please see http://tinyurl.com/2wy43fh >> >> > Every one of the first 20 entries is either the OP questions or your reply. And you think it was there before the OP sent his message? Oh wait, did you just invent a time machine? :) > Daniel - you are no help at all, and no funny. Actually, I'm damn funny! :) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From gelonida at gmail.com Sat Aug 7 13:53:55 2010 From: gelonida at gmail.com (Gelonida) Date: Sat, 07 Aug 2010 19:53:55 +0200 Subject: cscope like source code navigation for python code Message-ID: Hi, I'm using g?vim and its c-scope plugin for browsing C-code. What would be a good way of navigating larger python projects with vim? thanks for any suggestions From python at mrabarnett.plus.com Sat Aug 7 14:12:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 19:12:18 +0100 Subject: iterators and continuing after a StopIteration In-Reply-To: References: Message-ID: <4C5DA202.2020504@mrabarnett.plus.com> Roald de Vries wrote: > Hi all, > > > I have a list that I'm iterating over, and during the iteration items > are appended. Moreover, it is iterated over in two nested loops. If the > inner loop comes to the end, I want the outer loop to append an item. Is > there a way to do this? Because once an iterator has raised a > StopIteration, it can not go to a next item anymore. > > Aside question: is there a rationale for the current behavior? To me it > seems more natural to continue iteration after appending new items. > > > I want to use it for a graph walk. > > nodes is a list of all nodes, > edges is an on the fly constructed list of edges in the order of visiting, > initial_nodes is a list of (root) nodes > > edges = [] > edge_it = iter(edges) > for node in initial_nodes: > edges += node.leaving_edges > try: > while True: > edge = edge_it.next() > edges += edge.head.leaving_edges > except StopIteration: > pass > > > Thanks in advance, cheers, Roald You could add the new edges to another list: edges = [] pending_edges = [] for node in initial_nodes: pending_edges += node.leaving_edges while pending_edges: new_edges = [] for edge in pending_edges: new_edges += edge.head.leaving_edges edges += pending_edges pending_edges = new_edges or use indexing: edges = [] for node in initial_nodes: edges += node.leaving_edges index = 0 while index < len(edges): edges += edges[index].head.leaving_edges index += 1 From python at mrabarnett.plus.com Sat Aug 7 14:20:46 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 19:20:46 +0100 Subject: How to match patterns like XX YY XX YY? (regex) In-Reply-To: References: Message-ID: <4C5DA3FE.7000109@mrabarnett.plus.com> Peng Yu wrote: > Hi, > > Suppose that I have strings like the following > > test(a b)a b > test(xy uv)xy uv > ... > > I want to change them to > > test(a)a test(b)b > test(xy)xy test(uv)uv > ... > > > The problem is that I don't know how to capture pattern that repeat > itself (like 'a' and 'xy' in the example). I could use 'test\((\w+) > (\w+)\)(\w) (\w)', but it will capture something like 'test(a b)x y', > which I don't want to. > > I'm wondering if there is way to capture recurring patterns. > Use backreferences (it's in the documentation): pattern = re.compile(r'test\((\w+) (\w+)\)\1 \2') From python at mrabarnett.plus.com Sat Aug 7 14:24:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 19:24:52 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DA4F4.7080706@mrabarnett.plus.com> ????? wrote: > Hello guys! Need your precious help again! > > In every html file i have in the very first line a page_id fro counetr > countign purpsoes like in a format of a comment like this: > > > > > > and so on. every html file has its one page_id > > How can i grab that string representaion of a number from inside > the .html file using regex and convert it to an integer value? > > # ============================== > # open current html template and get the page ID number > # ============================== > > f = open( '/home/webville/public_html/' + page ) > > #read first line of the file > firstline = f.readline() > > page_id = re.match( '', firstline ) > print ( page_id ) Use group capture: found = re.match(r'', firstline).group(1) print(page_id) From python at mrabarnett.plus.com Sat Aug 7 14:27:58 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 19:27:58 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DA5AE.90307@mrabarnett.plus.com> ????? wrote: > i also dont know what wrong with this line: > > host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] > > hostmatch = re.search('cyta', host) > > if cookie.has_key('visitor') != 'nikos' or hostmatch is None: > # do stuff > > the 'stuff' never gets executed, while i ant them to be as long as i > dont have regex match! Try printing out repr(host). Does it contain "cyta"? From nikos.the.gr33k at gmail.com Sat Aug 7 14:48:02 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 11:48:02 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: On 7 ???, 21:27, MRAB wrote: > ????? wrote: > > i also dont know what wrong with this line: > > > host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] > > > hostmatch = re.search('cyta', host) > > > if cookie.has_key('visitor') != 'nikos' or hostmatch is None: > > ? ? ?# do stuff > > > the 'stuff' never gets executed, while i want them to be as long as i > > dont have regex match! > > Try printing out repr(host). Does it contain "cyta"? Yes it does contain it as print shown! is something wrong with this line in logic or syntax? if cookie.has_key('visitor') != 'nikos' or re.search('cyta', host) is None: # do database stuff From nikos.the.gr33k at gmail.com Sat Aug 7 14:51:46 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 11:51:46 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: On 7 ???, 21:24, MRAB wrote: > Use group capture: > > ? ? ?found = re.match(r'', firstline).group(1) > ? ? ?print(page_id) Worked like a charm! Thanks a lot! So match method here not only searched for the string representation of the number but also convert it to integer as well? r stand for retrieve the string here? and group? Wehn a regex searched a .txt file when is retrieving something for it always retrieve it as string right? or can get it as a number as well? From clp2 at rebertia.com Sat Aug 7 14:57:50 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 7 Aug 2010 11:57:50 -0700 Subject: Need Translation library In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 5:04 AM, siva moorthy wrote: > hi all, > i wish to code for translation in python > > i want to parse a python program itself and make some keyword changes > (replacement) > tell me any library to parse python source code Depending on you needs, one of: http://docs.python.org/library/tokenize.html http://docs.python.org/library/ast.html Cheers, Chris -- http://blog.rebertia.com From thomas at jollans.com Sat Aug 7 15:03:21 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 21:03:21 +0200 Subject: How to grab a number from inside a .html file using regex In-Reply-To: References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DADF9.9090806@jollans.com> On 08/07/2010 08:51 PM, ????? wrote: > On 7 ???, 21:24, MRAB wrote: > >> Use group capture: >> >> found = re.match(r'', firstline).group(1) >> print(page_id) > > Worked like a charm! Thanks a lot! > > So match method here not only searched for the string representation > of the number but also convert it to integer as well? > > r stand for retrieve the string here? r"xyz" is a raw string literal. That means that backslash escapes are turned off -- r'\n' == '\\n' > > and group? > > Wehn a regex searched a .txt file when is retrieving something for it > always retrieve it as string right? or can get it as a number as well? From python at mrabarnett.plus.com Sat Aug 7 15:07:49 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 20:07:49 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DAF05.1080008@mrabarnett.plus.com> ????? wrote: > On 7 ???, 21:27, MRAB wrote: >> ????? wrote: >>> i also dont know what wrong with this line: >>> host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] >>> hostmatch = re.search('cyta', host) >>> if cookie.has_key('visitor') != 'nikos' or hostmatch is None: >>> # do stuff >>> the 'stuff' never gets executed, while i want them to be as long as i >>> dont have regex match! >> Try printing out repr(host). Does it contain "cyta"? > > Yes it does contain it as print shown! > > is something wrong with this line in logic or syntax? > > if cookie.has_key('visitor') != 'nikos' or re.search('cyta', host) is > None: > # do database stuff > You said "i want them to be as long as i dont have regex match". re.search('cyta', host) will return None if there's no match, but you said "Yes it does contain it", so there _is_ a match, therefore: hostmatch is None is False. From nagle at animats.com Sat Aug 7 15:14:46 2010 From: nagle at animats.com (John Nagle) Date: Sat, 07 Aug 2010 12:14:46 -0700 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> On 8/7/2010 5:00 AM, Thomas Jollans wrote: > On 08/07/2010 05:05 AM, Default User wrote: >> > From "the emperor's new clothes" department: >> >> 1) Why do Python lists start with element [0], instead of element [1]? >> "Common sense" would seem to suggest that lists should start with [1]. > > As others have pointed out, there is a nice argument to be made for > zero-based indices. However, the killer reason is: "it's what everybody > else does." FORTRAN, MATLAB, and Octave all use 1-based subscripts. The languages which have real multidimensional arrays, rather than arrays of arrays, tend to use 1-based subscripts. That reflects standard practice in mathematics. John Nagle From wolftracks at invalid.com Sat Aug 7 15:17:57 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 12:17:57 -0700 Subject: Python Portability In-Reply-To: References: Message-ID: On 8/6/2010 2:23 AM, Lawrence D'Oliveiro wrote: > In message, W. eWatson wrote: > >> I made a one character change to it and sent him the new py file. He can't >> execute it. > > What exactly was the problem? > I put a minus sign in front of a variable. I had him use the shell to check his version numpy, which he just provided. version -- 1.4.0. As I think I mentioned above, he's probably not using the same numpy version that I use 1.2.0. Don't ask for an explanation of why I want him on 1.2.0. :-) I think that pretty much wraps up the problem. He needs to get back to 1.2.0. Presumably I have him somehow delete the numpy site-package, the numpy 1.2.0 package? Just drill his way dow from the .../lib/site_packages? Then install 1.2.0. He's missed the boat on that before by not following instructions. From python at mrabarnett.plus.com Sat Aug 7 15:17:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 20:17:59 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <4C5DB167.4000602@mrabarnett.plus.com> ????? wrote: > On 7 ???, 21:24, MRAB wrote: > >> Use group capture: >> >> found = re.match(r'', firstline).group(1) >> print(page_id) > > Worked like a charm! Thanks a lot! > > So match method here not only searched for the string representation > of the number but also convert it to integer as well? > > r stand for retrieve the string here? > > and group? > > Wehn a regex searched a .txt file when is retrieving something for it > always retrieve it as string right? or can get it as a number as well? The 'r' prefix makes it a 'raw string literal'. That means that the string literal won't treat backslashes as special. Before raw string literals were added to the Python language I would have needed to write: '' instead. (Actually, that's not strictly true in this case, because \d doesn't have a special meaning Python strings, but it's a good idea to use raw string literals habitually when writing regexes in order to reduce the chance of forgetting them when they _are_ necessary. Well, that's what I think, anyway. :-)) From nikos.the.gr33k at gmail.com Sat Aug 7 15:36:27 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 12:36:27 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> On 7 ???, 22:07, MRAB wrote: > re.search('cyta', host) will return None if there's no match, but you > said "Yes it does contain it", so there _is_ a match, therefore: > > ? ? ?hostmatch is None > > is False. The code block inside the if structure must be executes ONLY if the 'visitor' cookie is not set to the client's browser or the hostname address of the client doesn't contain in it the string 'cyta'. # ====================================== # do not increment the counter if a Cookie is set to the visitors browser already # ====================================== if cookie.has_key('visitor') != 'nikos' or re.search('cyta', host) is None: I still don't get it :) From nikos.the.gr33k at gmail.com Sat Aug 7 15:37:54 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 12:37:54 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> Message-ID: <0b6075f3-2f44-44d8-844f-166ac90e42c7@m1g2000yqo.googlegroups.com> On 7 ???, 22:17, MRAB wrote: > ????? wrote: > > On 7 ???, 21:24, MRAB wrote: > > >> Use group capture: > > >> ? ? ?found = re.match(r'', firstline).group(1) > >> ? ? ?print(page_id) > > > Worked like a charm! Thanks a lot! > > > So match method here not only searched for the string representation > > of the number but also convert it to integer as well? > > > r stand for retrieve the string here? > > > and group? > > > Wehn a regex searched a .txt file when is retrieving something for it > > always retrieve it as string right? or can get it as a number as well? > > The 'r' prefix makes it a 'raw string literal'. That means that the > string literal won't treat backslashes as special. Before raw string > literals were added to the Python language I would have needed to write: > > ? ? ?'' > > instead. > > (Actually, that's not strictly true in this case, because \d doesn't > have a special meaning Python strings, but it's a good idea to use raw > string literals habitually when writing regexes in order to reduce the > chance of forgetting them when they _are_ necessary. Well, that's what I > think, anyway. :-)) Couln't agree more! As the saying goes, better safe than sorry! :-) From thomas at jollans.com Sat Aug 7 15:52:53 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 07 Aug 2010 21:52:53 +0200 Subject: How to grab a number from inside a .html file using regex In-Reply-To: <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> Message-ID: <4C5DB995.4060502@jollans.com> On 08/07/2010 09:36 PM, ????? wrote: > cookie.has_key('visitor') != 'nikos' This is always True. has_key returns a bool, which is never equal to any string, even 'nikos'. From martin at v.loewis.de Sat Aug 7 16:00:39 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 07 Aug 2010 22:00:39 +0200 Subject: Python Portability--Not very portable? In-Reply-To: References: Message-ID: <4C5DBB67.6090700@v.loewis.de> > As an example, my inexperienced Python partner 30 miles away has gotten > out of step somehow. I think by installing a different version of numpy > than I use. I gave him a program we both use months ago, and he had no > trouble. (We both use IDLE on 2.5). I made a one character change to it > and sent him the new py file. He can't execute it. I doubt he has > changed anything in the intervening period. You'll find that many people will be very skeptical wrt. this story: this kind of thing really isn't supposed to happen, and it's difficult to believe that it failed just because of the one-character change. You already said that that the change was adding a minus sign somewhere. Can you now kindly also report what then the problem was that your partner encountered (specific error message would be appreciated). > A further example. Months ago I decided to see if I could compile a > program to avoid such problems as above. I planned to satisfy that need, > and see if I could distribute some simple programs to non-Python > friends. I pretty well understand the idea,and got it working with a > small program. It seemed like a lot of manual labor to do it. It's a lot of manual labor only the first time. When you package the next version of the same software, manual labor should be minimal. Regards, Martin From pavlovevidence at gmail.com Sat Aug 7 16:02:56 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 7 Aug 2010 13:02:56 -0700 (PDT) Subject: Nice way to cast a homogeneous tuple References: <4c50eb46$0$28664$c3e8da3@news.astraweb.com> <1pm7i7-473.ln1@satorlaser.homedns.org> Message-ID: <49f9d367-20fc-442f-b397-9d50ffb391f2@i4g2000prf.googlegroups.com> On Aug 7, 6:54?am, Albert van der Horst wrote: > In article <1pm7i7-473.... at satorlaser.homedns.org>, > Ulrich Eckhardt ? wrote: > > > > >Steven D'Aprano wrote: > >> Perhaps I have been misinformed, but my understanding of C type-casts is > >> that (where possible), a cast like `int(var)` merely tells the compiler > >> to temporarily disregard the type of var and treat it as if it were an > >> int. In other words, it's a compiler instruction rather than a conversion > >> function. > > >You are misinformed. The result of a cast in C or C++ behaves as if a > >temporary was created: > > > ?int x = 0; > > ?unsigned(x)--; // invalid, compiler error > > >Now, where this distinction gets blurred is when you are casting pointers: > > > ?(*(unsigned*)&x)--; > > >or, in C++, references: > > > ?reinterpret_cast(x)--; > > >Technically, these are still invalid though, only that they give you > >undefined behaviour at runtime instead of a compiler error, but those are > >already very fine details of the according standards. > > There is just one conclusion that should remain from this. > If you're ever going to program in in c or c++, casts are to be > avoided like the plague. You sound as if you don't usually program in C or C++, which suggests to me that you shouldn't be offering advice on how to program in these languages. I program in C all the time, and I can tell you you can't get very far in C or C++ without sometimes resorting to type-casts. (C ++ offers more help for class types, but there's not a lot you can do to avoid casts for converting between built-in types.) The CPython interpreter uses type casts all over the place, BTW. > (And recently they have been thought over in > C++ to be split in different names with the reinterpret_cast the most > dangerous, but at least it is a big read flag.) If by "recently" you mean "10 years ago", and by "thought over" you mean "standardized and implemented". > I see an analogy with goto's in my experience. Once you understand > how bad they are, you discover there is always a better solution. What better solution do you propose for this that doesn't use type- casting? int a, b; double ratio; ratio = (double)a/b; > It is unfortunate that cast's in Python share the same name, but > it is kind of unavoidable because it is about the proper CS name to use. Not really. Very few people call int(), float(), and company "type casts". They aren't type casts at all, they are constructors that sometimes have the same semantics as type casts in C. Carl Banks From python at mrabarnett.plus.com Sat Aug 7 16:07:01 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 21:07:01 +0100 Subject: How to grab a number from inside a .html file using regex In-Reply-To: <4C5DB995.4060502@jollans.com> References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> <4C5DB995.4060502@jollans.com> Message-ID: <4C5DBCE5.4050803@mrabarnett.plus.com> Thomas Jollans wrote: > On 08/07/2010 09:36 PM, ????? wrote: >> cookie.has_key('visitor') != 'nikos' > > This is always True. has_key returns a bool, which is never equal to any > string, even 'nikos'. I missed that bit! :-) Anyway, the OP said "the 'stuff' never gets executed". Kinda puzzling... From nikos.the.gr33k at gmail.com Sat Aug 7 16:29:54 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 7 Aug 2010 13:29:54 -0700 (PDT) Subject: How to grab a number from inside a .html file using regex References: <98f03dea-2cef-47ea-bdb1-a67fe2870ad6@q35g2000yqn.googlegroups.com> <201c7a33-71a2-4375-a6ec-d8635ca45e80@t26g2000yqt.googlegroups.com> Message-ID: <431664b9-f813-4523-b54d-b3697eb8bf24@y11g2000yqm.googlegroups.com> On 7 ???, 22:52, Thomas Jollans wrote: > On 08/07/2010 09:36 PM, ????? wrote: > > > cookie.has_key('visitor') != 'nikos' > > This is always True. has_key returns a bool, which is never equal to any > string, even 'nikos'. if cookie.has_key('visitor') or re.search('cyta', host) is None: adresses the problem :-) Thanks alot Thomas and MRAB for ALL your help! From torriem at gmail.com Sat Aug 7 17:01:37 2010 From: torriem at gmail.com (Michael Torrie) Date: Sat, 07 Aug 2010 15:01:37 -0600 Subject: Python Portability In-Reply-To: References: Message-ID: <4C5DC9B1.1040501@gmail.com> On 08/07/2010 01:17 PM, W. eWatson wrote: > Presumably I have him somehow delete the numpy site-package, the numpy > 1.2.0 package? Just drill his way dow from the .../lib/site_packages? > Then install 1.2.0. He's missed the boat on that before by not following > instructions. Wait. I'm confused. Aren't you distributing your python app as an executable, with the interpreter and all the libraries bundled? From martin at v.loewis.de Sat Aug 7 17:26:31 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 07 Aug 2010 23:26:31 +0200 Subject: Python Portability In-Reply-To: References: Message-ID: <4C5DCF87.4000800@v.loewis.de> Am 07.08.2010 23:01, schrieb Michael Torrie: > On 08/07/2010 01:17 PM, W. eWatson wrote: >> Presumably I have him somehow delete the numpy site-package, the numpy >> 1.2.0 package? Just drill his way dow from the .../lib/site_packages? >> Then install 1.2.0. He's missed the boat on that before by not following >> instructions. > > Wait. I'm confused. Aren't you distributing your python app as an > executable, with the interpreter and all the libraries bundled? No, he was really mentioning two distinct scenarios. In the one discussed above, the remote machine had all stuff manually installed, and somehow got the actual Python program copied into it. Regards, Martin From stefan_ml at behnel.de Sat Aug 7 17:58:20 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 07 Aug 2010 23:58:20 +0200 Subject: Problem with Elementtree and XMLSchem instance type In-Reply-To: <4C52D1F6.7020209@adm.umu.se> References: <4C52D1F6.7020209@adm.umu.se> Message-ID: Roland Hedberg, 30.07.2010 15:21: > I have the following XML snippet: > > xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > xmlns:fed="http://docs.oasis-open.org/wsfed/federation/200706" > xsi:type="fed:SecurityTokenServiceType"> > .... > > > This part after parsing with Elementtree gives me an Element instance > with the following properties: > >> tree.tag > {urn:oasis:names:tc:SAML:2.0:metadata}RoleDescriptor >> tree.keys() > ['{http://www.w3.org/2001/XMLSchema-instance}type'] >> tree['{http://www.w3.org/2001/XMLSchema-instance}type'] > fed:SecurityTokenServiceType > > And there is the problem, I've lost the coupling between the prefix > 'fed' and the namespace > "http://docs.oasis-open.org/wsfed/federation/200706". > > Is there any way I can get at the prefix<-> namespace mapping from an > Element instance ? > I've read the documentation I can find and there is nothing that tells > me how to get at the mapping. > > If I print the Element instance the prefix 'fed' is replace by 'ns0' or > something like that. > Definitely something that has no connection to the original 'fed'. Yes, ElementTree does that. There are two ways to work around this: recent ET versions support explicitly defining namespace-prefix mappings at a module global level (IIRC, starting with ET 1.3/Py2.7/Py3.2), so you can provide a fixed prefix if you know what's coming in. Failing that, you can switch to lxml.etree, which keeps namespace prefixes as seen in the parsed document. Stefan From aahz at pythoncraft.com Sat Aug 7 17:58:56 2010 From: aahz at pythoncraft.com (Aahz) Date: 7 Aug 2010 14:58:56 -0700 Subject: distutils question - building universal modules on OS X? References: Message-ID: In article , Louis Theran wrote: > >Is there a standard recipe for getting distutils to built universal .so >files for modules that have C/C++ source? You should check the archives of http://mail.python.org/mailman/listinfo/pythonmac-sig -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "....Normal is what cuts off your sixth finger and your tail..." --Siobhan From rantingrick at gmail.com Sat Aug 7 18:02:14 2010 From: rantingrick at gmail.com (rantingrick) Date: Sat, 7 Aug 2010 15:02:14 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> Message-ID: <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> On Aug 7, 9:10?am, Steven D'Aprano wrote: > On Sat, 07 Aug 2010 08:54:28 -0400, D'Arcy J.M. Cain wrote: > > On Sat, 07 Aug 2010 13:48:32 +0200 > > News123 wrote: > >> It makes sense in assembly language and even in many byte code > >> languages. It makes sense if you look at the internal representation of > >> unsigned numbers (which might become an index) > > >> For a complete beginner common sense dictates differently and there > >> might be confusion why the second element in a list has index 1. > > > Would said beginner also be surprised that a newborn baby is zero years > > old or would it be more natural to call them a one year old? ?Zero based > > counting is perfectly natural. > > There's nothing natural about saying that a baby is zero years old. A > newborn baby is "a newborn baby", then it's "one day old", "two days > old", ... "one month old", "two months old", ... "one year old". Well not if you are referring to how people "say" things. But what people "say" and the facts of reality are some times two different things. Heck we even have a few folks in this group who overuse the expression "used to" quite frequently in place of the more correct term "previously" -- i won't give names. But if i did i would start at index zero! When any object is "born" (whether it be a life form, or a planet, or even a class instance) "it" will be zero years old until 1 year of time has passed has passed. If you want to properly describe age you could say a baby who was born five minutes ago is... - 0 millenniums - 0 centuries - 0 decades - 0 years - 0 months - 0 days - 0 hours - 5 minutes - 60*5 seconds - (60*5)*1000 millisecond - crikey i'm tired! Just because Aunt Martha is is too lazy to list out the details that has no effect on reality. YES a newborn is zero years old. YES, a newborn is zero months old, ...an so on. From no.email at nospam.invalid Sat Aug 7 18:37:04 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 07 Aug 2010 15:37:04 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <7xwrs2t5gv.fsf@ruckus.brouhaha.com> Albert van der Horst writes: > We had a similar discussion on comp.lang.forth. Heh, fancy meeting you here ;-) > The bottom line is that to implement a programming language > you want to use a simpler programming language, not a more > complicated one. Nah, gas is written in C, and nobody implements VHDL as logic gates. > (We went on whether Forth would be a suitable high level assembler > for Haskell. It would beat C++ -- not C -- for implementing Python, > that much I'm sure.) Haskell (or at least certain parts of it) should probably be implemented in Coq or Agda, which are even higher level than Haskell. > Undoubtedly C is the right choice to implement Python. Python has been experimentally implemented in Haskell: http://hackage.haskell.org/package/berp-0.0.2 but the most interesting implementation (not yet ready for production, but a serious ongoing project partly funded by the EU) is written in Python itself: http://codespeak.net/pypy/ From python at mrabarnett.plus.com Sat Aug 7 18:44:05 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 07 Aug 2010 23:44:05 +0100 Subject: Python "why" questions In-Reply-To: <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: <4C5DE1B5.7070802@mrabarnett.plus.com> rantingrick wrote: > On Aug 7, 9:10 am, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 07 Aug 2010 08:54:28 -0400, D'Arcy J.M. Cain wrote: >>> On Sat, 07 Aug 2010 13:48:32 +0200 >>> News123 wrote: >>>> It makes sense in assembly language and even in many byte code >>>> languages. It makes sense if you look at the internal representation of >>>> unsigned numbers (which might become an index) >>>> For a complete beginner common sense dictates differently and there >>>> might be confusion why the second element in a list has index 1. >>> Would said beginner also be surprised that a newborn baby is zero years >>> old or would it be more natural to call them a one year old? Zero based >>> counting is perfectly natural. >> There's nothing natural about saying that a baby is zero years old. A >> newborn baby is "a newborn baby", then it's "one day old", "two days >> old", ... "one month old", "two months old", ... "one year old". > > Well not if you are referring to how people "say" things. But what > people "say" and the facts of reality are some times two different > things. Heck we even have a few folks in this group who overuse the > expression "used to" quite frequently in place of the more correct > term "previously" -- i won't give names. But if i did i would start at > index zero! > There's nothing wrong with "used to", but "more correct"? It either _is_ correct or _isn't_ correct. And it's "I", not "i". :-) > When any object is "born" (whether it be a life form, or a planet, or > even a class instance) "it" will be zero years old until 1 year of > time has passed has passed. If you want to properly describe age you > could say a baby who was born five minutes ago is... > > - 0 millenniums millennia > - 0 centuries > - 0 decades > - 0 years > - 0 months > - 0 days > - 0 hours > - 5 minutes > - 60*5 seconds > - (60*5)*1000 millisecond > - crikey i'm tired! > > Just because Aunt Martha is is too lazy to list out the details that > has no effect on reality. YES a newborn is zero years old. YES, a > newborn is zero months old, ...an so on. From hexamorph at gmx.net Sat Aug 7 19:06:34 2010 From: hexamorph at gmx.net (Hexamorph) Date: Sun, 08 Aug 2010 01:06:34 +0200 Subject: Python "why" questions In-Reply-To: <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: <4C5DE6FA.1090701@gmx.net> rantingrick wrote: > Well not if you are referring to how people "say" things. But what > people "say" and the facts of reality are some times two different > things. Heck we even have a few folks in this group who overuse the > expression "used to" quite frequently in place of the more correct > term "previously" -- i won't give names. Rick, do you know *ANY* other language other than English? Not everybody understands English on an Oxford level (and I doubt you do). You're just a loud-mouthing (probably incorrect English) idiot. (Spare your comments about personal attacks, you're not so stupid to not know why you regularly receive such comments) Lurking for long enough to know your style. Looking at your Unicode rant, combined with some other comments and your general "I am right and you are wrong because you disagree with me." style, I came to the conclusion, that you are either a faschist or the perfect role model for an imperialistic, foreign culture destroying, self-praising, arrogant, ignorant moron. > When any object is "born" (whether it be a life form, or a planet, or > even a class instance) "it" will be zero years old until 1 year of > time has passed has passed. A year is not the smallest index. A year is 365 days is 8760 hours is 525600 is 31536000 minutes, and so on and so on and so on... That's *totally* different from array[0], array[1], etc. There is *NO* array[0.5]. Going down to the smalled possible time scale (quantum physics level ), what is the the correct index for "my baby is *just* born, hence it's X quantum leap old." where x might be 0 or 1. Yes, I know that this is nonsense (since such a discrete quantum leap doesn't even exists) but so is the whole discussion. Something starts at 0, others at 1. You only have to add/sub 1 depending on the situation. Mind-boggling, I must say! And really, even brand-new programmer will face *A LOT* harder problems than this. Programming is not stamp collecting! Programming requires a half working brain, and those who don't have that, should sort their stamps while watching some "Next top model" stuff on TV. "Make everything as simple as possible, but not simpler." - Einstein From ben+python at benfinney.id.au Sat Aug 7 19:16:26 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Aug 2010 09:16:26 +1000 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> Message-ID: <878w4i10ad.fsf@benfinney.id.au> Peter Pearson writes: > Hey, that's a cute example, but . . . what a trap! Is it possible to > document the use-the-object-not-the-string requirement loudly enough > that people won't get caught? Don't use strings for such values. The data isn't going to be used, so there's no sense using a semantically rich data type like a string. Instead, use an ?object? instance; then, the only way to get a binding that will compare equal is to use the very object itself. FORWARD = object() BACKWARD = object() -- \ ?Never do anything against conscience even if the state demands | `\ it.? ?Albert Einstein | _o__) | Ben Finney From debatem1 at gmail.com Sat Aug 7 19:24:32 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 7 Aug 2010 16:24:32 -0700 Subject: Python "why" questions In-Reply-To: <4C5DE6FA.1090701@gmx.net> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> <4C5DE6FA.1090701@gmx.net> Message-ID: On Sat, Aug 7, 2010 at 4:06 PM, Hexamorph wrote: > rantingrick wrote: > >> Well not if you are referring to how people "say" things. But what >> people "say" and the facts of reality are some times two different >> things. Heck we even have a few folks in this group who overuse the >> expression "used to" quite frequently in place of the more correct >> term "previously" -- i won't give names. > > > > Rick, do you know *ANY* other language other than English? Not everybody > understands English on an Oxford level (and I doubt you do). You're just a > loud-mouthing (probably incorrect English) idiot. (Spare your comments about > personal attacks, you're not so stupid to not know why you regularly receive > such comments) > > Lurking for long enough to know your style. Looking at your Unicode rant, > combined with some other comments and your general "I am right and you are > wrong because you disagree with me." style, I came to the conclusion, that > you are either a faschist or the perfect role model for an imperialistic, > foreign culture destroying, self-praising, arrogant, ignorant moron. Rick? Is that you? Geremy Condra From wolftracks at invalid.com Sat Aug 7 19:24:52 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 16:24:52 -0700 Subject: Python Portability In-Reply-To: References: Message-ID: On 8/7/2010 2:01 PM, Michael Torrie wrote: > On 08/07/2010 01:17 PM, W. eWatson wrote: >> Presumably I have him somehow delete the numpy site-package, the numpy >> 1.2.0 package? Just drill his way dow from the .../lib/site_packages? >> Then install 1.2.0. He's missed the boat on that before by not following >> instructions. > > Wait. I'm confused. Aren't you distributing your python app as an > executable, with the interpreter and all the libraries bundled? Not at all. There is no exe. The py source program is all that goes out. It is expected that the recipients have the same versions of modules, numpy, etc, and IDLE. All under Windows. There's not a single person (of about 50) that gets person who is likely to have changed the Python environment. None of them know Python. When the sponsor decides to change the app we all use, then we update Python and modules as required. User's execute the programs with IDLE, or a double click of the py file. From ben+python at benfinney.id.au Sat Aug 7 19:34:22 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Aug 2010 09:34:22 +1000 Subject: Python "why" questions References: <4c5d61cc$0$28666$c3e8da3@news.astraweb.com> Message-ID: <874of60zgh.fsf@benfinney.id.au> Steven D'Aprano writes: > It didn't take me long to get used to thinking in zero-based indexes, > but years later, I still find it hard to *talk* in zero-based indexes. > It's bad enough saying that the first element in a list in the zeroth > element, but that the second element is the first makes my head > explode... Don't say those things, then. In addition to making your head explode, they're not true. There is no ?zeroth element? in a sequence. The first element in a sequence is addressed by index 0. The second element in a sequence is addressed by index 1. The last element in a sequence is addressed by index -1. In other words, it's never true (in Python) that index N addresses the Nth element of the sequence; so that's not a useful equivalence to maintain. Hope that helps. -- \ ?The trouble with eating Italian food is that five or six days | `\ later you're hungry again.? ?George Miller | _o__) | Ben Finney From wolftracks at invalid.com Sat Aug 7 19:36:48 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 16:36:48 -0700 Subject: Python Portability In-Reply-To: <4C5DCF87.4000800@v.loewis.de> References: <4C5DCF87.4000800@v.loewis.de> Message-ID: On 8/7/2010 2:26 PM, Martin v. Loewis wrote: > Am 07.08.2010 23:01, schrieb Michael Torrie: >> On 08/07/2010 01:17 PM, W. eWatson wrote: >>> Presumably I have him somehow delete the numpy site-package, the numpy >>> 1.2.0 package? Just drill his way dow from the .../lib/site_packages? >>> Then install 1.2.0. He's missed the boat on that before by not following >>> instructions. >> >> Wait. I'm confused. Aren't you distributing your python app as an >> executable, with the interpreter and all the libraries bundled? > > No, he was really mentioning two distinct scenarios. In the one > discussed above, the remote machine had all stuff manually installed, > and somehow got the actual Python program copied into it. > > Regards, > Martin To add to the msg I just sent to M. Torrie. We are given the msi programs for Python, PIL,matplotlib, and numpy. The question of how to uninstall and re-install a different version remains. The answer is? From ben+python at benfinney.id.au Sat Aug 7 19:39:18 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Aug 2010 09:39:18 +1000 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> Message-ID: <87zkwyyoux.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > No. You are giving me math and logic but the subject was common > sense. Common sense is often unhelpful, and in such cases the best way to teach something is to plainly contradict that common sense. Common sense, for example, would have the Earth as a flat surface with the Sun and Moon as roughly-identically-sized objects orbiting the Earth. Is it better to pander to that common sense, or to vigorously reject it in order to teach something more useful? -- \ ?Courage is not the absence of fear, but the decision that | `\ something else is more important than fear.? ?Ambrose Redmoon | _o__) | Ben Finney From usernet at ilthio.net Sat Aug 7 19:42:31 2010 From: usernet at ilthio.net (Tim Harig) Date: Sat, 7 Aug 2010 23:42:31 +0000 (UTC) Subject: cscope like source code navigation for python code References: Message-ID: On 2010-08-07, Gelonida wrote: > I'm using g?vim and its c-scope plugin for browsing C-code. > What would be a good way of navigating larger python projects with vim? ctags: http://ctags.sourceforge.net/ From ben+python at benfinney.id.au Sat Aug 7 19:43:39 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Aug 2010 09:43:39 +1000 Subject: Python Portability--Not very portable? References: Message-ID: <87vd7myono.fsf@benfinney.id.au> "W. eWatson" writes: > Yes, code reversal programs have been around for many, many decades. > Try one on MS Word or Adobe Acrobat. :-) Interesting examples. What ?important stuff? from those programs has not been ?ripped off?, to use your terms? Is there anything remaining in those programs which others would find sufficiently valuable that has *not* been ?ripped off?? -- \ ?If you make people think they're thinking, they'll love you; | `\ but if you really make them think, they'll hate you.? ?Donald | _o__) Robert Perry Marquis | Ben Finney From martin at v.loewis.de Sat Aug 7 19:45:46 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 08 Aug 2010 01:45:46 +0200 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> Message-ID: <4C5DF02A.6010200@v.loewis.de> > To add to the msg I just sent to M. Torrie. We are given the msi > programs for Python, PIL,matplotlib, and numpy. The question of how to > uninstall and re-install a different version remains. I'd claim that this is not the real question. The real question is, instead: "What specific error did you get when adding a single minus sign to the program?" Please try answering that question also. > The answer is? I'm not sure I understand the question. What do you mean by "given"? Perhaps "already downloaded locally"? If so, the obvious answer is "Go to Add-Remove-Programs. Uninstall. Then double-click the MSI files." If that is not a good answer: why not? If you want that automated: write a batch file, invoking "msiexec" as necessary. Regards, Martin From alex at moreati.org.uk Sat Aug 7 19:54:03 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Sat, 7 Aug 2010 16:54:03 -0700 (PDT) Subject: Sequential Object Store References: <6e21725a-e5c4-45be-81c4-5a9fd79df413@d8g2000yqf.googlegroups.com> Message-ID: On Aug 7, 5:26?pm, GZ wrote: > I am wondering if there is a module that can persist a stream of > objects without having to load everything into memory. (For this > reason, I think Pickle is out, too, because it needs everything to be > in memory.) >From the pickle docs it looks like you could do something like: try: import cPickle as pickle except ImportError import pickle file_obj = open('whatever', 'wb') p = pickle.Pickler(file_obj) for x in stream_of_objects: p.dump(x) p.memo.clear() del p file_obj.close() then later file_obj = open('whatever', 'rb') p = pickle.Unpickler(file_obj) while True: try: x = p.load() do_something_with(x) except EOFError: break Your loading loop could be wrapped in a generator function, so only one object should be held in memory at once. From nikos.the.gr33k at gmail.com Sat Aug 7 20:20:24 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 17:20:24 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex Message-ID: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Hello dear Pythoneers, I have over 500 .php web pages in various subfolders under 'data' folder that i have to rename to .html and and ditch the '' tages from within and also insert a very first line of where id must be an identification unique number of every page for counter tracking purposes. ONly pure html code must be left. I before find otu Python used php and now iam switching to templates + python solution so i ahve to change each and every page. I don't know how to handle such a big data replacing problem and cannot play with fire because those 500 pages are my cleints pages and data of those filesjust cannot be messes up. Can you provide to me a script please that is able of performing an automatic way of such a page content replacing? Thanks a million! From rantingrick at gmail.com Sat Aug 7 20:40:33 2010 From: rantingrick at gmail.com (rantingrick) Date: Sat, 7 Aug 2010 17:40:33 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> On Aug 7, 7:20?pm, ????? wrote: > Hello dear Pythoneers, I prefer Pythonista, but anywho.. > I have over 500 .php web pages in various subfolders under 'data' > folder that i have to rename to .html import os os.rename(old, new) > and and ditch the '' tages from within path = 'some/valid/path' f = open(path, 'r') data = f.read() f.close() data.replace('', '') > and also insert a very first line of > where id must be an identification unique number of every page for > counter tracking purposes. comment = ""%(idnum) data.insert(idx, comment) > ONly pure html code must be left. Well then don't F up! However judging from the amount of typos in this post i would suggest you do some major testing! > I don't know how to handle such a big data replacing problem and > cannot play with fire because those 500 pages are my cleints pages and > data of those files just cannot be messes up. Better do some serous testing first, or (if you have enough disc space ) create copies instead! > Can you provide to me a script please that is able of performing an > automatic way of such a page content replacing? This is very basic stuff and the fine manual is free you know. But how much are you willing to pay? From wolftracks at invalid.com Sat Aug 7 21:10:34 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 07 Aug 2010 18:10:34 -0700 Subject: Python Portability In-Reply-To: <4C5DF02A.6010200@v.loewis.de> References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On 8/7/2010 4:45 PM, Martin v. Loewis wrote: >> To add to the msg I just sent to M. Torrie. We are given the msi >> programs for Python, PIL,matplotlib, and numpy. The question of how to >> uninstall and re-install a different version remains. > > I'd claim that this is not the real question. The real question is, > instead: "What specific error did you get when adding a single minus > sign to the program?" > > Please try answering that question also. > >> The answer is? > > I'm not sure I understand the question. What do you mean by "given"? > Perhaps "already downloaded locally"? > > If so, the obvious answer is "Go to Add-Remove-Programs. Uninstall. > Then double-click the MSI files." If that is not a good answer: > why not? > > If you want that automated: write a batch file, invoking "msiexec" > as necessary. > > Regards, > Martin > > Given. We either download them from various specified sites or newbies get a CD when they receive hardware that is used by the sponsor's programs. Add-Remove would be a very good answer, except for one thing. Understand that I'm in Win7 so CP takes on a different form. On Control Panel Add-Remove, I can find exactly two Python files: Python 2.5, and python-Numpy-1.2.0. No scipy anything. Well, this is interesting. I just noticed Martin v. Loewis on the Python 2.5 entry. That's you, right? msiexec. Don't need it automated now, but it might be worthwhile, at some future point. I think I posted the errors my partner got above. Let me look. Yes, here's the copy. He gets Traceback (most recent call last): File "C:\Documents and Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", line 40, in from scipy import stats as stats # scoreatpercentile File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, in from stats import * File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, in import scipy.special as special File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 22, in from numpy.testing import NumpyTest ImportError: cannot import name NumpyTest Here are the first few lines of code. import sys, os, glob import string from numpy import * from datetime import datetime, timedelta import time from scipy import stats as stats # scoreatpercentile From cmpython at gmail.com Sat Aug 7 21:26:51 2010 From: cmpython at gmail.com (CM) Date: Sat, 7 Aug 2010 18:26:51 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> Message-ID: <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> > Apparently, the Japanese used to (before they started adopting western > conventions). I.e. ages were given as "in his tenth year" (meaning nine > years old). Koreans still do this. The day a child is born it is "one". Even odder to me, the next birthday is not on the next anniversary of the birth, but on the following New Year's Day. So a kid who is born on Dec 26th, will be "two" as of New Year's Day the week following his/ her birth. (They also are aware of the "western" version of their ages if needed). . From python at mrabarnett.plus.com Sat Aug 7 21:42:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Aug 2010 02:42:07 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> Message-ID: <4C5E0B6F.9000403@mrabarnett.plus.com> rantingrick wrote: > On Aug 7, 7:20 pm, ????? wrote: >> Hello dear Pythoneers, > > I prefer Pythonista, but anywho.. > >> I have over 500 .php web pages in various subfolders under 'data' >> folder that i have to rename to .html > > import os > os.rename(old, new) > >> and and ditch the '' tages from within > > path = 'some/valid/path' > f = open(path, 'r') > data = f.read() > f.close() > data.replace(' data.replace('?>', '') > That should be: data = data.replace('', '') >> and also insert a very first line of >> where id must be an identification unique number of every page for >> counter tracking purposes. > > comment = ""%(idnum) > data.insert(idx, comment) > Strings don't have an 'insert' method! >> ONly pure html code must be left. > > Well then don't F up! However judging from the amount of typos in this > post i would suggest you do some major testing! > >> I don't know how to handle such a big data replacing problem and >> cannot play with fire because those 500 pages are my cleints pages and >> data of those files just cannot be messes up. > > Better do some serous testing first, or (if you have enough disc > space ) create copies instead! > >> Can you provide to me a script please that is able of performing an >> automatic way of such a page content replacing? > > This is very basic stuff and the fine manual is free you know. But how > much are you willing to pay? From ian.g.kelly at gmail.com Sat Aug 7 22:08:05 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 7 Aug 2010 20:08:05 -0600 Subject: Python "why" questions In-Reply-To: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: On Sat, Aug 7, 2010 at 1:14 PM, John Nagle wrote: > ? FORTRAN, MATLAB, and Octave all use 1-based subscripts. > > ? The languages which have real multidimensional arrays, rather > than arrays of arrays, tend to use 1-based subscripts. ?That > reflects standard practice in mathematics. I propose that this has less to do with the fact that those languages have "real" multidimensional arrays, and more to do with the fact that those languages are designed for doing mathematics. C, Oberon, and others also have "real" multidimensional arrays, and use 0-based subscripts. Standard practice in mathematics is not necessarily best practice in programming. Cheers, Ian From nikos.the.gr33k at gmail.com Sat Aug 7 22:26:31 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 19:26:31 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> Message-ID: # rename ALL php files to html in every subfolder of the folder 'data' os.rename('*.php', '*.html') # how to tell python to rename ALL php files to html to ALL subfolder under 'data' ? # current path of the file to be processed path = './data' # this must be somehow in a loop i feel that read every file of every subfolder # open an html file for reading f = open(path, 'rw') # read the contents of the whole file data = f.read() # replace all php tags with empty string data = data.replace('', '') # write replaced data to file data = f.write() # insert an increasing unique integer number at the very first line of every html file processing comment = ""%(idnum) # how will the number change here an increased by one file after file? f = f.close() Please help i'm new to python an apart from syntx its a logic problem as well and needs experience. From roy at panix.com Sat Aug 7 22:35:59 2010 From: roy at panix.com (Roy Smith) Date: Sat, 07 Aug 2010 22:35:59 -0400 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> Message-ID: In article <7f3c505c-4002-427e-a969-6d735307e0f6 at z10g2000yqb.googlegroups.com>, CM wrote: > > Apparently, the Japanese used to (before they started adopting western > > conventions). I.e. ages were given as "in his tenth year" (meaning nine > > years old). With apologies to Paul Simon... One man's ceil() is another man's floor() From steveo at syslang.net Sat Aug 7 22:42:25 2010 From: steveo at syslang.net (Steven W. Orr) Date: Sat, 07 Aug 2010 22:42:25 -0400 Subject: I need a starter ptr writing python embedded in html. Message-ID: <4C5E1991.9020401@syslang.net> I'm ok in python but I haven't done too much with web pages. I have a web page that is hand written in html that has about 1000 entries in a table and I want to convert the table from entries like this to SomePythonCall('Some Date String', 'SomeTag', 'localSubdir', "http://www.example.com/remote/path/something.html", 'Click', 'Some Comment') Can someone tell me what I should look at to do this? Is mod_python where I should start or are there things that are better? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From jstrickler at gmail.com Sat Aug 7 22:42:31 2010 From: jstrickler at gmail.com (John S) Date: Sat, 7 Aug 2010 19:42:31 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <989608bf-56fd-4f96-988e-9f3e6daa8680@d8g2000yqf.googlegroups.com> On Aug 7, 8:20?pm, ????? wrote: > Hello dear Pythoneers, > > I have over 500 .php web pages in various subfolders under 'data' > folder that i have to rename to .html and and ditch the '' > tages from within and also insert a very first line of > where id must be an identification unique number of every page for > counter tracking purposes. ONly pure html code must be left. > > I before find otu Python used php and now iam switching to templates + > python solution so i ahve to change each and every page. > > I don't know how to handle such a big data replacing problem and > cannot play with fire because those 500 pages are my cleints pages and > data of those filesjust cannot be messes up. > > Can you provide to me a script please that is able of performing an > automatic way of such a page content replacing? > > Thanks a million! If the 500 web pages are PHP only in the sense that there is only one pair of tags in each file, surrounding the entire content, then what you ask for is doable. from os.path import join import os id = 1 # id number for currdir,files,dirs in os.walk('data'): for f in files: if f.endswith('php'): source_file_name = join(currdir,f) # get abs path to filename source_file = open(source_file_name) source_contents = source_file.read() # read contents of PHP file source_file.close() # replace tags source_contents = source_contents.replace('<%','') source_contents = source_contents.replace('%>','') # add ID source_contents = ( '' % id ) + source_contents id += 1 # create new file with .html extension source_file_name = source_file_name.replace('.php','.html') dest_file = open(source_file_name,'w') dest_file.write(source_contents) # write contents dest_file.close() Note: error checking left out for clarity. On the other hand, if your 500 web pages contain embedded PHP variables or logic, you have a big job ahead. Django templates and PHP are two different languages for embedding data and logic in web pages. Converting a project from PHP to Django involves more than renaming the template files and deleting "'; } ?> In Django, you would typically put this logic in a Django *view* (which btw is not what is called a 'view' in MVC term), which is the code that prepares data for the template. The logic would not live with the HTML. The template uses "template variables" that the view has associated with a Python variable or function. You might create a template variable (created via a Context object) named 'browser' that contains a value that identifies the browser. Thus, your Python template (HTML file) might look like this: {% if browser == 'IE' %}You are using Internet Explorer{% endif %} PHP tends to combine the presentation with the business logic, or in MVC terms, combines the view with the controller. Django separates them out, which many people find to be a better way. The person who writes the HTML doesn't have to speak Python, but only know the names of template variables and a little bit of template logic. In PHP, the HTML code and all the business logic lives in the same files. Even here, it would probably make sense to calculate the browser ID in the header of the HTML file, then access it via a variable in the body. If you have 500 static web pages that are part of the same application, but that do not contain any logic, your application might need to be redesigned. Also, you are doing your changes on a COPY of the application on a non- public server, aren't you? If not, then you really are playing with fire. HTH, John From rantingrick at gmail.com Sat Aug 7 22:46:18 2010 From: rantingrick at gmail.com (rantingrick) Date: Sat, 7 Aug 2010 19:46:18 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> Message-ID: <1ea6fd9a-d83b-4b45-b5e9-9b5673b9e5f4@e15g2000yqo.googlegroups.com> On Aug 7, 8:42?pm, MRAB wrote: > That should be: > > ? ?data = data.replace(' ? ?data = data.replace('?>', '') Yes, Thanks MRAB. I did forget that important detail. > Strings don't have an 'insert' method! *facepalm*! I really must stop Usenet-ing whilst consuming large volumes of alcoholic beverages. From jstrickler at gmail.com Sat Aug 7 22:56:05 2010 From: jstrickler at gmail.com (John S) Date: Sat, 7 Aug 2010 19:56:05 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <989608bf-56fd-4f96-988e-9f3e6daa8680@d8g2000yqf.googlegroups.com> Message-ID: <355b90cc-bbf5-41bc-9021-e796bf2a1f2c@5g2000yqz.googlegroups.com> Even though I just replied above, in reading over the OP's message, I think the OP might be asking: "How can I use RE string replacement to find PHP tags and convert them to Django template tags?" Instead of saying source_contents = source_contents.replace(...) say this instead: import re def replace_php_tags(m): ''' PHP tag replacer This function is called for each PHP tag. It gets a Match object as its parameter, so you can get the contents of the old tag, and should return the new (Django) tag. ''' # m is the match object from the current match php_guts = m.group(1) # the contents of the PHP tag # now put the replacement logic here # and return whatever should go in place of the PHP tag, # which could be '{{ python_template_var }}' # or '{% template logic ... %} # or some combination source_contents = re.sub('',replace_php_tags,source_contents) From nikos.the.gr33k at gmail.com Sat Aug 7 23:11:01 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 20:11:01 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <989608bf-56fd-4f96-988e-9f3e6daa8680@d8g2000yqf.googlegroups.com> Message-ID: <2a14900c-f2e5-49e0-b260-5129e4c851f6@14g2000yqa.googlegroups.com> On 8 ???, 05:42, John S wrote: > If the 500 web pages are PHP only in the sense that there is only one > pair of tags in each file, surrounding the entire content, then > what you ask for is doable. First of all, thank you very much John for your BIG effort to help me(i'm still readign your posts)! I have to tell you here that those php files contain several instances of php opening and closing tags(like 3 each php file). The rest is pure html data. That happened because those files were in the beginning html only files that later needed conversion to php due to some dynamic code that had to be used to address some issues. Please tell me that the code you provided can be adjusted to several instances as well! From nikos.the.gr33k at gmail.com Sat Aug 7 23:35:03 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 7 Aug 2010 20:35:03 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <989608bf-56fd-4f96-988e-9f3e6daa8680@d8g2000yqf.googlegroups.com> <355b90cc-bbf5-41bc-9021-e796bf2a1f2c@5g2000yqz.googlegroups.com> Message-ID: <921898ca-f8d1-472b-b47e-626a1b6afb59@l14g2000yql.googlegroups.com> On 8 ???, 05:56, John S wrote: >"How can I use RE string replacement to find PHP tags and convert them >to Django template tags?" No, not at all John, at least not yet! I have only 1 week that i'm learnign python(changing from php & perl) so i'm very fresh at this beautifull and straighforwrd language. When i have a good understnading of Python then i will proceed to Django templates. Until then my Python templates would be only 'simple html files' that the only thign they contain apart form the html data would be the special string formatting identifies '%s' :-) From miki.tebeka at gmail.com Sat Aug 7 23:57:50 2010 From: miki.tebeka at gmail.com (Miki) Date: Sat, 7 Aug 2010 20:57:50 -0700 (PDT) Subject: I need a starter ptr writing python embedded in html. References: Message-ID: <3cc2a461-19f0-4aaf-9305-dde36fa2656c@v6g2000prd.googlegroups.com> On Aug 7, 7:42?pm, "Steven W. Orr" wrote: > I'm ok in python but I haven't done too much with web pages. I have a web page > that is hand written in html that has about 1000 entries in a table and I want > to convert the table from entries like this > > ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? > > to > > ? ?SomePythonCall('Some Date String', > ? ? ? ? ? ? ? ? 'SomeTag', > ? ? ? ? ? ? ? ? 'localSubdir', > ? ? ? ? ? ? ? ? "http://www.example.com/remote/path/something.html", > ? ? ? ? ? ? ? ? 'Click', > ? ? ? ? ? ? ? ? 'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? Have a look at http://www.crummy.com/software/BeautifulSoup/. All the best, -- Miki http://mikitebeka.com The only difference between children and adults is the price of the toys From pavlovevidence at gmail.com Sun Aug 8 00:34:00 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 7 Aug 2010 21:34:00 -0700 (PDT) Subject: Nice way to cast a homogeneous tuple References: <4c50eb46$0$28664$c3e8da3@news.astraweb.com> <1pm7i7-473.ln1@satorlaser.homedns.org> <49f9d367-20fc-442f-b397-9d50ffb391f2@i4g2000prf.googlegroups.com> Message-ID: <6473a005-3753-4628-850d-be49cdf6bd2d@h17g2000pri.googlegroups.com> On Aug 7, 8:18?pm, Dennis Lee Bieber wrote: > On Sat, 7 Aug 2010 13:02:56 -0700 (PDT), Carl Banks > declaimed the following in > gmane.comp.python.general: > > > > > Not really. ?Very few people call int(), float(), and company "type > > casts". ?They aren't type casts at all, they are constructors that > > sometimes have the same semantics as type casts in C. > > ? ? ? ? Given the different syntax, I never see them as "type casts"... They > look like functions that take an argument (or more than one: > int("FE", 16) ) and convert it into a value of the type named... > > ? ? ? ? C, OTOH, I'm never sure if a conversion (the bit pattern of the > result is different from the bit pattern of the source) or an > equivalencing (the bit pattern of the result is the same as the bit > pattern of the source, but the /interpretation/ of those bits is > different) is taking place. C's type casts are always a conversion. There are no exceptions I'm aware of. The only way to reinterpret bits in C is to take a reference, cast the pointer, and then derefernece again. (C++ has a reinterpret_cast for that.) *(int*)&x Casting an integer to a pointer retains the same bits because a pointer's "value" is considered to be the same as the unsigned integer with the same bit pattern. Pointer-to-pointer casts in C++ don't always retain the same bits, BTW. Carl Banks From eknath.iyer at gmail.com Sun Aug 8 02:49:01 2010 From: eknath.iyer at gmail.com (Eknath Venkataramani) Date: Sun, 8 Aug 2010 12:19:01 +0530 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <4C5E1991.9020401@syslang.net> References: <4C5E1991.9020401@syslang.net> Message-ID: BeautifulSoup On Sun, Aug 8, 2010 at 8:12 AM, Steven W. Orr wrote: > I'm ok in python but I haven't done too much with web pages. I have a web > page > that is hand written in html that has about 1000 entries in a table and I > want > to convert the table from entries like this > > > > > > > > > > to > > SomePythonCall('Some Date String', > 'SomeTag', > 'localSubdir', > "http://www.example.com/remote/path/something.html", > 'Click', > 'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? > > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things have > .0. > happened but none stranger than this. Does your driver's license say Organ > ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are all- > 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Eknath Venkataramani -------------- next part -------------- An HTML attachment was scrubbed... URL: From sschwarzer at sschwarzer.net Sun Aug 8 03:46:40 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 08 Aug 2010 09:46:40 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <878w4i10ad.fsf@benfinney.id.au> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <878w4i10ad.fsf@benfinney.id.au> Message-ID: <4C5E60E0.3050603@sschwarzer.net> Hi Ben, On 2010-08-08 01:16, Ben Finney wrote: > Don't use strings for such values. The data isn't going to be used, so > there's no sense using a semantically rich data type like a string. > > Instead, use an ?object? instance; then, the only way to get a binding > that will compare equal is to use the very object itself. > > FORWARD = object() > BACKWARD = object() Yes, that's the obvious approach. :-) I had used strings in the example with the reasoning that they could be readily used in messages (from my post: "Using a string instead of an `object()` has the advantage that it makes usage in error messages easier."). For the record, another approach I've seen is something like FORWARD, BACKWARD, UNKNOWN = range(3) This has the same problem as when using strings for the constants but looking at the module contents it's a bit more obvious that these are just "magic numbers", so presumably the constant names should be used instead. Stefan From blur959 at hotmail.com Sun Aug 8 04:02:36 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 01:02:36 -0700 (PDT) Subject: Renaming of files in OS directory Message-ID: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Hi, all, I am writing a program that renames files inside OS directories the user provides. I am at the early stage of writing it and I encountered some problems. Below is my code. There is an error i received when i run this code. The error is, WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect. Hope you guys could help. import os, glob def fileDirectory(): #Asks the user for a file root directory fileroot = raw_input("Please input the file root directory \n\n") print fileroot #Returns a list with all the files inside the file root directory os.listdir(fileroot) fileDirectory() From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 04:09:35 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Aug 2010 08:09:35 GMT Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <4c5e663f$0$28655$c3e8da3@news.astraweb.com> On Sat, 07 Aug 2010 17:20:24 -0700, ????? wrote: > I don't know how to handle such a big data replacing problem and cannot > play with fire because those 500 pages are my cleints pages and data of > those filesjust cannot be messes up. Take a backup copy of the files, and only edit the copies. Don't replace the originals until you know they're correct. -- Steven From landa.martin at gmail.com Sun Aug 8 04:14:38 2010 From: landa.martin at gmail.com (Martin Landa) Date: Sun, 8 Aug 2010 01:14:38 -0700 (PDT) Subject: ctypes: pointer to method References: <2cede774-e376-49dd-8dd0-e356007fd6a6@h28g2000yqd.googlegroups.com> Message-ID: <72b2e878-b61c-4f0e-92ca-14e5d54adf0f@v41g2000yqv.googlegroups.com> On Aug 7, 12:46?pm, Martin Landa wrote: > the problem occurs when restype is not None, but c_int. E.g. solved. Martin From clp2 at rebertia.com Sun Aug 8 04:15:51 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 8 Aug 2010 01:15:51 -0700 Subject: Renaming of files in OS directory In-Reply-To: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: > Hi, all, I am writing a program that renames files inside OS > directories the user provides. I am at the early stage of writing it > and I encountered some problems. > > Below is my code. There is an error i received when i run this code. > The error is, WindowsError: [Error 123] The filename, directory name, > or volume label syntax is incorrect. Well, what directory did you input? Apparently it wasn't a valid or extant one. Cheers, Chris -- http://blog.rebertia.com From nikos.the.gr33k at gmail.com Sun Aug 8 04:30:51 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 01:30:51 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> Message-ID: On 8 ???, 11:09, Steven D'Aprano wrote: > On Sat, 07 Aug 2010 17:20:24 -0700, ????? wrote: > > I don't know how to handle such a big data replacing problem and cannot > > play with fire because those 500 pages are my cleints pages and data of > > those filesjust cannot be messes up. > > Take a backup copy of the files, and only edit the copies. Don't replace > the originals until you know they're correct. > > -- > Steven Yes of course, but the code that John S provided need soem modification in order to be able to change various instances of php tags and not only one set. From blur959 at hotmail.com Sun Aug 8 04:35:54 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 01:35:54 -0700 (PDT) Subject: Renaming of files in OS directory References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: On Aug 8, 4:15?pm, Chris Rebert wrote: > On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: > > Hi, all, I am writing a program that renames files inside OS > > directories the user provides. I am at the early stage of writing it > > and I encountered some problems. > > > Below is my code. There is an error i received when i run this code. > > The error is, WindowsError: [Error 123] The filename, directory name, > > or volume label syntax is incorrect. > > Well, what directory did you input? Apparently it wasn't a valid or extant one. > > Cheers, > Chris > --http://blog.rebertia.com I input for e.g, "C:" it works, basically, if i input a hard code string inside os.listdir it works, but if i stored the string that the user keyed inside a variable and run os.listdir with the variable, there is that error. But inputing hard code string inside os.listdir isn't what I want when I am writing this program. From clp2 at rebertia.com Sun Aug 8 04:58:10 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 8 Aug 2010 01:58:10 -0700 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <4C5E1991.9020401@syslang.net> References: <4C5E1991.9020401@syslang.net> Message-ID: On Sat, Aug 7, 2010 at 7:42 PM, Steven W. Orr wrote: > I'm ok in python but I haven't done too much with web pages. I have a web page > that is hand written in html that has about 1000 entries in a table and I want > to convert the table from entries like this > > ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? ? > ? ? > > to > > ? SomePythonCall('Some Date String', > ? ? ? ? ? ? ? ?'SomeTag', > ? ? ? ? ? ? ? ?'localSubdir', > ? ? ? ? ? ? ? ?"http://www.example.com/remote/path/something.html", > ? ? ? ? ? ? ? ?'Click', > ? ? ? ? ? ? ? ?'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? Certainly not mod_python; that project is dead. mod_wsgi is the suggested replacement. But both are relatively low-level solutions. Python has myriad web frameworks available for it; have a look at them. Cheers, Chris -- http://blog.rebertia.com From mark.dufour at gmail.com Sun Aug 8 05:01:32 2010 From: mark.dufour at gmail.com (Mark Dufour) Date: Sun, 8 Aug 2010 11:01:32 +0200 Subject: ANN: Shed Skin 0.5 Message-ID: Hi all, I have just released Shed Skin 0.5, an experimental (restricted) Python-to-C++ compiler. Please see my blog for more details about the release: http://shed-skin.blogspot.com/ Thanks, Mark Dufour. -- http://www.youtube.com/watch?v=E6LsfnBmdnk -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Sun Aug 8 05:21:56 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 02:21:56 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> Message-ID: <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> Script so far: #!/usr/bin/python import cgitb; cgitb.enable() import cgi, re, os print ( "Content-type: text/html; charset=UTF-8 \n" ) id = 0 # unique page_id for currdir, files, dirs in os.walk('data'): for f in files: if f.endswith('php'): # get abs path to filename src_f = join(currdir,f) # open php src file f = open(src_f, 'r') src_data = f.read() # read contents of PHP file f.close() print 'reading from %s' % src_f # replace tags src_data = src_data.replace('<%', '') src_data = src_data.replace('%>', '') print 'replacing php tags' # add ID src_data = ( '' % id ) + src_data id += 1 print 'adding unique page_id' # create new file with .html extension src_file = src_file.replace('.php', '.html') # open newly created html file for insertid data dest_f = open(src_f, 'w') dest_f.write(src_data) # write contents dest_f.close() print 'writing to %s' % dest_f Please help me adjust it, if need extra modification for more php tags replacing. From thomas at jollans.com Sun Aug 8 06:00:51 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 12:00:51 +0200 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: <4C5E8053.90901@jollans.com> On 08/08/2010 03:10 AM, W. eWatson wrote: > I think I posted the errors my partner got above. Let me look. Yes, > here's the copy. > He gets > > Traceback (most recent call last): > File "C:\Documents and > Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", > line 40, in > from scipy import stats as stats # scoreatpercentile > File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, > in > from stats import * > File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, > in > import scipy.special as special > File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line > 22, in > from numpy.testing import NumpyTest > ImportError: cannot import name NumpyTest > Is this error actually caused by the "one char change"? If you undo your "one char change", does the error disappear? > Here are the first few lines of code. > > import sys, os, glob > import string > from numpy import * > from datetime import datetime, timedelta > import time > from scipy import stats as stats # scoreatpercentile From thomas at jollans.com Sun Aug 8 06:05:10 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 12:05:10 +0200 Subject: Renaming of files in OS directory In-Reply-To: References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: <4C5E8156.4000001@jollans.com> On 08/08/2010 10:35 AM, blur959 wrote: > On Aug 8, 4:15 pm, Chris Rebert wrote: >> On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: >>> Hi, all, I am writing a program that renames files inside OS >>> directories the user provides. I am at the early stage of writing it >>> and I encountered some problems. >> >>> Below is my code. There is an error i received when i run this code. >>> The error is, WindowsError: [Error 123] The filename, directory name, >>> or volume label syntax is incorrect. >> >> Well, what directory did you input? Apparently it wasn't a valid or extant one. >> >> Cheers, >> Chris >> --http://blog.rebertia.com > > > I input for e.g, "C:" it works, basically, if i input a hard code > string inside os.listdir it works, but if i stored the string that the > user keyed inside a variable and run os.listdir with the variable, > there is that error. But inputing hard code string inside os.listdir > isn't what I want when I am writing this program. You didn't answert the question. What is the actual string you pass to os.listdir after you got it from the user? You could print repr(fileroot) to find out. My tentative guess is that maybe Windows doesn't like newlines in file names (I know UNIX allows them, but they're still usually a bad idea) and maybe you string ends with a newline. From thomas at jollans.com Sun Aug 8 06:09:00 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 12:09:00 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <1ea6fd9a-d83b-4b45-b5e9-9b5673b9e5f4@e15g2000yqo.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <35514db8-0e04-4a58-8830-b1c99e263238@e15g2000yqo.googlegroups.com> <1ea6fd9a-d83b-4b45-b5e9-9b5673b9e5f4@e15g2000yqo.googlegroups.com> Message-ID: <4C5E823C.40105@jollans.com> On 08/08/2010 04:46 AM, rantingrick wrote: > *facepalm*! I really must stop Usenet-ing whilst consuming large > volumes of alcoholic beverages. THAT explains a lot. Cheers From thomas at jollans.com Sun Aug 8 06:13:10 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 12:13:10 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> Message-ID: <4C5E8336.6070000@jollans.com> On 08/08/2010 11:21 AM, ????? wrote: > Please help me adjust it, if need extra modification for more php tags > replacing. Have you tried it ? I haven't, but I see no immediate reason why it wouldn't work with multiple PHP blocks. > #!/usr/bin/python > > import cgitb; cgitb.enable() > import cgi, re, os > > print ( "Content-type: text/html; charset=UTF-8 \n" ) > > > id = 0 # unique page_id > > for currdir, files, dirs in os.walk('data'): > > for f in files: > > if f.endswith('php'): > > # get abs path to filename > src_f = join(currdir,f) > > # open php src file > f = open(src_f, 'r') > src_data = f.read() # read contents of PHP file > f.close() > print 'reading from %s' % src_f > > # replace tags > src_data = src_data.replace('<%', '') > src_data = src_data.replace('%>', '') Did you read the script before posting? ;-) Here, you remove ASP-style tags. Which is fine, PHP supports them if you configure it that way, but you probably didn't. Change this to the start and end tags you actually use, and, if you use multiple forms (such as print 'replacing php tags' > > # add ID > src_data = ( '' % id ) + src_data > id += 1 > print 'adding unique page_id' > > # create new file with .html extension > src_file = src_file.replace('.php', '.html') > > # open newly created html file for insertid data > dest_f = open(src_f, 'w') > dest_f.write(src_data) # write contents > dest_f.close() > print 'writing to %s' % dest_f > From blur959 at hotmail.com Sun Aug 8 06:23:28 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 03:23:28 -0700 (PDT) Subject: Renaming of files in OS directory References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: On Aug 8, 6:05?pm, Thomas Jollans wrote: > On 08/08/2010 10:35 AM, blur959 wrote: > > > > > On Aug 8, 4:15 pm, Chris Rebert wrote: > >> On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: > >>> Hi, all, I am writing a program that renames files inside OS > >>> directories the user provides. I am at the early stage of writing it > >>> and I encountered some problems. > > >>> Below is my code. There is an error i received when i run this code. > >>> The error is, WindowsError: [Error 123] The filename, directory name, > >>> or volume label syntax is incorrect. > > >> Well, what directory did you input? Apparently it wasn't a valid or extant one. > > >> Cheers, > >> Chris > >> --http://blog.rebertia.com > > > I input for e.g, "C:" it works, basically, if i input a hard code > > string inside os.listdir it works, but if i stored the string that the > > user keyed inside a variable and run os.listdir with the variable, > > there is that error. But inputing hard code string inside os.listdir > > isn't what I want when I am writing this program. > > You didn't answert the question. What is the actual string you pass to > os.listdir after you got it from the user? You could > ? ? print repr(fileroot) > to find out. > > My tentative guess is that maybe Windows doesn't like newlines in file > names (I know UNIX allows them, but they're still usually a bad idea) > and maybe you string ends with a newline. I do not get what you mean. The string i passed in is stored inside the variable fileroot. In the case I tested, i inputed the string "C: \" inside the raw_input and stored it inside fileroot, I tried printing repr(fileroot) and it gave me "C:\" as the result and when i tried running os.listdir(fileroot) i got the error. The string i passed to os.listdir is the string i keyed inside fileroot under the raw_input? From ldo at geek-central.gen.new_zealand Sun Aug 8 06:44:56 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Aug 2010 22:44:56 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7x62zslkfm.fsf@ruckus.brouhaha.com> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xfwyvw05q.fsf@ruckus.brouhaha.com> <8c4g22F5ljU1@mid.individual.net> Message-ID: In message <8c4g22F5ljU1 at mid.individual.net>, Gregory Ewing wrote: > FWIW, certain parts of the Darwin kernel are written in a > carefully-selected subset of C++. So Apple evidently think > that it makes sense to use some C++ in a Unix kernel under > some circumstances. I wonder if that explains Apple?s well-known multitasking problems. :) From ldo at geek-central.gen.new_zealand Sun Aug 8 06:45:51 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Aug 2010 22:45:51 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In message , Albert van der Horst wrote: > The bottom line is that to implement a programming language > you want to use a simpler programming language, not a more > complicated one. That would rule out ever using a language to implement itself. From gelonida at gmail.com Sun Aug 8 06:47:51 2010 From: gelonida at gmail.com (Gelonida) Date: Sun, 08 Aug 2010 12:47:51 +0200 Subject: cscope like source code navigation for python code In-Reply-To: References: Message-ID: On 08/08/2010 01:42 AM, Tim Harig wrote: > On 2010-08-07, Gelonida wrote: >> I'm using g?vim and its c-scope plugin for browsing C-code. >> What would be a good way of navigating larger python projects with vim? > > ctags: > http://ctags.sourceforge.net/ Thanks Tim. This looks quite interesting. I prefereed vim/cscope for navigation, but guess after some learning with vim/ctags I should get along quite well. My biggest problem with is, that ctrl-] doesn't ask you to which tag to jump in case multiple options exist. From cournape at gmail.com Sun Aug 8 07:08:00 2010 From: cournape at gmail.com (David Cournapeau) Date: Sun, 8 Aug 2010 20:08:00 +0900 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On Sun, Aug 8, 2010 at 10:10 AM, W. eWatson wrote: > On 8/7/2010 4:45 PM, Martin v. Loewis wrote: >>> >>> To add to the msg I just sent to M. Torrie. We are given the msi >>> programs for Python, PIL,matplotlib, and numpy. The question of how to >>> uninstall and re-install a different version remains. >> >> I'd claim that this is not the real question. The real question is, >> instead: "What specific error did you get when adding a single minus >> sign to the program?" >> >> Please try answering that question also. >> >>> The answer is? >> >> I'm not sure I understand the question. What do you mean by "given"? >> Perhaps "already downloaded locally"? >> >> If so, the obvious answer is "Go to Add-Remove-Programs. Uninstall. >> Then double-click the MSI files." If that is not a good answer: >> why not? >> >> If you want that automated: write a batch file, invoking "msiexec" >> as necessary. >> >> Regards, >> Martin >> >> > Given. We either download them from various specified sites or newbies get a > CD when they receive hardware that is used by the sponsor's programs. > > Add-Remove would be a very good answer, except for one thing. Understand > that I'm in Win7 so CP takes on a different form. On Control Panel > Add-Remove, I can find exactly two Python files: Python 2.5, and > python-Numpy-1.2.0. No scipy anything. Well, this is interesting. I just > noticed Martin v. Loewis on the Python 2.5 entry. That's you, right? You are conflating so many issues at the same time, it is very difficult to follow what you are doing. Concerning the numpy error: you installed a version of scipy which requires a more recent version of numpy than the one you have. More concretely, NumpyTest has disappeared since 1.3.0. Unless you have a good reason not to, I strongly suggest to just use the last released versions of numpy and scipy (1.4.1 and 0.8.0 respectively). Note also that Enthought Python Distribution exists to exactly avoid those issues - they do the packaging hard word so that you don't have to. But none of this has anything to do with one character change or portability, cheers, David From thomas at jollans.com Sun Aug 8 07:27:15 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 13:27:15 +0200 Subject: cscope like source code navigation for python code In-Reply-To: References: Message-ID: <4C5E9493.6060101@jollans.com> On 08/07/2010 07:53 PM, Gelonida wrote: > Hi, > > I'm using g?vim and its c-scope plugin for browsing C-code. > > What would be a good way of navigating larger python projects with vim? > > > thanks for any suggestions > http://pypi.python.org/pypi/pycscope/0.2 Looks like an option From ldo at geek-central.gen.new_zealand Sun Aug 8 07:40:19 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Aug 2010 23:40:19 +1200 Subject: Microsoft lessening commitment to IronPython and IronRuby References: Message-ID: In message , Neil Hodgson wrote: > http://blog.jimmy.schementi.com/2010/08/start-spreading-news-future-of-jimmy.html Frankly I never understood the point of IronPython and IronRuby. They seemed like a desperate attempt to keep Dotnet relevant in the modern world of dynamic languages. Looks like it was a failure. Yawn. From shambhu.1980 at gmail.com Sun Aug 8 07:41:14 2010 From: shambhu.1980 at gmail.com (Shambhu) Date: Sun, 8 Aug 2010 04:41:14 -0700 (PDT) Subject: os.unlink on Windows References: Message-ID: Hi Thomas, I checked, file is present. Here is my sample script: import os filename = "C:\SHAMBHU\tmp\text_delete.txt" os.unlink(filename) File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\ \tmp\\text_delete.txt" is not (with extra backslash in path which is added by os.unlink). Regards. Shambhu. On Aug 7, 4:46?pm, Thomas Jollans wrote: > On 08/07/2010 01:10 PM, Shambhu Sharma wrote: > > > Hi, > > > ? ? ? ? I am new to Python. I was trying to use os.unlink function in > > windows. But i am getting error: > > OSError: [Errno 2] No such file or directory: > > 'C:\\SHAMBHU\\tmp\\text_delete.txt' > > > Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But > > os.unlink is adding extra backslash with pathname. > > No, it isn't. What you're seeing is simply the repr() of the path name > string. > > >>> p = r'C:\SHAMBHU\tmp\text_delete.txt' > >>> p > > 'C:\\SHAMBHU\\tmp\\text_delete.txt'>>> print(p) > > C:\SHAMBHU\tmp\text_delete.txt > > > > I think the file you're trying to delete probably doesn't exist. Why > don't you double-check that. > > > I tried with > > Python2.5 and Python3.1 but got same error. > > Please suggest how to remove this error. > > > -- > > If linux doesn't have a solution, then u have a wrong problem. > > > Shambhu Kumar Sharma > > 91-98864 91913 > > From nikos.the.gr33k at gmail.com Sun Aug 8 07:41:21 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 04:41:21 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> Message-ID: <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> On 8 ???, 13:13, Thomas Jollans wrote: > On 08/08/2010 11:21 AM, ????? wrote: > > > Please help me adjust it, if need extra modification for more php tags > > replacing. > > Have you tried it ? I haven't, but I see no immediate reason why it > wouldn't work with multiple PHP blocks. > > > > > > > #!/usr/bin/python > > > import cgitb; cgitb.enable() > > import cgi, re, os > > > print ( "Content-type: text/html; charset=UTF-8 \n" ) > > > id = 0 ?# unique page_id > > > for currdir, files, dirs in os.walk('data'): > > > ? ? for f in files: > > > ? ? ? ? if f.endswith('php'): > > > ? ? ? ? ? ? # get abs path to filename > > ? ? ? ? ? ? src_f = join(currdir,f) > > > ? ? ? ? ? ? # open php src file > > ? ? ? ? ? ? f = open(src_f, 'r') > > ? ? ? ? ? ? src_data = f.read() ? ? ? ? # read contents of PHP file > > ? ? ? ? ? ? f.close() > > ? ? ? ? ? ? print 'reading from %s' % src_f > > > ? ? ? ? ? ? # replace tags > > ? ? ? ? ? ? src_data = src_data.replace('<%', '') > > ? ? ? ? ? ? src_data = src_data.replace('%>', '') > > Did you read the script before posting? ;-) > Here, you remove ASP-style tags. Which is fine, PHP supports them if you > configure it that way, but you probably didn't. Change this to the start > and end tags you actually use, and, if you use multiple forms (such as > > > > > ? ? ? ? ? ? print 'replacing php tags' > > > ? ? ? ? ? ? # add ID > > ? ? ? ? ? ? src_data = ( '' % id ) + src_data > > ? ? ? ? ? ? id += 1 > > ? ? ? ? ? ? print 'adding unique page_id' > > > ? ? ? ? ? ? # create new file with .html extension > > ? ? ? ? ? ? src_file = src_file.replace('.php', '.html') > > > ? ? ? ? ? ? # open newly created html file for insertid data > > ? ? ? ? ? ? dest_f = open(src_f, 'w') > > ? ? ? ? ? ? dest_f.write(src_data) ? ? ?# write contents > > ? ? ? ? ? ? dest_f.close() > > ? ? ? ? ? ? print 'writing to %s' % dest_f Yes i have read the code very well and by mistake i wrote '<%>' instead of ' of every html file afetr removing the tags this line must be inserted(this holds the template variable) that 'counter.py' uses to produce data

??????? ??????????: %(counter)d

After making this modifications then i can trst the script to a COPY of the original data in my pc. *In my pc i run Windows 7 while remote web hosting setup uses Linux Servers. *That wont be a problem right? From thomas at jollans.com Sun Aug 8 07:45:35 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 13:45:35 +0200 Subject: Renaming of files in OS directory In-Reply-To: References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: <4C5E98DF.2000504@jollans.com> On 08/08/2010 12:23 PM, blur959 wrote: > On Aug 8, 6:05 pm, Thomas Jollans wrote: >> On 08/08/2010 10:35 AM, blur959 wrote: >> >> >> >>> On Aug 8, 4:15 pm, Chris Rebert wrote: >>>> On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: >>>>> Hi, all, I am writing a program that renames files inside OS >>>>> directories the user provides. I am at the early stage of writing it >>>>> and I encountered some problems. >> >>>>> Below is my code. There is an error i received when i run this code. >>>>> The error is, WindowsError: [Error 123] The filename, directory name, >>>>> or volume label syntax is incorrect. >> >>>> Well, what directory did you input? Apparently it wasn't a valid or extant one. >> >>>> Cheers, >>>> Chris >>>> --http://blog.rebertia.com >> >>> I input for e.g, "C:" it works, basically, if i input a hard code >>> string inside os.listdir it works, but if i stored the string that the >>> user keyed inside a variable and run os.listdir with the variable, >>> there is that error. But inputing hard code string inside os.listdir >>> isn't what I want when I am writing this program. >> >> You didn't answert the question. What is the actual string you pass to >> os.listdir after you got it from the user? You could >> print repr(fileroot) >> to find out. >> >> My tentative guess is that maybe Windows doesn't like newlines in file >> names (I know UNIX allows them, but they're still usually a bad idea) >> and maybe you string ends with a newline. > > > > I do not get what you mean. The string i passed in is stored inside > the variable fileroot. In the case I tested, i inputed the string "C: > \" inside the raw_input and stored it inside fileroot, I tried > printing repr(fileroot) and it gave me "C:\" as the result and when i > tried running os.listdir(fileroot) i got the error. The string i > passed to os.listdir is the string i keyed inside fileroot under the > raw_input? You are passing a string to os.listdir. (you call that string fileroot). There is probably something wrong with that string. In principle, it doesn't matter where you got the string from - with raw_input() or by hard-coding the string. repr(fileroot) is almost certainly not "C:\" -- that is not a valid string literal. What did you enter exactly? -- Thomas From usernet at ilthio.net Sun Aug 8 08:15:29 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 12:15:29 +0000 (UTC) Subject: cscope like source code navigation for python code References: Message-ID: On 2010-08-08, Gelonida wrote: > On 08/08/2010 01:42 AM, Tim Harig wrote: >> On 2010-08-07, Gelonida wrote: >>> I'm using g?vim and its c-scope plugin for browsing C-code. >>> What would be a good way of navigating larger python projects with vim? >> >> ctags: >> http://ctags.sourceforge.net/ > > I prefereed vim/cscope for navigation, but guess after some learning > with vim/ctags I should get along quite well. It takes a little getting used to because it isn't as intuative as cscope's visual navigation; but, it is quite efficient once you have internalized it. It also has a portability advantage. ctags works with all versions of vi so you are not just limited to vim. Excuberant ctags works with most langauges that you are likely to be working in and many tools are available that produce ctags files for other languages. > My biggest problem with is, that ctrl-] doesn't ask you to which tag to > jump in case multiple options exist. It usually jumps to the most relavant tag. If necessary, you can specify exactly which tag you need with ":tag". From thomas at jollans.com Sun Aug 8 08:17:26 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 14:17:26 +0200 Subject: os.unlink on Windows In-Reply-To: References: Message-ID: <4C5EA056.1080602@jollans.com> On 08/08/2010 01:41 PM, Shambhu wrote: > Hi Thomas, > > I checked, file is present. Here is my sample script: > import os > filename = "C:\SHAMBHU\tmp\text_delete.txt" > os.unlink(filename) > > File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\ > \tmp\\text_delete.txt" is not (with extra backslash in path which is > added by os.unlink). os.unlink isn't adding anything. The extra backslashes you're seeing are being added when DISPLAYING the file name string. That's because Python uses backslashes to escape special characters in strings. >>> print("C:\\SHAMBHU\\tmp\\text_delete.txt") C:\SHAMBHU\tmp\text_delete.txt >>> print("C:\SHAMBHU\tmp\text_delete.txt") C:\SHAMBHU mp ext_delete.txt >>> '\t' is the TAB character. What is the error message, exactly, when you run the above script? Since you didn't escape the backslashes properly, I expect it refers to 'C:\\SHAMBHU\tmp\text_delet.txt' -- The first backslash is still a backslash -- it gets doubled when printed as a string (but NOT when passed to the OS by unlink), but the second and third ones were used to create TAB characters. Probably. Either always double backslashes in paths, or use raw string literals (r"C:\SHAMBHU\tmp\text_delete.txt" -- keeps the \s) (or use forward slashes in paths...) > > Regards. > Shambhu. > > > > On Aug 7, 4:46 pm, Thomas Jollans wrote: >> On 08/07/2010 01:10 PM, Shambhu Sharma wrote: >> >>> Hi, >> >>> I am new to Python. I was trying to use os.unlink function in >>> windows. But i am getting error: >>> OSError: [Errno 2] No such file or directory: >>> 'C:\\SHAMBHU\\tmp\\text_delete.txt' >> >>> Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But >>> os.unlink is adding extra backslash with pathname. >> >> No, it isn't. What you're seeing is simply the repr() of the path name >> string. >> >>>>> p = r'C:\SHAMBHU\tmp\text_delete.txt' >>>>> p >> >> 'C:\\SHAMBHU\\tmp\\text_delete.txt'>>> print(p) >> >> C:\SHAMBHU\tmp\text_delete.txt >> >> >> > >> I think the file you're trying to delete probably doesn't exist. Why >> don't you double-check that. >> >>> I tried with >>> Python2.5 and Python3.1 but got same error. >>> Please suggest how to remove this error. >> >>> -- >>> If linux doesn't have a solution, then u have a wrong problem. >> >>> Shambhu Kumar Sharma >>> 91-98864 91913 >> >> > From blur959 at hotmail.com Sun Aug 8 08:35:52 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 05:35:52 -0700 (PDT) Subject: Renaming of files in OS directory References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> Message-ID: <509a751d-6c82-4129-b3de-85aab9f69ef1@v6g2000prd.googlegroups.com> On Aug 8, 7:45?pm, Thomas Jollans wrote: > On 08/08/2010 12:23 PM, blur959 wrote: > > > > > On Aug 8, 6:05 pm, Thomas Jollans wrote: > >> On 08/08/2010 10:35 AM, blur959 wrote: > > >>> On Aug 8, 4:15 pm, Chris Rebert wrote: > >>>> On Sun, Aug 8, 2010 at 1:02 AM, blur959 wrote: > >>>>> Hi, all, I am writing a program that renames files inside OS > >>>>> directories the user provides. I am at the early stage of writing it > >>>>> and I encountered some problems. > > >>>>> Below is my code. There is an error i received when i run this code. > >>>>> The error is, WindowsError: [Error 123] The filename, directory name, > >>>>> or volume label syntax is incorrect. > > >>>> Well, what directory did you input? Apparently it wasn't a valid or extant one. > > >>>> Cheers, > >>>> Chris > >>>> --http://blog.rebertia.com > > >>> I input for e.g, "C:" it works, basically, if i input a hard code > >>> string inside os.listdir it works, but if i stored the string that the > >>> user keyed inside a variable and run os.listdir with the variable, > >>> there is that error. But inputing hard code string inside os.listdir > >>> isn't what I want when I am writing this program. > > >> You didn't answert the question. What is the actual string you pass to > >> os.listdir after you got it from the user? You could > >> ? ? print repr(fileroot) > >> to find out. > > >> My tentative guess is that maybe Windows doesn't like newlines in file > >> names (I know UNIX allows them, but they're still usually a bad idea) > >> and maybe you string ends with a newline. > > > I do not get what you mean. The string i passed in is stored inside > > the variable fileroot. In the case I tested, i inputed the string "C: > > \" inside the raw_input and stored it inside fileroot, I tried > > printing repr(fileroot) and it gave me "C:\" as the result and when i > > tried running os.listdir(fileroot) i got the error. The string i > > passed to os.listdir is the string i keyed inside fileroot under the > > raw_input? > > You are passing a string to os.listdir. (you call that string fileroot). > There is probably something wrong with that string. In principle, it > doesn't matter where you got the string from - with raw_input() or by > hard-coding the string. > > repr(fileroot) is almost certainly not "C:\" -- that is not a valid > string literal. > > What did you enter exactly? > > -- Thomas Sorry, This is my first time using the os commands in python, Ok, firstly, I entered "C:\" inside raw_input and stored it inside fileroot. When i print repr(fileroot), my result was '"C:\\"' . And when I run os.listdir with fileroot, I got that error. I typed my os.listdir code like this: os.listdir(fileroot) I attached my code for reference, thanks again! import os, glob def fileDirectory(): # Ask user for file directory input fileroot = raw_input("Input") print repr(fileroot) #Returns a list with all the files inside the file root directory( The error occurs here ) os.listdir(fileroot) fileDirectory() From thomas at jollans.com Sun Aug 8 08:40:05 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 14:40:05 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> Message-ID: <4C5EA5A5.90107@jollans.com> On 08/08/2010 01:41 PM, ????? wrote: > I was so dizzy and confused yesterday that i forgot to metnion that > not only i need removal of php openign and closing tags but whaevers > data lurks inside those tags as well ebcause now with the 'counter.py' > script i wrote the html fiels would open ftm there and substitute the > tempalte variabels like %(counter)d I could just hand you a solution, but I'll be a bit of a bastard and just give you some hints. You could use regular expressions. If you know regular expressions, it's relatively trivial - but I doubt you know regexp. You could also repeatedly find the next occurrence of first a start tag, then an end tag, using either str.find or str.split, and build up a version of the file without PHP yourself. > Also before the > > > > > of every html file afetr removing the tags this line must be > inserted(this holds the template variable) that 'counter.py' uses to > produce data > >

??????? ??????????: %(counter)d >

This problem is truly trivial. I know you can do it yourself, or at least give it a good shot, and ask again when you hit a serious roadblock. If I may comment on your HTML: you forgot to close your
and tags. Close them! Also, both (CENTER and FONT) have been deprecated since HTML 4.0 -- you should consider using CSS for these tasks instead. Also, this line does not look like a heading, so H4 is hardly fitting. > > After making this modifications then i can trst the script to a COPY > of the original data in my pc. It would be nice if you re-read your posts before sending and tried to iron out some of more careless spelling mistakes. Maybe you are doing your best to post in good English -- it isn't bad and I realize this is neither your native language nor alphabet, in which case I apologize. The fact of the matter is: I originally interpreter "trst" as "trust", which made no sense whatsoever. > > *In my pc i run Windows 7 while remote web hosting setup uses Linux > Servers. > *That wont be a problem right? Nah. From wolftracks at invalid.com Sun Aug 8 09:03:48 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 08 Aug 2010 06:03:48 -0700 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On 8/8/2010 4:08 AM, David Cournapeau wrote: ... >> python-Numpy-1.2.0. No scipy anything. Well, this is interesting. I just >> noticed Martin v. Loewis on the Python 2.5 entry. That's you, right? > > You are conflating so many issues at the same time, it is very > difficult to follow what you are doing. > > Concerning the numpy error: you installed a version of scipy which > requires a more recent version of numpy than the one you have. More > concretely, NumpyTest has disappeared since 1.3.0. Unless you have a > good reason not to, I strongly suggest to just use the last released > versions of numpy and scipy (1.4.1 and 0.8.0 respectively). > > Note also that Enthought Python Distribution exists to exactly avoid > those issues - they do the packaging hard word so that you don't have > to. > > But none of this has anything to do with one character change or portability, > > cheers, > > David Believe me I had no intent of expanding this thread beyond looking for a straight and simple insight to Python distribution (portability, whatever) and how to get my partner squared away. The general issue seems to drifted off on its own accord. I find generally that once I've had to post five times on a topic, and haven't gotten a satisfactory answer, I'm not going to get one. Yes, you are quite correct about numpy, but for reasons which I have no plans to explain, I want my partner on the same version of numpy as myself. I now have the answer I need, and I do not care one more wit about a one character change. I'm done here. From thomas at jollans.com Sun Aug 8 09:13:25 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 15:13:25 +0200 Subject: Renaming of files in OS directory In-Reply-To: <509a751d-6c82-4129-b3de-85aab9f69ef1@v6g2000prd.googlegroups.com> References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> <509a751d-6c82-4129-b3de-85aab9f69ef1@v6g2000prd.googlegroups.com> Message-ID: <4C5EAD75.8000805@jollans.com> On 08/08/2010 02:35 PM, blur959 wrote: > Sorry, This is my first time using the os commands in python, Ok, > firstly, I entered "C:\" inside raw_input and stored it inside > fileroot. When i print repr(fileroot), my result was '"C:\\"' . And > when I run os.listdir with fileroot, I got that error. I typed my > os.listdir code like this: os.listdir(fileroot) > > I attached my code for reference, thanks again! Okay, maybe you've already understood the problem now, but in case you haven't: '"C:\\"' is no valid file name. The quotes ("") are part of what you're passing to the OS here, which you don't want. Just enter the file name without quotes. (or, if you really want quoting for some reason, you could manually strip the quotes, or use the shlex module. > > > import os, glob > > def fileDirectory(): > # Ask user for file directory input > fileroot = raw_input("Input") > print repr(fileroot) > > > #Returns a list with all the files inside the file root > directory( The error occurs here ) > os.listdir(fileroot) > > > fileDirectory() From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 09:29:43 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Aug 2010 13:29:43 GMT Subject: os.unlink on Windows References: Message-ID: <4c5eb146$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 04:41:14 -0700, Shambhu wrote: > Hi Thomas, > > I checked, file is present. Here is my sample script: > import os > filename = "C:\SHAMBHU\tmp\text_delete.txt" Did you intend to provide a filename with two TAB characters in it? c colon backslash s h a m b u TAB m p TAB e x t underscore d e l e t e dot t x t > File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\ > \tmp\\text_delete.txt" is not (with extra backslash in path which is > added by os.unlink). os.unlink does add any extra backslashes. You are misinterpreting what you are seeing. -- Steven From costin.gament at gmail.com Sun Aug 8 09:32:19 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 16:32:19 +0300 Subject: Class initialization Message-ID: Hi there. I'm kind of a beginner with Python (and programming in general). My problem is with initializing a class. Let's say I've defined it like this: class foo: a = 0 b = 0 and later I'm trying to initialize two different classes like this: c1 = foo() c2 = foo() The problem I have is that c1 and c2 tend to point to the same instance, like a weird c-like pointer. Please tell me, what am I doing wrong? Thank you, From gslindstrom at gmail.com Sun Aug 8 09:40:48 2010 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sun, 8 Aug 2010 08:40:48 -0500 Subject: # of Months between two dates Message-ID: I work for a company that processes claims for the health care industry (Novasys Health, recently purchased by Centene Corp). My current assignment has me writing a routine to compute insurance premiums. One of the requirements is to determine how many months a policy has been in effect. The datetime module will give me the number of days but, with months having different lengths, that does not do me much good. I've looked in the calendar library but didn't see anything there, either. I've written a function to return the months between date1 and date2 but I'd like to know if anyone is aware of anything in the standard library to do the same? For bonus points, does anyone know if postgres can do the same (we use a lot of date/time funcitons in postgres, already, but didn't see this problem addressed). On a side note; since I'm dealing with money (USD), I decided to use the decimal module for all computations. It's not a big difference -- unless you've seen the movie "Office Space" :-) -- but it sure is nice. Especially being able to easily round values to the nearest cent. You just have to love the standard library. Thanks for your help, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From blur959 at hotmail.com Sun Aug 8 09:43:52 2010 From: blur959 at hotmail.com (blur959) Date: Sun, 8 Aug 2010 06:43:52 -0700 (PDT) Subject: Renaming of files in OS directory References: <832f1e18-7250-4dc0-a8c3-09f6092f790d@h40g2000pro.googlegroups.com> <509a751d-6c82-4129-b3de-85aab9f69ef1@v6g2000prd.googlegroups.com> Message-ID: <2126c6f2-762b-47e6-b50e-6cb2c956c68d@l25g2000prn.googlegroups.com> On Aug 8, 9:13?pm, Thomas Jollans wrote: > On 08/08/2010 02:35 PM, blur959 wrote: > > > Sorry, This is my first time using the os commands in python, Ok, > > firstly, I entered "C:\" inside raw_input and stored it inside > > fileroot. When i print repr(fileroot), my result was '"C:\\"' . And > > when I run os.listdir with fileroot, I got that error. I typed my > > os.listdir code like this: os.listdir(fileroot) > > > I attached my code for reference, thanks again! > > Okay, maybe you've already understood the problem now, but in case you > haven't: > '"C:\\"' is no valid file name. The quotes ("") are part of what you're > passing to the OS here, which you don't want. Just enter the file name > without quotes. (or, if you really want quoting for some reason, you > could manually strip the quotes, or use the shlex module. > > > > > import os, glob > > > def fileDirectory(): > > ? ? # Ask user for file directory input > > ? ? fileroot = raw_input("Input") > > ? ? print repr(fileroot) > > > ? ? #Returns a list with all the files inside the file root > > directory( The error occurs here ) > > ? ? os.listdir(fileroot) > > > fileDirectory() > > okay i got it already thanks alot man! Appreciate it! From gelonida at gmail.com Sun Aug 8 09:49:26 2010 From: gelonida at gmail.com (Gelonida) Date: Sun, 08 Aug 2010 15:49:26 +0200 Subject: cscope like source code navigation for python code In-Reply-To: <4C5E9493.6060101@jollans.com> References: <4C5E9493.6060101@jollans.com> Message-ID: Hi Thomas, On 08/08/2010 01:27 PM, Thomas Jollans wrote: > On 08/07/2010 07:53 PM, Gelonida wrote: >> Hi, >> >> I'm using g?vim and its c-scope plugin for browsing C-code. >> >> What would be a good way of navigating larger python projects with vim? >> >> >> thanks for any suggestions >> > > > http://pypi.python.org/pypi/pycscope/0.2 > > Looks like an option Yes it looks like an option. Unfortunately it is from 2006 and reported (and aborted) on a syntax error of one of my files. My file is running and passes pylint / pychecker. So I'm afraid, that the code might be outdated. I'll investigte perhaps a little more. From downaold at gmail.com Sun Aug 8 09:59:56 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 8 Aug 2010 15:59:56 +0200 Subject: Class initialization In-Reply-To: References: Message-ID: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> On Aug 8, 2010, at 3:32 PM, Costin Gament wrote: > Hi there. > I'm kind of a beginner with Python (and programming in general). My > problem is with initializing a class. Let's say I've defined it like > this: > > class foo: > a = 0 > b = 0 > > and later I'm trying to initialize two different classes like this: > c1 = foo() > c2 = foo() > > The problem I have is that c1 and c2 tend to point to the same > instance, like a weird c-like pointer. Please tell me, what am I doing > wrong? Your problem probably is that a and b are class variables; c1 and c2 are different objects (in your terminology: they point to different instances). See http://docs.python.org/tutorial/classes.html#class-objects for more info. Cheers, Roald From nikos.the.gr33k at gmail.com Sun Aug 8 10:06:20 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 07:06:20 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> Message-ID: <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> On 8 ???, 15:40, Thomas Jollans wrote: > On 08/08/2010 01:41 PM, ????? wrote: > > > I was so dizzy and confused yesterday that i forgot to metnion that > > not only i need removal of php openign and closing tags but whaevers > > data lurks inside those tags as well ebcause now with the 'counter.py' > > script i wrote the html fiels would open ftm there and substitute the > > tempalte variabels like %(counter)d > > I could just hand you a solution, but I'll be a bit of a bastard and > just give you some hints. > > You could use regular expressions. If you know regular expressions, it's > relatively trivial - but I doubt you know regexp. Here is the code with some try-and-fail modification i made, still non- working based on your hints: ========================================================== id = 0 # unique page_id for currdir, files, dirs in os.walk('varsa'): for f in files: if f.endswith('php'): # get abs path to filename src_f = join(currdir, f) # open php src file print 'reading from %s' % src_f f = open(src_f, 'r') src_data = f.read() # read contents of PHP file f.close() # replace tags print 'replacing php tags and contents within' src_data = src_data.replace(r'', '') # the dot matches any character i hope! no matter how many of them?!? # add ID print 'adding unique page_id' src_data = ( '' % id ) + src_data id += 1 # add template variables print 'adding counter template variable' src_data = src_data + '''

??????? ??????????: %(counter)d

''' # i can think of this but the above line must be above NOT after but how to right that?!? # rename old php file to new with .html extension src_file = src_file.replace('.php', '.html') # open newly created html file for inserting data print 'writing to %s' % dest_f dest_f = open(src_f, 'w') dest_f.write(src_data) # write contents dest_f.close() This is the best i can do. Sorry for any typos i might made. Please shed some LIGHT! From costin.gament at gmail.com Sun Aug 8 10:14:08 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 17:14:08 +0300 Subject: Class initialization In-Reply-To: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: Thank you for your answer, but it seems I didn't make myself clear. Take the code: class foo: a = 0 b = 0 c1 = foo() c1.a = 5 c2 = foo() print c2.a 5 Somehow, when I try to acces the 'a' variable in c2 it has the same value as the 'a' variable in c1. Am I missing something? On Sun, Aug 8, 2010 at 4:59 PM, Roald de Vries wrote: > > Your problem probably is that a and b are class variables; c1 and c2 are > different objects (in your terminology: they point to different instances). > > See http://docs.python.org/tutorial/classes.html#class-objects for more > info. > > Cheers, Roald > > -- > http://mail.python.org/mailman/listinfo/python-list > From steveo at syslang.net Sun Aug 8 10:21:45 2010 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 08 Aug 2010 10:21:45 -0400 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <3cc2a461-19f0-4aaf-9305-dde36fa2656c@v6g2000prd.googlegroups.com> References: <3cc2a461-19f0-4aaf-9305-dde36fa2656c@v6g2000prd.googlegroups.com> Message-ID: <4C5EBD79.80607@syslang.net> On 08/07/10 23:57, quoth Miki: > On Aug 7, 7:42 pm, "Steven W. Orr" wrote: >> I'm ok in python but I haven't done too much with web pages. I have a web page >> that is hand written in html that has about 1000 entries in a table and I want >> to convert the table from entries like this >> >>
>> >> >> >> >> >> >> >> to >> >> SomePythonCall('Some Date String', >> 'SomeTag', >> 'localSubdir', >> "http://www.example.com/remote/path/something.html", >> 'Click', >> 'Some Comment') >> >> Can someone tell me what I should look at to do this? Is mod_python where I >> should start or are there things that are better? > Have a look at http://www.crummy.com/software/BeautifulSoup/. Thanks. But what I'm not seeing is any example of how to make this allowed to generate the html at run time. I think I want to embed my python code into an html file. Beautiful soup seems to allow me to create a preprocessor which I could use through a Makefile to generate the html. I have the feeling I'm missing something. Or do I use this in conjunction with wsgi? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From downaold at gmail.com Sun Aug 8 10:38:34 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 8 Aug 2010 16:38:34 +0200 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: <446A31BC-2992-416D-B7B9-A846CB7AC09A@gmail.com> On Aug 8, 2010, at 4:14 PM, Costin Gament wrote: > Thank you for your answer, but it seems I didn't make myself clear. You could have been clearer in your first post, yeah. > Take the code: > class foo: > a = 0 > b = 0 > c1 = foo() > c1.a = 5 > c2 = foo() > print c2.a > 5 > > Somehow, when I try to acces the 'a' variable in c2 it has the same > value as the 'a' variable in c1. Am I missing something? I can't reproduce this. Which version are you using? > On Sun, Aug 8, 2010 at 4:59 PM, Roald de Vries > wrote: >> >> Your problem probably is that a and b are class variables; And class variables are not instance variables. >> c1 and c2 are >> different objects (in your terminology: they point to different >> instances). I still suspect that this is the problem. In Python, classes are objects (instances of another class) too. In your class, you assign 0 to the variables foo.a and foo.b. >> See http://docs.python.org/tutorial/classes.html#class-objects for >> more >> info. So: > class foo: > a = 0 creates a class variable foo.a and set it to 0 > b = 0 creates a class variable foo.b and set it to 0 > c1 = foo() creates a new foo that can be referenced as c1 > c1.a = 5 creates an instance variable c1.a and set it to 5 > c2 = foo() creates a new foo that can be referenced as c2 > print c2.a there is no instance variable c2.a, so the class variable foo.a is referenced > 5 I get 0 here. Cheers, Roald From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 10:49:27 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Aug 2010 14:49:27 GMT Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: <4c5ec3f7$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 17:14:08 +0300, Costin Gament wrote: > Thank you for your answer, but it seems I didn't make myself clear. Take > the code: > class foo: > a = 0 > b = 0 > c1 = foo() > c1.a = 5 > c2 = foo() > print c2.a > 5 Incorrect. >>> class foo: ... a = 0 ... b = 0 ... >>> c1 = foo() >>> c1.a = 5 >>> c2 = foo() >>> print c2.a 0 -- Steven From costin.gament at gmail.com Sun Aug 8 10:57:38 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 17:57:38 +0300 Subject: Class initialization In-Reply-To: <4c5ec3f7$0$28663$c3e8da3@news.astraweb.com> References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> <4c5ec3f7$0$28663$c3e8da3@news.astraweb.com> Message-ID: Apparently, the code I've given here does, in fact, work. Still, I am encountering a similar problem in a much larger class (it is in a separate module, if that is any help). Also, the variable I am having trouble with is itself another class. I don't think it's appropriate to paste so much code in here, so if anybody has some knowledge about similar problems... On Sun, Aug 8, 2010 at 5:49 PM, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 17:14:08 +0300, Costin Gament wrote: > >> Thank you for your answer, but it seems I didn't make myself clear. Take >> the code: >> class foo: >> ? a = 0 >> ? b = 0 >> c1 = foo() >> c1.a = 5 >> c2 = foo() >> print c2.a >> 5 > > Incorrect. > >>>> class foo: > ... ? a = 0 > ... ? b = 0 > ... >>>> c1 = foo() >>>> c1.a = 5 >>>> c2 = foo() >>>> print c2.a > 0 > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > From thomas at jollans.com Sun Aug 8 10:59:34 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 16:59:34 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <4C5EC656.9070105@jollans.com> On 08/08/2010 04:06 PM, ????? wrote: > On 8 ???, 15:40, Thomas Jollans wrote: >> On 08/08/2010 01:41 PM, ????? wrote: >> >>> I was so dizzy and confused yesterday that i forgot to metnion that >>> not only i need removal of php openign and closing tags but whaevers >>> data lurks inside those tags as well ebcause now with the 'counter.py' >>> script i wrote the html fiels would open ftm there and substitute the >>> tempalte variabels like %(counter)d >> >> I could just hand you a solution, but I'll be a bit of a bastard and >> just give you some hints. >> >> You could use regular expressions. If you know regular expressions, it's >> relatively trivial - but I doubt you know regexp. > > Here is the code with some try-and-fail modification i made, still non- > working based on your hints: > ========================================================== > > id = 0 # unique page_id > > for currdir, files, dirs in os.walk('varsa'): > > for f in files: > > if f.endswith('php'): > > # get abs path to filename > src_f = join(currdir, f) > > # open php src file > print 'reading from %s' % src_f > f = open(src_f, 'r') > src_data = f.read() # read contents of PHP file > f.close() > > # replace tags > print 'replacing php tags and contents within' > src_data = src_data.replace(r'', '') # > the dot matches any character i hope! no matter how many of them?!? Two problems here: str.replace doesn't use regular expressions. You'll have to use the re module to use regexps. (the re.sub function to be precise) '.' matches a single character. Any character, but only one. '.*' matches as many characters as possible. This is not what you want, since it will match everything between the *first* . You want non-greedy matching. '.*?' is the same thing, without the greed. > > # add ID > print 'adding unique page_id' > src_data = ( '' % id ) + src_data > id += 1 > > # add template variables > print 'adding counter template variable' > src_data = src_data + '''

??????? > ??????????: %(counter)d

''' > # i can think of this but the above line must be above body> NOT after but how to right that?!? You will have to find the tag before inserting the string. str.find should help -- or you could use str.replace and replace the tag with you counter line, plus a new . > > # rename old php file to new with .html extension > src_file = src_file.replace('.php', '.html') > > # open newly created html file for inserting data > print 'writing to %s' % dest_f > dest_f = open(src_f, 'w') > dest_f.write(src_data) # write contents > dest_f.close() > > This is the best i can do. No it's not. You're just giving up too soon. From usernet at ilthio.net Sun Aug 8 11:01:53 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 15:01:53 +0000 (UTC) Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On 2010-08-08, Costin Gament wrote: > Thank you for your answer, but it seems I didn't make myself clear. > Take the code: > class foo: > a = 0 > b = 0 > c1 = foo() > c1.a = 5 > c2 = foo() > print c2.a > 5 > > Somehow, when I try to acces the 'a' variable in c2 it has the same > value as the 'a' variable in c1. Am I missing something? Others have told you that at a and b belong to the class object rather then to the instance objects. Perhaps this will demonstrate the difference: >>> class foo(): ... def __init__(self): ... self.a = 0 ... self.b = 0 ... >>> c1 = foo() >>> c1.a = 5 >>> c2 = foo() >>> print c2.a 0 >>> From albert at spenarnc.xs4all.nl Sun Aug 8 11:12:16 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 08 Aug 2010 15:12:16 GMT Subject: easy question on parsing python: "is not None" References: <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> Message-ID: In article <8c2uiuFg9bU1 at mid.individual.net>, Peter Pearson wrote: >On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: >[snip] >> I can imagine a case where you might want to compare a >> string with `is`: >> >> FORWARD = "forward" >> BACKWARD = "backward" >> >> ... >> >> def func(direction=FORWARD): >> if direction is FORWARD: >> ... >> elif direction is BACKWARD: >> ... >> else: >> ... >> >> in case you expect people to specifically use the constants >> you provided in the module. Here, the fact that FORWARD >> actually is the string "forward" might be considered an >> implementation detail. Using a string instead of an >> `object()` has the advantage that it makes usage in error >> messages easier. >> >> Actually, I've never seen such a use, as far as I remember. >> What do other people here think? Is the code above, which >> compares strings with `is`, bad style, and if yes, why? How >> would you write the code instead? > >Hey, that's a cute example, but . . . what a trap! Is it >possible to document the use-the-object-not-the-string requirement >loudly enough that people won't get caught? king = "This is just a string for denoting a chess object, \ if a field contains (a reference to) king, it means the piece \ is standing on that field" Even a fresh convert from the Java language would not insert the string instead of the name of the object. (In practive you want black kings and white kings to be different objects, probably.) > >-- >To email me, substitute nowhere->spamcop, invalid->net. -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From jhjaggars at gmail.com Sun Aug 8 11:13:00 2010 From: jhjaggars at gmail.com (Jesse Jaggars) Date: Sun, 8 Aug 2010 10:13:00 -0500 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On Sun, Aug 8, 2010 at 10:01 AM, Tim Harig wrote: > On 2010-08-08, Costin Gament wrote: >> Thank you for your answer, but it seems I didn't make myself clear. >> Take the code: >> class foo: >> ? a = 0 >> ? b = 0 >> c1 = foo() >> c1.a = 5 >> c2 = foo() >> print c2.a >> 5 >> >> Somehow, when I try to acces the 'a' variable in c2 it has the same >> value as the 'a' variable in c1. Am I missing something? > > Others have told you that at a and b belong to the class object rather then > to the instance objects. ?Perhaps this will demonstrate the difference: > >>>> class foo(): > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.a = 0 > ... ? ? ? ? ? ? self.b = 0 > ... >>>> c1 = foo() >>>> c1.a = 5 >>>> c2 = foo() >>>> print c2.a > 0 >>>> > -- > http://mail.python.org/mailman/listinfo/python-list > Is it possible that you are using a mutable class object? A common gotcha is to do something like this: >>> class foo(object): ... x = [] ... >>> a = foo() >>> b = foo() >>> a.x.append(123) >>> b.x [123] And expect b.x to be an empty list. From costin.gament at gmail.com Sun Aug 8 11:14:06 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 18:14:06 +0300 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: So you're saying I should just use __init__? Will that get me out of my predicament? No, I don't quite understand the difference between my exemple and using __init__, but I will read the docs about it. On Sun, Aug 8, 2010 at 6:01 PM, Tim Harig wrote: > > Others have told you that at a and b belong to the class object rather then > to the instance objects. ?Perhaps this will demonstrate the difference: > >>>> class foo(): > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.a = 0 > ... ? ? ? ? ? ? self.b = 0 > ... >>>> c1 = foo() >>>> c1.a = 5 >>>> c2 = foo() >>>> print c2.a > 0 >>>> From costin.gament at gmail.com Sun Aug 8 11:16:20 2010 From: costin.gament at gmail.com (Costin Gament) Date: Sun, 8 Aug 2010 18:16:20 +0300 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: That looks just like my code. What's the problem? On Sun, Aug 8, 2010 at 6:13 PM, Jesse Jaggars wrote: > > Is it possible that you are using a mutable class object? A common > gotcha is to do something like this: > >>>> class foo(object): > ... ? x = [] > ... >>>> a = foo() >>>> b = foo() >>>> a.x.append(123) >>>> b.x > [123] > > And expect b.x to be an empty list. From knny.myer at gmail.com Sun Aug 8 11:28:06 2010 From: knny.myer at gmail.com (Kenny Meyer) Date: Sun, 8 Aug 2010 11:28:06 -0400 Subject: cscope like source code navigation for python code In-Reply-To: References: <4C5E9493.6060101@jollans.com> Message-ID: <20100808152806.GD10814@5732Z> Gelonida (gelonida at gmail.com) wrote: > Hi Thomas, > > On 08/08/2010 01:27 PM, Thomas Jollans wrote: > > On 08/07/2010 07:53 PM, Gelonida wrote: > >> Hi, > >> > >> I'm using g?vim and its c-scope plugin for browsing C-code. > >> > >> What would be a good way of navigating larger python projects with vim? > >> > >> > >> thanks for any suggestions > >> > > > > > > http://pypi.python.org/pypi/pycscope/0.2 > > > > Looks like an option > > Yes it looks like an option. > Unfortunately it is from 2006 and reported (and aborted) on a syntax > error of one of my files. > > My file is running and passes pylint / pychecker. > > So I'm afraid, that the code might be outdated. > I'll investigte perhaps a little more. I wonder if you have seen the new version: http://pypi.python.org/pypi/pycscope/0.3 -- Onward and upwards, .O. Kenny Meyer ..O :wq OOO -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: Digital signature URL: From usernet at ilthio.net Sun Aug 8 11:28:32 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 15:28:32 +0000 (UTC) Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On 2010-08-08, Costin Gament wrote: > So you're saying I should just use __init__? Will that get me out of > my predicament? > No, I don't quite understand the difference between my exemple and > using __init__, but I will read the docs about it. It is not so much using __init__() that makes the difference as it what scope the variables are assigned to. If you define them as you where, then the variables are associated with the class object itself. If the variable is a mutable type, and you change it in one instance, it actually changes it in the class object which means it also changes for all of the instances. I used the constructor because it gives me a reference to the newly created instance object "self". I then assign the variables to self, which assignes them to the newly created instance object. Then each instance has its own separate a and b variables that will not change when the variables are changed inside of another instance object. From costin.gament at gmail.com Sun Aug 8 11:45:53 2010 From: costin.gament at gmail.com (=?UTF-8?Q?Costin_Gamen=C8=9B?=) Date: Sun, 8 Aug 2010 18:45:53 +0300 Subject: Class initialization In-Reply-To: References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: Thanks a lot. I'll try give it a go and see if it helps. On Sun, Aug 8, 2010 at 6:28 PM, Tim Harig wrote: > It is not so much using __init__() that makes the difference as it what > scope the variables are assigned to. ?If you define them as you where, then > the variables are associated with the class object itself. ?If the variable > is a mutable type, and you change it in one instance, it actually changes > it in the class object which means it also changes for all of the > instances. > > I used the constructor because it gives me a reference to the newly created > instance object "self". ?I then assign the variables to self, which > assignes them to the newly created instance object. ?Then each instance has > its own separate a and b variables that will not change when the variables > are changed inside of another instance object. From usernet at ilthio.net Sun Aug 8 11:49:32 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 15:49:32 +0000 (UTC) Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On 2010-08-08, Tim Harig wrote: > On 2010-08-08, Costin Gament wrote: >> So you're saying I should just use __init__? Will that get me out of >> my predicament? >> No, I don't quite understand the difference between my exemple and >> using __init__, but I will read the docs about it. > > It is not so much using __init__() that makes the difference as it what > scope the variables are assigned to. If you define them as you where, then > the variables are associated with the class object itself. If the variable > is a mutable type, and you change it in one instance, it actually changes > it in the class object which means it also changes for all of the > instances. > > I used the constructor because it gives me a reference to the newly created > instance object "self". I then assign the variables to self, which > assignes them to the newly created instance object. Then each instance has > its own separate a and b variables that will not change when the variables > are changed inside of another instance object. Maybe I can make that a little clearer yet. When you define a class in python you actually create a class object. This object is basically used as a template to create instance objects. When you define a variable attached to the class object that is mutable, the instance objects receive the exact same reference that was given to the instance object. Since it is mutable, any changes made using that reference will affect all of the instances that also point to that reference. You wouldn't have seen this effect using your simplified examle because number are immutable objects. When you change the value for one of the instance objects, it receives a new reference, rather then making the change in place. The other instances do not reflect this change because their variables still point back to the original reference given to the class. From steve at holdenweb.com Sun Aug 8 11:51:58 2010 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Aug 2010 11:51:58 -0400 Subject: DjangoCon 2010 Message-ID: <4C5ED29E.90403@holdenweb.com> This is a reminder that DjangoCon US 2010 is now under a month away! The third such conference, DjangoCon returns this year to the green Doubletree Hotel in Portland, OR from September 7-9, with a three day sprint hosted by Urban Airship from September 10-12. The program schedule is at http://djangocon.us/schedule/ and you can register at http://djangocon.us/tickets/ The conference price for hotel accommodation is guaranteed only until August 13, so if you plan to attend you should register straight away. -- Steve Holden +1 571 484 6266 +1 800 494 3119 DjangoCon US September 7-9, 2010 http://djangocon.us/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ From usernet at ilthio.net Sun Aug 8 11:55:09 2010 From: usernet at ilthio.net (Tim Harig) Date: Sun, 8 Aug 2010 15:55:09 +0000 (UTC) Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: On 2010-08-08, Tim Harig wrote: > On 2010-08-08, Tim Harig wrote: >> On 2010-08-08, Costin Gament wrote: >>> So you're saying I should just use __init__? Will that get me out of >>> my predicament? >>> No, I don't quite understand the difference between my exemple and >>> using __init__, but I will read the docs about it. >> >> It is not so much using __init__() that makes the difference as it what >> scope the variables are assigned to. If you define them as you where, then >> the variables are associated with the class object itself. If the variable >> is a mutable type, and you change it in one instance, it actually changes >> it in the class object which means it also changes for all of the >> instances. >> >> I used the constructor because it gives me a reference to the newly created >> instance object "self". I then assign the variables to self, which >> assignes them to the newly created instance object. Then each instance has >> its own separate a and b variables that will not change when the variables >> are changed inside of another instance object. > > Maybe I can make that a little clearer yet. When you define a class in > python you actually create a class object. This object is basically used > as a template to create instance objects. When you define a variable > attached to the class object that is mutable, the instance objects receive > the exact same reference that was given to the instance object. Since it > is mutable, any changes made using that reference will affect all of the > instances that also point to that reference. You wouldn't have seen this > effect using your simplified examle because number are immutable objects. > When you change the value for one of the instance objects, it receives a > new reference, rather then making the change in place. The other instances > do not reflect this change because their variables still point back to the > original reference given to the class. And to complete that thought, when you assign variables directly to the instance, as I did using the constructor's reference to self, each instance receives a brand new reference that is not shared among any of the other instances. From wolftracks at invalid.com Sun Aug 8 12:16:22 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 08 Aug 2010 09:16:22 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? Message-ID: See Subject. I use matplotlib, scipy, numpy and possibly one other module. If I go to the control panel, I only see numpy listed. Why? I use a search and find only numpy and Python itself. How can matplotlib and scipy be uninstalled? From aahz at pythoncraft.com Sun Aug 8 12:24:39 2010 From: aahz at pythoncraft.com (Aahz) Date: 8 Aug 2010 09:24:39 -0700 Subject: suitable py2app. References: <744e466d-40c8-4a20-97cc-c8973aa369a9@c38g2000vba.googlegroups.com> Message-ID: In article <744e466d-40c8-4a20-97cc-c8973aa369a9 at c38g2000vba.googlegroups.com>, ata.jaf wrote: > >I'm looking for a suitable tutorial for "py2app". I googled it but >couldn't find anything. Can you help me please? What did you google for? "py2app tutorial" finds lots of hits. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From breamoreboy at yahoo.co.uk Sun Aug 8 12:51:31 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 08 Aug 2010 17:51:31 +0100 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On 08/08/2010 17:16, W. eWatson wrote: > See Subject. I use matplotlib, scipy, numpy and possibly one other > module. If I go to the control panel, I only see numpy listed. Why? I > use a search and find only numpy and Python itself. How can matplotlib > and scipy be uninstalled? Have you heard of google? Mark Lawrence. From benjamin.kaplan at case.edu Sun Aug 8 12:57:59 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 8 Aug 2010 09:57:59 -0700 Subject: Class initialization In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 6:32 AM, Costin Gament wrote: > > Hi there. > I'm kind of a beginner with Python (and programming in general). My > problem is with initializing a class. Let's say I've defined it like > this: > > class foo: > ? a = 0 > ? b = 0 > > and later I'm trying to initialize two different classes like this: > c1 = foo() > c2 = foo() > > The problem I have is that c1 and c2 tend to point to the same > instance, like a weird c-like pointer. Please tell me, what am I doing > wrong? > > Thank you, Python is not C++ or Java. Don't expect it to behave like them. In Python, everything you declare in the class namespace is in the *class* namespace. Since functions are objects too, this works out rather nicely for the most part. Where it doesn't work is when you use mutable variables. Here's the example you wanted to give: class Foo(object): a = [] b= [] Unlike Java or C++, classes are objects too. That leads to one of the neat tricks you can do with Python. The code above is exactly the same thing as this Foo = type("Foo",object, {}) #that dictionary will become Foo's list of attributes Foo.a = [] Foo.b = [] Now, when you call f1 = Foo(), it creates a new object. But here's what happens when you call f1.a.append(1) : * First, Python will look in the attributes of f1 for a. But f1 doesn't have an attribute "a". * So it starts looking up the classes in the inheritance tree. It looks at Foo and finds that Foo does have an attribute "a", so it grabs that. * Then, it looks up the attribute "append" on the a attribute (which is a list), and calls that with the arguments Foo.a and 1. * When f2 = Foo() goes looking for a, it finds the exact same object- Foo.a. It doesn't have its own copy, If you want an object to have its own copy of the variable, you have to create the new copy when the object is created, not when the class is created. That's why you'll see this in most Python programs : class Foo(object) : def __init__(self) : #self is the new object that was just created. #now here we'll assign the attributes on the new object, instead of the class. self.a = [] self.b = [] From torriem at gmail.com Sun Aug 8 13:00:53 2010 From: torriem at gmail.com (Michael Torrie) Date: Sun, 08 Aug 2010 11:00:53 -0600 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: <4C5EE2C5.6050506@gmail.com> On 08/08/2010 10:16 AM, W. eWatson wrote: > See Subject. I use matplotlib, scipy, numpy and possibly one other > module. If I go to the control panel, I only see numpy listed. Why? I > use a search and find only numpy and Python itself. How can matplotlib > and scipy be uninstalled? The best way is probably to find the folders in site-packages that contain these modules and simply delete them. They will be self-contained in folders, so it should be a pretty clean delete. Or you could try just installing the versions you want on top of the existing versions. This should work, even for a downgrade. From drobinow at gmail.com Sun Aug 8 13:21:55 2010 From: drobinow at gmail.com (David Robinow) Date: Sun, 8 Aug 2010 13:21:55 -0400 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence wrote: > On 08/08/2010 17:16, W. eWatson wrote: >> >> See Subject. I use matplotlib, scipy, numpy and possibly one other >> module. If I go to the control panel, I only see numpy listed. Why? I >> use a search and find only numpy and Python itself. How can matplotlib >> and scipy be uninstalled? > > Have you heard of google? google is not relevant to this issue. This group is the correct forum. I'm not sure what the answer to the OP's problem is. If you no longer wish to use these modules I suggest doing nothing. No harm will result. If you want to upgrade just install the new version. If that doesn't work, file a bug report. From hunguponcontent at gmail.com Sun Aug 8 13:24:34 2010 From: hunguponcontent at gmail.com (Default User) Date: Sun, 8 Aug 2010 12:24:34 -0500 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> Message-ID: Not to prolong a good "food fight", but IIRC, many years ago in QBasic, one could choose OPTION BASE 0 or OPTION BASE 1 to make arrays start with element [0] or element [1], respectively. Could such a feature be added to Python without significantly bloating the interpreter? Then, if starting with [0] "works for you", nothing really changes. And if starting with [1] "works for you", then you are not made to feel like a second-class citizen, and about as welcome as a dimwit at the Mensa meeting. Isn't Python supposed to be simple and accessible, and therefore fun? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstrickler at gmail.com Sun Aug 8 13:29:16 2010 From: jstrickler at gmail.com (John S) Date: Sun, 8 Aug 2010 10:29:16 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <2b1da9fc-5c13-4301-8d0d-322eeac715ee@d17g2000yqb.googlegroups.com> On Aug 8, 10:59?am, Thomas Jollans wrote: > On 08/08/2010 04:06 PM, ????? wrote: > > > > > > > On 8 ???, 15:40, Thomas Jollans wrote: > >> On 08/08/2010 01:41 PM, ????? wrote: > > >>> I was so dizzy and confused yesterday that i forgot to metnion that > >>> not only i need removal of php openign and closing tags but whaevers > >>> data lurks inside those tags as well ebcause now with the 'counter.py' > >>> script i wrote the html fiels would open ftm there and substitute the > >>> tempalte variabels like %(counter)d > > >> I could just hand you a solution, but I'll be a bit of a bastard and > >> just give you some hints. > > >> You could use regular expressions. If you know regular expressions, it's > >> relatively trivial - but I doubt you know regexp. > > > Here is the code with some try-and-fail modification i made, still non- > > working based on your hints: > > ========================================================== > > > id = 0 ?# unique page_id > > > for currdir, files, dirs in os.walk('varsa'): > > > ? ? for f in files: > > > ? ? ? ? if f.endswith('php'): > > > ? ? ? ? ? ? # get abs path to filename > > ? ? ? ? ? ? src_f = join(currdir, f) > > > ? ? ? ? ? ? # open php src file > > ? ? ? ? ? ? print 'reading from %s' % src_f > > ? ? ? ? ? ? f = open(src_f, 'r') > > ? ? ? ? ? ? src_data = f.read() ? ? ? ? # read contents of PHP file > > ? ? ? ? ? ? f.close() > > > ? ? ? ? ? ? # replace tags > > ? ? ? ? ? ? print 'replacing php tags and contents within' > > ? ? ? ? ? ? src_data = src_data.replace(r'', '') ? ? ? ? ? ? # > > the dot matches any character i hope! no matter how many of them?!? > > Two problems here: > > str.replace doesn't use regular expressions. You'll have to use the re > module to use regexps. (the re.sub function to be precise) > > '.' ?matches a single character. Any character, but only one. > '.*' matches as many characters as possible. This is not what you want, > since it will match everything between the *first* . > You want non-greedy matching. > > '.*?' is the same thing, without the greed. > > > > > ? ? ? ? ? ? # add ID > > ? ? ? ? ? ? print 'adding unique page_id' > > ? ? ? ? ? ? src_data = ( '' % id ) + src_data > > ? ? ? ? ? ? id += 1 > > > ? ? ? ? ? ? # add template variables > > ? ? ? ? ? ? print 'adding counter template variable' > > ? ? ? ? ? ? src_data = src_data + '''

??????? > > ??????????: %(counter)d

''' > > ? ? ? ? ? ? # i can think of this but the above line must be above > body> NOT after but how to right that?!? > > You will have to find the tag before inserting the string. > str.find should help -- or you could use str.replace and replace the > tag with you counter line, plus a new . > > > > > ? ? ? ? ? ? # rename old php file to new with .html extension > > ? ? ? ? ? ? src_file = src_file.replace('.php', '.html') > > > ? ? ? ? ? ? # open newly created html file for inserting data > > ? ? ? ? ? ? print 'writing to %s' % dest_f > > ? ? ? ? ? ? dest_f = open(src_f, 'w') > > ? ? ? ? ? ? dest_f.write(src_data) ? ? ?# write contents > > ? ? ? ? ? ? dest_f.close() > > > This is the best i can do. > > No it's not. You're just giving up too soon. When replacing text in an HTML document with re.sub, you want to use the re.S (singleline) option; otherwise your pattern won't match when the opening tag is on one line and the closing is on another. From joel.goldstick at columbuswebmakers.com Sun Aug 8 13:31:21 2010 From: joel.goldstick at columbuswebmakers.com (Joel Goldstick) Date: Sun, 08 Aug 2010 13:31:21 -0400 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <4C5EE9E9.10906@columbuswebmakers.com> ? wrote: > Hello dear Pythoneers, > > I have over 500 .php web pages in various subfolders under 'data' > folder that i have to rename to .html and and ditch the '' > tages from within and also insert a very first line of > where id must be an identification unique number of every page for > counter tracking purposes. ONly pure html code must be left. > > I before find otu Python used php and now iam switching to templates + > python solution so i ahve to change each and every page. > > I don't know how to handle such a big data replacing problem and > cannot play with fire because those 500 pages are my cleints pages and > data of those filesjust cannot be messes up. > > Can you provide to me a script please that is able of performing an > automatic way of such a page content replacing? > > Thanks a million! This is quite a vague description of the file contents. But, for a completely different approach, how about using a browser and doing view source, then saving the html that was generated. This will contain no php code, but it will contain the results of whatever the php was doing. If you don't have time to do this manually, look into wget or curl, which will do the job in a program environment. The discussion so far has dealt with stripping php, and leaving the html. But the html must have embeded in it. Or, there could be long fragments of html which are constructed by php and then echo'ed. Joel Goldstick From thomas at jollybox.de Sun Aug 8 13:33:34 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 8 Aug 2010 19:33:34 +0200 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <4C5E1991.9020401@syslang.net> References: <4C5E1991.9020401@syslang.net> Message-ID: <201008081933.34614.thomas@jollybox.de> On Sunday 08 August 2010 04:42:25 Steven W. Orr wrote: > I'm ok in python but I haven't done too much with web pages. I have a web > page that is hand written in html that has about 1000 entries in a table > and I want to convert the table from entries like this > >
> > > > > > > > to > > SomePythonCall('Some Date String', > 'SomeTag', > 'localSubdir', > "http://www.example.com/remote/path/something.html", > 'Click', > 'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? I'm a bit confused about what you're actually asking. If you have a long, HTML file you want to convert to something else (like Python code...), then BeautifulSoup will help you do that - you can use it to parse the original file, and thus make it easier to do the conversion. If your question was "how do I use Python to create web sites": You don't embed Python in HTML. I doubt anybody does this seriously -- Python (with indentation-based scoping) is less well-suited for this than PHP or Ruby, and it's better to keep logic and presentation separate anyway. "The" standard for using Python on the web is WSGI -- it's a very simple, low- level interface between Python and the web server. There are a number of higher-level web frameworks that you might want to look at if your project is sufficiently complex. [1] -- Thomas [1] http://wiki.python.org/moin/WebFrameworks From joel.goldstick at columbuswebmakers.com Sun Aug 8 13:36:28 2010 From: joel.goldstick at columbuswebmakers.com (Joel Goldstick) Date: Sun, 08 Aug 2010 13:36:28 -0400 Subject: I need a starter ptr writing python embedded in html. In-Reply-To: <4C5E1991.9020401@syslang.net> References: <4C5E1991.9020401@syslang.net> Message-ID: <4C5EEB1C.7050607@columbuswebmakers.com> Steven W. Orr wrote: > I'm ok in python but I haven't done too much with web pages. I have a web page > that is hand written in html that has about 1000 entries in a table and I want > to convert the table from entries like this > > > > > > > > > > to > > SomePythonCall('Some Date String', > 'SomeTag', > 'localSubdir', > "http://www.example.com/remote/path/something.html", > 'Click', > 'Some Comment') > > Can someone tell me what I should look at to do this? Is mod_python where I > should start or are there things that are better? > > TIA > > Quickest way to get where you are going is django or another (perhaps smaller) framework. Since you say you are good with python, you could get your website done in a weekend Joel Goldstick From benjamin.kaplan at case.edu Sun Aug 8 13:51:10 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 8 Aug 2010 10:51:10 -0700 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> Message-ID: On Sun, Aug 8, 2010 at 10:24 AM, Default User wrote: > Not to prolong a good "food fight", but IIRC, many years ago in QBasic, > one could choose > > OPTION BASE 0 > > or > > OPTION BASE 1 > > to make arrays start with element [0] or element [1], respectively.? Could > such a feature be added to Python without significantly bloating the > interpreter? > > Then, if starting with [0] "works for you", nothing really changes.? And if > starting with [1] "works for you", then you are not made to feel like a > second-class citizen, and about as welcome as a dimwit at the Mensa > meeting. > > Isn't Python supposed to be simple and accessible, and therefore fun? > Python is also about being readable and consistent. It's going to get really confusing if half the files use 1-based lists and the other half use 0-based. Is it really that hard to get used to indices running from 0 to length-1? Also, good luck getting through life without running into C, C++, C#, Visual Basic, F#, Java, Ruby, Perl, Lisp, or OCaml code. Along with all the languages that use 0-based arrays. From nagle at animats.com Sun Aug 8 13:55:02 2010 From: nagle at animats.com (John Nagle) Date: Sun, 08 Aug 2010 10:55:02 -0700 Subject: urllib "quote" problem Message-ID: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> This warning appeared from urllib.quote: "/usr/local/lib/python2.6/urllib.py:1222: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal res = map(safe_map.__getitem__, s) " Here's urllib.quote from Python 2.6: ==== def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," Each of these characters is reserved in some component of a URL, but not necessarily in all of them. By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode '/'. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters. """ cachekey = (safe, always_safe) try: safe_map = _safemaps[cachekey] except KeyError: safe += always_safe safe_map = {} for i in range(256): c = chr(i) safe_map[c] = (c in safe) and c or ('%%%02X' % i) _safemaps[cachekey] = safe_map res = map(safe_map.__getitem__, s) #### WARNING REPORTED HERE return ''.join(res) ===== I don't, unfortunately, know what went into this call to produce the message; probably a URL in Unicode. This looks like code that will do the wrong thing in Python 2.6 for characters in the range 128-255. Those are illegal in type "str", but this code is constructing such values with "chr". John Nagle From benjamin.kaplan at case.edu Sun Aug 8 13:56:04 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 8 Aug 2010 10:56:04 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 10:21 AM, David Robinow wrote: > On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence wrote: >> On 08/08/2010 17:16, W. eWatson wrote: >>> >>> See Subject. I use matplotlib, scipy, numpy and possibly one other >>> module. If I go to the control panel, I only see numpy listed. Why? I >>> use a search and find only numpy and Python itself. How can matplotlib >>> and scipy be uninstalled? >> >> Have you heard of google? > google is not relevant to this issue. This group is the correct forum. > I'm not sure what the answer to the OP's problem is. If you no longer > wish to use these modules I suggest doing nothing. No harm will > result. Since this is specifically a matplotlib and scipy question, the most relevant forums would be the matplotlib and scipy mailing lists. The maintainers of those projects are probably on those lists, and they'll be able to answer this question better than we can since they know what the installers do in the first place. https://lists.sourceforge.net/lists/listinfo/matplotlib-users http://mail.scipy.org/mailman/listinfo/scipy-user From python at mrabarnett.plus.com Sun Aug 8 14:05:19 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Aug 2010 19:05:19 +0100 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> Message-ID: <4C5EF1DF.3090007@mrabarnett.plus.com> Default User wrote: > Not to prolong a good "food fight", but IIRC, many years ago in QBasic, > one could choose > > OPTION BASE 0 > > or > > OPTION BASE 1 > > to make arrays start with element [0] or element [1], respectively. > Could such a feature be added to Python without significantly bloating > the interpreter? > > Then, if starting with [0] "works for you", nothing really changes. And > if starting with [1] "works for you", then you are not made to feel like > a second-class citizen, and about as welcome as a dimwit at the Mensa > meeting. > If you changed the base then you'd break the standard library, unless everyone altered their code to compensate. It's all part of learning a programming language. Some have 0-based indexing, others have 1-based indexing; some have mutable strings, others have immutable strings, still others don't have 'proper' strings. Just learn to adapt. From python at mrabarnett.plus.com Sun Aug 8 14:16:51 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Aug 2010 19:16:51 +0100 Subject: # of Months between two dates In-Reply-To: References: Message-ID: <4C5EF493.2070508@mrabarnett.plus.com> Greg Lindstrom wrote: > I work for a company that processes claims for the health care industry > (Novasys Health, recently purchased by Centene Corp). My current > assignment has me writing a routine to compute insurance premiums. One > of the requirements is to determine how many months a policy has been in > effect. The datetime module will give me the number of days but, with > months having different lengths, that does not do me much good. I've > looked in the calendar library but didn't see anything there, either. > > I've written a function to return the months between date1 and date2 but > I'd like to know if anyone is aware of anything in the standard library > to do the same? For bonus points, does anyone know if postgres can do > the same (we use a lot of date/time funcitons in postgres, already, but > didn't see this problem addressed). > [snip] A simple expression is: diff = (current_year - start_year) * 12 + (current_month - start_month) According to this, if a policy started on 31 July 2010, then on 1 August 2010 it has been in effect for 1 month. Is this reasonable? It depends! It's probably better to write the function yourself according to what makes sense in your use-case, and document its behaviour clearly. From joel.goldstick at columbuswebmakers.com Sun Aug 8 14:24:50 2010 From: joel.goldstick at columbuswebmakers.com (Joel Goldstick) Date: Sun, 08 Aug 2010 14:24:50 -0400 Subject: # of Months between two dates In-Reply-To: References: Message-ID: <4C5EF672.8010508@columbuswebmakers.com> Greg Lindstrom wrote: > I work for a company that processes claims for the health care industry > (Novasys Health, recently purchased by Centene Corp). My current assignment > has me writing a routine to compute insurance premiums. One of the > requirements is to determine how many months a policy has been in effect. > The datetime module will give me the number of days but, with months having > different lengths, that does not do me much good. I've looked in the > calendar library but didn't see anything there, either. > > I've written a function to return the months between date1 and date2 but I'd > like to know if anyone is aware of anything in the standard library to do > the same? For bonus points, does anyone know if postgres can do the same > (we use a lot of date/time funcitons in postgres, already, but didn't see > this problem addressed). > > On a side note; since I'm dealing with money (USD), I decided to use the > decimal module for all computations. It's not a big difference -- unless > you've seen the movie "Office Space" :-) -- but it sure is nice. Especially > being able to easily round values to the nearest cent. You just have to > love the standard library. > > Thanks for your help, > --greg > > y_diff = present year - start date year m_diff = present month - start date month + (12 * y_diff) From thomas at jollans.com Sun Aug 8 14:47:16 2010 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 08 Aug 2010 20:47:16 +0200 Subject: Python "why" questions In-Reply-To: References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: <4C5EFBB4.9060300@jollans.com> On 2010-08-08 05:18, Dennis Lee Bieber wrote: > Was it this thread where I commented that many early BASICs would > allocate an eleven element array on > > DIM A(10) VB.net does this -- to cater for the classic VB programmer who is used to being able to index the number in brackets, and the .net framework, which uses 0-based indexing (as everything else would look silly in C#, or, especially, in C++/CLI. From costin.gament at gmail.com Sun Aug 8 15:25:15 2010 From: costin.gament at gmail.com (=?UTF-8?Q?Costin_Gamen=C8=9B?=) Date: Sun, 8 Aug 2010 22:25:15 +0300 Subject: Class initialization In-Reply-To: References: Message-ID: Thank you all for your answers and your patience. As soon as I can, I'll update my code and read up on the subject. If I still can't get it working, I'll bother you again. From martin at v.loewis.de Sun Aug 8 15:29:44 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 08 Aug 2010 21:29:44 +0200 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: > Add-Remove would be a very good answer, except for one thing. Understand > that I'm in Win7 so CP takes on a different form. On Control Panel > Add-Remove, I can find exactly two Python files: Python 2.5, and > python-Numpy-1.2.0. No scipy anything. Well, it should be there. Perhaps it was installed by a different user, and will only show up when that user goes into CP? Do you recall what procedure you have used for installation? > Well, this is interesting. I just > noticed Martin v. Loewis on the Python 2.5 entry. That's you, right? Correct. I keep building the installers, but was asked to put Python Software Foundation into the creator field of the MSI file. > I think I posted the errors my partner got above. Let me look. Yes, > here's the copy. > He gets > > Traceback (most recent call last): > File "C:\Documents and > Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", > line 40, in > from scipy import stats as stats # scoreatpercentile > File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, > in > from stats import * > File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, > in > import scipy.special as special > File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line > 22, in > from numpy.testing import NumpyTest > ImportError: cannot import name NumpyTest There is no way this can be attributed to an addition of a single character. In your partner's version of numpy.testing, there is no name NumpyTest. That sounds alright - in my version of numpy, there is no numpy.testing.NumpyTest, either. However, the line in special\__init__.py, on my system, reads from numpy.testing import Tester So it looks like that the scipy version and the numpy version don't match. Regards, Martin From andresen.nils at googlemail.com Sun Aug 8 15:49:22 2010 From: andresen.nils at googlemail.com (Nils) Date: Sun, 8 Aug 2010 12:49:22 -0700 (PDT) Subject: pre-uninstall script in bdist_wininst References: <5063a086-e5a1-49d9-aab2-78011633cfc2@o19g2000yqb.googlegroups.com> Message-ID: <0dd74e88-9043-44bd-910e-1374f3d5de70@v41g2000yqv.googlegroups.com> On 6 Aug., 04:02, Mark Hammond wrote: > According to a comment in pywin32's post-install script: > > ? ? ? ? ?elif arg == "-remove": > ? ? ? ? ? ? ?# bdist_msi calls us before uninstall, so we can undo what we > ? ? ? ? ? ? ?# previously did. ?Sadly, bdist_wininst calls us *after*, so > ? ? ? ? ? ? ?# we can't do much at all. > Sadly, I can not confirm this. I wrote the simplest install-script (dump call-parameters to a txt-file) and tested with 2.6 and 2.7 On bdist_wininst my install_script was called on install with parameter "-install" On bdist_wininst my install_script was called on install without parameters My script was never (ever) called on uninstall... > I'd suggest using py2exe to package the object and inno installer or > similar to handle the install and uninstall parts. Yes, I'll try that, thanks. From tjreedy at udel.edu Sun Aug 8 16:49:40 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 08 Aug 2010 16:49:40 -0400 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> Message-ID: On 8/7/2010 7:53 AM, Peter Otten wrote: > > You mean you'd go for the candidate who took the conservative approach and > got it right: > > print 1 > print 2 > print 'Fizz' > print 4 > print 'Buzz' > print 'Fizz' > print 7 > print 8 > print 'Fizz' > print 'Buzz' Way too verbose. How about print("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n etc. -- Terry Jan Reedy From tjreedy at udel.edu Sun Aug 8 17:04:35 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 08 Aug 2010 17:04:35 -0400 Subject: Smith-Waterman Algorithm in Python In-Reply-To: References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> <4C5D52BE.302@gmaiil.com> Message-ID: On 8/7/2010 1:43 PM, Daniel Fetchinson wrote: >> Every one of the first 20 entries is either the OP questions or your reply. > > And you think it was there before the OP sent his message? > Oh wait, did you just invent a time machine? :) > >> Daniel - you are no help at all, and no funny. > > Actually, I'm damn funny! :) I have noticed before that people who post without searching first end up polluting subsequent searches. Google obviously boosts the rank of recent pages. That is because when people search for something like "Lindsey Lohan", they most likely want the latest news rather than a definitive biography page. -- Terry Jan Reedy From jrmy.lnrd at gmail.com Sun Aug 8 18:20:17 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Sun, 8 Aug 2010 15:20:17 -0700 (PDT) Subject: Regular expression issue Message-ID: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> I am trying to learn regular expressions in python3 and have an issue with one of the examples I'm working with. The code is: #! /usr/bin/env python3 import re search_string = "[^aeiou]y$" print() in_string = 'vacancy' if re.search(search_string, in_string) != None: print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) else: print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) print() in_string = 'boy' if re.search(search_string, in_string) != None: print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) else: print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) print() in_string = 'day' if re.search(search_string, in_string) != None: print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) else: print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) print() in_string = 'pita' if re.search(search_string, in_string) != None: print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) else: print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) print() The output that I am getting is: ay, ey, iy, oy and uy are not at the end of vacancy. ay, ey, iy, oy or uy were found at the end of boy. ay, ey, iy, oy or uy were found at the end of day. ay, ey, iy, oy or uy were found at the end of pita. The last line of the output is the opposite of what I expected to see, and I'm having trouble figuring out what the issue is. Any help would be greatly appreciated. From thomas at jollybox.de Sun Aug 8 18:27:11 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 9 Aug 2010 00:27:11 +0200 Subject: Perl -> Python unpack In-Reply-To: References: Message-ID: <201008090027.12375.thomas@jollybox.de> On Friday 06 August 2010, it occurred to James Mills to exclaim: > Quick question for you Python enthusiasts that also > happen to know Perl quite well... Few and far between ... From thomas at jollybox.de Sun Aug 8 18:32:55 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 9 Aug 2010 00:32:55 +0200 Subject: Regular expression issue In-Reply-To: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <201008090032.55996.thomas@jollybox.de> On Monday 09 August 2010, it occurred to genxtech to exclaim: > I am trying to learn regular expressions in python3 and have an issue > with one of the examples I'm working with. > The code is: > > #! /usr/bin/env python3 > > import re > > search_string = "[^aeiou]y$" To translate this expression to English: a character that is not a, e, i, o, or u, followed by the character 'y', at the end of the line. "vacancy" matches. It ends with "c" (not one of aeiou), followed by "y" "pita" does not match: it does not end with "y". > print() > > in_string = 'vacancy' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of > {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of > {0}.".format(in_string)) > print() > > in_string = 'boy' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of > {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of > {0}.".format(in_string)) > print() > > in_string = 'day' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of > {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of > {0}.".format(in_string)) > print() > > in_string = 'pita' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of > {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of > {0}.".format(in_string)) > print() > > The output that I am getting is: > ay, ey, iy, oy and uy are not at the end of vacancy. > ay, ey, iy, oy or uy were found at the end of boy. > ay, ey, iy, oy or uy were found at the end of day. > ay, ey, iy, oy or uy were found at the end of pita. > > The last line of the output is the opposite of what I expected to see, > and I'm having trouble figuring out what the issue is. Any help would > be greatly appreciated. From python at mrabarnett.plus.com Sun Aug 8 18:50:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Aug 2010 23:50:52 +0100 Subject: Regular expression issue In-Reply-To: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <4C5F34CC.7020709@mrabarnett.plus.com> genxtech wrote: > I am trying to learn regular expressions in python3 and have an issue > with one of the examples I'm working with. > The code is: > > #! /usr/bin/env python3 > > import re > > search_string = "[^aeiou]y$" You can think of this as: a non-vowel followed by a 'y', then the end of the string. > print() > > in_string = 'vacancy' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) Matches because 'c' is a non-vowel, 'y' matches, and then the end of the string. > print() > > in_string = 'boy' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) Doesn't match because 'o' is a vowel, not a non-vowel. > print() > > in_string = 'day' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) Doesn't match because 'a' is a vowel, not a non-vowel. > print() > > in_string = 'pita' > if re.search(search_string, in_string) != None: > print(" ay, ey, iy, oy and uy are not at the end of {0}.".format(in_string)) > else: > print(" ay, ey, iy, oy or uy were found at the end of {0}.".format(in_string)) Doesn't match because 't' is a non-vowel but 'a' doesn't match 'y'. > print() > > The output that I am getting is: > ay, ey, iy, oy and uy are not at the end of vacancy. > ay, ey, iy, oy or uy were found at the end of boy. > ay, ey, iy, oy or uy were found at the end of day. > ay, ey, iy, oy or uy were found at the end of pita. > > The last line of the output is the opposite of what I expected to see, > and I'm having trouble figuring out what the issue is. Any help would > be greatly appreciated. From clp2 at rebertia.com Sun Aug 8 18:55:03 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 8 Aug 2010 15:55:03 -0700 Subject: Regular expression issue In-Reply-To: <201008090032.55996.thomas@jollybox.de> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> <201008090032.55996.thomas@jollybox.de> Message-ID: On Sun, Aug 8, 2010 at 3:32 PM, Thomas Jollans wrote: > On Monday 09 August 2010, it occurred to genxtech to exclaim: >> I am trying to learn regular expressions in python3 and have an issue >> with one of the examples I'm working with. >> The code is: >> >> #! /usr/bin/env python3 >> >> import re >> >> search_string = "[^aeiou]y$" > > To translate this expression to English: > > a character that is not a, e, i, o, or u, followed by the character 'y', at > the end of the line. > > "vacancy" matches. It ends with "c" (not one of aeiou), followed by "y" > > "pita" does not match: it does not end with "y". Or in other words, the regex will not match when: - the string ends in "ay", "ey", "iy", "oy", or "uy" - the string doesn't end in "y" - the string is less than 2 characters long So, the program has a logic error in its assumptions. A non-match *doesn't* imply that a string ends in one of the aforementioned pairs; the other possibilities have been overlooked. May I suggest instead using the much more straightforward `search_string = "[aeiou]y$"` and then swapping your conditions around? The double-negative sort of style the program is currently using is (as you've just experienced) harder to reason about and thus more error-prone. Cheers, Chris -- http://blog.rebertia.com From wolftracks at invalid.com Sun Aug 8 19:15:45 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 08 Aug 2010 16:15:45 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On 8/8/2010 10:56 AM, Benjamin Kaplan wrote: > On Sun, Aug 8, 2010 at 10:21 AM, David Robinow wrote: >> On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence wrote: >>> On 08/08/2010 17:16, W. eWatson wrote: >>>> >>>> See Subject. I use matplotlib, scipy, numpy and possibly one other >>>> module. If I go to the control panel, I only see numpy listed. Why? I >>>> use a search and find only numpy and Python itself. How can matplotlib >>>> and scipy be uninstalled? >>> >>> Have you heard of google? >> google is not relevant to this issue. This group is the correct forum. >> I'm not sure what the answer to the OP's problem is. If you no longer >> wish to use these modules I suggest doing nothing. No harm will >> result. > > Since this is specifically a matplotlib and scipy question, the most > relevant forums would be the matplotlib and scipy mailing lists. The > maintainers of those projects are probably on those lists, and they'll > be able to answer this question better than we can since they know > what the installers do in the first place. > > https://lists.sourceforge.net/lists/listinfo/matplotlib-users > http://mail.scipy.org/mailman/listinfo/scipy-user Well, you have a good point, and I will do that. However, I'm surprised there doesn't seem to be some uniformity on this subject. Yes, removing them directly is an option, but I prefer to find out why the discrepancy? BTW, I really do not plan to remove them now. The anomaly does deserve an answer. To suggest Google as above, makes no sense to me. This is the place to ask, as another poster stated. From benjamin.kaplan at case.edu Sun Aug 8 19:34:37 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 8 Aug 2010 16:34:37 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 4:15 PM, W. eWatson wrote: > On 8/8/2010 10:56 AM, Benjamin Kaplan wrote: >> >> On Sun, Aug 8, 2010 at 10:21 AM, David Robinow ?wrote: >>> >>> On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence >>> ?wrote: >>>> >>>> On 08/08/2010 17:16, W. eWatson wrote: >>>>> >>>>> See Subject. I use matplotlib, scipy, numpy and possibly one other >>>>> module. If I go to the control panel, I only see numpy listed. Why? I >>>>> use a search and find only numpy and Python itself. How can matplotlib >>>>> and scipy be uninstalled? >>>> >>>> Have you heard of google? >>> >>> google is not relevant to this issue. This group is the correct forum. >>> I'm not sure what the answer to the OP's problem is. If you no longer >>> wish to use these modules I suggest doing nothing. No harm will >>> result. >> >> Since this is specifically a matplotlib and scipy question, the most >> relevant forums would be the matplotlib and scipy mailing lists. The >> maintainers of those projects are probably on those lists, and they'll >> be able to answer this question better than we can since they know >> what the installers do in the first place. >> >> https://lists.sourceforge.net/lists/listinfo/matplotlib-users >> http://mail.scipy.org/mailman/listinfo/scipy-user > > Well, you have a good point, and I will do that. However, I'm surprised > there doesn't seem to be some uniformity on this subject. > > Yes, removing them directly is an option, but I prefer to find out why the > discrepancy? BTW, I really do not plan to remove them now. The anomaly does > deserve an answer. > There's a discrepancy because package management on Python is completely broken. Distutils and Setuptools (and it's new fork, Distribute) are inadequate- they act as installers, but don't provide a way to uninstall the program. There are attempts to fix this, such as pip and Activestate's PyPM, but they aren't used as widely as the older methods. > To suggest Google as above, makes no sense to me. This is the place to ask, > as another poster stated. > -- > http://mail.python.org/mailman/listinfo/python-list > From python.list at tim.thechases.com Sun Aug 8 19:34:46 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 08 Aug 2010 18:34:46 -0500 Subject: Regular expression issue In-Reply-To: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <4C5F3F16.3070600@tim.thechases.com> On 08/08/10 17:20, genxtech wrote: > if re.search(search_string, in_string) != None: While the other responses have addressed some of the big issues, it's also good to use if thing_to_test is None: or if thing_to_test is not None: instead of "== None" or "!= None". -tkc From mwilson at the-wire.com Sun Aug 8 19:47:18 2010 From: mwilson at the-wire.com (Mel) Date: Sun, 08 Aug 2010 19:47:18 -0400 Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: Costin Gament wrote: > So you're saying I should just use __init__? Will that get me out of > my predicament? > No, I don't quite understand the difference between my exemple and > using __init__, but I will read the docs about it. Here's the thing about class variables: Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class AClass (object): ... var = 5 ... >>> a = AClass() >>> b = AClass() >>> a.var, b.var (5, 5) >>> AClass.var = 7 >>> a.var, b.var (7, 7) >>> a.var = 9 >>> a.var, b.var (9, 7) >>> a.var is AClass.var False >>> b.var is AClass.var True When `var` is defined as a variable in AClass, it belongs to AClass. But all the instances of AClass are allowed to access it as though it's their own -- it's a sensible way for Python to manage attribute lookup. Assigning to AClass.var changes the value as seen by all the instances. Assigning to a.var creates a new variable in instance a's namespace, and from then on that becomes the value that will be found by looking up a.var . The `is` test shows that this is true. Mel. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 20:17:32 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 00:17:32 GMT Subject: Class initialization References: <95C418CF-4F6E-457E-AF18-3B41011D08C7@gmail.com> Message-ID: <4c5f491c$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 19:47:18 -0400, Mel wrote: > Costin Gament wrote: > >> So you're saying I should just use __init__? Will that get me out of my >> predicament? >> No, I don't quite understand the difference between my exemple and >> using __init__, but I will read the docs about it. > > Here's the thing about class variables: [snip example] No, that's actually the thing about class *attributes*. This is Python, not Java or whatever language you're used to that uses such bizarrely inconsistent terminology. A variable holding an int is an int variable. A variable holding a string is a string variable. A variable holding a float is a float variable. And a variable holding a class is a class variable. Given a class: class MyClass: attribute = None MyClass is a perfectly normal variable, like any other variable you create in Python. You can reassign to it, you can pass it to functions, it has an object bound to it. In other words, it's a class variable in the same way that n = 2 creates an int variable. (Although of course because Python has dynamic typing, n is only an int until it gets rebound to something which isn't an int. Likewise MyClass is only a class until it gets rebound to something else.) That's why Python has builtin functions getattr, setattr and hasattr rather than getvar, setvar and hasvar. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 20:26:23 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 00:26:23 GMT Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? References: Message-ID: <4c5f4b2f$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 13:21:55 -0400, David Robinow wrote: > On Sun, Aug 8, 2010 at 12:51 PM, Mark Lawrence > wrote: >> On 08/08/2010 17:16, W. eWatson wrote: >>> >>> See Subject. I use matplotlib, scipy, numpy and possibly one other >>> module. If I go to the control panel, I only see numpy listed. Why? I >>> use a search and find only numpy and Python itself. How can matplotlib >>> and scipy be uninstalled? >> >> Have you heard of google? > google is not relevant to this issue. This group is the correct forum. I would have thought that people who hang around dedicated forums for matplotlib and scipy would probably have more knowledge about the workings of the matplotlib and scipy installers than generic Python programmers, most of whom have never touched or used matplotlib or scipy. > I'm not sure what the answer to the OP's problem is. Oh the irony. -- Steven From peter.milliken at gmail.com Sun Aug 8 20:28:59 2010 From: peter.milliken at gmail.com (Peter) Date: Sun, 8 Aug 2010 17:28:59 -0700 (PDT) Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> On Aug 9, 6:49?am, Terry Reedy wrote: > On 8/7/2010 7:53 AM, Peter Otten wrote: > > > > > You mean you'd go for the candidate who took the conservative approach and > > got it right: > > > print 1 > > print 2 > > print 'Fizz' > > print 4 > > print 'Buzz' > > print 'Fizz' > > print 7 > > print 8 > > print 'Fizz' > > print 'Buzz' > > Way too verbose. How about > print("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n > etc. > > -- > Terry Jan Reedy And to hell with the code being maintainable afterwards? :-) Personally I would FIRE somebody who produced code like this. Assuming I was a manager or in a position to hire (I used to be in a previous life), then I would be looking for somebody who was capable of writing good, solid and MAINTAINABLE code (love those subjective words? :-)). Realistically, if the application is anything other than trivial then it will most likely have somebody poking around in it at some stage who isn't the brightest spark in the firmament. Anybody who produces nice, readable and straight forward code in my books gets the tick of approval. No offence intended, but anybody who tried to prove how "bright" they are by producing the least number of (unmaintainable) lines of code would not get past the first interview - unless they were prepared to sign a contract that guaranteed they would be available to maintain the application for its entire lifecycle. Generally (in my experience) people who write code like this don't hang around long - certainly not long enough to maintain their monstrosity! Peter From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 20:39:31 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 00:39:31 GMT Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> Message-ID: <4c5f4e42$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 17:28:59 -0700, Peter wrote: > On Aug 9, 6:49?am, Terry Reedy wrote: >> On 8/7/2010 7:53 AM, Peter Otten wrote: >> >> > You mean you'd go for the candidate who took the conservative >> > approach and got it right: >> >> > print 1 >> > print 2 >> > print 'Fizz' >> > print 4 >> > print 'Buzz' >> > print 'Fizz' >> > print 7 >> > print 8 >> > print 'Fizz' >> > print 'Buzz' >> >> Way too verbose. How about >> print("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n etc. >> >> -- >> Terry Jan Reedy > > And to hell with the code being maintainable afterwards? :-) I'm pretty sure both Peter Otten and Terry Reedy were being sarcastic and/ or ironic. -- Steven From rantingrick at gmail.com Sun Aug 8 20:43:03 2010 From: rantingrick at gmail.com (rantingrick) Date: Sun, 8 Aug 2010 17:43:03 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! Message-ID: Hello folks, You all know i been forced to use Ruby and i am not happy about that. But i thought i would share more compelling evidence of the moronicity of the Ruby language syntax from the perspective of regexp's. I recently built myself a nice little Ruby script editor because i hate everything else out there. Whist writing the Colorizer i realized (again) just how beautifully elegant Python is and how crufty and asinine Ruby is. Anyhow my point is that by looking at the regexp's you can clearly see that parsing Ruby syntax is BF and Python syntax is elegant! Here are a few examples: Note i used look back assertions for clarity. -------------------- Modules -------------------- Python does not have a module syntax (an thank Guido for that!) because we have a much better system of using the file as a module and not introducing more cruft into our scripts. Anyway if Python *did* have a module syntax it would look better than this crap! Python: N/A Ruby: r'(?<=module )(::)?(\w+(::)?)*' -------------------- Classes -------------------- Python and Ruby class definitions are almost the same except for the module cruft getting in the way again. Python: r'(?<=class )\w+' Ruby: r'(?<=class )(::)?(\w+(::)?)*' --------------------- Defs --------------------- HaHa, you're going to poop yourself when you see this! No introduction needed :-D. Python: r'(?<=def )\w+' Ruby: r'(?<=def )(self\.)?((\w+::\w+)|(\w+\.\w+)|(\w+))([?|!])?' --------------------- Strings --------------------- Single line strings are exactly the same in both languages except in Ruby double quoted strings are backslash interpreted and single quote strings are basically raw. Except Ruby introduces more cruft (as usual) in the form of what i call "lazy man" stings.... >>> a = %w{ one two three} ["one", "two", "three"] >>> s = %{one two three} one two three >>> repat = %r{one two three} /one two three/ ... only good for hand coding! ---------------------- Multi Line Strings ---------------------- Ha. Ruby does not really have multi line strings. Ruby has what they call a "Here Doc". Besides picking the most boneheaded name for such an object they also introduced and even more boneheaded syntax. To define a "Here Doc" (god i hate that name!) you start with double greater than ">>" and immediately follow with an identifier token of you choice (it can be anything your dirty little mind can come up with. >>HEREDOC this is the body of a here doc. Why the hell did they not just use triple quotes like Python did. Now i will need to remember some token to know where' i stopped HEREDOC As you can see it is another example of tacked on functionality that was not carefully considered before hand. Anyway here are the regexp's... Python: r'""".*?"""' Python: r"'''.*?'''" Ruby: r'<<(\w+).*?(\1)' -------------------------- Comments -------------------------- Ruby and Python single line comments are the same. Use the hash char. However Ruby introduces multi line comment blocks delimited by the tokens "=begin" and "=end". Python: r"#.*" Ruby: r"=begin.*?=end" Ruby: r"#.*" ------------------------- Conculsion ------------------------- I just want to take this opportunity to thank Mr. Van Rossum and the Python dev team for creating a truly revolutionary 21st century language that no other language can hold a candle to. Without Python we would be force to use these "other" monstrosities" on a daily basis -- and i just don't think i could bear it! Keep up the good work! From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 20:51:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 00:51:42 GMT Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? References: Message-ID: <4c5f511d$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 16:15:45 -0700, W. eWatson wrote: > To suggest Google as above, makes no sense to me. This is the place to > ask, as another poster stated. He may have stated it, but the evidence suggests he's wrong. You're asking a question about the details of the installers used specifically by scipy and matplotlib. Most people here have no idea about that, hence the lack of useful answers. The best likelihood of finding a solution is to go to a specialist forum, not a generic one. In any case, suggesting Google is *always* relevant. You gave us no reason at all to think that you had made any effort to solve the problem yourself before asking for us to volunteer our time. That's rude. Did you google for "uninstall scipy" before asking for help? Did you make any effort to read the Scipy manual first? Did you make any effort *at all*? If you had -- and for all we know, you might have spent days trying to solve this, or 3 seconds, or anything in between -- you didn't say so. Suggesting that you do some googling is absolutely relevant. Perhaps it's about time that we point you at this: http://catb.org/esr/faqs/smart-questions.html I don't agree with everything the author says, but the basic position is about right. -- Steven From roy at panix.com Sun Aug 8 21:01:46 2010 From: roy at panix.com (Roy Smith) Date: Sun, 08 Aug 2010 21:01:46 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> Message-ID: In article <388041a0-4bc5-4f65-bae3-d516fb90f57f at l25g2000prn.googlegroups.com>, Peter wrote: > Realistically, if the application is anything other than trivial then > it will most likely have somebody poking around in it at some stage > who isn't the brightest spark in the firmament. Anybody who produces > nice, readable and straight forward code in my books gets the tick of > approval. What he said. The first test of good code is that you can understand what you wrote six months after you wrote it. The second test is that you can explain it to some junior programmer a couple of cubes away from you, two or three years after you wrote it. The ultimate test is that some poor schmuck, long after you've moved on to another project (or company), can figure out what the heck you wrote, ten years later. And, oh, yeah, the junior programmer who you explained it to in the previous paragraph, may be 9 or 12 time zones away from the team who is currently maintaining your code, if he's around at all. From python at mrabarnett.plus.com Sun Aug 8 21:14:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 02:14:18 +0100 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: References: Message-ID: <4C5F566A.2000704@mrabarnett.plus.com> rantingrick wrote: > Hello folks, > [snip] > --------------------- > Strings > --------------------- > Single line strings are exactly the same in both languages except in > Ruby double quoted strings are backslash interpreted and single quote > strings are basically raw. Except Ruby introduces more cruft (as > usual) in the form of what i call "lazy man" stings.... > >>>> a = %w{ one two three} > ["one", "two", "three"] >>>> s = %{one two three} > one two three >>>> repat = %r{one two three} > /one two three/ > > ... only good for hand coding! > From Perl. > ---------------------- > Multi Line Strings > ---------------------- > Ha. Ruby does not really have multi line strings. Ruby has what they > call a "Here Doc". Besides picking the most boneheaded name for such > an object they also introduced and even more boneheaded syntax. To > define a "Here Doc" (god i hate that name!) you start with double > greater than ">>" and immediately follow with an identifier token of > you choice (it can be anything your dirty little mind can come up > with. > >>> HEREDOC > this is the body > of a > here doc. Why the > hell did they not just > use triple quotes like Python did. > Now i will need to remember some token to know where' > i stopped > HEREDOC > > As you can see it is another example of tacked on functionality that > was not carefully considered before hand. Anyway here are the > regexp's... > > Python: r'""".*?"""' > Python: r"'''.*?'''" > Ruby: r'<<(\w+).*?(\1)' > Also from Perl. I don't know what the point of your post was. We already know that we prefer Python; that's why we're here! :-) And anyway, being nasty about other languages feels unPythonic to me... From steve at REMOVE-THIS-cybersource.com.au Sun Aug 8 21:15:00 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 01:15:00 GMT Subject: Python -Vs- Ruby: A regexp match to the death! References: Message-ID: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> On Sun, 08 Aug 2010 17:43:03 -0700, rantingrick wrote: > Ha. Ruby does not really have multi line strings. Except, of course, it does, as you go on to show. > Ruby has what they > call a "Here Doc". Besides picking the most boneheaded name for such an > object It's standard terminology that has been around for a long time in many different languages. http://en.wikipedia.org/wiki/Here_document > they also introduced and even more boneheaded syntax. To define a > "Here Doc" (god i hate that name!) you start with double greater than > ">>" and immediately follow with an identifier token of you choice (it > can be anything your dirty little mind can come up with. > >>>HEREDOC > this is the body > of a > here doc. Why the > hell did they not just > use triple quotes like Python did. > Now i will need to remember some token to know where' i stopped > HEREDOC Incorrect. [steve at sylar ~]$ irb irb(main):001:0> s = >>END SyntaxError: compile error (irb):1: syntax error s = >>END ^ from (irb):1 irb(main):002:0> s = <<-END irb(main):003:0" Multi-line text irb(main):004:0" goes here irb(main):005:0" END => "Multi-line text\ngoes here\n" irb(main):006:0> puts s Multi-line text goes here => nil irb(main):007:0> > As you can see it is another example of tacked on functionality that was > not carefully considered before hand. I disagree. It's an old and venerable technique, and very useful on the rare occasion that you have lots of quotation marks in a string. Whether those rare occasions are common enough to require specialist syntax is another question. In Python, the idea is that two heredocs (''' and """) is enough for anybody. That makes it difficult to write a string literal like, e.g.: Python strings have four delimiters: (1) single quote ' (2) double quote " (3) single-quote here-doc ''' (4) double-quote here-doc """ plus equivalent raw-strings of each kind. Trying writing that as a single literal in Python without escapes. There are work-arounds, of course, like using implicit concatenation, but they're ugly. In Ruby they decided to be more general, so you can define whatever heredoc you need to quote whatever literal string you need. That's not bone-headed. -- Steven From wuwei23 at gmail.com Sun Aug 8 21:32:50 2010 From: wuwei23 at gmail.com (alex23) Date: Sun, 8 Aug 2010 18:32:50 -0700 (PDT) Subject: Python Portability References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: <7cfbef6a-916c-4215-937a-2e724ab6c534@z30g2000prg.googlegroups.com> "W. eWatson" wrote: > I now have the answer I need, and I do not care one more wit > about a one character change. > > I'm done here. That's a fantastic response to give to people who were actually willing to sacrifice their time to help you with your problems. I'm always stunned at those who come here in ignorance somehow "knowing" what the correct answer they wanted is, even when it runs counter to responses from far more experienced people. Good luck continuing to get help here with that attitude. From ranjithtenz at gmail.com Sun Aug 8 22:16:11 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Mon, 9 Aug 2010 07:46:11 +0530 Subject: Need a mentor Message-ID: Hi all, I`m doing a python based project, I need a mentor who can guide me and help me to complete the project. the idea is fully based upon application programming. What I want is just suggest me how to implement so that I write the code and send it back to you. And there you can check the codes and find the better solution or giving me some other ideas so that we can optimize the code and bring a better solution. I`m glad to work on python if anyone interested in this please kindly let me know it. Awaiting for your reply. -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter.milliken at gmail.com Sun Aug 8 22:16:17 2010 From: peter.milliken at gmail.com (Peter) Date: Sun, 8 Aug 2010 19:16:17 -0700 (PDT) Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> <4c5f4e42$0$28663$c3e8da3@news.astraweb.com> Message-ID: On Aug 9, 10:39?am, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 17:28:59 -0700, Peter wrote: > > On Aug 9, 6:49?am, Terry Reedy wrote: > >> On 8/7/2010 7:53 AM, Peter Otten wrote: > > >> > You mean you'd go for the candidate who took the conservative > >> > approach and got it right: > > >> > print 1 > >> > print 2 > >> > print 'Fizz' > >> > print 4 > >> > print 'Buzz' > >> > print 'Fizz' > >> > print 7 > >> > print 8 > >> > print 'Fizz' > >> > print 'Buzz' > > >> Way too verbose. How about > >> print("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n etc. > > >> -- > >> Terry Jan Reedy > > > And to hell with the code being maintainable afterwards? :-) > > I'm pretty sure both Peter Otten and Terry Reedy were being sarcastic and/ > or ironic. > > -- > Steven I'm sure you're right - and I repeat that I meant no offense. My comments were intended in the spirit of what to do or do not do in an interview for (any) programming job. Peter and Terry just offered some good examples of what you don't want to do (IMO) :-) So, I apologise if anybody has taken my comments as a slur on Peter and/or Terry's posts - they were not intended as such. Peter From georgeolivergo at gmail.com Sun Aug 8 22:46:08 2010 From: georgeolivergo at gmail.com (George Oliver) Date: Sun, 8 Aug 2010 19:46:08 -0700 (PDT) Subject: requirements in writing an email/rss/usenet client? Message-ID: hi, I'd like to know what to consider when writing an email/rss/usenet client. Apologies for such a broad question, but I've never attempted a project of this scope and I'm currently feeling out the requirements. My target is something like a gui-based mutt (I use a Windows OS btw), with influences from programs like Alpine (http://www.washington.edu/ alpine/) and Sup (http://sup.rubyforge.org/). I currently use Thunderbird + Muttator, which is a nice setup; but, it has some clunky parts, and I thought it might be simpler in the end to start fresh than try to engage with what seems to be the massive-ness of Thunderbird (of course, I may be disabused of this notion at some point ;) ). So far I've looked at the email and related modules in the standard lib, found some related links from the list [1], and read a little about the relevant protocols involved. I'd appreciate hearing about any other examples, references, or experiences of people who've written similar programs or related libraries. thanks, George [1] Including references to: * http://sourceforge.net/projects/usablemail/ * http://proquest.safaribooksonline.com/0596000855/python2-CHP-11-SECT-4 * http://wiki.laptop.org/go/Email * the pyne client * http://chandler.osafoundation.org/ From sushma.konanki at gmail.com Mon Aug 9 00:25:29 2010 From: sushma.konanki at gmail.com (sushma) Date: Sun, 8 Aug 2010 21:25:29 -0700 (PDT) Subject: urgent requirement Message-ID: <19ff72d0-8e2a-4ad5-9b7f-bca2b6466541@z34g2000pro.googlegroups.com> We have an urgent requirement for people who are having experience in python. If you are interested for this position forward your updated resume to the sushmak at millenniumsoft.com with the details mention below; current ctc: expected ctc: notice period: regards, sushma. www.millenniumsoft.com From wolftracks at invalid.com Mon Aug 9 00:54:42 2010 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 08 Aug 2010 21:54:42 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: <4c5f511d$0$28663$c3e8da3@news.astraweb.com> References: <4c5f511d$0$28663$c3e8da3@news.astraweb.com> Message-ID: On 8/8/2010 5:51 PM, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 16:15:45 -0700, W. eWatson wrote: > >> To suggest Google as above, makes no sense to me. This is the place to >> ask, as another poster stated. > > He may have stated it, but the evidence suggests he's wrong. You're > asking a question about the details of the installers used specifically > by scipy and matplotlib. Most people here have no idea about that, hence > the lack of useful answers. The best likelihood of finding a solution is > to go to a specialist forum, not a generic one. > > In any case, suggesting Google is *always* relevant. You gave us no > reason at all to think that you had made any effort to solve the problem > yourself before asking for us to volunteer our time. That's rude. Did you > google for "uninstall scipy" before asking for help? Did you make any > effort to read the Scipy manual first? Did you make any effort *at all*? > If you had -- and for all we know, you might have spent days trying to > solve this, or 3 seconds, or anything in between -- you didn't say so. > > Suggesting that you do some googling is absolutely relevant. > > Perhaps it's about time that we point you at this: > > http://catb.org/esr/faqs/smart-questions.html > > I don't agree with everything the author says, but the basic position is > about right. > > > For the last few hours, I've been on the scipy and numpy mail list, per a suggestion. No one seems to really understand uninstall there. I think Ben Caplan may have it right. You and I need go no further with this. We disagree--again. From shambhu.1980 at gmail.com Mon Aug 9 00:57:30 2010 From: shambhu.1980 at gmail.com (Shambhu) Date: Sun, 8 Aug 2010 21:57:30 -0700 (PDT) Subject: os.unlink on Windows References: <4c5eb146$0$28663$c3e8da3@news.astraweb.com> Message-ID: Hi Thomas, Steven, Thanks for explanation. It is working now after using double backslash in pathname. I was misinterpreting the display output and thinking that it was being added by 'os' module. Regards, Shambhu. T On Aug 8, 6:29?pm, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 04:41:14 -0700, Shambhu wrote: > > Hi Thomas, > > > ? ? ? ? ? ?I checked, file is present. Here is my sample script: > > import os > > filename = "C:\SHAMBHU\tmp\text_delete.txt" > > Did you intend to provide a filename with two TAB characters in it? > > c colon backslash s h a m b u TAB m p TAB e x t underscore d e l e t e > dot t x t > > > File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\ > > \tmp\\text_delete.txt" is not (with extra backslash in path which is > > added by os.unlink). > > os.unlink does add any extra backslashes. You are misinterpreting what > you are seeing. > > -- > Steven From tjreedy at udel.edu Mon Aug 9 01:11:59 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 01:11:59 -0400 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> <388041a0-4bc5-4f65-bae3-d516fb90f57f@l25g2000prn.googlegroups.com> <4c5f4e42$0$28663$c3e8da3@news.astraweb.com> Message-ID: On 8/8/2010 10:16 PM, Peter wrote: >> I'm pretty sure both Peter Otten and Terry Reedy were being sarcastic and/ >> or ironic. About the most I ever am ;=)! > I'm sure you're right - and I repeat that I meant no offense. > > My comments were intended in the spirit of what to do or do not do in > an interview for (any) programming job. Peter and Terry just offered > some good examples of what you don't want to do (IMO) :-) > > So, I apologise if anybody has taken my comments as a slur on Peter > and/or Terry's posts - they were not intended as such. I was not sure if you were taking me seriously or not, but rather than be insulted, I am delighted that I gave you an opportunity to both get something off your chest and say something worthwhile. When I was hired in part to maintain and extend someone else's work, it was in pretty good shape and the outgoing person, with more experience than me, gave me a quick head's about about it. But I realize that many others have been less fortunate, but of course cannot throw a fit in their new place of employment, as appropriate as it might seem. -- Terry Jan Reedy From nagle at animats.com Mon Aug 9 01:50:56 2010 From: nagle at animats.com (John Nagle) Date: Sun, 08 Aug 2010 22:50:56 -0700 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: <4c5f9748$0$1657$742ec2ed@news.sonic.net> On 8/8/2010 9:51 AM, Mark Lawrence wrote: > On 08/08/2010 17:16, W. eWatson wrote: >> See Subject. I use matplotlib, scipy, numpy and possibly one other >> module. If I go to the control panel, I only see numpy listed. Why? I >> use a search and find only numpy and Python itself. How can matplotlib >> and scipy be uninstalled? > > Have you heard of google? > > Mark Lawrence. It's a legitimate question. It might be framed as "why does Python package management not play well with the platform's package management system?" Which is a reasonable enough question. On Windows, some packages play well with Add/Remove programs, and some don't. On Linux, some packages play well with Yum, and some don't. The basic answer is that nobody is in charge. There's nobody even trying to herd the third-party modules. Unlike CPAN, which has standards for Perl packages and some level of quality control, PyPi is just a link farm. John Nagle From martin at v.loewis.de Mon Aug 9 01:59:06 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 09 Aug 2010 07:59:06 +0200 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: References: Message-ID: <4C5F992A.4040606@v.loewis.de> > There's a discrepancy because package management on Python is > completely broken. Distutils and Setuptools (and it's new fork, > Distribute) are inadequate- they act as installers, but don't provide > a way to uninstall the program. That's not true. If you use the bdist_wininst, bdist_msi, or bdist_rpm distutils commands, you get packages which support uninstallations very well. Regards, Martin From martin at v.loewis.de Mon Aug 9 02:01:06 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 09 Aug 2010 08:01:06 +0200 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? In-Reply-To: <4c5f9748$0$1657$742ec2ed@news.sonic.net> References: <4c5f9748$0$1657$742ec2ed@news.sonic.net> Message-ID: <4C5F99A2.9070309@v.loewis.de> > The basic answer is that nobody is in charge. There's nobody > even trying to herd the third-party modules. Unlike CPAN, which > has standards for Perl packages and some level of quality > control, PyPi is just a link farm. Do the standards of CPAN also include uninstallation? To my knowledge, they don't: so how does it help to have standards, wrt. to the OP's question? Regards, Martin From cjgohlke at gmail.com Mon Aug 9 02:30:46 2010 From: cjgohlke at gmail.com (Christoph Gohlke) Date: Sun, 8 Aug 2010 23:30:46 -0700 (PDT) Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? References: <4c5f511d$0$28663$c3e8da3@news.astraweb.com> Message-ID: <8135936c-9b50-4c04-afb7-46a564b24e62@b4g2000pra.googlegroups.com> On Aug 8, 9:54?pm, "W. eWatson" wrote: > On 8/8/2010 5:51 PM, Steven D'Aprano wrote: > > > On Sun, 08 Aug 2010 16:15:45 -0700, W. eWatson wrote: > > >> To suggest Google as above, makes no sense to me. This is the place to > >> ask, as another poster stated. > > > He may have stated it, but the evidence suggests he's wrong. You're > > asking a question about the details of the installers used specifically > > by scipy andmatplotlib. Most people here have no idea about that, hence > > the lack of useful answers. The best likelihood of finding a solution is > > to go to a specialist forum, not a generic one. > > > In any case, suggesting Google is *always* relevant. You gave us no > > reason at all to think that you had made any effort to solve the problem > > yourself before asking for us to volunteer our time. That's rude. Did you > > google for "uninstall scipy" before asking for help? Did you make any > > effort to read the Scipy manual first? Did you make any effort *at all*? > > If you had -- and for all we know, you might have spent days trying to > > solve this, or 3 seconds, or anything in between -- you didn't say so. > > > Suggesting that you do some googling is absolutely relevant. > > > Perhaps it's about time that we point you at this: > > >http://catb.org/esr/faqs/smart-questions.html > > > Idon'tagree with everything the author says, but the basic position is > > about right. > > For the last few hours, I've been on the scipy and numpy mail list, per > a suggestion. No one seems to really understand uninstall there. Well. Your question has been answered on Numpy-discussion in February and again today on SciPy-users. > I think > Ben Caplan may have it right. You and I need go no further with this. We > disagree--again. From ranjithtenz at gmail.com Mon Aug 9 02:31:26 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Mon, 9 Aug 2010 12:01:26 +0530 Subject: Need mentor Message-ID: Hi all, I have described the theme of my project here, When the script is runned a configuring window has to be displayed where the user has to configure for there desired Web Browser, Audio Player, Video Player, Text Editor (Each Specified in separate SS Tab). Here the script should retrieve all installed Web Browser, Audio Player, Video Player and Text Editor and categorized and displayed in their corresponding tab`s. Here the user has to choose and set their preferred Web Browser, Video Player, Audio Player, Text Editor and update the configure file. note 1: configuring window should run automatically only first if the user wants to reconfigure the file again they should run configuring module alone note 2: This script is to start it on every login and stay running on background until i shut download the machine. For an example, this is complete real time behavior of the script. Let us consider I`m the user I downloaded the script and runned it, It should check for a configuring file if there is no configure file is created means it should automatically create a new configure file and displays a configuring window in that window I will be offered by whatever the web browsers, audio player, video player, text editor installed on my machine will has to be shown to me in their corresponding tab`s I have to set my desired web browser if I choose chrome has my prefered web browser and whenever I press the key "w" on desktop screen the chrome browser should be opened, I have to set my desired Audio player if I choose exaile has my preferred audio player and whenever I press the key "a" on desktop screen the Exaile audio player should be opened,I have to set my desired video player if I choose vlc has my prefered video player and whenever I press the key "v" on desktop screen the vlc player should be opened, I have to set my desired text editor if I choose gedit has my prefered text editor and whenever I press the key "t" on desktop screen the Gedit text editor should be opened, this just like creating hotkeys and all these configured details should be updated when I click on apply and exits the configuring windows and runs the script at the desktop background while i`m in desktop when i just hit "w" chrome browser should opened -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Mon Aug 9 02:31:57 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 8 Aug 2010 23:31:57 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> On 8 ???, 17:59, Thomas Jollans wrote: > Two problems here: > > str.replace doesn't use regular expressions. You'll have to use the re > module to use regexps. (the re.sub function to be precise) > > '.' ?matches a single character. Any character, but only one. > '.*' matches as many characters as possible. This is not what you want, > since it will match everything between the *first* . > You want non-greedy matching. > > '.*?' is the same thing, without the greed. Thanks you, So i guess this needs to be written as: src_data = re.sub( '', '', src_data ) Tha 'r' special char doesn't need to be inserter before the regex here due to regex ain't containing backslashes. > You will have to find the tag before inserting the string. > str.find should help -- or you could use str.replace and replace the > tag with you counter line, plus a new . Ah yes! Damn why din't i think of it.... str.replace should do the trick. I was stuck trying to figure regexes. So, i guess that should work: src_data = src_data.replace('', '

??????? ??????????: %(counter)d

' ) > No it's not. You're just giving up too soon. Yes youa re right, your hints keep me going and thank you for that. From israelu at elbit.co.il Mon Aug 9 02:50:06 2010 From: israelu at elbit.co.il (iu2) Date: Sun, 8 Aug 2010 23:50:06 -0700 (PDT) Subject: xmlrpc and processes Message-ID: <3ec02745-4982-4f9e-955f-b771cdd64e19@d8g2000yqf.googlegroups.com> Hi, I have a SimpleXMLRPCServer running on one PC. I need several ServerProxy-s talking to it, each one running on a different PC. That is, I run on each PC a client application, that talks to the one server using xml-rpc. Is the xml-rpc designed to work like this? If not, is there something I can do to still be able to work with xml-rpc in this architucture? Thank you very much From pavlovevidence at gmail.com Mon Aug 9 02:53:41 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 8 Aug 2010 23:53:41 -0700 (PDT) Subject: urgent requirement References: <19ff72d0-8e2a-4ad5-9b7f-bca2b6466541@z34g2000pro.googlegroups.com> Message-ID: <156761d4-4c6d-4583-904e-15f720365177@u4g2000prn.googlegroups.com> On Aug 8, 9:25?pm, sushma wrote: > ? We have an urgent requirement for people who are having experience > in python. ?If you are interested for this position forward your > updated resume to the sush... at millenniumsoft.com with the details > mention below; > > current ctc: > expected ctc: > notice period: #1: You should post this on the Python jobs board. http://www.python.org/community/jobs/ #2: I know the economy's bad but not everyone is going to apply to every job posting they see. You should include a least a little information about the job. Carl Banks From ldo at geek-central.gen.new_zealand Mon Aug 9 02:57:51 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Aug 2010 18:57:51 +1200 Subject: Python Portability References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: In message , W. eWatson wrote: > Believe me I had no intent of expanding this thread beyond looking for a > straight and simple insight to Python distribution (portability, > whatever) and how to get my partner squared away. The general issue > seems to drifted off on its own accord. ?Drifted off? bullshit. A whole lot of responders have wasted a whole lot of time trying to get to the bottom of your ?one-character change?, and now you try to pretend it wasn?t the issue at all. From nikos.the.gr33k at gmail.com Mon Aug 9 03:07:22 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 00:07:22 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: Now the code looks as follows: ============================= #!/usr/bin/python import re, os, sys id = 0 # unique page_id for currdir, files, dirs in os.walk('test'): for f in files: if f.endswith('php'): # get abs path to filename src_f = join(currdir, f) # open php src file print ( 'reading from %s' % src_f ) f = open(src_f, 'r') src_data = f.read() # read contents of PHP file f.close() # replace tags print ( 'replacing php tags and contents within' ) src_data = re.sub( '', '', src_data ) # add ID print ( 'adding unique page_id' ) src_data = ( '' % id ) + src_data id += 1 # add template variables print ( 'adding counter template variable' ) src_data = src_data.replace('', '

??????? ??????????: %(counter)d ' ) # rename old php file to new with .html extension src_file = src_file.replace('.php', '.html') # open newly created html file for inserting data print ( 'writing to %s' % dest_f ) dest_f = open(src_f, 'w') dest_f.write(src_data) # write contents dest_f.close() I just tried to test it. I created a folder names 'test' in me 'd:\' drive. Then i have put to .php files inside form the original to test if it would work ok for those too files before acting in the whole copy and after in the original project. so i opened a 'cli' form my Win7 and tried D:\>convert.py D:\> Itsjust printed an empty line and nothign else. Why didn't even try to open the folder and fiels within? Syntactically it doesnt ghive me an error! Somehting with os.walk() methos perhaps? From debatem1 at gmail.com Mon Aug 9 03:12:37 2010 From: debatem1 at gmail.com (geremy condra) Date: Mon, 9 Aug 2010 00:12:37 -0700 Subject: Python Portability In-Reply-To: References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On Sun, Aug 8, 2010 at 11:57 PM, Lawrence D'Oliveiro wrote: > In message , W. eWatson wrote: > >> Believe me I had no intent of expanding this thread beyond looking for a >> straight and simple insight to Python distribution (portability, >> whatever) and how to get my partner squared away. The general issue >> seems to drifted off on its own accord. > > ?Drifted off? bullshit. A whole lot of responders have wasted a whole lot of > time trying to get to the bottom of your ?one-character change?, and now you > try to pretend it wasn?t the issue at all. To be fair, it wasn't, little though he knew it. Geremy Condra From rantingrick at gmail.com Mon Aug 9 03:29:19 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 9 Aug 2010 00:29:19 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> Message-ID: <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> On Aug 8, 8:15?pm, Steven D'Aprano wrote: > In Ruby they decided to be more general, so you can define whatever > heredoc you need to quote whatever literal string you need. That's not > bone-headed. Devils Advocate! PS: Man you're irb main was so full of cobweb i could barley see the code... haa... haaaa... hachew!. ;-) From __peter__ at web.de Mon Aug 9 03:38:34 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 09:38:34 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: ????? wrote: > Now the code looks as follows: > for currdir, files, dirs in os.walk('test'): > > for f in files: > > if f.endswith('php'): > > # get abs path to filename > src_f = join(currdir, f) > I just tried to test it. I created a folder names 'test' in me 'd:\' > drive. > Then i have put to .php files inside form the original to test if it > would work ok for those too files before acting in the whole copy and > after in the original project. > > so i opened a 'cli' form my Win7 and tried > > D:\>convert.py > > D:\> > > Itsjust printed an empty line and nothign else. Why didn't even try to > open the folder and fiels within? > Syntactically it doesnt ghive me an error! > Somehting with os.walk() methos perhaps? If there is a folder D:\test and it does contain some PHP files (double- check!) the extension could be upper-case. Try if f.lower().endswith("php"): ... or php_files = fnmatch.filter(files, "*.php") for f in php_files: ... Peter From rantingrick at gmail.com Mon Aug 9 03:56:14 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 9 Aug 2010 00:56:14 -0700 (PDT) Subject: Python Portability References: <4C5DCF87.4000800@v.loewis.de> <4C5DF02A.6010200@v.loewis.de> Message-ID: On Aug 8, 8:03?am, "W. eWatson" wrote: > I'm done here. Well thats just great, now how will we ever know what the one char change was. Hmm. >>> a = 'somestring' >>> -a Traceback (most recent call last): File "", line 1, in -a TypeError: bad operand type for unary -: 'str' Go figure! From ldo at geek-central.gen.new_zealand Mon Aug 9 04:08:30 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Aug 2010 20:08:30 +1200 Subject: os.unlink on Windows References: <4c5eb146$0$28663$c3e8da3@news.astraweb.com> Message-ID: In message , Shambhu wrote: > It is working now after using double backslash in pathname. Might be simpler to use slashes. From steve at REMOVE-THIS-cybersource.com.au Mon Aug 9 04:21:51 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2010 08:21:51 GMT Subject: Python -Vs- Ruby: A regexp match to the death! References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> Message-ID: <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> On Mon, 09 Aug 2010 00:29:19 -0700, rantingrick wrote: > On Aug 8, 8:15?pm, Steven D'Aprano cybersource.com.au> wrote: > >> In Ruby they decided to be more general, so you can define whatever >> heredoc you need to quote whatever literal string you need. That's not >> bone-headed. > > Devils Advocate! > > PS: Man you're irb main was so full of cobweb i could barley see the > code... haa... haaaa... hachew!. ;-) irb's default prompt is a bit too verbose for my tastes, but Python allows you to customise its prompt too. You'll often see people here posting copy/pastes with a customised prompt, so obviously some people like that sort of thing. Me, my biggest gripe with the interactive interpreter is that using >>> as a prompt clashes with > as the standard quoting character in email and news, but Guido has refused to even consider changing it. And that it's quite finicky about blank lines between methods and inside functions. Makes it hard to paste code directly into the interpreter. And that pasting doesn't strip out any leading prompts. It needs a good doctest mode. -- Steven From nikos.the.gr33k at gmail.com Mon Aug 9 04:22:04 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 01:22:04 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> On 9 ???, 10:38, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > Now the code looks as follows: > > for currdir, files, dirs in os.walk('test'): > > > ? ? ? ? for f in files: > > > ? ? ? ? ? ? ? ? if f.endswith('php'): > > > ? ? ? ? ? ? ? ? ? ? ? ? # get abs path to filename > > ? ? ? ? ? ? ? ? ? ? ? ? src_f = join(currdir, f) > > I just tried to test it. I created a folder names 'test' in me 'd:\' > > drive. > > Then i have put to .php files inside form the original to test if it > > would work ok for those too files before acting in the whole copy and > > after in the original project. > > > so i opened a 'cli' form my Win7 and tried > > > D:\>convert.py > > > D:\> > > > Itsjust printed an empty line and nothign else. Why didn't even try to > > open the folder and fiels within? > > Syntactically it doesnt ghive me an error! > > Somehting with os.walk() methos perhaps? > > If there is a folder D:\test and it does contain some PHP files (double- > check!) the extension could be upper-case. Try > > if f.lower().endswith("php"): ... > > or > > php_files = fnmatch.filter(files, "*.php") > for f in php_files: ... > > Peter The extension is in in lower case. folder is there, php files is there, i dont know why it doesnt't want to go into the d:\test to find them. Thast one problem. The other one is: i made the code simpler by specifying the filename my self. ========================= # get abs path to filename src_f = 'd:\\test\\index.php' # open php src file print ( 'reading from %s' % src_f ) f = open(src_f, 'r') src_data = f.read() # read contents of PHP file f.close() ========================= but although ti nwo finds the fiel i egt this error in 'cli': D:\>aconvert.py reading from d:\test\index.php Traceback (most recent call last): File "D:\aconvert.py", line 16, in src_data = f.read() # read contents of PHP file File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position 321: char acter maps to Somethign with the damn encodings again!! From __peter__ at web.de Mon Aug 9 04:45:37 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 10:45:37 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> Message-ID: ????? wrote: > On 9 ???, 10:38, Peter Otten <__pete... at web.de> wrote: >> ????? wrote: >> > Now the code looks as follows: >> > for currdir, files, dirs in os.walk('test'): >> >> > for f in files: >> >> > if f.endswith('php'): >> >> > # get abs path to filename >> > src_f = join(currdir, f) >> > I just tried to test it. I created a folder names 'test' in me 'd:\' >> > drive. >> > Then i have put to .php files inside form the original to test if it >> > would work ok for those too files before acting in the whole copy and >> > after in the original project. >> >> > so i opened a 'cli' form my Win7 and tried >> >> > D:\>convert.py >> >> > D:\> >> >> > Itsjust printed an empty line and nothign else. Why didn't even try to >> > open the folder and fiels within? >> > Syntactically it doesnt ghive me an error! >> > Somehting with os.walk() methos perhaps? >> >> If there is a folder D:\test and it does contain some PHP files (double- >> check!) the extension could be upper-case. Try >> >> if f.lower().endswith("php"): ... >> >> or >> >> php_files = fnmatch.filter(files, "*.php") >> for f in php_files: ... >> >> Peter > > The extension is in in lower case. folder is there, php files is > there, i dont know why it doesnt't want to go into the d:\test to find > them. > > Thast one problem. > > The other one is: > > i made the code simpler by specifying the filename my self. > > ========================= > # get abs path to filename > src_f = 'd:\\test\\index.php' > > # open php src file > print ( 'reading from %s' % src_f ) > f = open(src_f, 'r') > src_data = f.read() # read contents of PHP file > f.close() > ========================= > > but although ti nwo finds the fiel i egt this error in 'cli': > > D:\>aconvert.py > reading from d:\test\index.php > Traceback (most recent call last): > File "D:\aconvert.py", line 16, in > src_data = f.read() # read contents of PHP file > File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode > return codecs.charmap_decode(input,self.errors,decoding_table)[0] > UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position > 321: char > acter maps to > > Somethign with the damn encodings again!! Hmm, at one point in this thread you switched from Python 2.x to Python 3.2. There are a lot of subtle and not so subtle differences between 2.x and 3.x, and I recommend that you stick to one while you are still in newbie mode. If you want to continue to use 3.x I recommend that you at least use the stable 3.1 version. Now one change from Python 2 to 3 is that open(filename, "r") gives you a beast that is unicode-aware and assumes that the file is encoded in utf-8 unless you tell it otherwise with open(..., encoding=whatever). So what is the charset used for your index.php? Peter From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 9 05:04:40 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Aug 2010 11:04:40 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <8c3r45FsveU1@mid.individual.net> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <4C5C562A.90702@sschwarzer.net> <8c3r45FsveU1@mid.individual.net> Message-ID: <4c5fc4a7$0$23059$426a74cc@news.free.fr> Gregory Ewing a ?crit : > Ethan Furman wrote: > >> Instead of using 'is' use '=='. Maybe not as cute, but definitely >> more robust! > > It's also just as efficient if you use strings that > resemble identifiers, because they will be interned, Remember : this IS an implementation detail. From fetchinson at googlemail.com Mon Aug 9 05:24:31 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 9 Aug 2010 11:24:31 +0200 Subject: Smith-Waterman Algorithm in Python In-Reply-To: References: <9385284e-d98a-4e3e-a721-eb2e11b7f179@i24g2000yqa.googlegroups.com> <4C5D52BE.302@gmaiil.com> Message-ID: >>> Every one of the first 20 entries is either the OP questions or your >>> reply. >> >> And you think it was there before the OP sent his message? >> Oh wait, did you just invent a time machine? :) >> >>> Daniel - you are no help at all, and no funny. >> >> Actually, I'm damn funny! :) > > I have noticed before that people who post without searching first end > up polluting subsequent searches. Google obviously boosts the > rank of recent pages. This is one of the three major reasons stackoverflow and friends were developed. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From aimeixu at amazon.com Mon Aug 9 05:33:52 2010 From: aimeixu at amazon.com (aimeixu) Date: Mon, 9 Aug 2010 17:33:52 +0800 Subject: how to change a string into dictionary Message-ID: <4C5FCB80.7010701@amazon.com> Hi, I am newbie for python ,Here is my question: a = "{'a':'1','b':'2'}" how to change a into a dictionary ,says, a = {'a':'1','b':'2'} Thanks a lot .Really need help. From blur959 at hotmail.com Mon Aug 9 05:44:11 2010 From: blur959 at hotmail.com (blur959) Date: Mon, 9 Aug 2010 02:44:11 -0700 (PDT) Subject: simple renaming files program Message-ID: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Hi, all, I am working on a simple program that renames files based on the directory the user gives, the names the user searched and the names the user want to replace. However, I encounter some problems. When I try running the script, when it gets to the os.rename part, there will be an error. The error is : n = os.rename(file, file.replace(s, r)) WindowsError: [Error 2] The system cannot find the file specified I attached my code below, hope you guys can help me, Thanks! import os directory = raw_input("input file directory") s = raw_input("search for name") r = raw_input("replace name") for file in os.listdir(directory): n = os.rename(file, file.replace(s, r)) print n From nikos.the.gr33k at gmail.com Mon Aug 9 05:46:26 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 02:46:26 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> Message-ID: <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> On 9 ???, 11:45, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > On 9 ???, 10:38, Peter Otten <__pete... at web.de> wrote: > >> ????? wrote: > >> > Now the code looks as follows: > >> > for currdir, files, dirs in os.walk('test'): > > >> > for f in files: > > >> > if f.endswith('php'): > > >> > # get abs path to filename > >> > src_f = join(currdir, f) > >> > I just tried to test it. I created a folder names 'test' in me 'd:\' > >> > drive. > >> > Then i have put to .php files inside form the original to test if it > >> > would work ok for those too files before acting in the whole copy and > >> > after in the original project. > > >> > so i opened a 'cli' form my Win7 and tried > > >> > D:\>convert.py > > >> > D:\> > > >> > Itsjust printed an empty line and nothign else. Why didn't even try to > >> > open the folder and fiels within? > >> > Syntactically it doesnt ghive me an error! > >> > Somehting with os.walk() methos perhaps? > > >> If there is a folder D:\test and it does contain some PHP files (double- > >> check!) the extension could be upper-case. Try > > >> if f.lower().endswith("php"): ... > > >> or > > >> php_files = fnmatch.filter(files, "*.php") > >> for f in php_files: ... > > >> Peter > > > The extension is in in lower case. folder is there, php files is > > there, i dont know why it doesnt't want to go into the d:\test to find > > them. > > > Thast one problem. > > > The other one is: > > > i made the code simpler by specifying the filename my self. > > > ========================= > > # get abs path to filename > > src_f = 'd:\\test\\index.php' > > > # open php src file > > print ( 'reading from %s' % src_f ) > > f = open(src_f, 'r') > > src_data = f.read() ? ? ? ? ? ? ? ?# read contents of PHP file > > f.close() > > ========================= > > > but ?although ti nwo finds the fiel i egt this error in 'cli': > > > D:\>aconvert.py > > reading from d:\test\index.php > > Traceback (most recent call last): > > ? File "D:\aconvert.py", line 16, in > > ? ? src_data = f.read() ? ? ? ? # read contents of PHP file > > ? File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode > > ? ? return codecs.charmap_decode(input,self.errors,decoding_table)[0] > > UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position > > 321: char > > acter maps to > > > Somethign with the damn encodings again!! > > Hmm, at one point in this thread you switched from Python 2.x to Python 3.2. > There are a lot of subtle and not so subtle differences between 2.x and 3.x, > and I recommend that you stick to one while you are still in newbie mode. > > If you want to continue to use 3.x I recommend that you at least use the > stable 3.1 version. > > Now one change from Python 2 to 3 is that open(filename, "r") gives you a > beast that is unicode-aware and assumes that the file is encoded in utf-8 > unless you tell it otherwise with open(..., encoding=whatever). So what is > the charset used for your index.php? > > Peter Yes yesterday i switched to Python 3.2 Peter. When i open index.php within Notapad++ it says its in utf-8 without BOM and it contains inside exepect form english chars , greek cjhars as well fro printing. The file was made by my client in dreamweaver. So since its utf-8 what the problem of opening it? From anand.shashwat at gmail.com Mon Aug 9 05:53:38 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 9 Aug 2010 15:23:38 +0530 Subject: how to change a string into dictionary In-Reply-To: <4C5FCB80.7010701@amazon.com> References: <4C5FCB80.7010701@amazon.com> Message-ID: On Mon, Aug 9, 2010 at 3:03 PM, aimeixu wrote: > Hi, > I am newbie for python ,Here is my question: > a = "{'a':'1','b':'2'}" > how to change a into a dictionary ,says, a = {'a':'1','b':'2'} > Thanks a lot .Really need help. > Parse the string and re-create the dictionary. >>> s = "{'a':'1','b':'2'}" >>> ds = {} >>> for i in s.strip('{}').split(','): ... key, val = i.split(':') ... ds[key.strip("'")] = val.strip("'") ... >>> ds {'a': '1', 'b': '2'} >>> type(ds) > -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Aug 9 06:01:37 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 9 Aug 2010 03:01:37 -0700 Subject: simple renaming files program In-Reply-To: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: On Mon, Aug 9, 2010 at 2:44 AM, blur959 wrote: > Hi, all, I am working on a simple program that renames files based on > the directory the user gives, the names the user searched and the > names the user want to replace. However, I encounter some problems. > When I try running the script, when it gets to the os.rename part, > there will be an error. The error is : > ?n = os.rename(file, file.replace(s, r)) > WindowsError: [Error 2] The system cannot find the file specified > > I attached my code below, hope you guys can help me, Thanks! > > import os > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for file in os.listdir(directory): > ? ?n = os.rename(file, file.replace(s, r)) > ? ?print n os.rename() takes paths that are absolute (or possibly relative to the cwd), not paths that are relative to some arbitrary directory (as returned by os.listdir()). Also, never name a variable "file"; it shadows the name of the built-in type. Hence (untested): from os import listdir, rename from os.path import isdir, join directory = raw_input("input file directory") s = raw_input("search for name") r = raw_input("replace name") for filename in listdir(directory): path = join(directory, filename) #paste the directory name on if isdir(path): continue #skip subdirectories (they're not files) newname = filename.replace(s, r) newpath = join(directory, newname) n = rename(path, newpath) print n Cheers, Chris -- http://blog.rebertia.com From anand.shashwat at gmail.com Mon Aug 9 06:01:37 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 9 Aug 2010 15:31:37 +0530 Subject: simple renaming files program In-Reply-To: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: On Mon, Aug 9, 2010 at 3:14 PM, blur959 wrote: > Hi, all, I am working on a simple program that renames files based on > the directory the user gives, the names the user searched and the > names the user want to replace. However, I encounter some problems. > When I try running the script, when it gets to the os.rename part, > there will be an error. The error is : > n = os.rename(file, file.replace(s, r)) > WindowsError: [Error 2] The system cannot find the file specified > This is because the file does not exist. > > I attached my code below, hope you guys can help me, Thanks! > > import os > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for file in os.listdir(directory): > n = os.rename(file, file.replace(s, r)) > print n > Tried this on my system, works. >>> [shutil.move(i, r) for i in os.listdir(directory) if i==s] -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From eckhardt at satorlaser.com Mon Aug 9 06:04:45 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 09 Aug 2010 12:04:45 +0200 Subject: how to change a string into dictionary References: Message-ID: aimeixu wrote: > a = "{'a':'1','b':'2'}" > how to change a into a dictionary ,says, a = {'a':'1','b':'2'} You could evaluate it as regular Python code, using "exec": res = {} exec("a={'a':'1'}", res) print res['a'] However, if this is input from a file or the user, be aware that this opens loopholes for executing _any_ code, so you should only exec code from sources you can trust. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From __peter__ at web.de Mon Aug 9 06:06:31 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:06:31 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> Message-ID: ????? wrote: > On 9 ???, 11:45, Peter Otten <__pete... at web.de> wrote: >> ????? wrote: >> > On 9 ???, 10:38, Peter Otten <__pete... at web.de> wrote: >> >> ????? wrote: >> >> > Now the code looks as follows: >> >> > for currdir, files, dirs in os.walk('test'): >> >> >> > for f in files: >> >> >> > if f.endswith('php'): >> >> >> > # get abs path to filename >> >> > src_f = join(currdir, f) >> >> > I just tried to test it. I created a folder names 'test' in me 'd:\' >> >> > drive. >> >> > Then i have put to .php files inside form the original to test if it >> >> > would work ok for those too files before acting in the whole copy >> >> > and after in the original project. >> >> >> > so i opened a 'cli' form my Win7 and tried >> >> >> > D:\>convert.py >> >> >> > D:\> >> >> >> > Itsjust printed an empty line and nothign else. Why didn't even try >> >> > to open the folder and fiels within? >> >> > Syntactically it doesnt ghive me an error! >> >> > Somehting with os.walk() methos perhaps? >> >> >> If there is a folder D:\test and it does contain some PHP files >> >> (double- check!) the extension could be upper-case. Try >> >> >> if f.lower().endswith("php"): ... >> >> >> or >> >> >> php_files = fnmatch.filter(files, "*.php") >> >> for f in php_files: ... >> >> >> Peter >> >> > The extension is in in lower case. folder is there, php files is >> > there, i dont know why it doesnt't want to go into the d:\test to find >> > them. >> >> > Thast one problem. >> >> > The other one is: >> >> > i made the code simpler by specifying the filename my self. >> >> > ========================= >> > # get abs path to filename >> > src_f = 'd:\\test\\index.php' >> >> > # open php src file >> > print ( 'reading from %s' % src_f ) >> > f = open(src_f, 'r') >> > src_data = f.read() # read contents of PHP file >> > f.close() >> > ========================= >> >> > but although ti nwo finds the fiel i egt this error in 'cli': >> >> > D:\>aconvert.py >> > reading from d:\test\index.php >> > Traceback (most recent call last): >> > File "D:\aconvert.py", line 16, in >> > src_data = f.read() # read contents of PHP file >> > File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode >> > return codecs.charmap_decode(input,self.errors,decoding_table)[0] >> > UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position >> > 321: char >> > acter maps to >> >> > Somethign with the damn encodings again!! >> >> Hmm, at one point in this thread you switched from Python 2.x to Python >> 3.2. There are a lot of subtle and not so subtle differences between 2.x >> and 3.x, and I recommend that you stick to one while you are still in >> newbie mode. >> >> If you want to continue to use 3.x I recommend that you at least use the >> stable 3.1 version. >> >> Now one change from Python 2 to 3 is that open(filename, "r") gives you a >> beast that is unicode-aware and assumes that the file is encoded in utf-8 >> unless you tell it otherwise with open(..., encoding=whatever). So what >> is the charset used for your index.php? >> >> Peter > > > Yes yesterday i switched to Python 3.2 Peter. > > When i open index.php within Notapad++ it says its in utf-8 without > BOM and it contains inside exepect form english chars , greek cjhars > as well fro printing. > > The file was made by my client in dreamweaver. > > So since its utf-8 what the problem of opening it? Python says it's not, and I tend to believe it. You can open the file with open(..., errors="replace") but you will lose data (which is already garbled, anyway). Again: in the unlikely case that Python is causing your problem -- you do understand what an alpha version is? Peter From eckhardt at satorlaser.com Mon Aug 9 06:11:06 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 09 Aug 2010 12:11:06 +0200 Subject: simple renaming files program References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: blur959 wrote: > Hi, all, I am working on a simple program that renames files based on > the directory the user gives, the names the user searched and the > names the user want to replace. However, I encounter some problems. > When I try running the script, when it gets to the os.rename part, > there will be an error. The error is : > n = os.rename(file, file.replace(s, r)) > WindowsError: [Error 2] The system cannot find the file specified I see that you are using os.listdir(), so the files should be present, but still, I would consider checking that when I encounter this error. > I attached my code below, hope you guys can help me, Thanks! > > import os > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for file in os.listdir(directory): > n = os.rename(file, file.replace(s, r)) > print n Looks good so far, but what are the values in s, r, file and the result of file.replace(s, r) for the case that fails? Also, as a side note, help(os.rename) doesn't document any returnvalue to store in n, but that doesn't seem to be the problem. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From clp2 at rebertia.com Mon Aug 9 06:13:01 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 9 Aug 2010 03:13:01 -0700 Subject: how to change a string into dictionary In-Reply-To: References: <4C5FCB80.7010701@amazon.com> Message-ID: On Mon, Aug 9, 2010 at 2:53 AM, Shashwat Anand wrote: > On Mon, Aug 9, 2010 at 3:03 PM, aimeixu wrote: >> Hi, >> I am newbie for python ,Here is my question: >> a = "{'a':'1','b':'2'}" >> how to change a into a dictionary ,says, a = {'a':'1','b':'2'} >> Thanks a lot .Really need help. > > Parse the string and re-create the dictionary. >>>> s =?"{'a':'1','b':'2'}" >>>> ds = {} >>>> for i in s.strip('{}').split(','): > ... ? ? key, val = i.split(':') > ... ? ? ds[key.strip("'")] = val.strip("'") Just for the record, that'll break if the dictionary entries have embedded commas or colons. eval() will handle such cases correctly and probably* run faster, but is obviously insecure. If you have control of both ends of the serialization process, you might consider using the `json` or `pickle` std lib modules instead. Cheers, Chris -- *Do a benchmark obviously. http://blog.rebertia.com From __peter__ at web.de Mon Aug 9 06:19:19 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:19:19 +0200 Subject: simple renaming files program References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: Chris Rebert wrote: > Hence (untested): > from os import listdir, rename > from os.path import isdir, join > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for filename in listdir(directory): > path = join(directory, filename) #paste the directory name on > if isdir(path): continue #skip subdirectories (they're not files) > newname = filename.replace(s, r) > newpath = join(directory, newname) > n = rename(path, newpath) > print n Warning: I don't remember how Windows handles this, but unix will happily perform os.rename("alpha/alpha.txt", "beta/beta.txt") and overwrite beta/beta.txt with alpha/alpha.txt. I'd rather modify the filename before joining it with the directory. newname = filename.replace(s, r) if newname != filename: path = os.path.join(directory, filename) newpath = os.path.join(directory, newname) os.rename(path, newpath) If you don't you run the risk of operating in unexpected directories. Peter From dmitrey.kroshko at scipy.org Mon Aug 9 06:26:04 2010 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 9 Aug 2010 03:26:04 -0700 (PDT) Subject: Create child class of Python dict with modified values Message-ID: <9f567611-6031-45fa-94d6-af85ebf1f655@p7g2000yqa.googlegroups.com> hi all, suppose I have defined a child class of Python dict, currently it constructor looks like that: def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) #(+some more insufficient code) Constructor should be capable of calling with either any way Python dict is constructed or with a Python dict instance to be derived from; calculations speed is important. So it works well for now, but I want __init__ to set modified values, like this: values_of_the_dict = [some_func(elem) for elem in self.values()] How this could be done? Thank you in advance, Dmitrey. From targetsmart at gmail.com Mon Aug 9 06:29:38 2010 From: targetsmart at gmail.com (targetsmart) Date: Mon, 9 Aug 2010 03:29:38 -0700 (PDT) Subject: dumping generator Message-ID: Right now if I want to dump the contents of a generator object I use , a snip from a bigger block of code.. try: while gen: print gen.next() except StopIteration: print "Done" else: raise is there a much simpler way ? like for printing list we do list = range(10) print list would print [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] From nikos.the.gr33k at gmail.com Mon Aug 9 06:34:30 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 03:34:30 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> Message-ID: <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> On 9 ???, 13:06, Peter Otten <__pete... at web.de> wrote: > > So since its utf-8 what the problem of opening it? > > Python says it's not, and I tend to believe it. You are right! I tried to do the same exact openign via IDLE enviroment and i goth the encoding of the file from there! >>> open("d:\\test\\index.php" ,'r') <_io.TextIOWrapper name='d:\\test\\index.php' encoding='cp1253'> Thats why in the error in my previous post it said File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode it tried to use the cp1253 encoding. But now sicne Python as we see can undestand the nature of the encoding what causing it not to open the file? From __peter__ at web.de Mon Aug 9 06:38:52 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:38:52 +0200 Subject: Create child class of Python dict with modified values References: <9f567611-6031-45fa-94d6-af85ebf1f655@p7g2000yqa.googlegroups.com> Message-ID: dmitrey wrote: > hi all, > suppose I have defined a child class of Python dict, currently it > constructor looks like that: > def __init__(self, *args, **kwargs): > dict.__init__(self, *args, **kwargs) > #(+some more insufficient code) > > Constructor should be capable of calling with either any way Python > dict is constructed or with a Python dict instance to be derived from; > calculations speed is important. > > So it works well for now, but I want __init__ to set modified values, > like this: > values_of_the_dict = [some_func(elem) for elem in self.values()] > > How this could be done? >>> class D(dict): ... def __init__(self, *args, **kw): ... if args: ... args = ((k, v.upper()) for k, v in args[0]), ... if kw: ... for k in kw: kw[k] = 10*kw[k] ... dict.__init__(self, *args, **kw) ... >>> D(["ab", "cd"], e="f") {'a': 'B', 'c': 'D', 'e': 'ffffffffff'} Replace v.upper() and 10*kw[k] with the appropriate some_func() calls. Personally I would apply the function before passing the data to the dict subclass. Peter From __peter__ at web.de Mon Aug 9 06:40:47 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:40:47 +0200 Subject: dumping generator References: Message-ID: targetsmart wrote: > Right now if I want to dump the contents of a generator object I use , > a snip from a bigger block of code.. > > try: > while gen: print gen.next() > except StopIteration: > print "Done" > else: > raise > > is there a much simpler way ? Indeed there is: for item in gen: print item print "Done" Peter From dmitrey.kroshko at scipy.org Mon Aug 9 06:44:36 2010 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 9 Aug 2010 03:44:36 -0700 (PDT) Subject: Create child class of Python dict with modified values References: <9f567611-6031-45fa-94d6-af85ebf1f655@p7g2000yqa.googlegroups.com> Message-ID: <7a7c0b96-ffae-48a5-a6f2-5999c56f5fad@t20g2000yqa.googlegroups.com> On Aug 9, 1:38?pm, Peter Otten <__pete... at web.de> wrote: > dmitrey wrote: > > hi all, > > suppose I have defined a child class of Python dict, currently it > > constructor looks like that: > > ? ? def __init__(self, *args, **kwargs): > > ? ? ? ? dict.__init__(self, *args, **kwargs) > > ? ? ? ? #(+some more insufficient code) > > > Constructor should be capable of calling with either any way Python > > dict is constructed or with a Python dict instance to be derived from; > > calculations speed is important. > > > So it works well for now, but I want __init__ to set modified values, > > like this: > > values_of_the_dict = [some_func(elem) for elem in self.values()] > > > How this could be done? > >>> class D(dict): > > ... ? ? def __init__(self, *args, **kw): > ... ? ? ? ? ? ? if args: > ... ? ? ? ? ? ? ? ? ? ? args = ((k, v.upper()) for k, v in args[0]), > ... ? ? ? ? ? ? if kw: > ... ? ? ? ? ? ? ? ? ? ? for k in kw: kw[k] = 10*kw[k] > ... ? ? ? ? ? ? dict.__init__(self, *args, **kw) > ...>>> D(["ab", "cd"], e="f") > > {'a': 'B', 'c': 'D', 'e': 'ffffffffff'} > > Replace v.upper() and 10*kw[k] with the appropriate some_func() calls. OK, thank you. > Personally I would apply the function before passing the data to the dict > subclass. It's impossible for the situation in hand. D. From eckhardt at satorlaser.com Mon Aug 9 06:44:38 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 09 Aug 2010 12:44:38 +0200 Subject: dumping generator References: Message-ID: targetsmart wrote: > Right now if I want to dump the contents of a generator object I use , > a snip from a bigger block of code.. > > try: > while gen: print gen.next() > except StopIteration: > print "Done" > else: > raise > > is there a much simpler way ? Why not something like this: for i in gen: print i > like for printing list we do > list = range(10) > print list > would print > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] You could coerce the thing into a list: gen = xrange(10) print list(gen) :) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From __peter__ at web.de Mon Aug 9 06:47:22 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 12:47:22 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> Message-ID: ????? wrote: > On 9 ???, 13:06, Peter Otten <__pete... at web.de> wrote: > >> > So since its utf-8 what the problem of opening it? >> >> Python says it's not, and I tend to believe it. > > You are right! > > I tried to do the same exact openign via IDLE enviroment and i goth > the encoding of the file from there! > >>>> open("d:\\test\\index.php" ,'r') > <_io.TextIOWrapper name='d:\\test\\index.php' encoding='cp1253'> > > Thats why in the error in my previous post it said > File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode > it tried to use the cp1253 encoding. > > But now sicne Python as we see can undestand the nature of the > encoding what causing it not to open the file? It doesn't. You have to tell. *If* the file uses cp1253 you can open it with open(..., encoding="cp1253") Note that if the file is not in cp1253 python will still happily open it as long as it doesn't contain the following bytes: >>> for i in range(256): ... try: chr(i).decode("cp1253") and None ... except: print i ... 129 136 138 140 141 142 143 144 152 154 156 157 158 159 170 210 255 Peter From blur959 at hotmail.com Mon Aug 9 06:48:37 2010 From: blur959 at hotmail.com (blur959) Date: Mon, 9 Aug 2010 03:48:37 -0700 (PDT) Subject: simple renaming files program References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: On Aug 9, 6:01?pm, Chris Rebert wrote: > On Mon, Aug 9, 2010 at 2:44 AM, blur959 wrote: > > Hi, all, I am working on a simple program that renames files based on > > the directory the user gives, the names the user searched and the > > names the user want to replace. However, I encounter some problems. > > When I try running the script, when it gets to the os.rename part, > > there will be an error. The error is : > > ?n = os.rename(file, file.replace(s, r)) > > WindowsError: [Error 2] The system cannot find the file specified > > > I attached my code below, hope you guys can help me, Thanks! > > > import os > > directory = raw_input("input file directory") > > s = raw_input("search for name") > > r = raw_input("replace name") > > > for file in os.listdir(directory): > > ? ?n = os.rename(file, file.replace(s, r)) > > ? ?print n > > os.rename() takes paths that are absolute (or possibly relative to the > cwd), not paths that are relative to some arbitrary directory (as > returned by os.listdir()). > Also, never name a variable "file"; it shadows the name of the built-in type. > > Hence (untested): > from os import listdir, rename > from os.path import isdir, join > directory = raw_input("input file directory") > s = raw_input("search for name") > r = raw_input("replace name") > > for filename in listdir(directory): > ? ? path = join(directory, filename) #paste the directory name on > ? ? if isdir(path): continue #skip subdirectories (they're not files) > ? ? newname = filename.replace(s, r) > ? ? newpath = join(directory, newname) > ? ? n = rename(path, newpath) > ? ? print n > > Cheers, > Chris > --http://blog.rebertia.com Thanks, they worked! From not_my_email at sadf.com Mon Aug 9 07:12:45 2010 From: not_my_email at sadf.com (Vedran) Date: Mon, 9 Aug 2010 11:12:45 +0000 (UTC) Subject: Decorators without function Message-ID: Hello! Is it possible to apply a decorator on a block of code, without defining a function that decorator is applied to. I have to generate a lot of similar graphs. For that reason I use plot_decorator to perform usual figure setup(outfile, legend, x_label, y_label and so on), and pylab.plot commands to do the actual plotting. Current solution: @plot_decorator(fig_params1) def plt(): pylab.plot(..first graph data...) pylab.plot(..second graph data..) plt() Is it possible to apply decorator only to the body of plt (several pylab.plot commands) without actually defining this function, because I use it only once, right after the definition? From __peter__ at web.de Mon Aug 9 07:37:14 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 13:37:14 +0200 Subject: Decorators without function References: Message-ID: Vedran wrote: > Hello! > > Is it possible to apply a decorator on a block of code, without defining > a function that decorator is applied to. You can only decorate functions or classes. > I have to generate a lot of similar graphs. For that reason I use > plot_decorator to perform usual figure setup(outfile, legend, x_label, > y_label and so on), and pylab.plot commands to do the actual plotting. > > Current solution: > > @plot_decorator(fig_params1) > def plt(): > pylab.plot(..first graph data...) > pylab.plot(..second graph data..) > plt() > > Is it possible to apply decorator only to the body of plt (several > pylab.plot commands) without actually defining this function, because I > use it only once, right after the definition? I have a hunch that a contextmanager is a better match for your requirements, see http://docs.python.org/library/contextlib.html#contextlib.contextmanager Peter From saeed.gnu at gmail.com Mon Aug 9 07:41:23 2010 From: saeed.gnu at gmail.com (saeed.gnu) Date: Mon, 9 Aug 2010 04:41:23 -0700 (PDT) Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: "x is y" means "id(y) == id(y)" "x is not y" means "id(x) != id(x)" "x is not None" means "id(x) != id(None)" "x is not None" is a really silly statement!! because id(None) and id of any constant object is not predictable! I don't know whay people use "is" instead of "==". you should write "if x!=None" instead of "x is not None" From sschwarzer at sschwarzer.net Mon Aug 9 07:42:12 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 09 Aug 2010 13:42:12 +0200 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> Message-ID: <4C5FE994.1040103@sschwarzer.net> Hi Steven, On 2010-08-09 10:21, Steven D'Aprano wrote: > And that it's quite finicky about blank lines between methods and inside > functions. Makes it hard to paste code directly into the interpreter. > > And that pasting doesn't strip out any leading prompts. It needs a good > doctest mode. ipython [1] should help here: IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: %paste? Type: Magic function Base Class: String Form: > Namespace: IPython internal File: /usr/lib/pymodules/python2.6/IPython/Magic.py Definition: %paste(self, parameter_s='') Docstring: Allows you to paste & execute a pre-formatted code block from clipboard. The text is pulled directly from the clipboard without user intervention. The block is dedented prior to execution to enable execution of method definitions. '>' and '+' characters at the beginning of a line are ignored, to allow pasting directly from e-mails, diff files and doctests (the '...' continuation prompt is also stripped). The executed block is also assigned to variable named 'pasted_block' for later editing with '%edit pasted_block'. You can also pass a variable name as an argument, e.g. '%paste foo'. This assigns the pasted block to variable 'foo' as string, without dedenting or executing it (preceding >>> and + is still stripped) '%paste -r' re-executes the block previously entered by cpaste. IPython statements (magics, shell escapes) are not supported (yet). See also -------- cpaste: manually paste code into terminal until you mark its end. Unfortunatey, when I enter In [2]: %paste at the prompt it gives me (before I pasted anything) In [2]: %paste ------------------------------------------------------------ File "", line 1 http://pypi.python.org/pypi/ipython/0.10 ^ SyntaxError: invalid syntax So far, I couldn't find anything on the net on this. [1] http://pypi.python.org/pypi/ipython Stefan From alex.lavoro.propio at gmail.com Mon Aug 9 08:10:19 2010 From: alex.lavoro.propio at gmail.com (Alex Barna) Date: Mon, 9 Aug 2010 05:10:19 -0700 (PDT) Subject: GUI automation tool (windows) Message-ID: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> I know that this question has been asked for several times, but it surprises that there is no tool under very active development and the community activities are very low (mailing list posts). All the tools listed in: http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#GUITestingTools Comparing with AutoIt (www.autoitscript.com), it has tens to hundreds of posts everyday. AutoIt uses a proprietary BASIC -like language, and to be honest, I don't like it and I prefer a Pythonic solution. pywinauto seems to be the best choice but the community has been very low also. The same happens in pyguiunit, pyAA, WATSUP, all development seem to be ceased. So what happens to this field (Windows GUI automation) ? From saeed.gnu at gmail.com Mon Aug 9 08:11:11 2010 From: saeed.gnu at gmail.com (saeed.gnu) Date: Mon, 9 Aug 2010 05:11:11 -0700 (PDT) Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On Aug 9, 3:41?pm, "saeed.gnu" wrote: > "x is y" ? ? ? ? ?means ? "id(y) == id(y)" > "x is not y" ? ? ?means ? "id(x) != id(x)" > "x is not None" ? means ? "id(x) != id(None)" > > "x is not None" ?is a really silly statement!! because id(None) and id > of any constant object is not predictable! I don't know whay people > use "is" instead of "==". you should write "if x!=None" instead of "x > is not None" Although small objects are unique in the memory (with a unique id) and using "is" works ok, but that's not logical to compare id's when we actually want to compare values! From saeed.gnu at gmail.com Mon Aug 9 09:00:03 2010 From: saeed.gnu at gmail.com (saeed.gnu) Date: Mon, 9 Aug 2010 06:00:03 -0700 (PDT) Subject: Python "why" questions References: Message-ID: <2165a843-888d-40de-8033-e871c7699d5f@x25g2000yqj.googlegroups.com> > > 1) ?Why do Python lists start with element [0], instead of element > > [1]? ?"Common sense" would seem to suggest that lists should start > > with [1]. ? Because Zero is the neutral element of addition operation. And indexes (and all adresses in computing) involve with addition much more than multiplication! That's too clear i think and that's silly to use One as first index of arrays/lists in a programming language! From jrmy.lnrd at gmail.com Mon Aug 9 09:18:35 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Mon, 9 Aug 2010 06:18:35 -0700 (PDT) Subject: Regular expression issue References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> On Aug 8, 7:34?pm, Tim Chase wrote: > On 08/08/10 17:20, genxtech wrote: > > > if re.search(search_string, in_string) != None: > > While the other responses have addressed some of the big issues, > it's also good to use > > ? ?if thing_to_test is None: > > or > > ? ?if thing_to_test is not None: > > instead of "== None" or "!= None". > > -tkc I would like to thank all of you for your responses. I understand what the regular expression means, and am aware of the double negative nature of the test. I guess what I am really getting at is why the last test returns a value of None, and even when using the syntax suggested in this quoted solution, the code for the last test is doing the opposite of the previous 2 tests that also returned a value of None. I hope this makes sense and clarifies what I am trying to ask. Thanks From jrmy.lnrd at gmail.com Mon Aug 9 09:18:35 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Mon, 9 Aug 2010 06:18:35 -0700 (PDT) Subject: Regular expression issue References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> Message-ID: <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> On Aug 8, 7:34?pm, Tim Chase wrote: > On 08/08/10 17:20, genxtech wrote: > > > if re.search(search_string, in_string) != None: > > While the other responses have addressed some of the big issues, > it's also good to use > > ? ?if thing_to_test is None: > > or > > ? ?if thing_to_test is not None: > > instead of "== None" or "!= None". > > -tkc I would like to thank all of you for your responses. I understand what the regular expression means, and am aware of the double negative nature of the test. I guess what I am really getting at is why the last test returns a value of None, and even when using the syntax suggested in this quoted solution, the code for the last test is doing the opposite of the previous 2 tests that also returned a value of None. I hope this makes sense and clarifies what I am trying to ask. Thanks From mrmakent at cox.net Mon Aug 9 09:19:23 2010 From: mrmakent at cox.net (Mike Kent) Date: Mon, 9 Aug 2010 06:19:23 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: Message-ID: <8fa1a70c-c40b-40fd-8dc7-2cb155fbc8b1@l6g2000yqb.googlegroups.com> On Aug 8, 8:43?pm, rantingrick wrote: > Hello folks, > > You all know i been forced to use Ruby and i am not happy about that. ***Blablabla cut long rant*** Xah, this is really you, isn't it. Come on, confess. From frank at chagford.com Mon Aug 9 09:19:30 2010 From: frank at chagford.com (Frank Millman) Date: Mon, 9 Aug 2010 15:19:30 +0200 Subject: Circular imports (again) Message-ID: Hi all I know the problems related to circular imports, and I know some of the techniques to get around them. However, I find that I bump my head into them from time to time, which means, I guess, that I have not fully understood how to organise my code so that I avoid them in the first place. It has just happened again. I have organised my code into three modules, each representing a fairly cohesive functional area of the overall application. However, there really are times when Module A wants to invoke something from Module B, ditto for B and C, and ditto for C and A. I can think of two workarounds. One is to place the import statement inside the function that actually requires it. It is therefore not executed when the module itself is imported, thereby avoiding the problem. It works, but breaks the convention that all imports should be declared at the top of the program. A second solution is to avoid invoking the other modules directly, but rather use global Queue.Queues to pass requests from one module to another. Again, it works, but adds complication, especially if the 'invoker' needs to get a return value. So I think my main question is, is this a symptom of a flaw in my approach, or is this something that all programmers bump into from time to time? If the former, I can expand on my current requirement if anyone would like to suggest a better approach. If the latter, is either of the above solutions preferred, or are there other techniques to get around the problem. Any suggestions will be appreciated. Thanks Frank Millman From f3d27b at gmail.com Mon Aug 9 09:38:28 2010 From: f3d27b at gmail.com (Wang Lei) Date: Mon, 9 Aug 2010 21:38:28 +0800 Subject: HELP! build python error with message: "unable to load the file system codec" Message-ID: Hi, developers! I get python3k from the svn repository. The revision is 83889. When building it, i encounter this error. -------------------- gcc -pthread -Xlinker -export-dynamic -o python Modules/python.o libpython3.2.a -lpthread -ldl -lutil -lm XXX lineno: 1098, opcode: 32 Unable to get the locale encoding: fallback to utf-8 Fatal Python error: Py_Initialize: unable to load the file system codec LookupError: no codec search functions registered: can't find encoding /bin/sh: line 1: 14357 Aborted CC='gcc -pthread' LDSHARED='gcc -pthread -shared' LDFLAGS=' ' OPT='-DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes' ./python -E ../python-svn-14/setup.py build make: *** [sharedmods] Error 134 -------------------- What does that mean? Could anyone help? In case you want to check out the output. It is attached. -- Regards, Lei From eckhardt at satorlaser.com Mon Aug 9 09:39:08 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 09 Aug 2010 15:39:08 +0200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: candide wrote: > Python is an object oriented langage (OOL). The Python main > implementation is written in pure and "old" C90. Is it for historical > reasons? The fact that Python is OOP doesn't mean that the implementation of it has to be written using an OOP language. Other than that, I'm actually surprised that nobody mentioned that Python actually _is_ written in C++. Yes, it's restricted to a subset thereof that is compatible to C, but you could also claim that it was written in a subset of C compatible to C++. :) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From python at mrabarnett.plus.com Mon Aug 9 09:52:42 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 14:52:42 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> Message-ID: <4C60082A.2060206@mrabarnett.plus.com> ????? wrote: > On 8 ???, 17:59, Thomas Jollans wrote: > >> Two problems here: >> >> str.replace doesn't use regular expressions. You'll have to use the re >> module to use regexps. (the re.sub function to be precise) >> >> '.' matches a single character. Any character, but only one. >> '.*' matches as many characters as possible. This is not what you want, >> since it will match everything between the *first* . >> You want non-greedy matching. >> >> '.*?' is the same thing, without the greed. > > Thanks you, > > So i guess this needs to be written as: > > src_data = re.sub( '', '', src_data ) > In a regex '?' is a special character, so if you want a literal '?' you need to escape it. Therefore: src_data = re.sub(r'<\?(.*?)\?>', '', src_data) > Tha 'r' special char doesn't need to be inserter before the regex here > due to regex ain't containing backslashes. > >> You will have to find the tag before inserting the string. >> str.find should help -- or you could use str.replace and replace the >> tag with you counter line, plus a new . > > Ah yes! Damn why din't i think of it.... str.replace should do the > trick. I was stuck trying to figure regexes. > > So, i guess that should work: > > src_data = src_data.replace('', '

color=green> ??????? ??????????: %(counter)d

' ) > >> No it's not. You're just giving up too soon. > > Yes youa re right, your hints keep me going and thank you for that. From davea at ieee.org Mon Aug 9 10:07:36 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 10:07:36 -0400 Subject: simple renaming files program In-Reply-To: References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: <4C600BA8.8070500@ieee.org> blur959 wrote: > On Aug 9, 6:01 pm, Chris Rebert wrote: > >> >> os.rename() takes paths that are absolute (or possibly relative to the >> cwd), not paths that are relative to some arbitrary directory (as >> returned by os.listdir()). >> Also, never name a variable "file"; it shadows the name of the built-in type. >> >> Hence (untested): >> from os import listdir, rename >> from os.path import isdir, join >> directory =aw_input("input file directory") >> s =aw_input("search for name") >> r =aw_input("replace name") >> >> for filename in listdir(directory): >> path = join(directory, filename) #paste the directory name on >> if isdir(path): continue #skip subdirectories (they're not files) >> newname = filename.replace(s, r) >> newpath = join(directory, newname) >> n = rename(path, newpath) >> print n >> >> Cheers, >> Chris >> --http://blog.rebertia.com >> > > Thanks, they worked! > > A refinement: use os.path.join(), rather than just join(). It's smarter about adding the right kind of slash between the nodes, if needed. Currently, if you leave off the trailing slash (from "directory"), you'll end up with the files being one level up, and the individual files having a string prepended. DaveA From python at mrabarnett.plus.com Mon Aug 9 10:14:16 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 15:14:16 +0100 Subject: Regular expression issue In-Reply-To: <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> Message-ID: <4C600D38.6070903@mrabarnett.plus.com> genxtech wrote: > On Aug 8, 7:34 pm, Tim Chase wrote: >> On 08/08/10 17:20, genxtech wrote: >> >>> if re.search(search_string, in_string) != None: >> While the other responses have addressed some of the big issues, >> it's also good to use >> >> if thing_to_test is None: >> >> or >> >> if thing_to_test is not None: >> >> instead of "== None" or "!= None". >> >> -tkc > > I would like to thank all of you for your responses. I understand > what the regular expression means, and am aware of the double negative > nature of the test. I guess what I am really getting at is why the > last test returns a value of None, and even when using the syntax > suggested in this quoted solution, the code for the last test is doing > the opposite of the previous 2 tests that also returned a value of > None. I hope this makes sense and clarifies what I am trying to ask. > It returns None because it doesn't match. Why doesn't it match? Because the regex wants the last character to be a 'y', but it isn't, it's a 'a'. From nikos.the.gr33k at gmail.com Mon Aug 9 10:17:51 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 07:17:51 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> Message-ID: On 9 ???, 13:47, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > On 9 ???, 13:06, Peter Otten <__pete... at web.de> wrote: > > >> > So since its utf-8 what the problem of opening it? > > >> Python says it's not, and I tend to believe it. > > > You are right! > > > I tried to do the same exact openign via IDLE enviroment and i goth > > the encoding of the file from there! > > >>>> open("d:\\test\\index.php" ,'r') > > <_io.TextIOWrapper name='d:\\test\\index.php' encoding='cp1253'> > > > Thats why in the error in my previous post it said > > File "C:\Python32\lib\encodings\cp1253.py", line 23, in decode > > it tried to use the cp1253 encoding. > > > But now sicne Python as we see can undestand the nature of the > > encoding what causing it not to open the file? > > It doesn't. You have to tell. Why it doesn't? The idle response designates that it knows that file encoding is in "cp1253" which means it can identify it. *If* the file uses cp1253 you can open it with > > open(..., encoding="cp1253") > > Note that if the file is not in cp1253 python will still happily open it as > long as it doesn't contain the following bytes: > > >>> for i in range(256): > > ... ? ? try: chr(i).decode("cp1253") and None > ... ? ? except: print i > ... > 129 > 136 > 138 > 140 > 141 > 142 > 143 > 144 > 152 > 154 > 156 > 157 > 158 > 159 > 170 > 210 > 255 > > Peter I'm afraid it does because whn i tried: f = open(src_f, 'r', encoding="cp1253" ) i got the same error again.....what are those characters?Dont they belong too tot he same weird 'cp1253' encoding? Why compiler cant open them? From python at mrabarnett.plus.com Mon Aug 9 10:18:49 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 15:18:49 +0100 Subject: simple renaming files program In-Reply-To: <4C600BA8.8070500@ieee.org> References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> <4C600BA8.8070500@ieee.org> Message-ID: <4C600E49.3070907@mrabarnett.plus.com> Dave Angel wrote: > blur959 wrote: >> On Aug 9, 6:01 pm, Chris Rebert wrote: >> >>> >>> os.rename() takes paths that are absolute (or possibly relative to the >>> cwd), not paths that are relative to some arbitrary directory (as >>> returned by os.listdir()). >>> Also, never name a variable "file"; it shadows the name of the >>> built-in type. >>> >>> Hence (untested): >>> from os import listdir, rename >>> from os.path import isdir, join >>> directory =aw_input("input file directory") >>> s =aw_input("search for name") >>> r =aw_input("replace name") >>> >>> for filename in listdir(directory): >>> path = join(directory, filename) #paste the directory name on >>> if isdir(path): continue #skip subdirectories (they're not files) >>> newname = filename.replace(s, r) >>> newpath = join(directory, newname) >>> n = rename(path, newpath) >>> print n >>> >>> Cheers, >>> Chris >>> --http://blog.rebertia.com >>> >> >> Thanks, they worked! >> >> > A refinement: use os.path.join(), rather than just join(). It's > smarter about adding the right kind of slash between the nodes, if > needed. Currently, if you leave off the trailing slash (from > "directory"), you'll end up with the files being one level up, and the > individual files having a string prepended. > Have a look at the imports, Dave. :-) From nikos.the.gr33k at gmail.com Mon Aug 9 10:21:07 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 07:21:07 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> Message-ID: <1d07b6f8-6ccf-4472-a666-637a295ce1cd@z10g2000yqb.googlegroups.com> On 9 ???, 16:52, MRAB wrote: > ????? wrote: > > On 8 ???, 17:59, Thomas Jollans wrote: > > >> Two problems here: > > >> str.replace doesn't use regular expressions. You'll have to use the re > >> module to use regexps. (the re.sub function to be precise) > > >> '.' ?matches a single character. Any character, but only one. > >> '.*' matches as many characters as possible. This is not what you want, > >> since it will match everything between the *first* . > >> You want non-greedy matching. > > >> '.*?' is the same thing, without the greed. > > > Thanks you, > > > So i guess this needs to be written as: > > > src_data = re.sub( '', '', src_data ) > > In a regex '?' is a special character, so if you want a literal '?' you > need to escape it. Therefore: > > ? ? ?src_data = re.sub(r'<\?(.*?)\?>', '', src_data) i see, or perhaps even this: ? ?src_data = re.sub(r'', '', src_data) maybe it works here as well. From davea at ieee.org Mon Aug 9 10:21:38 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 10:21:38 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <4C600EF2.9060107@ieee.org> saeed.gnu wrote: > On Aug 9, 3:41 pm, "saeed.gnu" wrote: > >> "x is y" means "id(y) =id(y)" >> "x is not y" means "id(x) !=d(x)" >> "x is not None" means "id(x) !=d(None)" >> >> "x is not None" is a really silly statement!! because id(None) and id >> of any constant object is not predictable! I don't know whay people >> use "is" instead of "=. you should write "if x!=None" instead of "x >> is not None" >> > > Although small objects are unique in the memory (with a unique id) and > using "is" works ok, but that's not logical to compare id's when we > actually want to compare values! > > None is a single object; there is only one such object by language definition. So 'is' is the perfect operator if you want to check whether a particular object is that one or not. All other objects, of any possible type, will have a different ID than None. And talking about comparing values is nonsense anyway, since None has no value. It's only purpose is to indicate that some operation had no value, or no return statement, or ... Using '==' will not necessarily give the same result, and I can't think of ANY case where I'd prefer the former. If you disagree, give a concrete example. DaveA DaveA From blur959 at hotmail.com Mon Aug 9 10:24:36 2010 From: blur959 at hotmail.com (blur959) Date: Mon, 9 Aug 2010 07:24:36 -0700 (PDT) Subject: Creating a custom UI inside Maya with python Message-ID: Hi, all, I wonder if my post is relevant here, but i will still post it anyway. I am working on creating a custom UI inside Maya and I encountered some problems. Firstly, I am trying to create a textfield button that creates a locator-shaped curve based on the coordinates the user keyed into the text field. However I got no idea how to go about doing it properly. I hope you guys could give me some help. Thanks. I attached my code below. My code isn't working though. I have this error, which says button2 is not defined. I got no clue on how else to debug. import maya.cmds as cmds def createMyLayout(): window = cmds.window(widthHeight=(1000, 600), title="test", resizeToFitChildren=1) cmds.rowLayout("button1, button2, button3", numberOfColumns=5) cmds.columnLayout(adjustableColumn=True, columnAlign="center", rowSpacing=10) button2 = cmds.textFieldButtonGrp(label="LocatorCurve", text="Please key in your coordinates", changeCommand=edit_curve, buttonLabel="Execute", buttonCommand=locator_curve) cmds.setParent(menu=True) cmds.showWindow(window) def locator_curve(*args): # Coordinates of the locator-shaped curve. crv = cmds.curve(degree=1, point=[(1, 0, 0), (-1, 0, 0), (0, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 0), (0, 0, 1), (0, 0, -1), (0, 0, 0)]) return crv def edit_curve(*args): parts = button2.split(",") print parts x = parts[0] y = parts[1] z = parts[2] createMyLayout() From davea at ieee.org Mon Aug 9 10:40:06 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 10:40:06 -0400 Subject: simple renaming files program In-Reply-To: <4C600E49.3070907@mrabarnett.plus.com> References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> <4C600BA8.8070500@ieee.org> <4C600E49.3070907@mrabarnett.plus.com> Message-ID: <4C601346.4080804@ieee.org> MRAB wrote: > >>>> from os.path import isdir, join >>>> > > Have a look at the imports, Dave. :-) > Oops. I should have noticed that it was a function call, not a method. And there's no built-in called join(). I just usually avoid using this kind of alias, unless performance requires. thanks for keeping me honest. DaveA From nobody at nowhere.com Mon Aug 9 10:56:09 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 09 Aug 2010 15:56:09 +0100 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On Mon, 09 Aug 2010 04:41:23 -0700, saeed.gnu wrote: > "x is not None" is a really silly statement!! because id(None) and id > of any constant object is not predictable! I don't know whay people > use "is" instead of "==". you should write "if x!=None" instead of "x > is not None" No, you should use the identity check. If you use ==, the operand may have an __eq__ or __cmp__ method which considers the object equal to None. From pruebauno at latinmail.com Mon Aug 9 11:01:22 2010 From: pruebauno at latinmail.com (nn) Date: Mon, 9 Aug 2010 08:01:22 -0700 (PDT) Subject: Regular expression issue References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> Message-ID: On Aug 9, 9:18?am, genxtech wrote: > On Aug 8, 7:34?pm, Tim Chase wrote: > > > > > On 08/08/10 17:20, genxtech wrote: > > > > if re.search(search_string, in_string) != None: > > > While the other responses have addressed some of the big issues, > > it's also good to use > > > ? ?if thing_to_test is None: > > > or > > > ? ?if thing_to_test is not None: > > > instead of "== None" or "!= None". > > > -tkc > > I would like to thank all of you for your responses. ?I understand > what the regular expression means, and am aware of the double negative > nature of the test. ?I guess what I am really getting at is why the > last test returns a value of None, and even when using the syntax > suggested in this quoted solution, the code for the last test is doing > the opposite of the previous 2 tests that also returned a value of > None. ?I hope this makes sense and clarifies what I am trying to ask. > Thanks First: You understand the regular expression and the double negative but not both of them together, otherwise you would not be asking here. The suggestion of refactoring the code is that down the road you or somebody else doing maintenance will have to read it again. Good books avoid confusing grammar, likewise, good programs avoid confusing logic. Second: the root of your problem is the mistaken believe that P=>Q implies (not P)=>(not Q); This is not so. Let me give an example: if you say "if it rains" then "the ground is wet" that does not imply "if it doesn't rain" then "the ground is not wet". You could be watering the plants for instance. Saying "if the word finishes with a consonant and an y" then "ay, ey, iy, oy and uy are not at the end of the word" does not imply that "if the word does not finish with a consonant and an y" then "ay, ey, iy, oy or uy were found at the end of the word". The word could end in x for instance. I hope I didn't make it more confusing, otherwise other people will probably chime in to make it clear to you. From python at mrabarnett.plus.com Mon Aug 9 11:10:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 16:10:26 +0100 Subject: Creating a custom UI inside Maya with python In-Reply-To: References: Message-ID: <4C601A62.2020505@mrabarnett.plus.com> blur959 wrote: > Hi, all, I wonder if my post is relevant here, but i will still post > it anyway. I am working on creating a custom UI inside Maya and I > encountered some problems. Firstly, I am trying to create a textfield > button that creates a locator-shaped curve based on the coordinates > the user keyed into the text field. However I got no idea how to go > about doing it properly. I hope you guys could give me some help. > Thanks. I attached my code below. My code isn't working though. I have > this error, which says button2 is not defined. I got no clue on how > else to debug. > > import maya.cmds as cmds > > def createMyLayout(): [snip] > button2 = cmds.textFieldButtonGrp(label="LocatorCurve", > text="Please key in your > coordinates", > changeCommand=edit_curve, > buttonLabel="Execute", > buttonCommand=locator_curve) > [snip] When you assign to a name in a function the target is by default local to that function, so 'button2' is local to 'createMyLayout'. Add the line: global button2 to the function to make it visible to the rest of the module/file. From python at mrabarnett.plus.com Mon Aug 9 11:15:03 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 16:15:03 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <1d07b6f8-6ccf-4472-a666-637a295ce1cd@z10g2000yqb.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <5e3c534a-b2ce-463a-a032-1075b9bfc0ac@w30g2000yqw.googlegroups.com> <1d07b6f8-6ccf-4472-a666-637a295ce1cd@z10g2000yqb.googlegroups.com> Message-ID: <4C601B77.9080502@mrabarnett.plus.com> ????? wrote: > On 9 ???, 16:52, MRAB wrote: >> ????? wrote: >>> On 8 ???, 17:59, Thomas Jollans wrote: >>>> Two problems here: >>>> str.replace doesn't use regular expressions. You'll have to use the re >>>> module to use regexps. (the re.sub function to be precise) >>>> '.' matches a single character. Any character, but only one. >>>> '.*' matches as many characters as possible. This is not what you want, >>>> since it will match everything between the *first* . >>>> You want non-greedy matching. >>>> '.*?' is the same thing, without the greed. >>> Thanks you, >>> So i guess this needs to be written as: >>> src_data = re.sub( '', '', src_data ) >> In a regex '?' is a special character, so if you want a literal '?' you >> need to escape it. Therefore: >> >> src_data = re.sub(r'<\?(.*?)\?>', '', src_data) > > i see, or perhaps even this: > > src_data = re.sub(r'', '', src_data) > > maybe it works here as well. No. That regex means that it should match: # '>' From invalid at invalid.invalid Mon Aug 9 11:16:29 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 9 Aug 2010 15:16:29 +0000 (UTC) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: On 2010-08-07, Hexamorph wrote: > Lurking for long enough to know your style. Looking at your Unicode > rant, combined with some other comments and your general "I am right > and you are wrong because you disagree with me." style, I came to > the conclusion, that you are either a faschist or the perfect role > model for an imperialistic, foreign culture destroying, > self-praising, arrogant, ignorant moron. IOW, the "Ugly American". I assure you that we here in the US are aware of the problem and do try to keep them from annoying the rest of the world by providing them with an abundance of junk food, bad television, worse movies, and a variety of sporting events tailored to their tastes. Unfortunately the advent of cheap air-travel in the latter half of the 20th century has allowed small groups of them to escape and wander about various parts of the world (mainly Europe) in search of KFCs while complaining about the toilets, the food, the money, the weather, the roads, the cars, and so on. They are easily identified by their cloathing and their believe that everybody understands English if you speak it loudly and slowly while accompanying it with exaggerated, mostly-random hand gestures. Just avoid them if possible. Don't worry, the less contact they have with "furriners" the happier they are (which makes one wonder why they leave their home territories -- reasearch on that topic is ongoing). Unfortunately, if you work in the hospitality industries there's not much you can do other than grit your teeth, cross you fingers, and hope you'll end up with a batch that over-tips. -- Grant Edwards grant.b.edwards Yow! Youth of today! at Join me in a mass rally gmail.com for traditional mental attitudes! From johan at notused.invalid Mon Aug 9 11:19:17 2010 From: johan at notused.invalid (Johan) Date: Mon, 9 Aug 2010 17:19:17 +0200 Subject: Using dicts and lists as default arguments of functions Message-ID: <20100809171917.346bc849@reken.ne31.nl> Dear all, Considering this test program: def tst(a={}): print 1, a a['1'] = 1 print 2, a del a def tstb(a=[]): print 1, a a.append(1) print 2, a del a tst() tst() tstb() tstb() With output: tnjx at tnjx:~/tst> python tt.py 1 {} 2 {'1': 1} 1 {'1': 1} 2 {'1': 1} 1 [] 2 [1] 1 [1] 2 [1, 1] Would there be a way to ensure that the results does not depend on the previous call of the function. The desired output is: 1 {} 2 {'1': 1} 1 {} 2 {'1': 1} 1 [] 2 [1] 1 [] 2 [1] I know that tst({}) and tstb([]) will work, but is there any way to still use tst(), tstb()? Thanks in advance, Best regards, Johan From mwilson at the-wire.com Mon Aug 9 11:31:21 2010 From: mwilson at the-wire.com (Mel) Date: Mon, 09 Aug 2010 11:31:21 -0400 Subject: Using dicts and lists as default arguments of functions References: <20100809171917.346bc849@reken.ne31.nl> Message-ID: Johan wrote: > Dear all, > > Considering this test program: > > def tst(a={}): > print 1, a > a['1'] = 1 > print 2, a > del a The idiom to use is def tst (a=None): if a is None: a = {} # ... and so on. This means that every call to tst with unspecified a creates its own empty dict. Ditto for lists. Mel. From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 9 11:34:23 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Aug 2010 17:34:23 +0200 Subject: Using dicts and lists as default arguments of functions In-Reply-To: <20100809171917.346bc849@reken.ne31.nl> References: <20100809171917.346bc849@reken.ne31.nl> Message-ID: <4c601ffd$0$2755$426a74cc@news.free.fr> Johan a ?crit : > Dear all, > > Considering this test program: > > def tst(a={}): Stop here, we already know what will follow !-) And yes, it's one of Python's most (in)famous gotchas : default arguments values are computed only once, at function definition time (that is, when the def statement is executed). The correct way to write a function with mutable default arguments is: def func(arg=None): if arg is None: arg = [] # then proceed HTH From python at mrabarnett.plus.com Mon Aug 9 11:35:50 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 16:35:50 +0100 Subject: Using dicts and lists as default arguments of functions In-Reply-To: <20100809171917.346bc849@reken.ne31.nl> References: <20100809171917.346bc849@reken.ne31.nl> Message-ID: <4C602056.3080203@mrabarnett.plus.com> Johan wrote: > Dear all, > > Considering this test program: > > def tst(a={}): > print 1, a > a['1'] = 1 > print 2, a > del a > > def tstb(a=[]): > print 1, a > a.append(1) > print 2, a > del a > [snip] Do this instead: def tst(a=None): if a is None: a = {} print 1, a a['1'] = 1 print 2, a def tstb(a=None): if a is None: a = [] print 1, a a.append(1) print 2, a It's all explained here: http://effbot.org/zone/default-values.htm From iamforufriends at gmail.com Mon Aug 9 11:40:41 2010 From: iamforufriends at gmail.com (SAKEERA) Date: Mon, 9 Aug 2010 08:40:41 -0700 (PDT) Subject: EARN FROM HOME...EAZY... TRY THIS.#### Message-ID: <5e8886df-2337-41be-918a-cf7e8bb8bbdf@p22g2000pre.googlegroups.com> EARN FROM HOME...EAZY... TRY THIS.#### http://www.hymarkets.com/servlet/track?campaignID=70120000000AS5B&a_aid=d629b730 EARN FROM HOME...EAZY... TRY THIS.#### http://www.hymarkets.com/servlet/track?campaignID=70120000000AS5B&a_aid=d629b730 EARN FROM HOME...EAZY... TRY THIS.#### http://www.hymarkets.com/servlet/track?campaignID=70120000000AS5B&a_aid=d629b730 From michael at stroeder.com Mon Aug 9 11:43:00 2010 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 09 Aug 2010 17:43:00 +0200 Subject: ANN: python-ldap-2.3.12 Message-ID: Find a new release of python-ldap: http://pypi.python.org/pypi/python-ldap/2.3.12 python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). Project's web site: http://www.python-ldap.org/ Ciao, Michael. -- Michael Str?der E-Mail: michael at stroeder.com http://www.stroeder.com ---------------------------------------------------------------- Released 2.3.12 2010-08-05 Changes since 2.3.11: Lib/ * Removed tabs from various modules to make things work with python -tt. * Quick fix to ldif.is_dn() to let multi-valued RDNs pass as valid. Is too liberal in some corner-cases though... * Fix to ldif.is_dn() to allow dashes in attribute type (see SF#3020292) * ldap.open() now outputs a deprecation warning * module-wide locking is now limited to calling _ldap.initialize(). Still ldap.functions._ldap_function_call() is used to wrap all calls for writing debug log. Modules/ * New LDAP options available in OpenLDAP 2.4.18+ supported in LDAPObject.get/set_option(): ldap.OPT_X_KEEPALIVE_IDLE, ldap.OPT_X_KEEPALIVE_PROBES, ldap.OPT_X_KEEPALIVE_INTERVAL, ldap.OPT_X_TLS_CRLCHECK, ldap.OPT_X_TLS_CRLFILE Doc/ * Various small updates/improvements From nikos.the.gr33k at gmail.com Mon Aug 9 11:58:37 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 08:58:37 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> Message-ID: <905e8888-6664-4cae-8e57-27a1679a518a@y11g2000yqm.googlegroups.com> Please tell me that no matter what weird charhs has inside ic an still open thosie fiels and make the neccessary replacements. From python.koda at gmail.com Mon Aug 9 12:08:00 2010 From: python.koda at gmail.com (Alban Nona) Date: Mon, 9 Aug 2010 12:08:00 -0400 Subject: Subprocess Problem (Wait and while) Message-ID: Hi, I have some problem with my actual code. In fact, the script is done to work within nuke from the foundry which is a compositing software. Homever, I have some code difficulties as I quite new in the area. Here the deal: Im using subprocess command to copy some files into local directory, like this: cmd = ['xcopy', '/E', '/I', '/Q', '/Y', '%s' % _folder.replace('/', '\\'), '%s' % _temp.replace('/', '\\')] subprocess.Popen(cmd, shell=True) Its copying quite well. I have no problem with that. But, after the copy I would like to continue my code, but ONLY if the copy is done. If Im using a WAIT, its freezing the main program (nuke) until the copy in done. I want to avoid that. I also try "call" but same thing. Its freezing... I though about something like: while subprocess not finished: Do nothing else: Continue Program Like this its checking if the files is copying and do nothing until its done. I also tough: while os.listdir(src) != os.listdir(dst): Do nothing Else: Continue program But Im not sure its quite good solution. Someone can help me with this one please ? Thank you ! :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From darynr at gmail.com Mon Aug 9 12:11:37 2010 From: darynr at gmail.com (daryn) Date: Mon, 9 Aug 2010 09:11:37 -0700 (PDT) Subject: iter Message-ID: I'm just playing around with the iter function and I realize that I can use the iterator returned by it long after the original object has any name bound to it. Example: >>>a=[1,2,3,4] >>>b=iter(a) >>>b.next() 1 >>>a[1]=99 >>>a[3]=101 >>>del a >>>b.next() 99 >>>b.next() 3 >>>b.next() 101 it seems as if the original object is never being garbage collected even though there is no name bound to it. Does the name bound to the iterator object count as a reference to the original object for garbage collection purposes? Is there some way to retrieve/manipulate the original object via the iterator? Just trying to understand how this all works. -thanks for any help you can give daryn From __peter__ at web.de Mon Aug 9 12:21:39 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 18:21:39 +0200 Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> <905e8888-6664-4cae-8e57-27a1679a518a@y11g2000yqm.googlegroups.com> Message-ID: ????? wrote: > Please tell me that no matter what weird charhs has inside ic an still > open thosie fiels and make the neccessary replacements. Go back to 2.6 for the moment and defer learning about unicode until you're done with the conversion job. From tjreedy at udel.edu Mon Aug 9 12:28:17 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 12:28:17 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: On 8/9/2010 7:41 AM, saeed.gnu wrote: > "x is y" means "id(y) == id(y)" > "x is not y" means "id(x) != id(x)" > "x is not None" means "id(x) != id(None)" > > "x is not None" is a really silly statement!! Wrong. It is exactly right when that is what one means and is the STANDARD IDIOM. > because id(None) and id > of any constant object is not predictable! This is silly. The id of None and of any other object are predictably different. > I don't know whay people use "is" instead of "==". Because it is the right thing to do! > you should write "if x!=None" instead of "x is not None" Wrong. It is trivial to make a class whose objects compare == to None. -- Terry Jan Reedy From __peter__ at web.de Mon Aug 9 12:31:07 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 18:31:07 +0200 Subject: iter References: Message-ID: daryn wrote: > I'm just playing around with the iter function and I realize that I > can use the iterator returned by it long after the original object has > any name bound to it. Example: > >>>>a=[1,2,3,4] >>>>b=iter(a) >>>>b.next() > 1 >>>>a[1]=99 >>>>a[3]=101 >>>>del a >>>>b.next() > 99 >>>>b.next() > 3 >>>>b.next() > 101 > > it seems as if the original object is never being garbage collected > even though there is no name bound to it. Does the name bound to the > iterator object count as a reference to the original object for > garbage collection purposes? The listiterator object internally holds a reference to the list, but doesn't make it available to Python code. > Is there some way to retrieve/manipulate > the original object via the iterator? Not without dirty tricks (ctypes). > Just trying to understand how this all works. If you can read C look here: http://svn.python.org/view/python/branches/py3k/Objects/listobject.c?revision=81032&view=markup Peter From icanbob at gmail.com Mon Aug 9 12:49:57 2010 From: icanbob at gmail.com (bobicanprogram) Date: Mon, 9 Aug 2010 09:49:57 -0700 (PDT) Subject: xmlrpc and processes References: <3ec02745-4982-4f9e-955f-b771cdd64e19@d8g2000yqf.googlegroups.com> Message-ID: <83fa4bfc-2032-4486-b0f8-aa75d8c299b7@i13g2000yqd.googlegroups.com> On Aug 9, 2:50 am, iu2 wrote: > Hi, > > I have a SimpleXMLRPCServer running on one PC. > I need several ServerProxy-s talking to it, each one running on a > different PC. That is, I run on each PC a client application, that > talks to the one server using xml-rpc. > > Is the xml-rpc designed to work like this? If not, is there something > I can do to still be able to work with xml-rpc in this architucture? > > Thank you very much I don't have any direct experience with SimplXMLRPC, but depending on what you are actually trying to accomplish this technique might also work: http://www.icanprogram.com/06py/lesson1/lesson1.html Since SIMPL messaging is lower down on the stack than XML you could probably use SIMPL messages to carry XML structured content from client to server. bob From aahz at pythoncraft.com Mon Aug 9 12:52:20 2010 From: aahz at pythoncraft.com (Aahz) Date: 9 Aug 2010 09:52:20 -0700 Subject: Python parsing XML file problem with SAX References: Message-ID: In article , Stefan Behnel wrote: > >First of all: don't use SAX. Use ElementTree's iterparse() function. That >will shrink you code down to a simple loop in a few lines. Unless I'm missing something, that only helps if the final tree fits into memory. What do you suggest other than SAX if your XML file may be hundreds of megabytes? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From martin.hellwig at dcuktec.org Mon Aug 9 13:03:29 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 09 Aug 2010 18:03:29 +0100 Subject: xmlrpc and processes In-Reply-To: <3ec02745-4982-4f9e-955f-b771cdd64e19@d8g2000yqf.googlegroups.com> References: <3ec02745-4982-4f9e-955f-b771cdd64e19@d8g2000yqf.googlegroups.com> Message-ID: On 08/09/10 07:50, iu2 wrote: > Hi, > > I have a SimpleXMLRPCServer running on one PC. > I need several ServerProxy-s talking to it, each one running on a > different PC. That is, I run on each PC a client application, that > talks to the one server using xml-rpc. > > Is the xml-rpc designed to work like this? If not, is there something > I can do to still be able to work with xml-rpc in this architucture? > > Thank you very much Yeah should be no problem, you might get some ideas from reading this 'wrapper': http://code.google.com/p/dcuktec/source/browse/source/wrapped_xmlrpc_server/rpc.py -- mph From urban.dani at gmail.com Mon Aug 9 13:06:24 2010 From: urban.dani at gmail.com (Daniel Urban) Date: Mon, 9 Aug 2010 19:06:24 +0200 Subject: how to change a string into dictionary In-Reply-To: <4C5FCB80.7010701@amazon.com> References: <4C5FCB80.7010701@amazon.com> Message-ID: > a = "{'a':'1','b':'2'}" > how to change a into a dictionary ,says, a = {'a':'1','b':'2'} See also the ast.literal_eval function: http://docs.python.org/py3k/library/ast.html#ast.literal_eval Daniel From tjreedy at udel.edu Mon Aug 9 13:11:56 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 13:11:56 -0400 Subject: iter In-Reply-To: References: Message-ID: On 8/9/2010 12:11 PM, daryn wrote: > I'm just playing around with the iter function and I realize that I > can use the iterator returned by it long after the original object has > any name bound to it. Example: > >>>> a=[1,2,3,4] >>>> b=iter(a) >>>> b.next() > 1 >>>> a[1]=99 Changing a list while iterating through it is possible, sometimes useful, but error prone, especially with insert or delete. Changing a dict while iterating through it is prohibited since the iteration order depends on the exact internal structure. That in turn depends on the history of additions and deletions. >>>> a[3]=101 >>>> del a >>>> b.next() > 99 >>>> b.next() > 3 >>>> b.next() > 101 > > it seems as if the original object is never being garbage collected > even though there is no name bound to it. The fact that CPython currently deletes some things immediately is a current implementation detail, subject to change. > Does the name bound to the > iterator object count as a reference to the original object for > garbage collection purposes? Not quite. The iterator obviously has to have an internal reference, which amount to the almost the same thing. However, if you put the iterator in a list and deleted the name binding, both the iterator and list are still kept around. > Is there some way to retrieve/manipulate > the original object via the iterator? If you do dir(b), you will only see the standard __xx__ methods, most of which are inherited. Iterators can be written to expose an underlying object, if there is one, but some do not have one and this is not part of the simple iterator protocol. Hence builtin iterators for builtins do not do so. If one actually needed such lookup, this wrapper should work. class myiter(): def __init__(self, ob): self.ob = ob self.__itnext__ = iter(ob).__next__ def __iter__(self): return self def __next__(self): return self.__itnext__() it = myiter([1,2,3]) print (it.ob, list(it)) # [1, 2, 3] [1, 2, 3] > Just trying to understand how this all works. Keep experimenting. Python makes is so easy, especially with an edit window such as with IDLE and a Run command. I initially tried not defining myiter.__next__ and instead wrote: self.__next__ = iter(ob).__next__ but that does not work because special __xx__ methods are typically looked up on the class, not the instance. I know that but was not completely sure about this case. -- Terry Jan Reedy From tjreedy at udel.edu Mon Aug 9 13:15:24 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 13:15:24 -0400 Subject: Need mentor In-Reply-To: References: Message-ID: On 8/9/2010 2:31 AM, Ranjith Kumar wrote: > I have described the theme of my project here, Is this a class assignment or paid work? -- Terry Jan Reedy From tjreedy at udel.edu Mon Aug 9 13:24:11 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Aug 2010 13:24:11 -0400 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: On 8/9/2010 11:16 AM, Grant Edwards wrote: > IOW, the "Ugly American". [snip hate rant] Stereotypically bashing "Americans" is as ugly and obnoxious as bashing any other ethnic group. I have traveled the world and Americans are no worse, but are pretty much the same mix of good and bad. It is certainly off-topic and inappropriate for this group. -- Terry Jan Reedy From stefan_ml at behnel.de Mon Aug 9 13:31:20 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 09 Aug 2010 19:31:20 +0200 Subject: Python parsing XML file problem with SAX In-Reply-To: References: Message-ID: Aahz, 09.08.2010 18:52: > In article, > Stefan Behnel wrote: >> >> First of all: don't use SAX. Use ElementTree's iterparse() function. That >> will shrink you code down to a simple loop in a few lines. > > Unless I'm missing something, that only helps if the final tree fits into > memory. What do you suggest other than SAX if your XML file may be > hundreds of megabytes? Well, what about using ElementTree's iterparse() function in that case? That's what it's good at, and its cElementTree version is extremely fast. Stefan From ethan at stoneleaf.us Mon Aug 9 13:33:15 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 09 Aug 2010 10:33:15 -0700 Subject: Circular imports (again) In-Reply-To: References: Message-ID: <4C603BDB.4010103@stoneleaf.us> Frank Millman wrote: > Hi all > > I know the problems related to circular imports... > > It has just happened again. I have organised my code into three modules, > each representing a fairly cohesive functional area of the overall > application. However, there really are times when Module A wants to > invoke something from Module B, ditto for B and C, and ditto for C and A. I believe the issue arises when you have top-level code (module global code, or unindented code for the visual) that is calling the other module. If you keep your references to the other module in functions, you should be able to have your imports at module level. The below works fine. a.py ----- import b def spam(): b.eggs() def foo(): print "my circular-import-fu is strong!" # to amuse myself only!) ----- b.py ----- import a def eggs(): print 'sunnyside?' def ham(): a.foo() ----- If you put an in b.py, then you get: Traceback (most recent call last): File "", line 1, in File "a.py", line 1, in import b File "b.py", line 3, in a.spam() AttributeError: 'module' object has no attribute 'spam' Hope this helps. ~Ethan~ From nikos.the.gr33k at gmail.com Mon Aug 9 13:40:35 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 10:40:35 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <183ede24-6994-4010-9354-a437383e61a2@x21g2000yqa.googlegroups.com> <393c0b7f-aecf-46e1-9253-f49457ec3ed1@d17g2000yqb.googlegroups.com> <621d3779-a840-420d-af7b-2b1b6b8274ce@p7g2000yqa.googlegroups.com> <905e8888-6664-4cae-8e57-27a1679a518a@y11g2000yqm.googlegroups.com> Message-ID: On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > Please tell me that no matter what weird charhs has inside ic an still > > open thosie fiels and make the neccessary replacements. > > Go back to 2.6 for the moment and defer learning about unicode until you're > done with the conversion job. You are correct again! 3.2 caused the problem, i switched to 2.7 and now i donyt have that problem anymore. File is openign okey! it ALMOST convert correctly! # replace tags print ( 'replacing php tags and contents within' ) src_data = re.sub( '<\?(.*?)\?>', '', src_data ) it only convert the first instance of php tages and not the rest? But why? From thomas at jollybox.de Mon Aug 9 14:05:42 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 9 Aug 2010 20:05:42 +0200 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <201008092005.43602.thomas@jollybox.de> On Monday 09 August 2010, it occurred to ????? to exclaim: > On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > > ????? wrote: > > > Please tell me that no matter what weird charhs has inside ic an still > > > open thosie fiels and make the neccessary replacements. > > > > Go back to 2.6 for the moment and defer learning about unicode until > > you're done with the conversion job. > > You are correct again! 3.2 caused the problem, i switched to 2.7 and > now i donyt have that problem anymore. File is openign okey! > > it ALMOST convert correctly! > > # replace tags > print ( 'replacing php tags and contents within' ) > src_data = re.sub( '<\?(.*?)\?>', '', src_data ) > > it only convert the first instance of php tages and not the rest? > But why? http://docs.python.org/library/re.html#re.S You probably need to pass the re.DOTALL flag. From invalid at invalid.invalid Mon Aug 9 14:07:56 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 9 Aug 2010 18:07:56 +0000 (UTC) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: On 2010-08-09, Terry Reedy wrote: > On 8/9/2010 11:16 AM, Grant Edwards wrote: > >> IOW, the "Ugly American". > [snip hate rant] > > Stereotypically bashing "Americans" I wasn't bashing "Americans". I was making light of a certain type of American tourist commonly denoted by the phrase "ugly american". > is as ugly and obnoxious as bashing any other ethnic group. I have > traveled the world and Americans are no worse, but are pretty much > the same mix of good and bad. I've travelled the world as well, and I think that Americans do indeed make worse "tourists" than most others. I've seen a lot of European and Asian tourists in the US, and I've never seen from them the types of behavior for which the "Ugly American" tourists is famous. I've never been confronted here in the US by a Japanese tourist who thought that if he spoke Japanese to a store clerk loudly and slowing the clerk would understand. I've never seen European tourists trying to avoid eating "American" food or complaining about the electrical outlets. > It is certainly off-topic and inappropriate for this group. To that I'll confess. -- Grant Edwards grant.b.edwards Yow! I feel ... JUGULAR ... at gmail.com From pavlovevidence at gmail.com Mon Aug 9 14:08:16 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 9 Aug 2010 11:08:16 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> On Aug 9, 6:39?am, Ulrich Eckhardt wrote: > candide wrote: > > Python is an object oriented langage (OOL). The Python main > > implementation is written in pure and "old" C90. Is it for historical > > reasons? > > The fact that Python is OOP doesn't mean that the implementation of it has > to be written using an OOP language. > > Other than that, I'm actually surprised that nobody mentioned that Python > actually _is_ written in C++. Yes, it's restricted to a subset thereof that > is compatible to C, but you could also claim that it was written in a > subset of C compatible to C++. > > :) I highly doubt the Python source would build with a C++ compiler. C++ is "'mostly' 'backwards' compatible" with C insofar as you can pretty easily write C code that is also legal (and semantically equivalent) C++. But if you don't actively try to write code that is compatible with both languages, chances are the C code will invoke one of those "'minor' 'backwards' incompatibilies", the most common one being failure to cast a pointer. Carl Banks From lists at cheimes.de Mon Aug 9 14:27:20 2010 From: lists at cheimes.de (Christian Heimes) Date: Mon, 09 Aug 2010 20:27:20 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> Message-ID: > I highly doubt the Python source would build with a C++ compiler. > > C++ is "'mostly' 'backwards' compatible" with C insofar as you can > pretty easily write C code that is also legal (and semantically > equivalent) C++. But if you don't actively try to write code that is > compatible with both languages, chances are the C code will invoke one > of those "'minor' 'backwards' incompatibilies", the most common one > being failure to cast a pointer. Indeed: g++ -pthread -c -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -I. -IInclude -I./Include -DPy_BUILD_CORE -o Parser/parsetok.o Parser/parsetok.c Parser/parsetok.c: In function 'node* parsetok(tok_state*, grammar*, int, perrdetail*, int*)': Parser/parsetok.c:251: error: invalid conversion from 'void*' to 'char*' make: *** [Parser/parsetok.o] Error 1 Beside from several invalid conversions Python could most probably be compiled with a g++ compiler. I once worked on a patch to fix the conversion issues but Martin argued against it. There isn't really a point in cluttering the source with type casts. Christian From carey.tilden at gmail.com Mon Aug 9 14:27:40 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Mon, 9 Aug 2010 11:27:40 -0700 Subject: Need mentor In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 11:31 PM, Ranjith Kumar wrote: > I have?described?the theme of my project here, It appears all you did was describe your project. Did you ask a question or seek any specific guidance? Did I miss something? Carey From pavlovevidence at gmail.com Mon Aug 9 14:51:47 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 9 Aug 2010 11:51:47 -0700 (PDT) Subject: Circular imports (again) References: Message-ID: <1969caaa-f119-47e6-83d4-c57767bd8ea4@e15g2000yqo.googlegroups.com> On Aug 9, 6:19?am, "Frank Millman" wrote: > It has just happened again. I have organised my code into three modules, > each representing a fairly cohesive functional area of the overall > application. However, there really are times when Module A wants to invoke > something from Module B, ditto for B and C, and ditto for C and A. There's a dozen reasons why circular imports can go wrong. Can you describe the problem you're having getting them to work? If there's a traceback when you try to do it, cut-and-paste the traceback and relevant code here. If it's running, but you are not getting the behavior you expect, tell us what you expected to happen and what actually did. [snip] > So I think my main question is, is this a symptom of a flaw in my approach, > or is this something that all programmers bump into from time to time? I consider the need to resort to circular imports a red flag, not a manifest error. You say you are organizing the modules "functionally". I find that when I do that, I will occasionally get circular references, so I can believe you. I also find that in most such cases, reorganizing the modules according to "dependencies", so as to remove the circular import, makes it more confusing. Sometimes organizing by function makes more sense than organizing by dependency, and it's better to live with circular imports than to use a less- sensical organization. Carl Banks From bartc at freeuk.com Mon Aug 9 15:12:16 2010 From: bartc at freeuk.com (Bartc) Date: Mon, 9 Aug 2010 20:12:16 +0100 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: "D'Arcy J.M. Cain" wrote in message news:mailman.1735.1281185722.1673.python-list at python.org... > On Sat, 07 Aug 2010 13:48:32 +0200 > News123 wrote: >> It makes sense in assembly language and even in many byte code languages. >> It makes sense if you look at the internal representation of unsigned >> numbers (which might become an index) >> >> For a complete beginner common sense dictates differently and there >> might be confusion why the second element in a list has index 1. > > Would said beginner also be surprised that a newborn baby is zero years > old or would it be more natural to call them a one year old? Zero > based counting is perfectly natural. Depends whether you are counting (discrete) things, or measuring them (over a continuous range). You would start counting at 1, but start measuring from 0. -- Bartc From iamforufriends at gmail.com Mon Aug 9 15:14:44 2010 From: iamforufriends at gmail.com (SAKEERA) Date: Mon, 9 Aug 2010 12:14:44 -0700 (PDT) Subject: EARN FROM HOME... ITS REAL.... Message-ID: EARN FROM HOME... ITS REAL.... http://www.kamaraja.com/howitworks.htm?aff=naagaarjuna .......AND...... http://www.hyaffiliates.com?pid=d629b730 EARN FROM HOME... ITS REAL.... http://www.kamaraja.com/howitworks.htm?aff=naagaarjuna .......AND...... http://www.hyaffiliates.com?pid=d629b730 From nikos.the.gr33k at gmail.com Mon Aug 9 15:27:56 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 12:27:56 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <2b1da9fc-5c13-4301-8d0d-322eeac715ee@d17g2000yqb.googlegroups.com> Message-ID: On 8 ???, 20:29, John S wrote: > When replacing text in an HTML document with re.sub, you want to use > the re.S (singleline) option; otherwise your pattern won't match when > the opening tag is on one line and the closing is on another. Thats exactly the problem iam facing now with this statement. src_data = re.sub( '<\?(.*?)\?>', '', src_data ) you mean i have to switch it like this? src_data = re.S ( '<\?(.*?)\?>', '', src_data ) ? From rtw at rtw.me.uk Mon Aug 9 15:30:36 2010 From: rtw at rtw.me.uk (Rob Williscroft) Date: Mon, 9 Aug 2010 19:30:36 +0000 (UTC) Subject: dumping generator References: Message-ID: targetsmart wrote in news:cd83533b-f51e-4955-96c5-f8a10185bef1 @i18g2000pro.googlegroups.com in gmane.comp.python.general: > Right now if I want to dump the contents of a generator object I use , > a snip from a bigger block of code.. > > try: > while gen: print gen.next() > except StopIteration: > print "Done" > else: > raise > > is there a much simpler way ? print list( gen ) > > like for printing list we do > list = range(10) > print list > would print > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Rob. From zyzhu2000 at gmail.com Mon Aug 9 15:39:29 2010 From: zyzhu2000 at gmail.com (GZ) Date: Mon, 9 Aug 2010 12:39:29 -0700 (PDT) Subject: Sequential Object Store References: <6e21725a-e5c4-45be-81c4-5a9fd79df413@d8g2000yqf.googlegroups.com> Message-ID: <440b3d66-8936-4a02-89f9-86cb7f262969@d17g2000yqb.googlegroups.com> Hi Alex, On Aug 7, 6:54?pm, Alex Willmer wrote: > On Aug 7, 5:26?pm, GZ wrote: > > > I am wondering if there is a module that can persist a stream of > > objects without having to load everything into memory. (For this > > reason, I think Pickle is out, too, because it needs everything to be > > in memory.) > > From the pickle docs it looks like you could do something like: > > try: > ? ? import cPickle as pickle > except ImportError > ? ? import pickle > > file_obj = open('whatever', 'wb') > p = pickle.Pickler(file_obj) > > for x in stream_of_objects: > ? ? p.dump(x) > ? ? p.memo.clear() > > del p > file_obj.close() > > then later > > file_obj = open('whatever', 'rb') > p = pickle.Unpickler(file_obj) > > while True: > ? ? try: > ? ? ? ? x = p.load() > ? ? ? ? do_something_with(x) > ? ? except EOFError: > ? ? ? ? break > > Your loading loop could be wrapped in a generator function, so only > one object should be held in memory at once. This totally works! Thanks! From nikos.the.gr33k at gmail.com Mon Aug 9 15:53:21 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 12:53:21 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> Message-ID: <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> On 9 ???, 21:05, Thomas Jollans wrote: > On Monday 09 August 2010, it occurred to ????? to exclaim: > > > > > > > On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > > > ????? wrote: > > > > Please tell me that no matter what weird charhs has inside ic an still > > > > open thosie fiels and make the neccessary replacements. > > > > Go back to 2.6 for the moment and defer learning about unicode until > > > you're done with the conversion job. > > > You are correct again! 3.2 caused the problem, i switched to 2.7 and > > now i donyt have that problem anymore. File is openign okey! > > > it ALMOST convert correctly! > > > # replace tags > > print ( 'replacing php tags and contents within' ) > > src_data = re.sub( '<\?(.*?)\?>', '', src_data ) > > > it only convert the first instance of php tages and not the rest? > > But why? > > http://docs.python.org/library/re.html#re.S > > You probably need to pass the re.DOTALL flag. src_data = re.sub( '<\?(.*?)\?>', '', src_data, re.DOTALL ) like this? From clp2 at rebertia.com Mon Aug 9 15:55:26 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 9 Aug 2010 12:55:26 -0700 Subject: simple renaming files program In-Reply-To: References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: On Mon, Aug 9, 2010 at 3:19 AM, Peter Otten <__peter__ at web.de> wrote: > Chris Rebert wrote: > >> Hence (untested): >> from os import listdir, rename >> from os.path import isdir, join >> directory = raw_input("input file directory") >> s = raw_input("search for name") >> r = raw_input("replace name") >> >> for filename in listdir(directory): >> ? ? path = join(directory, filename) #paste the directory name on >> ? ? if isdir(path): continue #skip subdirectories (they're not files) >> ? ? newname = filename.replace(s, r) >> ? ? newpath = join(directory, newname) >> ? ? n = rename(path, newpath) >> ? ? print n > > Warning: I don't remember how Windows handles this, but unix will happily > perform os.rename("alpha/alpha.txt", "beta/beta.txt") and overwrite > beta/beta.txt with alpha/alpha.txt. > > I'd rather modify the filename before joining it with the directory. Er, unless I'm really missing something, that's what my code already does. Perhaps you misread it? The replace() clearly happens before the 2nd join(). I took special care to account for and avoid the potential problem you're talking about. Cheers, Chris -- http://blog.rebertia.com From nikos.the.gr33k at gmail.com Mon Aug 9 16:05:14 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 13:05:14 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> Message-ID: <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> On 9 ???, 10:07, ????? wrote: > Now the code looks as follows: > > ============================= > #!/usr/bin/python > > import re, os, sys > > id = 0 ?# unique page_id > > for currdir, files, dirs in os.walk('test'): > > ? ? ? ? for f in files: > > ? ? ? ? ? ? ? ? if f.endswith('php'): > > ? ? ? ? ? ? ? ? ? ? ? ? # get abs path to filename > ? ? ? ? ? ? ? ? ? ? ? ? src_f = join(currdir, f) > > ? ? ? ? ? ? ? ? ? ? ? ? # open php src file > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'reading from %s' % src_f ) > ? ? ? ? ? ? ? ? ? ? ? ? f = open(src_f, 'r') > ? ? ? ? ? ? ? ? ? ? ? ? src_data = f.read() ? ? ? ? ? ? # read contents of PHP file > ? ? ? ? ? ? ? ? ? ? ? ? f.close() > > ? ? ? ? ? ? ? ? ? ? ? ? # replace tags > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'replacing php tags and contents within' ) > ? ? ? ? ? ? ? ? ? ? ? ? src_data = re.sub( '', '', src_data ) > > ? ? ? ? ? ? ? ? ? ? ? ? # add ID > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'adding unique page_id' ) > ? ? ? ? ? ? ? ? ? ? ? ? src_data = ( '' % id ) + src_data > ? ? ? ? ? ? ? ? ? ? ? ? id += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? # add template variables > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'adding counter template variable' ) > ? ? ? ? ? ? ? ? ? ? ? ? src_data = src_data.replace('', '

color=green> ??????? ??????????: %(counter)d ' ) > > ? ? ? ? ? ? ? ? ? ? ? ? # rename old php file to new with .html extension > ? ? ? ? ? ? ? ? ? ? ? ? src_file = src_file.replace('.php', '.html') > > ? ? ? ? ? ? ? ? ? ? ? ? # open newly created html file for inserting data > ? ? ? ? ? ? ? ? ? ? ? ? print ( 'writing to %s' % dest_f ) > ? ? ? ? ? ? ? ? ? ? ? ? dest_f = open(src_f, 'w') > ? ? ? ? ? ? ? ? ? ? ? ? dest_f.write(src_data) ? ? ? ? ?# write contents > ? ? ? ? ? ? ? ? ? ? ? ? dest_f.close() > > I just tried to test it. I created a folder names 'test' in me 'd:\' > drive. > Then i have put to .php files inside form the original to test if it > would work ok for those too files before acting in the whole copy and > after in the original project. > > so i opened a 'cli' form my Win7 and tried > > D:\>convert.py > > D:\> > > Itsjust printed an empty line and nothign else. Why didn't even try to > open the folder and fiels within? > Syntactically it doesnt ghive me an error! > Somehting with os.walk() methos perhaps? Can you help in this too please? Now iam able to just convrt a single file 'd:\test\index.php' But these needs to be done for ALL the php files in every subfolder. > for currdir, files, dirs in os.walk('test'): > > ? ? ? ? for f in files: > > ? ? ? ? ? ? ? ? if f.endswith('php'): Should the above lines enter folders and find php files in each folder so to be edited? From __peter__ at web.de Mon Aug 9 16:06:50 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Aug 2010 22:06:50 +0200 Subject: simple renaming files program References: <6d288530-b6c9-495e-a084-4ea5a14ad011@y12g2000prb.googlegroups.com> Message-ID: Chris Rebert wrote: > On Mon, Aug 9, 2010 at 3:19 AM, Peter Otten <__peter__ at web.de> wrote: >> Warning: I don't remember how Windows handles this, but unix will happily >> perform os.rename("alpha/alpha.txt", "beta/beta.txt") and overwrite >> beta/beta.txt with alpha/alpha.txt. >> >> I'd rather modify the filename before joining it with the directory. > > Er, unless I'm really missing something, that's what my code already > does. Perhaps you misread it? The replace() clearly happens before the > 2nd join(). I took special care to account for and avoid the potential > problem you're talking about. You're right. Sorry for the confusion. Peter From torriem at gmail.com Mon Aug 9 16:06:51 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 09 Aug 2010 14:06:51 -0600 Subject: Circular imports (again) In-Reply-To: <1969caaa-f119-47e6-83d4-c57767bd8ea4@e15g2000yqo.googlegroups.com> References: <1969caaa-f119-47e6-83d4-c57767bd8ea4@e15g2000yqo.googlegroups.com> Message-ID: <4C605FDB.60208@gmail.com> On Aug 9, 6:19 am, "Frank Millman" wrote: > It has just happened again. I have organised my code into three modules, > each representing a fairly cohesive functional area of the overall > application. However, there really are times when Module A wants to invoke > something from Module B, ditto for B and C, and ditto for C and A. There are a number of ways to avoid circular imports, in order of my own preference: 1. Make common stuff a new module. So if A needs something from B, and vice versa, you must factor out the stuff and stick it in its own module. The fact that you have circular dependencies means that although things are cohesive, they are way too closely coupled. 2. Instead of having A refer directly to something in B (which would cause a circular dependency, have the caller pass in as a parameter to the function in A, whatever is needed from B. This could be just a variable, complex object, or even a function or method. Take advantage of the fact that everything in Python is a first-class object. 3. Take advantage of Python's dynamicism. Write an initializer function in A that allows you to tell it about B and C. In other words, you can pass B and C to some method in A and have it bind B and C to local attributes in A. Then you can call B and C's methods just fine from A since everything is looked up as it is called. From gagsl-py2 at yahoo.com.ar Mon Aug 9 16:14:26 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Aug 2010 17:14:26 -0300 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: En Mon, 09 Aug 2010 08:41:23 -0300, saeed.gnu escribi?: > "x is y" means "id(y) == id(y)" > "x is not y" means "id(x) != id(x)" No; consider this: py> id([])==id([]) True py> [] is [] False Comparing id's is the same as using the is operator only if you can guarantee that both operands are alive at the same time. -- Gabriel Genellina From python at mrabarnett.plus.com Mon Aug 9 16:17:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 21:17:25 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> Message-ID: <4C606255.9000201@mrabarnett.plus.com> ????? wrote: > On 9 ???, 21:05, Thomas Jollans wrote: >> On Monday 09 August 2010, it occurred to ????? to exclaim: >> >>> On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: >>>> ????? wrote: >>>>> Please tell me that no matter what weird charhs has inside ic an still >>>>> open thosie fiels and make the neccessary replacements. >>>> Go back to 2.6 for the moment and defer learning about unicode until >>>> you're done with the conversion job. >>> You are correct again! 3.2 caused the problem, i switched to 2.7 and >>> now i donyt have that problem anymore. File is openign okey! >>> it ALMOST convert correctly! >>> # replace tags >>> print ( 'replacing php tags and contents within' ) >>> src_data = re.sub( '<\?(.*?)\?>', '', src_data ) >>> it only convert the first instance of php tages and not the rest? >>> But why? >> http://docs.python.org/library/re.html#re.S >> >> You probably need to pass the re.DOTALL flag. > > src_data = re.sub( '<\?(.*?)\?>', '', src_data, re.DOTALL ) > > like this? re.sub doesn't accept a flags argument. You can put the flag inside the regex itself like this: src_data = re.sub(r'(?s)<\?(.*?)\?>', '', src_data) (Note that the abbreviation for re.DOTALL is re.S and the inline flag is '(?s)'. This is for historical reasons! :-)) From robert.kern at gmail.com Mon Aug 9 16:23:11 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 09 Aug 2010 15:23:11 -0500 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: <4C5FE994.1040103@sschwarzer.net> References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> <4C5FE994.1040103@sschwarzer.net> Message-ID: On 2010-08-09 06:42 , Stefan Schwarzer wrote: > Hi Steven, > > On 2010-08-09 10:21, Steven D'Aprano wrote: >> And that it's quite finicky about blank lines between methods and inside >> functions. Makes it hard to paste code directly into the interpreter. >> >> And that pasting doesn't strip out any leading prompts. It needs a good >> doctest mode. > > ipython [1] should help here: > > IPython 0.10 -- An enhanced Interactive Python. > ? -> Introduction and overview of IPython's features. > %quickref -> Quick reference. > help -> Python's own help system. > object? -> Details about 'object'. ?object also works, ?? prints more. > In [1]: %paste? > Type: Magic function > Base Class: > String Form:> > Namespace: IPython internal > File: /usr/lib/pymodules/python2.6/IPython/Magic.py > Definition: %paste(self, parameter_s='') > Docstring: > Allows you to paste& execute a pre-formatted code block from clipboard. > > The text is pulled directly from the clipboard without user > intervention. > > The block is dedented prior to execution to enable execution of method > definitions. '>' and '+' characters at the beginning of a line are > ignored, to allow pasting directly from e-mails, diff files and > doctests (the '...' continuation prompt is also stripped). The > executed block is also assigned to variable named 'pasted_block' for > later editing with '%edit pasted_block'. > > You can also pass a variable name as an argument, e.g. '%paste foo'. > This assigns the pasted block to variable 'foo' as string, without > dedenting or executing it (preceding>>> and + is still stripped) > > '%paste -r' re-executes the block previously entered by cpaste. > > IPython statements (magics, shell escapes) are not supported (yet). > > See also > -------- > cpaste: manually paste code into terminal until you mark its end. > > Unfortunatey, when I enter > > In [2]: %paste > > at the prompt it gives me (before I pasted anything) > > In [2]: %paste > ------------------------------------------------------------ > File "", line 1 > http://pypi.python.org/pypi/ipython/0.10 > ^ > SyntaxError: invalid syntax Yes, that's because you had that URL in your clipboard, not Python code. What were you expecting to happen? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From python at mrabarnett.plus.com Mon Aug 9 16:28:11 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 21:28:11 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> Message-ID: <4C6064DB.3090801@mrabarnett.plus.com> ????? wrote: > On 9 ???, 10:07, ????? wrote: >> Now the code looks as follows: >> >> ============================= >> #!/usr/bin/python >> >> import re, os, sys >> >> id = 0 # unique page_id >> >> for currdir, files, dirs in os.walk('test'): >> >> for f in files: >> >> if f.endswith('php'): >> [snip] >> >> I just tried to test it. I created a folder names 'test' in me 'd:\' >> drive. >> Then i have put to .php files inside form the original to test if it >> would work ok for those too files before acting in the whole copy and >> after in the original project. >> >> so i opened a 'cli' form my Win7 and tried >> >> D:\>convert.py >> >> D:\> >> >> Itsjust printed an empty line and nothign else. Why didn't even try to >> open the folder and fiels within? >> Syntactically it doesnt ghive me an error! >> Somehting with os.walk() methos perhaps? > > Can you help in this too please? > > Now iam able to just convrt a single file 'd:\test\index.php' > > But these needs to be done for ALL the php files in every subfolder. > >> for currdir, files, dirs in os.walk('test'): >> >> for f in files: >> >> if f.endswith('php'): > > Should the above lines enter folders and find php files in each folder > so to be edited? I'd start by commenting-out the lines which change the files and then add some more print statements to see which files it's finding. That might give a clue. Only when it's fixed and finding the correct files would I remove the additional print statements and then restore the commented lines. From nikos.the.gr33k at gmail.com Mon Aug 9 16:30:42 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Mon, 9 Aug 2010 13:30:42 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> Message-ID: <40382ef4-b443-4d5b-86f3-fd2490185ca9@z10g2000yqb.googlegroups.com> On 9 ???, 23:17, MRAB wrote: > ????? wrote: > > On 9 ???, 21:05, Thomas Jollans wrote: > >> On Monday 09 August 2010, it occurred to ????? to exclaim: > > >>> On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > >>>> ????? wrote: > >>>>> Please tell me that no matter what weird charhs has inside ic an still > >>>>> open thosie fiels and make the neccessary replacements. > >>>> Go back to 2.6 for the moment and defer learning about unicode until > >>>> you're done with the conversion job. > >>> You are correct again! 3.2 caused the problem, i switched to 2.7 and > >>> now i donyt have that problem anymore. File is openign okey! > >>> it ALMOST convert correctly! > >>> # replace tags > >>> print ( 'replacing php tags and contents within' ) > >>> src_data = re.sub( '<\?(.*?)\?>', '', src_data ) > >>> it only convert the first instance of php tages and not the rest? > >>> But why? > >>http://docs.python.org/library/re.html#re.S > > >> You probably need to pass the re.DOTALL flag. > > > ?src_data = re.sub( '<\?(.*?)\?>', '', src_data, re.DOTALL ) > > > like this? > > re.sub doesn't accept a flags argument. You can put the flag inside the > regex itself like this: > > ? ? ?src_data = re.sub(r'(?s)<\?(.*?)\?>', '', src_data) > > (Note that the abbreviation for re.DOTALL is re.S and the inline flag is > '(?s)'. This is for historical reasons! :-)) This is for the '.' to match any character including '\n' too right? so no matter if the php start tag and the end tag is in different lines still to be matched, correct? We nned the 'raw' string as well? why? The regex doens't cotnain backslashes. From bartc at freeuk.com Mon Aug 9 16:36:01 2010 From: bartc at freeuk.com (Bartc) Date: Mon, 9 Aug 2010 21:36:01 +0100 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: "Nobody" wrote in message news:pan.2010.08.07.15.23.59.515000 at nowhere.com... > On Sat, 07 Aug 2010 13:48:32 +0200, News123 wrote: > >>> "Common sense" is wrong. There are many compelling advantages to >>> numbering from zero instead of one: >>> >>> http://lambda-the-ultimate.org/node/1950 >> >> It makes sense in assembly language and even in many byte code languages. >> It makes sense if you look at the internal representation of unsigned >> numbers (which might become an index) > > It also makes sense mathematically. E.g. for an MxN array stored as a > 1-dimensional array, the element a[j][i] is at index > > j * N + i > > with zero-based indices but: > > (j-1) * N + (i-1) + 1 > = j * N + i - N > > with one-based indices. In other words, an extra offset to be added, in an expression already using a multiply and add, and which likely also needs an extra multiply and add to get the byte address of the element. (And often, the a[j][i] expression will be in a loop, which can be compiled to a pointer that just steps from one element to the next using a single add.) The indices i and j might anyway be user data which happens to be 1-based. And if the context is Python, I doubt whether the choice of 0-based over a 1-based makes that much difference in execution speed. (I've implemented languages that allow both 0 and 1-based indexing (and N-based for that matter). Both are useful. But my interpreted languages tend to use 1-based default indexing as it seems more natural and 'obvious') > > IOW, if a language uses one-based indices, it will inevitably end up > converting to and from zero-based indices under the hood, Sometimes. At the very low level (static, fixed array), the cost is absorbed into the address calculation. At a higher level, the cost is less significant, or there might be tricks to avoid the extra addition. > and may end up > forcing the user to do likewise if they need to do their own array > manipulation. Lots of things require this sort of calculation, eg. how many pages are needed to print 267 lines of text at 60 lines per page? These counts are 1-based so it's (L-1)/P+1 (integer divide), or 5 pages. If we switch to 0-based counting, it's just L/P ('266' lines require '4' pages), but who's going to explain that to the user? -- Bartc From nikos.the.gr33k at gmail.com Mon Aug 9 17:05:53 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 14:05:53 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> Message-ID: <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> On 9 ???, 23:28, MRAB wrote: > ????? wrote: > > On 9 ???, 10:07, ????? wrote: > >> Now the code looks as follows: > > >> ============================= > >> #!/usr/bin/python > > >> import re, os, sys > > >> id = 0 ?# unique page_id > > >> for currdir, files, dirs in os.walk('test'): > > >> ? ? ? ? for f in files: > > >> ? ? ? ? ? ? ? ? if f.endswith('php'): > > [snip] > > >> I just tried to test it. I created a folder names 'test' in me 'd:\' > >> drive. > >> Then i have put to .php files inside form the original to test if it > >> would work ok for those too files before acting in the whole copy and > >> after in the original project. > > >> so i opened a 'cli' form my Win7 and tried > > >> D:\>convert.py > > >> D:\> > > >> Itsjust printed an empty line and nothign else. Why didn't even try to > >> open the folder and fiels within? > >> Syntactically it doesnt ghive me an error! > >> Somehting with os.walk() methos perhaps? > > > Can you help in this too please? > > > Now iam able to just convrt a single file 'd:\test\index.php' > > > But these needs to be done for ALL the php files in every subfolder. > > >> for currdir, files, dirs in os.walk('test'): > > >> ? ? ? ? for f in files: > > >> ? ? ? ? ? ? ? ? if f.endswith('php'): > > > Should the above lines enter folders and find php files in each folder > > so to be edited? > > I'd start by commenting-out the lines which change the files and then > add some more print statements to see which files it's finding. That > might give a clue. Only when it's fixed and finding the correct files > would I remove the additional print statements and then restore the > commented lines. I did that, but it doesnt even get to the 'test' folder to search for the files! From torriem at gmail.com Mon Aug 9 17:13:04 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 09 Aug 2010 15:13:04 -0600 Subject: easy question on parsing python: "is not None" In-Reply-To: References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <4C606F60.1010004@gmail.com> On 08/09/2010 06:11 AM, saeed.gnu wrote: > On Aug 9, 3:41 pm, "saeed.gnu" wrote: >> "x is y" means "id(y) == id(y)" >> "x is not y" means "id(x) != id(x)" >> "x is not None" means "id(x) != id(None)" >> >> "x is not None" is a really silly statement!! because id(None) and id >> of any constant object is not predictable! I don't know whay people >> use "is" instead of "==". you should write "if x!=None" instead of "x >> is not None" > > Although small objects are unique in the memory (with a unique id) and > using "is" works ok, but that's not logical to compare id's when we > actually want to compare values! Sounds like you're confusing Python's namespace with variables. When I say: a = None I'm binding the None object to the a name. Thus a *is* None. While in theory "None" does have a value, doing "a is None" is much more explicit and clearer than "a == None" although perhaps the result is the same. In any event "a is None" is actually logical because that's what I'm normally interested in. Whether or not a is None. I don't really care about the value of None. From nikos.the.gr33k at gmail.com Mon Aug 9 17:15:30 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 14:15:30 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> Message-ID: <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> D:\>convert.py File "D:\convert.py", line 34 SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line 34, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details D:\> What does it refering too? what character cannot be identified? Line 34 is: src_data = src_data.replace( '', '

??????? ??????????: %(counter)d ' ) Also, for currdir, files, dirs in os.walk('test'): for f in files: if f.lower().endswith("php"): in the above lines should i state os.walk('test') or os.walk('d:\test') ? From sschwarzer at sschwarzer.net Mon Aug 9 17:43:08 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 09 Aug 2010 23:43:08 +0200 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> <4C5FE994.1040103@sschwarzer.net> Message-ID: <4C60766C.30401@sschwarzer.net> Hi Robert, On 2010-08-09 22:23, Robert Kern wrote: > On 2010-08-09 06:42 , Stefan Schwarzer wrote: >> Unfortunatey, when I enter >> >> In [2]: %paste >> >> at the prompt it gives me (before I pasted anything) >> >> In [2]: %paste >> ------------------------------------------------------------ >> File "", line 1 >> http://pypi.python.org/pypi/ipython/0.10 >> ^ >> SyntaxError: invalid syntax > > Yes, that's because you had that URL in your clipboard, not Python code. What > were you expecting to happen? I got that traceback as soon as I typed in "%paste" and pressed enter, without pasting anything in the terminal. I had assumed it works like :paste in Vim, activating a kind of "paste mode" where everything pasted into the terminal is modified as the help text suggests. Ok, I just noticed I should have actually _read_ the help text, not just scanned it. ;-) Sorry for the confusion. Stefan From sschwarzer at sschwarzer.net Mon Aug 9 17:47:14 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 09 Aug 2010 23:47:14 +0200 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: <4C60766C.30401@sschwarzer.net> References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> <4C5FE994.1040103@sschwarzer.net> <4C60766C.30401@sschwarzer.net> Message-ID: <4C607762.2080506@sschwarzer.net> On 2010-08-09 23:43, Stefan Schwarzer wrote: > I got that traceback as soon as I typed in "%paste" and > pressed enter, without pasting anything in the terminal. > I had assumed it works like :paste in Vim, activating a I meant ":set paste" of course. Stefan From tinnews at isbd.co.uk Mon Aug 9 17:52:39 2010 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Mon, 9 Aug 2010 22:52:39 +0100 Subject: mailbox.mbox not locking mbox properly Message-ID: <7u96j7-l8i.ln1@chris.zbmc.eu> I'm using the python mailbox class in a script that processes incoming mail and delivers it to various mbox format mailboxes. It appears that, although I am calling the lock method on the destination before writing to the mbox and calling unlock afterwards the locking isn't working correctly. I am reading the mail with mutt, if I deliver the mail direct using Postfix (i.e. bypassing my python script) mutt works perfectly and shows new mail arriving in the mailbox as expected with an 'N' flag beside it. If I deliver the mail with my python script I get an error from mutt saying "Mailbox was externally modified. Flags may be wrong.", or if I'm reading the mbox via NFS I get all sorts of strange errors (though again it works perfectly if Postfix writes to the mbox). So it seems that python's mailbox class locking isn't playing nicely with mutt's mailbox locking whereas postfix's locking does work correctly. Has anyone seen this problem before, and/or do I need to anything more than the following for the locking to work correctly:- # # # set up the mb for adding the new message, will create if it doesn't exist # dest = mailbox.mbox(mbName, factory=None) dest.lock() dest.add(m) # add the new message dest.flush() dest.unlock() Any help/comments most welcome -- Chris Green From python at mrabarnett.plus.com Mon Aug 9 18:32:53 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 23:32:53 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <40382ef4-b443-4d5b-86f3-fd2490185ca9@z10g2000yqb.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <98dc8799-0106-4166-b5e1-99c0ac143e0d@z10g2000yqb.googlegroups.com> <40382ef4-b443-4d5b-86f3-fd2490185ca9@z10g2000yqb.googlegroups.com> Message-ID: <4C608215.3080007@mrabarnett.plus.com> ????? wrote: > On 9 ???, 23:17, MRAB wrote: >> ????? wrote: >>> On 9 ???, 21:05, Thomas Jollans wrote: >>>> On Monday 09 August 2010, it occurred to ????? to exclaim: >>>>> On 9 ???, 19:21, Peter Otten <__pete... at web.de> wrote: >>>>>> ????? wrote: >>>>>>> Please tell me that no matter what weird charhs has inside ic an still >>>>>>> open thosie fiels and make the neccessary replacements. >>>>>> Go back to 2.6 for the moment and defer learning about unicode until >>>>>> you're done with the conversion job. >>>>> You are correct again! 3.2 caused the problem, i switched to 2.7 and >>>>> now i donyt have that problem anymore. File is openign okey! >>>>> it ALMOST convert correctly! >>>>> # replace tags >>>>> print ( 'replacing php tags and contents within' ) >>>>> src_data = re.sub( '<\?(.*?)\?>', '', src_data ) >>>>> it only convert the first instance of php tages and not the rest? >>>>> But why? >>>> http://docs.python.org/library/re.html#re.S >>>> You probably need to pass the re.DOTALL flag. >>> src_data = re.sub( '<\?(.*?)\?>', '', src_data, re.DOTALL ) >>> like this? >> re.sub doesn't accept a flags argument. You can put the flag inside the >> regex itself like this: >> >> src_data = re.sub(r'(?s)<\?(.*?)\?>', '', src_data) >> >> (Note that the abbreviation for re.DOTALL is re.S and the inline flag is >> '(?s)'. This is for historical reasons! :-)) > > This is for the '.' to match any character including '\n' too right? > so no matter if the php start tag and the end tag is in different > lines still to be matched, correct? > > We nned the 'raw' string as well? why? The regex doens't cotnain > backslashes. Yes it does; two of them! From jrmy.lnrd at gmail.com Mon Aug 9 18:34:36 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Mon, 9 Aug 2010 15:34:36 -0700 (PDT) Subject: Regular expression issue References: <10fb5379-4920-4c69-b3a0-1b6f393e4dcf@l6g2000yqb.googlegroups.com> <8871a477-e884-47ab-8bd9-e7b5df2711fe@5g2000yqz.googlegroups.com> Message-ID: <913a63f9-d8bd-40f1-b7b7-7d7b7fa480c6@c10g2000yqi.googlegroups.com> I have it now. Had to beat my head over it a couple times. Thanks everybody. From miki.tebeka at gmail.com Mon Aug 9 18:37:21 2010 From: miki.tebeka at gmail.com (Miki) Date: Mon, 9 Aug 2010 15:37:21 -0700 (PDT) Subject: I need a starter ptr writing python embedded in html. References: <3cc2a461-19f0-4aaf-9305-dde36fa2656c@v6g2000prd.googlegroups.com> Message-ID: <278a2eec-68d7-4ff9-81f1-623183988aff@i4g2000prf.googlegroups.com> > >> I'm ok in python but I haven't done too much with web pages. I have a web page > >> that is hand written in html that has about 1000 entries in a table and I want > >> to convert the table from entries like this > > >> ? ?

> >> ? ? ? > >> ? ? ? > >> ? ? ? > >> ? ? ? > >> ? ? ? > >> ? ? > > >> to > > >> ? ?SomePythonCall('Some Date String', > >> ? ? ? ? ? ? ? ? 'SomeTag', > >> ? ? ? ? ? ? ? ? 'localSubdir', > >> ? ? ? ? ? ? ? ? "http://www.example.com/remote/path/something.html", > >> ? ? ? ? ? ? ? ? 'Click', > >> ? ? ? ? ? ? ? ? 'Some Comment') > > >> Can someone tell me what I should look at to do this? Is mod_python where I > >> should start or are there things that are better? > > Have a look athttp://www.crummy.com/software/BeautifulSoup/. > > Thanks. But what I'm not seeing is any example of how to make this allowed to > generate the html at run time. Oh, I misunderstood you. You probably want one of the templating systems out there, such as Mako, Jinja2, Cheetah, ... Maybe http://cherrypy.org/wiki/intro/1 will be of help. All the best, -- Miki From python at mrabarnett.plus.com Mon Aug 9 18:43:17 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Aug 2010 23:43:17 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> Message-ID: <4C608485.1080703@mrabarnett.plus.com> ????? wrote: > D:\>convert.py > File "D:\convert.py", line 34 > SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line > 34, but no > encoding declared; see http://www.python.org/peps/pep-0263.html for > details > > D:\> > > What does it refering too? what character cannot be identified? > > Line 34 is: > > src_data = src_data.replace( '', '

color=green> ??????? ??????????: %(counter)d ' ) > Didn't you say that you're using Python 2.7 now? The default file encoding will be ASCII, but your file isn't ASCII, it contains Greek letters. Add the encoding line: # -*- coding: utf-8 -*- and check that the file is saved as UTF-8. > Also, > > for currdir, files, dirs in os.walk('test'): > > for f in files: > > if f.lower().endswith("php"): > > in the above lines > > should i state os.walk('test') or os.walk('d:\test') ? The path 'test' is relative to the current working directory. Is that D:\ for your script? If not, then it won't find the (correct) folder. It might be better to use an absolute path instead. You could use either: r'd:\test' (note that I've made it a raw string because it contains a backslash which I want treated as a literal backslash) or: 'd:/test' (Windows should accept a slash as well as of a backslash.) From aahz at pythoncraft.com Mon Aug 9 19:20:33 2010 From: aahz at pythoncraft.com (Aahz) Date: 9 Aug 2010 16:20:33 -0700 Subject: Python parsing XML file problem with SAX References: Message-ID: In article , Stefan Behnel wrote: >Aahz, 09.08.2010 18:52: >> In article, >> Stefan Behnel wrote: >>> >>> First of all: don't use SAX. Use ElementTree's iterparse() function. That >>> will shrink you code down to a simple loop in a few lines. >> >> Unless I'm missing something, that only helps if the final tree fits into >> memory. What do you suggest other than SAX if your XML file may be >> hundreds of megabytes? > >Well, what about using ElementTree's iterparse() function in that case? >That's what it's good at, and its cElementTree version is extremely fast. The docs say, "Parses an XML section into an element tree incrementally". Sure sounds like it retains the entire parsed tree in RAM. Not good. Again, how do you parse an XML file larger than your available memory using something other than SAX? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From atyazdi at ucdavis.edu Mon Aug 9 19:27:14 2010 From: atyazdi at ucdavis.edu (Anahita Yazdi) Date: Mon, 9 Aug 2010 16:27:14 -0700 Subject: Image histogram Message-ID: Hi, I was just wondering how would I be able to get some extra help regarding editing an image's histogram using python's module? I have modified a histogram of an image however I dont know how to apply the new histogram to the image and basically reload the image based on its new modified histogram instead of its own histogram? In the other words how should I make changes on an image's histogram in a way that the image recognizes the new histogram and gets changed? I need to somehow introduce a LUT for the image and use ".point(table)" function to reload the image however I am not sure how to make the right LUT from a modified histogram! Thanks for the help in advance, Anahita -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Mon Aug 9 19:39:44 2010 From: lists at cheimes.de (Christian Heimes) Date: Tue, 10 Aug 2010 01:39:44 +0200 Subject: Python parsing XML file problem with SAX In-Reply-To: References: Message-ID: Am 10.08.2010 01:20, schrieb Aahz: > The docs say, "Parses an XML section into an element tree incrementally". > Sure sounds like it retains the entire parsed tree in RAM. Not good. > Again, how do you parse an XML file larger than your available memory > using something other than SAX? The document at http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ explains it one way. The iterparser approach is ingenious but it doesn't work for every XML format. Let's say you have a 10 GB XML file with one million tags. An iterparser doesn't load the entire document. Instead it iterates over the file and yields (for example) one million ElementTrees for each tag and its children. You can get the nice API of ElementTree with the memory efficiency of a SAX parser if you obey "Listing 4". Christian From gherron at islandtraining.com Mon Aug 9 19:56:38 2010 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 09 Aug 2010 16:56:38 -0700 Subject: Image histogram In-Reply-To: References: Message-ID: <4C6095B6.4000509@islandtraining.com> On 08/09/2010 04:27 PM, Anahita Yazdi wrote: > Hi, > I was just wondering how would I be able to get some extra help > regarding editing an image's histogram using python's module? I have > modified a histogram of an image however I dont know how to apply the > new histogram to the image and basically reload the image based on its > new modified histogram instead of its own histogram? In the other > words how should I make changes on an image's histogram in a way that > the image recognizes the new histogram and gets changed? I need to > somehow introduce a LUT for the image and use ".point(table)" function > to reload the image however I am not sure how to make the right LUT > from a modified histogram! > Thanks for the help in advance, > Anahita This is a Python newsgroup, not an image processing news group. If you are asking for an algorithm to modify an image -- then you are on the wrong list, and you'd be better off asking on some image processing news group. If, on the other hand, you have an image processing algorithm in mind, then tell us about the algorithm, and we'll discuss how to implement it in Python. Gary Herron From no.email at nospam.invalid Mon Aug 9 20:02:26 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 09 Aug 2010 17:02:26 -0700 Subject: Image histogram References: Message-ID: <7x1va7ibcd.fsf@ruckus.brouhaha.com> Gary Herron writes: > This is a Python newsgroup, not an image processing news group. > If you are asking for an algorithm to modify an image.... I saw it as a question of how to do something using PIL. Seems ok to me. From ranjithtenz at gmail.com Mon Aug 9 20:44:36 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Tue, 10 Aug 2010 06:14:36 +0530 Subject: Python-list Digest, Vol 83, Issue 103 In-Reply-To: References: Message-ID: Hi Terry, > ---------- Forwarded message ---------- > From: Terry Reedy > To: python-list at python.org > Date: Mon, 09 Aug 2010 13:15:24 -0400 > Subject: Re: Need mentor > On 8/9/2010 2:31 AM, Ranjith Kumar wrote: > >> I have described the theme of my project here, >> > > Is this a class assignment or paid work? > I want to gain some scripting knowledge, so I asked my College senior student how to improvise the scripting knowledge he suggested me to start a new project and he himself gave me this idea. Its not paid work I just want to learn something. What i want my mentor to do is by suggesting me how to improve the coding standards and adding up some other features. Thanks for ur concerned Terry reedy. Awaiting for ur reply. -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Mon Aug 9 20:48:54 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 10 Aug 2010 12:48:54 +1200 Subject: Decorators without function In-Reply-To: References: Message-ID: <8cblevF28iU1@mid.individual.net> Vedran wrote: > @plot_decorator(fig_params1) > def plt(): > pylab.plot(..first graph data...) > pylab.plot(..second graph data..) > plt() You could do something like def call(f): f() @call @plot_decorator(fig_params1) def plt(): pylab.plot(..first graph data...) pylab.plot(..second graph data..) -- Greg From ranjithtenz at gmail.com Mon Aug 9 21:04:36 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Tue, 10 Aug 2010 06:34:36 +0530 Subject: Need mentor Message-ID: Hi Carey, ---------- Forwarded message ---------- From: Carey Tilden To: python-list at python.org Date: Mon, 9 Aug 2010 11:27:40 -0700 Subject: Re: Need mentor On Sun, Aug 8, 2010 at 11:31 PM, Ranjith Kumar wrote: > I have described the theme of my project here, >>It appears all you did was describe your project. Did you ask a question or seek any specific guidance? Did I miss something? I just seeking for guidance so i could come up with better result like adding new features and improve the coding style. Thats all why I described my project completely so anyone could guide me. I have three questions, 1) When the user logins into system the script should automatically starts running and only terminates the script when the user shut down or log out the system. 2) How to make the script running at the background(on the desktop)? 3) How to get the installed web browser`s list from a system and print it? Thanks in advance -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Mon Aug 9 21:18:35 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 10 Aug 2010 11:18:35 +1000 Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> Message-ID: <87iq3jz2ms.fsf@benfinney.id.au> "saeed.gnu" writes: > "x is y" means "id(y) == id(y)" > "x is not y" means "id(x) != id(x)" > "x is not None" means "id(x) != id(None)" No, the meanings are different. The behaviour might, or might not, be the same. The operators are different *because* the meanings are different. > "x is not None" is a really silly statement!! because id(None) and id > of any constant object is not predictable! The value returned from ?id? is not predictable; but it doesn't need to be predictable. It merely needs to obey the invariant that the identity of any given object won't change during the object's lifetime. -- \ ?You've got the brain of a four-year-old boy, and I'll bet he | `\ was glad to get rid of it.? ?Groucho Marx | _o__) | Ben Finney From gherron at islandtraining.com Mon Aug 9 21:23:38 2010 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 09 Aug 2010 18:23:38 -0700 Subject: Image histogram In-Reply-To: <7x1va7ibcd.fsf@ruckus.brouhaha.com> References: <7x1va7ibcd.fsf@ruckus.brouhaha.com> Message-ID: <4C60AA1A.4070804@islandtraining.com> On 08/09/2010 05:02 PM, Paul Rubin wrote: > Gary Herron writes: > >> This is a Python newsgroup, not an image processing news group. >> If you are asking for an algorithm to modify an image.... >> > I saw it as a question of how to do something using PIL. Seems ok to me. > A quote from the OP: "however I dont know how to apply the new histogram to the image" PIL has no such operation. I have no knowledge of any such operation. And frankly, I'm having a hard time imagining what "apply a histogram to the image" even means. (For instance if the original histogram says there are 30 pixels with some value, and the new histogram says there should be 20 pixels with that value -- which 10 do I replace, and with what do I replace them?) We can help him use PIL to read, manipulate, and write an image. But the actual manipulation he is requesting is so far unspecified. So I'll repeat: If he is looking for an algorithm -- I haven't got one. If he has an algorithm -- tell us about it, and we'll discuss implementing it in Python. Gary Herron From wuwei23 at gmail.com Mon Aug 9 21:24:29 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 9 Aug 2010 18:24:29 -0700 (PDT) Subject: I need a starter ptr writing python embedded in html. References: Message-ID: <2cb7fa82-dea8-40ac-9091-1a4d88dfe8cd@z34g2000pro.googlegroups.com> "Steven W. Orr" wrote: > I'm ok in python but I haven't done too much with web pages. I have a web page > that is hand written in html that has about 1000 entries in a table and I want > to convert the table [into html] Is the data coming from somewhere like a file or db? If so, I'd just use something simple like this html generator: http://pypi.python.org/pypi/html It's a very clever use of context managers to handle element nesting :) If the data doesn't change very often, I'd just write a simple script that parses the data source and builds a html page to server statically. If it does, it's not much extra to convert that to a WSGI script that returns the html string rather than creating a static file. I use this approach to produce a browseable table from a folder full of files with fixed-pattern names. Hope this helps. From sturlamolden at yahoo.no Mon Aug 9 21:51:44 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 9 Aug 2010 18:51:44 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> Message-ID: <60227fab-90e6-45b6-96b2-4fec205f3619@g33g2000yqc.googlegroups.com> On 9 Aug, 10:21, Steven D'Aprano wrote: > And that it's quite finicky about blank lines between methods and inside > functions. Makes it hard to paste code directly into the interpreter. The combination of editor, debugger and interpreter is what I miss most from Matlab. In Matlab we can have a function or script open in an editor, and use it directly from the interpreter. No need to reimport or anything: edit and invoke. It is also possible to paste data directly from the clipboard into variables in the interpreter. ipython does not have that annoying >>> prompt. From robert.kern at gmail.com Mon Aug 9 21:59:10 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 09 Aug 2010 20:59:10 -0500 Subject: Python -Vs- Ruby: A regexp match to the death! In-Reply-To: <4C60766C.30401@sschwarzer.net> References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> <7d185c6f-613a-4580-9f97-f55bc1966c85@z28g2000yqh.googlegroups.com> <4c5fba9e$0$28663$c3e8da3@news.astraweb.com> <4C5FE994.1040103@sschwarzer.net> <4C60766C.30401@sschwarzer.net> Message-ID: On 8/9/10 4:43 PM, Stefan Schwarzer wrote: > Hi Robert, > > On 2010-08-09 22:23, Robert Kern wrote: >> On 2010-08-09 06:42 , Stefan Schwarzer wrote: >>> Unfortunatey, when I enter >>> >>> In [2]: %paste >>> >>> at the prompt it gives me (before I pasted anything) >>> >>> In [2]: %paste >>> ------------------------------------------------------------ >>> File "", line 1 >>> http://pypi.python.org/pypi/ipython/0.10 >>> ^ >>> SyntaxError: invalid syntax >> >> Yes, that's because you had that URL in your clipboard, not Python code. What >> were you expecting to happen? > > I got that traceback as soon as I typed in "%paste" and > pressed enter, without pasting anything in the terminal. > I had assumed it works like :paste in Vim, activating a > kind of "paste mode" where everything pasted into the > terminal is modified as the help text suggests. %cpaste will do that. I implemented %paste because not all terminals will correctly paste arbitrary amounts of code correctly. Grabbing the text directly from the clipboard is less error-prone and removes redundant user interaction. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rene7705 at gmail.com Mon Aug 9 22:18:34 2010 From: rene7705 at gmail.com (Rene Veerman) Date: Tue, 10 Aug 2010 04:18:34 +0200 Subject: need a json representation of all members of any type of object, list or hashtable (php's var_dump) Message-ID: hi. for 2 open source components of mine that are used in debugging, i would like to capture the output generated by print for any variable. i'm new to python, so please excuse my noobishness. i don't know if objects can be json-ed as easy as lists and hash tables are by print. and i couldn't find how to capture the output generated by print into a string, so i can't use it with google appengine :( i'm in dire need of some expert advise here. -- --------------------------------- Greetings from Rene7705, My free open source webcomponents: ? http://code.google.com/u/rene7705/ ? http://mediabeez.ws/downloads (and demos) My music (i'm DJ firesnake) ? http://mediabeez.ws/music http://www.facebook.com/rene7705 --------------------------------- From benjamin.kaplan at case.edu Mon Aug 9 22:43:24 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 9 Aug 2010 19:43:24 -0700 Subject: need a json representation of all members of any type of object, list or hashtable (php's var_dump) In-Reply-To: References: Message-ID: On Mon, Aug 9, 2010 at 7:18 PM, Rene Veerman wrote: > hi. > > for 2 open source components of mine that are used in debugging, i > would like to capture the output generated by print for any variable. > i'm new to python, so please excuse my noobishness. > > i don't know if objects can be json-ed as easy as lists and hash > tables are by print. > and i couldn't find how to capture the output generated by print into > a string, so i can't use it with google appengine :( > > i'm in dire need of some expert advise here. > Use str() to turn stuff into strings. From python at mrabarnett.plus.com Mon Aug 9 22:49:47 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 10 Aug 2010 03:49:47 +0100 Subject: need a json representation of all members of any type of object, list or hashtable (php's var_dump) In-Reply-To: References: Message-ID: <4C60BE4B.3090902@mrabarnett.plus.com> Rene Veerman wrote: > hi. > > for 2 open source components of mine that are used in debugging, i > would like to capture the output generated by print for any variable. > i'm new to python, so please excuse my noobishness. > > i don't know if objects can be json-ed as easy as lists and hash > tables are by print. > and i couldn't find how to capture the output generated by print into > a string, so i can't use it with google appengine :( > > i'm in dire need of some expert advise here. > Lookup the 'StringIO' module (Python 2.x): from StringIO import StringIO import sys old_stdout = sys.stdout saved_output = StringIO() try: sys.stdout = saved_output print "Hello world!" finally: sys.stdout = old_stdout print saved_output.getvalue() From lepto.python at gmail.com Mon Aug 9 23:04:31 2010 From: lepto.python at gmail.com (oyster) Date: Tue, 10 Aug 2010 11:04:31 +0800 Subject: how to let shell.SendKeys use unicode on windows in python Message-ID: I want to use python to do some automatical operation on windows. the following is the code, which try to open a file with unicode characters in its filename in msword but I can't get it work correctly. Can anybody help me? if that is the shortcoming of WScript, is there any other way to do so in python? (I know there is something like autohotkey, but I am not willing to learn a new langauge ) thanks in advance import time import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate('winword') time.sleep(0.1) shell.SendKeys('%fo') # Alt+F, O time.sleep(0.1) path=r'c:\some unicode in file name.doc' shell.SendKeys(path) # fail on this line, no unicode appeared shell.SendKeys('{ENTER}') From wuwei23 at gmail.com Mon Aug 9 23:56:35 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 9 Aug 2010 20:56:35 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <35161a8e-d56a-4615-8ba8-a99a81da257a@q16g2000prf.googlegroups.com> Alex Barna wrote: > So what happens to this field (Windows GUI automation) ? Either someone cares enough to do something about it, or everyone just defaults to using AutoIT-like tools. Which Python implementation are you planning on contributing to? From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 00:12:10 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 04:12:10 GMT Subject: iter References: Message-ID: <4c60d19a$0$11121$c3e8da3@news.astraweb.com> On Mon, 09 Aug 2010 09:11:37 -0700, daryn wrote: > I'm just playing around with the iter function and I realize that I can > use the iterator returned by it long after the original object has any > name bound to it. Yes, the same as everything else in Python. Iterators aren't unique here. >>> a = [1,2,3] >>> b = [None, a, None] >>> id(a) == id(b[1]) # Same object, not a copy? True >>> del a >>> print b [None, [1, 2, 3], None] > it seems as if the original object is never being garbage collected even > though there is no name bound to it. Of course not. That would be a Bad Thing if Python garbage collected an object while other objects were still using it. Can you say "core dump"? > Does the name bound to the > iterator object count as a reference to the original object for garbage > collection purposes? No, but the iterator itself does. The technique is called *reference* counting, not "name counting". Each name is a reference, but not every reference is a name. > Is there some way to retrieve/manipulate the > original object via the iterator? Depends on the iterator. For the standard iterator created by iter(), I don't think so. But for a custom iterator type, there can be if you want: class MyIter(object): """Quick and dirty iterator.""" def __init__(self, data): self.data = data self.i = 0 def __iter__(self): return self def next(self): try: o = self.data[self.i] except IndexError: raise StopIteration self.i += 1 return o >>> it = MyIter([1,2,3,4]) >>> it.next() 1 >>> del it.data[1:3] >>> it.next() 4 -- Steven From navkirats at gmail.com Tue Aug 10 00:32:49 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Tue, 10 Aug 2010 10:02:49 +0530 Subject: favicon.ico problem Message-ID: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Hi guys, I am having this strange problem. I have programmed a very basic multiprocessing webserver using low level sockets. Each time the server receives a request it spawns a new process to handle the request. Now when through a web browser I type http://localhost:8001/ it automatically creates two processes: One process to server the '/' path and another one to serve the '/favicon.ico' path. I have not programmed it to serve the latter. Infact I dont even know where that name '/favicon.ico' comes from. Any insight into this weird behavior would be greatly appreciated. Regards, Nav From nad at acm.org Tue Aug 10 00:48:36 2010 From: nad at acm.org (Ned Deily) Date: Mon, 09 Aug 2010 21:48:36 -0700 Subject: favicon.ico problem References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Message-ID: In article <9F21F146-A43A-4108-962B-4DFA14E430E4 at gmail.com>, Navkirat Singh wrote: > I am having this strange problem. I have programmed a very basic > multiprocessing webserver using low level sockets. Each time the server > receives a request it spawns a new process to handle the request. Now when > through a web browser I type http://localhost:8001/ it automatically creates > two processes: One process to server the '/' path and another one to serve > the '/favicon.ico' path. I have not programmed it to serve the latter. Infact > I dont even know where that name '/favicon.ico' comes from. Any insight into > this weird behavior would be greatly appreciated. It's not the server's doing, it's the web browser requesting the favicon. See http://en.wikipedia.org/wiki/Favicon -- Ned Deily, nad at acm.org From John Tue Aug 10 00:53:10 2010 From: John (John) Date: Tue, 10 Aug 2010 00:53:10 -0400 Subject: File Manager in Tkinter Message-ID: As a learning exercise in Tkinter I htought about making a very simple and basic file manager for my own use. I tried searching google for any sample project and could not find anything. Not exactly sure how to start I tought I could ask here? I thought about making two listboxes one to list folders only the other files inside. I tried to make one listbox first but did not know how to list folders only. from Tkinter import * import os path = "D:\\" s = Scrollbar() L = Listbox() s.pack(side=RIGHT, fill=Y) L.pack(side=LEFT, fill=Y) s.config(command=L.yview) L.config(yscrollcommand=s.set) for filename in os.listdir(path): L.insert(END, filename) mainloop() Is there a way to list folders with images? Any suggestions or help how to proced would be appreciated. Thank you From chris.gonnerman at newcenturycomputers.net Tue Aug 10 00:56:15 2010 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 09 Aug 2010 23:56:15 -0500 Subject: [Python] favicon.ico problem In-Reply-To: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Message-ID: <4C60DBEF.505@newcenturycomputers.net> On 08/09/2010 11:32 PM, Navkirat Singh wrote: > I am having this strange problem. I have programmed a very basic multiprocessing webserver using low level sockets. Each time the server receives a request it spawns a new process to handle the request. Now when through a web browser I type http://localhost:8001/ it automatically creates two processes: One process to server the '/' path and another one to serve the '/favicon.ico' path. I have not programmed it to serve the latter. Infact I dont even know where that name '/favicon.ico' comes from. Any insight into this weird behavior would be greatly appreciated. > All modern browsers attempt to retrieve this file from any web server visited; it becomes the website's icon in any shortcut/deskcut, and appears on the address bar beside the URL. Short answer: You can safely ignore it. -- Chris. From clp2 at rebertia.com Tue Aug 10 01:07:09 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 9 Aug 2010 22:07:09 -0700 Subject: File Manager in Tkinter In-Reply-To: References: Message-ID: On Mon, Aug 9, 2010 at 9:53 PM, wrote: > As a learning exercise in Tkinter I htought about making a very simple > and basic file manager for my own use. I tried searching google for > any sample project and could not find anything. Not exactly ?sure how > to start I tought I could ask here? > > I thought about making two listboxes one to list folders only the > other files inside. I tried to make one listbox first but did not know > how to list folders only. os.path.isdir() tests a path for directory-ness. Check out the os.path std lib module generally: http://docs.python.org/library/os.path.html Cheers, Chris -- http://blog.rebertia.com From nikos.the.gr33k at gmail.com Tue Aug 10 01:11:44 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 9 Aug 2010 22:11:44 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> Message-ID: <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> On 10 ???, 01:43, MRAB wrote: > ????? wrote: > > D:\>convert.py > > ? File "D:\convert.py", line 34 > > SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line > > 34, but no > > ?encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor > > details > > > D:\> > > > What does it refering too? what character cannot be identified? > > > Line 34 is: > > > src_data = src_data.replace( '', '

> color=green> ??????? ??????????: %(counter)d ' ) > > Didn't you say that you're using Python 2.7 now? The default file > encoding will be ASCII, but your file isn't ASCII, it contains Greek > letters. Add the encoding line: > > ? ? ?# -*- coding: utf-8 -*- > > and check that the file is saved as UTF-8. > > > Also, > > > for currdir, files, dirs in os.walk('test'): > > > ? ?for f in files: > > > ? ? ? ? ? ?if f.lower().endswith("php"): > > > in the above lines > > > should i state ?os.walk('test') or ?os.walk('d:\test') ? > > The path 'test' is relative to the current working directory. Is that > D:\ for your script? If not, then it won't find the (correct) folder. > > It might be better to use an absolute path instead. You could use > either: > > ? ? ?r'd:\test' > > (note that I've made it a raw string because it contains a backslash > which I want treated as a literal backslash) or: > > ? ? ?'d:/test' > > (Windows should accept a slash as well as of a backslash.) I will try it as soon as i make another change that i missed: The ID number of each php page was contained in the old php code within this string PageID = some_number So instead of create a new ID number for eaqch page i have to pull out this number to store to the beginnign to the file as comment line, because it has direct relationship with the mysql database as in tracking the number of each webpage and finding the counter of it. # Grab the PageID contained within the php code and store it in id variable id = re.search( 'PageID = ', src_data ) How to tell Python to Grab that number after 'PageID = ' string and to store it in var id that a later use in the program? also i made another changewould something like this work: =============================== # open same php file for storing modified data print ( 'writing to %s' % dest_f ) f = open(src_f, 'w') f.write(src_data) f.close() # rename edited .php file to .html extension dst_f = src_f.replace('.php', '.html') os.rename( src_f, dst_f ) =============================== Because instead of creating a new .html file and inserting the desired data of the old php thus having two files(old php, and new html) i decided to open the same php file for writing that data and then rename it to html. Would the above code work? From gradyknotts at gmail.com Tue Aug 10 01:17:03 2010 From: gradyknotts at gmail.com (Grady Knotts) Date: Tue, 10 Aug 2010 00:17:03 -0500 Subject: Using the print command in Python3 Message-ID: <516FACB9-3BBE-424E-B406-DDE5F5039292@gmail.com> In earlier versions of Python I can do: print 'A', print 'B' to print everything on the same line: 'A B' But I don't know how to do this with Python3 I've been trying things like: print('A',) print('B') and it prints two different lines. So, do I get two different print statements to output on the same line? From zhxia at njnet.edu.cn Tue Aug 10 01:27:39 2010 From: zhxia at njnet.edu.cn (Xia, Zhen) Date: Tue, 10 Aug 2010 13:27:39 +0800 Subject: favicon.ico problem In-Reply-To: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Message-ID: <20100810132739.e2e17b33.zhxia@njnet.edu.cn> On Tue, 10 Aug 2010 10:02:49 +0530 Navkirat Singh wrote: > Hi guys, > > I am having this strange problem. I have programmed a very basic multiprocessing webserver using low level sockets. Each time the server receives a request it spawns a new process to handle the request. Now when through a web browser I type http://localhost:8001/ it automatically creates two processes: One process to server the '/' path and another one to serve the '/favicon.ico' path. I have not programmed it to serve the latter. Infact I dont even know where that name '/favicon.ico' comes from. Any insight into this weird behavior would be greatly appreciated. > > Regards, > Nav > -- > http://mail.python.org/mailman/listinfo/python-list Your server just need to return an HTTP 404 response for this 'favicon.ico' request. -- Xia, Zhen From benjamin.kaplan at case.edu Tue Aug 10 01:34:54 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 9 Aug 2010 22:34:54 -0700 Subject: Using the print command in Python3 In-Reply-To: <516FACB9-3BBE-424E-B406-DDE5F5039292@gmail.com> References: <516FACB9-3BBE-424E-B406-DDE5F5039292@gmail.com> Message-ID: On Mon, Aug 9, 2010 at 10:17 PM, Grady Knotts wrote: > In earlier versions of Python I can do: > ? ? ? ?print 'A', > ? ? ? ?print 'B' > to print everything on the same line: 'A B' > > But I don't know how to do this with Python3 > I've been trying things like: > ? ? ? ?print('A',) > ? ? ? ?print('B') > and it prints two different lines. > > So, do I get two different print statements to output on the same line? > >>> help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. From navkirats at gmail.com Tue Aug 10 01:54:26 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Tue, 10 Aug 2010 11:24:26 +0530 Subject: favicon.ico problem In-Reply-To: <20100810132739.e2e17b33.zhxia@njnet.edu.cn> References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> <20100810132739.e2e17b33.zhxia@njnet.edu.cn> Message-ID: On 10-Aug-2010, at 10:57 AM, Xia, Zhen wrote: > On Tue, 10 Aug 2010 10:02:49 +0530 > Navkirat Singh wrote: > >> Hi guys, >> >> I am having this strange problem. I have programmed a very basic multiprocessing webserver using low level sockets. Each time the server receives a request it spawns a new process to handle the request. Now when through a web browser I type http://localhost:8001/ it automatically creates two processes: One process to server the '/' path and another one to serve the '/favicon.ico' path. I have not programmed it to serve the latter. Infact I dont even know where that name '/favicon.ico' comes from. Any insight into this weird behavior would be greatly appreciated. >> >> Regards, >> Nav >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Your server just need to return an HTTP 404 response for this 'favicon.ico' request. > > > -- > Xia, Zhen > -- > http://mail.python.org/mailman/listinfo/python-list Thanks guys ! That explains it ! Nav From navkirats at gmail.com Tue Aug 10 01:59:58 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Tue, 10 Aug 2010 11:29:58 +0530 Subject: Using the print command in Python3 In-Reply-To: References: <516FACB9-3BBE-424E-B406-DDE5F5039292@gmail.com> Message-ID: On 10-Aug-2010, at 11:04 AM, Benjamin Kaplan wrote: > On Mon, Aug 9, 2010 at 10:17 PM, Grady Knotts wrote: >> In earlier versions of Python I can do: >> print 'A', >> print 'B' >> to print everything on the same line: 'A B' >> >> But I don't know how to do this with Python3 >> I've been trying things like: >> print('A',) >> print('B') >> and it prints two different lines. >> >> So, do I get two different print statements to output on the same line? >> > > >>>> help(print) > Help on built-in function print in module builtins: > > print(...) > print(value, ..., sep=' ', end='\n', file=sys.stdout) > > Prints the values to a stream, or to sys.stdout by default. > Optional keyword arguments: > file: a file-like object (stream); defaults to the current sys.stdout. > sep: string inserted between values, default a space. > end: string appended after the last value, default a newline. > -- > http://mail.python.org/mailman/listinfo/python-list One method of doing this: Use the join method of the string: print( "".join( [ 'A' , ' B' ] ) This will give you : 'AB' I have used extra spaces just for clarity. Hope this helps ! Nav From timr at probo.com Tue Aug 10 02:19:21 2010 From: timr at probo.com (Tim Roberts) Date: Mon, 09 Aug 2010 23:19:21 -0700 Subject: Microsoft lessening commitment to IronPython and IronRuby References: Message-ID: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Lawrence D'Oliveiro wrote: > >Frankly I never understood the point of IronPython and IronRuby. They seemed >like a desperate attempt to keep Dotnet relevant in the modern world of >dynamic languages. Looks like it was a failure. Yawn. I'm not sure that's really fair. The .NET Common Language Runtime is a vast and very useful class library, including two complete GUI systems. The thought was that IronPython and IronRuby would let people who were comfortable in those languages tap into the CLR. In the end, it seemed to me that writing an IronPython program was mostly an exercise of writing it in C# and then translating. .NET is just too "tuned" for C# and VB. Although IronPython was a good fit, it was just not a great fit. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From timr at probo.com Tue Aug 10 02:28:16 2010 From: timr at probo.com (Tim Roberts) Date: Mon, 09 Aug 2010 23:28:16 -0700 Subject: mailbox.mbox not locking mbox properly References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: tinnews at isbd.co.uk wrote: > >I'm using the python mailbox class in a script that processes incoming >mail and delivers it to various mbox format mailboxes. It appears >that, although I am calling the lock method on the destination before >writing to the mbox and calling unlock afterwards the locking isn't >working correctly. >... >So it seems that python's mailbox class locking isn't playing nicely >with mutt's mailbox locking whereas postfix's locking does work >correctly. Correct. The "dest.flush()" method creates a temporary file, copies the entire modified mailbox into it, removed the original file, and renames the temp file into place. The Postfix MDA, like most MDAs, just opens the existing file and appends the new data to it. >Has anyone seen this problem before, and/or do I need to anything more >than the following for the locking to work correctly:- It's not the locking. It's the flush mechanism. The mbox class doesn't know that the ONLY thing you did was an append. You might have modified other messages in the middle. If you want to do an append, you'll need to write your own subclass of mbox. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From stefan_ml at behnel.de Tue Aug 10 02:35:15 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 10 Aug 2010 08:35:15 +0200 Subject: Python parsing XML file problem with SAX In-Reply-To: References: Message-ID: Christian Heimes, 10.08.2010 01:39: > Am 10.08.2010 01:20, schrieb Aahz: >> The docs say, "Parses an XML section into an element tree incrementally". >> Sure sounds like it retains the entire parsed tree in RAM. Not good. >> Again, how do you parse an XML file larger than your available memory >> using something other than SAX? > > The document at > http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ explains it > one way. > > The iterparser approach is ingenious but it doesn't work for every XML > format. Let's say you have a 10 GB XML file with one million > tags. An iterparser doesn't load the entire document. Instead it > iterates over the file and yields (for example) one million ElementTrees > for each tag and its children. You can get the nice API of > ElementTree with the memory efficiency of a SAX parser if you obey > "Listing 4". In the very common case that you are interested in all children of the root element, it's even enough to intercept on the specific tag name (lxml.etree has an option for that, but an 'if' block will do just fine in ET) and just ".clear()" the child element at the end of the loop body. That results in very fast and simple code, but will leave the tags in the tree while only removing their content and attributes. Usually works well enough for several ten thousand elements, especially when using cElementTree. As usual, a bit of benchmarking will uncover the right way to do it in your case. That's also a huge advantage over SAX: iterparse code is much easier to tune into a streamlined loop body when you need it. Stefan From ldo at geek-central.gen.new_zealand Tue Aug 10 02:42:35 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 10 Aug 2010 18:42:35 +1200 Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Message-ID: In message <7fr16650meigqgmj8rh0n3a66q9r4j4eva at 4ax.com>, Tim Roberts wrote: > The .NET Common Language Runtime is a vast and very useful class library, > including two complete GUI systems. Used only by corporate code-cutter drones. Go on, name one creative thing which was ever done in Dotnet. From stefan_ml at behnel.de Tue Aug 10 03:02:18 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 10 Aug 2010 09:02:18 +0200 Subject: Microsoft lessening commitment to IronPython and IronRuby In-Reply-To: References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Message-ID: Lawrence D'Oliveiro, 10.08.2010 08:42: > In message<7fr16650meigqgmj8rh0n3a66q9r4j4eva at 4ax.com>, Tim Roberts wrote: > >> The .NET Common Language Runtime is a vast and very useful class library, >> including two complete GUI systems. > > Used only by corporate code-cutter drones. > > Go on, name one creative thing which was ever done in Dotnet. Erm, this is Microsoft. It's not about being creative, it's about selling stuff to users. Stefan From eckhardt at satorlaser.com Tue Aug 10 03:06:49 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 10 Aug 2010 09:06:49 +0200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> Message-ID: <9da7j7-pv2.ln1@satorlaser.homedns.org> Carl Banks wrote: > I highly doubt the Python source would build with a C++ compiler. As Christian showed, it doesn't. However, look around the sources a bit. There are lots of places where e.g. the returnvalue of malloc() (or, rather, the macro that resolves to something like it) is explicitly type-cast to the according pointer type. When asked on the developers' list, it was said that this was intended for compatibility with C++, e.g. in cases where people want to embed Python into their C++ projects. Of course, this contradicts Christian's statement that C++ compatibility wasn't considered useful enough. *shrug* Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 03:58:27 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 07:58:27 GMT Subject: Using the print command in Python3 References: Message-ID: <4c6106a3$0$28655$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 00:17:03 -0500, Grady Knotts wrote: > In earlier versions of Python I can do: > print 'A', > print 'B' > to print everything on the same line: 'A B' > > But I don't know how to do this with Python3 I've been trying things > like: > print('A',) > print('B') > and it prints two different lines. > > So, do I get two different print statements to output on the same line? print("Hello", end=' ') print("world") outputs: Hello world -- Steven From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 04:04:17 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 08:04:17 GMT Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Message-ID: <4c610801$0$28655$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 18:42:35 +1200, Lawrence D'Oliveiro wrote: > In message <7fr16650meigqgmj8rh0n3a66q9r4j4eva at 4ax.com>, Tim Roberts > wrote: > >> The .NET Common Language Runtime is a vast and very useful class >> library, including two complete GUI systems. > > Used only by corporate code-cutter drones. > > Go on, name one creative thing which was ever done in Dotnet. Not just Dotnet, but Python on Dotnet. http://www.python.org/about/success/resolver/ http://blog.jonudell.net/2007/09/27/first-look-at-resolver-an-ironpython-based-spreadsheet/ -- Steven From ldo at geek-central.gen.new_zealand Tue Aug 10 04:05:12 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 10 Aug 2010 20:05:12 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message <56a18e2b-4967-4a63-852e-1eb53bb6e561 at j8g2000yqd.googlegroups.com>, Alex Barna wrote: > So what happens to this field (Windows GUI automation) ? Can?t understand the point to it. ?GUI automation? is a contradiction in terms, because a GUI is designed for use by humans to do manual tasks, not ones that can be automated. Tasks that can be automated are most easily, flexibly, and above all reliably, done via command lines and other such scripting interfaces. From greg.ewing at canterbury.ac.nz Tue Aug 10 04:07:06 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 10 Aug 2010 20:07:06 +1200 Subject: Microsoft lessening commitment to IronPython and IronRuby In-Reply-To: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> Message-ID: <8ccf4kF38mU1@mid.individual.net> Tim Roberts wrote: > I'm not sure that's really fair. The .NET Common Language Runtime is a > vast and very useful class library, including two complete GUI systems. The > thought was that IronPython and IronRuby would let people who were > comfortable in those languages tap into the CLR. Is there any way for a non-.NET program to access a .NET library? Or is it necessary to drink the entire bottle of .NET kool-aid? -- Greg From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 04:20:35 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 08:20:35 GMT Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> Message-ID: <4c610bd2$0$28655$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 20:07:06 +1200, Gregory Ewing wrote: > Tim Roberts wrote: > >> I'm not sure that's really fair. The .NET Common Language Runtime is a >> vast and very useful class library, including two complete GUI systems. >> The thought was that IronPython and IronRuby would let people who were >> comfortable in those languages tap into the CLR. > > Is there any way for a non-.NET program to access a .NET library? Or is > it necessary to drink the entire bottle of .NET kool-aid? http://www.mono-project.com/Main_Page -- Steven From stefan_ml at behnel.de Tue Aug 10 04:32:43 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 10 Aug 2010 10:32:43 +0200 Subject: Microsoft lessening commitment to IronPython and IronRuby In-Reply-To: <4c610801$0$28655$c3e8da3@news.astraweb.com> References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <4c610801$0$28655$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano, 10.08.2010 10:04: > On Tue, 10 Aug 2010 18:42:35 +1200, Lawrence D'Oliveiro wrote: >> Go on, name one creative thing which was ever done in Dotnet. > > Not just Dotnet, but Python on Dotnet. > > http://www.python.org/about/success/resolver/ At the very end of that article, I found this statement: "Resolver One is Windows only" This sounds like a major drawback to me. It might be an acceptable "early project priority" if the app is only targeting the desktop, but this system additionally claims to be a "web-accessible spreadsheet". If this is supposed to run on a server, it means that it will always suffer from the "headless click-here-to-continue" problem. It might not be too hard to port the app to Mono, but the rather explicit claim above doesn't make me feel very comfortable about that upgrade path... Stefan From eric.brunel at pragmadev.com Tue Aug 10 04:40:53 2010 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 10 Aug 2010 10:40:53 +0200 Subject: File Manager in Tkinter References: Message-ID: In article , John wrote: > As a learning exercise in Tkinter I htought about making a very simple > and basic file manager for my own use. I tried searching google for > any sample project and could not find anything. Not exactly sure how > to start I tought I could ask here? > > I thought about making two listboxes one to list folders only the > other files inside. I tried to make one listbox first but did not know > how to list folders only. You just have to filter them explicitely by using os.path.isdir on each file name. > from Tkinter import * > import os > path = "D:\\" > > > s = Scrollbar() > L = Listbox() > > s.pack(side=RIGHT, fill=Y) > L.pack(side=LEFT, fill=Y) > > s.config(command=L.yview) > L.config(yscrollcommand=s.set) > > for filename in os.listdir(path): Add here: if os.path.isdir(os.path.join(path, filename)): > L.insert(END, filename) > > mainloop() > > > > Is there a way to list folders with images? AFAIK, not with a Listbox. You can do it with a Canvas, but it's much more complicated than using a Listbox, so maybe you should try to make your Listbox-only version works first. > Any suggestions or help how to proced would be appreciated. > > Thank you Good luck! From steve-REMOVE-THIS at cybersource.com.au Tue Aug 10 04:49:21 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 10 Aug 2010 08:49:21 GMT Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4c611291$0$28655$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 20:05:12 +1200, Lawrence D'Oliveiro wrote: > In message > <56a18e2b-4967-4a63-852e-1eb53bb6e561 at j8g2000yqd.googlegroups.com>, Alex > Barna wrote: > >> So what happens to this field (Windows GUI automation) ? > > Can?t understand the point to it. ?GUI automation? is a contradiction in > terms, because a GUI is designed for use by humans to do manual tasks, > not ones that can be automated. There have been plenty of systems for recording user actions and playing them back. They're very useful at times. http://en.wikipedia.org/wiki/Macro_recorder http://en.wikipedia.org/wiki/Macro_(computer_science) You might even have heard of one of them... Emacs. I hear that it's moderately popular among Linux users. http://www.linuxjournal.com/article/3769 > Tasks that can be automated are most easily, flexibly, and above all > reliably, done via command lines and other such scripting interfaces. That's a matter of opinion, and it clearly depends on the nature of the GUI and CLI, as well as what task you're trying to automate. -- Steven From tzuchien.chiu at gmail.com Tue Aug 10 04:52:54 2010 From: tzuchien.chiu at gmail.com (Chien) Date: Tue, 10 Aug 2010 01:52:54 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <35161a8e-d56a-4615-8ba8-a99a81da257a@q16g2000prf.googlegroups.com> Message-ID: <2eea0548-2d5f-48ed-b597-009df537bdb1@j8g2000yqd.googlegroups.com> On Aug 10, 5:56?am, alex23 wrote: > Alex Barna wrote: > > So what happens to this field (Windows GUI automation) ? > > Either someone cares enough to do something about it, or everyone just > defaults to using AutoIT-like tools. There were a lot of development but then all ceased, except pywinauto has a final release in April, but really low community activity. Does it mean AutoIt has much more advantages than Python tools (which I have not realized) ? > Which Python implementation are you planning on contributing to? I'd say pywinauto. It's more O-O than the other tools. Excerpt from its homepage (http://pywinauto.openqa.org/): Most other tools are not object oriented you end up writing stuff like: window = findwindow(title = "Untitled - Notepad", class = "Notepad") SendKeys(window, "%OF") # Format -> Font fontdialog = findwindow("title = "Font") buttonClick(fontdialog, "OK") I was hoping to create something more userfriendly (and pythonic): win = app.UntitledNotepad win.MenuSelect("Format->Font") app.Font.OK.Click() Alex Barna From tinnews at isbd.co.uk Tue Aug 10 05:01:11 2010 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Tue, 10 Aug 2010 10:01:11 +0100 Subject: mailbox.mbox not locking mbox properly References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: Tim Roberts wrote: > tinnews at isbd.co.uk wrote: > > > >I'm using the python mailbox class in a script that processes incoming > >mail and delivers it to various mbox format mailboxes. It appears > >that, although I am calling the lock method on the destination before > >writing to the mbox and calling unlock afterwards the locking isn't > >working correctly. > >... > >So it seems that python's mailbox class locking isn't playing nicely > >with mutt's mailbox locking whereas postfix's locking does work > >correctly. > > Correct. The "dest.flush()" method creates a temporary file, copies the > entire modified mailbox into it, removed the original file, and renames the > temp file into place. > Yes, I just took a look at the mailbox.py code and it does exactly that which of course screws up just about any normal MUA looking at the mbox. Grrrrrr! > The Postfix MDA, like most MDAs, just opens the existing file and appends > the new data to it. > > >Has anyone seen this problem before, and/or do I need to anything more > >than the following for the locking to work correctly:- > > It's not the locking. It's the flush mechanism. The mbox class doesn't > know that the ONLY thing you did was an append. You might have modified > other messages in the middle. If you want to do an append, you'll need to > write your own subclass of mbox. OK, thanks. In reality I can probably just use straightforward file reading and writing as the *only* thing I will ever be doing is to append a message to a mailbox file. I think there should be a big warning in the mailbox documentation to this effect as doing it the way that Python's mailbox class does it will break all sorts of things. There should maybe be a specific 'append' method. -- Chris Green From eckhardt at satorlaser.com Tue Aug 10 05:01:26 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 10 Aug 2010 11:01:26 +0200 Subject: delegate functions to member Message-ID: <64h7j7-r73.ln1@satorlaser.homedns.org> Hi! I have an extension module (a plugin written with Boost.Python) and around that a wrapper class that adapts a few things. Since the module is a plugin, there are multiple implementations of this. What I'm currently doing is this: plugin = __import__(plugin_name) class PluginWrapper(plugin.PluginClass): ... This means that the definition of class PluginWrapper actually depends on the previously loaded module. What I would like to do is to define the wrapper just once and instead pass the plugin module to the constructor: class PluginWrapper(object): ... plugin = __import__(plugin_name) instance = PluginWrapper(plugin) Now, I use the wrapper to make some function more friendly (e.g. default parameters, keyword-parameters, wrapping raw handles) but I want other functions from the baseclass to remain untouched. If I use a baseclass, this lookup is automatic. However, when I pass the instance to the constructor, I have to store it in a member, and then I have to add code for every function only to delegate it to that member. Is there an easy and generic way out of this? Thanks! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From chris at simplistix.co.uk Tue Aug 10 05:04:26 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 10 Aug 2010 10:04:26 +0100 Subject: MailingLogger 3.3.3 Released! Message-ID: <4C61161A.3020205@simplistix.co.uk> I'm pleased to announce a new release of Mailinglogger. Mailinglogger provides two handlers for the standard python logging framework that enable log entries to be emailed either as the entries are logged or as a summary at the end of the running process. The handlers have the following features: - customisable and dynamic subject lines for emails sent - emails sent with an X-Mailer header for easy filtering - flood protection to ensure the number of emails sent is not excessive - support for SMTP servers that require authentication - fully documented and tested The latest releases of ZConfig provides a great way to configure the python logging framework without having to resort to the appalling .ini-based configuration stuff: >>> from ZConfig import configureLoggers >>> configureLoggers(''' ... ... level INFO ... ... PATH STDOUT ... format %(levelname)s %(name)s %(message)s ... ... ... ''') This release and the previous release fix some problems with interpolating non-text objects into log messages and running the tests in non-GMT timezones. For more information, please see: http://www.simplistix.co.uk/software/python/mailinglogger or http://pypi.python.org/pypi/mailinglogger cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From mail at timgolden.me.uk Tue Aug 10 05:08:37 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 10 Aug 2010 10:08:37 +0100 Subject: Subprocess Problem (Wait and while) In-Reply-To: References: Message-ID: <4C611715.8080005@timgolden.me.uk> On 09/08/2010 17:08, Alban Nona wrote: > Hi, > > I have some problem with my actual code. > In fact, the script is done to work within nuke from the foundry which is a > compositing software. > Homever, I have some code difficulties as I quite new in the area. > > Here the deal: > Im using subprocess command to copy some files into local directory, like > this: > > cmd = ['xcopy', '/E', '/I', '/Q', '/Y', '%s' % _folder.replace('/', > '\\'), '%s' % _temp.replace('/', '\\')] > subprocess.Popen(cmd, shell=True) > > Its copying quite well. I have no problem with that. But, after the copy I > would like to continue my code, but ONLY if the copy is done. > If Im using a WAIT, its freezing the main program (nuke) until the copy in > done. I want to avoid that. I also try "call" but same thing. Its > freezing... > I though about something like: > > while subprocess not finished: > Do nothing > else: > Continue Program Have a look at the .poll method of subprocess.Popen > > Like this its checking if the files is copying and do nothing until its > done. I also tough: > > while os.listdir(src) != os.listdir(dst): > Do nothing > Else: > Continue program That's unlikely to work because Windows will create the directory entry first (and at the complete size) and will then fill it in as it copies. TJG From __peter__ at web.de Tue Aug 10 05:12:25 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 11:12:25 +0200 Subject: delegate functions to member References: <64h7j7-r73.ln1@satorlaser.homedns.org> Message-ID: Ulrich Eckhardt wrote: > Hi! > > I have an extension module (a plugin written with Boost.Python) and around > that a wrapper class that adapts a few things. Since the module is a > plugin, there are multiple implementations of this. What I'm currently > doing is this: > > plugin = __import__(plugin_name) > > class PluginWrapper(plugin.PluginClass): > ... > > This means that the definition of class PluginWrapper actually depends on > the previously loaded module. What I would like to do is to define the > wrapper just once and instead pass the plugin module to the constructor: > > class PluginWrapper(object): > ... > plugin = __import__(plugin_name) > instance = PluginWrapper(plugin) > > > Now, I use the wrapper to make some function more friendly (e.g. default > parameters, keyword-parameters, wrapping raw handles) but I want other > functions from the baseclass to remain untouched. If I use a baseclass, > this lookup is automatic. However, when I pass the instance to the > constructor, I have to store it in a member, and then I have to add code > for every function only to delegate it to that member. > > Is there an easy and generic way out of this? Use getattr() >>> class W(object): ... def __init__(self, wrapped): self._wrapped = wrapped ... def __getattr__(self, name): ... return getattr(self._wrapped, name) ... >>> class A(object): ... def hello(self): print "hello" ... >>> a = A() >>> w = W(a) >>> w.hello() hello However, with newsytle classes this doesn't work for __special__ methods >>> w.__str__() '<__main__.W object at 0x7f04ef2d4c50>' Peter From frank at chagford.com Tue Aug 10 05:13:06 2010 From: frank at chagford.com (Frank Millman) Date: Tue, 10 Aug 2010 11:13:06 +0200 Subject: Circular imports (again) References: Message-ID: "Frank Millman" wrote in message news:i3ov9e$dug$1 at dough.gmane.org... > Hi all > > I know the problems related to circular imports, and I know some of the > techniques to get around them. However, I find that I bump my head into > them from time to time, which means, I guess, that I have not fully > understood how to organise my code so that I avoid them in the first > place. > [...] > > So I think my main question is, is this a symptom of a flaw in my > approach, or is this something that all programmers bump into from time to > time? > Thanks for the replies. All good info, but it was Ethan that put me onto the right track. I omitted to mention one thing originally, as I did not think it important, but it turns out to be crucial. My code is organised into three 'packages', not 'modules'. To reproduce my situation, I did some tests with the following hierarchy - top/ a.py /bb __init__.py b.py /cc __init__.py c.py a.py ---- import bb.b import cc.c bb.b.foo() cc.c.foo() b.py ---- import cc.c def foo(): print 'in b.foo, call c.bar' cc.c.bar() def bar(): print ' bar in b' c.py ---- import bb.b def foo(): print 'in c.foo, call b.bar' bb.b.bar() def bar(): print ' bar in c' If I run 'a.py', I get the correct result - in b.foo, call c.bar bar in c in c.foo, call b.bar bar in b I changed 'a.py' - a.py ---- from bb import b from cc import c b.foo() c.foo() It still worked. Next I changed 'b.py' - b.py ---- from cc import c def foo(): print 'in b.foo, call c.bar' c.bar() def bar(): print ' bar in b' It still worked. Then I changed 'c.py' - c.py ---- from bb import b def foo(): print 'in b.foo, call c.bar' b.bar() def bar(): print ' bar in b' Now I get the following traceback - Traceback (most recent call last): File "F:\dd\a.py", line 1, in from bb import b File "F:\dd\bb\b.py", line 1, in from cc import c File "F:\dd\cc\c.py", line 1, in from bb import b ImportError: cannot import name b Now that I understand this, I can work around my problem by using fully-qualified module names. But it would be interesting to know the underlying reason for this behaviour. I am using python 2.6.2. Thanks for any insights. Frank From clp2 at rebertia.com Tue Aug 10 05:19:10 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 10 Aug 2010 02:19:10 -0700 Subject: delegate functions to member In-Reply-To: <64h7j7-r73.ln1@satorlaser.homedns.org> References: <64h7j7-r73.ln1@satorlaser.homedns.org> Message-ID: On Tue, Aug 10, 2010 at 2:01 AM, Ulrich Eckhardt wrote: > Hi! > > I have an extension module (a plugin written with Boost.Python) and around > that a wrapper class that adapts a few things. Since the module is a > plugin, there are multiple implementations of this. What I'm currently > doing is this: > > ?plugin = __import__(plugin_name) > > ?class PluginWrapper(plugin.PluginClass): > ? ? ... > > This means that the definition of class PluginWrapper actually depends on > the previously loaded module. What I would like to do is to define the > wrapper just once and instead pass the plugin module to the constructor: > > ?class PluginWrapper(object): > ? ?... > ?plugin = __import__(plugin_name) > ?instance = PluginWrapper(plugin) > > > Now, I use the wrapper to make some function more friendly (e.g. default > parameters, keyword-parameters, wrapping raw handles) but I want other > functions from the baseclass to remain untouched. If I use a baseclass, > this lookup is automatic. However, when I pass the instance to the > constructor, I have to store it in a member, and then I have to add code > for every function only to delegate it to that member. > > Is there an easy and generic way out of this? Create the subclass(es) dynamically: def wrap(plug_in): class PluginWrapper(plug_in.PluginClass): ... return PluginWrapper plugin = __import__(plugin_name) WrappedPlugin = wrap(plugin) Cheers, Chris -- http://blog.rebertia.com From jeanmichel at sequans.com Tue Aug 10 05:19:33 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 10 Aug 2010 11:19:33 +0200 Subject: easy question on parsing python: "is not None" In-Reply-To: <878w4i10ad.fsf@benfinney.id.au> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <4c5bc87b$0$10004$426a34cc@news.free.fr> <4C5C1000.3050102@sschwarzer.net> <8c2uiuFg9bU1@mid.individual.net> <878w4i10ad.fsf@benfinney.id.au> Message-ID: <4C6119A5.1000301@sequans.com> Ben Finney wrote: > Peter Pearson writes: > > >> Hey, that's a cute example, but . . . what a trap! Is it possible to >> document the use-the-object-not-the-string requirement loudly enough >> that people won't get caught? >> > > Don't use strings for such values. The data isn't going to be used, so > there's no sense using a semantically rich data type like a string. > > Instead, use an ?object? instance; then, the only way to get a binding > that will compare equal is to use the very object itself. > > FORWARD = object() > BACKWARD = object() > > Strings may have their use, most of the time providing a string representation of the object, here is an example: FORWARD = object() print 'moving %s' % FORWARD > moving Another approach using strings: class Direction: FORWARD = 'forward' print "moving %s' % Direction.FORWARD > moving forward Note that Direction.FORWARD is Direction.FORWARD is safe and will return True. JM From chris at simplistix.co.uk Tue Aug 10 05:25:01 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 10 Aug 2010 10:25:01 +0100 Subject: Execute 1.2 Released! Message-ID: <4C611AED.7060500@simplistix.co.uk> I'm pleased to announce the first public release of Execute. This is a collection of common patterns for executing commands as sub processes. It supports executing a simple command that requires no input in a sub process and can return: - text sent to the standard error and output streams - the return code set by the command - both of the above as a tuple For more information, please see: http://www.simplistix.co.uk/software/python/execute cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From clp2 at rebertia.com Tue Aug 10 05:25:02 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 10 Aug 2010 02:25:02 -0700 Subject: mailbox.mbox not locking mbox properly In-Reply-To: References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: On Tue, Aug 10, 2010 at 2:01 AM, wrote: > Tim Roberts wrote: >> tinnews at isbd.co.uk wrote: >> > >> >I'm using the python mailbox class in a script that processes incoming >> >mail and delivers it to various mbox format mailboxes. ?It appears >> >that, although I am calling the lock method on the destination before >> >writing to the mbox and calling unlock afterwards the locking isn't >> >working correctly. >> >... >> >So it seems that python's mailbox class locking isn't playing nicely >> >with mutt's mailbox locking whereas postfix's locking does work >> >correctly. >> >> Correct. ?The "dest.flush()" method creates a temporary file, copies the >> entire modified mailbox into it, removed the original file, and renames the >> temp file into place. >> > Yes, I just took a look at the mailbox.py code and it does exactly > that which of course screws up just about any normal MUA looking at > the mbox. ?Grrrrrr! > > >> The Postfix MDA, like most MDAs, just opens the existing file and appends >> the new data to it. >> >> >Has anyone seen this problem before, and/or do I need to anything more >> >than the following for the locking to work correctly:- >> >> It's not the locking. ?It's the flush mechanism. ?The mbox class doesn't >> know that the ONLY thing you did was an append. ?You might have modified >> other messages in the middle. ?If you want to do an append, you'll need to >> write your own subclass of mbox. > > OK, thanks. ?In reality I can probably just use straightforward file > reading and writing as the *only* thing I will ever be doing is to > append a message to a mailbox file. > > I think there should be a big warning in the mailbox documentation to > this effect as doing it the way that Python's mailbox class does it > will break all sorts of things. ?There should maybe be a specific > 'append' method. File a documentation and/or library bug: http://bugs.python.org/ Cheers, Chris From chris at simplistix.co.uk Tue Aug 10 05:26:04 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 10 Aug 2010 10:26:04 +0100 Subject: Checker 1.3 Released! Message-ID: <4C611B2C.3040403@simplistix.co.uk> I'm pleased to announce a new release of Checker. This is a cross-platform, pluggable tool for comparing the configuration of a machine with a known configuration stored in text files in a source control system all written in Python. This release and the previous release fix ordering issues in file listings as well as generalise operating package listing to support RedHat-like systems in addition to Debian-like systems. For more information, please see: http://www.simplistix.co.uk/software/python/checker cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From alex.lavoro.propio at gmail.com Tue Aug 10 06:25:27 2010 From: alex.lavoro.propio at gmail.com (Alex Barna) Date: Tue, 10 Aug 2010 03:25:27 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On Aug 10, 10:05?am, Lawrence D'Oliveiro > Can?t understand the point to it. ?GUI automation? is a contradiction in > terms, because a GUI is designed for use by humans to do manual tasks, not > ones that can be automated. Automating GUI is for testing. From ldo at geek-central.gen.new_zealand Tue Aug 10 06:28:35 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 10 Aug 2010 22:28:35 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> Message-ID: In message , Christian Heimes wrote: > There isn't really a point in cluttering the source with type casts. Makes you wonder why they bothered using a typed language at all. From santiago.caracol at gmail.com Tue Aug 10 06:34:28 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Tue, 10 Aug 2010 03:34:28 -0700 (PDT) Subject: freeze function calls Message-ID: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> Hello, I want to write a web application that does this: (1) The user submits a query: --------------------------------- | What is the answer? | --------------------------------- (2) The web server gives the user N answers and a button saying "More answers": . answer 1 . answer 2 . answer 3 I am aware of several ways to do this: I could calculate all answers, but show only the first N of them. For certain kinds of calulations, I could use a kind of setoff argument. But I would like to do it in a more general and (hopefully) efficient way: I want the function or object that calculates the answers to be "frozen" at the point at which it has already calculated N answers. If the function gets a -signal within a reasonable period of time, it goes on producing more answers exactly at the point at which it got frozen. If no signal is sent, the function call is terminated automatically after M seconds. Note that, although the program to be written is a web application, this is not a question about web application specific things. My only difficulty is how to "freeze" function calls. Has anyone done something of this kind? Santiago From eckhardt at satorlaser.com Tue Aug 10 06:40:41 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 10 Aug 2010 12:40:41 +0200 Subject: delegate functions to member References: <64h7j7-r73.ln1@satorlaser.homedns.org> Message-ID: <9um7j7-ki3.ln1@satorlaser.homedns.org> Peter Otten wrote: > Use getattr() > >>>> class W(object): > ... def __init__(self, wrapped): self._wrapped = wrapped > ... def __getattr__(self, name): > ... return getattr(self._wrapped, name) > ... I thought there was something like this, thanks! :) When I read this, I thought "OK, now I only have check first if the attribute can be looked up in 'self' first", but even that isn't the case. I tried it and added another function to class W above, which I can call just as if it was defined in _wrapped, so obviously (?) the __getattr__ lookup isn't done there. So, short follow-up question: Why does this work? Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From nikos.the.gr33k at gmail.com Tue Aug 10 07:04:11 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Tue, 10 Aug 2010 04:04:11 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> Message-ID: <94951243-3c97-4fef-9f47-ba6dcdef032f@l14g2000yql.googlegroups.com> Please help me with these last changes before i try to perform an overall change. its almost done! From __peter__ at web.de Tue Aug 10 07:17:47 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 13:17:47 +0200 Subject: delegate functions to member References: <64h7j7-r73.ln1@satorlaser.homedns.org> <9um7j7-ki3.ln1@satorlaser.homedns.org> Message-ID: Ulrich Eckhardt wrote: > Peter Otten wrote: >> Use getattr() >> >>>>> class W(object): >> ... def __init__(self, wrapped): self._wrapped = wrapped >> ... def __getattr__(self, name): >> ... return getattr(self._wrapped, name) >> ... > > I thought there was something like this, thanks! :) > > When I read this, I thought "OK, now I only have check first if the > attribute can be looked up in 'self' first", but even that isn't the case. The getattr() call inside __getattr__() raises an AttributeError if it can't find an attribute called name in self._wrapped. This very thing you'd have to do if you wanted to signal that an attribute doesn't exist, like in >>> class A: ... def __getattr__(self, name): ... if name == "foo": return 42 ... raise AttributeError ... >>> a = A() >>> a.foo 42 >>> a.bar Traceback (most recent call last): File "", line 1, in File "", line 4, in __getattr__ AttributeError > I tried it and added another function to class W above, which I can call > just as if it was defined in _wrapped, so obviously (?) the __getattr__ > lookup isn't done there. > > So, short follow-up question: Why does this work? __getattr__() is a fallback that is only tried when the normal lookup fails. If you need to intercept every attribute lookup use __getattribute__() instead: >> class A(object): ... def __getattr__(self, name): ... print "__getattr__(%r)" % name ... return 42 ... def __getattribute__(self, name): ... print "__getattribute__(%r)" % name ... return super(A, self).__getattribute__(name) ... >>> a = A() >>> a.foo = "yadda" >>> a.foo __getattribute__('foo') 'yadda' >>> a.bar __getattribute__('bar') __getattr__('bar') 42 Peter From jeanmichel at sequans.com Tue Aug 10 07:51:17 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 10 Aug 2010 13:51:17 +0200 Subject: Python "why" questions In-Reply-To: <87zkwyyoux.fsf@benfinney.id.au> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <87zkwyyoux.fsf@benfinney.id.au> Message-ID: <4C613D35.4070604@sequans.com> Ben Finney wrote: > "D'Arcy J.M. Cain" writes: > > >> No. You are giving me math and logic but the subject was common >> sense. >> > > Common sense is often unhelpful, and in such cases the best way to teach > something is to plainly contradict that common sense. > > Common sense, for example, would have the Earth as a flat surface with > the Sun and Moon as roughly-identically-sized objects orbiting the > Earth. Is it better to pander to that common sense, or to vigorously > reject it in order to teach something more useful? > > I could'nt agree more. If it was not for my scolarship, I would gladly think that the earth is flat and the sun is moving around. It took thousands of years for *1* man to figure out that was wrong. So if there is one thing that common sense is not helpful, then that thing is finding the Truth. JM "Ignorance is the mother of all traditions" (V. Hugo) From msarro at gmail.com Tue Aug 10 07:57:40 2010 From: msarro at gmail.com (Matty Sarro) Date: Tue, 10 Aug 2010 07:57:40 -0400 Subject: Newbie question - calculating prime numbers Message-ID: Hey Everyone, I'm currently trying to work through MIT's opencourseware and am using python. The second assignment they offer is to determine the 1000th prime number. Below is the code I am using: #Assignment 1a #Determine the 1000th prime number candidate=3 #Already know that 2 is prime primeCount=1 while (primeCount<=1000): for i in range (2,candidate): if ((candidate%i)==0): print(candidate, " is not a prime") else: print(candidate, " is a prime!") primeCount+=1 candidate+=2 Now I'm not looking for a solution, but I'm hoping that someone can at least tell me where the error in my logic is. The outer loop keeps count and will keep iterating until the 1000th prime number has been found. The inner loop just attempts to divide the candidate number by each possible factor until it's reached, and then increases the candidate number value by two since even numbers above 2 aren't prime. The if statement inside the inner loop simply checks if there is a remainder when attempting to divide the candidate by the possible factor. If there isn't, its a factor and we can print "not a prime". If there is always a remainder, nothing is a factor and so the candidate is a prime. I figured it seemed simple enough, but I keep getting a massive output and almost nothing listed is a correct prime number. Please be gentle, its my first post and I haven't programmed in ages :) -Matty -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmnc at spray.se Tue Aug 10 07:58:55 2010 From: jmnc at spray.se (Jonas Nilsson) Date: Tue, 10 Aug 2010 13:58:55 +0200 Subject: Weird Python behaviour Message-ID: <28B77025-74CC-4642-8EB7-E83838FBAF2D@spray.se> Hello, Lets say that I want to feed an optional list to class constructor: class Family(): def __init__(self, fName, members = []): self.fName = fName self.members = members Now, lets add members to two different instances of Family: f1 = Family("Smith") f1.members.append("Bill") f2 = Family("Smithers") f2.members.append("Joe") Finally, lets look at the members in the Smithers family: print f2.members output: ['Bill', 'Joe'] Why on earth is the output ['Bill', 'Joe']!? Is there a simple solution that separates f1 and f2 without forcing me to write code for the special case when you don't feed members to the __init__()-function? /Jonas From __peter__ at web.de Tue Aug 10 08:10:36 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 14:10:36 +0200 Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> Message-ID: Santiago Caracol wrote: > Hello, > > I want to write a web application that does this: > > (1) The user submits a query: > > --------------------------------- > | What is the answer? | > --------------------------------- > > > (2) The web server gives the user N answers and a button saying "More > answers": > > . answer 1 > . answer 2 > . answer 3 > > > > I am aware of several ways to do this: I could calculate all > answers, but show only the first N of them. For certain kinds of > calulations, > I could use a kind of setoff argument. But I would like to do it in a > more general > and (hopefully) efficient way: > > I want the function or object that calculates the answers to be > "frozen" at the point at which it has already calculated N answers. If > the function gets a -signal within a reasonable period > of time, it goes on producing more answers exactly at the point at > which it got frozen. If no signal is sent, the function call is > terminated automatically after > M seconds. > > Note that, although the program to be written is a web application, > this is not a question about web application specific things. My only > difficulty is how to "freeze" function calls. > > Has anyone done something of this kind? Python offers an elegant mechanism to calculate values on demand: the generator function: >>> def calculate_answers(): ... for i in range(100): ... print "calculating answer #%d" % i ... yield i * i ... >>> from itertools import islice >>> gen = calculate_answers() This builds the generator but doesn't run the code inside. Now let's look at the first three "answers": >>> for answer in islice(gen, 3): ... print "the answer is", answer ... calculating answer #0 the answer is 0 calculating answer #1 the answer is 1 calculating answer #2 the answer is 4 If you repeat the last step you get the next three answers: >>> for answer in islice(gen, 3): ... print "the answer is", answer ... calculating answer #3 the answer is 9 calculating answer #4 the answer is 16 calculating answer #5 the answer is 25 Peter From __peter__ at web.de Tue Aug 10 08:18:02 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 14:18:02 +0200 Subject: Weird Python behaviour References: Message-ID: Jonas Nilsson wrote: > Lets say that I want to feed an optional list to class constructor: > > class Family(): > def __init__(self, fName, members = []): > Why on earth is the output ['Bill', 'Joe']!? Is there a simple > solution that separates f1 and f2 without forcing me to write code for > the special case when you don't feed members to the __init__()-function? Congrats; you just encountered a very popular new trap ;) The most recent explanation is only one day old: http://mail.python.org/pipermail/python-list/2010-August/1252316.html Peter From no.email at please.post Tue Aug 10 08:19:03 2010 From: no.email at please.post (kj) Date: Tue, 10 Aug 2010 12:19:03 +0000 (UTC) Subject: shelf-like list? Message-ID: I'm looking for a module that implements "persistent lists": objects that behave like lists except that all their elements are stored on disk. IOW, the equivalent of "shelves", but for lists rather than a dictionaries. Does anyone know of such a module? (I suppose that I could slap together a crude implementation of such a thing by wrapping a shelf with suitable methods to simulate the list interface. But I'd rather not roll my own if a tested implementation already exist.) TIA! ~K From eckhardt at satorlaser.com Tue Aug 10 08:20:22 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 10 Aug 2010 14:20:22 +0200 Subject: delegate functions to member References: <64h7j7-r73.ln1@satorlaser.homedns.org> <9um7j7-ki3.ln1@satorlaser.homedns.org> Message-ID: <6ps7j7-0s3.ln1@satorlaser.homedns.org> Peter Otten wrote: > Ulrich Eckhardt wrote: >> So, short follow-up question: Why does this work? > > __getattr__() is a fallback that is only tried when the normal lookup > fails. If you need to intercept every attribute lookup use > __getattribute__() instead: Thank you Peter, that was the missing piece to understand it! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From santiago.caracol at gmail.com Tue Aug 10 08:30:57 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Tue, 10 Aug 2010 05:30:57 -0700 (PDT) Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> Message-ID: <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> > Python offers an elegant mechanism to calculate values on demand: the > generator function: > > >>> def calculate_answers(): > > ... ? ? for i in range(100): > ... ? ? ? ? ? ? print "calculating answer #%d" % i > ... ? ? ? ? ? ? yield i * i > ... > Thanks for pointing this out. I was aware of the yield statement. My problem is this: (1) The user submits a query: --------------------------------- | What is the answer? | --------------------------------- (2) The web server gives the user N answers and a button saying "More answers": . answer 1 . answer 2 . answer 3 At this stage the function that writes html to the user has been called. The call must be terminated, or else, the user doesn't get any html. This means that the call of the answer-calculating function, whether it uses yield or not, is also terminated. This means, when the user presses the -button, the calculation has to start at the beginning. From __peter__ at web.de Tue Aug 10 08:48:39 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 14:48:39 +0200 Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> Message-ID: Santiago Caracol wrote: >> Python offers an elegant mechanism to calculate values on demand: the >> generator function: >> >> >>> def calculate_answers(): >> >> ... for i in range(100): >> ... print "calculating answer #%d" % i >> ... yield i * i >> ... >> > > Thanks for pointing this out. I was aware of the yield statement. > > My problem is this: > > (1) The user submits a query: > > --------------------------------- > | What is the answer? | > --------------------------------- > > > (2) The web server gives the user N answers and a button saying "More > answers": > > . answer 1 > . answer 2 > . answer 3 > > > > At this stage the function that writes html to the user has been > called. The call must be terminated, or else, the user doesn't get any > html. This means that the call of the answer-calculating function, > whether it uses yield or not, is also terminated. This means, when the > user presses the -button, the calculation has to start > at the beginning. Adapted from the wsgiref documentation at http://docs.python.org/library/wsgiref.html $ cat wsgi_demo.py from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server from itertools import count, islice def answers(): for i in count(): yield "Answer #%d\n" % i gen = answers() def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return islice(gen, 3) httpd = make_server('', 8000, simple_app) print "Serving on port 8000..." httpd.serve_forever() Run the above with $ python wsgi_demo.py Serving on port 8000... Now point your favourite browser to http://localhost:8000/ and hit refresh. Peter From davea at ieee.org Tue Aug 10 08:51:47 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 10 Aug 2010 08:51:47 -0400 Subject: Newbie question - calculating prime numbers In-Reply-To: References: Message-ID: <4C614B63.5070108@ieee.org> Matty Sarro wrote: > Hey Everyone, > I'm currently trying to work through MIT's opencourseware and am using > python. The second assignment they offer is to determine the 1000th prime > number. Below is the code I am using: > > #Assignment 1a > #Determine the 1000th prime number > candidate=3 > #Already know that 2 is prime > primeCount=1 > while (primeCount<=1000): > for i in range (2,candidate): > if ((candidate%i)==0): > print(candidate, " is not a prime") > else: > print(candidate, " is a prime!") > primeCount+=1 > candidate+=2 > > > > > Now I'm not looking for a solution, but I'm hoping that someone can at least > tell me where the error in my logic is. > The outer loop keeps count and will keep iterating until the 1000th prime > number has been found. > The inner loop just attempts to divide the candidate number by each possible > factor until it's reached, and then increases the candidate number value by > two since even numbers above 2 aren't prime. > The if statement inside the inner loop simply checks if there is a remainder > when attempting to divide the candidate by the possible factor. If there > isn't, its a factor and we can print "not a prime". If there is always a > remainder, nothing is a factor and so the candidate is a prime. > > I figured it seemed simple enough, but I keep getting a massive output and > almost nothing listed is a correct prime number. > > Please be gentle, its my first post and I haven't programmed in ages :) > -Matty > > Once you discover a particular value is not a prime, you need to get out of that for loop. Add a break after the appropriate print. Also, the print that says it IS a prime is misplaced. You only know that if you've gone all the way through the loop without ever hitting the break. That's a candidate for the 'else' clause of the for loop. There are other changes you could make for efficiency, but get it working correctly first. DaveA From msarro at gmail.com Tue Aug 10 08:55:09 2010 From: msarro at gmail.com (Matty Sarro) Date: Tue, 10 Aug 2010 08:55:09 -0400 Subject: Newbie question - calculating prime numbers In-Reply-To: <4C614B63.5070108@ieee.org> References: <4C614B63.5070108@ieee.org> Message-ID: Hey Dave, Thank you for the heads up. I actually bashed my head against the desk a few times and eventually I realized what I was doing wrong. Here's my final code (slightly optimized) that's verified and working. Out of curiousity, what other optimizations could I throw at it (without diving too deep too fast). #Assignment 1a #Determine the 1000th prime number candidate=1 #Already know that 2 is prime primeCount=1 while (primeCount<=1000): isPrime="true" i=2 halfCand=(candidate/2) while (isPrime=="true") and (i<=halfCand): if ((candidate%i)==0): isPrime="false" else: i+=1 if isPrime=="true": print(candidate, "is a prime.") primeCount+=1 #else: #print(candidate, " is not a prime.") candidate+=2 print("The 1000th prime number is ",(candidate-2)) On Tue, Aug 10, 2010 at 8:51 AM, Dave Angel wrote: > Matty Sarro wrote: > >> Hey Everyone, >> I'm currently trying to work through MIT's opencourseware and am using >> python. The second assignment they offer is to determine the 1000th prime >> number. Below is the code I am using: >> >> #Assignment 1a >> #Determine the 1000th prime number >> candidate=3 >> #Already know that 2 is prime >> primeCount=1 >> while (primeCount<=1000): >> for i in range (2,candidate): >> if ((candidate%i)==0): >> print(candidate, " is not a prime") >> else: >> print(candidate, " is a prime!") >> primeCount+=1 >> candidate+=2 >> >> >> >> >> Now I'm not looking for a solution, but I'm hoping that someone can at >> least >> tell me where the error in my logic is. >> The outer loop keeps count and will keep iterating until the 1000th prime >> number has been found. >> The inner loop just attempts to divide the candidate number by each >> possible >> factor until it's reached, and then increases the candidate number value >> by >> two since even numbers above 2 aren't prime. >> The if statement inside the inner loop simply checks if there is a >> remainder >> when attempting to divide the candidate by the possible factor. If there >> isn't, its a factor and we can print "not a prime". If there is always a >> remainder, nothing is a factor and so the candidate is a prime. >> >> I figured it seemed simple enough, but I keep getting a massive output and >> almost nothing listed is a correct prime number. >> >> Please be gentle, its my first post and I haven't programmed in ages :) >> -Matty >> >> >> > Once you discover a particular value is not a prime, you need to get out of > that for loop. Add a break after the appropriate print. > > Also, the print that says it IS a prime is misplaced. You only know that > if you've gone all the way through the loop without ever hitting the break. > That's a candidate for the 'else' clause of the for loop. > > There are other changes you could make for efficiency, but get it working > correctly first. > > DaveA > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Tue Aug 10 09:02:30 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 10 Aug 2010 23:02:30 +1000 Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> <4c610bd2$0$28655$c3e8da3@news.astraweb.com> Message-ID: <87aaouzkm1.fsf@benfinney.id.au> Steven D'Aprano writes: > On Tue, 10 Aug 2010 20:07:06 +1200, Gregory Ewing wrote: > > Is there any way for a non-.NET program to access a .NET library? Or > > is it necessary to drink the entire bottle of .NET kool-aid? > > http://www.mono-project.com/Main_Page Anyone thinking of using Mono needs to be aware of the dangers of software patents in general, and of .NET in paticular. The copyright license for Mono is under free software terms. But that gives no license at all for the patents. Novell, who have an exclusive deal for those patents, happily encourages use of Mono by third parties. The controversy has raged for a number of years. For more coverage than you have time for, see . The issue has polarised discussion, unfortunately, and there is a lot of name-calling and hyperbole on the record now. As the Mono site hints, the patent situation for .NET is *very* muddy. Microsoft hold patents covering much of .NET, but have made a (non-binding) ?Community Promise? that applies to *some* parts of .NET . -- \ ?It is seldom that liberty of any kind is lost all at once.? | `\ ?David Hume | _o__) | Ben Finney From hobson42 at gmaiil.com Tue Aug 10 09:14:27 2010 From: hobson42 at gmaiil.com (Ian) Date: Tue, 10 Aug 2010 14:14:27 +0100 Subject: Newbie question - calculating prime numbers In-Reply-To: References: Message-ID: <4C6150B3.7020709@gmaiil.com> On 10/08/2010 12:57, Matty Sarro wrote: > Hey Everyone, > I'm currently trying to work through MIT's opencourseware and am using > python. The second assignment they offer is to determine the 1000th > prime number. Below is the code I am using: > > #Assignment 1a > #Determine the 1000th prime number > candidate=3 > #Already know that 2 is prime > primeCount=1 > while (primeCount<=1000): > for i in range (2,candidate): > if ((candidate%i)==0): > print(candidate, " is not a prime") > else: > print(candidate, " is a prime!") > primeCount+=1 > candidate+=2 > > > > > Now I'm not looking for a solution, but I'm hoping that someone can at > least tell me where the error in my logic is. Hi Matty, Dave Angel has already given you some helpful stuff. I would only like to add that you need three states inside your loop a) Candidate is known to be prime b) Candidate is known to be not prime c) Candidate may or may not be prime and the code has to keep working on it. You are detecting the "is not prime" case correctly. The other two situations are confused. A candidate is only prime if it is not divisible by *any* number other than 1 or itself. Two hints for efficiency: If candidate has a factor, one of those factors MUST be <= square root of candidate - so you don't need to loop through so many. If x is prime, all multiples of x are not prime. See sieve of Eratosthenes. Regards Ian From __peter__ at web.de Tue Aug 10 09:18:31 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 15:18:31 +0200 Subject: Newbie question - calculating prime numbers References: <4C614B63.5070108@ieee.org> Message-ID: Matty Sarro wrote: > Hey Dave, > Thank you for the heads up. I actually bashed my head against the desk a > few times and eventually I realized what I was doing wrong. Here's my > final code (slightly optimized) that's verified and working. Out of > curiousity, what other optimizations could I throw at it (without diving > too deep too fast). > > #Assignment 1a > #Determine the 1000th prime number > candidate=1 > #Already know that 2 is prime > primeCount=1 > while (primeCount<=1000): > isPrime="true" > i=2 > halfCand=(candidate/2) > while (isPrime=="true") and (i<=halfCand): > if ((candidate%i)==0): > isPrime="false" > else: > i+=1 > if isPrime=="true": > print(candidate, "is a prime.") > primeCount+=1 > #else: > #print(candidate, " is not a prime.") > candidate+=2 > print("The 1000th prime number is ",(candidate-2)) Congrats! One obvious thing would be to replace the "true" and "false" strings with actual boolean values: isPrime = True ... while isPrime and i <= halfCand: ... etc. For a different perspective on the problem have a look at http://mail.python.org/pipermail/python-list/2009-November/1226626.html Peter From davea at ieee.org Tue Aug 10 09:50:18 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 10 Aug 2010 09:50:18 -0400 Subject: Newbie question - calculating prime numbers In-Reply-To: References: <4C614B63.5070108@ieee.org> Message-ID: <4C61591A.8050108@ieee.org> Matty Sarro wrote: > Hey Dave, > Thank you for the heads up. I actually bashed my head against the desk a few > times and eventually I realized what I was doing wrong. Here's my final code > (slightly optimized) that's verified and working. Out of curiousity, what > other optimizations could I throw at it (without diving too deep too fast). > > #Assignment 1a > #Determine the 1000th prime number > candidate=1 > #Already know that 2 is prime > primeCount=1 > while (primeCount<=1000): > isPrime="true" > i=2 > halfCand=(candidate/2) > while (isPrime=="true") and (i<=halfCand): > if ((candidate%i)==0): > isPrime="false" > else: > i+=1 > if isPrime=="true": > print(candidate, "is a prime.") > primeCount+=1 > #else: > #print(candidate, " is not a prime.") > candidate+=2 > print("The 1000th prime number is ",(candidate-2)) > > You top-posted, which messed up the message sequence. You should post your message AFTER whatever you're quoting. Your code starts by printing that 1 is prime, which it's not. And it doesn't print 2. Those two errors happen to cancel, so the 1000th prime is still right. But the initial value for candidate= should be 3, not 1. I didn't try to figure where the other error is, but somewhere your count is off by one. You've changed your code from using the built-in control flow to doing it by hand. That's almost never a good idea, and in this case it'll slow you down. Learn about the break statement to break out of a for loop or while loop. It saves doing multiple tests in the loop construct. Use True and False, not strings. Your halfCand could have been rootCand; you only need to check up to the square root of the candidate (see math.sqrt()). In fact, you only need to check those primes you've already built, up to the square root. For example, to tell if 23 is prime, you only need to divide by 2, 3 and 5. This would require that you build a list of results, appending to it whenever you find a new prime. It would mean that primeCount is not needed, as it's simply len(primeList). I don't know which of these ideas has already been covered in your class. But if you used all of these ideas, your code would be smaller and much faster. Currently, it spends more time in the print statements than in calculating, so I temporarily commented out the print of the first 999 primes. I coded up a quick version, and without the prints of individual primes, it sped up 1.3 secs to 0.03 secs. If I have both versions do the first 10,000 primes, the original takes 176 secs, while mine takes 0.5 DaveA From darcy at druid.net Tue Aug 10 09:51:34 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 10 Aug 2010 09:51:34 -0400 Subject: Python "why" questions In-Reply-To: <4C613D35.4070604@sequans.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <87zkwyyoux.fsf@benfinney.id.au> <4C613D35.4070604@sequans.com> Message-ID: <20100810095134.fa3a3e79.darcy@druid.net> On Tue, 10 Aug 2010 13:51:17 +0200 Jean-Michel Pichavant wrote: Pardon the response to the response. I missed Ben's message. > Ben Finney wrote: > > "D'Arcy J.M. Cain" writes: > >> No. You are giving me math and logic but the subject was common > >> sense. > > > > Common sense is often unhelpful, and in such cases the best way to teach > > something is to plainly contradict that common sense. I even agree with you. However, the OP was claiming that zero based counting contradicted common sense and that was what I was responding to. I would never use "common sense" to prove anything. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From santiago.caracol at gmail.com Tue Aug 10 09:56:56 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Tue, 10 Aug 2010 06:56:56 -0700 (PDT) Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> Message-ID: <34b16983-ac50-49a0-a612-0c35d9bf6c6f@l14g2000yql.googlegroups.com> > Run the above with > > $ python wsgi_demo.py > Serving on port 8000... > Thanks a lot for this code. The problem with it is that the whole application IS a generator function. That means that if I run the code at, say foo.org, then any user that visits the site will augment the answer number of the server running at foo.org. What I am trying to do is to process specific queries for different users. Each user is supposed to get his very own answers to his very own questions. And if a user doesn't hit the -button during a certain period of time, the generator or function call reponsible for answering his question is supposed to be killed or thrown-away or forgotten. If the user asks a new question (while the answers to the old question are still being displayed), then the generator or function call is also supposed to be forgotten and a new generator or function call -- one that matches the user's new question -- is supposed to be initiated. Santiago From herta.hy at gmail.com Tue Aug 10 10:02:06 2010 From: herta.hy at gmail.com (Herta) Date: Tue, 10 Aug 2010 07:02:06 -0700 (PDT) Subject: how to save a whole web page with something block Message-ID: <46c3cfc7-9339-4cd0-9ef9-4358730b706f@o7g2000prg.googlegroups.com> Hi everyone, I want to save a web page. I use urllib to parse the web page. But I find the saved file, where some content is missing. The missing part is block from the original web page, such as this part
...
.I don't know how to parse a whole page without something block in it. Could you help me figure it out? Thank you! This is my program url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp? Param=4502931&ProtId=1&ProtType=Receptor' f = urllib.urlretrieve(url,'test.html') From steveo at syslang.net Tue Aug 10 10:07:23 2010 From: steveo at syslang.net (Steven W. Orr) Date: Tue, 10 Aug 2010 10:07:23 -0400 Subject: How to capture all the environment variables from shell? In-Reply-To: References: <4C4E43D3.9070203@syslang.net> Message-ID: <4C615D1B.7060204@syslang.net> On 8/2/2010 4:33 AM, Thorsten Kampe wrote: > * Tim Chase (Mon, 26 Jul 2010 21:42:24 -0500) >> On 07/26/10 21:26, Steven W. Orr wrote: >>> Please! Never export anything from your .bashrc unless you >>> really know what you're doing. Almost all exports should be >>> done in your .bash_profile >> >> Could you elaborate on your reasoning why (or why-not)? I've >> found that my .bash_profile doesn't get evaluated when I crank up >> another terminal window, while my bashrc does. Thus I tend to >> put my exports in my ~/.bashrc so they actually take effect in my >> shell... > > ~/.bash_profile is only evaluated for login shells and ~/.bashrc only > for non-login shells. Thus it's recommended to keep ~/.bash_profile > empty (except a source statement for .bashrc) and put all your settings, > aliases, exports, etc. in .bashrc. > > Thorsten Sorry. Dead wrong. Please reread the above comment I wrote. If you set your environment variables in the .bashrc then you completely lose the ability of environment variables to be inherited by sub-shells. Again, envvars should be set in the .bash_profile, most everything else should be set in the .bashrc, and the .bashrc should be sourced into the .bash_profile to solve the problem that you thought you were solving. After that, and again, be aware that the .bashrc alone is executed for login shells *which are not interactive*. for example: ssh somemachine 'echo Hello' This command will *not* go through the .bash_profile but it will go through the .bashrc. This means that for cases like this, we want to check to see if the bash process is interactive or not inside the .bashrc and then do the right thing. =============== [[ -z "$PS1" ]] && setPATHHere =============== This is not needed for the above degenerate case, but it is needed if the command in question is kept in a directory that you normally find in a place that is part of your personal login PATH. E.G., If myprog lives in ~/bin then ssh somemachine myprog will fail unless you use the above construct. Hopefully, I'll only have to re-explain this another google times... -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net steve orr From benjamin.kaplan at case.edu Tue Aug 10 10:43:22 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 10 Aug 2010 07:43:22 -0700 Subject: Weird Python behaviour In-Reply-To: <28B77025-74CC-4642-8EB7-E83838FBAF2D@spray.se> References: <28B77025-74CC-4642-8EB7-E83838FBAF2D@spray.se> Message-ID: On Tue, Aug 10, 2010 at 4:58 AM, Jonas Nilsson wrote: > Hello, > > Lets say that I want to feed an optional list to class constructor: > > class Family(): > ? ? ? ?def __init__(self, fName, members = []): > ? ? ? ? ? ? ? ?self.fName = fName > ? ? ? ? ? ? ? ?self.members = members > > Now, lets add members to two different instances of Family: > > f1 = Family("Smith") > f1.members.append("Bill") > > f2 = Family("Smithers") > f2.members.append("Joe") > > Finally, lets look at the members in the Smithers family: > > print f2.members > output: ['Bill', 'Joe'] > > Why on earth is the output ['Bill', 'Joe']!? Is there a simple solution that > separates f1 and f2 without forcing me to write code for the special case > when you don't feed members to the __init__()-function? > > /Jonas In python, a function definition is an executable statement, not a declaration. Default args only get evaluated once- when the function is first created. You have to use a sentinel value and create the object inside the function if you want it to get executed every time. class Family(): def __init__(self, fName, members = None): if members is None : members = [] self.fName = fName self.members = members If None is a valid argument to this function, then make a dummy object and check identity (to make sure it's *that* object and not just something that evaluates equal). sentinel = object() def something_that_accepts_none(foo = sentinel) : if foo is sentinel : foo = {} # other stuff From John Tue Aug 10 10:58:39 2010 From: John (John) Date: Tue, 10 Aug 2010 10:58:39 -0400 Subject: File Manager in Tkinter References: Message-ID: On Tue, 10 Aug 2010 10:40:53 +0200, Eric Brunel wrote: >In article , John wrote: > >> As a learning exercise in Tkinter I htought about making a very simple >> and basic file manager for my own use. I tried searching google for >> any sample project and could not find anything. Not exactly sure how >> to start I tought I could ask here? >> >> I thought about making two listboxes one to list folders only the >> other files inside. I tried to make one listbox first but did not know >> how to list folders only. > >You just have to filter them explicitely by using os.path.isdir on each >file name. > >> from Tkinter import * >> import os >> path = "D:\\" >> >> >> s = Scrollbar() >> L = Listbox() >> >> s.pack(side=RIGHT, fill=Y) >> L.pack(side=LEFT, fill=Y) >> >> s.config(command=L.yview) >> L.config(yscrollcommand=s.set) >> >> for filename in os.listdir(path): > >Add here: > if os.path.isdir(os.path.join(path, filename)): >> L.insert(END, filename) >> >> mainloop() >> >> >> >> Is there a way to list folders with images? > >AFAIK, not with a Listbox. You can do it with a Canvas, but it's much >more complicated than using a Listbox, so maybe you should try to make >your Listbox-only version works first. > >> Any suggestions or help how to proced would be appreciated. >> >> Thank you > >Good luck! Thank you both for the suggestions. Have you ever tried to make one? From bieffe62 at gmail.com Tue Aug 10 11:01:07 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Tue, 10 Aug 2010 08:01:07 -0700 (PDT) Subject: Weird Python behaviour References: Message-ID: <4f9fc841-bd4f-471c-9e7c-dd91515fb5d2@a18g2000yqa.googlegroups.com> On 10 Ago, 13:58, Jonas Nilsson wrote: > Hello, > > Lets say that I want to feed an optional list to class constructor: > > class Family(): > ? ? ? ? def __init__(self, fName, members = []): > ? ? ? ? ? ? ? ? self.fName = fName > ? ? ? ? ? ? ? ? self.members = members > > Now, lets add members to two different instances of Family: > > f1 = Family("Smith") > f1.members.append("Bill") > > f2 = Family("Smithers") > f2.members.append("Joe") > > Finally, lets look at the members in the Smithers family: > > print f2.members > output: ['Bill', 'Joe'] > > Why on earth is the output ['Bill', 'Joe']!? Is there a simple ? > solution that separates f1 and f2 without forcing me to write code for ? > the special case when you don't feed members to the __init__()-function? > > /Jonas You stumbled in two python common pitfalls at once :-) One, the default arguments issue, was already pointed to you. The other one is that python variables are just names for objects. Assigning a variable never mean making a copy, it just means using another name for the same object. There used to be a very nice (also graphic) explanationor this somewhere on the web, but my googling skills failed me this time, so instead I'll show you the concept using your own code: >>> class Family: ... def __init__(self, fName, members = []): ... self.fname = fName ... self.members = members ... >>> mlist = ["Bill"] >>> f1 = Family("Smiths", mlist ) >>> mlist.append( "John" ) # attempt to not-so-clever reyse of the sme variable >>> f2 = Family("Smithers", mlist ) >>> f1.members ['Bill', 'John'] Now my example is a bit contrieved but I'm sure you got the idea : in your example is better to copy the list with self.members = members[:]. Better yet, you could make use of python arguments grouping feature : >>> class Family: ... def __init__(self, fName, *members ): ... self.members = list(members) # because members is a tuple ... self.fname = fName ... >>> f1 = Family("Smith") >>> f1.members.append("Bill") >>> f2 = Family("Smithers") >>> f2.members.append("Joe") >>> f2.members ['Joe'] >>> f1.members ['Bill'] This solves your "no initial member" special case and allows for an easier syntax for creating class instances (no brackets involved) >>> f3 = Family("Bochicchio", "Angelo", "Francesco", "Mario") >>> f3.members ['Angelo', 'Francesco', 'Mario'] >>> Ciao ---- FB From fetchinson at googlemail.com Tue Aug 10 11:04:09 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 10 Aug 2010 17:04:09 +0200 Subject: how to save a whole web page with something block In-Reply-To: <46c3cfc7-9339-4cd0-9ef9-4358730b706f@o7g2000prg.googlegroups.com> References: <46c3cfc7-9339-4cd0-9ef9-4358730b706f@o7g2000prg.googlegroups.com> Message-ID: > I want to save a web page. I use urllib to parse the web page. But I > find the saved file, where some content is missing. The missing part > is block from the original web page, such as this part
style="display: block;" id="GeneInts">...
.I don't know how to > parse a whole page without something block in it. Could you help me > figure it out? Thank you! > > > This is my program > > url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp? > Param=4502931&ProtId=1&ProtType=Receptor' > f = urllib.urlretrieve(url,'test.html') A web server may present different output depending on the client used. When you use your browser to look at the source and then use urllib's saved file you access the web server with different clients. I'm not saying this is your problem, but potentially it is. So you might want to make urllib appear as a browser by sending the appropriate headers. HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From python at mrabarnett.plus.com Tue Aug 10 11:12:02 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 10 Aug 2010 16:12:02 +0100 Subject: Replace and inserting strings within .txt files with the use of regex In-Reply-To: <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> Message-ID: <4C616C42.6040506@mrabarnett.plus.com> ????? wrote: [snip] > > The ID number of each php page was contained in the old php code > within this string > > PageID = some_number > > So instead of create a new ID number for eaqch page i have to pull out > this number to store to the beginnign to the file as comment line, > because it has direct relationship with the mysql database as in > tracking the number of each webpage and finding the counter of it. > > # Grab the PageID contained within the php code and store it in id > variable > id = re.search( 'PageID = ', src_data ) > > How to tell Python to Grab that number after 'PageID = ' string and to > store it in var id that a later use in the program? > If the part of the file you're trying to match look like this: PageID = 12 then the regex should look like this: PageID = (\d+) and the code should look like this: page_id = re.search(r'PageID = (\d+)', src_data).group(1) The page_id will, of course, be a string. > also i made another changewould something like this work: > > =============================== > # open same php file for storing modified data > print ( 'writing to %s' % dest_f ) > f = open(src_f, 'w') > f.write(src_data) > f.close() > > # rename edited .php file to .html extension > dst_f = src_f.replace('.php', '.html') > os.rename( src_f, dst_f ) > =============================== > > Because instead of creating a new .html file and inserting the desired > data of the old php thus having two files(old php, and new html) i > decided to open the same php file for writing that data and then > rename it to html. > Would the above code work? Why wouldn't it? From nbuchholz at noao.edu Tue Aug 10 11:43:24 2010 From: nbuchholz at noao.edu (Nick Buchholz) Date: Tue, 10 Aug 2010 08:43:24 -0700 Subject: File Manager in Tkinter In-Reply-To: References: Message-ID: On Tue, 10 Aug 2010 10:58:39 -0400 John at mail.python.org wrote: >Thank you both for the suggestions. Have you ever tried to make one? >-- >http://mail.python.org/mailman/listinfo/python-list I don't know if my first reply went out so I'll repeat Here is a list box dialog written to allow selection of one of a specific type of file. It is a method in a larger gui object that controls hardware on a remote machine (called a PAN) and loads commands from files. def modeFiles(self): try: sysFile = self.chkConnected() except Disconnect,e: return (False, '') self.pan.ppxGetAVP( ('modeFdir', ) ) dir = self.pan.avps['modeFdir'].get() fileList = fetchModFiles(self.pan, dir=dir) flist = [] for file in fileList: idx = rfind(file, '/') flist.append(file[idx+1:]) dlg = Pmw.ComboBoxDialog(self.parent, title = 'Mode File Select', buttons=('Load', 'Cancel'), defaultbutton='Load', combobox_labelpos=N, label_text='Which Mode file to load', scrolledlist_items=flist, listbox_width=32) dlg.geometry('240x300+30+250') dlg.tkraise() result = dlg.activate(geometry='240x300+30+250') if result == 'Load': print "loading %s/%s "%(dir, dlg.get()) self.pan.ppxSetMode( (dlg.get(),) ) else: print "leaving" here is fetchModFilesz def fetchModFiles(pan=None, dir=None): """ A function to read mod files on remote pan in directory dir """ fileList = [] if pan is not None: if dir is None: rCmd = "/bin/echo $MONSOON_HOME" dir = commands.getoutput("ssh -X -l monsoon %s '%s'" % (pan.panName, rCmd) ) dir = dir+os.sep+'_'+pan.sysName lsCmd = "/bin/ls %s/*.mod"%(dir,) resp = commands.getoutput("ssh -X -l monsoon %s '%s'"% (pan.panName, lsCmd)) fileList = resp.split("\n") else: pass return fileList Someday I may have time to go back and clean these up and generalize them. But as the only software guy on a 3 man-year project due to complete in 9 months quick and dirty is the rule. Nick nbuchholz at noao.edu Day phone: (520) 318-8203 "Time is an illusion, Lunchtime doubly so" - Ford Prefect Time is an illusion perpetrated by the manufacturers of space. From __peter__ at web.de Tue Aug 10 11:46:02 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Aug 2010 17:46:02 +0200 Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> <34b16983-ac50-49a0-a612-0c35d9bf6c6f@l14g2000yql.googlegroups.com> Message-ID: Santiago Caracol wrote: >> Run the above with >> >> $ python wsgi_demo.py >> Serving on port 8000... >> > > Thanks a lot for this code. The problem with it is that the whole > application IS a generator function. That means that if I run the code > at, say foo.org, then any user that visits the site will augment the > answer number of the server running at foo.org. What I am trying to do > is to process specific queries for different users. Each user is > supposed to get his very own answers to his very own questions. And if > a user doesn't hit the -button during a certain period > of time, the generator or function call reponsible for answering his > question is supposed to be killed or thrown-away or forgotten. If the > user asks a new question (while the answers to the old question are > still being displayed), then the generator or function call is also > supposed to be forgotten and a new generator or function call -- one > that matches the user's new question -- is supposed to be initiated. Didn't you say you weren't interested in the web specific aspects? You may be able to do it by hand (the environ argument will probably include an IP that you can use to look up the generator in a dictionary) but I'd rather say you need a web framework that provides the session management. Cherrypy is a lightweight one, and after some try and way too much error I came up with # warning: newbie code import cherrypy from itertools import islice, count def answers(): for i in count(): yield "Answer #%d\n" % i class PythonRunner(object): def index(self): try: gen = cherrypy.session["gen"] except KeyError: cherrypy.session["gen"] = gen = answers() return "%s" % "".join(islice(gen, 3)) index.exposed = True if __name__ == '__main__': cherrypy.quickstart(PythonRunner(), config="cherry.conf") The contents of cherry.conf are: [global] server.socket_host = "127.0.0.1" server.socket_port = 8080 server.thread_pool = 10 [/] tools.sessions.on = True #tools.sessions.storage_type = "file" #tools.sessions.storage_path = "./sessions" tools.sessions.timeout = 60 See the result on http://localhost:8080/index I opened the page in Firefox and Konqueror, and the numbers were independent, so I'm pretty sure it works on a bigger scale, too. $ python -c 'import cherrypy; print cherrypy.__version__' 3.1.2 Note that storage_type = "file" is straight out for generators because they cannot be pickled. The workaround here would be a class like class Answers(object): def __init__(self): self.i = 0 def __iter__(self): return self def next(self): result = "Answer #%d\n" % self.i self.i += 1 return result Peter From sschwarzer at sschwarzer.net Tue Aug 10 11:57:21 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 10 Aug 2010 17:57:21 +0200 Subject: Weird Python behaviour In-Reply-To: <4f9fc841-bd4f-471c-9e7c-dd91515fb5d2@a18g2000yqa.googlegroups.com> References: <4f9fc841-bd4f-471c-9e7c-dd91515fb5d2@a18g2000yqa.googlegroups.com> Message-ID: <4C6176E1.7020504@sschwarzer.net> Hi, On 2010-08-10 17:01, Francesco Bochicchio wrote: > There used to be a very nice (also graphic) explanationor this > somewhere on the web, but my googling skills failed me this time, > so instead I'll show you the concept using your own code: Probably this isn't the page you're referring to, but I only recently gave a beginners' talk at EuroPython: http://sschwarzer.com/download/robust_python_programs_europython2010.pdf The topic of identity and assignments starts on slide 7, nice graphics start on slide 10. ;-) Stefan From jeff.hobbs at gmail.com Tue Aug 10 12:20:31 2010 From: jeff.hobbs at gmail.com (Jeff Hobbs) Date: Tue, 10 Aug 2010 09:20:31 -0700 (PDT) Subject: File Manager in Tkinter References: Message-ID: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> On Aug 9, 9:53?pm, John wrote: > As a learning exercise in Tkinter I htought about making a very simple > and basic file manager for my own use. I tried searching google for > any sample project and could not find anything. Not exactly ?sure how > to start I tought I could ask here? > > I thought about making two listboxes one to list folders only the > other files inside. I tried to make one listbox first but did not know > how to list folders only. Filter with os.path.isdir() > Is there a way to list folders with images? > Any suggestions or help how to proced would be appreciated. If you are using a Tkinter with Ttk (Tk 8.5), then use the treeview widget: http://docs.activestate.com/activepython/3.1/python/library/tkinter.ttk.html For more advanced needs, there is a Tk extension called tktreectrl that does some very cool views and has lots of controls: http://tktreectrl.sourceforge.net/ Jeff From torriem at gmail.com Tue Aug 10 12:29:23 2010 From: torriem at gmail.com (Michael Torrie) Date: Tue, 10 Aug 2010 10:29:23 -0600 Subject: Microsoft lessening commitment to IronPython and IronRuby In-Reply-To: <8ccf4kF38mU1@mid.individual.net> References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> Message-ID: <4C617E63.6020509@gmail.com> On 08/10/2010 02:07 AM, Gregory Ewing wrote: > Tim Roberts wrote: > >> I'm not sure that's really fair. The .NET Common Language Runtime is a >> vast and very useful class library, including two complete GUI systems. The >> thought was that IronPython and IronRuby would let people who were >> comfortable in those languages tap into the CLR. > > Is there any way for a non-.NET program to access a .NET library? > Or is it necessary to drink the entire bottle of .NET kool-aid? Well the only way for a non-.net program to access a .NET library is to either embed .NET or use some kind of bridge via RPC. So basically, the answer is "no." You pretty much have to embrace .NET or not use it. From John Tue Aug 10 12:43:12 2010 From: John (John) Date: Tue, 10 Aug 2010 12:43:12 -0400 Subject: File Manager in Tkinter References: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> Message-ID: <770366ta10gk98vgd5n2tapl7ag6skaeaj@4ax.com> On Tue, 10 Aug 2010 09:20:31 -0700 (PDT), Jeff Hobbs wrote: >On Aug 9, 9:53?pm, John wrote: >> As a learning exercise in Tkinter I htought about making a very simple >> and basic file manager for my own use. I tried searching google for >> any sample project and could not find anything. Not exactly ?sure how >> to start I tought I could ask here? >> >> I thought about making two listboxes one to list folders only the >> other files inside. I tried to make one listbox first but did not know >> how to list folders only. > >Filter with os.path.isdir() > >> Is there a way to list folders with images? >> Any suggestions or help how to proced would be appreciated. > >If you are using a Tkinter with Ttk (Tk 8.5), then use the treeview >widget: > >http://docs.activestate.com/activepython/3.1/python/library/tkinter.ttk.html > >For more advanced needs, there is a Tk extension called tktreectrl >that does some very cool views and has lots of controls: > >http://tktreectrl.sourceforge.net/ > >Jeff My python is version 2.6.5. Would you recomend I upgrade and if yes to which version? from tkinter import ttk Traceback (most recent call last): File "", line 1, in from tkinter import ttk ImportError: No module named tkinter From jmnc at spray.se Tue Aug 10 12:47:34 2010 From: jmnc at spray.se (Jonas Nilsson) Date: Tue, 10 Aug 2010 18:47:34 +0200 Subject: Weird Python behaviour Message-ID: On 10 Ago, 13:58, Jonas Nilsson wrote: .... > You stumbled in two python common pitfalls at once :-) > One, the default arguments issue, was already pointed to you. > > The other one is that python variables are just names for objects. > Assigning a variable never mean making a copy, it just means using > another name for the same object. > There used to be a very nice (also graphic) explanationor this > somewhere on the web, but my googling skills failed me this time, > so instead I'll show you the concept using your own code: > >>>> class Family: > ... def __init__(self, fName, members = []): > ... self.fname = fName > ... self.members = members > ... >>>> mlist = ["Bill"] >>>> f1 = Family("Smiths", mlist ) >>>> mlist.append( "John" ) # attempt to not-so-clever reyse of the >>>> sme variable >>>> f2 = Family("Smithers", mlist ) >>>> f1.members > ['Bill', 'John'] > > Now my example is a bit contrieved but I'm sure you got the idea : in > your example is better to copy the list with > self.members = members[:]. > > Better yet, you could make use of python arguments grouping feature : >>>> class Family: > ... def __init__(self, fName, *members ): > ... self.members = list(members) # because members is a > tuple > ... self.fname = fName > ... >>>> f1 = Family("Smith") >>>> f1.members.append("Bill") >>>> f2 = Family("Smithers") >>>> f2.members.append("Joe") >>>> f2.members > ['Joe'] >>>> f1.members > ['Bill'] > > This solves your "no initial member" special case and allows for an > easier syntax for creating class instances > (no brackets involved) > >>>> f3 = Family("Bochicchio", "Angelo", "Francesco", "Mario") >>>> f3.members > ['Angelo', 'Francesco', 'Mario'] >>>> > > > Ciao > ---- > FB Thanks everyone. I was a bit steamed about the problem as it was very unexpected. Because I couldn't figure out what key words to google on, I resorted to posting the problem here. /Jonas From esnow at verio.net Tue Aug 10 13:40:54 2010 From: esnow at verio.net (Eric Snow) Date: Tue, 10 Aug 2010 10:40:54 -0700 (PDT) Subject: type enforcement in _ssl.sslwrap Message-ID: <38664845-c34d-452e-a09c-3206383e90e3@s17g2000prh.googlegroups.com> ssl.SSLSocket.__init__ makes a call to _ssl.sslwrap (in the C module). That in turn makes a call to PyArg_ParseTuple, which casts the first arg of _ssl.sslwrap into a PySocketModule.Sock_Type object. My problem is that I am trying to pass in an object that implements the Socket interface, but does not inherit from _socket.socket, like you do with file-like objects. Is there a way to make this work, or is the PyArg_ParseTuple call going to stop me. Would I need to have _ssl.sslwrap do something differently with its args? -eric From nisha.sinah at gmail.com Tue Aug 10 13:56:36 2010 From: nisha.sinah at gmail.com (Jeannette) Date: Tue, 10 Aug 2010 10:56:36 -0700 (PDT) Subject: (Free Special Offer) Sweet & Sexy Homely Girls & Wives Want To Stay with You For a Nite Total Free Message-ID: <6d935b82-109b-4978-9392-bd9f4381bc37@q21g2000prm.googlegroups.com> http://photosfair1.blogspot.com/2010/04/miss-india-may2003-reena_1978.html http://photosfair1.blogspot.com/2010/04/dirty-wives_5225.html http://photosfair1.blogspot.com/2010/04/miss-april-2003esha_8032.html http://photosfair1.blogspot.com/2010/04/miss-august-2003khushbo_9889.html http://photosfair1.blogspot.com/2010/04/beautifull-english-house-wives_5073.html http://photosfair1.blogspot.com/2010/04/english-beautifull-real-house-wises_6871.html http://photosfair1.blogspot.com/2010/04/miss-india-nov2002aarna_1751.html http://photosfair1.blogspot.com/2010/04/english-aunties_9920.html http://photosfair1.blogspot.com/2010/04/lovely-sexy-wives_9058.html http://photosfair1.blogspot.com/2010/05/sexy-beauty_9772.html http://photosfair1.blogspot.com/2010/05/girls-stockings.html http://www.photosfair.com http://www.photosfair.com http://www.photosfair.com http://www.photosfair.com http://www.photosfair.com http://www.mysmsfair.com http://www.mysmsfair.com http://www.mysmsfair.com http://www.mysmsfair.com http://www.mysmsfair.com http://www.mysmsfair.com From bieffe62 at gmail.com Tue Aug 10 14:00:01 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Tue, 10 Aug 2010 11:00:01 -0700 (PDT) Subject: Weird Python behaviour References: <4f9fc841-bd4f-471c-9e7c-dd91515fb5d2@a18g2000yqa.googlegroups.com> <4C6176E1.7020504@sschwarzer.net> Message-ID: On 10 Ago, 17:57, Stefan Schwarzer wrote: > Hi, > > On 2010-08-10 17:01, Francesco Bochicchio wrote: > > > There used to be a very nice (also graphic) explanationor this > > somewhere on the web, but my googling skills failed me this time, > > so instead I'll show you the concept using your own code: > > Probably this isn't the page you're referring to, but I only > recently gave a beginners' talk at EuroPython: > > http://sschwarzer.com/download/robust_python_programs_europython2010.pdf > > The topic of identity and assignments starts on slide 7, > nice graphics start on slide 10. ;-) > > Stefan Also good :-) But I finally found the page I was referring to: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables Ciao --- FB From pavlovevidence at gmail.com Tue Aug 10 14:49:07 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 10 Aug 2010 11:49:07 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> Message-ID: On Aug 10, 12:06?am, Ulrich Eckhardt wrote: > Carl Banks wrote: > > I highly doubt the Python source would build with a C++ compiler. > > As Christian showed, it doesn't. However, look around the sources a bit. > There are lots of places where e.g. the returnvalue of malloc() (or, > rather, the macro that resolves to something like it) is explicitly > type-cast to the according pointer type. When asked on the developers' > list, it was said that this was intended for compatibility with C++, e.g. > in cases where people want to embed Python into their C++ projects. Of > course, this contradicts Christian's statement that C++ compatibility > wasn't considered useful enough. I question why it needs to be compatible with C++ to be able to embed Python in a C++ project. How many C++ compilers out there don't come bundled with a C compiler? Carl Banks From news1234 at free.fr Tue Aug 10 15:13:57 2010 From: news1234 at free.fr (News123) Date: Tue, 10 Aug 2010 21:13:57 +0200 Subject: GUI automation tool (windows) In-Reply-To: References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4c61a4f5$0$5804$426a34cc@news.free.fr> On 08/10/2010 12:25 PM, Alex Barna wrote: > On Aug 10, 10:05 am, Lawrence D'Oliveiro > Can?t understand the point > to it. ?GUI automation? is a contradiction in >> terms, because a GUI is designed for use by humans to do manual tasks, not >> ones that can be automated. > > Automating GUI is for testing. And sometimesfor working around SW, whch has no cli or other interface and should be automated From martin.hellwig at dcuktec.org Tue Aug 10 15:23:09 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 10 Aug 2010 20:23:09 +0100 Subject: GUI automation tool (windows) In-Reply-To: <4c61a4f5$0$5804$426a34cc@news.free.fr> References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c61a4f5$0$5804$426a34cc@news.free.fr> Message-ID: On 08/10/10 20:13, News123 wrote: > On 08/10/2010 12:25 PM, Alex Barna wrote: >> On Aug 10, 10:05 am, Lawrence D'Oliveiro> Can?t understand the point >> to it. ?GUI automation? is a contradiction in >>> terms, because a GUI is designed for use by humans to do manual tasks, not >>> ones that can be automated. >> >> Automating GUI is for testing. > And sometimesfor working around SW, whch has no cli or other interface > and should be automated > That and when you are forced using a gui and need to 'copy and paste' between two programs that have no native bridge except for the one that is between the keyboard and chair, then it is nice to know that there is a way of automating it. -- mph From james at agentultra.com Tue Aug 10 16:44:17 2010 From: james at agentultra.com (J Kenneth King) Date: Tue, 10 Aug 2010 16:44:17 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> Message-ID: <877hjykxjy.fsf@agentultra.com> James Mills writes: > On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >>> I would like to aquint myself with Python Interview questions >> >> This came up a while ago: >> >> http://www.mail-archive.com/python-list at python.org/msg168961.html >> >> Most of that thread is still relevant (perhaps throw in some py3l questions >> too) > > A common thing you can do in interviews is ask > your interviewee to write (in Python) a solution > to the "FizzBuzz" problem. Any good competent > Python programmer should be able to do this > in 5-10mins (5 if you're good). > > cheers > james Fizzbuzz is annoying in interviews. I've never worked at a job where I was under a timer while a group of people sat across from me and scrutinized everything I was doing. I don't see how it can honestly tell you anything useful about the person you're interviewing either. Do you really think that what you assume about the interviewee based on characteristics you can infer from their solution to be really, honestly true? They might even completely bomb the solution and still be a brilliant programmer, but you'll never know that if you trust this simple "fizzbuzz" test. I've been in those interviews on both sides of the table. Neither side was a good experience. If a test is necessary, make it a take-home or demand source code if they have it. Read their code and judge for yourself the quality of their work. Any questions in an interview should be the usual "get to know you" type stuff. "What was the most difficult challenge you've faced on the job? How did you respond?" That sort of thing. From xahlee at gmail.com Tue Aug 10 17:03:01 2010 From: xahlee at gmail.com (Xah Lee) Date: Tue, 10 Aug 2010 14:03:01 -0700 (PDT) Subject: a article on does lang influence thought Message-ID: <1475a4b3-4abf-4fb9-8804-5c9fa99bc1cc@z30g2000prg.googlegroups.com> Great article. ?Lost in Translation? (2010-07-23), by By Lera Boroditsky. >From The Wall Street Journal. ?New cognitive research suggests that language profoundly influences the way people see the world; a different sense of blame in Japanese and Spanish? http://online.wsj.com/article/SB10001424052748703467304575383131592767868.html no surprise to lispers. though, standard caution apply here... do take the findings in the story lightly, as such non-scientific writing usually are full of vague notions, misleading, and sometimes outright incorrect. Also, for those of you dumb mono-USers... perhaps it's time to pick up another lang. lol and, time to learn lojban too! ? Xah's lojban page http://xahlee.org/lojban/lojban.html Xah ? http://xahlee.org/ ? From benjamin.kaplan at case.edu Tue Aug 10 17:11:12 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 10 Aug 2010 14:11:12 -0700 Subject: python interview quuestions In-Reply-To: <877hjykxjy.fsf@agentultra.com> References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> Message-ID: On Tue, Aug 10, 2010 at 1:44 PM, J Kenneth King wrote: > James Mills writes: > >> On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: >>>> I would like to aquint myself with Python Interview questions >>> >>> This came up a while ago: >>> >>> http://www.mail-archive.com/python-list at python.org/msg168961.html >>> >>> Most of that thread is still relevant (perhaps throw in some py3l questions >>> too) >> >> A common thing you can do in interviews is ask >> your interviewee to write (in Python) a solution >> to the "FizzBuzz" problem. Any good competent >> Python programmer should be able to do this >> in 5-10mins (5 if you're good). >> >> cheers >> james > > Fizzbuzz is annoying in interviews. > > I've never worked at a job where I was under a timer while a group of > people sat across from me and scrutinized everything I was doing. > > I don't see how it can honestly tell you anything useful about the > person you're interviewing either. ?Do you really think that what you > assume about the interviewee based on characteristics you can infer from > their solution to be really, honestly true? ?They might even completely > bomb the solution and still be a brilliant programmer, but you'll never > know that if you trust this simple "fizzbuzz" test. > The interviews where I've been asked to write code, the interviewers had almost no interest in the code I actually wrote. They wanted me to think out loud, to see how I approached the problem. To make sure I did actually know how to program and not just copy/paste from a text book. > I've been in those interviews on both sides of the table. ?Neither side > was a good experience. > > If a test is necessary, make it a take-home or demand source code if > they have it. ?Read their code and judge for yourself the quality of > their work. > > Any questions in an interview should be the usual "get to know you" type > stuff. ?"What was the most difficult challenge you've faced on the job? > How did you respond?" ?That sort of thing. > -- Now those questions are completely useless for those of us still in school. Because almost nothing we've done so far really says anything about how we'll do on the job. When I get an interview like that, I usually end up with the same 2-3 responses to every single question, because those are the only experieces I've had outside of "well I had this tough homework assignment". From atyazdi at ucdavis.edu Tue Aug 10 17:35:07 2010 From: atyazdi at ucdavis.edu (Anahita Yazdi) Date: Tue, 10 Aug 2010 14:35:07 -0700 Subject: Image histogram In-Reply-To: References: Message-ID: Yes, my question is regarding PIL. And basically I need to reload an image given a new histogram. The new histogram has still the same amount of overall pixels however I have only switched a couple of picks. Another thing I have tried was using a function that could be given to the "point" module but problem with that was that I didnt want to apply the function to every single count in the histogram. I only need to change two or three picks there. Is this something that could be done with PIL modules at all? Thank you and sorry for the confusion, Anahita On Mon, Aug 9, 2010 at 4:27 PM, Anahita Yazdi wrote: > Hi, > I was just wondering how would I be able to get some extra help regarding > editing an image's histogram using python's module? I have modified a > histogram of an image however I dont know how to apply the new histogram to > the image and basically reload the image based on its new modified histogram > instead of its own histogram? In the other words how should I make changes > on an image's histogram in a way that the image recognizes the new histogram > and gets changed? I need to somehow introduce a LUT for the image and use > ".point(table)" function to reload the image however I am not sure how to > make the right LUT from a modified histogram! > Thanks for the help in advance, > Anahita > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff.hobbs at gmail.com Tue Aug 10 17:51:14 2010 From: jeff.hobbs at gmail.com (Jeff Hobbs) Date: Tue, 10 Aug 2010 14:51:14 -0700 (PDT) Subject: File Manager in Tkinter References: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> <770366ta10gk98vgd5n2tapl7ag6skaeaj@4ax.com> Message-ID: On Aug 10, 9:43?am, John wrote: > On Tue, 10 Aug 2010 09:20:31 -0700 (PDT), Jeff ?Hobbs > > > > wrote: > >On Aug 9, 9:53?pm, John wrote: > >> As a learning exercise in Tkinter I htought about making a very simple > >> and basic file manager for my own use. I tried searching google for > >> any sample project and could not find anything. Not exactly ?sure how > >> to start I tought I could ask here? > > >> I thought about making two listboxes one to list folders only the > >> other files inside. I tried to make one listbox first but did not know > >> how to list folders only. > > >Filter with os.path.isdir() > > >> Is there a way to list folders with images? > >> Any suggestions or help how to proced would be appreciated. > > >If you are using a Tkinter with Ttk (Tk 8.5), then use the treeview > >widget: > > >http://docs.activestate.com/activepython/3.1/python/library/tkinter.t... > > >For more advanced needs, there is a Tk extension called tktreectrl > >that does some very cool views and has lots of controls: > > >http://tktreectrl.sourceforge.net/ > > >Jeff > > My python is version 2.6.5. ?Would you recomend I upgrade and if yes > to which version? The version of python really isn't tightly coupled to the version of Tk, it is the configuration of how that python is built. ActivePython builds with Tk 8.5, so if you are using that, and it is < v3.1 (where ttk is in the core), then just do: pypm install pyttk which will install the wrapper you need for Ttk into v2.6 or 2.7 python. You need to make sure that you have Tk 8.5 (Tkinter.TkVersion >= 8.5) for ttk to work (though not technically true, the 8.4 tile version has subtle differences). The core python distro is still using the older Tk 8.4 in stock installers iiuc. Jeff From John Tue Aug 10 18:01:10 2010 From: John (John) Date: Tue, 10 Aug 2010 18:01:10 -0400 Subject: File Manager in Tkinter References: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> <770366ta10gk98vgd5n2tapl7ag6skaeaj@4ax.com> Message-ID: On Tue, 10 Aug 2010 14:51:14 -0700 (PDT), Jeff Hobbs wrote: >On Aug 10, 9:43?am, John wrote: >> On Tue, 10 Aug 2010 09:20:31 -0700 (PDT), Jeff ?Hobbs >> >> >> >> wrote: >> >On Aug 9, 9:53?pm, John wrote: >> >> As a learning exercise in Tkinter I htought about making a very simple >> >> and basic file manager for my own use. I tried searching google for >> >> any sample project and could not find anything. Not exactly ?sure how >> >> to start I tought I could ask here? >> >> >> I thought about making two listboxes one to list folders only the >> >> other files inside. I tried to make one listbox first but did not know >> >> how to list folders only. >> >> >Filter with os.path.isdir() >> >> >> Is there a way to list folders with images? >> >> Any suggestions or help how to proced would be appreciated. >> >> >If you are using a Tkinter with Ttk (Tk 8.5), then use the treeview >> >widget: >> >> >http://docs.activestate.com/activepython/3.1/python/library/tkinter.t... >> >> >For more advanced needs, there is a Tk extension called tktreectrl >> >that does some very cool views and has lots of controls: >> >> >http://tktreectrl.sourceforge.net/ >> >> >Jeff >> >> My python is version 2.6.5. ?Would you recomend I upgrade and if yes >> to which version? > >The version of python really isn't tightly coupled to the version of >Tk, it is the configuration of how that python is built. ActivePython >builds with Tk 8.5, so if you are using that, and it is < v3.1 (where >ttk is in the core), then just do: > pypm install pyttk >which will install the wrapper you need for Ttk into v2.6 or 2.7 >python. You need to make sure that you have Tk 8.5 (Tkinter.TkVersion >>= 8.5) for ttk to work (though not technically true, the 8.4 tile >version has subtle differences). The core python distro is still >using the older Tk 8.4 in stock installers iiuc. > >Jeff My version is from python.org can I upgrade my version to 8.5? tia for all the help much appreciated. From peter.milliken at gmail.com Tue Aug 10 18:51:31 2010 From: peter.milliken at gmail.com (Peter) Date: Tue, 10 Aug 2010 15:51:31 -0700 (PDT) Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> Message-ID: <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Agreed. Although anything that involves "take home" or reading of "their" code runs the risk of the candidate presenting somebody else's work... It was never a good experience being responsible for the hiring of somebody based on how well they sell themselves in an interview - some people are hopeless "sales people" and yet could be fantastic programmers! I mean lets face it, if you were good at selling would you still be a programmer? :-) I know who makes the most money! Of course there is the question of job satisfaction... I usually just tried to get a feel for their stated experience and ask some questions just to make sure they weren't presenting somebodies else's (fictitious even!) resume. You generally make the best decision based on a number of factors about each candidate and depend on the 3 or 6 month "trial" period to weed out any bad mistakes you may have made during selection! I remember one team I managed had an individual from overseas (I won't mention the country or anything) - and therefore background checks by HR were not really possible. The person made so many fundamental mistakes that I went to the project manager and asked to see the resume - there was no way in this world that they had ever done even 1/100th of what their resume stated! :-) Obviously the interviewers for that person where completely conned and missed the (what should have been) obvious signs that the resume and candidate did not match. This was one of the many reasons why I decided on a career change and went back to being a dumb and happy programmer! That was 14 years ago now and I haven't regretted the decision one single day of that time :-) Peter On Aug 11, 6:44?am, J Kenneth King wrote: > James Mills writes: > > On Sat, Aug 7, 2010 at 4:32 AM, Tim Chase wrote: > >>> I would like to aquint myself with Python Interview questions > > >> This came up a while ago: > > >> http://www.mail-archive.com/python-l... at python.org/msg168961.html > > >> Most of that thread is still relevant (perhaps throw in some py3l questions > >> too) > > > A common thing you can do in interviews is ask > > your interviewee to write (in Python) a solution > > to the "FizzBuzz" problem. Any good competent > > Python programmer should be able to do this > > in 5-10mins (5 if you're good). > > > cheers > > james > > Fizzbuzz is annoying in interviews. > > I've never worked at a job where I was under a timer while a group of > people sat across from me and scrutinized everything I was doing. > > I don't see how it can honestly tell you anything useful about the > person you're interviewing either. ?Do you really think that what you > assume about the interviewee based on characteristics you can infer from > their solution to be really, honestly true? ?They might even completely > bomb the solution and still be a brilliant programmer, but you'll never > know that if you trust this simple "fizzbuzz" test. > > I've been in those interviews on both sides of the table. ?Neither side > was a good experience. > > If a test is necessary, make it a take-home or demand source code if > they have it. ?Read their code and judge for yourself the quality of > their work. > > Any questions in an interview should be the usual "get to know you" type > stuff. ?"What was the most difficult challenge you've faced on the job? > How did you respond?" ?That sort of thing. From martin at v.loewis.de Tue Aug 10 20:06:57 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 11 Aug 2010 02:06:57 +0200 Subject: Why is python not written in C++ ? In-Reply-To: <9da7j7-pv2.ln1@satorlaser.homedns.org> References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> Message-ID: <4C61E9A1.5090800@v.loewis.de> Am 10.08.2010 09:06, schrieb Ulrich Eckhardt: > Carl Banks wrote: >> I highly doubt the Python source would build with a C++ compiler. > > As Christian showed, it doesn't. However, look around the sources a bit. > There are lots of places where e.g. the returnvalue of malloc() (or, > rather, the macro that resolves to something like it) is explicitly > type-cast to the according pointer type. When asked on the developers' > list, it was said that this was intended for compatibility with C++, e.g. > in cases where people want to embed Python into their C++ projects. Of > course, this contradicts Christian's statement that C++ compatibility > wasn't considered useful enough. It doesn't contradict at all. In order to embed Python into a C++ application, it is sufficient if the Python header files can be compiled with a C++ compiler, and linking to the C function works properly - which is indeed the case. People integrate Python with C++ quite often, both for embedding it into C++, and for writing extension modules in C++. Regards, Martin From roy at panix.com Tue Aug 10 20:08:14 2010 From: roy at panix.com (Roy Smith) Date: Tue, 10 Aug 2010 20:08:14 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: In article <507f1970-9c15-4200-a90b-6ebc018c074b at a4g2000prm.googlegroups.com>, Peter wrote: > Agreed. Although anything that involves "take home" or reading of > "their" code runs the risk of the candidate presenting somebody else's > work... I expect a candidate to emphasize their positive qualities, perhaps even exaggerate a little. The point of a technical interview is to assess just how much of each :-) What I do NOT expect is outright prevarication. I go into the interview with the assumption that the candidate is, if nothing else, honest. In any case, if the candidate were to submit somebody else's work, it would come out pretty quickly as we discussed their code. I suppose one question I might ask would be, "Can you explain why, when I copy-paste one of your comments into a google search box, your entire program appears?" > I usually just tried to get a feel for their stated experience and ask > some questions just to make sure they weren't presenting somebodies > else's (fictitious even!) resume. Amazingly enough, that does happen. I once got two resumes in the same pile which were word-for-word identical, except for the name on the top. I've been around the block a few times, but I was still shocked. I'm not sure what was more shocking; that people could be that dishonest, or that they could be so clumsy and stupid about it. From candide at free.invalid Tue Aug 10 20:37:08 2010 From: candide at free.invalid (candide) Date: Wed, 11 Aug 2010 02:37:08 +0200 Subject: Splitting a sequence into pieces with identical elements Message-ID: <4c61f0c2$0$30068$426a34cc@news.free.fr> Suppose you have a sequence s , a string for say, for instance this one : spppammmmegggssss We want to split s into the following parts : ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] ie each part is a single repeated character word. What is the pythonic way to answer this question? A naive solution would be the following : # ------------------------------- z='spppammmmegggssss' zz=[] while z: k=1 while z[:k]==k*z[0]: k+=1 zz+=[z[:k-1]] z=z[k-1:] print zz # ------------------------------- but I guess this code is not very idiomatic :( From clp2 at rebertia.com Tue Aug 10 21:11:00 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 10 Aug 2010 18:11:00 -0700 Subject: Splitting a sequence into pieces with identical elements In-Reply-To: <4c61f0c2$0$30068$426a34cc@news.free.fr> References: <4c61f0c2$0$30068$426a34cc@news.free.fr> Message-ID: On Tue, Aug 10, 2010 at 5:37 PM, candide wrote: > Suppose you have a sequence s , a string ?for say, for instance this one : > > spppammmmegggssss > > We want to split s into the following parts : > > ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] > > ie each part is a single repeated character word. > > What is the pythonic way to answer this question? If you're doing an operation on an iterable, always leaf thru itertools first: http://docs.python.org/library/itertools.html from itertools import groupby def split_into_runs(seq): return ["".join(run) for letter, run in groupby(seq)] If itertools didn't exist: def split_into_runs(seq): if not seq: return [] iterator = iter(seq) letter = next(iterator) count = 1 words = [] for c in iterator: if c == letter: count += 1 else: word = letter * count words.append(word) letter = c count = 1 words.append(letter*count) return words Cheers, Chris -- http://blog.rebertia.com From python.list at tim.thechases.com Tue Aug 10 21:18:36 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 10 Aug 2010 20:18:36 -0500 Subject: Splitting a sequence into pieces with identical elements In-Reply-To: <4c61f0c2$0$30068$426a34cc@news.free.fr> References: <4c61f0c2$0$30068$426a34cc@news.free.fr> Message-ID: <4C61FA6C.4010907@tim.thechases.com> On 08/10/10 19:37, candide wrote: > Suppose you have a sequence s , a string for say, for instance this one : > > spppammmmegggssss > > We want to split s into the following parts : > > ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] > > ie each part is a single repeated character word. While I'm not sure it's idiomatic, the overabuse of regexps in Python certainly seems prevalent enough to be idiomatic ;-) As such, you can use: import re r = re.compile(r'((.)\1*)') #r = re.compile(r'((\w)\1*)') s = 'spppammmmegggssss' results = [m.group(0) for m in r.finditer(s)] Additionally, you have all the properties of the match-object (which includes the start/end) available too if you need). You don't specify what you want to have happen with non-letters (whitespace, punctuation, etc). The above just treats them like any other character, finding repeats. If you just want "word" characters, you can use the 2nd ("\w") version, or adjust accordingly. -tkc From python at mrabarnett.plus.com Tue Aug 10 21:30:49 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 02:30:49 +0100 Subject: Splitting a sequence into pieces with identical elements In-Reply-To: <4C61FA6C.4010907@tim.thechases.com> References: <4c61f0c2$0$30068$426a34cc@news.free.fr> <4C61FA6C.4010907@tim.thechases.com> Message-ID: <4C61FD49.9070704@mrabarnett.plus.com> Tim Chase wrote: > On 08/10/10 19:37, candide wrote: >> Suppose you have a sequence s , a string for say, for instance this >> one : >> >> spppammmmegggssss >> >> We want to split s into the following parts : >> >> ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] >> >> ie each part is a single repeated character word. > > While I'm not sure it's idiomatic, the overabuse of regexps in Python > certainly seems prevalent enough to be idiomatic ;-) > > As such, you can use: > > import re > r = re.compile(r'((.)\1*)') > #r = re.compile(r'((\w)\1*)') That should be \2, not \1. Alternatively: r = re.compile(r'(.)\1*') #r = re.compile(r'(\w)\1*') > s = 'spppammmmegggssss' > results = [m.group(0) for m in r.finditer(s)] > > Additionally, you have all the properties of the match-object (which > includes the start/end) available too if you need). > > You don't specify what you want to have happen with non-letters > (whitespace, punctuation, etc). The above just treats them like any > other character, finding repeats. If you just want "word" characters, > you can use the 2nd ("\w") version, or adjust accordingly. > From ritchy_gato at hotmail.com Tue Aug 10 22:01:41 2010 From: ritchy_gato at hotmail.com (Ritchy lelis) Date: Tue, 10 Aug 2010 19:01:41 -0700 (PDT) Subject: How to implement a pipeline...??? Please help References: <5242b005-31b6-4a9c-afd9-6fbb82e28db7@l14g2000yql.googlegroups.com> Message-ID: <08ce00ca-f58e-4ff4-a95e-54f7a4d5071f@w30g2000yqw.googlegroups.com> On 7 Ago, 07:30, Dennis Lee Bieber wrote: > On Fri, 6 Aug 2010 16:47:58 -0700 (PDT), Ritchy lelis > declaimed the following in > gmane.comp.python.general: > > > Guys i'm asking if it's possible for a generic function for a > > pipeline, all the suggestions ideas are welcome. > > ? ? ? ? I've not done metaclasses, so don't know if a metaclass would be of > use... Since it appears one would have to have something that generates > functions on the fly based upon inputs... > > ? ? ? ? I look at details on what you are trying to create and see a > series-parallel circuit architecture with clocked stages and delay lines > for the summing of the outputs. That is, when the clock ticks, every > stage in the unit does its processing and provides and output... On the > next tick, those outputs become inputs to the subsequent stage and the > process repeats > > > Also if you have a specific solution for my problem I will be grateful > > for it here. > > ? ? ? ? I'm still blinking at the thought of doing analog to digital > conversion in Python! I sure wouldn't hold out much hope of real-time > signal processing. There is a reason ADC and DAC are done in hardware, > even if the intermediate processing is with general purpose processors. > > ? ? ? ? I'm also not sure I understand the > > np.linspace(1,1, Inc)... > > ? ? ? ? Looking up documentation implies you are trying to create a vector > of "inc" length, evenly populated by values between 1 and 1... which > means a vector of all 1s... Might it not be faster to just > > ? ? ? ? v = [1] * inc > > and pass v to some numpy method for conversion from Python list to numpy > vector? > > (the -1 to 1 at least makes sense) > > ? ? ? ? Me? I'd probably create a class in which the __init__() takes a > value specifying the number of stages. It would than create suitable > lists to track values, some sort of counter (c), a Semaphore (s) > [initialized at 0 -- ie, already acquired/block], ?a thread for EACH > stage, and an Event (e) object > > ? ? ? ? Each stage thread, initialized with its position in the pipeline. > The threads perform an e.wait() call. They also, after the wait is > released, perform an e.clear() call. As their processing, they each grab > from the pipeline "input" list the current value for their position. > After processing they update their position in the "output" list(s), > they decrement the counter c (maybe put a lock around access to c). The > thread that decrements c to 0 is responsible for "releasing" the > semaphore. > > ? ? ? ? The main code of the class instance is responsible for a loop that > does: set up the "input" list based on current value of stage outputs, > initialize c to the count of stages (minus 1?), e.set() to signal all > stage threads to process the current conditions, s.acquire() to block > until the last processed thread (by c hitting 0) does s.release(). It > then collects the output lists, does whatever shifting is needed to > prepare for the next cycle... > > ? ? ? ? Actually, that "loop" may not be a loop so much as a method off the > class like > > ? ? ? ? digitalOutput = adcInstance.step(analogInput) > > which is, itself, in a loop. > > That is, something like... > > myADC = ADC(stages=10) > while True: > ? ? ? ? voltage = getNextAnalogInput() > ? ? ? ? digital = myADC.step(voltage) > ? ? ? ? outputDigitalValue() > > ? ? ? ? Obviously I've not taken the time to actually lay out all the > instance lists needed for inputs and outputs, nor the code of threads > (while one can create the first "stages-1" threads with a loop, the > final stage needs a discrete creation) > > ? ? ? ? When one finds that the threading solution is really slow (though > understandable in terms of the hardware circuit -- one thread per stage > makes the stages easy to code), THEN one might try to figure out how to > implement an iterative version... I suspect using numpy would be the > third optimization -- removing iteration by using parallel vector > operations. > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ Hi First of all i would like to thank you for your time and help. I appreciate your suggestions and they seems very good to me... The only problem it's that i'm newbie at python programming, but still interested to learn more and more... I already got a solution through harsh but it worked. at least I got the wave form i wanted. Next i'm going to let you'll my solution here. It's rudimentary but it work's. Seems very perceptible that's why i will not explain it right now but if in case of doubt I will: Pipeline Function: from flash1b5 import flash1b5 from flash1b5 import * from flash2b import flash2b from flash2b import * import matplotlib.pyplot as plt import numpy as np from pylab import * if __name__ == "__main__": Inc = raw_input("Valor do Incrimento = ") Vref = np.linspace(1,1, Inc) Vi = np.linspace(-1,1, Inc) # x = np.linspace(-1,1, Inc) # Vi = 1*sin(2*pi*(x-1/4)) Cs = np.linspace(3e-12, 3e-12, Inc) Cf = np.linspace(3e-12, 3e-12, Inc) f1 = flash1b5(Vi, Vref, Cs, Cf) Vin1 = f1[0] Vt1 = f1[1] Vd1 = f1[2]*256 f2 = flash1b5(Vt1, Vref, Cs, Cf) Vin2 = f2[0] Vt2 = f2[1] Vd2 = f2[2]*128 f3 = flash1b5(Vt2, Vref, Cs, Cf) Vin3 = f3[0] Vt3 = f3[1] Vd3 = f3[2]*64 f4 = flash1b5(Vt3, Vref, Cs, Cf) Vin4 = f4[0] Vt4 = f4[1] Vd4 = f4[2]*32 f5 = flash1b5(Vt4, Vref, Cs, Cf) Vin5 = f5[0] Vt5 = f5[1] Vd5 = f5[2]*16 f6 = flash1b5(Vt5, Vref, Cs, Cf) Vin6 = f6[0] Vt6 = f6[1] Vd6 = f6[2]*8 f7 = flash1b5(Vt6, Vref, Cs, Cf) Vin7 = f7[0] Vt7 = f7[1] Vd7 = f7[2]*4 f8 = flash1b5(Vt7, Vref, Cs, Cf) Vin8 = f8[0] Vt8 = f8[1] Vd8 = f8[2]*2 f2b = flash2b(Vt8, Vref) Vin2b = f2b[0] Vd2b = f2b[1]*1 Vd = Vd1+Vd2+Vd3+Vd4+Vd5+Vd6+Vd7+Vd8+Vd2b ## print 'Vin = ',Vin ## print 'Vt = ',Vt ## print 'Vd = ',Vd ## # fig1 = figure(1,figsize=(8,5)) # ax1 = fig1.add_subplot(211, autoscale_on=False, xlim=(-1,1), ylim=(-1,1)) # ax1.plot(Vin1, Vt4, lw=2, color='blue') # grid (True); title('FLASH 1.5 BIT',fontsize = 16);ylabel('Vout_Residuo') ## ## ax1.annotate('00', xy=(-0.5, 0.5)) ## ax1.annotate('01', xy=(0.0, 0.5)) ## ax1.annotate('11', xy=(0.5, 0.5)) # ## hold(True) # fig2 = figure(1,figsize=(8,5)) ax2 = fig2.add_subplot(111, autoscale_on=True) ax2.plot(Vin1, Vd, lw=2, color='red') grid (True); xlabel('Vin');ylabel('Vout_Digital') # ## ax2.annotate('00 --> 0', xy=(-0.5, 0.1)) ## ax2.annotate('01 --> 1', xy=(0.0, 1.1)) ## ax2.annotate('11 --> 2', xy=(0.5, 2.1)) ## # plt.show() -------------------------------------------------------------------------- About the answer i got for my last post: 1 - v = [1] * inc > > and pass v to some numpy method for conversion from Python list to numpy > vector? Yes i agree with you, but at the time i made it i found that function (Linspace) that could do what i was loking for and i didn't worry about search for a better solution. but even if wanted to, i'm new at the programming language and i don't know how to convert a list to a vector in numpy. but still open for tips/tricks that could help me. 2 - > Me? I'd probably create a class in which the __init__() takes a > value specifying the number of stages. It would than create suitable > lists to track values, some sort of counter (c), a Semaphore (s) > [initialized at 0 -- ie, already acquired/block], a thread for EACH > stage, and an Event (e) object > Each stage thread, initialized with its position in the pipeline. > The threads perform an e.wait() call. They also, after the wait is > released, perform an e.clear() call. As their processing, they each grab > from the pipeline "input" list the current value for their position. > After processing they update their position in the "output" list(s), > they decrement the counter c (maybe put a lock around access to c). The > thread that decrements c to 0 is responsible for "releasing" the > semaphore I did understand your algorithm/idea and that's what i want to implement here (you couldn't be more right). but i don't now how to implement the funcs e.wait() call and e.clear() call. they already exists? i have to create them? if I may, i would like to ask more help on this one please. I hope not to be bothering you :( From darkrho at gmail.com Tue Aug 10 22:27:32 2010 From: darkrho at gmail.com (Rolando Espinoza La Fuente) Date: Tue, 10 Aug 2010 22:27:32 -0400 Subject: python interview quuestions In-Reply-To: <4C5CC582.5080005@tim.thechases.com> References: <4C5C5528.5060608@tim.thechases.com> <4C5CC582.5080005@tim.thechases.com> Message-ID: On Fri, Aug 6, 2010 at 10:31 PM, Tim Chase wrote: [...] >> More over, it can be done in just a single line of Python. >> >> 7 if you're not very familiar with Python. > > While it *can* be done in one line, I'm not sure it's the most legible > solution. ?Though I must say I like this one-line python version: > > for i in range(1, 101): print ((i%3==0 and 'fizz' or '') + (i%5==0 and > 'buzz' or '')) or i > > (adjust "3" and "5" for your local flavor of fizzbuzz) > > I'm not sure I'd hire a candidate that proposed this as a solution in > earnest, but I'd have fun chatting with them :) I didn't believe it could take more than 5 minutes, but this took me ~10 minutes, though I'm familiar with python and I did the FizzBuzz one-liners before: http://gist.github.com/518370 Well.. I tried to use generators to make it "cool" but changed it for a test-friendly approach. I'll find hard to remember the one-liners in an interview and get it right. Rolando Espinoza La fuente www.insophia.com From python.list at tim.thechases.com Tue Aug 10 22:31:09 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 10 Aug 2010 21:31:09 -0500 Subject: Splitting a sequence into pieces with identical elements In-Reply-To: <4C61FD49.9070704@mrabarnett.plus.com> References: <4c61f0c2$0$30068$426a34cc@news.free.fr> <4C61FA6C.4010907@tim.thechases.com> <4C61FD49.9070704@mrabarnett.plus.com> Message-ID: <4C620B6D.90303@tim.thechases.com> On 08/10/10 20:30, MRAB wrote: > Tim Chase wrote: >> r = re.compile(r'((.)\1*)') >> #r = re.compile(r'((\w)\1*)') > > That should be \2, not \1. > > Alternatively: > > r = re.compile(r'(.)\1*') Doh, I had played with both and mis-transcribed the combination of them into one malfunctioning regexp. My original trouble with the 2nd one was that r.findall() (not .finditer) was only returning the first letter of each because that's what was matched. Wrapping it in the extra set of parens and using "\2" returned the actual data in sub-tuples: >>> s = 'spppammmmegggssss' >>> import re >>> r = re.compile(r'(.)\1*') >>> r.findall(s) # no repeated text, just the initial letter ['s', 'p', 'a', 'm', 'e', 'g', 's'] >>> [m.group(0) for m in r.finditer(s)] ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] >>> r = re.compile(r'((.)\2*)') >>> r.findall(s) [('s', 's'), ('ppp', 'p'), ('a', 'a'), ('mmmm', 'm'), ('e', 'e'), ('ggg', 'g'), ('ssss', 's')] >>> [m.group(0) for m in r.finditer(s)] ['s', 'ppp', 'a', 'mmmm', 'e', 'ggg', 'ssss'] By then changing to .finditer() it made them both work the way I wanted. Thanks for catching my mistranscription. -tkc From ldo at geek-central.gen.new_zealand Tue Aug 10 22:57:27 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 14:57:27 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message , Alex Barna wrote: > On Aug 10, 10:05 am, Lawrence D'Oliveiro > >> Can?t understand the point to it. ?GUI automation? is a contradiction in >> terms, because a GUI is designed for use by humans to do manual tasks, >> not ones that can be automated. > > Automating GUI is for testing. But the most egregious GUI problems are going to be with humans being unable to figure out how to do something, am I right? How are you going to uncover those problems, except by testing with real people? Automated testing isn?t going to do it. From ldo at geek-central.gen.new_zealand Tue Aug 10 22:59:14 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 14:59:14 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c61a4f5$0$5804$426a34cc@news.free.fr> Message-ID: In message <4c61a4f5$0$5804$426a34cc at news.free.fr>, News123 wrote: > On 08/10/2010 12:25 PM, Alex Barna wrote: > >> On Aug 10, 10:05 am, Lawrence D'Oliveiro >> >>> Can?t understand the point to it. ?GUI automation? is a contradiction in >>> terms, because a GUI is designed for use by humans to do manual tasks, >>> not ones that can be automated. >> >> Automating GUI is for testing. > > And sometimesfor working around SW, whch has no cli or other interface > and should be automated Who would design software in such a brain-dead way? From invalid at invalid.invalid Tue Aug 10 23:06:49 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 03:06:49 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message >, Alex > Barna wrote: > >> On Aug 10, 10:05 am, Lawrence D'Oliveiro >> >>> Can???t understand the point to it. ???GUI automation??? is a contradiction in >>> terms, because a GUI is designed for use by humans to do manual tasks, >>> not ones that can be automated. >> >> Automating GUI is for testing. > > But the most egregious GUI problems are going to be with humans being > unable to figure out how to do something, am I right? How are you > going to uncover those problems, except by testing with real people? > Automated testing isn???t going to do it. Automated GUI testing isn't intended to uncover those sorts of problems in GUI design. Automated GUI intended to uncover problems in the underlying program functionality, and is used mainly for regression testing to insure that changes made to a program didn't cause any unintended changes in program behavior. Automated GUI testing often isn't even being used to test the program whos GUI is being automated. It's often used to test _other_ programs with which the GUI-automated-program interacts. -- Grant From invalid at invalid.invalid Tue Aug 10 23:08:18 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 03:08:18 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c61a4f5$0$5804$426a34cc@news.free.fr> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message <4c61a4f5$0$5804$426a34cc at news.free.fr>, News123 wrote: >> On 08/10/2010 12:25 PM, Alex Barna wrote: >>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>> >>>> Can???t understand the point to it. ???GUI automation??? is a >>>> contradiction in terms, because a GUI is designed for use by humans >>>> to do manual tasks, not ones that can be automated. >>> >>> Automating GUI is for testing. >> >> And sometimesfor working around SW, whch has no cli or other >> interface and should be automated > > Who would design software in such a brain-dead way? In my experience, almost everybody who designes apps for MS Windows. -- Grant From cs at zip.com.au Tue Aug 10 23:08:59 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 11 Aug 2010 13:08:59 +1000 Subject: How to capture all the environment variables from shell? In-Reply-To: <4C615D1B.7060204@syslang.net> References: <4C615D1B.7060204@syslang.net> Message-ID: <20100811030859.GA2279@cskk.homeip.net> On 10Aug2010 10:07, Steven W. Orr wrote: | On 8/2/2010 4:33 AM, Thorsten Kampe wrote: | > * Tim Chase (Mon, 26 Jul 2010 21:42:24 -0500) | >> On 07/26/10 21:26, Steven W. Orr wrote: | >>> Please! Never export anything from your .bashrc unless you | >>> really know what you're doing. Almost all exports should be | >>> done in your .bash_profile | >> | >> Could you elaborate on your reasoning why (or why-not)? I've | >> found that my .bash_profile doesn't get evaluated when I crank up | >> another terminal window, while my bashrc does. Thus I tend to | >> put my exports in my ~/.bashrc so they actually take effect in my | >> shell... | > | > ~/.bash_profile is only evaluated for login shells and ~/.bashrc only | > for non-login shells. Thus it's recommended to keep ~/.bash_profile | > empty (except a source statement for .bashrc) and put all your settings, | > aliases, exports, etc. in .bashrc. | | Sorry. Dead wrong. Please reread the above comment I wrote. If you set your | environment variables in the .bashrc then you completely lose the ability of | environment variables to be inherited by sub-shells. Again, envvars should be | set in the .bash_profile, most everything else should be set in the .bashrc, and | the .bashrc should be sourced into the .bash_profile to solve the problem that | you thought you were solving. | | After that, and again, be aware that the .bashrc alone is executed for login | shells *which are not interactive*. for example: | | ssh somemachine 'echo Hello' | | This command will *not* go through the .bash_profile but it will go through the | .bashrc. No, only interactive shells use the .bashrc. Still, you're quite right that envvars belong in the .bash_profile. .bashrc is for trivial setup stuff relevant only to interactive shells (for example history settings and interactive aliases). | This means that for cases like this, we want to check to see if the | bash process is interactive or not inside the .bashrc and then do the right thing. | | =============== | [[ -z "$PS1" ]] && setPATHHere | =============== This is Very Wrong. (RedHat do this test - it is bogus - if I set $PS1 in my profile it breaks badly.) Instead, test $-: case $- in *i*) echo INTERACTIVE ;; *) echo BATCH ;; esac | This is not needed for the above degenerate case, but it is needed if the | command in question is kept in a directory that you normally find in a place | that is part of your personal login PATH. E.G., If myprog lives in ~/bin then | | ssh somemachine myprog | | will fail unless you use the above construct. | | Hopefully, I'll only have to re-explain this another google times... "googol", surely? The reason .bashrc gets overused for envars, aside from ignorance and propagated bad habits, is that in a GUI desktop the setup sequence is often a bit backwards. A conventional terminal/console login means you get a login shell that sources your .{bash_}profile. And from there one would start a GUI and all the .profile stuff has been run Once, as it should be. But when the login itself is a GUI the various terminals get started _before_ the .profile stuff gets sourced, because the terminal is started by the desktop manager. Once common "fix" for this is to make all new terminals run login shells. Ugh, but it does work. But it they're not login shells, people stuff everything into their .bashrc because the .profile doesn't get sourced. And so the common awful setup you're bemoaning. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ For us, Zettai Zetsumei Toshi is an allegory for relations between the sexes, and it works especially well at this because we don't speak Japanese. She will say things, and we have no idea what the hell is going on, and then we'll select from a list of responses, but we have no idea which one is the right one, and then they're all wrong. It works on a lot of levels. - Tycho @ _Penny_Arcade_ From robert.kern at gmail.com Tue Aug 10 23:11:02 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 10 Aug 2010 22:11:02 -0500 Subject: GUI automation tool (windows) In-Reply-To: References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-10 21:57 , Lawrence D'Oliveiro wrote: > In message > , Alex > Barna wrote: > >> On Aug 10, 10:05 am, Lawrence D'Oliveiro >> >>> Can?t understand the point to it. ?GUI automation? is a contradiction in >>> terms, because a GUI is designed for use by humans to do manual tasks, >>> not ones that can be automated. >> >> Automating GUI is for testing. > > But the most egregious GUI problems are going to be with humans being unable > to figure out how to do something, am I right? Possibly, but it's not the *only* important problem. Automated GUI testing is usually a form of regression testing. You want to make sure that the behavior of parts of the GUI did not change when you made what should be unrelated modifications to the code. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Tue Aug 10 23:12:33 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 10 Aug 2010 22:12:33 -0500 Subject: GUI automation tool (windows) In-Reply-To: References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c61a4f5$0$5804$426a34cc@news.free.fr> Message-ID: On 2010-08-10 21:59 , Lawrence D'Oliveiro wrote: > In message<4c61a4f5$0$5804$426a34cc at news.free.fr>, News123 wrote: > >> On 08/10/2010 12:25 PM, Alex Barna wrote: >> >>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>> >>>> Can?t understand the point to it. ?GUI automation? is a contradiction in >>>> terms, because a GUI is designed for use by humans to do manual tasks, >>>> not ones that can be automated. >>> >>> Automating GUI is for testing. >> >> And sometimesfor working around SW, whch has no cli or other interface >> and should be automated > > Who would design software in such a brain-dead way? People who are not being paid for a CLI or other interface. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From cs at zip.com.au Tue Aug 10 23:16:01 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 11 Aug 2010 13:16:01 +1000 Subject: How to capture all the environment variables from shell? In-Reply-To: <20100811030859.GA2279@cskk.homeip.net> References: <20100811030859.GA2279@cskk.homeip.net> Message-ID: <20100811031601.GA4188@cskk.homeip.net> On 11Aug2010 13:08, I wrote: | On 10Aug2010 10:07, Steven W. Orr wrote: [...] | | After that, and again, be aware that the .bashrc alone is executed for login | | shells *which are not interactive*. for example: | | | | ssh somemachine 'echo Hello' | | | | This command will *not* go through the .bash_profile but it will go through the | | .bashrc. | | No, only interactive shells use the .bashrc. And then I read more closely and saw this in "man bash": Bash attempts to determine when it is being run by the remote shell daemon, usually rshd. If bash determines it is being run by rshd, it reads and executes commands from ~/.bashrc, if that file exists and is readable. It will not do this if invoked as sh. The --norc option may be used to inhibit this behavior, and the --rcfile option may be used to force another file to be read, but rshd does not generally invoke the shell with those options or allow them to be specified. Frankly, bash's startup behaviour is so corrupt (well, capricious anway) that I despair of it; I use zsh when possible. It also tries to be all things to all people, but is a bit saner. (And it doesn't hardwire ^W either!) Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ To be positive: To be mistaken at the top of one's voice. Ambrose Bierce (1842-1914), U.S. author. The Devil's Dictionary (1881-1906). From ben+python at benfinney.id.au Tue Aug 10 23:45:24 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 11 Aug 2010 13:45:24 +1000 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <87wrrxyfqj.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > Alex Barna wrote: > > > On Aug 10, 10:05 am, Lawrence D'Oliveiro > > > >> Can?t understand the point to it. ?GUI automation? is a > >> contradiction in terms, because a GUI is designed for use by humans > >> to do manual tasks, not ones that can be automated. > > > > Automating GUI is for testing. > > But the most egregious GUI problems are going to be with humans being > unable to figure out how to do something, am I right? You asked to understand the point of GUI automation. Alex responded with one (there may well be others) very good point of GUI automation: automated testing of the GUI's behaviour. What you raise here is not the point of GUI automation. Is you understanding of the point of GUI automation improved? -- \ ?I turned to speak to God/About the world's despair; But to | `\ make bad matters worse/I found God wasn't there.? ?Robert Frost | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Wed Aug 11 00:51:30 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 16:51:30 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message , Robert Kern wrote: > On 2010-08-10 21:57 , Lawrence D'Oliveiro wrote: > >> In message >> , Alex >> Barna wrote: >> >>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>> >>>> Can?t understand the point to it. ?GUI automation? is a contradiction >>>> in terms, because a GUI is designed for use by humans to do manual >>>> tasks, not ones that can be automated. >>> >>> Automating GUI is for testing. >> >> But the most egregious GUI problems are going to be with humans being >> unable to figure out how to do something, am I right? > > Possibly, but it's not the *only* important problem. Automated GUI testing > is usually a form of regression testing. You want to make sure that the > behavior of parts of the GUI did not change when you made what should be > unrelated modifications to the code. Again, that?s something that primarily affects real users, when they find some function is no longer in the place where they expect it to be. You have to test with real users to find out what they think of this sort of thing. From ldo at geek-central.gen.new_zealand Wed Aug 11 00:52:52 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 16:52:52 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message , Grant Edwards wrote: > Automated GUI intended to uncover problems in the underlying program > functionality ... That ?underlying? functionality has nothing to do with the GUI, then. Why not test it directly, rather than go through the GUI? > Automated GUI testing often isn't even being used to test the program > whos GUI is being automated. It's often used to test _other_ programs > with which the GUI-automated-program interacts. Again, this sounds like it has nothing to do with the GUI per se. From ben+python at benfinney.id.au Wed Aug 11 01:00:52 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 11 Aug 2010 15:00:52 +1000 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <87sk2lyc8r.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > In message , Grant Edwards wrote: > > > Automated GUI intended to uncover problems in the underlying program > > functionality ... > > That ?underlying? functionality has nothing to do with the GUI, then. Why > not test it directly, rather than go through the GUI? Because that behaviour can be different when tested in a way that doesn't involve using the actual program's interface. The GUI is part of the program's behaviour, remember, and just about any non-trivial GUI program will have quite complex behaviour specifically in its GUI. Is the concept of testing the actual program behaviour really foreign to you? If not, what part of this concept is causing you difficulty? -- \ ?Two paradoxes are better than one; they may even suggest a | `\ solution.? ?Edward Teller | _o__) | Ben Finney From magguru.anilkumar at gmail.com Wed Aug 11 01:01:03 2010 From: magguru.anilkumar at gmail.com (devi) Date: Tue, 10 Aug 2010 22:01:03 -0700 (PDT) Subject: GERMANY GIRLS SECRET SEX VIDEOS Message-ID: <7417e5b8-ed18-45cf-8508-6648e1749ce2@l25g2000prn.googlegroups.com> GERMANY GIRLS SECRET SEX VIDEOS At http://simpletoget.co.cc Due to high sex content, i have hidden the videos in an image.in that website on right side below search box click on image and watch videos in all angles. From invalid at invalid.invalid Wed Aug 11 02:09:21 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 06:09:21 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message , Robert > Kern wrote: > >> On 2010-08-10 21:57 , Lawrence D'Oliveiro wrote: >> >>> In message >>> , Alex >>> Barna wrote: >>> >>>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>>> >>>>> Can???t understand the point to it. ???GUI automation??? is a contradiction >>>>> in terms, because a GUI is designed for use by humans to do manual >>>>> tasks, not ones that can be automated. >>>> >>>> Automating GUI is for testing. >>> >>> But the most egregious GUI problems are going to be with humans being >>> unable to figure out how to do something, am I right? >> >> Possibly, but it's not the *only* important problem. Automated GUI testing >> is usually a form of regression testing. You want to make sure that the >> behavior of parts of the GUI did not change when you made what should be >> unrelated modifications to the code. > > Again, that???s something that primarily affects real users, when they find > some function is no longer in the place where they expect it to be. Automated testing can detect when some function is no longer where it used to be. > You have to test with real users to find out what they think of this > sort of thing. Again, nobody's talking about using automated testing to figure out what users think. We're talking about using automated testing to make sure that rev 3.5 acts the same what that rev 3.4 did when you push button X or select menu option Y. -- Grant From invalid at invalid.invalid Wed Aug 11 02:12:49 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 06:12:49 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> Automated GUI intended to uncover problems in the underlying program >> functionality ... > > That ???underlying??? functionality has nothing to do with the GUI, > then. Why not test it directly, rather than go through the GUI? Because in many programs _there_is_no_other_way_to_test_it_directly_. Yes, that sucks. In the real world most programs suck. You've still got to test them. >> Automated GUI testing often isn't even being used to test the program >> whos GUI is being automated. It's often used to test _other_ programs >> with which the GUI-automated-program interacts. > > Again, this sounds like it has nothing to do with the GUI per se. Exactly! That's what we've been trying to explain. Automating a GUI isn't done to test how well the GUI works for real users. It's done mainly for two purposes: 1) Regression testing to make sure that the GUI's behavior (good, bad, or indifferent) hasn't changed since the previous revision. 2) To test the functionality underlying the GUI. From tjreedy at udel.edu Wed Aug 11 02:24:11 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Aug 2010 02:24:11 -0400 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: On 8/10/2010 8:08 PM, Roy Smith wrote: > In any case, if the candidate were to submit somebody else's work, it > would come out pretty quickly as we discussed their code. I suppose one > question I might ask would be, "Can you explain why, when I copy-paste > one of your comments into a google search box, your entire program > appears?" Mostly likely because I wrote the original... would be my answer. -- Terry Jan Reedy From eckhardt at satorlaser.com Wed Aug 11 02:40:40 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 11 Aug 2010 08:40:40 +0200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> <4C61E9A1.5090800@v.loewis.de> Message-ID: <88t9j7-ri5.ln1@satorlaser.homedns.org> Martin v. Loewis wrote: > Am 10.08.2010 09:06, schrieb Ulrich Eckhardt: >> When asked on the developers' list, it was said that this was >> intended for compatibility with C++, e.g. in cases where people >> want to embed Python into their C++ projects. Of course, this >> contradicts Christian's statement that C++ compatibility >> wasn't considered useful enough. > > It doesn't contradict at all. In order to embed Python into a C++ > application, it is sufficient if the Python header files can be compiled > with a C++ compiler, and linking to the C function works > properly - which is indeed the case. That's true, maybe I don't remember the exact rationale. Especially if even someone like you, who is much deeper into Python development, doesn't, I'm wondering if I'm misremembering something.... Cheers! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From ldo at geek-central.gen.new_zealand Wed Aug 11 02:50:15 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 11 Aug 2010 18:50:15 +1200 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: In message , Grant Edwards wrote: > ... nobody's talking about using automated testing to figure out > what users think. That?s the trouble. What?s the point of a GUI, then? From girish.cfc at gmail.com Wed Aug 11 03:09:58 2010 From: girish.cfc at gmail.com (Girish) Date: Wed, 11 Aug 2010 00:09:58 -0700 (PDT) Subject: Access lotus notes using Python 2.5.1 Message-ID: Hello All, I am trying to send email using Lotos notes. When I run following commands to establish a COM connection, Python crashes with a error saying "Runtime Error.....Pythonwin.exe abnormal termination". import win32com.client session = win32com.client.Dispatch('Lotus.NotesSession') Any help is appreciated. Thanks, Girish From rNOSPAMon at flownet.com Wed Aug 11 03:11:43 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 00:11:43 -0700 Subject: Line-by-line processing when stdin is not a tty Message-ID: When stdin is not a tty, Python seems to buffer all the input through EOF before processing any of it: [ron at mickey:~]$ cat | python print 123 print 456 123 456 Is there a way to get Python to process input line-by-line the way it does when stdin is a TTY even when stdin is not a TTY? Thanks, rg From eric.brunel at pragmadev.com Wed Aug 11 03:24:46 2010 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 11 Aug 2010 09:24:46 +0200 Subject: File Manager in Tkinter References: <123f514f-2810-43f4-b557-bc7874ea4bda@o7g2000prg.googlegroups.com> <770366ta10gk98vgd5n2tapl7ag6skaeaj@4ax.com> Message-ID: In article <770366ta10gk98vgd5n2tapl7ag6skaeaj at 4ax.com>, John wrote: > My python is version 2.6.5. Would you recomend I upgrade and if yes > to which version? > > > from tkinter import ttk > > Traceback (most recent call last): > File "", line 1, in > from tkinter import ttk > ImportError: No module named tkinter On Python 2.x, the module is called Tkinter with an uppercase T. It has been changed to tkinter with a lowercase t in Python 3.x for naming consistency reasons. From ben+python at benfinney.id.au Wed Aug 11 03:27:40 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 11 Aug 2010 17:27:40 +1000 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <87ocd9y5g3.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > In message , Grant Edwards wrote: > > > ... nobody's talking about using automated testing to figure out > > what users think. > > That?s the trouble. What?s the point of a GUI, then? I've no idea what you're asking any more. The above response seems like a total non-sequitur. But the above exchange convinces me that you're asking it in the wrong forum. This no longer has anything at all to do with Python in particular. -- \ ?Books and opinions, no matter from whom they came, if they are | `\ in opposition to human rights, are nothing but dead letters.? | _o__) ?Ernestine Rose | Ben Finney From santiago.caracol at gmail.com Wed Aug 11 04:16:37 2010 From: santiago.caracol at gmail.com (Santiago Caracol) Date: Wed, 11 Aug 2010 01:16:37 -0700 (PDT) Subject: freeze function calls References: <67f5b977-b615-438f-8639-39bf4cee2231@5g2000yqz.googlegroups.com> <6b1e3bc4-cc75-4b0d-bcfb-0b8dfd750c40@5g2000yqz.googlegroups.com> <34b16983-ac50-49a0-a612-0c35d9bf6c6f@l14g2000yql.googlegroups.com> Message-ID: <97e1c46b-c657-4016-afa4-c2867edd5722@5g2000yqz.googlegroups.com> Peter, thanks again for all this code. You helped me a lot. > Didn't you say you weren't interested in the web specific aspects? I thought that, although my problem had to do with client-server stuff, it wasn't really web-specific. But now I think that that was part of my problem. I failed to see that using sessions could be the solution. Santiago From usernet at ilthio.net Wed Aug 11 04:38:48 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 08:38:48 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, RG wrote: > When stdin is not a tty, Python seems to buffer all the input through > EOF before processing any of it: > > [ron at mickey:~]$ cat | python > print 123 > print 456 > 123 > 456 > > Is there a way to get Python to process input line-by-line the way it > does when stdin is a TTY even when stdin is not a TTY? It would be much better to know the overall purpose of what you are trying to achieve. There are may be better ways (ie, sockets) depending what you are trying to do. Knowing your target platform would also be helpful. For the python interpeter itself, you can can get interactive behavior by invoking it with the -i option. If you want to handle stdin a single line at a time from inside of your program, you can access it using sys.stdin.readline(). From cs at zip.com.au Wed Aug 11 05:42:30 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 11 Aug 2010 19:42:30 +1000 Subject: Line-by-line processing when stdin is not a tty In-Reply-To: References: Message-ID: <20100811094230.GA21181@cskk.homeip.net> On 11Aug2010 00:11, RG wrote: | When stdin is not a tty, Python seems to buffer all the input through | EOF before processing any of it: | | [ron at mickey:~]$ cat | python | print 123 | print 456 | 123 | 456 | | Is there a way to get Python to process input line-by-line the way it | does when stdin is a TTY even when stdin is not a TTY? What you're seeing here is not python's behaviour but cat's behaviour. Almost all programs do line buffering (flush buffer at newline) when the file is a terminal (character device) and block buffering (flush when a fixed size buffer, typically 8192 bytes or some larger power of 2) when the file is not a terminal. This is default behaviour for the stdio package. So "cat" is simply not feeding any data to python until it has a lot of it; there is nothing python can do about that. We would need to know more about your specific task to suggest workarounds. Usually you either need an option on the upstream program to tell it to line buffer explicitly or you need to play silly games with pseudo terminals to convince the upstream program it is attached to a terminal. The latter is both ugly and generally inadvisable because many programs that change their buffering when attached to a terminal also change other behaviour, such as issuing interactiove prompts etc. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ The type syntax for C is essentially unparsable. - Rob Pike From jeanmichel at sequans.com Wed Aug 11 05:47:46 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 11 Aug 2010 11:47:46 +0200 Subject: GUI automation tool (windows) In-Reply-To: References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4C6271C2.4030008@sequans.com> Grant Edwards wrote: > On 2010-08-11, Lawrence D'Oliveiro wrote: > >> In message >> , Alex >> Barna wrote: >> >> >>> On Aug 10, 10:05 am, Lawrence D'Oliveiro >>> >>> >>>> Can???t understand the point to it. ???GUI automation??? is a contradiction in >>>> terms, because a GUI is designed for use by humans to do manual tasks, >>>> not ones that can be automated. >>>> >>> Automating GUI is for testing. >>> >> But the most egregious GUI problems are going to be with humans being >> unable to figure out how to do something, am I right? How are you >> going to uncover those problems, except by testing with real people? >> Automated testing isn???t going to do it. >> > > Automated GUI testing isn't intended to uncover those sorts of > problems in GUI design. Automated GUI intended to uncover problems in > the underlying program functionality, and is used mainly for > regression testing to insure that changes made to a program didn't > cause any unintended changes in program behavior. > > Automated GUI testing often isn't even being used to test the program > whos GUI is being automated. It's often used to test _other_ programs > with which the GUI-automated-program interacts. > > Yep, as an example, I worked on a cardio medical system (X ray). In order to get to the market, such system must prove its robustness, part of the proof was about chaining thousands of patients without a crash nor X ray failure. This is where GUI automation comes in. The tool was simulating the interaction between a doctor and the system application GUI and was working 24/7. JM From nikos.the.gr33k at gmail.com Wed Aug 11 05:48:22 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Wed, 11 Aug 2010 02:48:22 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> <939c62d1-a681-494b-824e-c80a3554c15f@z28g2000yqh.googlegroups.com> Message-ID: <206e6cef-3760-49a7-bb8a-c5d1fe3a4091@i31g2000yqm.googlegroups.com> On 10 ???, 18:12, MRAB wrote: > ????? wrote: > > [snip] > > > > > > > The ID number of each php page was contained in the old php code > > within this string > > > PageID = some_number > > > So instead of create a new ID number for eaqch page i have to pull out > > this number to store to the beginnign to the file as comment line, > > because it has direct relationship with the mysql database as in > > tracking the number of each webpage and finding the counter of it. > > > # Grab the PageID contained within the php code and store it in id > > variable > > id = re.search( 'PageID = ', src_data ) > > > How to tell Python to Grab that number after 'PageID = ' string and to > > store it in var id that a later use in the program? > > If the part of the file you're trying to match look like this: > > ? ? ?PageID = 12 > > then the regex should look like this: > > ? ? ?PageID = (\d+) > > and the code should look like this: > > ? ? ?page_id = re.search(r'PageID = (\d+)', src_data).group(1) > > The page_id will, of course, be a string. > Thank you very much for helping me with the syntax. > > also i made another changewould something like this work: > > > =============================== > > # open same php file for storing modified data > > print ( 'writing to %s' % dest_f ) > > f = open(src_f, 'w') > > f.write(src_data) > > f.close() > > > # rename edited .php file to .html extension > > dst_f = src_f.replace('.php', '.html') > > os.rename( src_f, dst_f ) > > =============================== > > > Because instead of creating a new .html file and inserting the desired > > data of the old php thus having two files(old php, and new html) i > > decided to open the same php file for writing that data and then > > rename it to html. > > Would the above code work? > > Why wouldn't it? I though i was perhaps did something wrong with the code. ========================================= for currdir, files, dirs in os.walk('d:\\test'): # neither 'd:/test' tracks the folder for f in files: if f.lower().endswith("php"): print currdir, files, dirs, f ========================================= As you advised me in a previous post of yours i need to find out why the converting code although works for a single file doesn't for some reason enter folders and subfolders to grab files form there to convert. So as you said i should comment all other statements to find out the culprit in the above lines. Well those lines are supposed to print current working folder and files but when i run the above code it gives me nothing in response, not even 'f'. So does that mean that os.walk() method cannot enter the windows 7 folders? * One more thing is that instead of trying to run the above script form 'cli' wouldn't it better to run it as a cgi script and see the results in the browser instead with the addition fo this line? print ( "Content-type: text/html; charset=UTF-8 \n" ) Or for some reason this has to be run from the shell to both local(windows 7) and remote hosting (linux) servers? From wolfgang at rohdewald.de Wed Aug 11 06:01:25 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Wed, 11 Aug 2010 12:01:25 +0200 Subject: Line-by-line processing when stdin is not a tty In-Reply-To: <20100811094230.GA21181@cskk.homeip.net> References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: <201008111201.25689.wolfgang@rohdewald.de> On Mittwoch 11 August 2010, Cameron Simpson wrote: > Usually you either > need an option on the upstream program to tell it to line > buffer explicitly once cat had an option -u doing exactly that but nowadays -u seems to be ignored http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html -- Wolfgang From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 06:20:20 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 10:20:20 GMT Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4c627964$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 18:50:15 +1200, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> ... nobody's talking about using automated testing to figure out what >> users think. > > That?s the trouble. What?s the point of a GUI, then? Are you trolling, or do you really fail to understand that the concepts of *testing a GUI's functionality* and *asking users what sort of interface they want* are independent concepts? Let's put it this way... "Nobody is talking about using automated testing to find out what command line switches users want on their command line tools." "That's the trouble. What's the point of a CLI, then?" Do you see the difference now? -- Steven From usernet at ilthio.net Wed Aug 11 06:32:41 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 10:32:41 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: On 2010-08-11, Wolfgang Rohdewald wrote: > On Mittwoch 11 August 2010, Cameron Simpson wrote: >> Usually you either >> need an option on the upstream program to tell it to line >> buffer explicitly > > once cat had an option -u doing exactly that but nowadays > -u seems to be ignored > > http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html I have to wonder why cat knows or cares. Since we are referring to a single directional pipe, there is no fear of creating any kind of race condition. In general, I would expect that the shell opens the pipe (pipe()), fork()s, closes its own 0 or 1 descriptor as appropriate for each child, copies (dup()) one the file descriptors to the appropriate file descriptor for the child process, and exec()s to call the new process. Neither of the processes, in general, needs to know anything other the to write and read from their given descriptors. From python.list at tim.thechases.com Wed Aug 11 06:50:44 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 11 Aug 2010 05:50:44 -0500 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: <4C628084.7080509@tim.thechases.com> On 08/11/10 01:24, Terry Reedy wrote: > On 8/10/2010 8:08 PM, Roy Smith wrote: >> In any case, if the candidate were to submit somebody else's >> work, it would come out pretty quickly as we discussed their >> code. I suppose one question I might ask would be, "Can you >> explain why, when I copy-paste one of your comments into a >> google search box, your entire program appears?" > > Mostly likely because I wrote the original... > > would be my answer. Unfortunately there are candidates who would give your answer but then have trouble with "Then why are the Last-Modified HTTP headers showing a date several months before our interview?" It's as bad as the phone-interviews I've done where in the background I can hear the person on the other end typing my questions into a search box and reading off answers. On the bright side, those are short interviews... ;-) -tkc From chris at simplistix.co.uk Wed Aug 11 07:13:29 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 11 Aug 2010 12:13:29 +0100 Subject: regex to remove lines made of only whitespace Message-ID: <4C6285D9.8080000@simplistix.co.uk> Hi All, I'm looking for a regex (or other solution, as long as it's quick!) that could be used to strip out lines made up entirely of whitespace. eg: 'x\n \t \n\ny' -> 'x\ny' Does anyone have one handy? cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From andreas.tawn at ubisoft.com Wed Aug 11 07:21:10 2010 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 11 Aug 2010 13:21:10 +0200 Subject: regex to remove lines made of only whitespace In-Reply-To: <4C6285D9.8080000@simplistix.co.uk> References: <4C6285D9.8080000@simplistix.co.uk> Message-ID: <654D9D97DA51AD479973BC2D5578603C06C254BE12@PDC-MAIL-CMS01.ubisoft.org> > Hi All, > > I'm looking for a regex (or other solution, as long as it's quick!) > that > could be used to strip out lines made up entirely of whitespace. > > eg: > > 'x\n \t \n\ny' -> 'x\ny' > > Does anyone have one handy? > > cheers, > > Chris for line in lines: if not line.strip(): continue doStuff(line) cheers, Drea From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 07:27:49 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 11:27:49 GMT Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <4c628934$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 06:12:49 +0000, Grant Edwards wrote: > Automating a GUI > isn't done to test how well the GUI works for real users. Or to put it another way... automated tests aren't useful for usability testing, regardless of whether one is testing a GUI app or a CLI app. > It's done mainly for two purposes: > > 1) Regression testing to make sure that the GUI's behavior (good, > bad, or indifferent) hasn't changed since the previous revision. > > 2) To test the functionality underlying the GUI. I would like to point out that automating GUIs isn't just done for testing purposes, but has other reasons as well. Probably the most common is for the same reason any automation is done, be it writing a script or building a robot: to reduce the amount of manual effort needed to do some repetitive or frequent task. Mouse and keyboard event recording software used to be one of the killer apps for power users back in the days of classic Apple Mac and early versions of Windows. I'm not entirely sure why they've faded away... it seems to have left an empty niche, for power users who aren't comfortable writing shell scripts, batch files or messing about with DBUS, but still want to automate repetitive tasks. Another common use is automating interactions with web sites via mechanize. -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 07:31:44 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 11:31:44 GMT Subject: regex to remove lines made of only whitespace References: Message-ID: <4c628a1f$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 12:13:29 +0100, Chris Withers wrote: > Hi All, > > I'm looking for a regex (or other solution, as long as it's quick!) that > could be used to strip out lines made up entirely of whitespace. def strip_blank_lines(lines): for line in lines: if not line.isspace(): yield line text = ''.join(strip_blank_lines(lines.split('\n'))) -- Steven From python.list at tim.thechases.com Wed Aug 11 07:33:15 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 11 Aug 2010 06:33:15 -0500 Subject: regex to remove lines made of only whitespace In-Reply-To: <654D9D97DA51AD479973BC2D5578603C06C254BE12@PDC-MAIL-CMS01.ubisoft.org> References: <4C6285D9.8080000@simplistix.co.uk> <654D9D97DA51AD479973BC2D5578603C06C254BE12@PDC-MAIL-CMS01.ubisoft.org> Message-ID: <4C628A7B.7060207@tim.thechases.com> On 08/11/10 06:21, Andreas Tawn wrote: >> I'm looking for a regex (or other solution, as long as it's quick!) >> that could be used to strip out lines made up entirely of whitespace. >> >> eg: >> >> 'x\n \t \n\ny' -> 'x\ny' > > for line in lines: > if not line.strip(): > continue > doStuff(line) Note that the OP's input and output were a single string. Perhaps something like >>> s = 'x\n \t \n\ny' >>> '\n'.join(line for line in s.splitlines() if line.strip()) 'x\ny' which, IMHO, has much greater clarity than any regexp with the added bonus of fewer regexp edge-cases (blanks at the beginning/middle/end of the text). -tkc From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 07:34:51 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 11:34:51 GMT Subject: type enforcement in _ssl.sslwrap References: <38664845-c34d-452e-a09c-3206383e90e3@s17g2000prh.googlegroups.com> Message-ID: <4c628adb$0$11101$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 10:40:54 -0700, Eric Snow wrote: > ssl.SSLSocket.__init__ makes a call to _ssl.sslwrap (in the C module). > That in turn makes a call to PyArg_ParseTuple, which casts the first arg > of _ssl.sslwrap into a PySocketModule.Sock_Type object. > > My problem is that I am trying to pass in an object that implements the > Socket interface, but does not inherit from _socket.socket, like you do > with file-like objects. Is there a way to make this work, or is the > PyArg_ParseTuple call going to stop me. I don't know. What happens when you try it? -- Steven From andreas.tawn at ubisoft.com Wed Aug 11 07:39:27 2010 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 11 Aug 2010 13:39:27 +0200 Subject: regex to remove lines made of only whitespace In-Reply-To: <4C628A7B.7060207@tim.thechases.com> References: <4C6285D9.8080000@simplistix.co.uk> <654D9D97DA51AD479973BC2D5578603C06C254BE12@PDC-MAIL-CMS01.ubisoft.org> <4C628A7B.7060207@tim.thechases.com> Message-ID: <654D9D97DA51AD479973BC2D5578603C06C254BE47@PDC-MAIL-CMS01.ubisoft.org> > On 08/11/10 06:21, Andreas Tawn wrote: > >> I'm looking for a regex (or other solution, as long as it's quick!) > >> that could be used to strip out lines made up entirely of > whitespace. > >> > >> eg: > >> > >> 'x\n \t \n\ny' -> 'x\ny' > > > > for line in lines: > > if not line.strip(): > > continue > > doStuff(line) > > Note that the OP's input and output were a single string. Ah, indeed. What do they say about the first part of assume? > Perhaps something like > >>> s = 'x\n \t \n\ny' > >>> '\n'.join(line for line in s.splitlines() if line.strip()) > 'x\ny' > > which, IMHO, has much greater clarity than any regexp with the > added bonus of fewer regexp edge-cases (blanks at the > beginning/middle/end of the text). > > -tkc This what I meant (no really) ;o). Cheers, Drea From enleverLesX_XXmcX at XmclavXeauX.com.invalid Wed Aug 11 07:44:22 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Wed, 11 Aug 2010 13:44:22 +0200 Subject: Access lotus notes using Python 2.5.1 References: Message-ID: <4c628d1b$0$5407$ba4acef3@reader.news.orange.fr> Hi! In several cases, Notes is not registred as COM server. Depending of installation. @-salutations -- MCi From sushma.konanki at gmail.com Wed Aug 11 08:09:01 2010 From: sushma.konanki at gmail.com (sushma) Date: Wed, 11 Aug 2010 05:09:01 -0700 (PDT) Subject: urgent requirement at Hyderabad Message-ID: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Hi, We are looking for Python Developers/programmers with 1+ years of experience. Send resume to sushmak at millenniumsoft.com Regards, Sushma. From stefan_ml at behnel.de Wed Aug 11 08:17:00 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 11 Aug 2010 14:17:00 +0200 Subject: urgent requirement at Hyderabad In-Reply-To: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Message-ID: In case anyone wondered: Hyderabad is likely referring to some place in Asia: http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29 Stefan From cs at zip.com.au Wed Aug 11 08:18:58 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 11 Aug 2010 22:18:58 +1000 Subject: Line-by-line processing when stdin is not a tty In-Reply-To: References: Message-ID: <20100811121858.GA5495@cskk.homeip.net> On 11Aug2010 10:32, Tim Harig wrote: | On 2010-08-11, Wolfgang Rohdewald wrote: | > On Mittwoch 11 August 2010, Cameron Simpson wrote: | >> Usually you either | >> need an option on the upstream program to tell it to line | >> buffer explicitly | > | > once cat had an option -u doing exactly that but nowadays | > -u seems to be ignored | > | > http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html | | I have to wonder why cat knows or cares. Since we are referring to | a single directional pipe, there is no fear of creating any kind of | race condition. In general, I would expect that the shell opens the | pipe (pipe()), fork()s, closes its own 0 or 1 descriptor as appropriate | for each child, copies (dup()) one the file descriptors to the | appropriate file descriptor for the child process, and exec()s to call | the new process. Neither of the processes, in general, needs to know | anything other the to write and read from their given descriptors. The buffering is a performance choice. Every write requires a context switch from userspace to kernel space, and availability of data in the pipe will wake up a downstream process blocked trying to read. It is far more efficient to do as few such copies as possible, so where interaction (as you point out) is one way it's usually better to write data in larger chunks. But when writing to a terminal, ostensibly for a human to read, line buffering is generally better (for exactly the issue the OP tripped over - humans expect stuff to happen as it occurs). -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ From benadictraj123 at gmail.com Wed Aug 11 08:23:46 2010 From: benadictraj123 at gmail.com (benadict raj) Date: Wed, 11 Aug 2010 05:23:46 -0700 (PDT) Subject: GET PAID FOR WORKING ONLINE $100 ON YOUR FIRST DAY Message-ID: GET PAID FOR WORKING ONLINE $100 ON YOUR FIRST DAY Just Re-launched! ClickMasterPro network Learn how to make money from your home using your website Just join this network and Learn the secrets of how to make 1000's of $$$$ by bringing visitors to your free link or website No investment free to join GREAT OFFER $1 PER REFERRAL if you bring 100 friends to this network you can earn $100 on your first day. I get paid through paypal or alertpay To join this network use the below link http://www.clickmasterpro.com/?rid=2662 Awesome earnings getpaid for your real effort form your home From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 08:34:09 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 12:34:09 GMT Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> Message-ID: <4c6298c1$0$11101$c3e8da3@news.astraweb.com> On Tue, 10 Aug 2010 16:44:17 -0400, J Kenneth King wrote: > Fizzbuzz is annoying in interviews. It's not for the benefit of the interviewee, but for the interviewer. > I've never worked at a job where I was under a timer while a group of > people sat across from me and scrutinized everything I was doing. > > I don't see how it can honestly tell you anything useful about the > person you're interviewing either. Do you really think that what you > assume about the interviewee based on characteristics you can infer from > their solution to be really, honestly true? They might even completely > bomb the solution and still be a brilliant programmer, but you'll never > know that if you trust this simple "fizzbuzz" test. I think you've missed the point of the FizzBuzz test. Nobody should judge your skill as a programmer from whether you can write FizzBuzz in 3 minutes during an interview. The test is to weed out the people who aren't programmers at all, but think they can bluff their way into a programming job. Sounds ridiculous, but apparently there are vast hordes of people who can barely program "Hello World" applying for programming jobs. One figure bandied about -- how accurately, I don't know -- is 199 out of every 200 job applicants for programming jobs are barely capable of writing a line of code. http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html Fizz Buzz and similar tests aim to weed them out, *quickly*, so you can spend more time interviewing people who actually are programmers. I personally know somebody who got his start as a professional programmer through pure bluff. He had read up just enough about the language to be able to toss in the odd buzzword, his CV was a masterpiece of imagination, and he was applying for a job during the Y2K panic when companies would hire anyone who could spell COBOL correctly by the third attempt. The other reason for starting with something like the Fizz Buzz test is precisely to see how the interviewee will react. Do they ask for clarification if the question is underspecified? That tells you they're smart enough to *notice* when something is underspecified, and confident enough to raise the issue in an interview. That's 100 bonus points right there. Do they go to pieces? That tells you they don't perform well under pressure. Do they argue with you that the question is pointless? That tells you that they're very confident, and quite likely arrogant enough not to worry about offending a potential employer (and maybe even deservedly so). This means they are potentially difficult to deal with. That doesn't mean you don't hire them: some people are so good that they deserve to be prima donna. But if you're not looking for a prima donna, then it's better to find out early, so you don't waste either your time or the other guy's. > I've been in those interviews on both sides of the table. Neither side > was a good experience. > > If a test is necessary, make it a take-home or demand source code if > they have it. Read their code and judge for yourself the quality of > their work. Getting interviewees to do a take-home problem just means you hire the guy who is friends with a good programmer, rather than the good programmer. > Any questions in an interview should be the usual "get to know you" type > stuff. "What was the most difficult challenge you've faced on the job? > How did you respond?" That sort of thing. I *hate* those questions. For many people, the honest answer would be "Nothing I've ever done in my job has been even half as difficult as getting through the interview, because I'm bad at selling myself", but if you say that, it just sounds like you're trying to bullshit your way through the interview. -- Steven From usernet at ilthio.net Wed Aug 11 08:35:08 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 12:35:08 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, Cameron Simpson wrote: > On 11Aug2010 10:32, Tim Harig wrote: >| On 2010-08-11, Wolfgang Rohdewald wrote: >| > On Mittwoch 11 August 2010, Cameron Simpson wrote: >| >> Usually you either >| >> need an option on the upstream program to tell it to line >| >> buffer explicitly >| > >| > once cat had an option -u doing exactly that but nowadays >| > -u seems to be ignored >| > >| > http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html >| >| I have to wonder why cat knows or cares. Since we are referring to >| a single directional pipe, there is no fear of creating any kind of >| race condition. In general, I would expect that the shell opens the >| pipe (pipe()), fork()s, closes its own 0 or 1 descriptor as appropriate >| for each child, copies (dup()) one the file descriptors to the >| appropriate file descriptor for the child process, and exec()s to call >| the new process. Neither of the processes, in general, needs to know >| anything other the to write and read from their given descriptors. > > The buffering is a performance choice. Every write requires a context > switch from userspace to kernel space, and availability of data in the > pipe will wake up a downstream process blocked trying to read. > > It is far more efficient to do as few such copies as possible, so where > interaction (as you point out) is one way it's usually better to write > data in larger chunks. But when writing to a terminal, ostensibly for a > human to read, line buffering is generally better (for exactly the issue > the OP tripped over - humans expect stuff to happen as it occurs). Right, I don't question the optimization. I question whether the intelligence that performes that optimation should be placed within cat or whether it should be placed within the shell. It seems to me that the shell has a better idea of how the command is being used and can therefore make a better decision about whether or not buffering is appropriate. From usernet at ilthio.net Wed Aug 11 08:57:38 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 12:57:38 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c628934$0$11101$c3e8da3@news.astraweb.com> Message-ID: On 2010-08-11, Steven D'Aprano wrote: > Mouse and keyboard event recording software used to be one of the killer > apps for power users back in the days of classic Apple Mac and early > versions of Windows. I'm not entirely sure why they've faded away... it It faided away because automation based on on mouse clicks, and to a lesser extent key injection, is very fragile. GUIs are subject to changing in ways that are unpredictable and difficult to detect. Some GUI widget sets provide some programatic way to access the GUI items directly for testing and debugging purposes; but, that isn't always available in the final product. > Another common use is automating interactions with web sites via > mechanize. There are better ways of automating web site interactions. You can other generate the GETS and POSTS directly or you can use import the browsers through COM/XPCOM and manipulate the pages using the browser's DOM object. From roy at panix.com Wed Aug 11 09:04:09 2010 From: roy at panix.com (Roy Smith) Date: Wed, 11 Aug 2010 09:04:09 -0400 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <4c6298c1$0$11101$c3e8da3@news.astraweb.com> Message-ID: In article <4c6298c1$0$11101$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > Sounds ridiculous, but apparently there are vast hordes of people who can > barely program "Hello World" applying for programming jobs. One figure > bandied about -- how accurately, I don't know -- is 199 out of every 200 > job applicants for programming jobs are barely capable of writing a line > of code. By the same token, there are lots of people with advanced degrees in computer science who can't code their way out of a paper bag. One advantage of the take-home test is that you can prepare the test once and amortize the preparation cost over many applicants. It's a big investment of time to interview somebody. By the time I get up to investing an hour or so of my time on a phone screen, I'd like to weed out the obvious rejects as cheaply as possible. Even more interesting is to publish some problems on your web site and instruct applicants to submit a solution to one of them along with their resume. This makes the per-applicant cost to administer the exam essentially zero. It also has the nice side-effect of weeding out the resume spammers. To be honest, I've never done this, but I've seen companies that do. I may try it sometime. I still want to see the candidate write some code during the interview. This gives me a chance to feed them a problem incrementally and see where they take it. From ben+python at benfinney.id.au Wed Aug 11 09:35:18 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 11 Aug 2010 23:35:18 +1000 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: <877hjxxofd.fsf@benfinney.id.au> Tim Chase writes: > Unfortunately there are candidates who would give your answer but then > have trouble with "Then why are the Last-Modified HTTP headers showing > a date several months before our interview?" My response: ?Ha! That's a trick question; ?Last-Modified? is a field in the header, not a header itself?. That might lead to the ?why are you interested in leaving your current position? question rather precipitously, though. -- \ ?Courage is not the absence of fear, but the decision that | `\ something else is more important than fear.? ?Ambrose Redmoon | _o__) | Ben Finney From sturlamolden at yahoo.no Wed Aug 11 09:44:14 2010 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 11 Aug 2010 06:44:14 -0700 (PDT) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> <4C61E9A1.5090800@v.loewis.de> <88t9j7-ri5.ln1@satorlaser.homedns.org> Message-ID: <44d30ac7-931e-4eb0-9aed-f664c872d438@l20g2000yqm.googlegroups.com> On 11 Aug, 08:40, Ulrich Eckhardt wrote: > That's true, maybe I don't remember the exact rationale. Especially if even > someone like you, who is much deeper into Python development, doesn't, I'm > wondering if I'm misremembering something.... Header (definition) and source (implementation) is not the same. A C++ compiler can use Python's header files and link with Python's C API correctly. But it cannot compile Python's C source code. A C compiler is required to compile and build Python. From invalid at invalid.invalid Wed Aug 11 10:09:45 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 14:09:45 +0000 (UTC) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: On 2010-08-11, Lawrence D'Oliveiro wrote: > In message , Grant Edwards wrote: > >> ... nobody's talking about using automated testing to figure out >> what users think. > > That???s the trouble. What???s the point of a GUI, then? OK, now you're just trolling. -- Grant Edwards grant.b.edwards Yow! I guess you guys got at BIG MUSCLES from doing too gmail.com much STUDYING! From invalid at invalid.invalid Wed Aug 11 10:13:09 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 14:13:09 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, Tim Harig wrote: > On 2010-08-11, RG wrote: >> When stdin is not a tty, Python seems to buffer all the input through >> EOF before processing any of it: >> >> [ron at mickey:~]$ cat | python >> print 123 >> print 456 >> 123 >> 456 >> >> Is there a way to get Python to process input line-by-line the way it >> does when stdin is a TTY even when stdin is not a TTY? > > It would be much better to know the overall purpose of what you are trying > to achieve. There are may be better ways (ie, sockets) depending what you > are trying to do. Knowing your target platform would also be helpful. > > For the python interpeter itself, you can can get interactive behavior by > invoking it with the -i option. If you're talking about unbuffered stdin/stdout, the option is -u. I don't really see how the -i option is relevent -- it causes the interpreter to go into interactive mode after running the script. > If you want to handle stdin a single line at a time from inside of your > program, you can access it using sys.stdin.readline(). That doesn't have any effect on stdin buffering. -- Grant Edwards grant.b.edwards Yow! ... I want to perform at cranial activities with gmail.com Tuesday Weld!! From __peter__ at web.de Wed Aug 11 10:49:03 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Aug 2010 16:49:03 +0200 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: Grant Edwards wrote: > On 2010-08-11, Tim Harig wrote: >> On 2010-08-11, RG wrote: >>> When stdin is not a tty, Python seems to buffer all the input through >>> EOF before processing any of it: >>> >>> [ron at mickey:~]$ cat | python >>> print 123 >>> print 456 >>> 123 >>> 456 >>> >>> Is there a way to get Python to process input line-by-line the way it >>> does when stdin is a TTY even when stdin is not a TTY? >> >> It would be much better to know the overall purpose of what you are >> trying >> to achieve. There are may be better ways (ie, sockets) depending what >> you >> are trying to do. Knowing your target platform would also be helpful. >> >> For the python interpeter itself, you can can get interactive behavior by >> invoking it with the -i option. > > If you're talking about unbuffered stdin/stdout, the option is -u. > > I don't really see how the -i option is relevent -- it causes the > interpreter to go into interactive mode after running the script. I'd say the following looks like what the OP was asking for: $ cat | python -i -c'import sys; sys.ps1=""' print sys.stdin.isatty() False print 1 1 print 2 2 (Whether it's useful is yet another question) >> If you want to handle stdin a single line at a time from inside of your >> program, you can access it using sys.stdin.readline(). > > That doesn't have any effect on stdin buffering. "for line in stream"-style file iteration uses an internal buffer that is not affected by the -u option; stream.readline() doesnt use this optimization. Peter From phd at phd.pp.ru Wed Aug 11 10:59:33 2010 From: phd at phd.pp.ru (Oleg Broytman) Date: Wed, 11 Aug 2010 18:59:33 +0400 Subject: SQLObject 0.13.0 Message-ID: <20100811145933.GB20946@phd.pp.ru> Hello! I'm pleased to announce version 0.13.0, the first stable release of branch 0.13 of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.13.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.12 --------------- Features & Interface -------------------- * SQLObject instances that don't have a per-instance connection can be pickled and unpickled. * Validators became stricter: StringCol and UnicodeCol now accept only str, unicode or an instance of a class that implements __unicode__ (but not __str__ because every object has a __str__ method); BoolCol accepts only bool or int or an instance of a class that implements __nonzero__; IntCol accepts int, long or an instance of a class that implements __int__ or __long__; FloatCol accepts float, int, long or an instance of a class that implements __float__, __int__ or __long__. * Added a connection class for rdbhost.com (commercial Postgres-over-Web service). Small Features -------------- * Added TimedeltaCol; currently it's only implemented on PostgreSQL as an INTERVAL type. * Do not pollute the base sqlmeta class to allow Style to set idName. In the case of inherited idName inherited value takes precedence; to allow Style to set idName reset inherited idName to None. * Better handling of circular dependencies in sqlobject-admin - do not include the class in the list of other classes. * Renamed db_encoding to dbEncoding in UnicodeStringValidator. * A new parameter 'sslmode' was added to PostgresConnection. * Removed SQLValidator - its attemptConvert was never called because in FormEncode it's named attempt_convert. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytman http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From invalid at invalid.invalid Wed Aug 11 11:01:12 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 11 Aug 2010 15:01:12 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, Peter Otten <__peter__ at web.de> wrote: > Grant Edwards wrote: >>> If you want to handle stdin a single line at a time from inside of >>> your program, you can access it using sys.stdin.readline(). >> >> That doesn't have any effect on stdin buffering. > > "for line in stream"-style file iteration uses an internal buffer that is > not affected by the -u option; stream.readline() doesnt use this > optimization. You're right. Why didn't I know that? Using "for line in sys.stdin" does it's own buffering. In my tests using sys.stdin.readline() worked as the OP desired either with or without -u, either with or without cat. IOW, "cat" isn't buffering output on my system (or if it is, it's line-buffering). -- Grant Edwards grant.b.edwards Yow! I don't know WHY I at said that ... I think it gmail.com came from the FILLINGS in my rear molars ... From badouglas at gmail.com Wed Aug 11 11:08:21 2010 From: badouglas at gmail.com (bruce) Date: Wed, 11 Aug 2010 08:08:21 -0700 Subject: mysqldb - parameter issue Message-ID: hi... using python v2.6, using the mysqldb lib the test tbl looks like: DROP TABLE IF EXISTS `functionError_TBL`; CREATE TABLE `functionError_TBL` ( `parentFunction` varchar(100) NOT NULL default '', `currentFunction` varchar(100) NOT NULL default '', `parentFunctionID` int(10) NOT NULL default 0, `errorStatus` int(1) NOT NULL default 0, `clientServerUUID` varchar(100) NOT NULL default '', `processTime` timestamp NOT NULL default 0, `CollegeID` int(10) NOT NULL default 0, `CrawlID` varchar(200) NOT NULL default '', `CollegeName` varchar(200) NOT NULL default '', `CollegeAbbrv` varchar(200) NOT NULL default '', . . the test script looks like . . tlist= [(1, 1, 1281502771)] ins="insert into functionError_TBL " ins=ins+"(errorStatus, CollegeID, processTime)" ins=ins+" values " ins=ins+" (%s,%s, from_unixtime(%s))" db.executemany (ins, tlist) if the parameter is : (%s,%s, from_unixtime(%s))" it appears to work, data is inserted correctly... if the parameters are changed to (%s,from_unixtime(%s), %s)" along with the corresponding insert portion, and the test list, an error is generated.. this implies that something is going on with the use of the "from_unixtime" that i don't fully understand.. thoughts/pointers/comments... thanks thoughts on how to resolve this would be greatly appreciated. thanks From backgoodoo at gmail.com Wed Aug 11 11:09:50 2010 From: backgoodoo at gmail.com (Back9) Date: Wed, 11 Aug 2010 08:09:50 -0700 (PDT) Subject: How to swallow traceback message Message-ID: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Hi, I run my py app to display a file's contents, and it is normally very long. So I use it like below: python myapp.py input_file | more to see them step by step. But when I try to exit it, normally I use Ctrl+ C key to quit it. Problem is every time I do like it, it shows Traceback message and it makes my app not professional. How do I handle it gracefully. TIA From usernet at ilthio.net Wed Aug 11 11:19:03 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 15:19:03 +0000 (UTC) Subject: How to swallow traceback message References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: On 2010-08-11, Back9 wrote: > python myapp.py input_file | more > to see them step by step. > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > Problem is every time I do like it, it shows Traceback message and it > makes my app not professional. You have three options. 1. Exit more properly. 2. Catch and handle SIGINT yourself. 3. Wrap whatever section of your program is being interrupted in try/except to catch the KeyboardInterrupt exception when it is generated. From chris at simplistix.co.uk Wed Aug 11 11:21:20 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 11 Aug 2010 16:21:20 +0100 Subject: urgent requirement at Hyderabad In-Reply-To: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Message-ID: <4C62BFF0.4000504@simplistix.co.uk> sushma wrote: > We are looking for Python Developers/programmers with 1+ years of > experience. Send resume to sushmak at millenniumsoft.com So urgent you can't even be bothered to describe the job or post the advert in the correct place on the python job board. Good luck with that ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From eknath.iyer at gmail.com Wed Aug 11 11:24:36 2010 From: eknath.iyer at gmail.com (Eknath Venkataramani) Date: Wed, 11 Aug 2010 11:24:36 -0400 Subject: How to swallow traceback message In-Reply-To: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: See Exception Handling On Wed, Aug 11, 2010 at 11:09 AM, Back9 wrote: > Hi, > > I run my py app to display a file's contents, and it is normally very > long. > So I use it like below: > > python myapp.py input_file | more > to see them step by step. > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > Problem is every time I do like it, it shows Traceback message and it > makes my app not professional. > > How do I handle it gracefully. > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > -- Eknath Venkataramani -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Wed Aug 11 11:30:01 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 11 Aug 2010 17:30:01 +0200 Subject: How to swallow traceback message In-Reply-To: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: <4C62C1F9.40508@sequans.com> Back9 wrote: > Hi, > > I run my py app to display a file's contents, and it is normally very > long. > So I use it like below: > > python myapp.py input_file | more > to see them step by step. > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > Problem is every time I do like it, it shows Traceback message and it > makes my app not professional. > > How do I handle it gracefully. > > TIA > if __name__ == '__main__': try: main() except KeyboardInterrupt: print 'Hey ! this is a professional application' Cheers, JM From backgoodoo at gmail.com Wed Aug 11 11:32:19 2010 From: backgoodoo at gmail.com (Back9) Date: Wed, 11 Aug 2010 08:32:19 -0700 (PDT) Subject: How to swallow traceback message References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: On Aug 11, 11:19?am, Tim Harig wrote: > On 2010-08-11, Back9 wrote: > > > python myapp.py input_file | more > > to see them step by step. > > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > > Problem is every time I do like it, it shows Traceback message and it > > makes my app not professional. > > You have three options. > > ? ? ? ? 1. Exit more properly. > > ? ? ? ? 2. Catch and handle SIGINT yourself. > > ? ? ? ? 3. Wrap whatever section of your program is being interrupted in > ? ? ? ? ? ? ? ? try/except to catch the KeyboardInterrupt exception when it > ? ? ? ? ? ? ? ? is generated. I should have mentioned that I already use try/except KeyboardInterrupt statement. But it does not seem to work as I expected. TIA From torriem at gmail.com Wed Aug 11 12:02:14 2010 From: torriem at gmail.com (Michael Torrie) Date: Wed, 11 Aug 2010 10:02:14 -0600 Subject: How to swallow traceback message In-Reply-To: References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: <4C62C986.5030900@gmail.com> On 08/11/2010 09:32 AM, Back9 wrote: > I should have mentioned that I already use try/except > KeyboardInterrupt statement. > But it does not seem to work as I expected. If you want anyone to help further, you will need to say a) what you are expecting it to do and b) what it is actually doing. From chris at simplistix.co.uk Wed Aug 11 12:04:12 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 11 Aug 2010 17:04:12 +0100 Subject: regex to remove lines made of only whitespace In-Reply-To: <4c628a1f$0$11101$c3e8da3@news.astraweb.com> References: <4c628a1f$0$11101$c3e8da3@news.astraweb.com> Message-ID: <4C62C9FC.3010307@simplistix.co.uk> Steven D'Aprano wrote: > def strip_blank_lines(lines): > for line in lines: > if not line.isspace(): > yield line > > text = ''.join(strip_blank_lines(lines.split('\n'))) The final version I have is: def strip_blank_lines(text): result = [] for line in text.split('\n'): if line and not line.isspace(): result.append(line) return '\n'.join(result) Any improvements would be very welcome! Chris From fuglyducky at gmail.com Wed Aug 11 12:07:16 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Wed, 11 Aug 2010 09:07:16 -0700 (PDT) Subject: Confused: Newbie Function Calls Message-ID: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> I am a complete newbie to Python (and programming in general) and I have no idea what I'm missing. Below is a script that I am trying to work with and I cannot get it to work. When I call the final print function, nothing prints. However, if I print within the individual functions, I get the appropriate printout. Am I missing something??? Thanks in advance!!!! ################################################ # Global variable sample_string = "" def gen_header(sample_string): HEADER = """ mymultilinestringhere """ sample_string += HEADER return sample_string def gen_nia(sample_string): NIA = """ anothermultilinestringhere """ sample_string += NIA return sample_string gen_header(sample_string) gen_nia(sample_string) print(sample_string) From esnow at verio.net Wed Aug 11 12:12:06 2010 From: esnow at verio.net (Eric Snow) Date: Wed, 11 Aug 2010 09:12:06 -0700 (PDT) Subject: type enforcement in _ssl.sslwrap References: <38664845-c34d-452e-a09c-3206383e90e3@s17g2000prh.googlegroups.com> <4c628adb$0$11101$c3e8da3@news.astraweb.com> Message-ID: On Aug 11, 5:34?am, Steven D'Aprano wrote: > On Tue, 10 Aug 2010 10:40:54 -0700, Eric Snow wrote: > > ssl.SSLSocket.__init__ makes a call to _ssl.sslwrap (in the C module). > > That in turn makes a call to PyArg_ParseTuple, which casts the first arg > > of _ssl.sslwrap into a PySocketModule.Sock_Type object. > > > My problem is that I am trying to pass in an object that implements the > > Socket interface, but does not inherit from _socket.socket, like you do > > with file-like objects. ?Is there a way to make this work, or is the > > PyArg_ParseTuple call going to stop me. > > I don't know. What happens when you try it? > > -- > Steven When I pass my socket object in to ssl.wrap_socket I get the following exception: Traceback (most recent call last): File "", line 1, in ... File "/usr/local/lib/python2.7/ssl.py", line 342, in wrap_socket ciphers=ciphers) File "/usr/local/lib/python2.7/ssl.py", line 119, in __init__ ciphers) TypeError: must be _socket.socket, not ClientSocket I looked at what is going on there and found the call to _ssl.sslwrap. I tracked it down in the C source and found the call to PyArg_ParseTuple. -eric From suranap at gmail.com Wed Aug 11 12:21:34 2010 From: suranap at gmail.com (Pinku Surana) Date: Wed, 11 Aug 2010 09:21:34 -0700 (PDT) Subject: Is ElementTree development still active? Message-ID: <8b9ee78d-746e-4bb3-aef7-932ad2028650@x21g2000yqa.googlegroups.com> I checked the svn repo at effbot.org, but it appears to have no updates since 2007. Has development moved elsewhere? Thanks. From torriem at gmail.com Wed Aug 11 12:30:59 2010 From: torriem at gmail.com (Michael Torrie) Date: Wed, 11 Aug 2010 10:30:59 -0600 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: <4C62D043.9030200@gmail.com> On 08/11/2010 10:07 AM, fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! Yes. You are passing sample_string into the functions, but not doing anything with the return value. > def gen_header(sample_string): ^^^^^^^^^^^^^^^ The sample_string name is rebound to the parameter now, completely hiding the global variable, if that's really what you wanted. > def gen_nia(sample_string): ^^^^^^^^^^^^^^^^^^^ Again. > NIA = """ > anothermultilinestringhere > """ > > sample_string += NIA > return sample_string > > > gen_header(sample_string) > gen_nia(sample_string) Try this: sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) You could drop the arguments to your functions and use the "global" keyword to get access to sample_string from within the functions, but normally that's a bad idea. From the_mineo at web.de Wed Aug 11 12:31:39 2010 From: the_mineo at web.de (Wieland Hoffmann) Date: Wed, 11 Aug 2010 18:31:39 +0200 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: On 11.08.2010 18:07, fuglyducky wrote: > Am I missing something??? Thanks in advance!!!! Assign the returned value of your functions to something (like sample_string) and it will work: > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > HEADER = """ > mymultilinestringhere > """ > > sample_string += HEADER > return sample_string > > def gen_nia(sample_string): > NIA = """ > anothermultilinestringhere > """ > > sample_string += NIA > return sample_string > > > sample_string = gen_header(sample_string) > sample_string = gen_nia(sample_string) > > print(sample_string) From suranap at gmail.com Wed Aug 11 12:31:50 2010 From: suranap at gmail.com (Pinku Surana) Date: Wed, 11 Aug 2010 09:31:50 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> On Aug 11, 12:07?pm, fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! > > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > ? ? HEADER = """ > ? ? mymultilinestringhere > ? ? """ > > ? ? sample_string += HEADER > ? ? return sample_string > > def gen_nia(sample_string): > ? ? NIA = """ > ? ? anothermultilinestringhere > ? ? """ > > ? ? sample_string += NIA > ? ? return sample_string > > gen_header(sample_string) > gen_nia(sample_string) > > print(sample_string) There are 2 problems with your program. (1) If you want to use a global variable in a function, you have to add the line "global sample_string" to the beginning of that function. (2) Once you do (1), you will get an error because you've got sample_string as a global and a function parameter. Which one do you want to use in the function? You should change the name of the parameter to "sample" to solve that confusion. Here's the result, which works for me: sample_string = "" def gen_header(sample): global sample_string HEADER = """ mymultilinestringhere """ sample_string = sample + HEADER return sample_string def gen_nia(sample): global sample_string NIA = """ anothermultilinestringhere """ sample_string = sample + NIA return sample_string gen_header(sample_string) gen_nia(sample_string) print(sample_string) From robert.kern at gmail.com Wed Aug 11 12:33:56 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Aug 2010 11:33:56 -0500 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: On 8/11/10 11:07 AM, fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! > > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > HEADER = """ > mymultilinestringhere > """ > > sample_string += HEADER > return sample_string By default, all assignments inside of a function are local to the function. Even augmented assignments like +=. Python strings are immutable, so sample_string += HEADER works exactly like sample_string = sample_string + HEADER The string referred to by the global name sample_string is never modified and the global name is never reassigned. http://docs.python.org/py3k/tutorial/classes.html#python-scopes-and-namespaces > gen_header(sample_string) > gen_nia(sample_string) > > print(sample_string) You probably want something like the following: sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) print(sample_string) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ericwoodworth at gmail.com Wed Aug 11 12:39:19 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 09:39:19 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: This will work: ------------------------------------------------------------------------ sample_string="" def gen_header(sample_string=""): HEADER = """ mymultilinestringhere """ sample_string+= HEADER return sample_string def gen_nia(sample_string=""): NIA = """ anothermultilinestringhere """ sample_string += NIA return sample_string sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) print(sample_string) ------------------------------------------------------------------------ and this will work ------------------------------------------------------------------------ sample_string="" def gen_header(OtherString): global sample_string HEADER = """ mymultilinestringhere """ sample_string+= HEADER def gen_nia(OtherString): global sample_string NIA = """ anothermultilinestringhere """ sample_string += NIA gen_header(sample_string) gen_nia(sample_string) print(sample_string) ------------------------------------------------------------------------ The first one is the better of the 2 in this example but the second one will show you how to use global variables if you really need to use them So your problem was that you thought you were working on a global variable in your functions when you were not. Since the your def lines contained sample_string that make it a local variable. So when you were doing your += statements you were working on a local variable and not a global variable. You were returning the value of the local variable but you didn't have anything in the main body of your script catching that value. So simply changing these 2 lines: sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) made the global sample_string variable store the values of the return data. If you want to use global variables then you just have to do 2 things. First you have to make sure you don't have any local variables it the function with the same name. So I change the name to OtherString in the def line. Then you need a global statement at the start of your function (global sample_string) that tells python that you really do want to use that global variable. Global variables can cause you no end of heartache so python forces you to explicitly state that you want to use them. Hope that helps. From fuglyducky at gmail.com Wed Aug 11 12:39:58 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Wed, 11 Aug 2010 09:39:58 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> Message-ID: On Aug 11, 9:31?am, Pinku Surana wrote: > On Aug 11, 12:07?pm, fuglyducky wrote: > > > > > I am a complete newbie to Python (and programming in general) and I > > have no idea what I'm missing. Below is a script that I am trying to > > work with and I cannot get it to work. When I call the final print > > function, nothing prints. However, if I print within the individual > > functions, I get the appropriate printout. > > > Am I missing something??? Thanks in advance!!!! > > > ################################################ > > # Global variable > > sample_string = "" > > > def gen_header(sample_string): > > ? ? HEADER = """ > > ? ? mymultilinestringhere > > ? ? """ > > > ? ? sample_string += HEADER > > ? ? return sample_string > > > def gen_nia(sample_string): > > ? ? NIA = """ > > ? ? anothermultilinestringhere > > ? ? """ > > > ? ? sample_string += NIA > > ? ? return sample_string > > > gen_header(sample_string) > > gen_nia(sample_string) > > > print(sample_string) > > There are 2 problems with your program. > > (1) If you want to use a global variable in a function, you have to > add the line "global sample_string" to the beginning of that > function. > > (2) Once you do (1), you will get an error because you've got > sample_string as a global and a function parameter. Which one do you > want to use in the function? You should change the name of the > parameter to "sample" to solve that confusion. > > Here's the result, which works for me: > > sample_string = "" > def gen_header(sample): > ? ? global sample_string > ? ? HEADER = """ > ? ? mymultilinestringhere > ? ? """ > ? ? sample_string = sample + HEADER > ? ? return sample_string > def gen_nia(sample): > ? ? global sample_string > ? ? NIA = """ > ? ? anothermultilinestringhere > ? ? """ > ? ? sample_string = sample + NIA > ? ? return sample_string > gen_header(sample_string) > gen_nia(sample_string) > print(sample_string) Thanks! That did the trick. I am a bit confused though. I tried to follow a sample in a book (which works) where I didn't have to 1) pass the global variable as a parameter into the function, 2) did not have to define the global variable within the function. I apologize if this is a super stupid question but if it is global, why do I have to pass it into the function? Shouldn't the global variable be accessible from anywhere??? From jeanmichel at sequans.com Wed Aug 11 12:47:05 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 11 Aug 2010 18:47:05 +0200 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: <4C62D409.6010402@sequans.com> fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! > > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > HEADER = """ > mymultilinestringhere > """ > > sample_string += HEADER > return sample_string > > def gen_nia(sample_string): > NIA = """ > anothermultilinestringhere > """ > > sample_string += NIA > return sample_string > > > gen_header(sample_string) > gen_nia(sample_string) > > print(sample_string) > sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) print sample_string That should work. I guess you made an error thinking that sample_string += HEADER would change the value of the given parameter. It does not. The value is changed only for sample_string within the function This is the case for any immutable object (strings are immutable) in Python. Example: class AMutable(object): def __init__(self): self.description = 'I am X' myString = 'I am a immutable string' # an immutable object myMutable = AMutable() # a mutable object def bar(myMutable): myMutable.description = 'I am Y' # change the attribute description of the object def foo(aString): aString = 'fooooooooo' # will have no effect outside the function print 'before calling bar: ', myMutable.description bar(myMutable) print 'after calling bar: ', myMutable.description print 'before calling foo: ', myString foo(myString) print 'after calling foo: ', myString > before calling bar: I am X after calling bar: I am Y before calling foo: I am a immutable string after calling foo: I am a immutable string cheers, JM From ericwoodworth at gmail.com Wed Aug 11 12:55:56 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 09:55:56 -0700 (PDT) Subject: Queue cleanup Message-ID: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Hi I'm writing a multithreaded app that relies on Queues to move data between the threads. I'm trying to write my objects in a general way so that I can reuse them in the future so I need to write them in such a way that I don't know how many producer and how many consumer threads I might need. I also might have different consumer threads do different tasks (for example one might write to a log and one might write to SQL) so that again means I can't plan for a set ratio of consumers to producers. So it's unknown. So this means that instead of having 1 Queue that all the producers put to and that all the consumers get from I actually have 1 Queue per producer thread that the main body sends to the correct type of consumer thread. So I could get something like this where 3 producer threads write to 3 different Queues all of which get read by 1 consumer thread: P1 P2 P3 \ | / \ | / C1 So producers 1, 2, and 3 all write to individual Queues and consumer 1 had a list of those Queues and reads them all. The problem I'm having is that those producer threads can come and go pretty quickly and when they die I can cleanup the thread with join() but I'm still left with the Queue. So I could get something like this: P1 P3 \ | / \ | / C1 So here the P2 thread has ended and gone away but I still have his Queue lingering. So on a thread I can use is_alive() to check status and use join() to clean up but I don't see any analogous functionality for Queues. How do I kill them? I thought about putting a suicide message on the Queue and then C1 would read it and set the variable to None but i'm not sure setting the variable to None actually makes the Queue go away. It could just end up sitting in memory unreferenced - and that's not good. Additionally, I could have any number of consumer threads reading that Queue so once the first one get the suicide note the other consumer threads never would. I figure there has to be an elegant way for managing my Queues but so far I can't find it. Any suggestions would be appreciated and thanks in advance for any help. ps Python rocks. From ericwoodworth at gmail.com Wed Aug 11 12:58:17 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 09:58:17 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> Message-ID: <7d32ea1f-c415-4f66-b391-77c57caa5f1a@j5g2000vbg.googlegroups.com> On Aug 11, 12:39?pm, fuglyducky wrote: > On Aug 11, 9:31?am, Pinku Surana wrote: > > > > > > > On Aug 11, 12:07?pm, fuglyducky wrote: > > > > I am a complete newbie to Python (and programming in general) and I > > > have no idea what I'm missing. Below is a script that I am trying to > > > work with and I cannot get it to work. When I call the final print > > > function, nothing prints. However, if I print within the individual > > > functions, I get the appropriate printout. > > > > Am I missing something??? Thanks in advance!!!! > > > > ################################################ > > > # Global variable > > > sample_string = "" > > > > def gen_header(sample_string): > > > ? ? HEADER = """ > > > ? ? mymultilinestringhere > > > ? ? """ > > > > ? ? sample_string += HEADER > > > ? ? return sample_string > > > > def gen_nia(sample_string): > > > ? ? NIA = """ > > > ? ? anothermultilinestringhere > > > ? ? """ > > > > ? ? sample_string += NIA > > > ? ? return sample_string > > > > gen_header(sample_string) > > > gen_nia(sample_string) > > > > print(sample_string) > > > There are 2 problems with your program. > > > (1) If you want to use a global variable in a function, you have to > > add the line "global sample_string" to the beginning of that > > function. > > > (2) Once you do (1), you will get an error because you've got > > sample_string as a global and a function parameter. Which one do you > > want to use in the function? You should change the name of the > > parameter to "sample" to solve that confusion. > > > Here's the result, which works for me: > > > sample_string = "" > > def gen_header(sample): > > ? ? global sample_string > > ? ? HEADER = """ > > ? ? mymultilinestringhere > > ? ? """ > > ? ? sample_string = sample + HEADER > > ? ? return sample_string > > def gen_nia(sample): > > ? ? global sample_string > > ? ? NIA = """ > > ? ? anothermultilinestringhere > > ? ? """ > > ? ? sample_string = sample + NIA > > ? ? return sample_string > > gen_header(sample_string) > > gen_nia(sample_string) > > print(sample_string) > > Thanks! That did the trick. > > I am a bit confused though. I tried to follow a sample in a book > (which works) where I didn't have to 1) pass the global variable as a > parameter into the function, 2) did not have to define the global > variable within the function. I apologize if this is a super stupid > question but if it is global, why do I have to pass it into the > function? Shouldn't the global variable be accessible from anywhere??? If it's a global then you don't have to pass it to the function but you do have to have the line that says: global sample_string Now if you think the example in the book didn't do that and it still worked then if you post that sample I'm sure somebody can tell you why it worked. The book example might be doing something different. From rNOSPAMon at flownet.com Wed Aug 11 12:59:55 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 09:59:55 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , Cameron Simpson wrote: > On 11Aug2010 00:11, RG wrote: > | When stdin is not a tty, Python seems to buffer all the input through > | EOF before processing any of it: > | > | [ron at mickey:~]$ cat | python > | print 123 > | print 456 > | 123 > | 456 > | > | Is there a way to get Python to process input line-by-line the way it > | does when stdin is a TTY even when stdin is not a TTY? > > What you're seeing here is not python's behaviour but cat's behaviour. > > Almost all programs do line buffering (flush buffer at newline) when the > file is a terminal (character device) and block buffering (flush when a > fixed size buffer, typically 8192 bytes or some larger power of 2) when > the file is not a terminal. This is default behaviour for the stdio > package. > > So "cat" is simply not feeding any data to python until it has a lot of > it; I don't think that's right: [ron at mickey:~]$ cat | cat 123 123 321 321 Cat seems to flush its buffer after every newline. Also: [ron at mickey:~]$ cat -u | python print 123 print 456 123 456 > We would need to know > more about your specific task to suggest workarounds. I'm writing a system in a different language but want to use a Python library. I know of lots of ways to do this (embed a Python interpreter, fire up a python server) but by far the easiest to implement is to have the main program spawn a Python interpreter and interact with it through its stdin/stdout. In my code I explicitly force the output stream that is being piped to Python's stdin to be flushed so I know it's not a buffering problem on the input side. rg From ericwoodworth at gmail.com Wed Aug 11 13:01:09 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 10:01:09 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <6f6c0aa0-fc6f-47d4-bbf3-2ebe04f97cba@v23g2000vbi.googlegroups.com> On Aug 11, 12:55?pm, EW wrote: > Hi > > I'm writing a multithreaded app that relies on Queues to move data > between the threads. ?I'm trying to write my objects in a general way > so that I can reuse them in the future so I need to write them in such > a way that I don't know how many producer and how many consumer > threads I might need. ?I also might have different consumer threads do > different tasks (for example one might write to a log and one might > write to SQL) so that again means I can't plan for a set ratio of > consumers to producers. ?So it's unknown. > > So this means that instead of having 1 Queue that all the producers > put to and that all the consumers get from I actually have 1 Queue per > producer thread ?that the main body sends to the correct type of > consumer thread. ?So I could get something like this where 3 producer > threads write to 3 different Queues all of which get read by 1 > consumer thread: > > P1 ? ?P2 ? P3 > ? ? ?\ ? ?| ? / > ? ? ? ?\ ?| ?/ > ? ? ? ? C1 > > So producers 1, 2, and 3 all write to individual Queues and consumer 1 > had a list of those Queues and reads them all. ?The problem I'm having > is that those producer threads can come and go pretty quickly and when > they die I can cleanup the thread with join() but I'm still left with > the Queue. ?So I could get something like this: > > P1 ? ? ? ? P3 > ? ? ?\ ? ?| ? / > ? ? ? ?\ ?| ?/ > ? ? ? ? C1 > > So here the P2 thread has ended and gone away but I still have his > Queue lingering. > > So on a thread I can use is_alive() to check status and use join() to > clean up but I don't see any analogous functionality for Queues. ?How > do I kill them? ?I thought about putting a suicide message on the > Queue and then C1 would read it and set the variable to None but i'm > not sure setting the variable to None actually makes the Queue go > away. ?It could just end up sitting in memory unreferenced - and > that's not good. ?Additionally, I could have any number of consumer > threads reading that Queue so once the first one get the suicide note > the other consumer threads never would. > > I figure there has to be an elegant way for managing my Queues but so > far I can't find it. ?Any suggestions would be appreciated and thanks > in advance for any help. > > ps Python rocks. Whoo..the formatting got torn up! My terrible diagrams are even more terrible! Oh well, I think you'll catch my meaning :) From rNOSPAMon at flownet.com Wed Aug 11 13:02:24 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 10:02:24 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > Grant Edwards wrote: > > > On 2010-08-11, Tim Harig wrote: > >> On 2010-08-11, RG wrote: > >>> When stdin is not a tty, Python seems to buffer all the input through > >>> EOF before processing any of it: > >>> > >>> [ron at mickey:~]$ cat | python > >>> print 123 > >>> print 456 > >>> 123 > >>> 456 > >>> > >>> Is there a way to get Python to process input line-by-line the way it > >>> does when stdin is a TTY even when stdin is not a TTY? > >> > >> It would be much better to know the overall purpose of what you are > >> trying > >> to achieve. There are may be better ways (ie, sockets) depending what > >> you > >> are trying to do. Knowing your target platform would also be helpful. > >> > >> For the python interpeter itself, you can can get interactive behavior by > >> invoking it with the -i option. > > > > If you're talking about unbuffered stdin/stdout, the option is -u. > > > > I don't really see how the -i option is relevent -- it causes the > > interpreter to go into interactive mode after running the script. > > I'd say the following looks like what the OP was asking for: > > $ cat | python -i -c'import sys; sys.ps1=""' > print sys.stdin.isatty() > False > print 1 > 1 > print 2 > 2 That is indeed the behavior I'm looking for. > (Whether it's useful is yet another question) It's useful to me :-) I'm trying to access a python library from a program written in another language for which an equivalent library is not available. The easiest way to do that is to spawn a Python interpreter and interact with it through stdin/stdout. Thanks! rg From davea at ieee.org Wed Aug 11 13:08:44 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 11 Aug 2010 13:08:44 -0400 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: <4C62D91C.9020509@ieee.org> fuglyducky wrote: > I am a complete newbie to Python (and programming in general) and I > have no idea what I'm missing. Below is a script that I am trying to > work with and I cannot get it to work. When I call the final print > function, nothing prints. However, if I print within the individual > functions, I get the appropriate printout. > > Am I missing something??? Thanks in advance!!!! > > ################################################ > # Global variable > sample_string = "" > > def gen_header(sample_string): > HEADER = """ > mymultilinestringhere > """ > > sample_string += HEADER > return sample_string > > def gen_nia(sample_string): > NIA = """ > anothermultilinestringhere > """ > > sample_string += NIA > return sample_string > > > gen_header(sample_string) > gen_nia(sample_string) > > print(sample_string) > > It'd be best if you used different names for global scope than you do inside your functions. It won't change how this case works, but at least it'd be clearer what's happening. And sometimes you can get an unintended side effect when you use the same name for two different variables. In function gen_header(), you take an argument, and return a modified version of it. But the call to it never uses the return value. If you want to make any changes to the global value, you'd do something like this: sample_string = gen_header(sample_string) sample_string = gen_nia(sample_string) print(sample_string) HTH DaveA From no.email at nospam.invalid Wed Aug 11 13:18:24 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 10:18:24 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <7x39ulysnz.fsf@ruckus.brouhaha.com> EW writes: > I also might have different consumer threads do > different tasks (for example one might write to a log and one might > write to SQL) so that again means I can't plan for a set ratio of > consumers to producers.... So it's unknown. > > So this means that instead of having 1 Queue that all the producers > put to and that all the consumers get from I actually have 1 Queue per > producer thread That doesn't sound appropriate. Queues can have many readers and many writers. So use one queue per task (logging, SQL, etc), regardless of the number of producer or consumer threads. Any producer with an SQL request sends it to the SQL queue, which can have many listeners. The different SQL consumer threads listen to the SQL queue and pick up requests and handle them. From ericwoodworth at gmail.com Wed Aug 11 13:26:42 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 10:26:42 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> Message-ID: On Aug 11, 1:18?pm, Paul Rubin wrote: > EW writes: > > I also might have different consumer threads do > > different tasks (for example one might write to a log and one might > > write to SQL) so that again means I can't plan for a set ratio of > > consumers to producers.... ?So it's unknown. > > > So this means that instead of having 1 Queue that all the producers > > put to and that all the consumers get from I actually have 1 Queue per > > producer thread > > That doesn't sound appropriate. ?Queues can have many readers and many > writers. ?So use one queue per task (logging, SQL, etc), regardless of > the number of producer or consumer threads. ?Any producer with an SQL > request sends it to the SQL queue, which can have many listeners. ?The > different SQL consumer threads listen to the SQL queue and pick up > requests and handle them. I thought about doing it that way and I could do it that way but it still seems like there should be a way to clean up Queues on my own. If I did it this way then I guess I'd be relying on garbage collection when the script ended to clean up the Queues for me. What if I want to clean up my own Queues? Regardless of the specifics of my current design, I'm just generally curious how people manage cleanup of their Queues when they don't want them any more. From badouglas at gmail.com Wed Aug 11 13:29:29 2010 From: badouglas at gmail.com (bruce) Date: Wed, 11 Aug 2010 10:29:29 -0700 Subject: mysqldb - parameter issue In-Reply-To: References: Message-ID: hey dennis... umm.. given that i'm building the ins var/string to insert into the execute... i can't just place the triple quotes around it.. are you saying that the execute should have quotes placed around it within the execute so it would be something like execute("\""+sel""\""... or are you saying that within python i can just extend the line for the "sel" on multiple lines.. as to the err. i'm getting a " >>> Warning: Data truncated for column it appears that if i place the >>from_unixtime(%s) << at the end of the paramaters, then everything works.. but if i place it within the "%s" block.. the error is generated. I'm assuming there's some way to wrap the from_unixtime(%s) so it could be used as %s,%s,%s, from_unixtime(%s), %s, %s,... in checking the docs/spec.. i didn't see anything that discussed this... thanks > ins = """insert into functionError_TBL > (errorStatus, CollegeID, processTime) > values (%s, %s, from_unixtime(%s) )""" > On Wed, Aug 11, 2010 at 9:53 AM, Dennis Lee Bieber wrote: > On Wed, 11 Aug 2010 08:08:21 -0700, bruce > declaimed the following in gmane.comp.python.general: > > >> ? tlist= [(1, 1, 1281502771)] >> >> ? ins="insert into functionError_TBL " >> ? ins=ins+"(errorStatus, CollegeID, processTime)" >> ? ins=ins+" values " >> ? ins=ins+" ?(%s,%s, ?from_unixtime(%s))" > > ? ? ? ?Without examining the rest of the problem, the above sequence can be > cleaned up by using triple quotes... > > ? ? ? ?ins = """insert into functionError_TBL > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(errorStatus, CollegeID, processTime) > ? ? ? ? ? ? ? ? ? ? ? ?values (%s, %s, from_unixtime(%s) )""" > >> >> along with the corresponding insert portion, and the test list, an >> error is generated.. >> > ? ? ? ?What error? You've failed to post the most important part... EXACTLY > what the system reports... > -- > ? ? ? ?Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ?wlfraed at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Wed Aug 11 13:35:59 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Aug 2010 13:35:59 -0400 Subject: Confused: Newbie Function Calls In-Reply-To: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: Rather than patch your code, I think you should see a better approach. from textwrap import dedent # removes common whitespace prefix lines = [] def add_header(ss): "Add header to sequence of string lines" ss.append(dedent("""\ # No initial blank line my multi-line string here """)) def add_more(ss): "Add more to sequence of string lines" ss.append(dedent(""" # Start with blank line another multi-line string here """)) add_header(lines) add_more(lines) print(''.join(lines)) # prints -------------------------------- my multi-line string here another multi-line string here -------------------------------- PS. Only use 'gen' for naming generator functions when you get to them. -- Terry Jan Reedy From tjreedy at udel.edu Wed Aug 11 13:44:14 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Aug 2010 13:44:14 -0400 Subject: Is ElementTree development still active? In-Reply-To: <8b9ee78d-746e-4bb3-aef7-932ad2028650@x21g2000yqa.googlegroups.com> References: <8b9ee78d-746e-4bb3-aef7-932ad2028650@x21g2000yqa.googlegroups.com> Message-ID: On 8/11/2010 12:21 PM, Pinku Surana wrote: > I checked the svn repo at effbot.org, but it appears to have no > updates since 2007. Has development moved elsewhere? It is now in the stdlib (19.11) as xml.etree.ElementTree http://svn.python.org/view/python/branches/py3k/Modules/_elementtree.c?revision=83949&view=markup last revised 12 min ago. -- Terry Jan Reedy From python at mrabarnett.plus.com Wed Aug 11 13:55:23 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 18:55:23 +0100 Subject: Queue cleanup In-Reply-To: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <4C62E40B.9050905@mrabarnett.plus.com> EW wrote: [snip] > So here the P2 thread has ended and gone away but I still have his > Queue lingering. > > So on a thread I can use is_alive() to check status and use join() to > clean up but I don't see any analogous functionality for Queues. How > do I kill them? I thought about putting a suicide message on the > Queue and then C1 would read it and set the variable to None but i'm > not sure setting the variable to None actually makes the Queue go > away. It could just end up sitting in memory unreferenced - and > that's not good. Additionally, I could have any number of consumer > threads reading that Queue so once the first one get the suicide note > the other consumer threads never would. > > I figure there has to be an elegant way for managing my Queues but so > far I can't find it. Any suggestions would be appreciated and thanks > in advance for any help. > An object will be available for garbage collection when nothing refers to it either directly or indirectly. If it's unreferenced then it will go away. As for the suicide note, if a consumer sees it then it can put it back into the queue so other consumers will see it and then forget about the queue (set the variable which refers to the queue to None, or, if the references are in a list, delete it from the list). From usernet at ilthio.net Wed Aug 11 13:56:13 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 17:56:13 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, RG wrote: > I'm writing a system in a different language but want to use a Python > library. I know of lots of ways to do this (embed a Python interpreter, > fire up a python server) but by far the easiest to implement is to have > the main program spawn a Python interpreter and interact with it through > its stdin/stdout. Or, open python using a socket. That way you have total control over how the information is transfered, as well as bi-directional transfer. From ericwoodworth at gmail.com Wed Aug 11 13:57:14 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 10:57:14 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <3a46969a-0f58-498b-8854-6e7d8b28dde6@j2g2000vbo.googlegroups.com> On Aug 11, 1:55?pm, MRAB wrote: > EW wrote: > > [snip] > > > > > So here the P2 thread has ended and gone away but I still have his > > Queue lingering. > > > So on a thread I can use is_alive() to check status and use join() to > > clean up but I don't see any analogous functionality for Queues. ?How > > do I kill them? ?I thought about putting a suicide message on the > > Queue and then C1 would read it and set the variable to None but i'm > > not sure setting the variable to None actually makes the Queue go > > away. ?It could just end up sitting in memory unreferenced - and > > that's not good. ?Additionally, I could have any number of consumer > > threads reading that Queue so once the first one get the suicide note > > the other consumer threads never would. > > > I figure there has to be an elegant way for managing my Queues but so > > far I can't find it. ?Any suggestions would be appreciated and thanks > > in advance for any help. > > An object will be available for garbage collection when nothing refers > to it either directly or indirectly. If it's unreferenced then it will > go away. > > As for the suicide note, if a consumer sees it then it can put it back > into the queue so other consumers will see it and then forget about the > queue (set the variable which refers to the queue to None, or, if the > references are in a list, delete it from the list). Ok great. I wasn't sure about the Garbage collection part of it. That's actually pretty easy. Thanks! From usernet at ilthio.net Wed Aug 11 14:06:42 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 18:06:42 +0000 (UTC) Subject: How to swallow traceback message References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: On 2010-08-11, Back9 wrote: > On Aug 11, 11:19?am, Tim Harig wrote: >> On 2010-08-11, Back9 wrote: >> > But when I try to exit it, normally I use Ctrl+ C key to quit it. >> > Problem is every time I do like it, it shows Traceback message and it >> > makes my app not professional. >> >> You have three options. >> >> ? ? ? ? 1. Exit more properly. >> >> ? ? ? ? 2. Catch and handle SIGINT yourself. >> >> ? ? ? ? 3. Wrap whatever section of your program is being interrupted in >> ? ? ? ? ? ? ? ? try/except to catch the KeyboardInterrupt exception when it >> ? ? ? ? ? ? ? ? is generated. > > I should have mentioned that I already use try/except > KeyboardInterrupt statement. > But it does not seem to work as I expected. The either your code is somewhere outside of the try/except block when it receives SIGINT, the exception is being caught somewhere below the try/except clause that you added for KeyboardInterrupt, or there is something wrong with your handling code. If you want much more help, you are going to have to post some code to give us some specifics to troubleshoot. From no.email at nospam.invalid Wed Aug 11 14:16:29 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 11:16:29 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> Message-ID: <7xd3tpqaki.fsf@ruckus.brouhaha.com> EW writes: > I thought about doing it that way and I could do it that way but it > still seems like there should be a way to clean up Queues on my own. > If I did it this way then I guess I'd be relying on garbage collection > when the script ended to clean up the Queues for me. Oh, I see. As long as it's possible to start new producer or consumer threads that touch a queue, obviously that queue has to still be around. If the program starts all its threads at the beginning, then runs til they exit, then does more stuff, then you could do something like: # make dictonary of queues, one queue per task type queues = {'sql': Queue(), 'logging': Queue(), ... } for i in threading.Thread(target=your_handler, args=[queues]) del queues and then when all the threads exit, there are no remaining references to the queues. But why do you care? Queues aren't gigantic structures, they're just a list (collections.deque) with an rlock. It's fine to let the gc clean them up; that's the whole point of having a gc in the first place. From nagle at animats.com Wed Aug 11 14:24:07 2010 From: nagle at animats.com (John Nagle) Date: Wed, 11 Aug 2010 11:24:07 -0700 Subject: Is there a Python equivalent to Perl's File::Listing::parse_dir Message-ID: <4c62ead3$0$1587$742ec2ed@news.sonic.net> Perl has a function which will take a remote directory page, in the form that most web sites return for a file directory, and parse it into a useful form: http://www.xav.com/perl/site/lib/File/Listing.html This is especially useful for FTP sites. Is there a Python equivalent of this? I'm converting some old Perl code. Even the Python FTP module doesn't have a directory parser. John Nagle From __peter__ at web.de Wed Aug 11 14:26:49 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Aug 2010 20:26:49 +0200 Subject: How to swallow traceback message References: <76f87f0a-8d58-4e84-ba30-717b45989e64@p7g2000yqa.googlegroups.com> Message-ID: Back9 wrote: > I run my py app to display a file's contents, and it is normally very > long. > So I use it like below: > > python myapp.py input_file | more > to see them step by step. > > But when I try to exit it, normally I use Ctrl+ C key to quit it. > Problem is every time I do like it, it shows Traceback message and it > makes my app not professional. > > How do I handle it gracefully. Step 1, provoke the error: $ python -c"while 1: print 42" | head -n1 42 Traceback (most recent call last): File "", line 1, in IOError: [Errno 32] Broken pipe Step 1a, read the error message carefully ;) Step 2, catch the error: $ python -c"try: while 1: print 42 except IOError as e: if e.errno != 32: raise " | head -n1 42 Step 3, repeat if necessary. IOError is only one example. Peter From rNOSPAMon at flownet.com Wed Aug 11 14:37:20 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 11:37:20 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , Tim Harig wrote: > On 2010-08-11, RG wrote: > > I'm writing a system in a different language but want to use a Python > > library. I know of lots of ways to do this (embed a Python interpreter, > > fire up a python server) but by far the easiest to implement is to have > > the main program spawn a Python interpreter and interact with it through > > its stdin/stdout. > > Or, open python using a socket. You mean a TCP/IP socket? Or a unix domain socket? The former has security issues, and the latter seems like a lot of work. Or is there an easy way to do it that I don't know about? rg From ericwoodworth at gmail.com Wed Aug 11 14:39:10 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 11:39:10 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> Message-ID: <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> On Aug 11, 2:16?pm, Paul Rubin wrote: > EW writes: > > I thought about doing it that way and I could do it that way but it > > still seems like there should be a way to clean up Queues on my own. > > If I did it this way then I guess I'd be relying on garbage collection > > when the script ended to clean up the Queues for me. > > Oh, I see. ?As long as it's possible to start new producer or consumer > threads that touch a queue, obviously that queue has to still be around. > If the program starts all its threads at the beginning, then runs til > they exit, then does more stuff, then you could do something like: > > ? ? # make dictonary of queues, one queue per task type > ? ? queues = {'sql': Queue(), 'logging': Queue(), ... } > > ? ? for i in > ? ? ? ?threading.Thread(target=your_handler, args=[queues]) > > ? ? del queues > > and then when all the threads exit, there are no remaining references to > the queues. ?But why do you care? ?Queues aren't gigantic structures, > they're just a list (collections.deque) with an rlock. ?It's fine to let > the gc clean them up; that's the whole point of having a gc in the first > place. Well I cared because I thought garbage collection would only happen when the script ended - the entire script. Since I plan on running this as a service it'll run for months at a time without ending. So I thought I was going to have heaps of Queues hanging out in memory, unreferenced and unloved. It seemed like bad practice so I wanted to get out ahead of it. But the GC doesn't work the way I thought it worked so there's really no problem I guess. I was just confused on garbage collection it seems. From pramo4d at gmail.com Wed Aug 11 14:43:46 2010 From: pramo4d at gmail.com (Pramod) Date: Wed, 11 Aug 2010 11:43:46 -0700 (PDT) Subject: How to input values of the matrix from keyboard in python Message-ID: Hi I want to know the how we input values into the matrix (N*N size) from keyboard in python, Here I wrote Matrix programe in C++ This asks values from key board and print on the console N*N matrix ; Thanks in advance .... #include using namespace std; int main() { double **a; int i,j,n; cout<<"Enter size of the matrix\n"; cin>>n; for(i=0;i>a[i][j]; cout< Hi all, Is there a way that I can startup my script and pass it a file? For example: ~$ python myscript.py mytext.txt and then access mytext.txt in myscript.py? As a long shot, for myscript.py I tried def __init__(fle): print fle expecting the full path to mytext.txt to be printed but that didn't work. Obviously I've never done this. I hope the above makes sense. any help will be greatly appreciated. Thanks, -- Bradley J. Hintze Graduate Student Duke University School of Medicine 801-712-8799 From no.email at nospam.invalid Wed Aug 11 14:52:27 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 11:52:27 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> Message-ID: <7xvd7h2d90.fsf@ruckus.brouhaha.com> EW writes: > Well I cared because I thought garbage collection would only happen > when the script ended - the entire script. Since I plan on running > this as a service it'll run for months at a time without ending. So I > thought I was going to have heaps of Queues hanging out in memory, > unreferenced and unloved. It seemed like bad practice so I wanted to > get out ahead of it. Even if GC worked that way it wouldn't matter, if you use just one queue per type of task. That number should be a small constant so the memory consumption is small. From falk at mauve.rahul.net Wed Aug 11 14:53:15 2010 From: falk at mauve.rahul.net (Edward A. Falk) Date: Wed, 11 Aug 2010 18:53:15 +0000 (UTC) Subject: urgent requirement at Hyderabad References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Message-ID: In article , Stefan Behnel wrote: >In case anyone wondered: Hyderabad is likely referring to some place in Asia: It's one of the high-tech cities in India. A lot of out-sourcing winds up there. -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From __peter__ at web.de Wed Aug 11 14:58:25 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Aug 2010 20:58:25 +0200 Subject: passing file from command line startup References: Message-ID: Bradley Hintze wrote: > Hi all, > > Is there a way that I can startup my script and pass it a file? For > example: > > ~$ python myscript.py mytext.txt > > and then access mytext.txt in myscript.py? > > As a long shot, for myscript.py I tried > > def __init__(fle): > print fle > > expecting the full path to mytext.txt to be printed but that didn't work. > > Obviously I've never done this. I hope the above makes sense. any help > will be greatly appreciated. > > Thanks, You are looking for sys.argv: $ cat tmp.py import sys print sys.argv $ python tmp.py one two 'many arguments' ['tmp.py', 'one', 'two', 'many arguments'] Around that simple mechanism fancier libraries have been built: http://docs.python.org/library/argparse.html Peter From robert.kern at gmail.com Wed Aug 11 15:03:11 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Aug 2010 14:03:11 -0500 Subject: passing file from command line startup In-Reply-To: References: Message-ID: On 8/11/10 1:47 PM, Bradley Hintze wrote: > Hi all, > > Is there a way that I can startup my script and pass it a file? For example: > > ~$ python myscript.py mytext.txt > > and then access mytext.txt in myscript.py? > > As a long shot, for myscript.py I tried > > def __init__(fle): > print fle > > expecting the full path to mytext.txt to be printed but that didn't work. > > Obviously I've never done this. I hope the above makes sense. any help > will be greatly appreciated. http://docs.python.org/library/sys#sys.argv I do recommend using argparse to process command line arguments, even for the simplest cases: http://docs.python.org/library/argparse -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From python at mrabarnett.plus.com Wed Aug 11 15:04:41 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 20:04:41 +0100 Subject: passing file from command line startup In-Reply-To: References: Message-ID: <4C62F449.4040204@mrabarnett.plus.com> Bradley Hintze wrote: > Hi all, > > Is there a way that I can startup my script and pass it a file? For example: > > ~$ python myscript.py mytext.txt > > and then access mytext.txt in myscript.py? > > As a long shot, for myscript.py I tried > > def __init__(fle): > print fle > > expecting the full path to mytext.txt to be printed but that didn't work. > > Obviously I've never done this. I hope the above makes sense. any help > will be greatly appreciated. > import sys print sys.argv From clp2 at rebertia.com Wed Aug 11 15:06:19 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 11 Aug 2010 12:06:19 -0700 Subject: How to input values of the matrix from keyboard in python In-Reply-To: References: Message-ID: On Wed, Aug 11, 2010 at 11:43 AM, Pramod wrote: > Hi > > ? I want to know the how we input values into the matrix (N*N size) > from keyboard in python, > > Here I wrote Matrix programe in C++ > > This ?asks values from key board and print on the console N*N matrix ; > > Thanks in advance .... > > > #include > using namespace std; > int main() > { > ? ? ? ?double **a; > ? ? ? ?int i,j,n; > ? ? ? ?cout<<"Enter size of the matrix\n"; > ? ? ? ?cin>>n; > ? ? ? ? ? ? ? ?for(i=0;i ? ? ? ? ? ? ? ?for(j=0;j ? ? ? ? ? ? ? ? ? ? ? ?a[i][j] = random(); > //or > ? ? ? ? ? ? ? ?//cin>>a[i][j]; > ? ? ? ? ? ? ? ?cout< ? ? ? ?} > ? ? ? ?for(i=0;i ? ? ? ? ? ? ? ?for(j=0;j ? ? ? ? ? ? ? ? ? ? ? ?cout< ? ? ? ? ? ? ? ?cout< ? ? ? ?} > ? ? ? ?delete [] a; > } from random import random from sys import exit while True: try: N = int(raw_input("Enter size of the matrix: ")) except ValueError: print "Invalid input. Try again." except EOFError: exit(1) else: break a = [[random() for j in xrange(N)] for i in xrange(N)] stringified = "\n".join("\t".join(row) for row in a) print stringified If you're doing serious work with matrices, look at the NumPy package. Cheers, Chris -- http://blog.rebertia.com From iamforufriends at gmail.com Wed Aug 11 15:07:21 2010 From: iamforufriends at gmail.com (UR DREEM GIRL) Date: Wed, 11 Aug 2010 12:07:21 -0700 (PDT) Subject: FIND A NEW HOT GIRL FROM YOUR AREA FREE AND ENJOY Message-ID: <05fe2ce2-ce52-4e2a-8cd0-0a82ed4b8930@u4g2000prn.googlegroups.com> FIND A NEW HOT GIRL FROM YOUR AREA FREE AND ENJOY CLICK... http://adultfriendfinder.com/go/g1250650-ppc http://adultfriendfinder.com/go/g1250650-ppc http://adultfriendfinder.com/go/g1250650-ppc From python at mrabarnett.plus.com Wed Aug 11 15:08:50 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 20:08:50 +0100 Subject: How to input values of the matrix from keyboard in python In-Reply-To: References: Message-ID: <4C62F542.7070803@mrabarnett.plus.com> Pramod wrote: > Hi > > I want to know the how we input values into the matrix (N*N size) > from keyboard in python, > > Here I wrote Matrix programe in C++ > > > This asks values from key board and print on the console N*N matrix ; > [snip] Read from the keyboard using raw_input() (in Python 2, or input() in Python 3) and convert to float. Incidentally, your C++ program doesn't allocate the array. From jearl at notengoamigos.org Wed Aug 11 15:20:41 2010 From: jearl at notengoamigos.org (Jason Earl) Date: Wed, 11 Aug 2010 13:20:41 -0600 Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> <4c610bd2$0$28655$c3e8da3@news.astraweb.com> <87aaouzkm1.fsf@benfinney.id.au> Message-ID: <87hbj1j6ra.fsf@notengoamigos.org> On Tue, Aug 10 2010, Ben Finney wrote: > Steven D'Aprano writes: > >> On Tue, 10 Aug 2010 20:07:06 +1200, Gregory Ewing wrote: >> > Is there any way for a non-.NET program to access a .NET library? Or >> > is it necessary to drink the entire bottle of .NET kool-aid? >> >> http://www.mono-project.com/Main_Page > > Anyone thinking of using Mono needs to be aware of the dangers of > software patents in general, and of .NET in paticular. > > The copyright license for Mono is under free software terms. But that > gives no license at all for the patents. Novell, who have an exclusive > deal for those patents, happily encourages use of Mono by third > parties. > > The controversy has raged for a number of years. For more coverage > than you have time for, see > . The issue has > polarised discussion, unfortunately, and there is a lot of > name-calling and hyperbole on the record now. > > As the Mono site hints, the patent situation for .NET is *very* muddy. > Microsoft hold patents covering much of .NET, but have made a > (non-binding) ?Community Promise? that applies to *some* parts of .NET > . Which is more of a promise than Microsoft has given to Python. I am not arguing for Mono, as I am not a fan. But if you honestly think that Python doesn't infringe on some of Microsoft's patents you are crazy. So where is the promise from Microsoft saying that they won't sue the Python development team into oblivion, or Python end users, for that matter? There isn't one. So while the Mono promise doesn't cover all of Mono, it does cover *some* of Mono, which is better than what Python can say. If you happen to be believe that Microsoft is likely to attack Free Software via patents then Mono is arguably the safest choice. Especially if you confine yourself to the ECMA-sponsored core and the Free Software libraries that are not re-implementations of Microsoft's technology. Jason From pramo4d at gmail.com Wed Aug 11 15:27:32 2010 From: pramo4d at gmail.com (Pramod) Date: Wed, 11 Aug 2010 12:27:32 -0700 (PDT) Subject: How to give matrix input from keyboard or file in python Message-ID: I want to write the following programm in python . Main objective is input from keyoard to enter elements into the matrix . Thanks in advance #include #include #include using namespace std; int main() { double **a; int i,j,n; cout<<"Enter size of the matrix\n"; cin>>n; a=new double* [n]; for(i=0;i>a[i][j]; cout< stringified = "\n".join("\t".join(row) for row in a) File "two.py", line 16, in stringified = "\n".join("\t".join(row) for row in a) TypeError: sequence item 0: expected string, float found Thanks in Advance From backgoodoo at gmail.com Wed Aug 11 15:31:17 2010 From: backgoodoo at gmail.com (Back9) Date: Wed, 11 Aug 2010 12:31:17 -0700 (PDT) Subject: most popular gui framework for python Message-ID: Hi, Does anyone know of what is the most popular gui framework for python application? TIA From python at mrabarnett.plus.com Wed Aug 11 15:33:17 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 20:33:17 +0100 Subject: Queue cleanup In-Reply-To: <7xvd7h2d90.fsf@ruckus.brouhaha.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> <7xvd7h2d90.fsf@ruckus.brouhaha.com> Message-ID: <4C62FAFD.1020102@mrabarnett.plus.com> Paul Rubin wrote: > EW writes: >> Well I cared because I thought garbage collection would only happen >> when the script ended - the entire script. Since I plan on running >> this as a service it'll run for months at a time without ending. So I >> thought I was going to have heaps of Queues hanging out in memory, >> unreferenced and unloved. It seemed like bad practice so I wanted to >> get out ahead of it. > > Even if GC worked that way it wouldn't matter, if you use just one queue > per type of task. That number should be a small constant so the memory > consumption is small. That's basically how _non_-garbage-collected languages work! :-) From suranap at gmail.com Wed Aug 11 15:35:48 2010 From: suranap at gmail.com (Pinku Surana) Date: Wed, 11 Aug 2010 12:35:48 -0700 (PDT) Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> Message-ID: <13e3dc53-f475-46ad-bd3c-ca023b7b6bcb@c38g2000vba.googlegroups.com> On Aug 11, 12:39?pm, fuglyducky wrote: > On Aug 11, 9:31?am, Pinku Surana wrote: > > > > > > > On Aug 11, 12:07?pm, fuglyducky wrote: > > > > I am a complete newbie to Python (and programming in general) and I > > > have no idea what I'm missing. Below is a script that I am trying to > > > work with and I cannot get it to work. When I call the final print > > > function, nothing prints. However, if I print within the individual > > > functions, I get the appropriate printout. > > > > Am I missing something??? Thanks in advance!!!! > > > > ################################################ > > > # Global variable > > > sample_string = "" > > > > def gen_header(sample_string): > > > ? ? HEADER = """ > > > ? ? mymultilinestringhere > > > ? ? """ > > > > ? ? sample_string += HEADER > > > ? ? return sample_string > > > > def gen_nia(sample_string): > > > ? ? NIA = """ > > > ? ? anothermultilinestringhere > > > ? ? """ > > > > ? ? sample_string += NIA > > > ? ? return sample_string > > > > gen_header(sample_string) > > > gen_nia(sample_string) > > > > print(sample_string) > > > There are 2 problems with your program. > > > (1) If you want to use a global variable in a function, you have to > > add the line "global sample_string" to the beginning of that > > function. > > > (2) Once you do (1), you will get an error because you've got > > sample_string as a global and a function parameter. Which one do you > > want to use in the function? You should change the name of the > > parameter to "sample" to solve that confusion. > > > Here's the result, which works for me: > > > sample_string = "" > > def gen_header(sample): > > ? ? global sample_string > > ? ? HEADER = """ > > ? ? mymultilinestringhere > > ? ? """ > > ? ? sample_string = sample + HEADER > > ? ? return sample_string > > def gen_nia(sample): > > ? ? global sample_string > > ? ? NIA = """ > > ? ? anothermultilinestringhere > > ? ? """ > > ? ? sample_string = sample + NIA > > ? ? return sample_string > > gen_header(sample_string) > > gen_nia(sample_string) > > print(sample_string) > > Thanks! That did the trick. > > I am a bit confused though. I tried to follow a sample in a book > (which works) where I didn't have to 1) pass the global variable as a > parameter into the function, 2) did not have to define the global > variable within the function. I apologize if this is a super stupid > question but if it is global, why do I have to pass it into the > function? Shouldn't the global variable be accessible from anywhere??? Since you're new to programming, it's important to understand the fundamentals. x = 0 # GLOBAL def fun(x): # PARAMETER, a type of LOCAL variable y = 1 # LOCAL x += y # Which x do you mean? The local or global? print x # What is this value? fun(x) print x # What is this value? Even though I used the same name "x" for a local and global variable, they are actually completely different. When I call "fun(x)" it COPIES the global value of "x" into the local variable "x" in "fun". In this code, Python assumes in "x += y" you want to use the LOCAL variable. To Python the code looks like this: x_global = 0 def fun(x_local): y_local = 1 x_local += y_local print x_local fun(x_global) print x_global # This is never changed! If that's not what you want, then you have to explicitly tell Python that you want to use the global value (this is not good programming style, by the way!). That's what the "global" keyword does. Try to write some small programs that pass around numbers and strings with different variable names. Try every combination you can think of until you get good at predicting what the output is. From cmpython at gmail.com Wed Aug 11 15:36:49 2010 From: cmpython at gmail.com (CM) Date: Wed, 11 Aug 2010 12:36:49 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <36998fb7-cbb6-4a10-83a6-f943068a6511@v15g2000yqe.googlegroups.com> On Aug 9, 8:10?am, Alex Barna wrote: > I know that this question has been asked for several times, but it > surprises that there is no tool under very active development and the > community activities are very low (mailing list posts). > > All the tools listed in: > > http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#GUITestingTools > > Comparing with AutoIt (www.autoitscript.com), it has tens to hundreds > of posts everyday. AutoIt uses a proprietary BASIC -like language, and > to be honest, I don't like it and I prefer a Pythonic solution. > > pywinauto seems to be the best choice but the community has been very > low also. The same happens in pyguiunit, pyAA, WATSUP, all development > seem to be ceased. > > So what happens to this field (Windows GUI automation) ? This is a little late, but you might want to check out Sikuli. Search for it in this forum, there is a long thread about it. It might be a new useful way to write GUI tests. I have no real idea, though. Che From usernet at ilthio.net Wed Aug 11 15:38:13 2010 From: usernet at ilthio.net (Tim Harig) Date: Wed, 11 Aug 2010 19:38:13 +0000 (UTC) Subject: Line-by-line processing when stdin is not a tty References: Message-ID: On 2010-08-11, RG wrote: > In article , > Tim Harig wrote: > >> On 2010-08-11, RG wrote: >> > I'm writing a system in a different language but want to use a Python >> > library. I know of lots of ways to do this (embed a Python interpreter, >> > fire up a python server) but by far the easiest to implement is to have >> > the main program spawn a Python interpreter and interact with it through >> > its stdin/stdout. >> >> Or, open python using a socket. > > You mean a TCP/IP socket? Or a unix domain socket? The former has > security issues, and the latter seems like a lot of work. Or is there > an easy way to do it that I don't know about? I was referring to unix domain sockets or more specifically stream pipes. I guess it depends what language you are using and what libraries you have access to. Under C, working with stream pipes is no more trivial then using pipe(). You can simply create the socket descriptors using socketpair(). Keep one of the descriptors for your process and pass the other to the python child process as both stdin and stdout. From thomas at jollybox.de Wed Aug 11 15:38:47 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 11 Aug 2010 21:38:47 +0200 Subject: Is there a Python equivalent to Perl's File::Listing::parse_dir In-Reply-To: <4c62ead3$0$1587$742ec2ed@news.sonic.net> References: <4c62ead3$0$1587$742ec2ed@news.sonic.net> Message-ID: <201008112138.48097.thomas@jollybox.de> On Wednesday 11 August 2010, it occurred to John Nagle to exclaim: > This is especially useful for FTP sites. It sounds like you're trying to use HTTP to something a lot more easily done with FTP, without any reason not to use FTP. http://docs.python.org/library/ftplib.html#ftplib.FTP.dir From python at mrabarnett.plus.com Wed Aug 11 15:39:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 11 Aug 2010 20:39:32 +0100 Subject: urgent requirement at Hyderabad In-Reply-To: References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> Message-ID: <4C62FC74.2040300@mrabarnett.plus.com> Stefan Behnel wrote: > In case anyone wondered: Hyderabad is likely referring to some place in > Asia: > > http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29 > And Berlin is likely some place in Europe: http://en.wikipedia.org/wiki/Berlin_(disambiguation) :-) From ericjvandervelden at gmail.com Wed Aug 11 15:45:07 2010 From: ericjvandervelden at gmail.com (Eric J. Van der Velden) Date: Wed, 11 Aug 2010 12:45:07 -0700 (PDT) Subject: mi Message-ID: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> Hello, I have these types, class A: def __init__(s): super().__init__() print("A") class B(A): def __init__(s): super().__init__() print("B") class C(A): def __init__(s): super().__init__() print("C") class D(B,C): def __init__(s): super().__init__() print("D") If I do (in 3.1) >>> d=D() A C B D Why this order? I thought, first to D, then B, then A. He prints "A". He comes back in B and prints "B". He goes to C. Then somehow he doesn't go again to A. He prints "C". Then back to D and prints "D". Thanks, Eric J. From user at example.net Wed Aug 11 15:47:27 2010 From: user at example.net (J.O. Aho) Date: Wed, 11 Aug 2010 21:47:27 +0200 Subject: most popular gui framework for python In-Reply-To: References: Message-ID: <8cgd2fFjs7U1@mid.individual.net> Back9 wrote: > Does anyone know of what is the most popular gui framework for python > application? Don't think it's the most popular, but I think it may be the one which works for quite a lot of different platforms, PyQt, works fine on my desktop as cellphone. -- //Aho From debatem1 at gmail.com Wed Aug 11 15:51:24 2010 From: debatem1 at gmail.com (geremy condra) Date: Wed, 11 Aug 2010 12:51:24 -0700 Subject: python interview quuestions In-Reply-To: References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <4c6298c1$0$11101$c3e8da3@news.astraweb.com> Message-ID: On Wed, Aug 11, 2010 at 6:04 AM, Roy Smith wrote: > In article <4c6298c1$0$11101$c3e8da3 at news.astraweb.com>, > ?Steven D'Aprano wrote: > >> Sounds ridiculous, but apparently there are vast hordes of people who can >> barely program "Hello World" applying for programming jobs. One figure >> bandied about -- how accurately, I don't know -- is 199 out of every 200 >> job applicants for programming jobs are barely capable of writing a line >> of code. > > By the same token, there are lots of people with advanced degrees in > computer science who can't code their way out of a paper bag. > > One advantage of the take-home test is that you can prepare the test > once and amortize the preparation cost over many applicants. ?It's a big > investment of time to interview somebody. ?By the time I get up to > investing an hour or so of my time on a phone screen, I'd like to weed > out the obvious rejects as cheaply as possible. > > Even more interesting is to publish some problems on your web site and > instruct applicants to submit a solution to one of them along with their > resume. ?This makes the per-applicant cost to administer the exam > essentially zero. ?It also has the nice side-effect of weeding out the > resume spammers. ?To be honest, I've never done this, but I've seen > companies that do. ?I may try it sometime. I can't recall who it was, but I remember being very impressed by a company that did a variant of this a few years ago: they put programming problems on the sides of pay phones, taxis, etc. with a note that said 'If you can solve this, call us'. I have zero doubt that they got some top talent that way. Geremy Condra From no.email at nospam.invalid Wed Aug 11 16:11:23 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 13:11:23 -0700 Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <4c6298c1$0$11101$c3e8da3@news.astraweb.com> Message-ID: <7xfwykoqok.fsf@ruckus.brouhaha.com> geremy condra writes: > I can't recall who it was, but I remember being very impressed by a > company that did a variant of this a few years ago: they put > programming problems on the sides of pay phones, taxis, etc. with a > note that said 'If you can solve this, call us'. I have zero doubt > that they got some top talent that way. Several companies have done that. You might be thinking of ITA Software: http://www.itasoftware.com/careers/puzzle_archive.html From thomas at jollybox.de Wed Aug 11 16:13:29 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 11 Aug 2010 22:13:29 +0200 Subject: most popular gui framework for python In-Reply-To: References: Message-ID: <201008112213.30328.thomas@jollybox.de> On Wednesday 11 August 2010, it occurred to Back9 to exclaim: > Hi, > > Does anyone know of what is the most popular gui framework for python > application? I'd guess at Tkinter - it's part of the standard library. Another quite popular option is PyGtk. Other good ones include wxPython, PyQt, and PySide. From raoulbia at gmail.com Wed Aug 11 16:14:35 2010 From: raoulbia at gmail.com (Baba) Date: Wed, 11 Aug 2010 13:14:35 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 Message-ID: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> level: beginner exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 packs, write an exhaustive search to find the largest number of McNuggets that cannot be bought in exact quantity. exercise source: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf please help me write this code i believe it's something along the lines of this: c=0 sol=[] for n in range (0,10): for a in range (0,10): for b in range (0,10): for c in range (0,10): sol=6*a+9*b+20*c if sol!=n: c+=1 if c==6: print sol From rNOSPAMon at flownet.com Wed Aug 11 16:20:59 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 13:20:59 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , Tim Harig wrote: > On 2010-08-11, RG wrote: > > In article , > > Tim Harig wrote: > > > >> On 2010-08-11, RG wrote: > >> > I'm writing a system in a different language but want to use a Python > >> > library. I know of lots of ways to do this (embed a Python interpreter, > >> > fire up a python server) but by far the easiest to implement is to have > >> > the main program spawn a Python interpreter and interact with it through > >> > its stdin/stdout. > >> > >> Or, open python using a socket. > > > > You mean a TCP/IP socket? Or a unix domain socket? The former has > > security issues, and the latter seems like a lot of work. Or is there > > an easy way to do it that I don't know about? > > I was referring to unix domain sockets or more specifically stream > pipes. I guess it depends what language you are using and what libraries > you have access to. Under C, working with stream pipes is no more trivial > then using pipe(). You can simply create the socket descriptors using > socketpair(). Keep one of the descriptors for your process and pass the > other to the python child process as both stdin and stdout. Ah. That is in fact exactly what I am doing, and that is how I first encountered this problem. rg From thomas at jollybox.de Wed Aug 11 16:24:35 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 11 Aug 2010 22:24:35 +0200 Subject: mi In-Reply-To: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> References: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> Message-ID: <201008112224.35960.thomas@jollybox.de> On Wednesday 11 August 2010, it occurred to Eric J. Van der Velden to exclaim: > Hello, > > I have these types, > > class A: > def __init__(s): > super().__init__() > print("A") > class B(A): > def __init__(s): > super().__init__() > print("B") > class C(A): > def __init__(s): > super().__init__() > print("C") > class D(B,C): > def __init__(s): > super().__init__() > print("D") > > If I do (in 3.1) > > >>> d=D() > > A > C > B > D > > Why this order? I thought, first to D, then B, then A. He prints "A". > He comes back in B and prints "B". He goes to C. Then somehow he > doesn't go again to A. He prints "C". Then back to D and prints "D". Think again about what you're seeing here. You're printing AFTER the call to super().__init__(). That means that it first walks the inheritance hierarchy, and then prints -- your trace is "the wrong way around" So, what happens is: you call D(). In it, super() delegates to B(). Which has super delegate to C(), which then has super() delegate finally to A(). D, B, C, A You say you were expecting D, B, A -- but what of C? You also imply that you would have expected two visits to A -- but that would defeat the point of super() -- you don't actually want one constructor to be called twice: the constructor almost certainly isn't written with that possibility in mind. > > Thanks, > > Eric J. From ericwoodworth at gmail.com Wed Aug 11 16:26:43 2010 From: ericwoodworth at gmail.com (EW) Date: Wed, 11 Aug 2010 13:26:43 -0700 (PDT) Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> <7xvd7h2d90.fsf@ruckus.brouhaha.com> Message-ID: <9b270554-e7cb-48ec-aa0e-c78690a81b54@q26g2000vbn.googlegroups.com> On Aug 11, 2:52?pm, Paul Rubin wrote: > EW writes: > > Well I cared because I thought garbage collection would only happen > > when the script ended - the entire script. ?Since I plan on running > > this as a service it'll run for months at a time without ending. ?So I > > thought I was going to have heaps of Queues hanging out in memory, > > unreferenced and unloved. ?It seemed like bad practice so I wanted to > > get out ahead of it. > > Even if GC worked that way it wouldn't matter, if you use just one queue > per type of task. ?That number should be a small constant so the memory > consumption is small. Well I can't really explain it but 1 Queue per task for what I'm designing just doesn't feel right to me. It feels like it will lack future flexibility. I like having 1 Queue per producer thread object and the person instantiating that object can do whatever he wants with that Queue. I can't prove I'll need that level of flexibility but I don't see why it' bad to have. It's still a small number of Queues, it's just a small, variable, number of Queues. From news1234 at free.fr Wed Aug 11 16:48:26 2010 From: news1234 at free.fr (News123) Date: Wed, 11 Aug 2010 22:48:26 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4c630c9a$0$5445$426a74cc@news.free.fr> As said in the instructions. if you find six consecutive numbers, that can be bough in exact quantity, then you know, that all bigger numbers can also be bought in exact quantity. I would do a brute force approach first I would create one function, which will try to find out, whether one can buy an exact quantity of n nuggets. example function prototype def can_buy(n_nuggets): # here you have to write your code the function should return True or if you're curious a list of packages and quantities if quantity n_nuggets can be bought otherwise it should return False or an empty list. then you can create another function which will start with 6 nuggets (or if you like to with 1 nugget) and which will count how many times in sequence it managed to return a result. (by using the function can_buy() and managibng a counter) If it found 6 results in sequence, then you know, that all bigger numbers can also be bought and that the biggest number, which could not be bought was 6 numbers before. I think nobody here will write the soultion for you. If you write some more code and if you tell us what it's supposed to to and with what exectly you're having trouble with I can give you more hints. On 08/11/2010 10:14 PM, Baba wrote: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf > > please help me write this code > > i believe it's something along the lines of this: > > c=0 > sol=[] > for n in range (0,10): > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print sol Not very modular. > c=0 # c could have a meaningful name and probably a different one > # it seems, that you reuse c also in a for statement > sol=[] > for n in range (0,10): # n should not only go from 0 to 10 > # but from 0 until c is 6 # i'd put this in a separate function it makes it also easier for # you to understand and test > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): # c used here and lso as counter > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print "solution is",sol-6 > From peter.milliken at gmail.com Wed Aug 11 17:02:28 2010 From: peter.milliken at gmail.com (Peter) Date: Wed, 11 Aug 2010 14:02:28 -0700 (PDT) Subject: most popular gui framework for python References: Message-ID: <4b19ddc3-129d-40fc-b82f-41211f6105fa@s17g2000prh.googlegroups.com> On Aug 12, 6:13?am, Thomas Jollans wrote: > On Wednesday 11 August 2010, it occurred to Back9 to exclaim: > > > Hi, > > > Does anyone know of what is the most popular gui framework for python > > application? > > I'd guess at Tkinter - it's part of the standard library. > Another quite popular option is PyGtk. Other good ones include wxPython, PyQt, > and PySide. Lots of choices - you could try Jython as well, then you have access to all the Java GUI framework :-) Personally, I have used Tkinter, PMW (Widgets built on Tkinter) - all of my GUI stuff to date is written using these. I have tried WxPython - I found it quite difficult to learn, but this was quite some years ago now and perhaps there are some easy books that will help you ease into it. I am currently experimenting with PyQt - I have Mark Summerfield's book, "Rapid GUI Programming with Python and Qt" - very readable book. Now that the Qt license is more friendly to the "hobbyist" I think I will switch all of my GUI work over to PyQt. There are so many these days (just look at the Python wiki page on GUIs) that you can't really try them all - just not enough hours in the day. I would suggest you have a quick browse of what's available and then select one or two to focus on. Most are pretty well "portable" between multiple platforms - but realistically I have never used anything other than a Windoze platform cross-platform compatibility may not be such a big deal. I would strongly recommend reading the Python Wiki page on GUI programming: http://wiki.python.org/moin/GuiProgramming Peter From rNOSPAMon at flownet.com Wed Aug 11 17:07:27 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 14:07:27 -0700 Subject: Line-by-line processing when stdin is not a tty References: Message-ID: In article , RG wrote: > In article , > Tim Harig wrote: > > > On 2010-08-11, RG wrote: > > > In article , > > > Tim Harig wrote: > > > > > >> On 2010-08-11, RG wrote: > > >> > I'm writing a system in a different language but want to use a Python > > >> > library. I know of lots of ways to do this (embed a Python > > >> > interpreter, > > >> > fire up a python server) but by far the easiest to implement is to > > >> > have > > >> > the main program spawn a Python interpreter and interact with it > > >> > through > > >> > its stdin/stdout. > > >> > > >> Or, open python using a socket. > > > > > > You mean a TCP/IP socket? Or a unix domain socket? The former has > > > security issues, and the latter seems like a lot of work. Or is there > > > an easy way to do it that I don't know about? > > > > I was referring to unix domain sockets or more specifically stream > > pipes. I guess it depends what language you are using and what libraries > > you have access to. Under C, working with stream pipes is no more trivial > > then using pipe(). You can simply create the socket descriptors using > > socketpair(). Keep one of the descriptors for your process and pass the > > other to the python child process as both stdin and stdout. > > Ah. That is in fact exactly what I am doing, and that is how I first > encountered this problem. > > rg And now I have encountered another problem: -> print sys.stdin.encoding <- None But when I run from a terminal: [ron at mickey:~]$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'UTF-8' I thought the value of sys.stdin.encoding was hard-coded into the Python executable at compile time, but that's obviously wrong. So how does Python get the value of sys.stdin.encoding? rg From clp2 at rebertia.com Wed Aug 11 17:09:57 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 11 Aug 2010 14:09:57 -0700 Subject: mi In-Reply-To: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> References: <5d7030e1-4c6e-48fb-8f62-4f3d3fc420c9@l20g2000yqm.googlegroups.com> Message-ID: On Wed, Aug 11, 2010 at 12:45 PM, Eric J. Van der Velden wrote: > Hello, > > I have these types, > > class A: > ? ? ? ?def __init__(s): > ? ? ? ? ? ? ? ?super().__init__() > ? ? ? ? ? ? ? ?print("A") > class B(A): > ? ? ? ?def __init__(s): > ? ? ? ? ? ? ? ?super().__init__() > ? ? ? ? ? ? ? ?print("B") > class C(A): > ? ? ? ?def __init__(s): > ? ? ? ? ? ? ? ?super().__init__() > ? ? ? ? ? ? ? ?print("C") > class D(B,C): > ? ? ? ?def __init__(s): > ? ? ? ? ? ? ? ?super().__init__() > ? ? ? ? ? ? ? ?print("D") > > If I do (in 3.1) >>>> d=D() > A > C > B > D > > Why this order? Well, it's clearer for illustration purposes if you do the print()s "preorder" (before the super calls) rather than "postorder", but anyway... Because that's how Python's Method Resolution Order (MRO) works. Very smart people have thought a lot about this. It is The Right Order (tm). To understand *why* it's right, read: http://www.python.org/download/releases/2.2.3/descrintro/#mro and (if you dare): http://www.python.org/download/releases/2.3/mro/ The order (of the method calls, not the print()s) is (extremely roughly) from most derived to most ancestral, without calling anything twice. Is that not a logical and sensible (albeit not necessarily obvious) rule? > I thought, first to D, then B, then A. He prints "A". > He comes back in B and prints "B". He goes to C. Then somehow he > doesn't go again to A. He prints "C". Then back to D and prints "D". "super()" is a bit of a misnomer. **It doesn't necessarily call a superclass method.** In fact, the Dylan programming language (which Python borrowed its MRO from) instead names the analogous function "next-method" because it calls the method that comes after the current one in the MRO. Here's what actually happened: D called B. Then B called *C* (seems bizarre, yes). C is obviously not a superclass of B; but this is the only way to make things work out right (see aforelinked docs). From there, C called A, and the rest is obvious. Multiple inheritance can get tricky; avoid it when possible. Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Wed Aug 11 17:13:04 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 11 Aug 2010 14:13:04 -0700 Subject: How to input values of the matrix from keyboard in python In-Reply-To: References: Message-ID: On Wed, Aug 11, 2010 at 12:06 PM, Chris Rebert wrote: > On Wed, Aug 11, 2010 at 11:43 AM, Pramod wrote: >> Hi >> >> ? I want to know the how we input values into the matrix (N*N size) >> from keyboard in python, >> >> Here I wrote Matrix programe in C++ >> >> This ?asks values from key board and print on the console N*N matrix ; >> >> Thanks in advance .... >> >> >> #include >> using namespace std; >> int main() >> { >> ? ? ? ?double **a; >> ? ? ? ?int i,j,n; >> ? ? ? ?cout<<"Enter size of the matrix\n"; >> ? ? ? ?cin>>n; >> ? ? ? ? ? ? ? ?for(i=0;i> ? ? ? ? ? ? ? ?for(j=0;j> ? ? ? ? ? ? ? ? ? ? ? ?a[i][j] = random(); >> //or >> ? ? ? ? ? ? ? ?//cin>>a[i][j]; >> ? ? ? ? ? ? ? ?cout<> ? ? ? ?} >> ? ? ? ?for(i=0;i> ? ? ? ? ? ? ? ?for(j=0;j> ? ? ? ? ? ? ? ? ? ? ? ?cout<> ? ? ? ? ? ? ? ?cout<> ? ? ? ?} >> ? ? ? ?delete [] a; >> } > > from random import random > from sys import exit > > while True: > ? ?try: > ? ? ? ?N = int(raw_input("Enter size of the matrix: ")) > ? ?except ValueError: > ? ? ? ?print "Invalid input. Try again." > ? ?except EOFError: > ? ? ? ?exit(1) > ? ?else: > ? ? ? ?break > > a = [[random() for j in xrange(N)] for i in xrange(N)] > stringified = "\n".join("\t".join(row) for row in a) > print stringified Should have prefaced that with an "untested" disclaimer. Make that: stringified = "\n".join("\t".join(str(cell) for cell in row) for row in a) - Chris From peter.milliken at gmail.com Wed Aug 11 17:14:42 2010 From: peter.milliken at gmail.com (Peter) Date: Wed, 11 Aug 2010 14:14:42 -0700 (PDT) Subject: python interview quuestions References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <507f1970-9c15-4200-a90b-6ebc018c074b@a4g2000prm.googlegroups.com> Message-ID: On Aug 11, 8:50?pm, Tim Chase wrote: > On 08/11/10 01:24, Terry Reedy wrote: > > > On 8/10/2010 8:08 PM, Roy Smith wrote: > >> In any case, if the candidate were to submit somebody else's > >> work, it would come out pretty quickly as we discussed their > >> code. ?I suppose one question I might ask would be, "Can you > >> explain why, when I copy-paste one of your comments into a > >> google search box, your entire program appears?" > > > Mostly likely because I wrote the original... > > > would be my answer. > > Unfortunately there are candidates who would give your answer but > then have trouble with "Then why are the Last-Modified HTTP > headers showing a date several months before our interview?" > It's as bad as the phone-interviews I've done where in the > background I can hear the person on the other end typing my > questions into a search box and reading off answers. ?On the > bright side, those are short interviews... ;-) > > -tkc I know we are straying somewhat here :-) But as an interviewer way back when in the never-never, I used to look at the interviewee's work history i.e. 18 months here, 12 months there, 6 months here etc and pretty much wipe them from my short-list based on that alone :-) Because it takes at least 3 months for a programmer to get "up to speed" fitting into your company and on your applications, they are usually only really productive and really "hitting their stride" at 6 months - somebody who "job hops" will already be looking for the next job by that time! I really did't have time to waste on these people - then there was the agents fee for finding them for you - big investment for zero return. So I would recommend to anybody that they attempt to maintain a stable work history in this respect. For example, my personal work history is 8, 7.5, 8.5, 0.5, 3, 3, 8 (years that is). My current company is extremely stable, I enjoy the work, so I don't see any reason why I won't be here until I retire (or die at my desk - whichever comes first :-)). Peter From thomas at jollybox.de Wed Aug 11 17:15:45 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 11 Aug 2010 23:15:45 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <201008112315.45841.thomas@jollybox.de> On Wednesday 11 August 2010, it occurred to Baba to exclaim: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. The MacDonald's at Nuremberg central station once sold me 25 in a 20-pack. So this won't work. > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00 > -introduction-to-computer-science-and-programming-fall-2008/assignments/pse > t2.pdf > > please help me write this code > > i believe it's something along the lines of this: > > c=0 > sol=[] > for n in range (0,10): > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print sol From emile at fenx.com Wed Aug 11 17:25:08 2010 From: emile at fenx.com (Emile van Sebille) Date: Wed, 11 Aug 2010 14:25:08 -0700 Subject: urgent requirement at Hyderabad In-Reply-To: <4C62FC74.2040300@mrabarnett.plus.com> References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> <4C62FC74.2040300@mrabarnett.plus.com> Message-ID: On 8/11/2010 12:39 PM MRAB said... > Stefan Behnel wrote: >> In case anyone wondered: Hyderabad is likely referring to some place >> in Asia: >> >> http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29 >> > And Berlin is likely some place in Europe: > > http://en.wikipedia.org/wiki/Berlin_(disambiguation) > > :-) And Paris is likely someplace in the US... http://en.wikipedia.org/wiki/Paris_%28disambiguation%29 Emile :)) From tormod.hagen at gmail.com Wed Aug 11 17:29:24 2010 From: tormod.hagen at gmail.com (tormod) Date: Wed, 11 Aug 2010 14:29:24 -0700 (PDT) Subject: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT) Message-ID: Hi, I've tried countless times to build & install cx_Oracle on Python 3.1.2, and failed every time, so I'd like to ask someone for help. I've included step-by-step (literally) description of my last try, with so much detail I could, to help clarify things. I can build without errors. I can install without errors. I fail to import. I'm using an NT box (os:Win7) Downloaded Oracle Instant Client 10.2.0.4 instantclient-basic-win32-10.2.0.4.zip --> extracted to C:\TEMP \ORAIC10\bin instantclient-sdk-win32-10.2.0.4.zip --> extracted to C:\TEMP \ORAIC10\sdk Downloaded source code(cx_Oracle-5.0.4.tar.gz) from http://cx-oracle.sourceforge.net/ --> extracted to C:\TEMP\Python\cx_Oracle Installed Python 3.1.2 --> C:\Python31 Installed MinGW 5.1.6 --> C:\MinGW Startet command prompt: cd C:\TEMP\Python\cx_Oracle PATH=%PATH%;C:\Python31;C:\MinGW\bin;C:\TEMP\ORAIC10\bin SET ORACLE_HOME=C:\TEMP\ORAIC10 SET LD_LIBRARY_PATH=C:\TEMP\ORAIC10\sdk\lib python setup.py build -c mingw32 python setup.py install start python: Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import cx_Oracle Traceback (most recent call last): File "", line 1, in ImportError: DLL load failed: The specified module could not be found. running build running build_ext building 'cx_Oracle' extension creating build creating build\temp.win32-3.1-10g creating build\temp.win32-3.1-10g\Release C:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\TEMP\ORAIC10\sdk \include -I C:\Python31\include -IC:\Python31\PC -c cx_Oracle.c -o build \temp.win32-3.1-10g\ Release\cx_oracle.o -DBUILD_VERSION=5.0.4 -DWITH_UNICODE writing build\temp.win32-3.1-10g\Release\cx_Oracle.def creating build\lib.win32-3.1-10g C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-3.1-10g \Release\cx_ oracle.o build\temp.win32-3.1-10g\Release\cx_Oracle.def -LC:\TEMP \ORAIC10\bin -L C:\TEMP\ORAIC10 -LC:\TEMP\ORAIC10\oci\lib\msvc -LC:\TEMP\ORAIC10\sdk \lib\msvc -L C:\Python31\libs -LC:\Python31\PCbuild -loci -lpython31 -lmsvcr90 -o build\lib.w in32-3.1-10g\cx_Oracle.pyd running install running build running build_ext running install_lib copying build\lib.win32-3.1-10g\cx_Oracle.pyd -> C:\Python31\Lib\site- packages running install_data running install_egg_info Removing C:\Python31\Lib\site-packages\cx_Oracle-5.0.4-py3.1.egg-info Writing C:\Python31\Lib\site-packages\cx_Oracle-5.0.4-py3.1.egg-info I've opened the cx_Oracle.pyd with Dependency Walker (http:// www.dependencywalker.com/) and DW reports it can't find: OCI.DLL, PYTHON31.DLL, MSVCR90.DLL (why?) Appreciate any help, even wildshots and 2 cents are welcome - I'll try everything. Cheers, Tom From no.email at nospam.invalid Wed Aug 11 17:38:50 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 14:38:50 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> <7xvd7h2d90.fsf@ruckus.brouhaha.com> <9b270554-e7cb-48ec-aa0e-c78690a81b54@q26g2000vbn.googlegroups.com> Message-ID: <7x4of0n82d.fsf@ruckus.brouhaha.com> EW writes: > Well I can't really explain it but 1 Queue per task for what I'm > designing just doesn't feel right to me. It feels like it will lack > future flexibility. That makes no sense at all. Multiple readers and writers per queue are the way Python queues are designed to work. The normal way to spray a bunch of concurrent tasks to worker threads is just have a bunch of workers listening to one queue. It's the same way at the producer end. From cs at zip.com.au Wed Aug 11 18:12:49 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 12 Aug 2010 08:12:49 +1000 Subject: Line-by-line processing when stdin is not a tty In-Reply-To: References: Message-ID: <20100811221249.GA3087@cskk.homeip.net> On 11Aug2010 12:35, Tim Harig wrote: | > The buffering is a performance choice. Every write requires a context | > switch from userspace to kernel space, and availability of data in the | > pipe will wake up a downstream process blocked trying to read. | > It is far more efficient to do as few such copies as possible, [...] | | Right, I don't question the optimization. I question whether the | intelligence that performes that optimation should be placed within cat or | whether it should be placed within the shell. It seems to me that the | shell has a better idea of how the command is being used and can therefore | make a better decision about whether or not buffering is appropriate. I would argue it's not much better placed, though it would be nice if the control could be issued from there. But it can't. Regarding the former, in this pipeline: cat some files... | python filter program | something else how shall the shell know if the python filter (to take the OP's case) wants its input line buffered (rare) or block buffered (usually ok)? What might be useful would be a way to attach an attribute to a pipe or other file descriptor indicating the desired buffering behaviour that writers to the file descriptor should adopt. Of course, the ugly sides to that are how many buffering regimes should it be possible to express and how and when should the upstream (writing) program decide to check? In a pipeline the pipes are made _before_ any of the programs commence because the programs need to be attached to the pipes (this is done before the programs themselves are dispatched). So, _after_ dispatch the python-wanting-line-buffering issues an ioctl on the pipe saying "I want line buffering". However, the upstream program may well already have commenced operation before that happens. It may even have run to completion before that happens! So, shall all upstream programs be required to poll? How often? On every write? Shall they receive a signal? What if they don't catch it? If the downstream program _requires_ line buffering then the whole situation is racey and unreliable. You can see that on reflection this isn't easy to resolve cleanly from _outside_ the writing program. To do it from inside requires all programs to sprout an option like GNU cat's -u option. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ What progress we are making. In the Middle Ages they would have burned me. Now they are content with burning my books. - Sigmund Freud From alex.lavoro.propio at gmail.com Wed Aug 11 18:45:44 2010 From: alex.lavoro.propio at gmail.com (Alex Barna) Date: Wed, 11 Aug 2010 15:45:44 -0700 (PDT) Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> <4c628934$0$11101$c3e8da3@news.astraweb.com> Message-ID: <605127db-07d8-40e0-bef5-ad441d2b2605@x21g2000yqa.googlegroups.com> I'm afraid that my first post has not been understood correctly and most of the following posts are OT, as Ben Finney indicated. The GUI automation has a long history, perhaps since the first windowing system was invented. For years I've been doing this using several different technologies/languages. But to my surprise, this ares is not very *cultivated* by Pythonistas. Many projects (see the link in my first post) have lost the love of their maintainers and have not been updated for years. Except one, pywinauto, which has a recent release in April. However, the community activity (mailing list) is very low, website and documentation have not been updated for long also. All this freaks me out on adopting a technology like this : - is there still anyone using it ? - what if I encounter a problem but no body replies me in the mailing list ? Comparing with the rival AutoIt, using a BASIC-like language, which I don't like at all, has hundreads of post in the users' forum everyday. It makes me doubt: is Python the correct language to do GUI automation ? P.S.: hopefully it has been clarified, my original intention of the post is not to debate/discuss: - *why* automating GUI ? - whether GUI/CLI is better. - the points GUI or CLI is designed for. Obvious they are all OT. Alex Barna. From gelonida at gmail.com Wed Aug 11 19:07:25 2010 From: gelonida at gmail.com (Gelonida) Date: Thu, 12 Aug 2010 01:07:25 +0200 Subject: segfault with small pyqt script Message-ID: Hi Guys, I'm desperate. I'm having a real application, which fails rather often when finishing it. I'm not sure, whether any serious problem could be hidden behind it The script is a pyqt script, which segfaults most of the time on my ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. Trying to create the smallest possible test case I ended up with following script, which I named dodo.py and which i made executable with chmod +x ./dodo.py #!/usr/bin/env python from PyQt4.QtGui import QDialog,QGridLayout,QLabel,QComboBox,QPushButton,QApplication a = "one" b = "unused" c = "also unused" d= "ans also unused" e = "another var" f = "something" class MyForm(QDialog): def __init__(self,parent=None,config=None,ini_info=None): super(MyForm,self).__init__(parent=parent) grid = QGridLayout() quit_btn = QPushButton("Quit") quit_btn.clicked.connect(self.quit) grid.addWidget(quit_btn,0,0) name = "a_name" vals_box = QComboBox() vals_box.addItem("one") vals_box.addItem("two") grid.addWidget(vals_box,0,1) self.setLayout(grid) def quit(self): self.close() if __name__ == "__main__": app = QApplication([]) myform = MyForm() myform.show() retcode = app.exec_() print "last" In order to perform the test several times I typed on the command line: a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done As soon as the window shows up I click twice (slowly ) on 'one' and then on quit. Sample output can be seen here: gelonida at mypc:/my/directory$ a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done last last Segmentation fault last last Segmentation fault last Segmentation fault last Segmentation fault last last last last last Segmentation fault last last Segmentation fault last Segmentation fault as you see the segfault happens rather often. Does anybody see something suspicious with my code? Can anybody else reproduce this? as soon as I remove more lines the error seems to disappear. What else could I do to debug this issue? thanks for help or other ideas If I run my script with strace ./dodo.py I get following last lines for a run without error > rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f65d6b3b8f0}, {0x4d9820, [], SA_RESTORER, 0x7f65d6b3b8f0}, 8) = 0 > munmap(0x7f65c6344000, 622280) = 0 > brk(0x2d71000) = 0x2d71000 > poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLIN|POLLOUT}]) > read(7, "\22\0\233\6\2\0\300\5\2\0\300\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 384 > writev(7, [{"\232\7\2\0\210\0\300\0056\0\2\0\207\0\300\5<\0\2\0\211\0\300\5\232\7\2\0s\0\300\5"..., 540}, {NULL, 0}, {"", 0}], 3) = 540 > poll([{fd=7, events=POLLIN}], 1, -1) = 1 ([{fd=7, revents=POLLIN}]) > read(7, "\34\0\241\6r\0\300\5\234\1\0\0\377\261\220\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 1472 > read(7, 0x29fa704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}]) > writev(7, [{"O\7\2\0\1\0\300\5<\0\2\0\0\0\300\5+\0\1\0", 20}, {NULL, 0}, {"", 0}], 3) = 20 > poll([{fd=7, events=POLLIN}], 1, -1) = 1 ([{fd=7, revents=POLLIN}]) > read(7, "\1\2\333\6\0\0\0\0\5\0\300\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 4096) = 32 > read(7, 0x29fa704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > close(7) = 0 > write(19, "\1\v\3\200\1\0\0\0\0\0\0\0\t\0\0\0", 16) = 16 > close(19) = 0 > open("/proc/stat", O_RDONLY|O_CLOEXEC) = 7 > read(7, "cpu 59482 54 13580 7506040 4761"..., 8192) = 2439 > close(7) = 0 > writev(15, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12 > close(15) = 0 > writev(13, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12 > close(13) = 0 > close(12) = 0 > close(11) = 0 > unlink("/tmp/orbit-klausf/linc-1282-0-6094bc6991603") = 0 > close(14) = 0 > write(6, "@", 1) = 1 > close(6) = 0 > close(5) = 0 > rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_NOCLDSTOP, 0x7f65d6b3b8f0}, {0x7f65d40a3860, [], SA_RESTORER|SA_NOCLDSTOP, 0x7f65d6b3b8f0}, 8) = 0 > exit_group(0) and following when an error occurs: > writev(16, [{"<\10\2\0;\6\340\5F\6\5\0!\6\340\5\10\0\340\5\0\0\0\0U\0\33\0\232\7\2\0"..., 16380}, {NULL, 0}, {"", 0}], 3) = 16380 > read(16, 0xbc49d4, 4096) = -1 EAGAIN (Resource temporarily unavailable) > poll([{fd=16, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=16, revents=POLLOUT}]) > writev(16, [{"\232\10\t\0\3\6\340\5R\6\340\5C\6\340\5=\6\340\5\0\0\0\0\0\0\0\0\2\0\2\0"..., 4256}, {NULL, 0}, {"", 0}], 3) = 4256 > poll([{fd=16, events=POLLIN}], 1, -1) = 1 ([{fd=16, revents=POLLIN}]) > read(16, "\16\0\317\26s\0\340\5\0\0>\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 64 > read(16, 0xbc49d4, 4096) = -1 EAGAIN (Resource temporarily unavailable) > poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}]) > writev(7, [{"7\0\4\0\25\1\300\5\v\0\300\5\0\0\0\0007\1\4\0\26\1\300\5\v\0\300\5\0\0\0\0"..., 9940}, {NULL, 0}, {"", 0}], 3) = 9940 > read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > poll([{fd=3, events=POLLIN}, {fd=11, events=POLLIN|POLLPRI}, {fd=13, events=POLLIN|POLLPRI}, {fd=14, events=POLLIN|POLLPRI}, {fd=15, events=POLLIN|POLLPRI}, {fd=16, events=POLLIN}, {fd=17, events=POLLIN}, {fd=18, events=POLLIN}, {fd=19, events=POLLIN}, {fd=7, events=POLLIN}], 10, 0) = 0 (Timeout) > read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) > fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 > mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb00bc75000 > write(1, "last\n", 5last > ) = 5 > rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7fb0124088f0}, {0x4d9820, [], SA_RESTORER, 0x7fb0124088f0}, 8) = 0 > --- SIGSEGV (Segmentation fault) @ 0 (0) --- > +++ killed by SIGSEGV +++ > Segmentation fault thanks a lot for any ideas or explanations From gelonida at gmail.com Wed Aug 11 19:14:26 2010 From: gelonida at gmail.com (Gelonida) Date: Thu, 12 Aug 2010 01:14:26 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: Jusy FYI: I made further tests and can crash the python script even if I delete the linesassigning strings to variables a to f On 08/12/2010 01:07 AM, Gelonida wrote: > Hi Guys, > I'm desperate. I'm having a real application, which fails rather often > when finishing it. I'm not sure, whether any serious problem could be > hidden behind it > > The script is a pyqt script, which segfaults most of the time on my > ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. > > Trying to create the smallest possible test case I ended up with > following script, which I named dodo.py and which i made executable with > chmod +x ./dodo.py > > #!/usr/bin/env python > from PyQt4.QtGui import > QDialog,QGridLayout,QLabel,QComboBox,QPushButton,QApplication > a = "one" > b = "unused" > c = "also unused" > d= "ans also unused" > e = "another var" > f = "something" > class MyForm(QDialog): > def __init__(self,parent=None,config=None,ini_info=None): > super(MyForm,self).__init__(parent=parent) > grid = QGridLayout() > quit_btn = QPushButton("Quit") > quit_btn.clicked.connect(self.quit) > grid.addWidget(quit_btn,0,0) > name = "a_name" > vals_box = QComboBox() > vals_box.addItem("one") > vals_box.addItem("two") > grid.addWidget(vals_box,0,1) > self.setLayout(grid) > def quit(self): > self.close() > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > print "last" > > > > In order to perform the test several times I typed on the command line: > > a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done > > As soon as the window shows up > I click twice (slowly ) on 'one' and then on quit. > > Sample output can be seen here: > gelonida at mypc:/my/directory$ a="" ; while [ "$a" = "" ] ; do ./dodo.py ; > read -t 1 a ; done > last > last > Segmentation fault > last > last > Segmentation fault > last > Segmentation fault > last > Segmentation fault > last > last > last > last > last > Segmentation fault > last > last > Segmentation fault > last > Segmentation fault > > > as you see the segfault happens rather often. > > Does anybody see something suspicious with my code? > Can anybody else reproduce this? > as soon as I remove more lines the error seems to disappear. > > What else could I do to debug this issue? > > thanks for help or other ideas > > > > If I run my script with strace ./dodo.py > I get following last lines for a run without error >> rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f65d6b3b8f0}, {0x4d9820, [], SA_RESTORER, 0x7f65d6b3b8f0}, 8) = 0 >> munmap(0x7f65c6344000, 622280) = 0 >> brk(0x2d71000) = 0x2d71000 >> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLIN|POLLOUT}]) >> read(7, "\22\0\233\6\2\0\300\5\2\0\300\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 384 >> writev(7, [{"\232\7\2\0\210\0\300\0056\0\2\0\207\0\300\5<\0\2\0\211\0\300\5\232\7\2\0s\0\300\5"..., 540}, {NULL, 0}, {"", 0}], 3) = 540 >> poll([{fd=7, events=POLLIN}], 1, -1) = 1 ([{fd=7, revents=POLLIN}]) >> read(7, "\34\0\241\6r\0\300\5\234\1\0\0\377\261\220\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 1472 >> read(7, 0x29fa704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}]) >> writev(7, [{"O\7\2\0\1\0\300\5<\0\2\0\0\0\300\5+\0\1\0", 20}, {NULL, 0}, {"", 0}], 3) = 20 >> poll([{fd=7, events=POLLIN}], 1, -1) = 1 ([{fd=7, revents=POLLIN}]) >> read(7, "\1\2\333\6\0\0\0\0\5\0\300\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 4096) = 32 >> read(7, 0x29fa704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> close(7) = 0 >> write(19, "\1\v\3\200\1\0\0\0\0\0\0\0\t\0\0\0", 16) = 16 >> close(19) = 0 >> open("/proc/stat", O_RDONLY|O_CLOEXEC) = 7 >> read(7, "cpu 59482 54 13580 7506040 4761"..., 8192) = 2439 >> close(7) = 0 >> writev(15, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12 >> close(15) = 0 >> writev(13, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12 >> close(13) = 0 >> close(12) = 0 >> close(11) = 0 >> unlink("/tmp/orbit-klausf/linc-1282-0-6094bc6991603") = 0 >> close(14) = 0 >> write(6, "@", 1) = 1 >> close(6) = 0 >> close(5) = 0 >> rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_NOCLDSTOP, 0x7f65d6b3b8f0}, {0x7f65d40a3860, [], SA_RESTORER|SA_NOCLDSTOP, 0x7f65d6b3b8f0}, 8) = 0 >> exit_group(0) > > > and following when an error occurs: >> writev(16, [{"<\10\2\0;\6\340\5F\6\5\0!\6\340\5\10\0\340\5\0\0\0\0U\0\33\0\232\7\2\0"..., 16380}, {NULL, 0}, {"", 0}], 3) = 16380 >> read(16, 0xbc49d4, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> poll([{fd=16, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=16, revents=POLLOUT}]) >> writev(16, [{"\232\10\t\0\3\6\340\5R\6\340\5C\6\340\5=\6\340\5\0\0\0\0\0\0\0\0\2\0\2\0"..., 4256}, {NULL, 0}, {"", 0}], 3) = 4256 >> poll([{fd=16, events=POLLIN}], 1, -1) = 1 ([{fd=16, revents=POLLIN}]) >> read(16, "\16\0\317\26s\0\340\5\0\0>\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 64 >> read(16, 0xbc49d4, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}]) >> writev(7, [{"7\0\4\0\25\1\300\5\v\0\300\5\0\0\0\0007\1\4\0\26\1\300\5\v\0\300\5\0\0\0\0"..., 9940}, {NULL, 0}, {"", 0}], 3) = 9940 >> read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> poll([{fd=3, events=POLLIN}, {fd=11, events=POLLIN|POLLPRI}, {fd=13, events=POLLIN|POLLPRI}, {fd=14, events=POLLIN|POLLPRI}, {fd=15, events=POLLIN|POLLPRI}, {fd=16, events=POLLIN}, {fd=17, events=POLLIN}, {fd=18, events=POLLIN}, {fd=19, events=POLLIN}, {fd=7, events=POLLIN}], 10, 0) = 0 (Timeout) >> read(7, 0xb44704, 4096) = -1 EAGAIN (Resource temporarily unavailable) >> fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 >> mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb00bc75000 >> write(1, "last\n", 5last >> ) = 5 >> rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7fb0124088f0}, {0x4d9820, [], SA_RESTORER, 0x7fb0124088f0}, 8) = 0 >> --- SIGSEGV (Segmentation fault) @ 0 (0) --- >> +++ killed by SIGSEGV +++ >> Segmentation fault > > > > > thanks a lot for any ideas or explanations > > > > > > From giacomo.boffi at polimi.it Wed Aug 11 19:24:34 2010 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Thu, 12 Aug 2010 01:24:34 +0200 Subject: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove? References: <4C5F992A.4040606@v.loewis.de> Message-ID: <86fwyk3f7x.fsf@aiuole.stru.polimi.it> "Martin v. Loewis" writes: > If you use the bdist_wininst, bdist_msi, or bdist_rpm distutils > commands, you get packages which support uninstallations very well. bdist_deb? -- Vorrei andare a lavorare in Sicilia, a max 15 km dal mare. Con chi devo parlare? Col capomafia distrettuale? Oppure bisogna sporcarsi le mani e fare la tessera di FI? -- Marvin, in IFQ From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 19:37:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 23:37:01 GMT Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4c63341c$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 > packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. Is this a trick question? I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) McNuggets. And that's not even close to the largest number that you can't buy. Unhelpfully yours, -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Aug 11 19:42:24 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2010 23:42:24 GMT Subject: urgent requirement at Hyderabad References: <5042f047-6b4e-430f-9370-0d91c50b7664@h40g2000pro.googlegroups.com> <4C62FC74.2040300@mrabarnett.plus.com> Message-ID: <4c633560$0$11101$c3e8da3@news.astraweb.com> On Wed, 11 Aug 2010 14:25:08 -0700, Emile van Sebille wrote: > On 8/11/2010 12:39 PM MRAB said... >> Stefan Behnel wrote: >>> In case anyone wondered: Hyderabad is likely referring to some place >>> in Asia: >>> >>> http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29 >>> >> And Berlin is likely some place in Europe: >> >> http://en.wikipedia.org/wiki/Berlin_(disambiguation) >> >> :-) > > And Paris is likely someplace in the US... > > http://en.wikipedia.org/wiki/Paris_%28disambiguation%29 No, I'm pretty sure it's a town in Australia filled with murderers... http://en.wikipedia.org/wiki/The_Cars_That_Ate_Paris -- Steven From chrischia82 at gmail.com Wed Aug 11 19:50:44 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Wed, 11 Aug 2010 16:50:44 -0700 (PDT) Subject: Python Tkinter Simple Qn Message-ID: Hi i have the following problem with Python Tkinter. I switch to switch the image background (which i used Tkinter.Label with image arg to display on the GUI). How can I do that? the callback function which i have created doesn't seem to work... some advice? below is my code: import Tkinter as tk from PIL import Image, ImageTk root = tk.Tk() # having problem with switching the image def callback(event): global root root.panel1.pack_forget() root.panel1.image = image2 root.panel1.pack() def app(): root.title('FIT 2022 Assignment 1') # pick an image file you have .bmp .jpg .gif. .png # load the file and covert it to a Tkinter image object imageFile = "c:\\test1.jpg" image1 = ImageTk.PhotoImage(Image.open(imageFile)) imageFile2 = "c:\\test2.jpg" image2 = ImageTk.PhotoImage(Image.open(imageFile2)) # get the image size w = image1.width() h = image1.height() # position coordinates of root 'upper left corner' x = 0 y = 0 # make the root window the size of the image root.geometry("%dx%d+%d+%d" % (w, h, x, y)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=image1) panel1.pack(side='top', fill='both', expand='yes') panel1.image = image1 panel1.bind("", callback) panel1.pack() root.mainloop() app() From ben+python at benfinney.id.au Wed Aug 11 19:52:29 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 12 Aug 2010 09:52:29 +1000 Subject: Microsoft lessening commitment to IronPython and IronRuby References: <7fr16650meigqgmj8rh0n3a66q9r4j4eva@4ax.com> <8ccf4kF38mU1@mid.individual.net> <4c610bd2$0$28655$c3e8da3@news.astraweb.com> <87aaouzkm1.fsf@benfinney.id.au> <87hbj1j6ra.fsf@notengoamigos.org> Message-ID: <87mxsswvuq.fsf@benfinney.id.au> Jason Earl writes: > Which is more of a promise than Microsoft has given to Python. I am > not arguing for Mono, as I am not a fan. But if you honestly think > that Python doesn't infringe on some of Microsoft's patents you are > crazy. It's quite true that anyone can be sued, at any time, for anything. And any program can, because of the crazy patent system in many countries, be infringing any (usually large) number of software idea patent claims, without the programmers having done anything unusual to cause that situation. Microsoft, or any other party for that matter, very well may have any number of software idea patents that could be interpreted to cover Python's code. The main difference in the case of Mono is that Microsoft has widely and repeatedly asserted that such patents do exist, their assertions seem quite plausible since they wrote the specifications on which Mono is implemented, its ?Community Promise? very carefully does *not* grant any kind of binding permission to implement or use software ideas from those patents, and it has consistently wielded other such patents aggressively and maintains the willingness to continue to do so. None of that is true for Python. Which is why people aren't saying Python is a patent trap, but rather that Mono is. -- \ ?Most people, I think, don't even know what a rootkit is, so | `\ why should they care about it?? ?Thomas Hesse, Sony BMG, 2006 | _o__) | Ben Finney From ben+python at benfinney.id.au Wed Aug 11 20:00:36 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 12 Aug 2010 10:00:36 +1000 Subject: most popular gui framework for python References: Message-ID: <87iq3gwvh7.fsf@benfinney.id.au> Back9 writes: > Does anyone know of what is the most popular gui framework for python > application? The Python standard library comes with one, Tkinter . Recently the Tix extension is also available in the standard library bringing much richer and better-looking widgets to Tk. -- \ ?Dvorak users of the world flgkd!? ?Kirsten Chevalier, | `\ rec.humor.oracle.d | _o__) | Ben Finney From python at mrabarnett.plus.com Wed Aug 11 20:15:31 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 01:15:31 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <4c63341c$0$11101$c3e8da3@news.astraweb.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c63341c$0$11101$c3e8da3@news.astraweb.com> Message-ID: <4C633D23.5070903@mrabarnett.plus.com> Steven D'Aprano wrote: > On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote: > >> level: beginner >> >> exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 >> packs, write an exhaustive search to find the largest number of >> McNuggets that cannot be bought in exact quantity. > > Is this a trick question? > > I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) > McNuggets. And that's not even close to the largest number that you can't > buy. > If you'd looked at the link then you would've seen that it's mathematically possible. But then I expect you have a life! :-) From ben+python at benfinney.id.au Wed Aug 11 20:18:31 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 12 Aug 2010 10:18:31 +1000 Subject: GUI automation tool (windows) References: <56a18e2b-4967-4a63-852e-1eb53bb6e561@j8g2000yqd.googlegroups.com> Message-ID: <87eie4wunc.fsf@benfinney.id.au> Alex Barna writes: > I know that this question has been asked for several times, [?] > So what happens to this field (Windows GUI automation [with Python]) ? Alex Barna writes: > It makes me doubt: is Python the correct language to do GUI > automation ? Your questions are definitely on-topic here. However, you might want to make use of the ?testing-in-python? forum where your questions are even *more* on-topic :-) -- \ ?We are stuck with technology when what we really want is just | `\ stuff that works.? ?Douglas Adams | _o__) | Ben Finney From nobody at nowhere.com Wed Aug 11 20:28:09 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 12 Aug 2010 01:28:09 +0100 Subject: How to capture all the environment variables from shell? References: <4C615D1B.7060204@syslang.net> Message-ID: On Wed, 11 Aug 2010 13:08:59 +1000, Cameron Simpson wrote: > The reason .bashrc gets overused for envars, aside from ignorance and > propagated bad habits, is that in a GUI desktop the setup sequence is > often a bit backwards. A conventional terminal/console login means you > get a login shell that sources your .{bash_}profile. And from there one > would start a GUI and all the .profile stuff has been run Once, as it > should be. But when the login itself is a GUI the various terminals get > started _before_ the .profile stuff gets sourced, because the terminal > is started by the desktop manager. Once common "fix" for this is to > make all new terminals run login shells. Ugh, but it does work. Er, not really. If you don't source your ~/.profile (etc) from e.g. ~/.xsession, GUI applications don't get to see the environment settings therein. The environment isn't just for shells. The reason why ~/.profile is only sourced by login shells is that it's supposed to be sourced exactly once, by the initial process of a session, i.e. the one from which all other programs descend. For a terminal-based login, "login" (or sshd or whatever) starts the shell as a login shell (with argv[0][0] == '-'), and the shell sets up the environment. For a desktop login, there is no login shell, so something else has to set up the environment. Simple enough; well, simple enough for anyone who understands Unix, processes, sessions, etc. But apparently too complex for the people who create desktop environments, who seem to think that the environment is somehow specific to shells. So you usually need to manually configure your session script (e.g. ~/.xsession for xdm) to set up the environment before the desktop environment gets a look-in. One caveat: if you set LD_LIBRARY_PATH, it will be unset when running a setuid or setgid program. This is sometimes the case for terminal emulators[1], in which case you need to have ~/.bashrc reinstate the setting. [1] Allocating a BSD-style pty requires root privilege, and writing utmp/wtmp entries requires write permission on the file. Modern systems have Unix98 ptys and a setgid helper program to manage the utmp/wtmp entries, so there shouldn't be any need for xterm etc to be setuid or setgid nowadays. From nobody at nowhere.com Wed Aug 11 20:42:51 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 12 Aug 2010 01:42:51 +0100 Subject: Line-by-line processing when stdin is not a tty References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: On Wed, 11 Aug 2010 10:32:41 +0000, Tim Harig wrote: >>> Usually you either >>> need an option on the upstream program to tell it to line >>> buffer explicitly >> >> once cat had an option -u doing exactly that but nowadays >> -u seems to be ignored >> >> http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html > > I have to wonder why cat knows or cares. The issue relates to the standard C library. By convention[1], stdin and stdout are line-buffered if the descriptor refers to a tty, and are block-buffered otherwise. stderr is always unbuffered. Any program which uses stdin and stdout without explicitly setting the buffering or using fflush() will exhibit this behaviour. [1] ANSI/ISO C is less specific; C99, 7.19.3p7: As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device. POSIX says essentially the same thing: From rNOSPAMon at flownet.com Wed Aug 11 21:21:43 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 18:21:43 -0700 Subject: How does Python get the value for sys.stdin.encoding? Message-ID: I thought it was hard-coded into the Python executable at compile time, but that is apparently not the case: [ron at mickey:~]$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys;print sys.stdin.encoding UTF-8 >>> ^D [ron at mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python None [ron at mickey:~]$ And indeed, trying to pipe unicode into Python doesn't work, even though it works fine when Python runs interactively. So how can I make this work? Thanks, rg From pavlovevidence at gmail.com Wed Aug 11 21:31:42 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 11 Aug 2010 18:31:42 -0700 (PDT) Subject: Deer Esurance Message-ID: <72ef108e-4c50-4076-b391-9c419059668c@h17g2000pri.googlegroups.com> If you're going to send me unsolicited email, the least you can do it include pics of Erin. Carl Banks From rNOSPAMon at flownet.com Wed Aug 11 21:49:26 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 18:49:26 -0700 Subject: Line-by-line processing when stdin is not a tty References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: In article , Nobody wrote: > On Wed, 11 Aug 2010 10:32:41 +0000, Tim Harig wrote: > > >>> Usually you either > >>> need an option on the upstream program to tell it to line > >>> buffer explicitly > >> > >> once cat had an option -u doing exactly that but nowadays > >> -u seems to be ignored > >> > >> http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html > > > > I have to wonder why cat knows or cares. > > The issue relates to the standard C library. By convention[1], stdin and > stdout are line-buffered if the descriptor refers to a tty, and are > block-buffered otherwise. stderr is always unbuffered. > > Any program which uses stdin and stdout without explicitly setting the > buffering or using fflush() will exhibit this behaviour. > > [1] ANSI/ISO C is less specific; C99, 7.19.3p7: > > As initially opened, the standard error stream is not fully > buffered; the standard input and standard output streams are > fully buffered if and only if the stream can be determined not > to refer to an interactive device. > > POSIX says essentially the same thing: > > This doesn't explain why "cat | cat" when run interactively outputs line-by-line (which it does). STDIN to the first cat is a TTY, but the second one isn't. For that matter, you can also do this: nc -l 1234 | cat and then telnet localhost 1234 and type at it, and it still works line-by-line. rg From bhanu.ramappa at gmail.com Wed Aug 11 22:15:42 2010 From: bhanu.ramappa at gmail.com (Bhanu Kumar) Date: Thu, 12 Aug 2010 07:45:42 +0530 Subject: python ide for ubuntu Message-ID: Hi All, Is there any good free python IDE available in Ubuntu? thanks, -Bhanu -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Wed Aug 11 22:24:49 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 11 Aug 2010 19:24:49 -0700 Subject: How does Python get the value for sys.stdin.encoding? In-Reply-To: References: Message-ID: On Wed, Aug 11, 2010 at 6:21 PM, RG wrote: > I thought it was hard-coded into the Python executable at compile time, > but that is apparently not the case: > > [ron at mickey:~]$ python > Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) > [GCC 4.2.1 (Apple Inc. build 5646)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys;print sys.stdin.encoding > UTF-8 >>>> ^D > [ron at mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python > None > [ron at mickey:~]$ > > And indeed, trying to pipe unicode into Python doesn't work, even though > it works fine when Python runs interactively. ?So how can I make this > work? > Sys.stdin and stdout are files, just like any other. There's nothing special about them at compile time. When the interpreter starts, it checks to see if they are ttys. If they are, then it tries to figure out the terminal's encoding based on the environment. The code for this is in pythonrun.c if you want to see exactly what it's doing. If stdout and stdin aren't ttys, then their encoding stays as None and the interpreter will use sys.getdefaultencoding() if you try printing Unicode strings. By the way, there is no such thing as piping Unicode into Python. Unicode is an abstract concept where each character maps to a codepoint. Pipes can only deal with bytes. You may be using one of the 5 encodings capable of holding the entire range of Unicode characters (UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE, and UTF-32 BE), but that's not the same thing as Unicode. You really have to watch your encodings when you pass data around between programs. There's no way to avoid it. From nyc61 at fibertel.com.ar Wed Aug 11 23:34:21 2010 From: nyc61 at fibertel.com.ar (apustilnik) Date: Wed, 11 Aug 2010 20:34:21 -0700 (PDT) Subject: globbal | creating networks Message-ID: Hi, i'd like to invite you to know this new way to keep in touch with friends, and meet new people! http://www.globbal.com.ar/login1.php Invite your friends to join, and start creating your own globbal networks! Are you ready to live a new experience? Are you ready to live globbal! Sign up now! From cs at zip.com.au Thu Aug 12 00:16:37 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 12 Aug 2010 14:16:37 +1000 Subject: How to capture all the environment variables from shell? In-Reply-To: References: Message-ID: <20100812041637.GA14479@cskk.homeip.net> On 12Aug2010 01:28, Nobody wrote: | On Wed, 11 Aug 2010 13:08:59 +1000, Cameron Simpson wrote: | > The reason .bashrc gets overused for envars, aside from ignorance and | > propagated bad habits, is that in a GUI desktop the setup sequence is | > often a bit backwards. A conventional terminal/console login means you | > get a login shell that sources your .{bash_}profile. And from there one | > would start a GUI and all the .profile stuff has been run Once, as it | > should be. But when the login itself is a GUI the various terminals get | > started _before_ the .profile stuff gets sourced, because the terminal | > is started by the desktop manager. Once common "fix" for this is to | > make all new terminals run login shells. Ugh, but it does work. | | Er, not really. If you don't source your ~/.profile (etc) from e.g. | ~/.xsession, GUI applications don't get to see the environment settings | therein. The environment isn't just for shells. I think we're in violent agreement here. I arrange to do exactly that in my own desktop setups. However, the ones that ship with distros generally don't, possibly because a shell-aborting error in the .profile (or unwanted interaction etc) will abort the GUI login/desktop-setup. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ The Puritan hated bear-baiting, not because it gave pain to the bear, but because it gave pleasure to the spectator. - Macaulay, History of England From gagsl-py2 at yahoo.com.ar Thu Aug 12 01:20:44 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Aug 2010 02:20:44 -0300 Subject: favicon.ico problem References: <9F21F146-A43A-4108-962B-4DFA14E430E4@gmail.com> Message-ID: En Tue, 10 Aug 2010 01:32:49 -0300, Navkirat Singh escribi?: > I am having this strange problem. I have programmed a very basic > multiprocessing webserver using low level sockets. Each time the server > receives a request it spawns a new process to handle the request. Now > when through a web browser I type http://localhost:8001/ it > automatically creates two processes: One process to server the '/' path > and another one to serve the '/favicon.ico' path. I have not programmed > it to serve the latter. Infact I dont even know where that name > '/favicon.ico' comes from. Any insight into this weird behavior would be > greatly appreciated. It't the browser attempting to get an icon for the page. See http://en.wikipedia.org/wiki/Favicon -- Gabriel Genellina From nagle at animats.com Thu Aug 12 01:34:36 2010 From: nagle at animats.com (John Nagle) Date: Wed, 11 Aug 2010 22:34:36 -0700 Subject: urllib2 does not implement "with" Python 2.6 Message-ID: <4c6387f8$0$1587$742ec2ed@news.sonic.net> Somewhat to my surprise, in Python 2.6, with urllib2.urlopen(url) as fh : doesn't work. It fails with "AttributeError: addinfourl instance has no attribute '__exit__'". I thought that all the file-like objects supported "with" in 2.6. No? John Nagle From rNOSPAMon at flownet.com Thu Aug 12 01:50:43 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 22:50:43 -0700 Subject: How does Python get the value for sys.stdin.encoding? References: Message-ID: In article , Benjamin Kaplan wrote: > On Wed, Aug 11, 2010 at 6:21 PM, RG wrote: > > I thought it was hard-coded into the Python executable at compile time, > > but that is apparently not the case: > > > > [ron at mickey:~]$ python > > Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) > > [GCC 4.2.1 (Apple Inc. build 5646)] on darwin > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import sys;print sys.stdin.encoding > > UTF-8 > >>>> ^D > > [ron at mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python > > None > > [ron at mickey:~]$ > > > > And indeed, trying to pipe unicode into Python doesn't work, even though > > it works fine when Python runs interactively. ?So how can I make this > > work? > > > > Sys.stdin and stdout are files, just like any other. There's nothing > special about them at compile time. When the interpreter starts, it > checks to see if they are ttys. If they are, then it tries to figure > out the terminal's encoding based on the environment. The code for > this is in pythonrun.c if you want to see exactly what it's doing. Thanks. Looks like the magic incantation is: export PYTHONIOENCODING='utf-8' > By the way, there is no such thing as piping Unicode into Python. Yeah, I know. I should have said "piping UTF-8 encoded unicode" or something like that. > You really have to watch your encodings > when you pass data around between programs. There's no way to avoid > it. Yeah, I keep re-learning that lesson again and again. rg From no.email at nospam.invalid Thu Aug 12 02:14:19 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 11 Aug 2010 23:14:19 -0700 Subject: urllib2 does not implement "with" Python 2.6 References: <4c6387f8$0$1587$742ec2ed@news.sonic.net> Message-ID: <7xr5i49x38.fsf@ruckus.brouhaha.com> John Nagle writes: > "AttributeError: addinfourl instance has no attribute '__exit__'". > > I thought that all the file-like objects supported "with" in 2.6. > No? I guess not. Use contextlib.closing. From zak.mc.kraken at libero.it Thu Aug 12 02:49:02 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Thu, 12 Aug 2010 08:49:02 +0200 Subject: Beyond the moratorium Message-ID: Hi all. I know, maybe I'm just lazily speculating, but I'm curious about what's next, in python, when GvR will stop the moratorium and will let changes in the language. I don't know what to expect... some syntax sugar about concurrent programming? static types? an erlang-style "bang" (!) process message passing? -- By ZeD From rNOSPAMon at flownet.com Thu Aug 12 02:50:13 2010 From: rNOSPAMon at flownet.com (RG) Date: Wed, 11 Aug 2010 23:50:13 -0700 Subject: Why can't I set sys.ps1 to a unicode string? Message-ID: More precisely, why does sys.ps1 not appear if I set it to a unicode string? This problem is hard for me to describe here because my newsreader is not properly unicode enabled, but here's the gist of it: Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> First, let's make sure our encodings are set properly: >>> import sys >>> sys.stdin.encoding 'utf-8' >>> sys.stdout.encoding 'utf-8' Looks good. Now, let's make two unicode strings, identical except for one character: >>> s1 = u'%%% %%% ' >>> s2 = u'%%% ' + u'\u262f' + '%%% ' >>> print s1 %%% %%% >>> print s2 %%% /&%%% If this were a properly unicode-enabled newsreader you would see a yin-yang symbol in the middle of s2. Now the weird part: >>> sys.ps1 = s1 %%% %%% sys.ps1 = s2 # This is as expected print s1 # But this isn't. There's no prompt! %%% %%% # Everything still works print s2 %%% /&%%% sys.ps1 = s1 # If we reset sys.ps1 we get our prompt back %%% %%% sys.ps1 = '>>> ' >>> sys.ps1 = u'>>> ' >>> So... why does having a non-ascii character in sys.ps1 make the prompt vanish? (If you're wondering why I care, I want to connect to an interactive python interpreter from another program, and I want a non-ascii delimiter to unambiguously mark the end of the interpreter's output on every interaction.) Thanks, rg From werner at thieprojects.ch Thu Aug 12 02:53:18 2010 From: werner at thieprojects.ch (Werner Thie) Date: Thu, 12 Aug 2010 08:53:18 +0200 Subject: python ide for ubuntu In-Reply-To: References: Message-ID: <4C639A5E.7090107@thieprojects.ch> Eclipse with pydev (great debugging) does the trick nicely, free of charge and throws in some other goodies (JScript/HTML/XML editing) too. I use the EE for Java developer version http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliosr Install pydev from Menu Help/Software Updates After ten years of Python coding and suffering thru most of the commercial products like VisualPython, Komodo, Wings, asf I heartily recommend Eclipse nowadays. If you want to stay as pythonesque as possible you could go with SPE which uses wxPython and integrates with Blender, although this project seems to be stalled. Werner On 12.08.2010 04:15, Bhanu Kumar wrote: > Hi All, > > Is there any good free python IDE available in Ubuntu? > > > thanks, > -Bhanu > -------------- next part -------------- A non-text attachment was scrubbed... Name: werner.vcf Type: text/x-vcard Size: 297 bytes Desc: not available URL: From eckhardt at satorlaser.com Thu Aug 12 03:01:38 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 12 Aug 2010 09:01:38 +0200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> <4C61E9A1.5090800@v.loewis.de> <88t9j7-ri5.ln1@satorlaser.homedns.org> <44d30ac7-931e-4eb0-9aed-f664c872d438@l20g2000yqm.googlegroups.com> Message-ID: sturlamolden wrote: > On 11 Aug, 08:40, Ulrich Eckhardt wrote: > Header (definition) and source (implementation) is not the same. I'm aware of this and that's not the thing I was talking about. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From stefan_ml at behnel.de Thu Aug 12 03:17:04 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 12 Aug 2010 09:17:04 +0200 Subject: Beyond the moratorium In-Reply-To: References: Message-ID: Vito 'ZeD' De Tullio, 12.08.2010 08:49: > I know, maybe I'm just lazily speculating, but I'm curious about what's > next, in python, when GvR will stop the moratorium and will let changes in > the language. > > I don't know what to expect... some syntax sugar about concurrent > programming? static types? an erlang-style "bang" (!) process message > passing? One of the reasons the moratorium was established was to reduce the time spent in overly speculative discussions about various features that will most likely not end up in the language anyway. Also note that your examples above span both the language and the stdlib, which are put under different constraints by the moratorium. Stefan From ben+python at benfinney.id.au Thu Aug 12 03:22:00 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 12 Aug 2010 17:22:00 +1000 Subject: Beyond the moratorium References: Message-ID: <871va4wb1j.fsf@benfinney.id.au> Vito 'ZeD' De Tullio writes: > I know, maybe I'm just lazily speculating, but I'm curious about > what's next, in python, when GvR will stop the moratorium and will let > changes in the language. Subscribe to the ?python-ideas? forum for the latest pie-in-the-sky discussions about how to change Python, including the occasional contribution from GvR on ideas that take his interest. -- \ ?In the long run, the utility of all non-Free software | `\ approaches zero. All non-Free software is a dead end.? ?Mark | _o__) Pilgrim, 2006 | Ben Finney From martin at v.loewis.de Thu Aug 12 03:26:15 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Thu, 12 Aug 2010 09:26:15 +0200 Subject: Why can't I set sys.ps1 to a unicode string? In-Reply-To: References: Message-ID: > So... why does having a non-ascii character in sys.ps1 make the prompt > vanish? I can't pinpoint it to a specific line of code. Most likely, it tries to encode the prompt as ASCII before writing it to stdout. That fails, and it silently ignores the error. FWIW, this is fixed in Python 3. Regards, Martin From news1234 at free.fr Thu Aug 12 03:39:32 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 09:39:32 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <4c63341c$0$11101$c3e8da3@news.astraweb.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c63341c$0$11101$c3e8da3@news.astraweb.com> Message-ID: <4C63A534.2040404@free.fr> Hi Steven, On 08/12/2010 01:37 AM, Steven D'Aprano wrote: > On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote: > >> level: beginner >> >> exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 >> packs, write an exhaustive search to find the largest number of >> McNuggets that cannot be bought in exact quantity. > > Is this a trick question? > > I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) > McNuggets. And that's not even close to the largest number that you can't > buy. You CAN buy that many Nuggets. You just need the money and of course you have to wait a little until they are ready. From ldo at geek-central.gen.new_zealand Thu Aug 12 03:39:41 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 12 Aug 2010 19:39:41 +1200 Subject: how to save a whole web page with something block References: <46c3cfc7-9339-4cd0-9ef9-4358730b706f@o7g2000prg.googlegroups.com> Message-ID: In message , Daniel Fetchinson wrote: > A web server may present different output depending on the client > used. It may also require execution of some JavaScript to insert HTML content. > So you might want to make urllib appear as a browser by sending the > appropriate headers. If the above is the case, then this won?t be enough. From debatem1 at gmail.com Thu Aug 12 04:03:10 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 12 Aug 2010 01:03:10 -0700 Subject: python ide for ubuntu In-Reply-To: <4C639A5E.7090107@thieprojects.ch> References: <4C639A5E.7090107@thieprojects.ch> Message-ID: On Wed, Aug 11, 2010 at 11:53 PM, Werner Thie wrote: > Eclipse with pydev (great debugging) does the trick nicely, free of charge > and throws in some other goodies (JScript/HTML/XML editing) too. > > I use the EE for Java developer version > > http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliosr > > Install pydev from Menu Help/Software Updates > > After ten years of Python coding and suffering thru most of the commercial > products like VisualPython, Komodo, Wings, asf I heartily recommend Eclipse > nowadays. > > If you want to stay as pythonesque as possible you could go with SPE which > uses wxPython and integrates with Blender, although this project seems to be > stalled. > > Werner Or you could use a text editor and a terminal and spare yourself the agony of dealing with 600MB of Java of questionable quality ;). And don't even get me started about all the unsigned OSGi bundles that float around in there. Geremy Condra From news1234 at free.fr Thu Aug 12 04:24:23 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 10:24:23 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4c63afb7$0$431$426a34cc@news.free.fr> On 08/11/2010 10:14 PM, Baba wrote: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf > > please help me write this code > > i believe it's something along the lines of this: > > c=0 > sol=[] > for n in range (0,10): > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print sol > If you're interested in more, than just finishing the exercise, then you should post your solution even if you have it already and read about all the tips how to make it faster or shorter or more readable From eric.brunel at pragmadev.com Thu Aug 12 04:42:51 2010 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 12 Aug 2010 10:42:51 +0200 Subject: Python Tkinter Simple Qn References: Message-ID: In article , ChrisChia wrote: > Hi i have the following problem with Python Tkinter. > I switch to switch the image background (which i used Tkinter.Label > with image arg to display on the GUI). > > How can I do that? the callback function which i have created doesn't > seem to work... It is usually way better to post the actual error than just saying "doesn't seem to work"? Here your problem is quite clear, but in most circumstances, it would be quite difficult to figure out what's happening. > some advice? > > below is my code: > > > import Tkinter as tk > from PIL import Image, ImageTk > > root = tk.Tk() > > # having problem with switching the image > def callback(event): > global root > root.panel1.pack_forget() > root.panel1.image = image2 The variable image2 is not known in this context, so no wonder the callback doesn't work. Let me guess: it says something like "NameError: name 'image2' is not defined"? > root.panel1.pack() > > > def app(): > > root.title('FIT 2022 Assignment 1') > > # pick an image file you have .bmp .jpg .gif. .png > # load the file and covert it to a Tkinter image object > imageFile = "c:\\test1.jpg" > image1 = ImageTk.PhotoImage(Image.open(imageFile)) > imageFile2 = "c:\\test2.jpg" > image2 = ImageTk.PhotoImage(Image.open(imageFile2)) Here, you create image2 as a local variable in function app. So the variable name will not be known outside of app. If you want it to be global, you have to add a line: global image2 at the beginning of your app function. Then it should work correctly. By the way, I usually find it better to organize a GUI into classes rather than using functions. This way, you could store the images in object attributes and define your callback as a method, and not as a function. > # get the image size > w = image1.width() > h = image1.height() > > > # position coordinates of root 'upper left corner' > x = 0 > y = 0 > > > # make the root window the size of the image > root.geometry("%dx%d+%d+%d" % (w, h, x, y)) > > > # root has no image argument, so use a label as a panel > panel1 = tk.Label(root, image=image1) > panel1.pack(side='top', fill='both', expand='yes') > panel1.image = image1 > panel1.bind("", callback) > > > panel1.pack() > root.mainloop() > > > app() HTH - Eric - From meitham at meitham.com Thu Aug 12 04:42:55 2010 From: meitham at meitham.com (meitham) Date: Thu, 12 Aug 2010 01:42:55 -0700 (PDT) Subject: most popular gui framework for python References: Message-ID: <981f0dbe-73b6-470f-ab87-869f387fc922@s9g2000yqd.googlegroups.com> On Aug 11, 8:31?pm, Back9 wrote: > Hi, > > Does anyone know of what is the most popular gui framework for python > application? > > TIA I used to prefer using GTK mainly because it is available on most platforms. I have realised the majority of the enterprises prefer to use browsers even for local applications. So a combination of django/ html/css/jquery/ajax now gives me the best gui I could get. This approach also forces me to separate logic from presentation, and the gui will be truly platform independent which could run on any device with a browser. Meitham From ph4nut at gmail.com Thu Aug 12 04:59:26 2010 From: ph4nut at gmail.com (ph4nut) Date: Thu, 12 Aug 2010 01:59:26 -0700 (PDT) Subject: Does anyone use Quixote for web developing? Message-ID: Hi all,I am learning Quixote a few days ago,,,and i have no idea about whether there is any Google Group talking about Quixote,so i post this post to check that is Quixote been talking in this group before or can i ask question about Quixote here! From jeanmichel at sequans.com Thu Aug 12 05:23:41 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 12 Aug 2010 11:23:41 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4C63BD9D.30602@sequans.com> Baba wrote: > level: beginner > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf > > please help me write this code > > i believe it's something along the lines of this: > > c=0 > sol=[] > for n in range (0,10): > for a in range (0,10): > for b in range (0,10): > for c in range (0,10): > sol=6*a+9*b+20*c > if sol!=n: > c+=1 > if c==6: > print sol > > > for mcNugget in range(0,10): sendTo(trashbin) You're welcome :p JM From no.email at nospam.invalid Thu Aug 12 05:33:25 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Thu, 12 Aug 2010 02:33:25 -0700 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <7x1va4tbtm.fsf@ruckus.brouhaha.com> Baba writes: > exercise: given that packs of McNuggets can only be bought in 6, 9 or > 20 packs, write an exhaustive search to find the largest number of > McNuggets that cannot be bought in exact quantity. Is that a homework problem? Hint: first convince yourself that a largest number actually exists. From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 12 05:40:59 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 12 Aug 2010 11:40:59 +0200 Subject: Does anyone use Quixote for web developing? In-Reply-To: References: Message-ID: <4c63c198$0$24088$426a74cc@news.free.fr> ph4nut a ?crit : > Hi all,I am learning Quixote a few days ago,,,and i have no idea about > whether there is any Google Group talking about Quixote,so i post this > post to check that is Quixote been talking in this group before or can > i ask question about Quixote here! From the project's home page: """ There is a mailing list for discussing Quixote and you should look there for information about obtaining the current release: * quixote-users """ From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 12 05:42:09 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 12 Aug 2010 11:42:09 +0200 Subject: python ide for ubuntu In-Reply-To: References: <4C639A5E.7090107@thieprojects.ch> Message-ID: <4c63c1df$0$24088$426a74cc@news.free.fr> geremy condra a ?crit : (about eclipse+pydev) > Or you could use a text editor and a terminal and spare yourself the > agony of dealing with 600MB of Java of questionable quality ;). +1 QOTW From xrgtn at yandex.ru Thu Aug 12 06:30:03 2010 From: xrgtn at yandex.ru (Alexander Gattin) Date: Thu, 12 Aug 2010 13:30:03 +0300 Subject: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT) In-Reply-To: References: Message-ID: <20100812103003.GA24917@xrgtn-q40> Hello, On Wed, Aug 11, 2010 at 02:29:24PM -0700, tormod wrote: > I've tried countless times to build & install cx_Oracle on Python > 3.1.2, and failed every time, so I'd like to ask someone for help. ... > I've opened the cx_Oracle.pyd with Dependency Walker (http:// > www.dependencywalker.com/) and DW reports it can't find: OCI.DLL, > PYTHON31.DLL, MSVCR90.DLL (why?) Does Windows have anything like LD_LIBRARY_PATH/SHLIB_PATH? > Appreciate any help, even wildshots and 2 cents are welcome - I'll try > everything. please try starting python -d (--debug IIRC) and then loading cx_Oracle manually (>>> import cx_Oracle). Usually it succeeds (sic!) but outputs a lot of symbol errors. // Problem with Oracle libs -- With best regards, xrgtn (+380501102966/+380636177128/xrgtn at jabber.kiev.ua) From downaold at gmail.com Thu Aug 12 06:44:24 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 12 Aug 2010 12:44:24 +0200 Subject: python ide for ubuntu In-Reply-To: References: Message-ID: <30CC6202-509E-4D09-9921-79A7B61C9351@gmail.com> Hi Bhanu, On Aug 12, 2010, at 4:15 AM, Bhanu Kumar wrote: > Hi All, > > Is there any good free python IDE available in Ubuntu? See a similar discussion at django-users mailing list: http://groups.google.com/group/django-users/browse_thread/thread/562189578285211 Cheers, Roald From downaold at gmail.com Thu Aug 12 07:04:58 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 12 Aug 2010 13:04:58 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <7x1va4tbtm.fsf@ruckus.brouhaha.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: On Aug 12, 2010, at 11:33 AM, Paul Rubin wrote: > Baba writes: >> exercise: given that packs of McNuggets can only be bought in 6, 9 or >> 20 packs, write an exhaustive search to find the largest number of >> McNuggets that cannot be bought in exact quantity. > > Is that a homework problem? Hint: first convince yourself that a > largest number actually exists. Good point. There is actually an upper bound. Let's take 6 packs of 20, that's 120 nuggets. Now 121 nuggets can be reached by substituting 1 pack of 20 with 2 packs of 6 and 1 pack of 9. 122 = 4*20 + 2*(2*6+9) 123 = 3*20 + 3*(2*6+9) ... 126 = 6*20 + 6 127 = 121 + 6 = 5*20 + (2*6 + 9) + 6 ... etcetera. Now you have to find the largest number below 120, which you can easily do with brute force (untested): can_be_bought = [False for i in range(120)] for twenties in range(6): for nines in range(14): for sixes in range(20): can_be_bought[twenties*20+nines*9+sixes*6] = True for i in reverse(range(120)): if not can_be_bought[i]: return i Cheers, Roald From msarro at gmail.com Thu Aug 12 07:41:47 2010 From: msarro at gmail.com (Matty Sarro) Date: Thu, 12 Aug 2010 07:41:47 -0400 Subject: Programming Puzzles? What's your favorite puzzle? Message-ID: Hey All! Hope your thursday is treating you well. I'm looking for suggestions on books of programming/engineering puzzles that range from beginners to advanced and even expert level problems. I know they exist; we had them back in college for practicing before the ACM programming competitions. However I can't seem to really find any books out there that look like they're what I'm seeking. Basically I haven't programmed a lot since I was in college, and that was about 9 years ago. I'm expected to do a bit more programming at my current job and I figure the best way to get back into things is to have some practical things to solve, and maybe have a bit of fun in the process. Anyone have any suggestions? Also, if you have any favorite puzzles/simple learning programs to suggest, please, share with the class :) -Matty -------------- next part -------------- An HTML attachment was scrubbed... URL: From drodrig at magicbrain.com Thu Aug 12 07:49:15 2010 From: drodrig at magicbrain.com (drodrig) Date: Thu, 12 Aug 2010 04:49:15 -0700 (PDT) Subject: Copying a file with a question mark in it's name in Windows Message-ID: A python script I use to backup files on a Windows 2003 server occasionally fails to retrieve the size of a file with a question mark in the name. The exception I get is "OSError #123 The filename, directory name, or volume label syntax is incorrect". I realize that technically a question mark in the name of a file on Windows is illegal, but nevertheless these files exist on the file system. It seems that they are created by Office 2007 Word, for the most part. The line that fails is: os.path.getsize(source) Where source is the full path to the file with the question mark in it's name. Any idea how to retrieve the file's size? Also, I imagine that after I overcome this hurdle, I'll need help finding a way to copy the file (assuming copy2() doesn't work). I've tried escaping the question mark ("\\?"). Same result. Although I could use the Windows "dir" command, parsing the results to find the size of the file then use the Windows "copy" command, I'd rather stay away from this type of solution. Any help is appreciated! From iktomus.heyokis at gmail.com Thu Aug 12 08:05:55 2010 From: iktomus.heyokis at gmail.com (=?TIS-620?B?4KLp0rnNuQ==?=) Date: Thu, 12 Aug 2010 05:05:55 -0700 (PDT) Subject: Long rant about Python in Education Message-ID: This is in response to one of the pyWiki pages: PythonAsAFirstLanguage. If there's a better place I could have posted this, please tell me about it. I will be posting this elsewhere over the next few ideas, because I feel it's my duty to spread this idea. It's not grandiose, just Quixotic. Someone wrote, "We could really use some success stories of Python in education." Right... Python was developed to be easily learnt by children. So that's not a declarative sentence. It's an implied question. Here's my answer. It took a while to write, but it's quite simple. Problem: Python won't be easily learnt by my stepchild, I know for a fact. She loves her laptop, but she calls me a nerd whenever Linux gets brought up at the dinner table. I'm not bitter about this. But I want you guys, especially the ones who are planning on having kids, as well as the ones who already have them, to understand what steps you can take to teach your kids Python. I've basically outlined an 'algorithm' for it here. If you don't have time to read a long, eccentric, rambling post, just 'read the lead' Solution to problem: 1) Only let them see you using the terminal. Don't even use Windows in the house. 2) Their first laptop should be installed with a nice, well-supported Linux distro. 3) Brush up on your Linux skills yourself. The bottom line: teach them to do beautiful things with the terminal. I believe Linux should be mastered by everyone who uses it. And I believe Linux (not Python) is the way to teach children to program. Especially intuitive ones. (In the Myers-Briggs scale.) Why is this important? Because the part of the world that most hates America right now is full of intuitives. And if we want not to be blown off the face of the earth in a few decades, we have to empower them in a very new way: we have to teach them to enjoy programming, enjoy computers, and develop their minds in a way that doesn't involve becoming 'Imams' who are essentially the learned mafia bosses of terrorism. I have mastered Classical Arabic. I once met a Pakistani and told him I had done so. We were in the middle of a theological debate. In the middle of his Islamic theology was, laughably enough, some Christian theology that I have no idea how it got there. Orthodox Islam has no concept of original sin, but he believed in it. That was a real surprise for me. Anyway, despite the fact that he'd only read translations of the Qur'an, whereas I'd read the original, he was not impressed. He said that Pakistan had many 'schools' for studying Arabic, and that there was an incredible number of 'students' there. These people aren't dumb, guys. They're just learning the wrong stuff. We can't change the schools, but we don't need to. Don't forget that Arabs and Central Asians both had education systems based on Islam before western education came with the French and British. The attempt to re-establish the primacy of that system of education is what Islamic terrorism is all about. It was based on memorizing/hearing the Qur'an, yes, then learning the meanings of the words by reading it. Actually, for an intuitive person, this is an excellent way to learn any language (find a text, find a recording, memorize the recording, intuit the meanings) and I have used it to learn Spanish, Chinese, and Arabic. How does this apply to Linux/Python? Having access to the /usr/bin directory means having access to a whole load of algorithms without even having to write them yourself! Hasn't anyone but me thought of how great that would be for kids? So, when you guys ban windows in the home and start breastfeeding your kids terminals (I was using a DOS terminal correctly at age 9, shouldn't be hard to teach them whippersnappers to use a -nix shell), then you can bring in Python. But first, start writing Python to put in their /usr/bin directories, so that they get comfortable with the idea that Python can be both scripted and compiled, and that programs are simply algorithms that get called using arguments. Then teach them to write Python stuff they can put into /usr/bin Important: ban windows entirely in the home. I cannot stress this enough. My stepdaughter is as good with computers as I was at her age, and I've seen her play around with the settings on her laptop when she's bored. Obviously, she wants to explore the machine sometimes, but windows has trained her mind not to look for geeky solutions. Windows has trained her to think of a computer as a magic machine, and not as an algorithm machine. Will the real Bill Gates please stand up. When I was her 10, my stepfather banned me from playing DOOM unless I could get it to work using the DOS command line. I did not manage to replace the .dll file he had deleted, but I did learn lots. Will the real Bill Gates please stand up, please stand up, please stand up... So, in conclusion: DO people of the free-thinking world want a Mozart Python genius to show off to the schools in Europe, Japan, Saudi (most importantly, because it's a very rich country), the US, and all the other richer countries... Do you? I do. I'll see that kid as some sort of divine messiah, the way this world is heading now. The minute we can get 10-year-old Python geniuses in countries like Pakistan, Algeria, and occupied Palestine, they will be superstars, inspire the upper classes in their respective countries to teach their kids programming, and our earth will no longer have anything to fear from Islamic terrorism (using Linux, which is the John the Baptist of this whole equation), because sooner or later, the terrorists who are just bored teenagers will start writing good programs. Also, my travels around the world have convinced me that Arabs will someday be be the best programmers on the earth. My stepdaughter has an Arab background, and her case convinces me further. She could be a great computer programmer, if windows hadn't spoiled her! Windows has spoiled them all, though, sadly... They (Arabs) have the typology for it -- far more intuitives than we white people do. But the way "globalization" has worked, turning the whole world into an empire run by rich countries, of course there's a revolt stirring in the poorer ones. It was bound to happen someday. The fat cats who run these globalizing corporations mostly read the Bible everyday and think the apocalypse is coming soon. It's their prophecy guys, their book. Not ours. The Linux shell is our Qur'an. Python is our New Testament. Will somebody please write the Torah already? Our new style of imperialism has also taught the Arabs and Central Asians that, in order to succeed in life, you have to be 'sensate' (Jung/Myers-Briggs again here. Please read up if you don't know what I'm talking about. The sensation function is what lets us do math, learn logic, sketch, play music, etc.) Want to cause an explosion of world peace? Want Python to change the world? I know this sounds grandiose guys, but I've just given you guys the answer. I've traveled the world including the parts of the Middle East where Bin Laden's doing most of his dirty work. I've done quite a bit of everything, and this is the answer: teach Python. But don't teach it first. Ban them from windows first. Important: When they want something done, make them figure out how to do it in the terminal. They will try, if they are good, because I tried. And unfortunately, since it was DOS, I did not have a whole slew of algorithms in the / usr/bin directory waiting to be learnt and studied. Also, I did not have a command history at my disposal. That's unfortunate, but it doesn't stop me from trying to master Linux now. A child who's mastered Linux at age 9 or 10 will be the first kid to get on international TV for learning good Python. . . He will be our era's Mozart... But you can't teach them Python until they're familiar with the workings of a computer. Don't even try. It's like trying to teach algrebra without geometry first -- the one was invented first, so it needs to be learned first. The fact that we now teach algebra first in some schools just makes people hate math. Ditto with teaching kids C/C++ who've never even touched linux. It's a scary education system... And my 2 cents is that the proliferation of western education creates hooligans, mafiosos, Imams who support terrorism, and other classes of thugs in societies where people are intuitive, like Pakistan or Egypt... Let's face it, guys. Our world only works in the favor of the few, the proud, the sensate. Thankfully, computers taught me everything I've ever learned. That's why I regard them in high esteem. My laptop is more than an object -- it is almost divine. What powers it? Electricity, which is almost divine. And what is greater than electricity? Ahh, the electromagnetic spectrum... the mystery of nature... Signing off for now to fight more terrorists, But not before a Coffee Break, Alec From mail at timgolden.me.uk Thu Aug 12 08:11:33 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 12 Aug 2010 13:11:33 +0100 Subject: Copying a file with a question mark in it's name in Windows In-Reply-To: References: Message-ID: <4C63E4F5.7050706@timgolden.me.uk> On 12/08/2010 12:49, drodrig wrote: > A python script I use to backup files on a Windows 2003 server > occasionally fails to retrieve the size of a file with a question mark > in the name. The exception I get is "OSError #123 The filename, > directory name, or volume label syntax is incorrect". I realize that > technically a question mark in the name of a file on Windows is > illegal, but nevertheless these files exist on the file system. It > seems that they are created by Office 2007 Word, for the most part. Could you show us the script you're using? I'm not aware of any way to get a question mark into a file name; even using the file namespace prefix \\?\ doesn't allow it as far as I can tell. Where are you seeing the question mark? Is it possible it's a placeholder for an unprintable character rather than an actual question mark? TJG From johnroth1 at gmail.com Thu Aug 12 08:20:42 2010 From: johnroth1 at gmail.com (John Roth) Date: Thu, 12 Aug 2010 05:20:42 -0700 (PDT) Subject: Beyond the moratorium References: <871va4wb1j.fsf@benfinney.id.au> Message-ID: <145c25ca-54fc-473b-941c-babf21d0b588@l25g2000prn.googlegroups.com> On Aug 12, 1:22?am, Ben Finney wrote: > Vito 'ZeD' De Tullio writes: > > > I know, maybe I'm just lazily speculating, but I'm curious about > > what's next, in python, when GvR will stop the moratorium and will let > > changes in the language. > > Subscribe to the ?python-ideas? forum for the latest pie-in-the-sky > discussions about how to change Python, including the occasional > contribution from GvR on ideas that take his interest. > > -- > ?\ ? ? ? ? ? ? ??In the long run, the utility of all non-Free software | > ? `\ ? ? ?approaches zero. All non-Free software is a dead end.? ?Mark | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Pilgrim, 2006 | > Ben Finney You might also want to look at PEP 3152, which was just posted. John Roth From sajuptpm at gmail.com Thu Aug 12 08:26:57 2010 From: sajuptpm at gmail.com (sajuptpm) Date: Thu, 12 Aug 2010 05:26:57 -0700 (PDT) Subject: Secure LDAP Configuration Message-ID: <81a712a4-3d1c-45f2-9fbf-deecd5e80068@g21g2000prn.googlegroups.com> I want to create an LDAP database for my company with following settings. Only the ldap user belongs to my company can search and view ldap entries I want to protect ldap user belongs to my company One ldap user can't search and view others details Only allow ldap users to authenticate with there username and password I need an LDAP administrator for my company.Only he can add and delete users from LDAP. For these how configure /etc/openldap/slapd.conf I need to add group and role infornations to ldap directory.Can i use existing attributes like 'ou' for these or need to add new attribute. Here is the LDAP entry i configured. dn: uid=user6,dc=localhost,dc=localdomain objectclass: top objectclass: person objectclass: inetorgperson ou: [('userGroup111','userr'),('adminGroup','admin'), ('Server111','operator')] cn: user6 sn: My company uid: user6 userPassword: 123456 ou: [('userGroup111','userr'),('adminGroup','admin'), ('Server111','operator')] <-----newly added group and role pair.Is it correct way???? Have any other way to do it. From iamforufriends at gmail.com Thu Aug 12 08:51:22 2010 From: iamforufriends at gmail.com (UR DREEM GIRL) Date: Thu, 12 Aug 2010 05:51:22 -0700 (PDT) Subject: 34,100,617 active members r waiting 4 live sex chat, dating ... Message-ID: 34,100,617 active members r waiting 4 live sex chat, dating ... click bellow.... http://www.adultfriendfinder.com/go/g1250650-ppc http://www.adultfriendfinder.com/go/g1250650-ppc http://www.adultfriendfinder.com/go/g1250650-ppc From h.goebel at crazy-compilers.com Thu Aug 12 09:03:34 2010 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Thu, 12 Aug 2010 15:03:34 +0200 Subject: Announcing: python-ghostscript 0.3 Message-ID: Announcing: python-ghostscript 0.3 A Python-Interface to the Ghostscript C-API using ctypes :Copyright: GNU Public License v3 (GPLv3) :Author: Hartmut Goebel :Homepage: http://bitbucket.org/htgoebel/python-ghostscript :Download: http://pypi.python.org/pypi/ghostscript `Ghostscript`__, is a well known interpreter for the PostScript language and for PDF. This package implements a interface to the Ghostscript C-API using `ctypes`__. Both a low-level and a pythonic, high-level interface are provided. __ http://www.ghostscript.com/ __ http://docs.python.org/library/ctypes.html This package is currently tested only under GNU/Linux. Please report whether it works in your environment, too. Thanks. Latest Changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :0.3 (2010-08-12): * Added support for win32: The DLL to load is searched in registry. * On other platforms: Be more inteligent about finding Ghostscript shared object file (fall back to ctypes.util.find_library() if `libgs.8.so` can not be loaded * Better error messages if lib/dll is not found. * Removed relative imports, so older versions of Python can be used. * Added nice project logo :0.2 (2010-08-06): * Fixed several bugs, esp. for running strings by Ghostscript. Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is an example for how to use the high-level interface of `python-ghostscript`. This implements a very basic ps2pdf-tool:: import sys import ghostscript args = [ "ps2pdf", # actual value doesn't matter "-dNOPAUSE", "-dBATCH", "-dSAFER", "-sDEVICE=pdfwrite", "-sOutputFile=" + sys.argv[1], "-c", ".setpdfwrite", "-f", sys.argv[2] ] ghostscript.Ghostscript(*args) -- Regards Hartmut Goebel | Hartmut Goebel | h.goebel at crazy-compilers.com | | www.crazy-compilers.com | compilers which you thought are impossible | From blur959 at hotmail.com Thu Aug 12 09:15:23 2010 From: blur959 at hotmail.com (blur959) Date: Thu, 12 Aug 2010 06:15:23 -0700 (PDT) Subject: Renaming OS files by file type in python Message-ID: <953bbeb2-b3a5-4882-999f-184f2a51d331@x24g2000pro.googlegroups.com> Hi all, I am creating a program that renames all files of the similar file type. But i am stuck at this part. I tried running this code and I got this error: new_name = os.rename(path, newpath) WindowsError: [Error 183] Cannot create a file when that file already exists. Hope you guys could help. import os directory = raw_input("Please input file directory. \n\n") s = raw_input("Please input a name to replace. \n\n") ext = raw_input("input file ext") for filename in listdir(directory): if ext in filename: path = join(directory, filename) fnpart = os.path.splitext(filename)[0] replace_name = filename.replace(fnpart, s) newpath = os.path.join(directory, replace_name) new_name = os.rename(path, newpath) print new_name From alekseymv at gmail.com Thu Aug 12 09:16:02 2010 From: alekseymv at gmail.com (Aleksey) Date: Thu, 12 Aug 2010 06:16:02 -0700 (PDT) Subject: Copying a file with a question mark in it's name in Windows References: Message-ID: On 12 ???, 18:49, drodrig wrote: > A python script I use to backup files on a Windows 2003 server > occasionally fails to retrieve the size of a file with a question mark > in the name. The exception I get is "OSError #123 The filename, > directory name, or volume label syntax is incorrect". I realize that > technically a question mark in the name of a file on Windows is > illegal, but nevertheless these files exist on the file system. It > seems that they are created by Office 2007 Word, for the most part. If "?" is a placeholder for an unprintable character you can try view real file name in IDLE: import glob print glob.glob(u'e:/full/path/to/file?') In path to file you must instead question use wild "?". Will be printed all like files. ----------------------------- Under Windows I too have similar problem: windows sometimes (from any programs - e.g. Firefox) save files with wrong names, but later do not manipulate with it. From davea at ieee.org Thu Aug 12 09:22:30 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 12 Aug 2010 09:22:30 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: <4C63F596.5000007@ieee.org> Roald de Vries wrote: >
On Aug > 12, 2010, at 11:33 AM, Paul Rubin wrote: >> Baba writes: >>> exercise: given that packs of McNuggets can only be bought in 6, 9 or >>> 20 packs, write an exhaustive search to find the largest number of >>> McNuggets that cannot be bought in exact quantity. >> >> Is that a homework problem? Hint: first convince yourself that a >> largest number actually exists. > > Good point. There is actually an upper bound. Let's take 6 packs of > 20, that's 120 nuggets. > Now 121 nuggets can be reached by substituting 1 pack of 20 with 2 > packs of 6 and 1 pack of 9. > 122 = 4*20 + 2*(2*6+9) > 123 = 3*20 + 3*(2*6+9) > ... > 126 = 6*20 + 6 > 127 = 121 + 6 = 5*20 + (2*6 + 9) + 6 > ... etcetera. > > Now you have to find the largest number below 120, which you can > easily do with brute force (untested): > > can_be_bought = [False for i in range(120)] > for twenties in range(6): > for nines in range(14): > for sixes in range(20): > can_be_bought[twenties*20+nines*9+sixes*6] = True > for i in reverse(range(120)): > if not can_be_bought[i]: return i > > Cheers, Roald > for i in reverse(range(120)): if not can_be_bought[i]: return i can probably be replaced by (untested): return len(can_be_bought) - reverse(can_be_bought).index(False) - 1 DaveA From davea at ieee.org Thu Aug 12 09:37:55 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 12 Aug 2010 09:37:55 -0400 Subject: Programming Puzzles? What's your favorite puzzle? In-Reply-To: References: Message-ID: <4C63F933.5010702@ieee.org> Matty Sarro wrote: > Hey All! > Hope your thursday is treating you well. I'm looking for suggestions on > books of programming/engineering puzzles that range from beginners to > advanced and even expert level problems. I know they exist; we had them back > in college for practicing before the ACM programming competitions. However I > can't seem to really find any books out there that look like they're what > I'm seeking. Basically I haven't programmed a lot since I was in college, > and that was about 9 years ago. I'm expected to do a bit more programming at > my current job and I figure the best way to get back into things is to have > some practical things to solve, and maybe have a bit of fun in the process. > > Anyone have any suggestions? > > Also, if you have any favorite puzzles/simple learning programs to suggest, > please, share with the class :) > > -Matty > > For puzzles: http://projecteuler.net http://www.pythonchallenge.com And you might get some ideas from: http://wiki.python.org/moin/CodingProjectIdeas DaveA From darcy at druid.net Thu Aug 12 09:39:12 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 12 Aug 2010 09:39:12 -0400 Subject: Long rant about Python in Education In-Reply-To: References: Message-ID: <20100812093912.ecefc452.darcy@druid.net> On Thu, 12 Aug 2010 05:05:55 -0700 (PDT) ??????? wrote: > have to teach them to enjoy programming, enjoy computers, and develop > their minds in a way that doesn't involve becoming 'Imams' who are > essentially the learned mafia bosses of terrorism. This is the point that I stopped reading your "message" and added you to my blacklist. Goodbye. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From as at sci.fi Thu Aug 12 09:42:17 2010 From: as at sci.fi (Anssi Saari) Date: Thu, 12 Aug 2010 16:42:17 +0300 Subject: How does Python get the value for sys.stdin.encoding? References: Message-ID: Benjamin Kaplan writes: > Sys.stdin and stdout are files, just like any other. There's nothing > special about them at compile time. When the interpreter starts, it > checks to see if they are ttys. If they are, then it tries to figure > out the terminal's encoding based on the environment. Just a related question, is looking at sys.stdin.encoding the proper way of doing things? I've been working on a script to display some email headers, some of which are encoded in MIME to various charsets. Until now I have used whatever locale.getdefaultlocale() returns as the target encoding, since "it seemed to work". Although on one computer the call returns ISO-8859-15 even though I don't quite understand why. From ericjvandervelden at gmail.com Thu Aug 12 09:43:30 2010 From: ericjvandervelden at gmail.com (Eric J. Van der Velden) Date: Thu, 12 Aug 2010 06:43:30 -0700 (PDT) Subject: __class__ of what Message-ID: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Hello, I have, class C: n=0 def __init__(s): __class__.n+=1 I do >>> C() This is fine. But of what thing I am taking the __class__ of? I can also do @staticmethod def p(): print(__class__.n) >>> C.p() 1 Thanks, Eric J. From neilc at norwich.edu Thu Aug 12 09:44:51 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 12 Aug 2010 13:44:51 GMT Subject: Programming Puzzles? What's your favorite puzzle? References: Message-ID: <8cic6jF98kU1@mid.individual.net> On 2010-08-12, Dave Angel wrote: > For puzzles: > > http://projecteuler.net ...if you like math problems. > http://www.pythonchallenge.com ...if you like fooling around with PIL, graphics and bytes. -- Neil Cerutti From doug.shawhan at gmail.com Thu Aug 12 09:49:24 2010 From: doug.shawhan at gmail.com (Doug) Date: Thu, 12 Aug 2010 06:49:24 -0700 (PDT) Subject: Using elementtree to Create HTML Form / Set "selected" Message-ID: I'm using elementtree to create a form. I would like to set the "selected" attribute. Setting using the usual option.set( "selected" = "" ) gives me how does one make which is what I need. From ph4nut at gmail.com Thu Aug 12 09:54:11 2010 From: ph4nut at gmail.com (ph4nut) Date: Thu, 12 Aug 2010 06:54:11 -0700 (PDT) Subject: Does anyone use Quixote for web developing? References: <4c63c198$0$24088$426a74cc@news.free.fr> Message-ID: On Aug 12, 5:40?pm, Bruno Desthuilliers wrote: > ph4nut a ?crit : > > > Hi all,I am learning Quixote a few days ago,,,and i have no idea about > > whether there is any Google Group talking about Quixote,so i post this > > post to check that is Quixote been talking in this group before or can > > i ask question about Quixote here! > > ?From the project's home page: > > """ > There is a mailing list for discussing Quixote and you should look there > for information about obtaining the current release: > > ? ? ?* quixote-users > """ Thanks,I will have a check! From ph4nut at gmail.com Thu Aug 12 09:54:26 2010 From: ph4nut at gmail.com (ph4nut) Date: Thu, 12 Aug 2010 06:54:26 -0700 (PDT) Subject: Does anyone use Quixote for web developing? References: <4c63c198$0$24088$426a74cc@news.free.fr> Message-ID: <9317fc1d-bfe6-48e2-9588-3f3573f22445@u4g2000prn.googlegroups.com> On Aug 12, 5:40?pm, Bruno Desthuilliers wrote: > ph4nut a ?crit : > > > Hi all,I am learning Quixote a few days ago,,,and i have no idea about > > whether there is any Google Group talking about Quixote,so i post this > > post to check that is Quixote been talking in this group before or can > > i ask question about Quixote here! > > ?From the project's home page: > > """ > There is a mailing list for discussing Quixote and you should look there > for information about obtaining the current release: > > ? ? ?* quixote-users > """ Thanks,I will have a check! From jeanmichel at sequans.com Thu Aug 12 10:06:05 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 12 Aug 2010 16:06:05 +0200 Subject: __class__ of what In-Reply-To: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> References: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Message-ID: <4C63FFCD.9090007@sequans.com> Eric J. Van der Velden wrote: > Hello, > > I have, > > class C: > n=0 > def __init__(s): > __class__.n+=1 > > Should be class C: n = 0 def __init__(self): self.__class__.n+=1 C.n+=1 # equivalent to this line (I prefer this one, more readable, less refactor-friendly) @classmethod def p(cls): print(cls.n) JM From eric.brunel at pragmadev.com Thu Aug 12 10:07:22 2010 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 12 Aug 2010 16:07:22 +0200 Subject: __class__ of what References: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Message-ID: In article <72151646-65cb-47bb-bd55-e7eb67577c05 at z10g2000yqb.googlegroups.com>, "Eric J. Van der Velden" wrote: > Hello, > > I have, > > class C: > n=0 > def __init__(s): > __class__.n+=1 > > > I do > >>> C() > > This is fine. No it's not, at least in Python 2.x: >>> C() Traceback (most recent call last): File "", line 1, in File "", line 4, in __init__ NameError: global name '__class__' is not defined > But of what thing I am taking the __class__ of? Nothing, precisely. You should write s.__class__ (and replace s by self while you're at it). > I can also do > > @staticmethod > def p(): > print(__class__.n) > > >>> C.p() > 1 No you can't, again in Python 2.x: >>> C.p() Traceback (most recent call last): File "", line 1, in File "", line 4, in p NameError: global name '__class__' is not defined Unless I'm missing something or something fundamental changed in Python 3, your examples do not work? > Thanks, > > Eric J. From __peter__ at web.de Thu Aug 12 10:21:07 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 16:21:07 +0200 Subject: __class__ of what References: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Message-ID: Eric J. Van der Velden wrote: > I have, > > class C: > n=0 > def __init__(s): > __class__.n+=1 > > > I do >>>> C() > > This is fine. But of what thing I am taking the __class__ of? > I can also do > > @staticmethod > def p(): > print(__class__.n) > >>>> C.p() > 1 I had no idea that this existed. __class__ was probably added to make super() calls without an explicit class argument possible in Python 3. It is made available as a closure: >>> class A: ... def f(self): __class__ ... def g(self): pass ... >>> A.f.__closure__[0].cell_contents >>> A.g.__closure__ is None True Peter From __peter__ at web.de Thu Aug 12 10:47:55 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 16:47:55 +0200 Subject: Using elementtree to Create HTML Form / Set "selected" References: Message-ID: Doug wrote: > I'm using elementtree to create a form. > > I would like to set the "selected" attribute. > > Setting using the usual > option.set( "selected" = "" ) Maybe that should be option.set(selected="selected"). I think > how does one make > > which is what I need. From doug.shawhan at gmail.com Thu Aug 12 10:55:24 2010 From: doug.shawhan at gmail.com (Doug) Date: Thu, 12 Aug 2010 07:55:24 -0700 (PDT) Subject: Using elementtree to Create HTML Form / Set "selected" References: Message-ID: <1b59481f-8a5a-41e3-9d09-baeb8a1f027b@d8g2000yqf.googlegroups.com> On Aug 12, 10:47?am, Peter Otten <__pete... at web.de> wrote: > Doug wrote: > > I'm using elementtree to create a form. > > > I would like to set the "selected" attribute. > > > Setting using the usual > > ?option.set( "selected" = "" ) > > Maybe that should be option.set(selected="selected"). I think > > > > how does one make > > ? > > which is what I need. Makes sense to me. Thanks! From sschwarzer at sschwarzer.net Thu Aug 12 11:05:45 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 12 Aug 2010 17:05:45 +0200 Subject: __class__ of what In-Reply-To: References: <72151646-65cb-47bb-bd55-e7eb67577c05@z10g2000yqb.googlegroups.com> Message-ID: <4C640DC9.80105@sschwarzer.net> Hello Jean-Michel, On 2010-08-12 16:06, Jean-Michel Pichavant wrote: > Eric J. Van der Velden wrote: > Should be > > class C: > n = 0 > def __init__(self): > self.__class__.n+=1 > C.n+=1 # equivalent to this line (I prefer this one, more > readable, less refactor-friendly) I think both lines have slightly different semantics if you consider instantiating an object of a derived class. (The following formatting is from IPython, thus the differences to the "usual" interpreter output.) Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >>> class C(object): ... n = 0 ... def __init__(self): ... self.__class__.n += 1 ... >>> class D(C): ... pass ... >>> d = D() >>> D.n 1 >>> C.n 0 Here, the augmented assignment looks up self.__class__.n which it doesn't find and so gets it from class C. The actual assignment assigns to D.n, however. On the other hand: >>> class C(object): ... n = 0 ... def __init__(self): ... C.n += 1 ... >>> class D(C): ... pass ... >>> d = D() >>> D.n 1 >>> C.n 1 Here, only C is changed. D doesn't get an own attribute n, and after the instantiation of d, D.n looks up and gets n from the base class C. Curiously, >>> dir(D) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'n'] seems to contain n (is it supposed to be listed here?), but >>> dict(D.__dict__) {'__doc__': None, '__module__': '__main__'} indicates that D doesn't contain n. But C does: >>> dict(C.__dict__) {'__dict__': , '__doc__': None, '__init__': , '__module__': '__main__', '__weakref__': , 'n': 1} I hope everything I wrote above is valid. If not, please correct me. :-) Anyway, depending on what you want, either of the two variants might be ok. In any case I'd include a meaningful comment on why you actually wrote what you wrote. :-) Stefan From dlanorslegov at rocketmail.com Thu Aug 12 11:12:33 2010 From: dlanorslegov at rocketmail.com (Dlanor Slegov) Date: Thu, 12 Aug 2010 08:12:33 -0700 (PDT) Subject: Inserting/Deleting newline(s) in very large text files Message-ID: <595550.37557.qm@web120110.mail.ne1.yahoo.com> Hi, I am dealing with very large text files (a few million lines) and would like to check and modify them according to a well defined format. The format requires?ONLY ONE?NEWLINE (followed by some sort of text) on top of the file and NO NEWLINE in the very end. The input files can be very diverse, such as?one file may have 2 newlines on top and none in the end or other may not have a newline on top and 5 in the end. The aim is to check these files &?introduce JUST ONE NEWLINE in the?TOP and NO NEWLINE in the BOTTOM. Any pointers will be appreciated. Thanks, DS. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Thu Aug 12 11:24:40 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 12 Aug 2010 09:24:40 -0600 Subject: Programming Puzzles? What's your favorite puzzle? In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 5:41 AM, Matty Sarro wrote: > Hey All! > Hope your thursday is treating you well. I'm looking for suggestions on > books of programming/engineering puzzles that range from beginners to > advanced and even expert level problems. I know they exist; we had them back > in college for practicing before the ACM programming competitions. However I > can't seem to really find any books out there that look like they're what > I'm seeking. Basically I haven't programmed a lot since I was in college, > and that was about 9 years ago. I'm expected to do a bit more programming at > my current job and I figure the best way to get back into things is to have > some practical things to solve, and maybe have a bit of fun in the process. > > Anyone have any suggestions? http://www.spoj.pl/ http://www.codechef.com/ Many of the problems at those sites are difficult in Python due to the time constraints, but they're well worth checking out. Cheers, Ian From p.c.j.kleiweg at rug.nl Thu Aug 12 11:36:38 2010 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Thu, 12 Aug 2010 17:36:38 +0200 (CEST) Subject: Announcing: python-ghostscript 0.3 In-Reply-To: References: Message-ID: Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010: > Here is an example for how to use the high-level interface of > `python-ghostscript`. This implements a very basic ps2pdf-tool:: > > import sys > import ghostscript > > args = [ > "ps2pdf", # actual value doesn't matter > "-dNOPAUSE", "-dBATCH", "-dSAFER", > "-sDEVICE=pdfwrite", > "-sOutputFile=" + sys.argv[1], > "-c", ".setpdfwrite", > "-f", sys.argv[2] > ] > > ghostscript.Ghostscript(*args) How is this different from os.system(' '.join(args)) ? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From p.c.j.kleiweg at rug.nl Thu Aug 12 11:36:38 2010 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Thu, 12 Aug 2010 17:36:38 +0200 Subject: Announcing: python-ghostscript 0.3 In-Reply-To: References: Message-ID: Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010: > Here is an example for how to use the high-level interface of > `python-ghostscript`. This implements a very basic ps2pdf-tool:: > > import sys > import ghostscript > > args = [ > "ps2pdf", # actual value doesn't matter > "-dNOPAUSE", "-dBATCH", "-dSAFER", > "-sDEVICE=pdfwrite", > "-sOutputFile=" + sys.argv[1], > "-c", ".setpdfwrite", > "-f", sys.argv[2] > ] > > ghostscript.Ghostscript(*args) How is this different from os.system(' '.join(args)) ? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From bavantgarde at yahoo.com Thu Aug 12 11:44:19 2010 From: bavantgarde at yahoo.com (BAvant Garde) Date: Thu, 12 Aug 2010 08:44:19 -0700 (PDT) Subject: unicode string alteration Message-ID: <155711.87581.qm@web83402.mail.sp1.yahoo.com> HELP!!! I need help with a unicode issue that has me stumped. I must be doing something? wrong because I don't believe this condition would have slipped thru testing. Wherever the string u'\udbff\udc00' occurs u'\U0010fc00' or unichr(1113088) is substituted and the file loses 1 character resulting in all trailing characters being shifted out of position. No other corrupt strings have been detected. ? ? The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04 where the maximum ord # is 1114111 (wide Python build). ? ? Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535 (narrow Python build) the string u'\U0010fc00' also occurs and it "seems" that the substitution takes place but no characters are lost and file sizes are ok. Note that ord(u'\U0010fc00') causes the following error: ???????????? "TypeError: ord() expected a character, but string of length 2 found" The condition is otherwise invisible in 2.5.4 and is handled internally without any apparent effect on processing with characters u'\udbff' and u'\udc00' each being separately accessible. The first part of the attachment repeats this email but also has examples and illustrates other related oddities. ? ? Any help would be greatly appreciated. Bruce -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: unicode_internals_question_linux2.txt URL: From nawabadeel at gmail.com Thu Aug 12 11:56:27 2010 From: nawabadeel at gmail.com (Sohail) Date: Thu, 12 Aug 2010 08:56:27 -0700 (PDT) Subject: How to parse a sentence using grammars provided by nltk? Message-ID: <1bf11039-012c-4f77-824e-4e7fc4c3eab0@a36g2000yqc.googlegroups.com> Hi, When I define my own production rules for the grammar the code below runs fine. Can anyone tell me how to use the built in grammars of nltk (if there are any)? >>> groucho_grammar = nltk.parse_cfg(""" ... S -> NP VP ... PP -> P NP ... NP -> Det N | Det N PP | 'I' ... VP -> V NP | VP PP ... Det -> 'an' | 'my' ... N -> 'elephant' | 'pajamas' ... V -> 'shot' ... P -> 'in' ... """) >>> sent = ['I', 'shot', 'an', 'elephant', 'in', 'my', 'pajamas'] >>> parser = nltk.ChartParser(groucho_grammar) >>> trees = parser.nbest_parse(sent) >>> for tree in trees: ... print tree thanks From zac256 at gmail.com Thu Aug 12 12:13:42 2010 From: zac256 at gmail.com (Zac Burns) Date: Thu, 12 Aug 2010 09:13:42 -0700 Subject: Extract stack from running python program Message-ID: Is there a utility to extract the stacks from a running python program that is hung? Sounds like a long shot but if anyone knows it would be you guys. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu Aug 12 12:16:08 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 17:16:08 +0100 Subject: Renaming OS files by file type in python In-Reply-To: <953bbeb2-b3a5-4882-999f-184f2a51d331@x24g2000pro.googlegroups.com> References: <953bbeb2-b3a5-4882-999f-184f2a51d331@x24g2000pro.googlegroups.com> Message-ID: <4C641E48.6080308@mrabarnett.plus.com> blur959 wrote: > Hi all, I am creating a program that renames all files of the similar > file type. But i am stuck at this part. I tried running this code and > I got this error: new_name = os.rename(path, newpath) > WindowsError: [Error 183] Cannot create a file when that file already > exists. Hope you guys could help. > [snip] As the traceback says, a file with that new name already exists. You can't have 2 files with the same name in the same folder. From dreadpiratejeff at gmail.com Thu Aug 12 12:19:22 2010 From: dreadpiratejeff at gmail.com (J) Date: Thu, 12 Aug 2010 12:19:22 -0400 Subject: OptParse and Constant values Message-ID: How do you use OptParse with constants? Example: usage = 'Usage: %prog [OPTIONS]' parser = OptionParser(usage) parser.add_option('-l','--level', action='store_const', default=LOG_INFO, help='Set the log level to inject into syslog (either an\ integer [0 - 7] or one of LOG_EMERG, LOG_ALERT,LOG_CRIT,\ LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG') (options,args) = parser.parse_args() print options always returns {'level':None} regarless of whether I call it with an int (0 - 7) or the const name (LOG_*) I'm importing syslog like so: from syslog import * so all the syslog constants should be available to me at run time (at least that's my understanding) so I'm doing something wrong here or just not understanding how to do a constant as an option. The basic gist of the above is that I'm writing a tool to do basic syslog testing by injecting messages and making sure they end up in the correct log file... I can do all of this manually or in a loop by looping through the various log levels, however, I want to be able to specify them at run-time using an optional argument. Any ideas on how to make this work, or at least why it's not doing what I thought it would do? Cheers Jeff From robert.kern at gmail.com Thu Aug 12 12:41:40 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Aug 2010 11:41:40 -0500 Subject: OptParse and Constant values In-Reply-To: References: Message-ID: On 8/12/10 11:19 AM, J wrote: > How do you use OptParse with constants? > > Example: > usage = 'Usage: %prog [OPTIONS]' > parser = OptionParser(usage) > parser.add_option('-l','--level', > action='store_const', > default=LOG_INFO, > help='Set the log level to inject into syslog (either an\ > integer [0 - 7] or one of LOG_EMERG, LOG_ALERT,LOG_CRIT,\ > LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG') > (options,args) = parser.parse_args() > > print options > > always returns {'level':None} regarless of whether I call it with an > int (0 - 7) or the const name (LOG_*) http://docs.python.org/library/optparse#standard-option-actions 'store_const' means that the option is a flag without arguments and stores the value provided by the 'const' keyword to add_option() (it defaults to None so that's what you get when you use that flag). This is not what you want. You just want the default 'store' action. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From john at castleamber.com Thu Aug 12 13:22:15 2010 From: john at castleamber.com (John Bokma) Date: Thu, 12 Aug 2010 12:22:15 -0500 Subject: Long rant about Python in Education References: Message-ID: <87tymz4ugo.fsf@castleamber.com> "D'Arcy J.M. Cain" writes: > On Thu, 12 Aug 2010 05:05:55 -0700 (PDT) > ??????? wrote: >> have to teach them to enjoy programming, enjoy computers, and develop >> their minds in a way that doesn't involve becoming 'Imams' who are >> essentially the learned mafia bosses of terrorism. > > This is the point that I stopped reading your "message" and added you > to my blacklist. Goodbye. For what it's worth, same here. Also, I don't think it's a good idea to force a learning environment or an OS on a child. IMO it works best if you let the child discover and be a guide, not "thou should not use Windows". Not so remarkable that the rant moves from an extremistic teaching environment to an extremistic world view. From hating everything that's not Linux and idolizing the CLI to hating everything that is different in general. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From python at mrabarnett.plus.com Thu Aug 12 13:31:29 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 18:31:29 +0100 Subject: unicode string alteration In-Reply-To: <155711.87581.qm@web83402.mail.sp1.yahoo.com> References: <155711.87581.qm@web83402.mail.sp1.yahoo.com> Message-ID: <4C642FF1.1050508@mrabarnett.plus.com> BAvant Garde wrote: > HELP!!! > I need help with a unicode issue that has me stumped. I must be doing > something wrong because I don't believe this condition would have > slipped thru testing. > > Wherever the string u'\udbff\udc00' occurs u'\U0010fc00' or > unichr(1113088) is substituted and the file loses 1 character resulting > in all trailing characters being shifted out of position. No other > corrupt strings have been detected. > > The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04 > where the maximum ord # is 1114111 (wide Python build). > > Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535 > (narrow Python build) the string u'\U0010fc00' also occurs and it > "seems" that the substitution takes place but no characters are lost and > file sizes are ok. Note that ord(u'\U0010fc00') causes the following error: > "TypeError: ord() expected a character, but string of > length 2 found" > The condition is otherwise invisible in 2.5.4 and is handled internally > without any apparent effect on processing with characters u'\udbff' and > u'\udc00' each being separately accessible. > > The first part of the attachment repeats this email but also has > examples and illustrates other related oddities. > > Any help would be greatly appreciated. > It's not an error, it's a "surrogate pair". Surrogate pairs are part of the Unicode specification. Unicode codepoints go up to U+0010FFFF. If you're using 16 bits per codepoint, like in a narrow build of Python, then the codepoints above U+FFFF _can't_ be represented directly, so they are represented by a pair of codepoints called a "surrogate pair". If, on the other hand, you're using 32 bits per codepoint, like in a wide build of Python, then the codepoints above U+FFFF _can_ be represented directly, so surrogate pairs aren't needed, and, indeed shouldn't be there. What you're seeing in the wide build is Python replacing a surrogate pair with the codepoint that it represents, which is actually the right thing to do because, as I said, the surrogate pairs really shouldn't be there. From rNOSPAMon at flownet.com Thu Aug 12 13:36:37 2010 From: rNOSPAMon at flownet.com (RG) Date: Thu, 12 Aug 2010 10:36:37 -0700 Subject: Why can't I set sys.ps1 to a unicode string? References: Message-ID: In article , "Martin v. Loewis" wrote: > > So... why does having a non-ascii character in sys.ps1 make the prompt > > vanish? > > I can't pinpoint it to a specific line of code. Most likely, it tries > to encode the prompt as ASCII before writing it to stdout. That fails, > and it silently ignores the error. > > FWIW, this is fixed in Python 3. Guess it's time to upgrade. :-) Thanks! rg From wherespythonmonks at gmail.com Thu Aug 12 13:45:12 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 13:45:12 -0400 Subject: inline exception handling in python Message-ID: Hi! I have on a few occasions now wanted to have inline-exception handling, like the inline if/else operator. For example, The following might raise ZeroDivisionError: f = n / d So, I can look before I leap (which is okay): f = float("nan") if d == 0 else n/d; But, what I'd like to be able to write is: f = n / d except float("nan"); Which I find much more appealing than: try: f = n / d except: f = float("nan") (Obviously, I am thinking about more complicated functions than "n/d" -- but this works as an example.) Thoughts? W From dreadpiratejeff at gmail.com Thu Aug 12 13:47:53 2010 From: dreadpiratejeff at gmail.com (J) Date: Thu, 12 Aug 2010 13:47:53 -0400 Subject: OptParse and Constant values In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 12:41, Robert Kern wrote: > On 8/12/10 11:19 AM, J wrote: >> >> How do you use OptParse with constants? > http://docs.python.org/library/optparse#standard-option-actions > > 'store_const' means that the option is a flag without arguments and stores > the value provided by the 'const' keyword to add_option() (it defaults to > None so that's what you get when you use that flag). This is not what you > want. You just want the default 'store' action. Thanks Robert... Sigh... head -> desk -> repeat :) From thomas at jollybox.de Thu Aug 12 14:08:01 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 20:08:01 +0200 Subject: inline exception handling in python In-Reply-To: References: Message-ID: <201008122008.02041.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: > try: > f = n / d > except: > f = float("nan") A catch-all except clause. Never a good idea. It's not as bad in this case, as there is only one expression, but there are still a couple of other exceptions that have a chance of occurring here: KeyboardInterrupt and SystemExit. So: try: f = n / d except ZeroDivisionError: f = float('nan') > f = n / d except float("nan"); So this syntax really isn't adequate for real use: catch-all except clauses are frowned upon, and rightfully so. Besides, more often than not, you want to have a finally clause around when you're dealing with exceptions. > (Obviously, I am thinking about more complicated functions than "n/d" > -- but this works as an example.) The more complex the function is, the more likely it is to raise an exception you can't handle that easily. From wherespythonmonks at gmail.com Thu Aug 12 14:19:13 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 14:19:13 -0400 Subject: inline exception handling in python In-Reply-To: <201008122008.02041.thomas@jollybox.de> References: <201008122008.02041.thomas@jollybox.de> Message-ID: On Thu, Aug 12, 2010 at 2:08 PM, Thomas Jollans wrote: > On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: >> try: >> ? ?f = n / d >> except: >> ? ?f = float("nan") > > A catch-all except clause. Never a good idea. It's not as bad in this case, as > there is only one expression, but there are still a couple of other exceptions > that have a chance of occurring here: KeyboardInterrupt and SystemExit. > So: > > try: > ? ?f = n / d > except ZeroDivisionError: > ? ?f = float('nan') > > >> f = n / d except float("nan"); > > So this syntax really isn't adequate for real use: catch-all except clauses > are frowned upon, and rightfully so. > > Besides, more often than not, you want to have a finally clause around when > you're dealing with exceptions. > > >> (Obviously, I am thinking about more complicated functions than "n/d" >> -- but this works as an example.) > > The more complex the function is, the more likely it is to raise an exception > you can't handle that easily. > -- > http://mail.python.org/mailman/listinfo/python-list > With a bit imagination the syntax can handle specific exceptions: f = n /d except except(ZeroDivisionError) float("nan") f = n /d except except(ZeroDivisionError) float("nan") except(ValueError) float("nan") But then we cannot bind to useful variable you say... I think the problem in my case is best solved by look before you leap, or a wrapper function. [I just hate function call overhead for this. ] Thanks, W From wherespythonmonks at gmail.com Thu Aug 12 14:25:25 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 14:25:25 -0400 Subject: inline exception handling in python In-Reply-To: References: <201008122008.02041.thomas@jollybox.de> Message-ID: On Thu, Aug 12, 2010 at 2:19 PM, wheres pythonmonks wrote: > On Thu, Aug 12, 2010 at 2:08 PM, Thomas Jollans wrote: >> On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: >>> try: >>> ? ?f = n / d >>> except: >>> ? ?f = float("nan") >> >> A catch-all except clause. Never a good idea. It's not as bad in this case, as >> there is only one expression, but there are still a couple of other exceptions >> that have a chance of occurring here: KeyboardInterrupt and SystemExit. >> So: >> >> try: >> ? ?f = n / d >> except ZeroDivisionError: >> ? ?f = float('nan') >> >> >>> f = n / d except float("nan"); >> >> So this syntax really isn't adequate for real use: catch-all except clauses >> are frowned upon, and rightfully so. >> >> Besides, more often than not, you want to have a finally clause around when >> you're dealing with exceptions. >> >> >>> (Obviously, I am thinking about more complicated functions than "n/d" >>> -- but this works as an example.) >> >> The more complex the function is, the more likely it is to raise an exception >> you can't handle that easily. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > With a bit imagination the syntax can handle specific exceptions: > > f = n /d except except(ZeroDivisionError) float("nan") > > f = n /d except except(ZeroDivisionError) float("nan") > except(ValueError) float("nan") > > But then we cannot bind to useful variable you say... > > I think the problem in my case is best solved by look before you leap, > or a wrapper function. ?[I just hate function call overhead for this. > ] > > Thanks, > > W > I mean something along these lines: f = n /d except(ZeroDivisionError) float("nan") except(ValueError) float("nan") From raoulbia at gmail.com Thu Aug 12 14:37:43 2010 From: raoulbia at gmail.com (Baba) Date: Thu, 12 Aug 2010 11:37:43 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> Message-ID: <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Hi News123 Thank You for helping me out. Indeed i am not looking for the code but rather for hints that direct my reasoning as well as hints as to how to write basic programs like this. You have broken down the approach into 2 parts. I have tried to solve part 1 but i'm not quite there yet. Here's my code: def can_buy(n_nuggets): for a in range (1,n_nuggets): for b in range (1,n_nuggets): for c in range (1,n_nuggets): if 6*a+9*b+20*c==n_nuggets: #print a,b,c,'n_nuggets=',n_nuggets return True else: return False can_buy(55) as you can see i am trying to loop through all combinations of values bewtween 1 and n_nuggets and when the equation resolves it should return True, else it should return False. I was hoping that when i then call my function and ask it to test a value nothing happens. What is wrong? My syntax? My semantic? Both? tnx Baba From python at mrabarnett.plus.com Thu Aug 12 14:42:12 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 19:42:12 +0100 Subject: inline exception handling in python In-Reply-To: References: Message-ID: <4C644084.9040500@mrabarnett.plus.com> wheres pythonmonks wrote: > Hi! > > I have on a few occasions now wanted to have inline-exception > handling, like the inline if/else operator. > > For example, > > The following might raise ZeroDivisionError: > > f = n / d > > So, I can look before I leap (which is okay): > > f = float("nan") if d == 0 else n/d; > > But, what I'd like to be able to write is: > > f = n / d except float("nan"); > > Which I find much more appealing than: > > try: > f = n / d > except: > f = float("nan") > > (Obviously, I am thinking about more complicated functions than "n/d" > -- but this works as an example.) > > Thoughts? > Discussed a year ago: [Python-Dev] (try-except) conditional expression similar to (if-else) conditional (PEP 308) http://code.activestate.com/lists/python-dev/90256/ From wherespythonmonks at gmail.com Thu Aug 12 14:54:07 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 14:54:07 -0400 Subject: inline exception handling in python In-Reply-To: <4C644084.9040500@mrabarnett.plus.com> References: <4C644084.9040500@mrabarnett.plus.com> Message-ID: On Thu, Aug 12, 2010 at 2:42 PM, MRAB wrote: > wheres pythonmonks wrote: >> >> Hi! >> >> I have on a few occasions now wanted to have inline-exception >> handling, like the inline if/else operator. >> >> For example, >> >> The following might raise ZeroDivisionError: >> >> f = n / d >> >> So, I can look before I leap (which is okay): >> >> f = float("nan") if d == 0 else n/d; >> >> But, what I'd like to be able to write is: >> >> f = n / d except float("nan"); >> >> Which I find much more appealing than: >> >> try: >> ? f = n / d >> except: >> ? f = float("nan") >> >> (Obviously, I am thinking about more complicated functions than "n/d" >> -- but this works as an example.) >> >> Thoughts? >> > Discussed a year ago: > > [Python-Dev] (try-except) conditional expression similar to (if-else) > conditional (PEP 308) > > http://code.activestate.com/lists/python-dev/90256/ > > -- > http://mail.python.org/mailman/listinfo/python-list > http://code.activestate.com/lists/python-dev/90256/ Nice -- excellent discussion and what I was looking for. I am guessing that no implementation materialized. From thomas at jollybox.de Thu Aug 12 14:57:02 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 20:57:02 +0200 Subject: inline exception handling in python In-Reply-To: References: <201008122008.02041.thomas@jollybox.de> Message-ID: <201008122057.03688.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: > [I just hate function call overhead for this.] I think you've got your priorities wrong. If you want to avoid unnecessary overhead, avoid exceptions more than functions. From homeusenet4 at brianhv.org Thu Aug 12 15:00:17 2010 From: homeusenet4 at brianhv.org (Brian Victor) Date: Thu, 12 Aug 2010 19:00:17 +0000 (UTC) Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: Baba wrote: > def can_buy(n_nuggets): [snip] > can_buy(55) > > as you can see i am trying to loop through all combinations of values > bewtween 1 and n_nuggets and when the equation resolves it should > return True, else it should return False. > > I was hoping that when i then call my function and ask it to test a > value nothing happens. What is wrong? My syntax? My semantic? Both? You're calling the function, but you're not doing anything with the result. If you use "print can_buy(55)" you'll see the result on the console. Presumably you'll actually want to use it in an if statement. -- Brian From tormod.hagen at gmail.com Thu Aug 12 15:00:34 2010 From: tormod.hagen at gmail.com (tormod) Date: Thu, 12 Aug 2010 12:00:34 -0700 (PDT) Subject: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT) References: Message-ID: <7762bda5-e1dc-461c-82a1-7eaa431b5bef@x25g2000yqj.googlegroups.com> On Aug 12, 12:30?pm, Alexander Gattin wrote: > Does Windows have anything like > LD_LIBRARY_PATH/SHLIB_PATH? No, isn't that only if I have an actual Oracle client installed (not the instant client)? But great tip, wasn't exactly the solution, but your question triggered me to check the Windows environment variables*. I included env. variable name PATH and the value ;C:\Python31;C:\MinGW\bin;C:\TEMP \ORAIC10\bin. Only thing I set manually in the command prompt was: SET ORACLE_HOME=C: \TEMP\ORAIC10 , before the build. *=I checked the setup.py script which says: userOracleHome = os.environ.get("ORACLE_HOME") Checking in Visual Basic::environ("path") only included info from the Windows env. variables, and not the ones I set via the command prompt with PATH=%PATH%;... so I reckon if it applies to VB it also does for os.environ I can now import without errors! Thanks Alexander for putting me in the right direction. From __peter__ at web.de Thu Aug 12 15:02:40 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 21:02:40 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: Baba wrote: > Thank You for helping me out. Indeed i am not looking for the code but > rather for hints that direct my reasoning as well as hints as to how > to write basic programs like this. > > You have broken down the approach into 2 parts. I have tried to solve > part 1 but i'm not quite there yet. Here's my code: > > def can_buy(n_nuggets): > for a in range (1,n_nuggets): > for b in range (1,n_nuggets): > for c in range (1,n_nuggets): > if 6*a+9*b+20*c==n_nuggets: > #print a,b,c,'n_nuggets=',n_nuggets > return True > else: > return False > > > can_buy(55) > > as you can see i am trying to loop through all combinations of values > bewtween 1 and n_nuggets and when the equation resolves it should > return True, else it should return False. > > I was hoping that when i then call my function and ask it to test a > value nothing happens. What is wrong? My syntax? My semantic? Both? First, the function gives up too early; it should only return False when all combinations of a, b, c (technically: the product of the ranges) have been tried. Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + 0*20 is never tried; fix your ranges accordingly. Peter From tjreedy at udel.edu Thu Aug 12 15:10:32 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Aug 2010 15:10:32 -0400 Subject: urllib2 does not implement "with" Python 2.6 In-Reply-To: <4c6387f8$0$1587$742ec2ed@news.sonic.net> References: <4c6387f8$0$1587$742ec2ed@news.sonic.net> Message-ID: On 8/12/2010 1:34 AM, John Nagle wrote: > Somewhat to my surprise, in Python 2.6, > > with urllib2.urlopen(url) as fh : > > doesn't work. It fails with > "AttributeError: addinfourl instance has no attribute '__exit__'". > > I thought that all the file-like objects supported "with" in 2.6. > No? This seems to work in 3.1, which first came out almost a year after 2.6. from urllib.request import urlopen with urlopen("http://www.python.org") as fh : pass -- Terry Jan Reedy From aahz at pythoncraft.com Thu Aug 12 15:24:14 2010 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2010 12:24:14 -0700 Subject: image resize doesn't work References: Message-ID: In article , Chris Hare wrote: > >And I see now what I did wrong - thanks for putting up with the questions. Posting that information is useful for any other newbies who might be following along.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From thomas at jollybox.de Thu Aug 12 15:25:59 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 21:25:59 +0200 Subject: Inserting/Deleting newline(s) in very large text files In-Reply-To: <595550.37557.qm@web120110.mail.ne1.yahoo.com> References: <595550.37557.qm@web120110.mail.ne1.yahoo.com> Message-ID: <201008122125.59751.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to Dlanor Slegov to exclaim: > Hi, > > I am dealing with very large text files (a few million lines) and would > like to check and modify them according to a well defined format. The > format requires ONLY ONE NEWLINE (followed by some sort of text) on top of > the file and NO NEWLINE in the very end. The input files can be very > diverse, such as one file may have 2 newlines on top and none in the end > or other may not have a newline on top and 5 in the end. > > > The aim is to check these files & introduce JUST ONE NEWLINE in the TOP and > NO NEWLINE in the BOTTOM. > > Any pointers will be appreciated. If the files are that long, you might want to avoid storing the whole file in memory at the same time. Have you already tried writing the program? If not, go write the program! (and then come back, possibly, if you have questions) PS: What a strange format that must be. Everybody agrees that text files should end with a line feed, because some text editors might mess up if they don't. From aahz at pythoncraft.com Thu Aug 12 15:31:46 2010 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2010 12:31:46 -0700 Subject: exception handling with sqlite db errors References: <2a47b306-45d1-474a-9f8e-5b71eba629c9@p11g2000prf.googlegroups.com> Message-ID: In article <2a47b306-45d1-474a-9f8e-5b71eba629c9 at p11g2000prf.googlegroups.com>, CM wrote: > >Maybe it's not much of an issue, but I think it would be a shame if >occasional hangs/crashes could be caused by these (rare?) database >conflicts if there is a good approach for avoiding them. I guess I >could put every last write to the db in a try/except block but I >thought there should be a more general solution, since that will >require many such exceptions and seems inelegant. Wrap all your uses of sqlite into a function that does the try/except; you only write the code once, then. As you progress, you can also change the code to retry operations. Here's some ugly code I wrote on top of SQLObject: from sqlobject.dbconnection import registerConnection from sqlobject.sqlite.sqliteconnection import SQLiteConnection class RetrySQLiteConnection(SQLiteConnection): """ Because SQLite is not really concurrent, having multiple processes read/write can result in locked DB failures. In addition, SQLObject doesn't properly protect operations in transations, so you can get spurious DB errors claiming that the DB is corrupt because of foreign key integrity failures. This subclass retries DatabaseError and OperationalError exceptions. """ MAX_RETRIES = 4 SAFE_DB_ERROR = [ 'database disk image is malformed', 'file is encrypted or is not a database', ] def _safe_db_error(self, exception): err = str(exception).lower() for safe_err in self.SAFE_DB_ERROR: if safe_err in err: return True return False def _check_integrity(self): conn = self.getConnection() try: i = 0 while True: i += 1 try: cursor = conn.cursor() query = "pragma integrity_check" SQLiteConnection._executeRetry(self, conn, cursor, query) result = cursor.fetchall() if result == [('ok',)]: return True else: logging.error("Bad integrity result: %s", result) return False except DatabaseError, e: if i < self.MAX_RETRIES: logging.info('integrity_check, try #%s: %s', i, e) time.sleep(2) else: logging.error('integrity_check, try #%s: %s', i, e) raise finally: self.releaseConnection(conn) def _executeRetry(self, conn, cursor, query): i = 0 while True: i += 1 try: return SQLiteConnection._executeRetry(self, conn, cursor, query) except OperationalError, e: if i < self.MAX_RETRIES: logging.warn('OperationalError, try #%s: %s', i, e) time.sleep(10) else: logging.error('OperationalError, try #%s: %s', i, e) raise except DatabaseError, e: if e.__class__ is not DatabaseError: # Don't retry e.g. IntegrityError raise if not self._safe_db_error(e): # Only retry specific errors raise if not self._check_integrity(): raise if i < self.MAX_RETRIES: logging.warn('DatabaseError, try #%s: %s', i, e) time.sleep(0.5) else: logging.error('DatabaseError, try #%s: %s', i, e) raise def conn_builder(): return RetrySQLiteConnection registerConnection(['retrysqlite'], conn_builder) def init(): dbpath = os.path.join(common.getSyncDataPath(), app.dbname) connection_string = "retrysqlite:" + dbpath global _connection _connection = connectionForURI(connection_string) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From nobody at nowhere.com Thu Aug 12 15:32:43 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 12 Aug 2010 20:32:43 +0100 Subject: Line-by-line processing when stdin is not a tty References: <20100811094230.GA21181@cskk.homeip.net> Message-ID: On Wed, 11 Aug 2010 18:49:26 -0700, RG wrote: > This doesn't explain why "cat | cat" when run interactively outputs > line-by-line (which it does). STDIN to the first cat is a TTY, but the > second one isn't. GNU cat doesn't use stdio, it uses read() and write(), so there isn't any buffering. For more complex programs, using unbuffered I/O may not be practical, due to either code complexity or performance. From aahz at pythoncraft.com Thu Aug 12 15:32:54 2010 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2010 12:32:54 -0700 Subject: Announcing: python-ghostscript 0.3 References: Message-ID: In article , Peter Kleiweg wrote: >Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010: > >> Here is an example for how to use the high-level interface of >> `python-ghostscript`. This implements a very basic ps2pdf-tool:: >> >> import sys >> import ghostscript >> >> args = [ >> "ps2pdf", # actual value doesn't matter >> "-dNOPAUSE", "-dBATCH", "-dSAFER", >> "-sDEVICE=pdfwrite", >> "-sOutputFile=" + sys.argv[1], >> "-c", ".setpdfwrite", >> "-f", sys.argv[2] >> ] >> >> ghostscript.Ghostscript(*args) > >How is this different from os.system(' '.join(args)) ? You don't have problems with shell metacharacters. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From python at mrabarnett.plus.com Thu Aug 12 15:34:34 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Aug 2010 20:34:34 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: <4C644CCA.4060402@mrabarnett.plus.com> Baba wrote: > Hi News123 > > Thank You for helping me out. Indeed i am not looking for the code but > rather for hints that direct my reasoning as well as hints as to how > to write basic programs like this. > > You have broken down the approach into 2 parts. I have tried to solve > part 1 but i'm not quite there yet. Here's my code: > > def can_buy(n_nuggets): > for a in range (1,n_nuggets): > for b in range (1,n_nuggets): > for c in range (1,n_nuggets): > if 6*a+9*b+20*c==n_nuggets: > #print a,b,c,'n_nuggets=',n_nuggets > return True > else: > return False > > > can_buy(55) > > as you can see i am trying to loop through all combinations of values > bewtween 1 and n_nuggets and when the equation resolves it should > return True, else it should return False. > > I was hoping that when i then call my function and ask it to test a > value nothing happens. What is wrong? My syntax? My semantic? Both? > Think about it this way. How many packs of 20 would you need? You don't want too many, but too few is OK. Then, how many packs of 9 for the remaining nuggets? (Again, you don't want too many.) Then, how many packs of 6? If all the nuggets are accounted for, good, otherwise reduce the number of one of the packs and try again. Repeat as necessary. A couple of 'for' loops will do it. From thomas at jollybox.de Thu Aug 12 15:36:18 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 21:36:18 +0200 Subject: Why can't I set sys.ps1 to a unicode string? In-Reply-To: References: Message-ID: <201008122136.19067.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to RG to exclaim: > %%% /&%%% > > If this were a properly unicode-enabled newsreader you would see a > yin-yang symbol in the middle of s2. Are you sure about that? Now maybe the mailing list gateway is messing things up, but I rather suspect your newsreader (or USENET server) is sending out nonsense. After all, Unicode usually works around here. Some excerpts from the message, as I received it: Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit [...] >>> print s2 %%% /&%%% No quoted-printable. No UTF-7. Just three completely random characters? From downaold at gmail.com Thu Aug 12 15:42:59 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 12 Aug 2010 21:42:59 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: <37E4ACD0-BEC1-4693-8DB5-66FB342D73A9@gmail.com> On Aug 12, 2010, at 9:02 PM, Peter Otten wrote: > Baba wrote: > > >> Thank You for helping me out. Indeed i am not looking for the code >> but >> rather for hints that direct my reasoning as well as hints as to how >> to write basic programs like this. >> >> You have broken down the approach into 2 parts. I have tried to solve >> part 1 but i'm not quite there yet. Here's my code: >> >> def can_buy(n_nuggets): >> for a in range (1,n_nuggets): >> for b in range (1,n_nuggets): >> for c in range (1,n_nuggets): >> if 6*a+9*b+20*c==n_nuggets: >> #print a,b,c,'n_nuggets=',n_nuggets >> return True >> else: >> return False >> >> >> can_buy(55) >> >> as you can see i am trying to loop through all combinations of values >> bewtween 1 and n_nuggets and when the equation resolves it should >> return True, else it should return False. >> >> I was hoping that when i then call my function and ask it to test a >> value nothing happens. What is wrong? My syntax? My semantic? Both? > > First, the function gives up too early; it should only return False > when all > combinations of a, b, c (technically: the product of the ranges) > have been > tried. > > Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + > 0*20 is > never tried; fix your ranges accordingly. Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and n_nuggets/20 respectively. This will work, but does too much work. Cheers, Roald From p.c.j.kleiweg at rug.nl Thu Aug 12 15:55:47 2010 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Thu, 12 Aug 2010 21:55:47 +0200 Subject: Announcing: python-ghostscript 0.3 In-Reply-To: References: Message-ID: Aahz schreef op de 12e dag van de oogstmaand van het jaar 2010: > In article , > Peter Kleiweg wrote: > >Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010: > > > >> Here is an example for how to use the high-level interface of > >> `python-ghostscript`. This implements a very basic ps2pdf-tool:: > >> > >> import sys > >> import ghostscript > >> > >> args = [ > >> "ps2pdf", # actual value doesn't matter > >> "-dNOPAUSE", "-dBATCH", "-dSAFER", > >> "-sDEVICE=pdfwrite", > >> "-sOutputFile=" + sys.argv[1], > >> "-c", ".setpdfwrite", > >> "-f", sys.argv[2] > >> ] > >> > >> ghostscript.Ghostscript(*args) > > > >How is this different from os.system(' '.join(args)) ? > > You don't have problems with shell metacharacters. Then use os.spawnv(os.P_WAIT, args[0], args) -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From martin.hellwig at dcuktec.org Thu Aug 12 15:56:15 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 12 Aug 2010 20:56:15 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: On 08/11/10 21:14, Baba wrote: How about rephrasing that question in your mind first, i.e.: For every number that is one higher then the previous one*: If this number is dividable by: 6 or 9 or 20 or any combination of 6, 9, 20 than this number _can_ be bought in an exact number else print this number * There are an infinite amount of numbers, just imagine the biggest number you can think of and I say plus 1 :-) Next thing you have to do is figure out how to write this in python, particularly getting all the combinations of divisions can be tricky. Hint; you are not really interested in the division result but rather if a division would be complete or give a remainder (modulo operator). If you get an remainder this could be okay if that can divided by one of the other numbers, and so forth till you ran out of combinations. -- mph From nagle at animats.com Thu Aug 12 16:17:06 2010 From: nagle at animats.com (John Nagle) Date: Thu, 12 Aug 2010 13:17:06 -0700 Subject: Decompressing a file retrieved by URL seems too complex Message-ID: <4c6456cd$0$1623$742ec2ed@news.sonic.net> I'm reading a URL which is a .gz file, and decompressing it. This works, but it seems far too complex. Yet none of the "wrapping" you might expect to work actually does. You can't wrap a GzipFile around an HTTP connection, because GzipFile, reasonably enough, needs random access, and tries to do "seek" and "tell". Nor is the output descriptor from gzip general; it fails on "readline", but accepts "read". (No good reason for that.) So I had to make a second copy. John Nagle def readurl(url) : if url.endswith(".gz") : nd = urllib2.urlopen(url,timeout=TIMEOUTSECS) td1 = tempfile.TemporaryFile() # compressed file td1.write(nd.read()) # fetch and copy file nd.close() # done with network td2 = tempfile.TemporaryFile() # decompressed file td1.seek(0) # rewind gd = gzip.GzipFile(fileobj=td1, mode="rb") # wrap unzip td2.write(gd.read()) # decompress file td1.close() # done with compressed copy td2.seek(0) # rewind return(td2) # return file object for compressed object else : return(urllib2.urlopen(url,timeout=TIMEOUTSECS)) From wherespythonmonks at gmail.com Thu Aug 12 16:18:37 2010 From: wherespythonmonks at gmail.com (wheres pythonmonks) Date: Thu, 12 Aug 2010 16:18:37 -0400 Subject: inline exception handling in python In-Reply-To: <201008122057.03688.thomas@jollybox.de> References: <201008122008.02041.thomas@jollybox.de> <201008122057.03688.thomas@jollybox.de> Message-ID: On Thu, Aug 12, 2010 at 2:57 PM, Thomas Jollans wrote: > On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim: >> [I just hate function call overhead for this.] > > I think you've got your priorities wrong. If you want to avoid unnecessary > overhead, avoid exceptions more than functions. > > -- > http://mail.python.org/mailman/listinfo/python-list > Well I suppose it matters depending on the nature of the data you are looking at... But small function calls tend to be the death of interpreted languages... >>> timeit.timeit(""" def f(y,i): try: return(y/(i%10)) except: return(float("nan")) for i in range(100): x = f(7,i) """) 56.362180419240985 >>> timeit.timeit(""" for i in range(100): try: x = 7 / (i % 10) except: x = float("nan") """) 34.588313601484742 >>> From paddy3118 at googlemail.com Thu Aug 12 16:20:19 2010 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Aug 2010 13:20:19 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class Message-ID: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> I find myself needing to calculate the difference between two Counters or multisets or bags. I want those items that are unique to each bag. I know how to calculate it: >>> b = Counter(a=1, b=2) >>> c = Counter(a=3, b=1) >>> diff = (b - c) + (c - b) >>> (b - c) Counter({'b': 1}) >>> (c - b) Counter({'a': 2}) >>> diff Counter({'a': 2, 'b': 1}) But thought why doesn't this operation appear already as a method of the class? - Paddy. From news1234 at free.fr Thu Aug 12 16:28:09 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 22:28:09 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> Message-ID: <4C645959.7010207@free.fr> Hi Baba, The last tips should really help you getting started: for testing your function you could do: Below your uncorrected code and a test for it def can_buy(n_nuggets): for a in range (1,n_nuggets): for b in range (1,n_nuggets): for c in range (1,n_nuggets): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True else: return False # show the results for the first 50 numbers. for n in xrange(50): result = can_buy(n) # get the result (see Brian's comment) print("result of can_buy(%2d) is %s" % (n,result)) with the print statement in can_buy() you should immediately see some issues. as soon as can_buy seems to work, you could comment the print statement. Additionally: I would return [a,b,c] if you got a result and [] if you got no result. So you don't only seem whether you can buy n nuggets, but you can also see how (AND even verify the solution) the print statement should show you what Peter said. You just make one test and return immediately in the else statement Instead you should continue until you found a solution or until you tried all possibilities. After having fixed the fact, that you don't try all options, you'll see that your first success would be with 6+9+12 = 27 nuggets es you never try with 0 boxes of a kind. (as Peter mentioned) Finally as Roald says. if you can reduce the upper limit of your search ranges. if you have for example 13 nuggets you do not have to try 3 boxes of 6 as this is already 18, so trying only 0,1 or two boxes is enough You will now also see, what On 08/12/2010 09:42 PM, Roald de Vries wrote: > > On Aug 12, 2010, at 9:02 PM, Peter Otten wrote: > >> Baba wrote: >> >> >>> Thank You for helping me out. Indeed i am not looking for the code but >>> rather for hints that direct my reasoning as well as hints as to how >>> to write basic programs like this. >>> >>> You have broken down the approach into 2 parts. I have tried to solve >>> part 1 but i'm not quite there yet. Here's my code: >>> >>> def can_buy(n_nuggets): >>> for a in range (1,n_nuggets): >>> for b in range (1,n_nuggets): >>> for c in range (1,n_nuggets): >>> if 6*a+9*b+20*c==n_nuggets: >>> #print a,b,c,'n_nuggets=',n_nuggets >>> return True >>> else: >>> return False >>> >>> >>> can_buy(55) >>> >>> as you can see i am trying to loop through all combinations of values >>> bewtween 1 and n_nuggets and when the equation resolves it should >>> return True, else it should return False. >>> >>> I was hoping that when i then call my function and ask it to test a >>> value nothing happens. What is wrong? My syntax? My semantic? Both? >> >> First, the function gives up too early; it should only return False >> when all >> combinations of a, b, c (technically: the product of the ranges) have >> been >> tried. >> >> Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + >> 0*20 is >> never tried; fix your ranges accordingly. > > Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and > n_nuggets/20 respectively. This will work, but does too much work. > > Cheers, Roald > From jdnier at gmail.com Thu Aug 12 16:28:26 2010 From: jdnier at gmail.com (David Niergarth) Date: Thu, 12 Aug 2010 13:28:26 -0700 (PDT) Subject: default behavior References: Message-ID: <0272074b-8508-4b7a-a11e-3f004506f522@v41g2000yqv.googlegroups.com> Peter Otten <__pete... at web.de> wrote: > > >>> 1 .conjugate() > This is a syntax I never noticed before. My built-in complier (eyes) took one look and said: "that doesn't work." Has this always worked in Python but I never noticed? I see other instance examples also work. >>> '1' .zfill(2) '01' >>> 1.0 .is_integer() True and properties >>> 1.0 .real 1.0 Curiously, this works From news1234 at free.fr Thu Aug 12 16:35:12 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 22:35:12 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <4C645959.7010207@free.fr> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> Message-ID: <4C645B00.7090808@free.fr> One more small tip to verify whether your code is working: On 08/12/2010 10:28 PM, News123 wrote: > Hi Baba, Your code, but returning the result as suggested in my preious post: > def can_buy(n_nuggets): > for a in range (1,n_nuggets): > for b in range (1,n_nuggets): > for c in range (1,n_nuggets): > print "trying for %2d: %2d %2d %2d" % (n,a,b,c) > if 6*a+9*b+20*c==n_nuggets: > return [a,b,c] > else: > return [] > # show the results for the first 50 numbers. # and verify whether it's true for n in xrange(50): result = can_buy(n) # get the result (see Brian's commen print("result of can_buy(%2d) is %s" % (n,result)) if result: a,b,c = result if a*6+b*9+c*12 != n: print "ERROR: can_buy() gives wrong result" Alternatively you can use a nice python feature called asserts assert statements can be used to vrify whether your code works as expected. Nothing will be printed if the assertion is correct otherwise your program will abort and print the assertion error: Example: for n in xrange(50): result = can_buy(n) # get the result (see Brian's commen print("result of can_buy(%2d) is %s" % (n,result)) if result: a,b,c = result assert a*6+b*9+c*12 == n > > > with the print statement in can_buy() you should immediately see some > issues. > as soon as can_buy seems to work, you could comment the print statement. > > > Additionally: > I would return [a,b,c] if you got a result > and [] if you got no result. > > So you don't only seem whether you can buy n nuggets, but you can also > see how (AND even verify the solution) > > > the print statement should show you what Peter said. > You just make one test and return immediately in the else statement > > Instead you should continue until you found a solution or until you > tried all possibilities. > > After having fixed the fact, that you don't try all options, you'll see > that your first success would be with 6+9+12 = 27 nuggets es you never > try with 0 boxes of a kind. (as Peter mentioned) > > Finally as Roald says. > > if you can reduce the upper limit of your search ranges. > if you have for example 13 nuggets you do not have to try 3 boxes of 6 > as this is already 18, so trying only 0,1 or two boxes is enough > > > > > > > > You will now also see, what > On 08/12/2010 09:42 PM, Roald de Vries wrote: >> >> On Aug 12, 2010, at 9:02 PM, Peter Otten wrote: >> >>> Baba wrote: >>> >>> >>>> Thank You for helping me out. Indeed i am not looking for the code but >>>> rather for hints that direct my reasoning as well as hints as to how >>>> to write basic programs like this. >>>> >>>> You have broken down the approach into 2 parts. I have tried to solve >>>> part 1 but i'm not quite there yet. Here's my code: >>>> >>>> def can_buy(n_nuggets): >>>> for a in range (1,n_nuggets): >>>> for b in range (1,n_nuggets): >>>> for c in range (1,n_nuggets): >>>> if 6*a+9*b+20*c==n_nuggets: >>>> #print a,b,c,'n_nuggets=',n_nuggets >>>> return True >>>> else: >>>> return False >>>> >>>> >>>> can_buy(55) >>>> >>>> as you can see i am trying to loop through all combinations of values >>>> bewtween 1 and n_nuggets and when the equation resolves it should >>>> return True, else it should return False. >>>> >>>> I was hoping that when i then call my function and ask it to test a >>>> value nothing happens. What is wrong? My syntax? My semantic? Both? >>> >>> First, the function gives up too early; it should only return False >>> when all >>> combinations of a, b, c (technically: the product of the ranges) have >>> been >>> tried. >>> >>> Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + >>> 0*20 is >>> never tried; fix your ranges accordingly. >> >> Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and >> n_nuggets/20 respectively. This will work, but does too much work. >> >> Cheers, Roald >> > From jdnier at gmail.com Thu Aug 12 16:37:04 2010 From: jdnier at gmail.com (David Niergarth) Date: Thu, 12 Aug 2010 13:37:04 -0700 (PDT) Subject: default behavior References: <0272074b-8508-4b7a-a11e-3f004506f522@v41g2000yqv.googlegroups.com> Message-ID: [Oops, now complete...] Peter Otten <__pete... at web.de> wrote: > > > >>> 1 .conjugate() > This is a syntax I never noticed before. My built-in complier (eyes) took one look and said: "that doesn't work." Has this always worked in Python but I never noticed? I see other instance examples also work. ? >>> '1' .zfill(2) ? '01' ? >>> 1.0 .is_integer() ? True and properties ? >>> 1.0 .real ? 1.0 Curiously, a float literal works without space >>> 1.0.conjugate() 1.0 but not an int. >>> 1.conjugate() File "", line 1 1.conjugate() ^ SyntaxError: invalid syntax Anyway, I didn't realize int has a method you can call. --David From thomas at jollybox.de Thu Aug 12 16:37:30 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 22:37:30 +0200 Subject: shelf-like list? In-Reply-To: References: Message-ID: <201008122237.30461.thomas@jollybox.de> On Tuesday 10 August 2010, it occurred to kj to exclaim: > I'm looking for a module that implements "persistent lists": objects > that behave like lists except that all their elements are stored > on disk. IOW, the equivalent of "shelves", but for lists rather > than a dictionaries. > > Does anyone know of such a module? > > (I suppose that I could slap together a crude implementation of > such a thing by wrapping a shelf with suitable methods to simulate > the list interface. But I'd rather not roll my own if a tested > implementation already exist.) You could simply use pickle to save the data every once in a while. From nagle at animats.com Thu Aug 12 16:40:14 2010 From: nagle at animats.com (John Nagle) Date: Thu, 12 Aug 2010 13:40:14 -0700 Subject: Decompressing a file retrieved by URL seems too complex Message-ID: <4c645c39$0$1595$742ec2ed@news.sonic.net> (Repost with better indentation) I'm reading a URL which is a .gz file, and decompressing it. This works, but it seems far too complex. Yet none of the "wrapping" you might expect to work actually does. You can't wrap a GzipFile around an HTTP connection, because GzipFile, reasonably enough, needs random access, and tries to do "seek" and "tell". Nor is the output descriptor from gzip general; it fails on "readline", but accepts "read". (No good reason for that.) So I had to make a second copy. John Nagle def readurl(url) : if url.endswith(".gz") : nd = urllib2.urlopen(url,timeout=TIMEOUTSECS) td1 = tempfile.TemporaryFile() # compressed file td1.write(nd.read()) # fetch and copy file nd.close() # done with network td2 = tempfile.TemporaryFile() # decompressed file td1.seek(0) # rewind gd = gzip.GzipFile(fileobj=td1, mode="rb") # wrap unzip td2.write(gd.read()) # decompress file td1.close() # done with compressed copy td2.seek(0) # rewind return(td2) # return file object for compressed object else : return(urllib2.urlopen(url,timeout=TIMEOUTSECS)) From news1234 at free.fr Thu Aug 12 16:41:32 2010 From: news1234 at free.fr (News123) Date: Thu, 12 Aug 2010 22:41:32 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: <4c645c7c$0$3675$426a74cc@news.free.fr> On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: > On 08/11/10 21:14, Baba wrote: > > > How about rephrasing that question in your mind first, i.e.: > > For every number that is one higher then the previous one*: > If this number is dividable by: > 6 or 9 or 20 or any combination of 6, 9, 20 > than this number _can_ be bought in an exact number > else > print this number > you are allowed to mix. 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 I guess, trying to find the result with divisions and remainders is overly complicated. Simple brute force trial to find a combination shall be enough. Also: if you know for example, that you can buy 101,102,103,104,105 and 106 nuggets, then you know, that you can buy any other larger amout of nuggets. 107 = 101 + one box of six 108 = 102 + one box of six . . . As soon as you found 6 sequential solutions you can stop searching. From bradley.h at aggiemail.usu.edu Thu Aug 12 16:43:40 2010 From: bradley.h at aggiemail.usu.edu (Bradley Hintze) Date: Thu, 12 Aug 2010 16:43:40 -0400 Subject: Floating numbers Message-ID: Hi all. Is there a way I can keep my floating point number as I typed it? For example, I want 34.52 to be 34.52 and NOT 34.5200000002. -- Bradley J. Hintze Graduate Student Duke University School of Medicine 801-712-8799 From jjposner at optimum.net Thu Aug 12 16:51:05 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 12 Aug 2010 16:51:05 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: <4C645EB9.7060105@optimum.net> On 8/12/2010 9:22 AM, Dave Angel wrote: >> >> Now you have to find the largest number below 120, which you can >> easily do with brute force Dept of overkill, iterators/generators division ... -John #------------------ from itertools import imap, product, ifilter from operator import mul box_sizes = (6, 9, 20) def sum_product(s1, s2): """ return "scalar product" of two sequences """ return sum(imap(mul, s1, s2)) def reachables(target): """ return generator of numbers that are <= target and are valid linear combos of McNuggets """ candidate_box_counts = product( xrange(target/box_sizes[0] + 1), xrange(target/box_sizes[1] + 1), xrange(target/box_sizes[2] + 1), ) gen = (sum_product(box_sizes, tup) for tup in candidate_box_counts) return (ifilter(lambda val, tgt=target: val < tgt, gen)) if __name__ == "__main__": tgt = 120 # thanks, Dave Angel unreachables = set(xrange(tgt)) - set(reachables(tgt)) print "Max unreachable:", max(unreachables) From __peter__ at web.de Thu Aug 12 16:52:03 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 22:52:03 +0200 Subject: default behavior References: <0272074b-8508-4b7a-a11e-3f004506f522@v41g2000yqv.googlegroups.com> Message-ID: David Niergarth wrote: > [Oops, now complete...] > Peter Otten <__pete... at web.de> wrote: >> >> > >>> 1 .conjugate() >> > This is a syntax I never noticed before. My built-in complier (eyes) > took one look and said: "that doesn't work." (1).conjugate may hurt a little less. Anyway, the space is only needed for the tokenizer that without it would produce a float immediately followed by a name. > Has this always worked in > Python but I never noticed? Probably. > I see other instance examples also work. > > >>> '1' .zfill(2) > '01' > >>> 1.0 .is_integer() > True > > and properties > > >>> 1.0 .real > 1.0 > > Curiously, a float literal works without space > > >>> 1.0.conjugate() > 1.0 > > but not an int. > > >>> 1.conjugate() > File "", line 1 > 1.conjugate() > ^ > SyntaxError: invalid syntax > > Anyway, I didn't realize int has a method you can call. > > --David From fuglyducky at gmail.com Thu Aug 12 17:06:46 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Thu, 12 Aug 2010 14:06:46 -0700 (PDT) Subject: re.sub and variables Message-ID: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> I have a function that I am attempting to call from another file. I am attempting to replace a string using re.sub with another string. The problem is that the second string is a variable. When I get the output, it shows the variable name rather than the value. Is there any way to pass a variable into a regex? If not, is there any other way to do this? I need to be able to dump the variable value into the replacement string. For what it's worth this is an XML file so I'm not afraid to use some sort of XML library but they look fairly complicated for a newbie like me. Also, this is py3.1.2 is that makes any difference. Thanks!!! ##################################################### import random import re import datetime def pop_time(some_string, start_time): global that_string rand_time = random.randint(0, 30) delta_time = datetime.timedelta(seconds=rand_time) for line in some_string: end_time = delta_time + start_time new_string = re.sub("thisstring", "thisstring\\end_time", some_string) start_time = end_time return new_string From invalid at invalid.invalid Thu Aug 12 17:20:18 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 12 Aug 2010 21:20:18 +0000 (UTC) Subject: Floating numbers References: Message-ID: On 2010-08-12, Bradley Hintze wrote: > Is there a way I can keep my floating point number as I typed it? No. > For example, I want 34.52 to be 34.52 and NOT 34.5200000002. You can't represent 34.52 using base-2 IEEE floating point (the HW floating point format used by pretty much all modern computers). 34.5200000002 is as close as you can get. When you enter a base-10 floating-point number, the computer will use the closest base-2 IEEE floating point number. Here are the nitty-gritty details: http://docs.sun.com/source/806-3568/ncg_goldberg.html Can you explain what your actual problem is? -- Grant Edwards grant.b.edwards Yow! I'm imagining a surfer at van filled with soy sauce! gmail.com From gherron at islandtraining.com Thu Aug 12 17:23:37 2010 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 12 Aug 2010 14:23:37 -0700 Subject: Floating numbers In-Reply-To: References: Message-ID: <4C646659.6010500@islandtraining.com> On 08/12/2010 01:43 PM, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. > > Is this a Python question? The answer is both Yes and No. The binary floating point representation of numbers on a computer cannot exactly represent most decimal number you would like to type. (Similar to the fact that you cannot represent 1/3 exactly in a decimal system.) But that's the internal representation, over which you have no control. You do, however, have control over how a number is displayed when printed. Python 2: Choose a format that displays the exact number of digits you want '%.2f' % a or let str(a) choose but not repr(a) which tries to get all the digits. (Adding to the confusion, you might also find it confusing to understand which of str() or repr() Python chooses to display a number.) Python 3: Python3 uses David Gay?s algorithm for chosing how to display floats. Both str(a) and repr(a) produce '34.52' for your example, which is probably just what you want. Gary Herron From invalid at invalid.invalid Thu Aug 12 17:24:14 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 12 Aug 2010 21:24:14 +0000 (UTC) Subject: Floating numbers References: Message-ID: On 2010-08-12, Grant Edwards wrote: > On 2010-08-12, Bradley Hintze wrote: > >> Is there a way I can keep my floating point number as I typed it? > > No. > >> For example, I want 34.52 to be 34.52 and NOT 34.5200000002. > > You can't represent 34.52 using base-2 IEEE floating point (the HW > floating point format used by pretty much all modern computers). > 34.5200000002 is as close as you can get. > > When you enter a base-10 floating-point number, the computer will use > the closest base-2 IEEE floating point number. > > Here are the nitty-gritty details: > > http://docs.sun.com/source/806-3568/ncg_goldberg.html Here is a gentler intro: http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate -- Grant Edwards grant.b.edwards Yow! If I felt any more at SOPHISTICATED I would DIE gmail.com of EMBARRASSMENT! From thomas at jollybox.de Thu Aug 12 17:24:48 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 23:24:48 +0200 Subject: Floating numbers In-Reply-To: References: Message-ID: <201008122324.49315.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to Bradley Hintze to exclaim: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. The conversion from decimal to binary and vice versa is inexact -- but they're the same number internally: Python 2.6.6rc1+ (r266rc1:83691, Aug 5 2010, 17:07:04) [GCC 4.4.5 20100728 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 34.52 34.520000000000003 >>> 34.520000000000003 == 34.52 True >>> Python 3 is a bit smarter when printing, so you don't really notice what's going on: Python 3.1.2 (release31-maint, Jul 8 2010, 09:18:08) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 34.52 34.52 >>> 34.520000000000003 34.52 >>> From philip at semanchuk.com Thu Aug 12 17:25:07 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 12 Aug 2010 17:25:07 -0400 Subject: Floating numbers In-Reply-To: References: Message-ID: <4A61DB54-FEC5-4649-B7FD-8C01EB650102@semanchuk.com> On Aug 12, 2010, at 4:43 PM, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. Hi Bradley, Use the Decimal type instead. It's not as convenient as float, but it will give you a consistent representation of your numbers. The behavior of floating point numbers surprises a lot of people and has been discussed at length a number of times here (and elsewhere). If you're in the mood for EXTREMELY thorough coverage of the subject, you can read this: http://docs.sun.com/source/806-3568/ncg_goldberg.html There's a gentler discussion of it here: http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding HTH Philip From invalid at invalid.invalid Thu Aug 12 17:25:13 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 12 Aug 2010 21:25:13 +0000 (UTC) Subject: Floating numbers References: Message-ID: On 2010-08-12, Grant Edwards wrote: >> Here are the nitty-gritty details: >> >> http://docs.sun.com/source/806-3568/ncg_goldberg.html > > Here is a gentler intro: > > http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate And another good page: http://docs.python.org/tutorial/floatingpoint.html -- Grant Edwards grant.b.edwards Yow! I feel like I'm at in a Toilet Bowl with a gmail.com thumbtack in my forehead!! From clp2 at rebertia.com Thu Aug 12 17:28:41 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 12 Aug 2010 14:28:41 -0700 Subject: Floating numbers In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 1:43 PM, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. See also: http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding Another option is to use the `decimal` module, which *can* exactly represent decimal numbers (to a user-specified finite precision) and is generally a bit more intuitive but /substantially/ slower: http://docs.python.org/library/decimal.html Cheers, Chris -- http://blog.rebertia.com From lists at cheimes.de Thu Aug 12 17:30:54 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 12 Aug 2010 23:30:54 +0200 Subject: Floating numbers In-Reply-To: References: Message-ID: > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. This isn't a Python issue. Python uses IEEE 754 [1] double precision floats like most other languages. 34.52 can't be stored in a float. The next valid float is 34.5200000002. Christian [1] http://en.wikipedia.org/wiki/IEEE_754 From fuglyducky at gmail.com Thu Aug 12 17:33:28 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Thu, 12 Aug 2010 14:33:28 -0700 (PDT) Subject: re.sub and variables References: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> Message-ID: On Aug 12, 2:06?pm, fuglyducky wrote: > I have a function that I am attempting to call from another file. I am > attempting to replace a string using re.sub with another string. The > problem is that the second string is a variable. When I get the > output, it shows the variable name rather than the value. Is there any > way to pass a variable into a regex? > > If not, is there any other way to do this? I need to be able to dump > the variable value into the replacement string. > > For what it's worth this is an XML file so I'm not afraid to use some > sort of XML library but they look fairly complicated for a newbie like > me. > > Also, this is py3.1.2 is that makes any difference. > > Thanks!!! > > ##################################################### > > import random > import re > import datetime > > def pop_time(some_string, start_time): > ? ? global that_string > > ? ? rand_time = random.randint(0, 30) > ? ? delta_time = datetime.timedelta(seconds=rand_time) > > ? ? for line in some_string: > ? ? ? ? end_time = delta_time + start_time > ? ? ? ? new_string = re.sub("thisstring", "thisstring\\end_time", > some_string) > ? ? ? ? start_time = end_time > > ? ? return new_string Disregard...I finally figured out how to use string.replace. That appears to work perfectly. Still...if anyone happens to know about passing a variable into a regex that would be great. From hexamorph at gmx.net Thu Aug 12 17:38:10 2010 From: hexamorph at gmx.net (Hexamorph) Date: Thu, 12 Aug 2010 23:38:10 +0200 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c5d6955$0$28666$c3e8da3@news.astraweb.com> <6bb8251f-f205-4732-b46c-35ba80720307@x25g2000yqj.googlegroups.com> Message-ID: <4C6469C2.8070408@gmx.net> Terry Reedy wrote: > On 8/9/2010 11:16 AM, Grant Edwards wrote: Just for the record: I sincerely apologize for my rant. I usually don't loose control so heavily, but this "Rick" person makes me mad (killfile'd now) >> IOW, the "Ugly American". No! That's not what I said. I'm myself one of those "bad germans" and I *entirely* agree with Mr. Reedy's comment: > Stereotypically bashing "Americans" is as ugly and obnoxious as bashing > any other ethnic group. I have traveled the world and Americans are no > worse, but are pretty much the same mix of good and bad. It is certainly > off-topic and inappropriate for this group. From thomas at jollybox.de Thu Aug 12 17:40:27 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 12 Aug 2010 23:40:27 +0200 Subject: Decompressing a file retrieved by URL seems too complex In-Reply-To: <4c645c39$0$1595$742ec2ed@news.sonic.net> References: <4c645c39$0$1595$742ec2ed@news.sonic.net> Message-ID: <201008122340.27823.thomas@jollybox.de> On Thursday 12 August 2010, it occurred to John Nagle to exclaim: > (Repost with better indentation) Good, good. > > def readurl(url) : > if url.endswith(".gz") : The file name could be anything. You should be checking the reponse Content- Type header -- that's what it's for. > nd = urllib2.urlopen(url,timeout=TIMEOUTSECS) > td1 = tempfile.TemporaryFile() # compressed file You can keep the whole thing in memory by using StringIO. > td1.write(nd.read()) # fetch and copy file You're reading the entire fire into memory anyway ;-) > nd.close() # done with network > td2 = tempfile.TemporaryFile() # decompressed file Okay, maybe there is somthing missing from GzipFile -- but still you could use StringIO again, I expect. > Nor is the output descriptor from gzip general; it fails > on "readline", but accepts "read". >>> from gzip import GzipFile >>> GzipFile.readline >>> GzipFile.readlines >>> GzipFile.__iter__ >>> What exactly is it that's failing, and how? > td1.seek(0) # rewind > gd = gzip.GzipFile(fileobj=td1, mode="rb") # wrap unzip > td2.write(gd.read()) # decompress file > td1.close() # done with compressed copy > td2.seek(0) # rewind > return(td2) # return file object for compressed object > else : > return(urllib2.urlopen(url,timeout=TIMEOUTSECS)) From carey.tilden at gmail.com Thu Aug 12 17:46:07 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Thu, 12 Aug 2010 14:46:07 -0700 Subject: inline exception handling in python In-Reply-To: References: <201008122008.02041.thomas@jollybox.de> <201008122057.03688.thomas@jollybox.de> Message-ID: On Thu, Aug 12, 2010 at 1:18 PM, wheres pythonmonks wrote: > Well I suppose it matters depending on the nature of the data you are > looking at... ?But small function calls tend to be the death of interpreted > languages... I would be interested to see a real application that had performance negatively impacted by function call overhead. Sure, it's easy to measure in micro benchmarks, but what about profiling a real application? Carey From news1234 at free.fr Thu Aug 12 18:31:58 2010 From: news1234 at free.fr (News123) Date: Fri, 13 Aug 2010 00:31:58 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: <4c64765e$0$28580$426a74cc@news.free.fr> On 08/12/2010 10:51 PM, John Posner wrote: > On 8/12/2010 9:22 AM, Dave Angel wrote: >>> >>> Now you have to find the largest number below 120, which you can >>> easily do with brute force > > Dept of overkill, iterators/generators division ... > > -John > > #------------------ > from itertools import imap, product, ifilter > from operator import mul > > box_sizes = (6, 9, 20) > > def sum_product(s1, s2): > """ > return "scalar product" of two sequences > """ > return sum(imap(mul, s1, s2)) > > def reachables(target): > """ > return generator of numbers that are <= target > and are valid linear combos of McNuggets > """ > candidate_box_counts = product( > xrange(target/box_sizes[0] + 1), > xrange(target/box_sizes[1] + 1), > xrange(target/box_sizes[2] + 1), > ) Couldn't this be rewritten as: candidate_box_counts = product( * [ xrange(target/sizes + 1) for size in box_sizes ] ) > > gen = (sum_product(box_sizes, tup) > for tup in candidate_box_counts) > > return (ifilter(lambda val, tgt=target: val < tgt, > gen)) > > if __name__ == "__main__": > tgt = 120 # thanks, Dave Angel > unreachables = set(xrange(tgt)) - set(reachables(tgt)) > print "Max unreachable:", max(unreachables) From missive at hotmail.com Thu Aug 12 18:53:31 2010 From: missive at hotmail.com (Lee Harr) Date: Fri, 13 Aug 2010 03:23:31 +0430 Subject: segfault with small pyqt script Message-ID: > I'm desperate. I'm having a real application, which fails rather often > when finishing it. I'm not sure, whether any serious problem could be > hidden behind it > > The script is a pyqt script, which segfaults most of the time on my > ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. Looks to be a known issue: http://www.google.com/search?q=pyqt+segfault+on+exit https://launchpad.net/bugs/561303 The last activity on that bug is almost 2 months ago... Hopefully the fix will be distributed soon. From bavantgarde at yahoo.com Thu Aug 12 18:57:50 2010 From: bavantgarde at yahoo.com (BAvant Garde) Date: Thu, 12 Aug 2010 15:57:50 -0700 (PDT) Subject: unicode string alteration In-Reply-To: <4C642FF1.1050508@mrabarnett.plus.com> Message-ID: <156365.97065.qm@web83402.mail.sp1.yahoo.com> Thanks MRAB, I'll have to do some reading about unicode surrogates. Also need to research which python versions/platforms are narrow builds and which are wide. Much to learn here. Thanks!? --- On Thu, 8/12/10, MRAB wrote: From: MRAB Subject: Re: unicode string alteration To: python-list at python.org Date: Thursday, August 12, 2010, 12:31 PM BAvant Garde wrote: > HELP!!! > I need help with a unicode issue that has me stumped. I must be doing something? wrong because I don't believe this condition would have slipped thru testing. > > Wherever the string u'\udbff\udc00' occurs u'\U0010fc00' or unichr(1113088) is substituted and the file loses 1 character resulting in all trailing characters being shifted out of position. No other corrupt strings have been detected. >? ? The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04 where the maximum ord # is 1114111 (wide Python build). >? ? Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535 (narrow Python build) the string u'\U0010fc00' also occurs and it "seems" that the substitution takes place but no characters are lost and file sizes are ok. Note that ord(u'\U0010fc00') causes the following error: >? ? ? ? ? ? ? "TypeError: ord() expected a character, but string of length 2 found" > The condition is otherwise invisible in 2.5.4 and is handled internally without any apparent effect on processing with characters u'\udbff' and u'\udc00' each being separately accessible. > > The first part of the attachment repeats this email but also has examples and illustrates other related oddities. >? ? Any help would be greatly appreciated. > It's not an error, it's a "surrogate pair". Surrogate pairs are part of the Unicode specification. Unicode codepoints go up to U+0010FFFF. If you're using 16 bits per codepoint, like in a narrow build of Python, then the codepoints above U+FFFF _can't_ be represented directly, so they are represented by a pair of codepoints called a "surrogate pair". If, on the other hand, you're using 32 bits per codepoint, like in a wide build of Python, then the codepoints above U+FFFF _can_ be represented directly, so surrogate pairs aren't needed, and, indeed shouldn't be there. What you're seeing in the wide build is Python replacing a surrogate pair with the codepoint that it represents, which is actually the right thing to do because, as I said, the surrogate pairs really shouldn't be there. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From bsalter01 at earthlink.net Thu Aug 12 19:09:10 2010 From: bsalter01 at earthlink.net (Brian Salter) Date: Thu, 12 Aug 2010 16:09:10 -0700 Subject: Importing libs on Windows? Message-ID: I've seen a number of tutorials that describe how to bring in a dll in python, but does anybody know of a tutorial for how to bring in a lib? Is it even possible? Thanks, in advance! From sjmachin at lexicon.net Thu Aug 12 19:14:57 2010 From: sjmachin at lexicon.net (John Machin) Date: Thu, 12 Aug 2010 16:14:57 -0700 (PDT) Subject: re.sub and variables References: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> Message-ID: <380d19dc-5aa3-426b-af04-cc2a35ef8d04@m35g2000prn.googlegroups.com> On Aug 13, 7:33?am, fuglyducky wrote: > On Aug 12, 2:06?pm, fuglyducky wrote: > > > > > I have a function that I am attempting to call from another file. I am > > attempting to replace a string using re.sub with another string. The > > problem is that the second string is a variable. When I get the > > output, it shows the variable name rather than the value. Is there any > > way to pass a variable into a regex? > > > If not, is there any other way to do this? I need to be able to dump > > the variable value into the replacement string. > > > For what it's worth this is an XML file so I'm not afraid to use some > > sort of XML library but they look fairly complicated for a newbie like > > me. > > > Also, this is py3.1.2 is that makes any difference. > > > Thanks!!! > > > ##################################################### > > > import random > > import re > > import datetime > > > def pop_time(some_string, start_time): > > ? ? global that_string > > > ? ? rand_time = random.randint(0, 30) > > ? ? delta_time = datetime.timedelta(seconds=rand_time) > > > ? ? for line in some_string: > > ? ? ? ? end_time = delta_time + start_time > > ? ? ? ? new_string = re.sub("thisstring", "thisstring\\end_time", > > some_string) > > ? ? ? ? start_time = end_time > > > ? ? return new_string > > Disregard...I finally figured out how to use string.replace. That > appears to work perfectly. Still...if anyone happens to know about > passing a variable into a regex that would be great. Instead of new_string = re.sub( "thisstring", "thisstring\\end_time", some_string) you probably meant to use something like new_string = re.sub( "thisstring", "thisstring" + "\\" + end_time, some_string) string.replace is antique and deprecated. You should be using methods of str objects, not functions in the string module. >>> s1 = "foobarzot" >>> s2 = s1.replace("bar", "-") >>> s2 'foo-zot' >>> From gherron at islandtraining.com Thu Aug 12 19:46:38 2010 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 12 Aug 2010 16:46:38 -0700 Subject: Importing libs on Windows? In-Reply-To: References: Message-ID: <4C6487DE.2070202@islandtraining.com> On 08/12/2010 04:09 PM, Brian Salter wrote: > I've seen a number of tutorials that describe how to bring in a dll in > python, but does anybody know of a tutorial for how to bring in a > lib? Is it even possible? > > Thanks, in advance! > > Look at the Python module named ctypes: http://docs.python.org/library/ctypes.html Gary Herron From bsalter01 at earthlink.net Thu Aug 12 20:52:33 2010 From: bsalter01 at earthlink.net (Brian Salter) Date: Thu, 12 Aug 2010 17:52:33 -0700 Subject: Importing libs on Windows? In-Reply-To: References: Message-ID: It appears that every example is calling a dll, and I'm looking to bring in a lib. Does ctypes work with libs too? "Gary Herron" wrote in message news:mailman.2044.1281656800.1673.python-list at python.org... > On 08/12/2010 04:09 PM, Brian Salter wrote: >> I've seen a number of tutorials that describe how to bring in a dll in >> python, but does anybody know of a tutorial for how to bring in a lib? >> Is it even possible? >> >> Thanks, in advance! >> >> > > Look at the Python module named ctypes: > http://docs.python.org/library/ctypes.html > > Gary Herron > > From nad at acm.org Thu Aug 12 21:14:10 2010 From: nad at acm.org (Ned Deily) Date: Thu, 12 Aug 2010 18:14:10 -0700 Subject: Floating numbers References: Message-ID: In article , Christian Heimes wrote: >> Is there a way I can keep my floating point number as I typed it? For >> example, I want 34.52 to be 34.52 and NOT 34.5200000002. > This isn't a Python issue. Python uses IEEE 754 [1] double precision > floats like most other languages. 34.52 can't be stored in a float. The > next valid float is 34.5200000002. Well, it is a *bit* of a Python issue since, as others have pointed out, Python's behavior has changed due to the implementation of Gay's rounding algorithm in 3.1 and also in 2.7: $ python2.6 -c 'print(repr(34.52))' 34.520000000000003 $ python2.7 -c 'print(repr(34.52))' 34.52 $ python3.1 -c 'print(repr(34.52))' 34.52 -- Ned Deily, nad at acm.org From benjamin.kaplan at case.edu Thu Aug 12 21:19:40 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 12 Aug 2010 18:19:40 -0700 Subject: Floating numbers In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 6:14 PM, Ned Deily wrote: > In article , > ?Christian Heimes wrote: >>> Is there a way I can keep my floating point number as I typed it? For >>> example, I want 34.52 to be 34.52 and NOT 34.5200000002. >> This isn't a Python issue. Python uses IEEE 754 [1] double precision >> floats like most other languages. 34.52 can't be stored in a float. The >> next valid float is 34.5200000002. > > Well, it is a *bit* of a Python issue since, as others have pointed out, > Python's behavior has changed due to the implementation of Gay's > rounding algorithm in 3.1 and also in 2.7: > > $ python2.6 -c 'print(repr(34.52))' > 34.520000000000003 > $ python2.7 -c 'print(repr(34.52))' > 34.52 > $ python3.1 -c 'print(repr(34.52))' > 34.52 > But that's not keeping the number the way it was typed. It's just not showing you the exact approximation. It doesn't get rid of rounding errors. >>> 34.52 34.52 >>> >>> _ * 10**10 345200000000.00006 > -- > ?Ned Deily, > ?nad at acm.org > > -- > http://mail.python.org/mailman/listinfo/python-list > From tycho at tycho.ws Thu Aug 12 21:40:30 2010 From: tycho at tycho.ws (Tycho Andersen) Date: Thu, 12 Aug 2010 20:40:30 -0500 Subject: Importing libs on Windows? In-Reply-To: References: Message-ID: <20100813014030.GT1506@mittens.Belkin> On Thu, Aug 12, 2010 at 04:09:10PM -0700, Brian Salter wrote: > I've seen a number of tutorials that describe how to bring in a dll > in python, but does anybody know of a tutorial for how to bring in a > lib? Is it even possible? I don't know if it's possible, but why do you want to do it? .lib files in Windows are static libraries, which traditionally aren't loaded dynamically. Is there some reason you can't use a DLL? \t From steve at REMOVE-THIS-cybersource.com.au Thu Aug 12 22:03:48 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 02:03:48 GMT Subject: re.sub and variables References: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> Message-ID: <4c64a804$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 14:33:28 -0700, fuglyducky wrote: > if anyone happens to know about > passing a variable into a regex that would be great. The same way you pass anything into any string. Regexes are ordinary strings. If you want to construct a string from a variable t = "orl", you can do any of these: "Hello w" + t + "d" "".join(["Hello", " ", "w", t, "d"]) "Hello w%sd" % t "Hello %s" % ("w" + t + "d") "Hello w%(var)sd" % {"var": t} "Hello wSPAMd".replace("SPAM", t) or many other variations. Constructing a regex is no different. -- Steven From nad at acm.org Thu Aug 12 22:10:38 2010 From: nad at acm.org (Ned Deily) Date: Thu, 12 Aug 2010 19:10:38 -0700 Subject: Floating numbers References: Message-ID: In article , Benjamin Kaplan wrote: > > Well, it is a *bit* of a Python issue since, as others have pointed out, > > Python's behavior has changed due to the implementation of Gay's > > rounding algorithm in 3.1 and also in 2.7: > > > > $ python2.6 -c 'print(repr(34.52))' > > 34.520000000000003 > > $ python2.7 -c 'print(repr(34.52))' > > 34.52 > > $ python3.1 -c 'print(repr(34.52))' > > 34.52 > But that's not keeping the number the way it was typed. It's just not > showing you the exact approximation. It doesn't get rid of rounding > errors. > >>> 34.52 > 34.52 > >>> >>> _ * 10**10 > 345200000000.00006 Yes, as discussed earlier in this thread and I didn't mean to imply otherwise. I should have worded my comment differently: the main reason for making it was to point out that the new float repr format feature is also in 2.7. -- Ned Deily, nad at acm.org From python at mrabarnett.plus.com Thu Aug 12 22:20:30 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Aug 2010 03:20:30 +0100 Subject: re.sub and variables In-Reply-To: <4c64a804$0$28668$c3e8da3@news.astraweb.com> References: <58082166-3f4c-4744-922c-3de6289b1b0d@q21g2000prm.googlegroups.com> <4c64a804$0$28668$c3e8da3@news.astraweb.com> Message-ID: <4C64ABEE.5040302@mrabarnett.plus.com> Steven D'Aprano wrote: > On Thu, 12 Aug 2010 14:33:28 -0700, fuglyducky wrote: > >> if anyone happens to know about >> passing a variable into a regex that would be great. > > The same way you pass anything into any string. > > Regexes are ordinary strings. If you want to construct a string from a > variable t = "orl", you can do any of these: > > "Hello w" + t + "d" > > "".join(["Hello", " ", "w", t, "d"]) > > "Hello w%sd" % t > > "Hello %s" % ("w" + t + "d") > > "Hello w%(var)sd" % {"var": t} > > "Hello wSPAMd".replace("SPAM", t) > > or many other variations. Constructing a regex is no different. > You just need to remember that if you pass a string into re.sub as a replacement then it'll be treated as a template. It's all in the documentation! :-) From jjposner at optimum.net Thu Aug 12 22:26:20 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 12 Aug 2010 22:26:20 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <4c64765e$0$28580$426a74cc@news.free.fr> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4c64765e$0$28580$426a74cc@news.free.fr> Message-ID: <4C64AD4B.1010006@optimum.net> On 8/12/2010 6:31 PM, News123 wrote: >> candidate_box_counts = product( >> xrange(target/box_sizes[0] + 1), >> xrange(target/box_sizes[1] + 1), >> xrange(target/box_sizes[2] + 1), >> ) > > Couldn't this be rewritten as: > candidate_box_counts = product( > * [ xrange(target/sizes + 1) for size in box_sizes ] > ) > Sure (except for the typo: "sizes" should be "size"). You could even use a generator expression instead of a list comprehension: candidate_box_counts = product( * ( xrange(target/size + 1) for size in box_sizes ) ) -John From matt at schinckel.net Thu Aug 12 22:52:07 2010 From: matt at schinckel.net (Matt Schinckel) Date: Thu, 12 Aug 2010 19:52:07 -0700 (PDT) Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> Message-ID: <479d903d-2610-4755-a2aa-cd46540ff44d@y12g2000prb.googlegroups.com> On Aug 6, 8:15?am, "Rhodri James" wrote: > On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks ? > > wrote: > > Well, I am not convinced of the equivalence of not None and true: [snip] > >>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam" > True > >>> a = "spam, eggs, chips and spam" > >>> b = "spam, eggs, chips and spam" > >>> a is b > False but: >>> a = "hello" >>> b = "hello" >>> a is b True Ooh, that looks dangerous. Are they the same object? >>> a += "o" >>> a 'helloo' >>> b 'hello' Phew. (Python does not make two copies of small strings until it needs to). Matt. From aahz at pythoncraft.com Thu Aug 12 23:24:12 2010 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2010 20:24:12 -0700 Subject: Decompressing a file retrieved by URL seems too complex References: <4c645c39$0$1595$742ec2ed@news.sonic.net> Message-ID: In article <4c645c39$0$1595$742ec2ed at news.sonic.net>, John Nagle wrote: > >I'm reading a URL which is a .gz file, and decompressing it. This >works, but it seems far too complex. Yet none of the "wrapping" >you might expect to work actually does. You can't wrap a GzipFile >around an HTTP connection, because GzipFile, reasonably enough, needs >random access, and tries to do "seek" and "tell". Nor is the output >descriptor from gzip general; it fails on "readline", but accepts >"read". (No good reason for that.) So I had to make a second copy. Also consider using zlib directly. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From iamforufriends at gmail.com Fri Aug 13 00:32:52 2010 From: iamforufriends at gmail.com (UR DREEM GIRL) Date: Thu, 12 Aug 2010 21:32:52 -0700 (PDT) Subject: morethen 34, 100, 617 active members r waiting 4 live hot chat, dating ... Message-ID: morethen 34,100,617 active members r waiting 4 live hot chat, dating ... free and eazy to meet and enjoy.... just click.... start.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From ldo at geek-central.gen.new_zealand Fri Aug 13 00:45:36 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 13 Aug 2010 16:45:36 +1200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> Message-ID: In message , Jean- Michel Pichavant wrote: > for mcNugget in range(0,10): > sendTo(trashbin) Ah, but should that be mcNugget.sendTo(trashbin) or trashbin.insert(mcNugget) ? From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 00:52:21 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 04:52:21 GMT Subject: Inserting/Deleting newline(s) in very large text files References: <595550.37557.qm@web120110.mail.ne1.yahoo.com> Message-ID: <4c64cf85$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 21:25:59 +0200, Thomas Jollans wrote: > Everybody agrees that text files > should end with a line feed, because some text editors might mess up if > they don't. For some definition of "everybody". Obviously the text editors which DON'T mess up don't make the assumption that all text files end with a newline. -- Steven From tjreedy at udel.edu Fri Aug 13 01:12:10 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Aug 2010 01:12:10 -0400 Subject: easy question on parsing python: "is not None" In-Reply-To: <479d903d-2610-4755-a2aa-cd46540ff44d@y12g2000prb.googlegroups.com> References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <479d903d-2610-4755-a2aa-cd46540ff44d@y12g2000prb.googlegroups.com> Message-ID: On 8/12/2010 10:52 PM, Matt Schinckel wrote: >>>> a = "hello" >>>> b = "hello" >>>> a is b > True > > Ooh, that looks dangerous. Only for mutable objects > Are they the same object? Yes. >>>> a += "o" This is equivalent to a = a+"o". The expression creates a new object. The assignment binds the object to name 'a'. > (Python does not make two copies of small strings until it needs to). Python never copies *any* object until you ask it to. It never made a copy of the original 'a' here either. It combined the values of two string objects to make a new string object with a new value. -- Terry Jan Reedy From nobody at nowhere.com Fri Aug 13 01:34:52 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 13 Aug 2010 06:34:52 +0100 Subject: Floating numbers References: Message-ID: On Thu, 12 Aug 2010 18:19:40 -0700, Benjamin Kaplan wrote: > But that's not keeping the number the way it was typed. It's just not > showing you the exact approximation. Nor is 34.520000000000003 showing you the "exact approximation". The closest "double" to 34.52 is 4858258098025923 / 2**47, whose exact decimal representation is: 34.52000000000000312638803734444081783294677734375 The decimal representation of 1/(2**n) for n>0 always ends in 5. As a consequence of this, the exact decimal representation of any binary floating-point value which isn't itself an integer must end in 5. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 01:36:15 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 05:36:15 GMT Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> Message-ID: <4c64d9cf$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 13:20:19 -0700, Paddy wrote: > I find myself needing to calculate the difference between two Counters > or multisets or bags. Is this collections.Counter from Python 3.1? If so, you should say so, and if not, you should tell us which Counter class this is. It will save people (by which I mean *me*) from spending an unrewarding few minutes trying to import Counter in Python 2.5 and writing up a sarcastic response ... :) > I want those items that are unique to each bag. I know how to calculate > it: > > >>> b = Counter(a=1, b=2) > >>> c = Counter(a=3, b=1) > >>> diff = (b - c) + (c - b) > >>> (b - c) > Counter({'b': 1}) > >>> (c - b) > Counter({'a': 2}) > >>> diff > Counter({'a': 2, 'b': 1}) > > But thought why doesn't this operation appear already as a method of the > class? Don't know. Perhaps you should put in a feature request. -- Steven From nobody at nowhere.com Fri Aug 13 01:39:50 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 13 Aug 2010 06:39:50 +0100 Subject: Importing libs on Windows? References: Message-ID: On Thu, 12 Aug 2010 16:09:10 -0700, Brian Salter wrote: > I've seen a number of tutorials that describe how to bring in a dll in > python, but does anybody know of a tutorial for how to bring in a lib? Is > it even possible? No. ctypes relies upon the OS to actually load the library, and the OS doesn't provide any mechanism to load a ".lib" file. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 01:40:14 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 05:40:14 GMT Subject: inline exception handling in python References: Message-ID: <4c64dabe$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 20:08:01 +0200, Thomas Jollans wrote: [...] > Besides, more often than not, you want to have a finally clause around > when you're dealing with exceptions. Oh I don't know about that. Doing a quick and totally unscientific survey of my own code, I find that try...except with no finally outnumbers try...finally by about 10 to 1. In any case, any syntax for inline exception handling should be kept nice and lightweight. It shouldn't try to duplicate all the functionality of try...except...else...finally blocks. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 01:42:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 05:42:01 GMT Subject: inline exception handling in python References: <201008122008.02041.thomas@jollybox.de> Message-ID: <4c64db29$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 14:19:13 -0400, wheres pythonmonks wrote: > I think the problem in my case is best solved by look before you leap, > or a wrapper function. [I just hate function call overhead for this. ] Sounds suspiciously like premature micro-optimization to me. Function call overhead is tiny compared to the cost of catching an exception, and probably of a similar cost to looking before you leap. -- Steven From clp2 at rebertia.com Fri Aug 13 01:45:54 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 12 Aug 2010 22:45:54 -0700 Subject: EXOR or symmetric difference for the Counter class In-Reply-To: <4c64d9cf$0$28668$c3e8da3@news.astraweb.com> References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <4c64d9cf$0$28668$c3e8da3@news.astraweb.com> Message-ID: On Thu, Aug 12, 2010 at 10:36 PM, Steven D'Aprano wrote: > On Thu, 12 Aug 2010 13:20:19 -0700, Paddy wrote: > >> I find myself needing to calculate the difference between two Counters >> or multisets or bags. > > Is this collections.Counter from Python 3.1? "Changed in version **2.7**: Added Counter and OrderedDict." That is still ahead of the curve though. Cheers, Chris From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 01:51:40 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 05:51:40 GMT Subject: default behavior References: <0272074b-8508-4b7a-a11e-3f004506f522@v41g2000yqv.googlegroups.com> Message-ID: <4c64dd6b$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 13:28:26 -0700, David Niergarth wrote: > Peter Otten <__pete... at web.de> wrote: >> >> >>> 1 .conjugate() >> >> > This is a syntax I never noticed before. My built-in complier (eyes) > took one look and said: "that doesn't work." Has this always worked in > Python but I never noticed? Yes. Here is is working in Python 2.2: [steve at sylar ~]$ python2.2 Python 2.2.3 (#1, Aug 12 2010, 01:08:27) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 2 .__add__(3) 5 Syntactically, it also worked as far back as Python 1.5, although it is rather pointless since int objects didn't gain any methods until 2.2: [steve at sylar ~]$ python1.5 Python 1.5.2 (#1, Apr 1 2009, 22:55:54) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> 2 .__add__(3) Traceback (innermost last): File "", line 1, in ? AttributeError: 'int' object has no attribute '__add__' > I see other instance examples also work. > > >>> '1' .zfill(2) > '01' You don't need the space between strings and the attribute access: "1".zfill(2) is fine. You only need it for numbers, due to the ambiguity between the decimal point and dotted attribute access. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 02:03:54 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2010 06:03:54 GMT Subject: easy question on parsing python: "is not None" References: <7AEDA9A8-4951-4403-B6CF-0381CA41499E@gmail.com> <479d903d-2610-4755-a2aa-cd46540ff44d@y12g2000prb.googlegroups.com> Message-ID: <4c64e04a$0$28668$c3e8da3@news.astraweb.com> On Thu, 12 Aug 2010 19:52:07 -0700, Matt Schinckel wrote: >>>> a = "hello" >>>> b = "hello" >>>> a is b > True > > Ooh, that looks dangerous. Are they the same object? You don't need another test to know that they are the same object. The `is` operator does exactly that: a is b *only* if a and b are the same object. >>>> a += "o" >>>> a > 'helloo' >>>> b > 'hello' > > Phew. This tests for mutability, not sameness. If strings were mutable, then modifying a in place would likewise cause b to be modified (because they are the same object). Here's an example: >>> a = b = [1, 2, 3] >>> a is b True >>> a += [4] >>> b [1, 2, 3, 4] But of course, if strings were mutable like lists, they wouldn't be cached! The consequences would be horrific if they were, unless Python's execution model were radically different. Copy-on-write perhaps? > (Python does not make two copies of small strings until it needs to). Python doesn't copy anything unless you ask it to. -- Steven From doulos05 at gmail.com Fri Aug 13 02:22:23 2010 From: doulos05 at gmail.com (JonathanB) Date: Thu, 12 Aug 2010 23:22:23 -0700 (PDT) Subject: extra rows in a CSV module output when viewed in excel 2007 Message-ID: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> The subject basically says it all, here's the code that's producing the csv file: def write2CSV(self,output): writer = csv.writer(open(output, 'w'), dialect='excel') writer.writerow(['Name','Description','Due Date','Subject', 'Grade','Maximum Grade', self.name, self.grade]) for row in self.assignment_list: writer.writerow(row.output2list()) return True Here's the text from the csv file my test-run outputs: Name,Description,Due Date,Subject,Grade,Maximum Grade,Test Student,2 Math Homework 8/21,Math Review pp. 103-104,2010-08-13,Math,10,10,, Math Test,Chapter 5,2010-09-21,Math,45,50,, Science Test,Matter,2010-09-11,Science,400,500,, When I view it in Excel, there's an extra row between every result. How can I remove those? From wuwei23 at gmail.com Fri Aug 13 02:52:41 2010 From: wuwei23 at gmail.com (alex23) Date: Thu, 12 Aug 2010 23:52:41 -0700 (PDT) Subject: extra rows in a CSV module output when viewed in excel 2007 References: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> Message-ID: On Aug 13, 4:22?pm, JonathanB wrote: > ? ? ? ? writer = csv.writer(open(output, 'w'), dialect='excel') I think - not able to test atm - that if you open the file in 'wb' mode instead it should be fine. From gelonida at gmail.com Fri Aug 13 03:11:40 2010 From: gelonida at gmail.com (Gelonida) Date: Fri, 13 Aug 2010 09:11:40 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: Lee, On 08/13/2010 12:53 AM, Lee Harr wrote: > >> I'm desperate. I'm having a real application, which fails rather often >> when finishing it. I'm not sure, whether any serious problem could be >> hidden behind it >> >> The script is a pyqt script, which segfaults most of the time on my >> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. > > > Looks to be a known issue: > http://www.google.com/search?q=pyqt+segfault+on+exit > https://launchpad.net/bugs/561303 > > The last activity on that bug is almost 2 months ago... > Hopefully the fix will be distributed soon. This seems to be the problem. In my case I can workaround the issue by adding one line. if __name__ == "__main__": app = QApplication([]) myform = MyForm() myform.show() retcode = app.exec_() myform = None # <<<< THIS IS THE WORK AROUND print "last" Thaks a lot From blur959 at hotmail.com Fri Aug 13 03:54:40 2010 From: blur959 at hotmail.com (blur959) Date: Fri, 13 Aug 2010 00:54:40 -0700 (PDT) Subject: How do I get number of files in a particular directory. Message-ID: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> Hi, all, Is there a way to get a number of files in a particular directory? I tried using os.walk, os.listdir but they are return me with a list, tuple of the files, etc. But I want it to return a number. Is it possible? From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 13 04:44:13 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 13 Aug 2010 10:44:13 +0200 Subject: How do I get number of files in a particular directory. In-Reply-To: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> Message-ID: <4c6505c5$0$9878$426a34cc@news.free.fr> blur959 a ?crit : > Hi, all, Is there a way to get a number of files in a particular > directory? I tried using os.walk, os.listdir but they are return me > with a list, tuple of the files, etc. But I want it to return a > number. Is it possible? len(any_sequence) From cs at zip.com.au Fri Aug 13 04:51:11 2010 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 13 Aug 2010 18:51:11 +1000 Subject: How do I get number of files in a particular directory. In-Reply-To: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> Message-ID: <20100813085110.GA4173@cskk.homeip.net> On 13Aug2010 00:54, blur959 wrote: | Hi, all, Is there a way to get a number of files in a particular | directory? I tried using os.walk, os.listdir but they are return me | with a list, tuple of the files, etc. But I want it to return a | number. Is it possible? Measure the length of the list returned to you? The len() built in function suggests itself... -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ From martin.hellwig at dcuktec.org Fri Aug 13 04:57:25 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 13 Aug 2010 09:57:25 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: <4c645c7c$0$3675$426a74cc@news.free.fr> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION On 08/12/10 21:41, News123 wrote: > On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: >> On 08/11/10 21:14, Baba wrote: >> >> >> How about rephrasing that question in your mind first, i.e.: >> >> For every number that is one higher then the previous one*: >> If this number is dividable by: >> 6 or 9 or 20 or any combination of 6, 9, 20 >> than this number _can_ be bought in an exact number >> else >> print this number >> > > you are allowed to mix. > 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 I was aware of that, thats whhy I wrote: "or any combination of 6, 9, 20" > > I guess, trying to find the result with divisions and remainders is > overly complicated. Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 Type "help", "copyright", "credits" or "license" for more information. >>> MODULO_COMBINATIONS = [[20], [9], [6], ... [20, 9], [20, 6], [9, 20], ... [9, 6], [6, 20], [6, 9], ... [20, 9, 6], [20, 6, 9], [9, 20, 6], ... [9, 6, 20], [6, 20, 9], [6, 9, 20]] >>> >>> def apply_combinations_on(number): ... tmp = list() ... for combination in MODULO_COMBINATIONS: ... remainder = number ... for modulo_value in combination: ... if remainder == 0: ... remainder = None ... break ... ... result = remainder % modulo_value ... ... if result == remainder : ... remainder = None ... break ... ... remainder = result ... ... if remainder == 0: ... tmp.append(str(combination)) ... return(tmp) ... >>> print(apply_combinations_on(15)) ['[9, 6]'] >>> What is so over complicated about it? -- mph From blur959 at hotmail.com Fri Aug 13 05:18:11 2010 From: blur959 at hotmail.com (blur959) Date: Fri, 13 Aug 2010 02:18:11 -0700 (PDT) Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> Message-ID: <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Hi, I tried that, but it doesn't seem to work. My file directory has many different files extensions, and I want it to return me a number based on the number of files with similar files extensions. But when I tried running it, I get many weird numbers. Below is my code i had so far and the result. import os directory = raw_input("Please input file directory. \n\n") s = raw_input("Please input a name to replace. \n\n") ext = raw_input("input file ext") for files in os.listdir(directory): if ext in files: file_number = len(files) print file_number The result is: 13 13 13 6 15 8 10 10 8 7 5 where the result should be just 11. Can anyone help me? Thanks. From davea at ieee.org Fri Aug 13 05:23:31 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 13 Aug 2010 05:23:31 -0400 Subject: Importing libs on Windows? In-Reply-To: References: Message-ID: <4C650F13.7010704@ieee.org> Brian Salter wrote: > It appears that every example is calling a dll, and I'm looking to > bring in a lib. Does ctypes work with libs too? > > "Gary Herron" wrote in message > news:mailman.2044.1281656800.1673.python-list at python.org... >> On 08/12/2010 04:09 PM, Brian Salter wrote: >>> I've seen a number of tutorials that describe how to bring in a dll >>> in python, but does anybody know of a tutorial for how to bring in a >>> lib? Is it even possible? >>> >>> Thanks, in advance! >>> >>> >> >> Look at the Python module named ctypes: >> http://docs.python.org/library/ctypes.html >> >> Gary Herron >> >> > A lib file is not executable. It's a *description* of routines and data that has to be converted by a linker into actual executable code. The reason it's called a static lib is that once it is converted by the linker, the actual executable code resides inside the EXE file. So an application written in C doesn't ship with the lib file either (unless of course it's a compiler/linker). What's your actual goal? DaveA From sschwarzer at sschwarzer.net Fri Aug 13 05:30:37 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 13 Aug 2010 11:30:37 +0200 Subject: How do I get number of files in a particular directory. In-Reply-To: <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: <4C6510BD.2090800@sschwarzer.net> On 2010-08-13 11:18, blur959 wrote: > import os > > directory = raw_input("Please input file directory. \n\n") > s = raw_input("Please input a name to replace. \n\n") > ext = raw_input("input file ext") > > for files in os.listdir(directory): > if ext in files: > file_number = len(files) > print file_number > > > The result is: > 13 > 13 > 13 > 6 > 15 > 8 > 10 > 10 > 8 > 7 > 5 > > where the result should be just 11. Can anyone help me? Thanks. `os.listdir` returns a list of names. What you named `files` should actually be `filename`. What you got printed in the loop are the lengths of each filename. Stefan From jeanmichel at sequans.com Fri Aug 13 05:45:28 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 13 Aug 2010 11:45:28 +0200 Subject: writing \feff at the begining of a file Message-ID: <4C651438.50203@sequans.com> Hello python world, I'm trying to update the content of a $Microsoft$ VC2005 project files using a python application. Since those files are XML data, I assumed I could easily do that. My problem is that VC somehow thinks that the file is corrupted and update the file like the following: - +? Actually, is displayed in a different color by vim, telling me that this is some kind of special caracter code (I'm no familiar with such thing). After googling that, I have a clue : could be some unicode caracter use to indicate something ... well I don't know in fact ("UTF-8 files sometimes start with a byte-order marker (BOM) to indicate that they are encoded in UTF-8."). My problem is however simplier : how do I add such character at the begining of the file ? I tried f = open('paf', w) f.write(u'\ufeff') UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128) The error may be explicit but I have no idea how to proceed further. Any clue ? JM From __peter__ at web.de Fri Aug 13 05:46:03 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 11:46:03 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: Martin P. Hellwig wrote: > SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION > > On 08/12/10 21:41, News123 wrote: > >> On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: >>> On 08/11/10 21:14, Baba wrote: >>> >>> >>> How about rephrasing that question in your mind first, i.e.: >>> >>> For every number that is one higher then the previous one*: >>> If this number is dividable by: >>> 6 or 9 or 20 or any combination of 6, 9, 20 >>> than this number _can_ be bought in an exact number >>> else >>> print this number >>> >> >> you are allowed to mix. >> 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 > > I was aware of that, thats whhy I wrote: > "or any combination of 6, 9, 20" > >> >> I guess, trying to find the result with divisions and remainders is >> overly complicated. > > Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) > [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 > Type "help", "copyright", "credits" or "license" for more information. > >>> MODULO_COMBINATIONS = [[20], [9], [6], > ... [20, 9], [20, 6], [9, 20], > ... [9, 6], [6, 20], [6, 9], > ... [20, 9, 6], [20, 6, 9], [9, 20, 6], > ... [9, 6, 20], [6, 20, 9], [6, 9, 20]] > >>> > >>> def apply_combinations_on(number): > ... tmp = list() > ... for combination in MODULO_COMBINATIONS: > ... remainder = number > ... for modulo_value in combination: > ... if remainder == 0: > ... remainder = None > ... break > ... > ... result = remainder % modulo_value > ... > ... if result == remainder : > ... remainder = None > ... break > ... > ... remainder = result > ... > ... if remainder == 0: > ... tmp.append(str(combination)) > ... return(tmp) > ... > >>> print(apply_combinations_on(15)) > ['[9, 6]'] > >>> > > What is so over complicated about it? > Well, it was hard enough for me to run the code rather than just read it. I get >>> apply_combinations_on(21) [] which should be 1*9 + 2*6 What am I missing? Peter From mail at timgolden.me.uk Fri Aug 13 05:58:59 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 13 Aug 2010 10:58:59 +0100 Subject: writing \feff at the begining of a file In-Reply-To: <4C651438.50203@sequans.com> References: <4C651438.50203@sequans.com> Message-ID: <4C651763.3070306@timgolden.me.uk> On 13/08/2010 10:45, Jean-Michel Pichavant wrote: > My problem is however simplier : how do I add such character at the > begining of the file ? > I tried > > f = open('paf', w) f = open ("pag", "wb") f.write ("\xfe\xff") TJG From dickinsm at gmail.com Fri Aug 13 06:01:25 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 13 Aug 2010 03:01:25 -0700 (PDT) Subject: Floating numbers References: Message-ID: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> On Aug 12, 9:43?pm, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.5200000002. Nitpick: unless you're on very unusual hardware, you're missing some zeros here. On my machine, under Python 2.6, the float 34.52 displays as 34.520000000000003, and the value stored internally is actually 34.52000000000000312638803734444081783294677734375; so that's within 1 part in 10**16 of the value you entered. Why do you care? That's a serious question, and its answer goes a long way to determining what you should do. - If you're doing calculations with this number, then the difference between the number Python stores and 34.52 is so miniscule that in normal situations it's not going to matter. In particular, if it represents some physical quantity then any error in the representation will be swamped by the inherent measurement error. IOW, it's not worth worrying about. - If you're printing this number, and you just want the output to look nice (why? perhaps because you're showing this to other people?), then use float formatting operations to limit the number of decimal places you're printing. For example, '%.6f' % my_float, or format(my_float, '.6f'), will give my_float to 6 places after the decimal point. Or, as others have mentioned, it just so happens that Python 2.7 and 3.x will output a nice representation for this float automatically. That wouldn't necessarily be true if the result were coming from a calculation, though, so you shouldn't rely on repr producing nice results in those versions of Python. - If you *really* need a number that represents the *exact* value 34.52, then use the decimal module, or perhaps consider using a simple home-brewed fixed-point representation. One situation where you might care is when doing financial calculations, and in particular when rounding a quantity to a smaller number of decimal digits. Here binary floats can give unpredictable results in halfway cases. (E.g., round(2.675, 2) might give 2.68 or 2.67, depending on what version of Python you're using, and also possibly depending on your platforms.) -- Mark From __peter__ at web.de Fri Aug 13 06:09:57 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 12:09:57 +0200 Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: blur959 wrote: > Hi, I tried that, but it doesn't seem to work. My file directory has > many different files extensions, and I want it to return me a number > based on the number of files with similar files extensions. But when I > tried running it, I get many weird numbers. Below is my code i had so > far and the result. Use glob.glob() instead of os.listdir() if you are only interested in files with a specific extension: >>> import glob >>> len(glob.glob("*.py")) 42 Peter From downaold at gmail.com Fri Aug 13 06:25:06 2010 From: downaold at gmail.com (Roald de Vries) Date: Fri, 13 Aug 2010 12:25:06 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <4C645EB9.7060105@optimum.net> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4C645EB9.7060105@optimum.net> Message-ID: <0E6BB339-057C-4B78-A0EB-AC4EA2FAF152@gmail.com> On Aug 12, 2010, at 10:51 PM, John Posner wrote: > On 8/12/2010 9:22 AM, Dave Angel wrote: >>> >>> Now you have to find the largest number below 120, which you can >>> easily do with brute force > tgt = 120 # thanks, Dave Angel Anytime, but I'm not Dave Angel. My previous algorithm was more efficient, but for those who like one- liners: [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) for b in range(x/9) for c in range(x/6))][-1] Cheers, Roald From darragh.ssa at gmail.com Fri Aug 13 06:31:09 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Fri, 13 Aug 2010 03:31:09 -0700 (PDT) Subject: Deditor -- pythonic text-editor Message-ID: Hey, I've finished my second version of deditor, a python text-editor for python under linux. It offers some python-only features like an interpreter, a code- analyzer, syntax-highlighting,... Are there some people in here who would like to test the app? (and maybe even help spread it) more info can be found on launchpad: https://launchpad.net/deditor or you can mail me darragh.ssa at gmail.com From downaold at gmail.com Fri Aug 13 06:38:53 2010 From: downaold at gmail.com (Roald de Vries) Date: Fri, 13 Aug 2010 12:38:53 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <0E6BB339-057C-4B78-A0EB-AC4EA2FAF152@gmail.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4C645EB9.7060105@optimum.net> <0E6BB339-057C-4B78-A0EB-AC4EA2FAF152@gmail.com> Message-ID: <0101CFDA-4A4D-463B-ABBE-830B1869B1AA@gmail.com> On Aug 13, 2010, at 12:25 PM, Roald de Vries wrote: > My previous algorithm was more efficient, but for those who like one- > liners: > > [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) > for b in range(x/9) for c in range(x/6))][-1] OK, I did some real testing now, and there's some small error in the above. All solutions for all x's are given by: [(x, a, b, c) for x in range(120) for a in range(x/20+1) for b in range(x/9+1) for c in range(x/6+1) if x == a*20+b*9+c*6] ... and all non-solutions by: [x for x in range(120) if not any(x == a*20+b*9+c*6 for a in range(x/20+1) for b in range(x/9+1) for c in range(x/6+1))] Cheers, Roald From srisimhan at gmail.com Fri Aug 13 06:40:05 2010 From: srisimhan at gmail.com (Srikanth N) Date: Fri, 13 Aug 2010 16:10:05 +0530 Subject: Python CGI windows Message-ID: Dear All, I Have certain clarification in python CGI. I use Python IDLE *1. How do we execute CGI Scripts in Windows? 2. How do i configure the Server?(If i use WAMP,XAMPP) 3. Is mod_python required for python cgi? * Someone Please revert back to me with the solution for the same.I would be at-most thankful -- Thanks & Regards, Srikanth.N -------------- next part -------------- An HTML attachment was scrubbed... URL: From eckhardt at satorlaser.com Fri Aug 13 06:43:44 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Fri, 13 Aug 2010 12:43:44 +0200 Subject: writing \feff at the begining of a file References: Message-ID: <08kfj7-7ei.ln1@satorlaser.homedns.org> Jean-Michel Pichavant wrote: > My problem is however simplier : how do I add such character [a BOM] > at the begining of the file ? > I tried > > f = open('paf', w) > f.write(u'\ufeff') > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in > position 0: ordinal not in range(128) Try the codecs module to open the file, which will then do all the transcoding between internal texts and external UTF-8 for you. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From martin.hellwig at dcuktec.org Fri Aug 13 06:51:22 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 13 Aug 2010 11:51:22 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: On 08/13/10 10:46, Peter Otten wrote: > Martin P. Hellwig wrote: > >> SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION No it wasn't :-) > which should be 1*9 + 2*6 > > What am I missing? > Aah interesting, 21 % 9 returns 3 instead of 12, which makes sense of course. I guess the algorithm has to be adapted in a way that if the value is bigger or equal twice the size of the modulo value you need to iterate over it, something like: for minus_multiplier in range(1, int(number, modulo_value)+2): number = number - (modulo_value * minus_multiplier) do the rest of the loop Probably another ten lines or so to make it working as it should -- mph From blur959 at hotmail.com Fri Aug 13 07:02:21 2010 From: blur959 at hotmail.com (blur959) Date: Fri, 13 Aug 2010 04:02:21 -0700 (PDT) Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: On Aug 13, 6:09?pm, Peter Otten <__pete... at web.de> wrote: > blur959 wrote: > > Hi, I tried that, but it doesn't seem to work. My file directory has > > many different files extensions, and I want it to return me a number > > based on the number of files with similar files extensions. But when I > > tried running it, I get many weird numbers. Below is my code i had so > > far and the result. > > Use glob.glob() instead of os.listdir() if you are only interested in files > with a specific extension: > > >>> import glob > >>> len(glob.glob("*.py")) > > 42 > > Peter Hi, I want to make it such that the user inputs a file extension and it prints the number of similar file extensions out. I tried doing this: directory = raw_input("input file directory") ext = raw_input("input file ext") file_list = len(glob.glob(ext)) print file_list And my result was this: 0 which it is suppose to be 11 May I know why? And how do I specify which directory it is searching the files extension from? I want the user to specify a directory and it searches the particular directory for the particular file extensions and prints the number out. Hope you guys could help. Thanks From dlanorslegov at rocketmail.com Fri Aug 13 07:14:37 2010 From: dlanorslegov at rocketmail.com (Dlanor Slegov) Date: Fri, 13 Aug 2010 04:14:37 -0700 (PDT) Subject: Inserting/Deleting newline(s) in very large text files In-Reply-To: References: <595550.37557.qm@web120110.mail.ne1.yahoo.com> Message-ID: <959582.50301.qm@web120114.mail.ne1.yahoo.com> I would greatly appreciate a python solution as this problem is only the head of a larger problem for which I am on a mission to write a FULL one-stop-shop python script. I am trying two things- iter() and fileinput module... Thanks! ________________________________ From: Matty Sarro To: Dlanor Slegov Sent: Thu, August 12, 2010 5:22:58 PM Subject: Re: Inserting/Deleting newline(s) in very large text files On Thu, Aug 12, 2010 at 11:12 AM, Dlanor Slegov wrote: Hi, > >I am dealing with very large text files (a few million lines) and would like to >check and modify them according to a well defined format. The format >requires?ONLY ONE?NEWLINE (followed by some sort of text) on top of the file and >NO NEWLINE in the very end. The input files can be very diverse, such as?one >file may have 2 newlines on top and none in the end or other may not have a >newline on top and 5 in the end. > > >The aim is to check these files &?introduce JUST ONE NEWLINE in the?TOP and NO >NEWLINE in the BOTTOM. > >Any pointers will be appreciated. > >Thanks, >DS. >?? > >-- >http://mail.python.org/mailman/listinfo/python-list > > If you're using a unix box you may want to look into sed. sed -i. '1i text to be inserted in first line' For example: sed -i.bak '1i alias bond0 bonding' /etc/modprobe.conf Would back up the original file to the initial filename plus the extension .bak. Then it would insert: alias bond0 bonding into /etc/modprobe.conf Into the 1st line of the file, moving everything else down one line. You can find some info on dealing with newlines here: http://www.grymoire.com/Unix/Sed.html#toc-uh-nl I know you're looking for a python solution, but this may be easier. Just a heads up. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Aug 13 07:21:58 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 13:21:58 +0200 Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: blur959 wrote: > On Aug 13, 6:09 pm, Peter Otten <__pete... at web.de> wrote: >> blur959 wrote: >> > Hi, I tried that, but it doesn't seem to work. My file directory has >> > many different files extensions, and I want it to return me a number >> > based on the number of files with similar files extensions. But when I >> > tried running it, I get many weird numbers. Below is my code i had so >> > far and the result. >> >> Use glob.glob() instead of os.listdir() if you are only interested in >> files with a specific extension: >> >> >>> import glob >> >>> len(glob.glob("*.py")) >> >> 42 >> >> Peter > > > Hi, I want to make it such that the user inputs a file extension and > it prints the number of similar file extensions out. > I tried doing this: > > directory = raw_input("input file directory") > ext = raw_input("input file ext") > > file_list = len(glob.glob(ext)) > print file_list > > > And my result was this: > 0 > which it is suppose to be 11 > > May I know why? And how do I specify which directory it is searching > the files extension from? I want the user to specify a directory and > it searches the particular directory for the particular file > extensions and prints the number out. > Hope you guys could help. The part of the filename you don't care about has to be replaced with a "*": import os import glob directory = raw_input("directory? ") ext = raw_input("file extension? ") pattern = os.path.join(directory, "*" + ext) matching_files = glob.glob(pattern) print len(matching_files), "matching files" Note that you'll learn a lot more when you look up in the documentation how the functions mentioned actually work instead of coming back here for every tiny detail. I you don't feel ready yet to understand enough of the Python documentation, go one step back and work your way through a tutorial or introductory book. A starting point is here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Peter From mikael.liljeroth at gmail.com Fri Aug 13 07:22:08 2010 From: mikael.liljeroth at gmail.com (Mikael Liljeroth) Date: Fri, 13 Aug 2010 13:22:08 +0200 Subject: Embedding, subinterpreters and dynamic types Message-ID: Hi, this is my first contact with the python community so I hope this is the right place for my two questions. They are both related to embedding and extending python. I'm writing a program that dynamically loads c++ modules that extend the functionality of my program. These modules are controlled by scripts. Currently I have embedded the v8 javascript engine but I would also like to support scripts written in python. I have a special interface between the c++ modules and the scripts to be able to support different scripting languages. Scripts are separated into different 'applications' that are executed in one process triggered by external events (no threading, since I'm working in an event driven system). The scripts should execute independently of each other. I solved this with v8 by switching between the applications' contexts. However, it seems like python has some issues with this. 1. To do some basic context switching I assume I should use a sub interpreter ie create a new thread state (without any actual threads). I cannot find any information on how to do this except creating the new thread state. Is this the preferred way of doing this, if so, how do I switch between different thread states and execute scripts in them? I assume scripts running in one thread state are isolated from scripts running in other thread states, like global variables and such (except for the GIL thing?) ? I do not care much about security problems like file descriptor issues and extension issues right now. 2. When a new C++ module is loaded into my program I want to create a representation of it in Python. Not as a type, but rather just return a single object instance reference of a new type representing the exported attributes and methods of the module's C++ class. In other words, I want to be able to do something like this obj = application.getObject("objectId"); where objectId is the name of an instance of that c++ module type. I do not want the script to be able to create new instances of this type, since this is done via xml in my program. Hence I would also like to be able to associate my C++ object with my returned python object to be able to manipulate it when methods are called on 'obj'. So how do I define a new type on the fly and create an instance of it, associated with a c++ pointer and return it in the c function representing the python method 'getObject' in my application module? Hope this makes any sense, let me know if something is unclear. Regards Mikael Liljeroth From davea at ieee.org Fri Aug 13 08:15:29 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 13 Aug 2010 08:15:29 -0400 Subject: How do I get number of files in a particular directory. In-Reply-To: References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: <4C653761.8090305@ieee.org> blur959 wrote: > On Aug 13, 6:09 pm, Peter Otten <__pete... at web.de> wrote: > >> blur959 wrote: >> >>> Hi, I tried that, but it doesn't seem to work. My file directory has >>> many different files extensions, and I want it to return me a number >>> based on the number of files with similar files extensions. But when I >>> tried running it, I get many weird numbers. Below is my code i had so >>> far and the result. >>> >> Use glob.glob() instead of os.listdir() if you are only interested in files >> with a specific extension: >> >> >>>>> import glob >>>>> len(glob.glob("*.py")) >>>>> >> 42 >> >> Peter >> > > > Hi, I want to make it such that the user inputs a file extension and > it prints the number of similar file extensions out. > I tried doing this: > > directory =aw_input("input file directory") > ext =aw_input("input file ext") > > file_list =en(glob.glob(ext)) > print file_list > > > And my result was this: > 0 > which it is suppose to be 11 > > May I know why? And how do I specify which directory it is searching > the files extension from? I want the user to specify a directory and > it searches the particular directory for the particular file > extensions and prints the number out. > Hope you guys could help. > > Thanks > > Glob doesn't do much useful unless there's a wildcard. And as you point out, it also needs the directory. You want to pass it something like mydirect/*.txt In your case, you might construct that with something like os.path.join(directory, "*." + ext) DaveA From wxjmfauth at gmail.com Fri Aug 13 10:03:23 2010 From: wxjmfauth at gmail.com (jmfauth) Date: Fri, 13 Aug 2010 07:03:23 -0700 (PDT) Subject: Floating numbers References: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> Message-ID: <24495a41-bae0-4965-9bfb-de55230c632d@a36g2000yqc.googlegroups.com> A quick question. I understand how to get these numbers 34.52000000000000312638803734444081783294677734375 and 47 (from 2**47) and the sign. with the decimal module, but I fail to find this one 4858258098025923 Possible? From blur959 at hotmail.com Fri Aug 13 10:40:42 2010 From: blur959 at hotmail.com (blur959) Date: Fri, 13 Aug 2010 07:40:42 -0700 (PDT) Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: Hi all, I got a problem with my script. Everything looks good so far but for some reason my os.rename isn't working. Can anyone tell me why? Hope you guys could help. Thanks. import os import glob directory = raw_input("directory? ") ext = raw_input("file extension? ") r = raw_input("replace name") pattern = os.path.join(directory, "*" + ext) matching_files = glob.glob(pattern) file_number = len(matching_files) for filename in os.listdir(directory): if ext in filename: path = os.path.join(directory, filename) seperated_names = os.path.splitext(filename)[0] replace_name = filename.replace(seperated_names, r) split_new_names = os.path.splitext(replace_name)[0] for pad_number in range(0, file_number): padded_numbers = "%04d" % pad_number padded_names = "%s_%s" % (split_new_names, padded_numbers) newpath = os.path.join(directory, padded_names) newpathext = "%s%s" % (newpath, ext) new_name = os.rename(path, newpathext) From patentsvnc at gmail.com Fri Aug 13 11:27:50 2010 From: patentsvnc at gmail.com (Den) Date: Fri, 13 Aug 2010 08:27:50 -0700 (PDT) Subject: Python "why" questions References: Message-ID: > ... However, the killer reason is: "it's what everybody > else does. If this were really true, lists would be 1-based. I go back to WATFOR; and Fortran (and I believe Cobol and PL/I, though I'm not positive about them) were 1-based. (Now that I think about it, PL/I, knowing IBM, could probably be set to use either) Back then, everyone else was doing 1-based lists. In my opinion, the reason lists are 0-based started with a lazy programmer who decided that his own comfort (using 0-based addressing at the machine level and not having to translate the high-level 1- based language index into a low-level 0-based index) was paramount over teaching the language and having it make sense in the real world. After all, not even Brian Kernighan thinks books start on page 0. I'm not singling out C in this case because it is a relatively low- level language for low-level programmers and 0-based lists make perfect sense in that context. But then every compiler/interpreter programmer after that stopped caring about it. I smile every time I see the non-nonsensical sentence "The first thing, therefore, is in thing[0]" in a programming language learning book or tutorial. I laugh every time I hear someone defend that as common sense. Every three year old watching Sesame Street knows counting things starts with '1', not '0'. When you were three and you counted your blocks, you started with '1', not '0'. The whole rest of the world understands that implicitly, even if their counting starts '1', '2', 'many'. 0-based lists are NOT common sense. They only make sense to the programmers of computer languages, and their fanbois. There may be loads of reasons for it, but don't throw common sense around as one of them. Den From dickinsm at gmail.com Fri Aug 13 11:43:24 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 13 Aug 2010 08:43:24 -0700 (PDT) Subject: Floating numbers References: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> <24495a41-bae0-4965-9bfb-de55230c632d@a36g2000yqc.googlegroups.com> Message-ID: On Aug 13, 3:03?pm, jmfauth wrote: > A quick question. > > I understand how to get these numbers > > 34.52000000000000312638803734444081783294677734375 > > and > > 47 (from 2**47) > > and the sign. > > with the decimal module, but I fail to find this one > > 4858258098025923 > > Possible? See the float.as_integer_ratio method. -- Mark From praveen.python.plone at gmail.com Fri Aug 13 12:46:34 2010 From: praveen.python.plone at gmail.com (Praveen) Date: Fri, 13 Aug 2010 09:46:34 -0700 (PDT) Subject: text to DB Message-ID: I have a text file in this format PRA 1:13 2:20 3:5 SRA 1:45 2:75 3:9 TRA 1:2 2:65 3:45 pattern is- Book Chapter:Verses now i have my DB schema like this book_id chapter_id versed_id 1 1 13 1 2 20 1 3 5 2 1 45 2 2 75 2 3 9 3 1 2 3 2 65 3 3 45 I want to write a pyhton script which read the text file and dump to DB could any one give me suggestion From thomas at jollans.com Fri Aug 13 12:50:12 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 18:50:12 +0200 Subject: Embedding, subinterpreters and dynamic types In-Reply-To: References: Message-ID: <4C6577C4.7010004@jollans.com> On 2010-08-13 13:22, Mikael Liljeroth wrote: > Hi, this is my first contact with the python community so I hope this > is the right place for my two questions. > They are both related to embedding and extending python. > > I'm writing a program that dynamically loads c++ modules that extend > the functionality of my program. > These modules are controlled by scripts. Currently I have embedded the > v8 javascript engine but I would also like to support scripts written > in python. I have a special interface between the c++ modules and the > scripts to be able to support different scripting languages. Scripts > are separated into different 'applications' that are executed in one > process triggered by external events (no threading, since I'm working > in an event driven system). The scripts should execute independently > of each other. I solved this with v8 by switching between the > applications' contexts. However, it seems like python has some issues > with this. > > 1. To do some basic context switching I assume I should use a sub > interpreter ie create a new thread state (without any actual threads). > I cannot find any information on how to do this except creating the > new thread state. Is this the preferred way of doing this, if so, how > do I switch between different thread states and execute scripts in > them? I assume scripts running in one thread state are isolated from > scripts running in other thread states, like global variables and such > (except for the GIL thing?) ? I do not care much about security > problems like file descriptor issues and extension issues right now. > Py_NewInterpreter does indeed sound like what you want. I have a feeling you're going to run into problems here sooner or later, say, when extension modules that aren't yours use static variables. As for switching interpreters, after skimming the docs, I'm guessing you're looking for PyEval_AcquireThread http://docs.python.org/py3k/c-api/init.html#PyEval_AcquireThread > 2. When a new C++ module is loaded into my program I want to create a > representation of it in Python. Not as a type, but rather just return > a single object instance reference of a new type representing the > exported attributes and methods of the module's C++ class. In other > words, I want to be able to do something like this obj = > application.getObject("objectId"); where objectId is the name of an > instance of that c++ module type. I do not want the script to be able > to create new instances of this type, since this is done via xml in my > program. Hence I would also like to be able to associate my C++ object > with my returned python object to be able to manipulate it when > methods are called on 'obj'. So how do I define a new type on the fly > and create an instance of it, associated with a c++ pointer and return > it in the c function representing the python method 'getObject' in my > application module? > How difficult this is obviously depends somewhat on how varied the types you create are, but in principle, there's no difference between creating a type statically and creating one on-the-fly: all you need to do to create a type is create a PyTypeObject structure with suitable function pointers. If you want to make it impossible to create a second instance of your type, you can simply create a tp_new or tp_init that raises an exception. If you have a good look at http://docs.python.org/py3k/extending/newtypes.html , you'll notice that most of the "creating a type" involves writing a static PyTypeObject structure -- you'll just have to allocate that yourself, and you should be good. From szport at gmail.com Fri Aug 13 13:00:56 2010 From: szport at gmail.com (zaur) Date: Fri, 13 Aug 2010 10:00:56 -0700 (PDT) Subject: how to make portable distribution of python 2.6? Message-ID: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> All greetings! How to make portable distribution of python 2.6? From simon at brunningonline.net Fri Aug 13 13:03:16 2010 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 13 Aug 2010 18:03:16 +0100 Subject: python interview quuestions In-Reply-To: <4c6298c1$0$11101$c3e8da3@news.astraweb.com> References: <4C5C5528.5060608@tim.thechases.com> <877hjykxjy.fsf@agentultra.com> <4c6298c1$0$11101$c3e8da3@news.astraweb.com> Message-ID: On 11 August 2010 13:34:09 UTC+1, Steven D'Aprano wrote: > Getting interviewees to do a take-home problem just means you hire the > guy who is friends with a good programmer, rather than the good > programmer. We give a take-home problem. If we like the code we see, we invite the candidate to come in and pair with one of our devs in adding a simple feature or two to their own code. It's time consuming, but not so time consuming as hiring a weak dev. -- Cheers, Simon B. From thomas at jollans.com Fri Aug 13 13:14:44 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 19:14:44 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4C657D84.6030506@jollans.com> On 2010-08-13 17:27, Den wrote: > There may be loads of reasons for it, but don't throw common sense > around as one of them. > It's a good thing then that I didn't: >> ... However, the killer reason is: "it's what everybody >> else does. >> > "Where it all started" is that 0-based indexing gives languages like C a very nice property: a[i] and *(a+i) are equivalent in C. From a language design viewpoint, I think that's quite a strong argument. Languages based directly on C (C++, Objective C, ...) can't break with this for obvious reasons, and other language designers/implementers imitated this behaviour without any good reason to do so, or not to do so. In higher-level languages, it doesn't really matter. 1-based indexing might seam more intuitive, but in the end, it's just another thing you have to learn when learning a language, like "commas make tuples", and somebody studying a programming language learns it, and gets used to it if they aren't used to it already. From thomas at jollans.com Fri Aug 13 13:28:01 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 19:28:01 +0200 Subject: how to make portable distribution of python 2.6? In-Reply-To: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> References: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> Message-ID: <4C6580A1.2010203@jollans.com> On 2010-08-13 19:00, zaur wrote: > All greetings! > > How to make portable distribution of python 2.6? > I don't know, but what you're looking for probably already exists. Do you mean "portable" as in portable, i.e. "take this and build it for your system, it should work if your OS is supported"? Then you can get source tarballs from python.org http://python.org/download/ Or do you understand "portable" the way that is fashionable in the Windows world nowadays for some reason, i.e. "look, Ma, already installed if you happen to use Microsoft Windows of roughly the right version!" Then http://www.portablepython.com/ is exactly where Google would have lead you had you searched. From thomas at jollans.com Fri Aug 13 13:34:57 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 19:34:57 +0200 Subject: Python CGI windows In-Reply-To: References: Message-ID: <4C658241.5000203@jollans.com> On 2010-08-13 12:40, Srikanth N wrote: > *1. How do we execute CGI Scripts in Windows? > * You'll need a web server. > *2. How do i configure the Server?(If i use WAMP,XAMPP) > * For CGI, you just need your server configured for CGI, nothing Python-specific. It would surprise me if XAMPP didn't set up a working cgi-bin for your programming pleasure anyway. > *3. Is mod_python required for python cgi? > * No. mod_python is a completely different approach to running Python from the web. Don't use it, it's dead. If you want something similar, use mod_wsgi. ** Come to think of it, you should probably look into WSGI anyway -- you can run WSGI scripts via CGI for the time being, that's simple enough, and switch to something else for production, or for serious development, later on. > Someone Please revert back to me with the solution for the same.I > would be at-most thankful This line is fascinating, -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Fri Aug 13 13:36:08 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 13 Aug 2010 17:36:08 GMT Subject: Python "why" questions References: Message-ID: <8cle48FdneU1@mid.individual.net> On 2010-08-13, Thomas Jollans wrote: > 1-based indexing might seam more intuitive, but in the end, > it's just another thing you have to learn when learning a > language, like "commas make tuples", and somebody studying a > programming language learns it, and gets used to it if they > aren't used to it already. I think the main reason zero-based indexing is chosen in higher level languages is the following useful property: x[n:m] + x[m:len(x)] == x -- Neil Cerutti From thomas at jollans.com Fri Aug 13 13:36:44 2010 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 13 Aug 2010 19:36:44 +0200 Subject: Python CGI windows In-Reply-To: References: Message-ID: <4C6582AC.4010302@jollans.com> On 2010-08-13 12:40, Srikanth N wrote: > *2. How do i configure the Server?(If i use WAMP,XAMPP) > * Sorry, I forgot to link you to http://www.editrocket.com/articles/python_apache_windows.html Hope this helps. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Fri Aug 13 13:45:22 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Aug 2010 18:45:22 +0100 Subject: writing \feff at the begining of a file In-Reply-To: <4C651438.50203@sequans.com> References: <4C651438.50203@sequans.com> Message-ID: <4C6584B2.8060903@mrabarnett.plus.com> Jean-Michel Pichavant wrote: > Hello python world, > > I'm trying to update the content of a $Microsoft$ VC2005 project files > using a python application. > Since those files are XML data, I assumed I could easily do that. > > My problem is that VC somehow thinks that the file is corrupted and > update the file like the following: > > - > +? > > > Actually, is displayed in a different color by vim, telling me > that this is some kind of special caracter code (I'm no familiar with > such thing). > After googling that, I have a clue : could be some unicode caracter use > to indicate something ... well I don't know in fact ("UTF-8 files > sometimes start with a byte-order marker (BOM) to indicate that they are > encoded in UTF-8."). > > My problem is however simplier : how do I add such character at the > begining of the file ? > I tried > > f = open('paf', w) > f.write(u'\ufeff') > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in > position 0: ordinal not in range(128) > > The error may be explicit but I have no idea how to proceed further. Any > clue ? > In Python 2 the default encoding is 'ascii'. What you want is 'utf-8'. Use codecs.open() instead, with the 'utf-8-sig' encoding, which will include the BOM. From martin at address-in-sig.invalid Fri Aug 13 13:53:56 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Fri, 13 Aug 2010 17:53:56 +0000 (UTC) Subject: Python "why" questions References: Message-ID: On Fri, 13 Aug 2010 19:14:44 +0200, Thomas Jollans wrote: > "Where it all started" is that 0-based indexing gives languages like C a > very nice property: a[i] and *(a+i) are equivalent in C. From a language > design viewpoint, I think that's quite a strong argument. Languages > based directly on C (C++, Objective C, ...) can't break with this for > obvious reasons, and other language designers/implementers imitated this > behaviour without any good reason to do so, or not to do so. In > higher-level languages, it doesn't really matter. 1-based indexing might > seam more intuitive. > In a higher level language 1-based indexing is just as limiting as 0- based indexing. What you really want is the ability to declare the index range to suit the problem: in Algol 60 it is very useful to be able to declare something like: real sample[-500:750]; and Algol 68 went even further: flex [1:0] int count where the array bounds change dynamically with each assignment to 'count'. Iteration is supported by the lwb and upb operators which return the bounds of an array, so you can write: for i from lwb count to upb count do.... -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From python at mrabarnett.plus.com Fri Aug 13 13:57:24 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Aug 2010 18:57:24 +0100 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: <4C658784.9050404@mrabarnett.plus.com> Martin P. Hellwig wrote: > On 08/13/10 10:46, Peter Otten wrote: >> Martin P. Hellwig wrote: >> >>> SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION > No it wasn't :-) > >> which should be 1*9 + 2*6 >> >> What am I missing? >> > > Aah interesting, 21 % 9 returns 3 instead of 12, which makes sense of > course. I guess the algorithm has to be adapted in a way that if the > value is bigger or equal twice the size of the modulo value you need to > iterate over it, something like: > for minus_multiplier in range(1, int(number, modulo_value)+2): > number = number - (modulo_value * minus_multiplier) > do the rest of the loop > > Probably another ten lines or so to make it working as it should > I don't understand what you're trying to do. My solution would be: def can_buy(nuggets): for packs_20 in range(nuggets // 20, -1, -1): remaining_20 = nuggets - 20 * packs_20 for packs_9 in range(remaining_20 // 9, -1, -1): remaining_9 = remaining_20 - 9 * packs_9 if remaining_9 % 6 == 0: packs_6 = remaining_9 // 6 return [packs_6, packs_9, packs_20] return [] From nobody at nowhere.com Fri Aug 13 14:04:10 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 13 Aug 2010 19:04:10 +0100 Subject: writing \feff at the begining of a file References: Message-ID: On Fri, 13 Aug 2010 11:45:28 +0200, Jean-Michel Pichavant wrote: > I'm trying to update the content of a $Microsoft$ VC2005 project files > using a python application. > Since those files are XML data, I assumed I could easily do that. > > My problem is that VC somehow thinks that the file is corrupted and > update the file like the following: > > - > +? > > > Actually, is displayed in a different color by vim, telling me > that this is some kind of special caracter code (I'm no familiar with > such thing). U+FEFF is a "byte order mark" or BOM. Each Unicode-based encoding (UTF-8, UTF-16, UTF-16-LE, etc) will encode it differently, so it enables a program reading the file to determine the encoding before reading any actual data. > My problem is however simplier : how do I add such character at the > begining of the file ? > I tried Either: 1. Open the file as binary and write '\xef\xbb\xbf' to the file: f = open('foo.txt', 'wb') f.write('\xef\xbb\xbf') [You can also use the constant BOM_UTF8 from the codecs module.] 2. Open the file as utf-8 and write u'\ufeff' to the file: import codecs f = codecs.open('foo.txt', 'w', 'utf-8') f.write(u'\ufeff') 3. Open the file as utf-8-sig and don't write anything (or write an empty string): import codecs f = codecs.open('foo.txt', 'w', 'utf-8-sig') f.write('') The utf-8-sig codec automatically writes a BOM at the beginning of the file. It is present in Python 2.5 and later. From python at mrabarnett.plus.com Fri Aug 13 14:09:55 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Aug 2010 19:09:55 +0100 Subject: text to DB In-Reply-To: References: Message-ID: <4C658A73.5010904@mrabarnett.plus.com> Praveen wrote: > I have a text file in this format > PRA 1:13 2:20 3:5 > SRA 1:45 2:75 3:9 > TRA 1:2 2:65 3:45 > > pattern is- Book Chapter:Verses > > now i have my DB schema like this > book_id chapter_id versed_id > 1 1 13 > 1 2 20 > 1 3 5 > 2 1 45 > 2 2 75 > 2 3 9 > 3 1 2 > 3 2 65 > 3 3 45 > > I want to write a pyhton script which read the text file and dump to > DB > > could any one give me suggestion Read through the file a line at a time. For the first line the book_id is 1, for the second it's 2, etc. Split each line on whitespace, and then for all but the first entry (which is a name?) split on the colon to get the chapter_id and versed_id. Insert each tuple of (book_id, chapter_id, versed_id) into the DB. You haven't said what type of DB it is, so I can't help you there. Just read the documentation. From szport at gmail.com Fri Aug 13 14:23:59 2010 From: szport at gmail.com (zaur) Date: Fri, 13 Aug 2010 11:23:59 -0700 (PDT) Subject: how to make portable distribution of python 2.6? References: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> Message-ID: <21480f31-c156-408a-a354-70debaa2dedc@l6g2000yqb.googlegroups.com> On 13 ???, 21:28, Thomas Jollans wrote: > On 2010-08-13 19:00, zaur wrote:> All greetings! > > > How to make portable distribution of python 2.6? > > I don't know, but what you're looking for probably already exists. > > Do you mean "portable" as in portable, i.e. "take this and build it for > your system, it should work if your OS is supported"? Then you can get > source tarballs from python.org > > http://python.org/download/ > > Or do you understand "portable" the way that is fashionable in the > Windows world nowadays for some reason, i.e. "look, Ma, already > installed if you happen to use Microsoft Windows of roughly the right > version!" > > Thenhttp://www.portablepython.com/is exactly where Google would have > lead you had you searched. I want to realize howto build my own portable python in order to use them without installation. I want also to be able install modules (numpy, matplotlib, pyqt, etc...) when it is necessary. This very usefull for teaching python in computer classes. From raoulbia at gmail.com Fri Aug 13 14:25:32 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 13 Aug 2010 11:25:32 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> Message-ID: <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> Hi News 123, Ok i'm getting closer. I am able to write code that will output values that can be bought in exact quantity (truelist) and values that cannot be bought in exact quantities. For a range up to 29 i get this: true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28] the sixth value that passes the test of having an exact solution is 20 so that would mean that the last number i got that cannot be bought in exact quantity is 19 that doesn't seem quite right, does it? def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True return False truelist=[] falselist=[] for n_nuggets in range(30): result = can_buy(n_nuggets) if result==True: truelist=truelist+[n_nuggets,] else: falselist=falselist+[n_nuggets,] print 'true',truelist print 'false',falselist tnx Baba From raoulbia at gmail.com Fri Aug 13 14:25:47 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 13 Aug 2010 11:25:47 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> Message-ID: Hi News 123, Ok i'm getting closer. I am able to write code that will output values that can be bought in exact quantity (truelist) and values that cannot be bought in exact quantities. For a range up to 29 i get this: true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28] the sixth value that passes the test of having an exact solution is 20 so that would mean that the last number i got that cannot be bought in exact quantity is 19 that doesn't seem quite right, does it? def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True return False truelist=[] falselist=[] for n_nuggets in range(30): result = can_buy(n_nuggets) if result==True: truelist=truelist+[n_nuggets,] else: falselist=falselist+[n_nuggets,] print 'true',truelist print 'false',falselist tnx Baba From andrei.avk at gmail.com Fri Aug 13 14:30:57 2010 From: andrei.avk at gmail.com (AK) Date: Fri, 13 Aug 2010 14:30:57 -0400 Subject: Python Tutorial Message-ID: <4C658F61.9010708@gmail.com> Hello, I plan to make a new python tutorial and I'd like to collaborate with someone on it. I'm thinking of a slightly different approach than existing tutorials: the idea is that readers will learn from examples, going from small but complete and useful scripts to larger programs, similar to Django by Example: http://lightbird.net/dbe/ If you are interested and have a few years of experience with Python, drop me an email and we'll discuss this further... -ak From lie.1296 at gmail.com Fri Aug 13 14:31:45 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 14 Aug 2010 04:31:45 +1000 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <4c658ab2$1@dnews.tpgi.com.au> On 08/10/10 06:36, Bartc wrote: > And if the context is Python, I doubt whether the choice of 0-based over a > 1-based makes that much difference in execution speed. And I doubt anyone cares about execution speed when deciding whether to use 1-based or 0-based array. The reason why you want to choose the alternative that use less conversion to the other system is to simplify the source code. Many common mathematical/physics/economics formulas are expressed much simply if we use 0-based counting: * arithmetic series: - 1-based: s(n) = a + (n - 1) * d - 0-based: s(n) = a + n * d * geometric series: - 1-based: g(n) = a * r**(n - 1) - 0-based: g(n) = a * r**n * equation of motion: - 1-based: x(t) = a + 1/2 * a * (t - 1)**2 - 0-based: x(t) = a + 1/2 * a * t**2 * exponential growth/decay: - 1-based: d(t) = a * e**(k * (t - 1)) - 0-based: d(t) = a * e**(k*t) In fact, most textbooks would already uses 0-based formula for some of these formulas already. Most physics and economic textbooks would show the base 0 variation of the formula, and refers to t=0 as the point in time where the "event" started. I often used this model of thinking for 0-based array indices (and negative indices): -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 (7) instead of: In short, the choice of 0-based array is of practical purpose, rather than historical purpose. From lie.1296 at gmail.com Fri Aug 13 14:43:50 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 14 Aug 2010 04:43:50 +1000 Subject: Python "why" questions In-Reply-To: <4c658ab2$1@dnews.tpgi.com.au> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <4c658ab2$1@dnews.tpgi.com.au> Message-ID: <4c658d87$1@dnews.tpgi.com.au> Sorry the message gets cuts off by an accidental press of send button. On 08/14/10 04:31, Lie Ryan wrote: > On 08/10/10 06:36, Bartc wrote: >> And if the context is Python, I doubt whether the choice of 0-based over a >> 1-based makes that much difference in execution speed. > > And I doubt anyone cares about execution speed when deciding whether to > use 1-based or 0-based array. The reason why you want to choose the > alternative that use less conversion to the other system is to simplify > the source code. > > Many common mathematical/physics/economics formulas are expressed much > simply if we use 0-based counting: > > * arithmetic series: > - 1-based: s(n) = a + (n - 1) * d > - 0-based: s(n) = a + n * d > * geometric series: > - 1-based: g(n) = a * r**(n - 1) > - 0-based: g(n) = a * r**n > * equation of motion: > - 1-based: x(t) = a + 1/2 * a * (t - 1)**2 > - 0-based: x(t) = a + 1/2 * a * t**2 > * exponential growth/decay: > - 1-based: d(t) = a * e**(k * (t - 1)) > - 0-based: d(t) = a * e**(k*t) > > > In fact, most textbooks would already uses 0-based formula for some of > these formulas already. Most physics and economic textbooks would show > the base 0 variation of the formula, and refers to t=0 as the point in > time where the "event" started. > > I often used this model of thinking for 0-based array indices (and > negative indices): > > -7 -6 -5 -4 -3 -2 -1 > +---+---+---+---+---+---+---+ > | c | h | a | r | l | i | e | > +---+---+---+---+---+---+---+ > 0 1 2 3 4 5 6 (7) > > instead of: > so to repeat, I often use this model of thinking: -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 (7) instead of: -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 that is, the indices refers to the "gap" between the array entries. The "gap index" model highlights the naturalness of using 0-based array, negative indices, array slicing, and half-open. From wxjmfauth at gmail.com Fri Aug 13 14:46:50 2010 From: wxjmfauth at gmail.com (jmfauth) Date: Fri, 13 Aug 2010 11:46:50 -0700 (PDT) Subject: Floating numbers References: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> <24495a41-bae0-4965-9bfb-de55230c632d@a36g2000yqc.googlegroups.com> Message-ID: <77846e0a-251b-41f4-85d6-4e23e3dd260f@d8g2000yqf.googlegroups.com> On 13 ao?t, 17:43, Mark Dickinson wrote: > On Aug 13, 3:03?pm, jmfauth wrote: > > > > > A quick question. > > > I understand how to get these numbers > > > 34.52000000000000312638803734444081783294677734375 > > > and > > > 47 (from 2**47) > > > and the sign. > > > with the decimal module, but I fail to find this one > > > 4858258098025923 > > > Possible? > > See the float.as_integer_ratio method. > > -- > Mark Thanks. I *stupidely* forget this. jmf From hansmu at xs4all.nl Fri Aug 13 15:14:40 2010 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 13 Aug 2010 21:14:40 +0200 Subject: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT) In-Reply-To: <7762bda5-e1dc-461c-82a1-7eaa431b5bef@x25g2000yqj.googlegroups.com> References: <7762bda5-e1dc-461c-82a1-7eaa431b5bef@x25g2000yqj.googlegroups.com> Message-ID: <4c6599df$0$22933$e4fe514c@news.xs4all.nl> tormod wrote: > On Aug 12, 12:30 pm, Alexander Gattin wrote: >> Does Windows have anything like LD_LIBRARY_PATH/SHLIB_PATH? Yes and no. Windows uses PATH both for finding execuables and for finding DLLs. So if there's a DLL Windows cannot find, you need to add the folder containing that DLL to your PATH variable. > No, isn't that only if I have an actual Oracle client installed (not > the instant client)? Whether you use the instant client or an actual Oracle client is not the issue. You may or may not need LD_LIBRARY_PATH either way. When you import cx_Oracle on Linux, it loads a file named cx_Oracle.so which in turn loads two files named libclntsh.so and libnnz10.so. These two files are part of the Oracle client installation. The dynamic loader has a list of directories where it tries to find these files; if they aren't there, then the import of cx_Oracle will fail. In that case, you need to set LD_LIBRARY_PATH to the directory containing them (or talk your sysadmin into adding this directory to the default path. He'd do that by adding the directory to /etc/ld.so.conf and running ldconfig). Hope this helps, -- HansM From ian.g.kelly at gmail.com Fri Aug 13 15:25:07 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 13 Aug 2010 13:25:07 -0600 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> Message-ID: On Fri, Aug 13, 2010 at 12:25 PM, Baba wrote: > Hi News 123, > > Ok i'm getting closer. I am able to write code that will output values > that can be bought in exact quantity (truelist) and values that cannot > be bought in exact quantities. > > For a range up to 29 i get this: > true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] > false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, > 28] > > the sixth value that passes the test of having an exact solution is 20 > so that would mean that the last number i got that cannot be bought in > exact quantity is 19 > > that doesn't seem quite right, does it? It's not. You're not just trying to find the sixth value that can be bought in exact quantity, but a sequence of six values that can all be bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not sequential. From alister.ware at ntlworld.com Fri Aug 13 15:30:26 2010 From: alister.ware at ntlworld.com (Alister Ware) Date: Fri, 13 Aug 2010 19:30:26 GMT Subject: How do I get number of files in a particular directory. References: <26eb8bc6-f9e8-4fa8-ac3e-5d22e6335131@s17g2000prh.googlegroups.com> <862915e1-ab44-4600-9ee6-80a4add48b5a@p12g2000prn.googlegroups.com> Message-ID: On Fri, 13 Aug 2010 07:40:42 -0700, blur959 wrote: > Hi all, I got a problem with my script. Everything looks good so far but > for some reason my os.rename isn't working. Can anyone tell me why? Hope > you guys could help. Thanks. > You have a number of logic flaws in your code. 1st you do not actually need to know how many matching files you have. 2nd you need to rename the file inside the same loop that is splitting your file name (this is why you are failing, your rename loop has the same filename each time around), I knocked up a quick hack loosely based on your original code that will generate the file names for you. it has some stratigic print statements so you can see what is happening (always a good idea when debugging code) I have left the actual re-naming of the files for you to complete, I would also agree with the earlier suggestion that you work through some on line tutorials import os import glob def rename(filelist): #function to add a count to each filenale in a list count=0 for fullname in filelist: count+=1 print "full file path %s" % fullname path,filename=os.path.split(fullname) name,ext=os.path.splitext(filename) print "path: '%s' Name: '%s' Extn: '%s'" % (path,name,ext) newname="%s_%04d.%s" %(name,count,ext) print "New filename: '%s'" % newname # rename filename to newname goes here # dont forget you also need path directory = raw_input("directory? ") ext = raw_input("file extension? ") r = raw_input("replace name") pattern = os.path.join(directory, "*." + ext) matching_files = glob.glob(pattern) rename(matching_files) -- Nothing makes one so vain as being told that one is a sinner. Conscience makes egotists of us all. -- Oscar Wilde From inhahe at gmail.com Fri Aug 13 15:54:52 2010 From: inhahe at gmail.com (inhahe) Date: Fri, 13 Aug 2010 12:54:52 -0700 (PDT) Subject: struct pointing to another struct? Message-ID: say i have this definition: 1 typedef struct SDL_Surface { 2 Uint32 flags; /* Read-only */ 3 SDL_PixelFormat *format; /* Read-only */ 4 int w, h; /* Read-only */ 5 Uint16 pitch; /* Read-only */ 6 void *pixels; /* Read-write */ 7 SDL_Rect clip_rect; /* Read-only */ 8 int refcount; /* Read-mostly */ 9 10 /* This structure also contains private fields not shown here */ 11 } SDL_Surface; notice two pointers, format and pixels. say format has this definition. 1 typedef struct { 2 SDL_Palette *palette; 3 Uint8 BitsPerPixel; 4 Uint8 BytesPerPixel; 5 Uint8 Rloss, Gloss, Bloss, Aloss; 6 Uint8 Rshift, Gshift, Bshift, Ashift; 7 Uint32 Rmask, Gmask, Bmask, Amask; 8 Uint32 colorkey; 9 Uint8 alpha; 10 } SDL_PixelFormat; so say i want to create a mock sdl handle and pass it to some library function that requires an sdl handle. (would it even work? would i need to use an SDL_SWSURFACE?) so i make the pixelformat data using struct.pack, and make the surface data using struct.pack, but how do i link the surface data to the pixelformat data? if i just use id() it'll give me the memory address of the "box" for the string and not the string data itself. thanks. From __peter__ at web.de Fri Aug 13 16:07:45 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 22:07:45 +0200 Subject: struct pointing to another struct? References: Message-ID: inhahe wrote: > say i have this definition: > > 1 typedef struct SDL_Surface { > 2 Uint32 flags; /* Read-only */ > 3 SDL_PixelFormat *format; /* Read-only */ > 4 int w, h; /* Read-only */ > 5 Uint16 pitch; /* Read-only */ > 6 void *pixels; /* Read-write */ > 7 SDL_Rect clip_rect; /* Read-only */ > 8 int refcount; /* Read-mostly */ > 9 > 10 /* This structure also contains private fields not shown here > */ > 11 } SDL_Surface; > > notice two pointers, format and pixels. > say format has this definition. > > > 1 typedef struct { > 2 SDL_Palette *palette; > 3 Uint8 BitsPerPixel; > 4 Uint8 BytesPerPixel; > 5 Uint8 Rloss, Gloss, Bloss, Aloss; > 6 Uint8 Rshift, Gshift, Bshift, Ashift; > 7 Uint32 Rmask, Gmask, Bmask, Amask; > 8 Uint32 colorkey; > 9 Uint8 alpha; > 10 } SDL_PixelFormat; > > so say i want to create a mock sdl handle and pass it to some library > function that requires an sdl handle. (would it even work? would i > need to use an SDL_SWSURFACE?) > > so i make the pixelformat data using struct.pack, and make the surface > data using struct.pack, but how do i link the surface data to the > pixelformat data? if i just use id() it'll give me the memory address > of the "box" for the string and not the string data itself. thanks. I think you are looking at the wrong module; you need ctypes, not struct. http://docs.python.org/library/ctypes.html Peter From news1234 at free.fr Fri Aug 13 16:22:44 2010 From: news1234 at free.fr (News123) Date: Fri, 13 Aug 2010 22:22:44 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4C645EB9.7060105@optimum.net> <0E6BB339-057C-4B78-A0EB-AC4EA2FAF152@gmail.com> Message-ID: <4c65a994$0$20281$426a74cc@news.free.fr> Roald, What would your solution be if you weren't allowed to 'know' that 120 is an upper limit. Assume you were only allowed to 'know', that you won't find any other amount, which can't be bought A AOON A you found six solutions in a row? I have a rather straightforward solution trying from 0 nuggets on until I found six 'hits' in a row, but would be interested about other idioms. On 08/13/2010 12:38 PM, Roald de Vries wrote: > On Aug 13, 2010, at 12:25 PM, Roald de Vries wrote: >> My previous algorithm was more efficient, but for those who like >> one-liners: >> >> [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) >> for b in range(x/9) for c in range(x/6))][-1] > > OK, I did some real testing now, and there's some small error in the > above. All solutions for all x's are given by: > > [(x, a, b, c) for x in range(120) for a in range(x/20+1) for b in > range(x/9+1) for c in range(x/6+1) if x == a*20+b*9+c*6] > > ... and all non-solutions by: > > [x for x in range(120) if not any(x == a*20+b*9+c*6 for a in > range(x/20+1) for b in range(x/9+1) for c in range(x/6+1))] > > Cheers, Roald From inhahe at gmail.com Fri Aug 13 16:28:08 2010 From: inhahe at gmail.com (inhahe) Date: Fri, 13 Aug 2010 13:28:08 -0700 (PDT) Subject: struct pointing to another struct? References: Message-ID: On Aug 13, 4:07?pm, Peter Otten <__pete... at web.de> wrote: > inhahe wrote: > > say i have this definition: > > > ? ?1 typedef struct SDL_Surface { > > ? ?2 ? ? Uint32 flags; ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-only */ > > ? ?3 ? ? SDL_PixelFormat *format; ? ? ? ? ? ? ? ?/* Read-only */ > > ? ?4 ? ? int w, h; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-only */ > > ? ?5 ? ? Uint16 pitch; ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-only */ > > ? ?6 ? ? void *pixels; ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-write */ > > ? ?7 ? ? SDL_Rect clip_rect; ? ? ? ? ? ? ? ? ? ? /* Read-only */ > > ? ?8 ? ? int refcount; ? ? ? ? ? ? ? ? ? ? ? ? ? /* Read-mostly */ > > ? ?9 > > ? 10 ? /* This structure also contains private fields not shown here > > */ > > ? 11 } SDL_Surface; > > > notice two pointers, format and pixels. > > say format has this definition. > > > ? ?1 typedef struct { > > ? ?2 ? SDL_Palette *palette; > > ? ?3 ? Uint8 ?BitsPerPixel; > > ? ?4 ? Uint8 ?BytesPerPixel; > > ? ?5 ? Uint8 ?Rloss, Gloss, Bloss, Aloss; > > ? ?6 ? Uint8 ?Rshift, Gshift, Bshift, Ashift; > > ? ?7 ? Uint32 Rmask, Gmask, Bmask, Amask; > > ? ?8 ? Uint32 colorkey; > > ? ?9 ? Uint8 ?alpha; > > ? 10 } SDL_PixelFormat; > > > so say i want to create a mock sdl handle and pass it to some library > > function that requires an sdl handle. (would it even work? would i > > need to use an SDL_SWSURFACE?) > > > so i make the pixelformat data using struct.pack, and make the surface > > data using struct.pack, but how do i link the surface data to the > > pixelformat data? ?if i just use id() it'll give me the memory address > > of the "box" for the string and not the string data itself. ?thanks. > > I think you are looking at the wrong module; you need ctypes, not struct. > > http://docs.python.org/library/ctypes.html > > Peter can you (or anybody) tell me how to link one c struct to another using ctypes? Thx From jjposner at optimum.net Fri Aug 13 16:28:52 2010 From: jjposner at optimum.net (John Posner) Date: Fri, 13 Aug 2010 16:28:52 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> <4C645EB9.7060105@optimum.net> Message-ID: <4C65AB04.6000405@optimum.net> On 8/13/2010 6:25 AM, Roald de Vries wrote: > On Aug 12, 2010, at 10:51 PM, John Posner wrote: >> On 8/12/2010 9:22 AM, Dave Angel wrote: >>>> >>>> Now you have to find the largest number below 120, which you can >>>> easily do with brute force >> tgt = 120 # thanks, Dave Angel > > Anytime, but I'm not Dave Angel. Oops -- sorry for the erroneous attribution, Roald. -John From kxepal at gmail.com Fri Aug 13 16:47:09 2010 From: kxepal at gmail.com (Kxepal) Date: Fri, 13 Aug 2010 13:47:09 -0700 (PDT) Subject: Dump logging configuration Message-ID: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> Hi all! Sorry for dumb question if it is - I'd tried to google it before but have found nothing. Is there any way to dump current logging configuration for future loading it via fileConfig/dictConfig? From vamsikrishna.bandlamudi at gmail.com Fri Aug 13 16:50:48 2010 From: vamsikrishna.bandlamudi at gmail.com (Vamsi) Date: Fri, 13 Aug 2010 13:50:48 -0700 (PDT) Subject: Help to convert Number to String Message-ID: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> I am trying to count the number of lines in a file and insert into the file but getting the error message "TypeError: must be string or read-only character buffer, not int", Could you please help me how to correct this? here is the code lines1 = sum(1 for line in open('C:/test1.txt')) wfile = open('C:/test1.txt'', 'a') wfile.write(str(lines1).zfill(9)) wfile.close() Thanks. From news1234 at free.fr Fri Aug 13 17:02:52 2010 From: news1234 at free.fr (News123) Date: Fri, 13 Aug 2010 23:02:52 +0200 Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c645c7c$0$3675$426a74cc@news.free.fr> Message-ID: <4c65b2fd$0$11772$426a74cc@news.free.fr> On 08/13/2010 10:57 AM, Martin P. Hellwig wrote: > SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION > > On 08/12/10 21:41, News123 wrote: > >> On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: >>> On 08/11/10 21:14, Baba wrote: >>> >>> >>> How about rephrasing that question in your mind first, i.e.: >>> >>> For every number that is one higher then the previous one*: >>> If this number is dividable by: >>> 6 or 9 or 20 or any combination of 6, 9, 20 >>> than this number _can_ be bought in an exact number >>> else >>> print this number >>> >> >> you are allowed to mix. >> 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 > > I was aware of that, thats whhy I wrote: > "or any combination of 6, 9, 20" > >> >> I guess, trying to find the result with divisions and remainders is >> overly complicated. > > Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) > [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 > Type "help", "copyright", "credits" or "license" for more information. >>>> MODULO_COMBINATIONS = [[20], [9], [6], > ... [20, 9], [20, 6], [9, 20], > ... [9, 6], [6, 20], [6, 9], > ... [20, 9, 6], [20, 6, 9], [9, 20, 6], > ... [9, 6, 20], [6, 20, 9], [6, 9, 20]] >>>> >>>> def apply_combinations_on(number): > ... tmp = list() > ... for combination in MODULO_COMBINATIONS: > ... remainder = number > ... for modulo_value in combination: > ... if remainder == 0: > ... remainder = None > ... break > ... > ... result = remainder % modulo_value > ... > ... if result == remainder : > ... remainder = None > ... break > ... > ... remainder = result > ... > ... if remainder == 0: > ... tmp.append(str(combination)) > ... return(tmp) > ... >>>> print(apply_combinations_on(15)) > ['[9, 6]'] >>>> > > What is so over complicated about it? What I meant with complicated is your mathematical assumption about modulos, which are probably not obvious to everybody on the first glance. Saying, that you can find out, whether for integers a,b.c,n the equation n = a*6 + b*9 + c*20 is true by verifying whether n mod 6 == 0 or n mod 9 == 0 or (n mod 6) mod 9 == 0 or (n mod 9) mod 6 == 0 Trial error is not so smart, but much easier to explain to beginners. One can even return a,b,c for verification. Being a little (and incrementally) smart, the search space can then be reduced by some degrees with rather easy to explain and incremental assumptions, For given example the run times are so short, that it's not really an issue. Another advantage of brute force is, that you can return a,b,c and not only say, whether a,b,c exist. This allows simple verification or assertions during debugging and learning. # plain brute force. #------------------------------------ def can_buy(n_nuggets): for a in range (n_nuggets): for b in range (n_nuggets): for c in range (n_nuggets): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a + 9*b + 20*c == n_nuggets: return (a,b,c) return () # brute force but reduce the upper limit for each loop by saying, # that one can stop if one a*6 > n or b*9 > n or c*20 >n #------------------------------------------ def can_buy(n_nuggets): for a in range (n_nuggets / 6 + 1): for b in range (n_nuggets / 9 + 1): for c in range (n_nuggets / 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a + 9*b + 20*c == n_nuggets: return (a,b,c) return () # as above code, but try even less in inner loops by # removing what has been taken in outer loop #-------------------------------------------- def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1, left_6 / 9 + 1): left_9 = left_6 - b * 9 for c in range (1, left_9/ 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a+9*b+20*c==n_nuggets: return (a,b,c) return () # as above code, but do less multiplications # in inner loop #------------------------------------------- def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1, left_6 / 9 + 1): left_9 = left_6 - b * 9 for c in range (1, left_9/ 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 20*c == left_9: return (a,b,c) return () # as above code, but use modulo in inner loop # ------------------------------------------ def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1, left_6 / 9 + 1): left_9 = left_6 - b * 9 print "trying for %2d: %2d %2d c" % (n,a,b) if left_9 % 20 == 0: return (a,b,left_9/20) return () From __peter__ at web.de Fri Aug 13 17:03:32 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Aug 2010 23:03:32 +0200 Subject: struct pointing to another struct? References: Message-ID: inhahe wrote: > On Aug 13, 4:07 pm, Peter Otten <__pete... at web.de> wrote: >> inhahe wrote: >> > say i have this definition: >> >> > 1 typedef struct SDL_Surface { >> > 2 Uint32 flags; /* Read-only */ >> > 3 SDL_PixelFormat *format; /* Read-only */ >> > 4 int w, h; /* Read-only */ >> > 5 Uint16 pitch; /* Read-only */ >> > 6 void *pixels; /* Read-write */ >> > 7 SDL_Rect clip_rect; /* Read-only */ >> > 8 int refcount; /* Read-mostly */ >> > 9 >> > 10 /* This structure also contains private fields not shown here >> > */ >> > 11 } SDL_Surface; >> >> > notice two pointers, format and pixels. >> > say format has this definition. >> >> > 1 typedef struct { >> > 2 SDL_Palette *palette; >> > 3 Uint8 BitsPerPixel; >> > 4 Uint8 BytesPerPixel; >> > 5 Uint8 Rloss, Gloss, Bloss, Aloss; >> > 6 Uint8 Rshift, Gshift, Bshift, Ashift; >> > 7 Uint32 Rmask, Gmask, Bmask, Amask; >> > 8 Uint32 colorkey; >> > 9 Uint8 alpha; >> > 10 } SDL_PixelFormat; >> >> > so say i want to create a mock sdl handle and pass it to some library >> > function that requires an sdl handle. (would it even work? would i >> > need to use an SDL_SWSURFACE?) >> >> > so i make the pixelformat data using struct.pack, and make the surface >> > data using struct.pack, but how do i link the surface data to the >> > pixelformat data? if i just use id() it'll give me the memory address >> > of the "box" for the string and not the string data itself. thanks. >> >> I think you are looking at the wrong module; you need ctypes, not struct. >> >> http://docs.python.org/library/ctypes.html >> >> Peter > > can you (or anybody) tell me how to link one c struct to another using > ctypes? Thx I know it sounds old-fashioned, but the documentation is worth reading. It contains examples for structs, pointers and arrays, e. g. """ >>> from ctypes import * >>> class cell(Structure): ... pass ... >>> cell._fields_ = [("name", c_char_p), ... ("next", POINTER(cell))] >>> """ Peter From news1234 at free.fr Fri Aug 13 17:09:30 2010 From: news1234 at free.fr (News123) Date: Fri, 13 Aug 2010 23:09:30 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> Message-ID: <4c65b48a$0$12630$426a74cc@news.free.fr> Hi BAba, On 08/13/2010 09:25 PM, Ian Kelly wrote: > On Fri, Aug 13, 2010 at 12:25 PM, Baba wrote: >> Hi News 123, >> >> Ok i'm getting closer. I am able to write code that will output values >> that can be bought in exact quantity (truelist) and values that cannot >> be bought in exact quantities. >> >> For a range up to 29 i get this: >> true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] >> false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, >> 28] >> >> the sixth value that passes the test of having an exact solution is 20 >> so that would mean that the last number i got that cannot be bought in >> exact quantity is 19 >> >> that doesn't seem quite right, does it? As Thomas says: > > It's not. You're not just trying to find the sixth value that can be > bought in exact quantity, but a sequence of six values that can all be > bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not > sequential. Six True values in a row without a False value n between tells you, that you can stop searching. So you that's what you have to write A piece of code, which fetches true fals values for 0 to e.g. 200 nuggets and stops if you had 6 True values in a row. Think how you do it manually: you can try this even without the can_buy function and plug in th can_buy() function only if you ahve your detection of 6 True values in a row working. test_sequence = "0010011011101110111101111111011111" # below I use the enumerate function. # rather useful for going through a list AND having a counter value. # when plugging in your function you can switch back to # for n_nuggets in xramge(200): # perhaps here some initialisation for your searching for i, a_char in enumerat(test_suequence): print "entry %2d (%s) is %s" % (i,a_char,result) result = a_char == '1' # result is now true for a '1' # and false for a '0' # here some code to determine the length of the sequence if sequence_length == 6: print "I found a sequence of 6 and can stop searching" print "my solution is " From python at rcn.com Fri Aug 13 17:12:28 2010 From: python at rcn.com (Raymond Hettinger) Date: Fri, 13 Aug 2010 14:12:28 -0700 (PDT) Subject: shelf-like list? References: Message-ID: On Aug 12, 1:37?pm, Thomas Jollans wrote: > On Tuesday 10 August 2010, it occurred to kj to exclaim: > > > I'm looking for a module that implements "persistent lists": objects > > that behave like lists except that all their elements are stored > > on disk. ?IOW, the equivalent of "shelves", but for lists rather > > than a dictionaries. . . . > You could simply use pickle to save the data every once in a while. That is a very reasonable solution. From gelonida at gmail.com Fri Aug 13 17:13:26 2010 From: gelonida at gmail.com (Gelonida) Date: Fri, 13 Aug 2010 23:13:26 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: On 08/13/2010 09:11 AM, Gelonida wrote: > Lee, > > On 08/13/2010 12:53 AM, Lee Harr wrote: >> >>> I'm desperate. I'm having a real application, which fails rather often >>> when finishing it. I'm not sure, whether any serious problem could be >>> hidden behind it >>> >>> The script is a pyqt script, which segfaults most of the time on my >>> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. >> >> >> Looks to be a known issue: >> http://www.google.com/search?q=pyqt+segfault+on+exit >> https://launchpad.net/bugs/561303 >> >> The last activity on that bug is almost 2 months ago... >> Hopefully the fix will be distributed soon. > > > > This seems to be the problem. > > > In my case I can workaround the issue by adding one line. > > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > myform = None # <<<< THIS IS THE WORK AROUND > print "last" > For more complex multi widget examples it doesn't seem enough to just destroy the main widget. probably I had to recursively assign all widgets / dialogues sub widgets to None. So I'll just try to stay away from this pyqt release and stick with older or newer ones. From gelonida at gmail.com Fri Aug 13 17:13:37 2010 From: gelonida at gmail.com (Gelonida) Date: Fri, 13 Aug 2010 23:13:37 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: On 08/13/2010 09:11 AM, Gelonida wrote: > Lee, > > On 08/13/2010 12:53 AM, Lee Harr wrote: >> >>> I'm desperate. I'm having a real application, which fails rather often >>> when finishing it. I'm not sure, whether any serious problem could be >>> hidden behind it >>> >>> The script is a pyqt script, which segfaults most of the time on my >>> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. >> >> >> Looks to be a known issue: >> http://www.google.com/search?q=pyqt+segfault+on+exit >> https://launchpad.net/bugs/561303 >> >> The last activity on that bug is almost 2 months ago... >> Hopefully the fix will be distributed soon. > > > > This seems to be the problem. > > > In my case I can workaround the issue by adding one line. > > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > myform = None # <<<< THIS IS THE WORK AROUND > print "last" > For more complex multi widget examples it doesn't seem enough to just destroy the main widget. probably I had to recursively assign all widgets / dialogues sub widgets to None. So I'll just try to stay away from this pyqt release and stick with older or newer ones. From xahlee at gmail.com Fri Aug 13 17:18:53 2010 From: xahlee at gmail.com (Xah Lee) Date: Fri, 13 Aug 2010 14:18:53 -0700 (PDT) Subject: math symbols in unicode (grouped by purpose) Message-ID: some collection of math symbols in unicode. ? Math Symbols in Unicode http://xahlee.org/comp/unicode_math_operators.html ? Arrows in Unicode http://xahlee.org/comp/unicode_arrows.html ? Matching Brackets in Unicode http://xahlee.org/comp/unicode_matching_brackets.html these are grouped by the symbol's purpose as much as possible. i made them because i can't find unicode symbols grouped by purpose elsewhere. The unicode ?plane -> block? structure does not group symbols well, because the chars are added throughout the decades. Some symbols get added in one block, but later on related symbols get added elsewhere. For example, binary relational symbols are scattered in different unicode blocks. Same for binary operators, or all symbols used for set theory, etc. Sometimes a symbol has multiple uses in different math fields, so which block it gets added into unicode is not well defined. hope it's useful to some one. Xah ? http://xahlee.org/ ? From aahz at pythoncraft.com Fri Aug 13 17:34:57 2010 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2010 14:34:57 -0700 Subject: Floating numbers References: <595969e7-354f-456d-82b5-6aeafbabe419@d8g2000yqf.googlegroups.com> Message-ID: In article <595969e7-354f-456d-82b5-6aeafbabe419 at d8g2000yqf.googlegroups.com>, Mark Dickinson wrote: > > - If you *really* need a number that represents the *exact* value >34.52, then use the decimal module, or perhaps consider using a simple >home-brewed fixed-point representation. Don't use a home-brew fixed-point, rely on Uncle Tim! http://pythoncraft.com/FixedPoint.py -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From tjreedy at udel.edu Fri Aug 13 18:09:49 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Aug 2010 18:09:49 -0400 Subject: Python "why" questions In-Reply-To: References: Message-ID: On 8/13/2010 11:27 AM, Den wrote: > > I smile every time I see the non-nonsensical sentence "The first > thing, therefore, is in thing[0]" in a programming language learning > book or tutorial. I laugh every time I hear someone defend that as > common sense. If one thinks in terms of slicing at gap positions, the 'proper' indexes would range from 0.5 (average of 0 and 1) to n-0.5. For convenience, we round down or up. To put it another way, seq[n:n+1] is abbreviated as either seq[n] or seq[n+1]. Put this way, the first choice is at least as sensible as the second. Given that Python allows indexing from both end, I prefer 0,1,2,... and -1,-2,-3,... to 1,2,3... and 0,-1,-2,... or 1,2,3,... and -1,-2,-3. As someone else pointed out, discretizing a continuous variable starting at 0 gives 0,1,2,... so having indexes that match is handy. If a problem is formulated in terms of 1,2,3, one can simply leave the first cell blank rather than reformulate. If a problem is formulated in terms of 0,1,2,... and indexes are 1 based, then one must reformulate. > Every three year old watching Sesame Street knows > counting things starts with '1', not '0'. And that is the same mistake that most societies make, the mistake that put a lid on Greak math, science, and finance. All fresh counts begin with 0. Counting by people usually begins with a silent 0, just as fresh tallies begin with a blank stick or paper. But not always. For instance, lets count the people who have, up to noe, become billionaires with Python. We start with an overt 0. Now we can discuss whether the founders of Google should increase that to 2. Mechanical counting requires an overt 0. A car odometer starts at 0, not 1 and not . Have you never written a counting program? Starting with n = 1 instead of n = 0 before counting the first item would be a bad bug. > There may be loads of reasons for it, but don't throw common sense > around as one of them. I won't. Only a few (about 3 or 4) societies included a proper 0 in their number systems. -- Terry Jan Reedy From paddy3118 at googlemail.com Fri Aug 13 18:19:55 2010 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 13 Aug 2010 15:19:55 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <4c64d9cf$0$28668$c3e8da3@news.astraweb.com> Message-ID: <51310abd-bc61-434b-9498-ba055b469f95@a36g2000yqc.googlegroups.com> On Aug 13, 6:36?am, Steven D'Aprano wrote: > On Thu, 12 Aug 2010 13:20:19 -0700, Paddy wrote: > > I find myself needing to calculate the difference between two Counters > > or multisets or bags. > > Is this collections.Counter from Python 3.1? If so, you should say so, > and if not, you should tell us which Counter class this is. It will save > people (by which I mean *me*) from spending an unrewarding few minutes > trying to import Counter in Python 2.5 and writing up a sarcastic > response ... :) > > > I want those items that are unique to each bag. I know how to calculate > > it: > > > ? ? >>> b = Counter(a=1, b=2) > > ? ? >>> c = Counter(a=3, b=1) > > ? ? >>> diff = (b - c) + (c - b) > > ? ? >>> (b - c) > > ? ? Counter({'b': 1}) > > ? ? >>> (c - b) > > ? ? Counter({'a': 2}) > > ? ? >>> diff > > ? ? Counter({'a': 2, 'b': 1}) > > > But thought why doesn't this operation appear already as a method of the > > class? > > Don't know. Perhaps you should put in a feature request. > > -- > Steven Yes it is Counter in both 3.1 and 2.7 (And somewhere on Activestate too). Before I put in a feature request, I wanted to know if other have seen the need. From tjreedy at udel.edu Fri Aug 13 18:25:46 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Aug 2010 18:25:46 -0400 Subject: writing \feff at the begining of a file In-Reply-To: <4C651438.50203@sequans.com> References: <4C651438.50203@sequans.com> Message-ID: A short background to MRAB's answer which I will try to get right. The byte-order-mark was invented for UTF-16 encodings so the reader could determine whether the pairs of bytes are in little or big endiean order, depending on whether the first two bute are fe and ff or ff and fe (or maybe vice versa, does not matter here). The concept is meaningless for utf-8 which consists only of bytes in a defined order. This is part of the Unicode standard. However, Microsoft (or whoever) re-purposed (hijacked) that pair of bytes to serve as a non-standard indicator of utf-8 versus any non-unicode encoding. The result is a corrupted utf-8 stream that python accommodates with the utf-8-sig(nature) codec (versus the standard utf-8 codec). -- Terry Jan Reedy From ian.g.kelly at gmail.com Fri Aug 13 19:10:16 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 13 Aug 2010 17:10:16 -0600 Subject: Python "why" questions In-Reply-To: References: Message-ID: On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie wrote: > In a higher level language 1-based indexing is just as limiting as 0- > based indexing. What you really want is the ability to declare the index > range to suit the problem: in Algol 60 it is very useful to be able to > declare something like: > > ? ? ? ?real sample[-500:750]; Ugh, no. The ability to change the minimum index is evil. I don't much care whether a high-level language uses 0-based or 1-based indexing, but I do care that it is consistent. On the occasions when I am forced to use Visual Basic, the single biggest wart that drives me up a wall is constantly having to figure out whether the particular thing that I am currently indexing is 0-based or 1-based. Cheers, Ian From sschwarzer at sschwarzer.net Fri Aug 13 19:27:24 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 14 Aug 2010 01:27:24 +0200 Subject: Help to convert Number to String In-Reply-To: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> Message-ID: <4C65D4DC.7080101@sschwarzer.net> Hi Vamsi, On 2010-08-13 22:50, Vamsi wrote: > I am trying to count the number of lines in a file and insert into > the file but getting the error message "TypeError: must be string or > read-only character buffer, not int", Could you please help me how to > correct this? Which Python version do you use? For which statement exactly do you get the message? > here is the code > > lines1 = sum(1 for line in open('C:/test1.txt')) > wfile = open('C:/test1.txt'', 'a') You have two quotes here after the filename. These give a SyntaxError here. Python sees two concatenated strings, "C:/test1.txt" and ", " and stumbles over the a immediately after the closing quote of the second string. > wfile.write(str(lines1).zfill(9)) > wfile.close() If I remove the redundant quote character and substitute filenames appropriate for my system, everything works. Maybe the code you included in this post isn't the same which led to the error? Stefan From me+list/python at ixokai.io Fri Aug 13 19:37:40 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Fri, 13 Aug 2010 16:37:40 -0700 Subject: Simple Python Sandbox Message-ID: <4C65D744.10201@ixokai.io> Howdy-ho. So, I'm working on a project which embeds Python into a bigger system to provide extensibility. In this project, there's basically two types of people who will be entering python code. The trusted folks, who write code which are in files, and which can do anything. The untrusted folks, who are writing very simple chunks of code which can only do limited things. This latter group we want to sandbox as good as possible. Now, I know that its not possible to perfectly sandbox Python, and I know certain things will never be perfectly safe (like someone doing some crazy [0] * 100000 * 100000 and similar things). That's OK. For this sandbox, we're killing import, execfile, open, eval, reload in __builtin__. This all works well. However in previous discussions, I learned about: >>> [b for b in (1).__class__.__bases__[0].__class__.__subclasses__((1).__class__.__bases__[0]) if b.__name__ == 'file'][0]('../blahblah', 'w').write("Hi!") >>> ^D ixokai$ more ../blahblah Hi! And things like that. (The above may not be the most efficient way to do it). So, I had an idea: why not just do some simple sanitization. When input comes in, just directly replace __ with DISALLOWED, and add getattr/setattr/delattr to the mix of things we kill out of builtins. This second group of people are doing simple little scripting tasks, and not things that would ever involve needing to access a __method__, not even a normal one like __init__. Most of what they do is me.this or me.that("hi") and such. Occasionally there's a little simple logic, but that's it. Can you think of a way out of such a sandbox? A way to access disallowed stuff, not a way to DOS. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From debatem1 at gmail.com Fri Aug 13 19:57:50 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 13 Aug 2010 16:57:50 -0700 Subject: Simple Python Sandbox In-Reply-To: <4C65D744.10201@ixokai.io> References: <4C65D744.10201@ixokai.io> Message-ID: On Fri, Aug 13, 2010 at 4:37 PM, Stephen Hansen wrote: > Howdy-ho. > > So, I'm working on a project which embeds Python into a bigger system to > provide extensibility. In this project, there's basically two types of > people who will be entering python code. > > The trusted folks, who write code which are in files, and which can do > anything. > > The untrusted folks, who are writing very simple chunks of code which > can only do limited things. > > This latter group we want to sandbox as good as possible. Now, I know > that its not possible to perfectly sandbox Python, and I know certain > things will never be perfectly safe (like someone doing some crazy [0] * > 100000 * 100000 and similar things). That's OK. > > For this sandbox, we're killing import, execfile, open, eval, reload in > __builtin__. This all works well. However in previous discussions, I > learned about: > >>>> [b for b in > (1).__class__.__bases__[0].__class__.__subclasses__((1).__class__.__bases__[0]) > if b.__name__ == 'file'][0]('../blahblah', 'w').write("Hi!") >>>> ^D > ixokai$ more ../blahblah > Hi! > > And things like that. (The above may not be the most efficient way to do > it). So, I had an idea: why not just do some simple sanitization. When > input comes in, just directly replace __ with DISALLOWED, and add > getattr/setattr/delattr to the mix of things we kill out of builtins. > > This second group of people are doing simple little scripting tasks, and > not things that would ever involve needing to access a __method__, not > even a normal one like __init__. Most of what they do is me.this or > me.that("hi") and such. Occasionally there's a little simple logic, but > that's it. > > Can you think of a way out of such a sandbox? A way to access disallowed > stuff, not a way to DOS. You may want to check out repy- they use it in the Seattle restricted execution environment, and some pretty smart people claim it has decent security properties. Here's a summary of some of the things they don't allow: https://seattle.cs.washington.edu/wiki/PythonVsRepy Full disclosure: while I don't directly work on the repy environment, I have worked on some other parts of the Seattle project. Geremy Condra From me+list/python at ixokai.io Fri Aug 13 20:05:59 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Fri, 13 Aug 2010 17:05:59 -0700 Subject: Simple Python Sandbox In-Reply-To: References: <4C65D744.10201@ixokai.io> Message-ID: <4C65DDE7.8030203@ixokai.io> On 8/13/10 4:57 PM, geremy condra wrote: > You may want to check out repy- they use it in the Seattle restricted > execution environment, and some pretty smart people claim it has > decent security properties. Here's a summary of some of the things > they don't allow: > > https://seattle.cs.washington.edu/wiki/PythonVsRepy Thanks, I'll look at it. However, its essential we have a fully capable and powered Python for the first-class of people. They're not sandboxed at all. However, I'll check out what they've done for inspiration. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 21:06:14 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2010 01:06:14 GMT Subject: Help to convert Number to String References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> Message-ID: <4c65ec05$0$28668$c3e8da3@news.astraweb.com> On Fri, 13 Aug 2010 13:50:48 -0700, Vamsi wrote: > I am trying to count the number of lines in a file and insert into the > file but getting the error message "TypeError: must be string or > read-only character buffer, not int", Could you please help me how to > correct this? > > > here is the code > > lines1 = sum(1 for line in open('C:/test1.txt')) > wfile = open('C:/test1.txt'', 'a') > wfile.write(str(lines1).zfill(9)) > wfile.close() No, that ISN'T the code you are using. Don't re-type the code (introducing syntax errors), but copy and paste WORKING code. Also you need to copy and paste the EXACT error message you get, not just paraphrasing it. When I correct the obvious errors in your code above, it works for me: >>> f = open('test', 'w') >>> f.write('hello\nworld\n') 12 >>> f.close() >>> lines1 = sum(1 for line in open('test')) >>> wfile = open('test', 'a') >>> wfile.write(str(lines1).zfill(9)) 9 >>> wfile.close() and the file is correctly updated: >>> open('test').read() 'hello\nworld\n000000002' -- Steven From gogonai.alien76 at gmail.com Fri Aug 13 21:09:22 2010 From: gogonai.alien76 at gmail.com (ali nurwatoni) Date: Fri, 13 Aug 2010 18:09:22 -0700 (PDT) Subject: Dominate Mafia Wars Message-ID: <8b43ef4e-4093-4b06-8a65-49095b9256da@y32g2000prc.googlegroups.com> $27 Guide Show You How To Cheat Your Way To The Top. Guaranteed! http://onlinepartner.org/dominate-mafiawars-game Alinurwatoni Supervisor http://www.gogonai.info/?id=alien76 From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 21:54:27 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2010 01:54:27 GMT Subject: writing \feff at the begining of a file References: <4C651438.50203@sequans.com> Message-ID: <4c65f752$0$28668$c3e8da3@news.astraweb.com> On Fri, 13 Aug 2010 18:25:46 -0400, Terry Reedy wrote: > A short background to MRAB's answer which I will try to get right. > > The byte-order-mark was invented for UTF-16 encodings so the reader > could determine whether the pairs of bytes are in little or big endiean > order, depending on whether the first two bute are fe and ff or ff and > fe (or maybe vice versa, does not matter here). The concept is > meaningless for utf-8 which consists only of bytes in a defined order. > This is part of the Unicode standard. > > However, Microsoft (or whoever) re-purposed (hijacked) that pair of > bytes to serve as a non-standard indicator of utf-8 versus any > non-unicode encoding. The result is a corrupted utf-8 stream that python > accommodates with the utf-8-sig(nature) codec (versus the standard utf-8 > codec). Is there a standard way to autodetect the encoding of a text file? I do this: Open the file in binary mode; if the first three bytes are codecs.BOM_UTF8, then it's a Microsoft UTF-8 text file; otherwise if the first two byes are codecs.BOM_BE or codecs.BOM_LE, the encoding is utf-16- be or utf-16-le respectively. (I don't bother to check for other BOMs, such as for utf-32. There are *lots* of them, but in my experience the encodings are rarely used, and the BOMs aren't defined in the codecs module, so I don't bother to support them.) If there's no BOM, then re-open the file and read the first two lines. If either of them match this regex 'coding[=:]\s*([-\w.]+)' then I take the encoding name from that. This matches Python's behaviour, and supports EMACS and vi encoding declarations. Otherwise, there is no declared encoding, and I use whatever encoding I like (whatever was specified by the user or the application default). -- Steven From vamsikrishna.bandlamudi at gmail.com Fri Aug 13 22:43:38 2010 From: vamsikrishna.bandlamudi at gmail.com (Vamsi) Date: Fri, 13 Aug 2010 19:43:38 -0700 (PDT) Subject: Help to convert Number to String References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> <4C65D4DC.7080101@sschwarzer.net> Message-ID: <1e5a5939-42ab-4d8d-a969-a068dea0cb3a@t2g2000yqe.googlegroups.com> On Aug 13, 7:27?pm, Stefan Schwarzer wrote: > Hi Vamsi, > > On 2010-08-13 22:50, Vamsi wrote: > > > I am trying to count the number of lines in a file and insert ?into > > the file but getting the error message "TypeError: must be string or > > read-only character buffer, not int", Could you please help me how to > > correct this? > > Which Python version do you use? > > For which statement exactly do you get the message? > > > here is the code > > > lines1 = sum(1 for line in open('C:/test1.txt')) > > wfile = open('C:/test1.txt'', 'a') > > You have two quotes here after the filename. These give a > SyntaxError here. Python sees two concatenated strings, > "C:/test1.txt" and ", " and stumbles over the a immediately > after the closing quote of the second string. > > > wfile.write(str(lines1).zfill(9)) > > wfile.close() > > If I remove the redundant quote character and substitute > filenames appropriate for my system, everything works. > > Maybe the code you included in this post isn't the same > which led to the error? > > Stefan Thank you Stefan,I pasted only part of the code.I am new to Python and using 2.7.My actual code is as below, If I run the below code I am getting the error "TypeError: 'str' object is not callable" ,Now I found that I am using the "str" variable which is a function.Thanks a lot for your help. fileopen = open('C:/MPython/test.txt', 'r') str = fileopen.read() print str fileopen.close() lines1 = sum(1 for line in open('C:/MPython/test.txt')) wfile = open('C:/MPython/test.txt', 'a') wfile.write("\n") wfile.write(str(lines1).zfill(9)) wfile.close() From vamsikrishna.bandlamudi at gmail.com Fri Aug 13 22:45:11 2010 From: vamsikrishna.bandlamudi at gmail.com (Vamsi) Date: Fri, 13 Aug 2010 19:45:11 -0700 (PDT) Subject: Help to convert Number to String References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> <4c65ec05$0$28668$c3e8da3@news.astraweb.com> Message-ID: <5ded0e17-e240-4aee-9c60-d4d20f98c1ad@x21g2000yqa.googlegroups.com> On Aug 13, 9:06?pm, Steven D'Aprano wrote: > On Fri, 13 Aug 2010 13:50:48 -0700, Vamsi wrote: > > I am trying to count the number of lines in a file and insert ?into the > > file but getting the error message "TypeError: must be string or > > read-only character buffer, not int", Could you please help me how to > > correct this? > > > here is the code > > > lines1 = sum(1 for line in open('C:/test1.txt')) > > wfile = open('C:/test1.txt'', 'a') > > wfile.write(str(lines1).zfill(9)) > > wfile.close() > > No, that ISN'T the code you are using. > > Don't re-type the code (introducing syntax errors), but copy and paste > WORKING code. Also you need to copy and paste the EXACT error message you > get, not just paraphrasing it. > > When I correct the obvious errors in your code above, it works for me: > > > > >>> f = open('test', 'w') > >>> f.write('hello\nworld\n') > 12 > >>> f.close() > >>> lines1 = sum(1 for line in open('test')) > >>> wfile = open('test', 'a') > >>> wfile.write(str(lines1).zfill(9)) > 9 > >>> wfile.close() > > and the file is correctly updated: > > >>> open('test').read() > > 'hello\nworld\n000000002' > > -- > Steven Thank you Steve for your response. I pasted only part of the code.I am new to Python and using 2.7.My actual code is as below, If I run the below code I am getting the error "TypeError: 'str' object is not callable" ,Now I found that I am using the "str" variable which is a function.Thanks a lot for your help. fileopen = open('C:/MPython/test.txt', 'r') str = fileopen.read() print str fileopen.close() lines1 = sum(1 for line in open('C:/MPython/test.txt')) wfile = open('C:/MPython/test.txt', 'a') wfile.write("\n") wfile.write(str(lines1).zfill(9)) wfile.close() From steve at REMOVE-THIS-cybersource.com.au Fri Aug 13 23:04:17 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2010 03:04:17 GMT Subject: Simple Python Sandbox References: Message-ID: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: > Howdy-ho. > > So, I'm working on a project which embeds Python into a bigger system to > provide extensibility. In this project, there's basically two types of > people who will be entering python code. > > The trusted folks, who write code which are in files, and which can do > anything. > > The untrusted folks, who are writing very simple chunks of code which > can only do limited things. I suggest that if the untrusted code is only supposed to be simple and limited, you would be best off to write your own "mini-language" using Python syntax. E.g. if the untrusted users are only going to write code that does (say) simple arithmetic, then why give them the ability to create closures, use generator expressions, connect to web servers, etc? You might think that it's a lot of work to write a mini-language, even with the tools in the standard library, and it is. But it will probably be less work than securing Python :) The fact is that Python is not designed to be used by untrusted users, and it is REALLY hard to keep it in a sandbox. There was an attempt to sandbox Python, if I recall correctly it was the bastion module, but it turned out to be so leaky that it was removed from the standard library with extreme prejudice. Since then, others have been working on it, including Google, but I don't know how successful they've been. Here's an example... suppose you wish to allow reading files, but not writing them. Sounds simple? http://tav.espians.com/a-challenge-to-break-python-security.html Now, I'm not suggesting that the exploits there are directly applicable to your sandbox, but they give a small idea of the sorts of things you need to consider. -- Steven From ben+python at benfinney.id.au Fri Aug 13 23:04:34 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 14 Aug 2010 13:04:34 +1000 Subject: Help to convert Number to String References: <24900396-44cf-4301-a379-310f0f0cfba9@x25g2000yqj.googlegroups.com> <4c65ec05$0$28668$c3e8da3@news.astraweb.com> <5ded0e17-e240-4aee-9c60-d4d20f98c1ad@x21g2000yqa.googlegroups.com> Message-ID: <87r5i1uc71.fsf@benfinney.id.au> Vamsi writes: > fileopen = open('C:/MPython/test.txt', 'r') > str = fileopen.read() The above statement clobbers the existing binding of ?str? to the built-in string type. From that point on, the built-in string type is no longer accessible by the name ?str?; that name accesses a different object. Choose a better name for the return value; make it describe what the value is for in the context of the program. in_file = open('C:/MPython/test.txt', 'r') in_file_content = in_file.read() print in_file_content in_file.close() # ? It also has the advantage of making your code more readable, since the names help indicate *why* the code is written the way it is. -- \ ?Creativity can be a social contribution, but only in so far as | `\ society is free to use the results.? ?Richard Stallman | _o__) | Ben Finney From zyzhu2000 at gmail.com Sat Aug 14 00:00:01 2010 From: zyzhu2000 at gmail.com (GZ) Date: Fri, 13 Aug 2010 21:00:01 -0700 (PDT) Subject: minidom help -- line number Message-ID: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> Hi All, I am writing a little program that reads the minidom tree built from an xml file. I would like to print out the line number of the xml file on the parts of the tree that are not valid. But I do not seem to find a way to correspond minidom nodes to line numbers. Can anyone give me some help? Thanks, gz From perica.zivkovic at gmail.com Sat Aug 14 03:35:39 2010 From: perica.zivkovic at gmail.com (Perica Zivkovic) Date: Sat, 14 Aug 2010 00:35:39 -0700 (PDT) Subject: how to make portable distribution of python 2.6? References: <2b3be724-e75a-4840-ae54-c251b85a2679@w30g2000yqw.googlegroups.com> <21480f31-c156-408a-a354-70debaa2dedc@l6g2000yqb.googlegroups.com> Message-ID: Hi there, numpy, matplotlib are already parts of Portable Python, PyQt is coming in one of the next versions. Creating it is not so difficult, it is basically repackaging of the python core and the required modules. Tricky part is keeping it portable as big part of libs is storing their configuration settings all over the place or require python env. variables. Drop me an email an maybe I can help you by including modules you need in next release of Portable Python. I'm already helping several universities, maybe we can work together to create one distribution which targets computer classes (together with tutorials, documentation, how-to guides etc.) keep pythoning ! Perica Zivkovic On Aug 13, 8:23?pm, zaur wrote: > On 13 ???, 21:28, Thomas Jollans wrote: > > > > > > > On 2010-08-13 19:00, zaur wrote:> All greetings! > > > > How to make portable distribution of python 2.6? > > > I don't know, but what you're looking for probably already exists. > > > Do you mean "portable" as in portable, i.e. "take this and build it for > > your system, it should work if your OS is supported"? Then you can get > > source tarballs from python.org > > >http://python.org/download/ > > > Or do you understand "portable" the way that is fashionable in the > > Windows world nowadays for some reason, i.e. "look, Ma, already > > installed if you happen to use Microsoft Windows of roughly the right > > version!" > > > Then http://www.portablepython.com/ is exactly where Google would have > > lead you had you searched. > > I want to realize howto build my own portable python in order to use > them without installation. > I want also to be able install modules (numpy, matplotlib, pyqt, > etc...) when it is necessary. > This very usefull for teaching python in computer classes. From thomas at jollybox.de Sat Aug 14 05:27:58 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 14 Aug 2010 11:27:58 +0200 Subject: writing \feff at the begining of a file In-Reply-To: <4c65f752$0$28668$c3e8da3@news.astraweb.com> References: <4C651438.50203@sequans.com> <4c65f752$0$28668$c3e8da3@news.astraweb.com> Message-ID: <201008141127.59165.thomas@jollybox.de> On Saturday 14 August 2010, it occurred to Steven D'Aprano to exclaim: > On Fri, 13 Aug 2010 18:25:46 -0400, Terry Reedy wrote: > > A short background to MRAB's answer which I will try to get right. > > > > The byte-order-mark was invented for UTF-16 encodings so the reader > > could determine whether the pairs of bytes are in little or big endiean > > order, depending on whether the first two bute are fe and ff or ff and > > fe (or maybe vice versa, does not matter here). The concept is > > meaningless for utf-8 which consists only of bytes in a defined order. > > This is part of the Unicode standard. > > > > However, Microsoft (or whoever) re-purposed (hijacked) that pair of > > bytes to serve as a non-standard indicator of utf-8 versus any > > non-unicode encoding. The result is a corrupted utf-8 stream that python > > accommodates with the utf-8-sig(nature) codec (versus the standard utf-8 > > codec). > > Is there a standard way to autodetect the encoding of a text file? I do > this: No, there is no way to autodetect the encoding of a text file. > Open the file in binary mode; if the first three bytes are > codecs.BOM_UTF8, then it's a Microsoft UTF-8 text file; otherwise if the > first two byes are codecs.BOM_BE or codecs.BOM_LE, the encoding is utf-16- > be or utf-16-le respectively. Unless the file happens to be UCS-2/UTF-16, or it happens to be a UTF-8 with garbage at the top. > If there's no BOM, then re-open the file and read the first two lines. If > either of them match this regex 'coding[=:]\s*([-\w.]+)' then I take the > encoding name from that. This matches Python's behaviour, and supports > EMACS and vi encoding declarations. This is a completely different method, and probably the most common in real usage: 1. Assume the file is ASCII (or some similar code page), but be liberal about characters you don't recognize 2. Know the file format you're reading. 3. Switch encoding once you have reached an indication of which exact character set to use. For Python, use the coding cookie if it's there For XML, read the declaration. For HTML, look for a tag, or just guess If no encoding is specified in a way you recognize, then you're out of luck. You'd usually just guess. (better still, you'd know what encoding you're dealing with in the first place, but that's too much to ask, I suppose...) You can try to take an educated guess by cross-referencing character frequencies with tables for known encoding/language combinations. I think this is what Microsoft IE does when it encounters a web page of unspecified encoding. From martin at v.loewis.de Sat Aug 14 07:36:45 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 14 Aug 2010 13:36:45 +0200 Subject: writing \feff at the begining of a file In-Reply-To: <4c65f752$0$28668$c3e8da3@news.astraweb.com> References: <4C651438.50203@sequans.com> <4c65f752$0$28668$c3e8da3@news.astraweb.com> Message-ID: <4C667FCD.6040802@v.loewis.de> > Is there a standard way to autodetect the encoding of a text file? Use the chardet module: http://chardet.feedparser.org/ Regards, Martin From gslindstrom at gmail.com Sat Aug 14 08:29:33 2010 From: gslindstrom at gmail.com (gslindstrom) Date: Sat, 14 Aug 2010 05:29:33 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6,9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: On Aug 12, 4:33?am, Paul Rubin wrote: > Baba writes: > > exercise: given that packs of McNuggets can only be bought in 6, 9 or > > 20 packs, write an exhaustive search to find the largest number of > > McNuggets that cannot be bought in exact quantity. > > Is that a homework problem? ?Hint: first convince yourself that a > largest number actually exists. If I recall, this was a "puzzler" on the NPR radio show "Car Talk". Still might be homework, though. From raoulbia at gmail.com Sat Aug 14 10:52:26 2010 From: raoulbia at gmail.com (Baba) Date: Sat, 14 Aug 2010 07:52:26 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> Message-ID: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> On Aug 13, 8:25?pm, Ian Kelly wrote: > It's not. ?You're not just trying to find the sixth value that can be > bought in exact quantity, but a sequence of six values that can all be > bought in exact quantity. ?The integers [6, 9, 12, 15, 18, 20] are not > sequential. Hi Ian, Thanks for stating the obvious. I obviously hadn't understood a fundamental part of the theorem which states that 6 SEQUENTIAL passes must be found! That's a good lesson learned and will help me in future exercises to make sure i understand the theory first. Thanks again! Ok so with your and News123's help (no offence to all others but i need to keep it simple at this stage)i was able to find the solution: 43 my code is probably not elegant but a huge step forward from where i started: def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return [a,b,c] return [] for n_nuggets in range(50): result1 = can_buy(n_nuggets) result2 = can_buy(n_nuggets+1) result3 = can_buy(n_nuggets+2) result4 = can_buy(n_nuggets+3) result5 = can_buy(n_nuggets+4) result6 = can_buy(n_nuggets+5) if result1!=[] and result2!=[] and result3!=[] and result4!=[] and result5!=[] and result6!=[]: if (n_nuggets+5)-n_nuggets==5: print n_nuggets-1 break i suppose this can be tweaked to make it shorter? For instance i wonder if i can do the same with less variable to be defined? tnx Baba From frederick.williams2 at tesco.net Sat Aug 14 11:24:30 2010 From: frederick.williams2 at tesco.net (Frederick Williams) Date: Sat, 14 Aug 2010 16:24:30 +0100 Subject: print v. print() Message-ID: <4C66B52E.3B49EC1@tesco.net> I am learning Python from Hammond & Robinson's _Python Programming on Win32_, January 2000 edition. This print "Sleeping for 10 seconds" which appears in some example code, fails to... um... Compile? Interpret? Well, whatever the word is, it fails. Trial and error revealed that print("Sleeping for 10 seconds") does the trick. I am using version 3.1.2, presumably the book's authors used some earlier version. So why the change from print to print()? I should warn you that I know nothing about computers in general or Python in particular. -- I can't go on, I'll go on. From aahz at pythoncraft.com Sat Aug 14 11:28:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 14 Aug 2010 08:28:44 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> Message-ID: In article , Grant Edwards wrote: > >I also looked at Modula-3 once, and thought it had some real promise, >but I think it's probably deader than Ada now. That's because you should be using Oberon instead. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From thomas at jollybox.de Sat Aug 14 11:30:28 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 14 Aug 2010 17:30:28 +0200 Subject: print v. print() In-Reply-To: <4C66B52E.3B49EC1@tesco.net> References: <4C66B52E.3B49EC1@tesco.net> Message-ID: <201008141730.29535.thomas@jollybox.de> On Saturday 14 August 2010, it occurred to Frederick Williams to exclaim: > I am learning Python from Hammond & Robinson's _Python Programming on > Win32_, January 2000 edition. This > > print "Sleeping for 10 seconds" > > which appears in some example code, fails to... um... Compile? > Interpret? Well, whatever the word is, it fails. Trial and error > revealed that > > print("Sleeping for 10 seconds") > > does the trick. I am using version 3.1.2, presumably the book's authors > used some earlier version. Yes, indeed. Python 3.0 changed a number of things, the most visible is removing the print statement in favour of the print() function. > So why the change from print to print()? There's no reason for print to be a statement -- it can just as well be a function, which makes the language more regular, and therefore quite possibly easier to learn. > > I should warn you that I know nothing about computers in general or > Python in particular. From mwilson at the-wire.com Sat Aug 14 11:44:22 2010 From: mwilson at the-wire.com (Mel) Date: Sat, 14 Aug 2010 11:44:22 -0400 Subject: print v. print() References: <4C66B52E.3B49EC1@tesco.net> Message-ID: Thomas Jollans wrote: > On Saturday 14 August 2010, it occurred to Frederick Williams to exclaim: >> So why the change from print to print()? > There's no reason for print to be a statement -- it can just as well be a > function, which makes the language more regular, and therefore quite > possibly easier to learn. The downside to a print() function is that assigning to `print` can mask the function, and leave a neophyte without any way to get output out of the program. The problem with that downside, I guess, is that rogue assignment to sys.stdout can kill a print statement just as dead as a print() function, so the statement's so-called advantage is not that great. Mel. From mwilson at the-wire.com Sat Aug 14 11:49:28 2010 From: mwilson at the-wire.com (Mel) Date: Sat, 14 Aug 2010 15:49:28 +0000 (UTC) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: Baba wrote: > def can_buy(n_nuggets): > for a in range (0,n_nuggets): > for b in range (0,n_nuggets): > for c in range (0,n_nuggets): > #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > if 6*a+9*b+20*c==n_nuggets: > return [a,b,c] > return [] > > for n_nuggets in range(50): > result1 = can_buy(n_nuggets) > result2 = can_buy(n_nuggets+1) > result3 = can_buy(n_nuggets+2) > result4 = can_buy(n_nuggets+3) > result5 = can_buy(n_nuggets+4) > result6 = can_buy(n_nuggets+5) > if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > if (n_nuggets+5)-n_nuggets==5: > print n_nuggets-1 > break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? That can_buy function is a computational heavyweight -- very repetitive when called inside a loop. It could be cheaper to compute a list of quantities that can be purchased, then check to see what's in the list -- or the set, if you optimize a bit more. Mel. From juanknebel at gmail.com Sat Aug 14 12:19:59 2010 From: juanknebel at gmail.com (Juan Andres Knebel) Date: Sat, 14 Aug 2010 13:19:59 -0300 Subject: python ide for ubuntu In-Reply-To: <30CC6202-509E-4D09-9921-79A7B61C9351@gmail.com> References: <30CC6202-509E-4D09-9921-79A7B61C9351@gmail.com> Message-ID: Hi Bhanu, if you want to use QT try eric4 for python2 or eric5 for python3. Is very nice IDE, but if you want to develop only pure python use kate or similar or eclipse if you need a nice way to see the debug processes On Thu, Aug 12, 2010 at 7:44 AM, Roald de Vries wrote: > Hi Bhanu, > > > On Aug 12, 2010, at 4:15 AM, Bhanu Kumar wrote: > >> Hi All, >> >> Is there any good free python IDE available in Ubuntu? >> > > See a similar discussion at django-users mailing list: > > http://groups.google.com/group/django-users/browse_thread/thread/562189578285211 > > Cheers, Roald > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Juan Andres Knebel -------------- next part -------------- An HTML attachment was scrubbed... URL: From thudfoo at opensuse.us Sat Aug 14 12:40:29 2010 From: thudfoo at opensuse.us (member thudfoo) Date: Sat, 14 Aug 2010 09:40:29 -0700 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: On 8/14/10, Baba wrote: > On Aug 13, 8:25 pm, Ian Kelly wrote: > >> It's not. You're not just trying to find the sixth value that can be >> bought in exact quantity, but a sequence of six values that can all be >> bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not >> sequential. > > Hi Ian, > > Thanks for stating the obvious. I obviously hadn't understood a > fundamental part of the theorem which states that 6 SEQUENTIAL passes > must be found! That's a good lesson learned and will help me in future > exercises to make sure i understand the theory first. Thanks again! > > Ok so with your and News123's help (no offence to all others but i > need to keep it simple at this stage)i was able to find the solution: > 43 > > my code is probably not elegant but a huge step forward from where i > started: > > def can_buy(n_nuggets): > for a in range (0,n_nuggets): > for b in range (0,n_nuggets): > for c in range (0,n_nuggets): > #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > if 6*a+9*b+20*c==n_nuggets: > return [a,b,c] > return [] > > for n_nuggets in range(50): > result1 = can_buy(n_nuggets) > result2 = can_buy(n_nuggets+1) > result3 = can_buy(n_nuggets+2) > result4 = can_buy(n_nuggets+3) > result5 = can_buy(n_nuggets+4) > result6 = can_buy(n_nuggets+5) > if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > if (n_nuggets+5)-n_nuggets==5: > print n_nuggets-1 > break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? > > tnx > Baba > One tweak: def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return [a,b,c] return [] for n_nuggets in range(50): if (can_buy(n_nuggets) and can_buy(n_nuggets+1) and can_buy(n_nuggets+2) and can_buy(n_nuggets+3) and can_buy(n_nuggets+4) and can_buy(n_nuggets+5)): print n_nuggets - 1 break From ian.g.kelly at gmail.com Sat Aug 14 12:43:38 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 14 Aug 2010 10:43:38 -0600 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: On Sat, Aug 14, 2010 at 8:52 AM, Baba wrote: > my code is probably not elegant but a huge step forward from where i > started: > > def can_buy(n_nuggets): > ? for a in range (0,n_nuggets): > ? ? ? for b in range (0,n_nuggets): > ? ? ? ? ? for c in range (0,n_nuggets): > ? ? ? ? ? ? ? #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > ? ? ? ? ? ? ? if 6*a+9*b+20*c==n_nuggets: > ? ? ? ? ? ? ? ? ? return [a,b,c] > ? return [] > > for n_nuggets in range(50): > ? ?result1 = can_buy(n_nuggets) > ? ?result2 = can_buy(n_nuggets+1) > ? ?result3 = can_buy(n_nuggets+2) > ? ?result4 = can_buy(n_nuggets+3) > ? ?result5 = can_buy(n_nuggets+4) > ? ?result6 = can_buy(n_nuggets+5) > ? ?if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > ? ? if (n_nuggets+5)-n_nuggets==5: > ? ? ? ?print n_nuggets-1 > ? ? ? ?break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? Instead of calling can_buy() 6 times on every iteration of the main loop, I would suggest maintaining a list of the sequential results. Just call it once on each number of nuggets in order. If the number of nuggets is purchasable, and the list is empty or the last item in the list is the number of nuggets - 1, then append the number of nuggets to the list. If the last item in the list is not the number of nuggets - 1, then they're not sequential and you start a new list. When the length of the list reaches 6, you're done, and the answer is equal to the first item in the list - 1. You can also improve the can_buy() function by tightening up the loop limits. You don't need to go all the way up to n_nuggets on each loop. From python at mrabarnett.plus.com Sat Aug 14 12:44:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 14 Aug 2010 17:44:15 +0100 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: <4C66C7DF.1010900@mrabarnett.plus.com> Baba wrote: > On Aug 13, 8:25 pm, Ian Kelly wrote: > >> It's not. You're not just trying to find the sixth value that can be >> bought in exact quantity, but a sequence of six values that can all be >> bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not >> sequential. > > Hi Ian, > > Thanks for stating the obvious. I obviously hadn't understood a > fundamental part of the theorem which states that 6 SEQUENTIAL passes > must be found! That's a good lesson learned and will help me in future > exercises to make sure i understand the theory first. Thanks again! > > Ok so with your and News123's help (no offence to all others but i > need to keep it simple at this stage)i was able to find the solution: > 43 > > my code is probably not elegant but a huge step forward from where i > started: > > def can_buy(n_nuggets): > for a in range (0,n_nuggets): > for b in range (0,n_nuggets): > for c in range (0,n_nuggets): > #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > if 6*a+9*b+20*c==n_nuggets: > return [a,b,c] > return [] > > for n_nuggets in range(50): > result1 = can_buy(n_nuggets) > result2 = can_buy(n_nuggets+1) > result3 = can_buy(n_nuggets+2) > result4 = can_buy(n_nuggets+3) > result5 = can_buy(n_nuggets+4) > result6 = can_buy(n_nuggets+5) > if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > if (n_nuggets+5)-n_nuggets==5: > print n_nuggets-1 > break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? > Increase the number of nuggets one by one and keep a count of the number of consecutive successes. If you can buy a number of nuggets exactly, increment the count, otherwise reset the count. When the count reaches 6 you know that you're at the end of a sequence of consecutive successes. From bhanu.ramappa at gmail.com Sat Aug 14 12:56:21 2010 From: bhanu.ramappa at gmail.com (Bhanu Kumar) Date: Sat, 14 Aug 2010 22:26:21 +0530 Subject: python ide for ubuntu In-Reply-To: References: <30CC6202-509E-4D09-9921-79A7B61C9351@gmail.com> Message-ID: Thanks!! On Sat, Aug 14, 2010 at 9:49 PM, Juan Andres Knebel wrote: > Hi Bhanu, > if you want to use QT try eric4 for python2 or eric5 for python3. Is very > nice IDE, but if you want to develop only pure python use kate or similar or > eclipse if you need a nice way to see the debug processes > > > On Thu, Aug 12, 2010 at 7:44 AM, Roald de Vries wrote: > >> Hi Bhanu, >> >> >> On Aug 12, 2010, at 4:15 AM, Bhanu Kumar wrote: >> >>> Hi All, >>> >>> Is there any good free python IDE available in Ubuntu? >>> >> >> See a similar discussion at django-users mailing list: >> >> http://groups.google.com/group/django-users/browse_thread/thread/562189578285211 >> >> Cheers, Roald >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > Juan Andres Knebel > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollybox.de Sat Aug 14 13:07:49 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 14 Aug 2010 19:07:49 +0200 Subject: minidom help -- line number In-Reply-To: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> References: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> Message-ID: <201008141907.49646.thomas@jollybox.de> On Saturday 14 August 2010, it occurred to GZ to exclaim: > Hi All, > > I am writing a little program that reads the minidom tree built from > an xml file. I would like to print out the line number of the xml file > on the parts of the tree that are not valid. But I do not seem to find > a way to correspond minidom nodes to line numbers. The DOM does not contain things like line number information. You work with the structure of the document, not the appearance of the file you happen to be using as a source. You can't use line numbers with minidom. For stream-based parsers like SAX and eXpat (both in the standard library) this makes more sense, and they both allow you to check the current line number in one way or another. From python at rcn.com Sat Aug 14 13:14:14 2010 From: python at rcn.com (Raymond Hettinger) Date: Sat, 14 Aug 2010 10:14:14 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> Message-ID: On Aug 12, 1:20?pm, Paddy wrote: > I find myself needing to calculate the difference between two Counters > or multisets or bags. > > I want those items that are unique to each bag. Tell us about your use cases. I'm curious how a program would ascribe semantic meaning to the result. The phrase "unique to each bag" doesn't quite cover it, perhaps something like "number in either source above the minimum held in common". AFAICT, I've never needed something like this as a primitive. Even the xor operation for regular sets is rarely used. > I know how to > calculate it: > > ? ? >>> b = Counter(a=1, b=2) > ? ? >>> c = Counter(a=3, b=1) > ? ? >>> diff = (b - c) + (c - b) > >>> diff > Counter({'a': 2, 'b': 1}) That seems simple enough. You could also use: diff = (b | c) - (b & c) # max(b,c) - min(b,c) Raymond From jjposner at optimum.net Sat Aug 14 13:27:53 2010 From: jjposner at optimum.net (John Posner) Date: Sat, 14 Aug 2010 13:27:53 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> Message-ID: <4C66D219.4040407@optimum.net> On 8/14/2010 10:52 AM, Baba wrote: > > for n_nuggets in range(50): > result1 = can_buy(n_nuggets) > result2 = can_buy(n_nuggets+1) > result3 = can_buy(n_nuggets+2) > result4 = can_buy(n_nuggets+3) > result5 = can_buy(n_nuggets+4) > result6 = can_buy(n_nuggets+5) > if result1!=[] and result2!=[] and result3!=[] and result4!=[] and > result5!=[] and result6!=[]: > if (n_nuggets+5)-n_nuggets==5: > print n_nuggets-1 > break > > i suppose this can be tweaked to make it shorter? For instance i > wonder if i can do the same with less variable to be defined? [Other responders have covered a lots of the points I make below. I guess I need to be quicker!] First, congratulations on getting to a solution! Code can very often be made shorter, although it's not always worth your while to do so. And often, shorter code is less understandable code -- which makes a big difference if you need to revisit the code later on. Here are some things that can be done with your for-loop: 1. You don't need this "if" test, because it's always true: if (n_nuggets+5)-n_nuggets==5: 2. Whenever you find yourself inventing a series of variables like "result1", "result2", "result3", etc., think about using a list instead. results = [] for i in range(6): results.append(can_buy(n_nuggets + i)) And to get really fancy, you can use a single "list comprehension" statement to do it all results = [can_buy(n_nuggets + i) for i in range(6)] 3. Your "if" statement tests whether all the lists are non-empty. In Python, expressions (a) and (b) are equivalent: (a) if result[0] != [] (b) if result[0] So your "if" test can be expressed as: if (result[0] and result[1] and result[2] and result[3] and result[4] and result[5]) (The parentheses are not required by "if", but they *do* enable you to split the expression across two or more lines.) And you can use the "all" function to rescue this cumbersome statement; if all(results) After all this work, the code is getting pretty short: for n_nuggets in range(50): results = [can_buy(n_nuggets + i) for i in range(6)] if all(results): print n_nuggets-1 break 4. The variable "results" is defined in one statement, and then is used just once, in the very next statement. There's no harm in that, and I think it makes the mode easier to understand, but you can get rid of it: for n_nuggets in range(50): if all([can_buy(n_nuggets + i) for i in range(6)]): print n_nuggets-1 break But wait, there's more ... :-) So far, we've just refined the *implementation* of your algorithm. But the algorithm itself could use some work. * When n_nuggets==0, we compute can_buy(0), can_buy(1), can_buy(2), can_buy(3), can_buy(4), and can_buy(5). * When n_nuggets==1, we compute can_buy(1), can_buy(2), can_buy(3), can_buy(4), can_buy(5), and can_buy(6). ... and so on. We can use an algorithm in which can_buy(i) is computed just once for each value of i: can_buy_count = 0 n_nuggets = 0 while n_nuggets < 50: if can_buy(n_nuggets): can_buy_count += 1 else: can_buy_count = 0 if can_buy_count == 6: print n_nuggets - 6 break else: n_nuggets += 1 And here's how you could shorten *this* code: ### cbc = "can buy count" cbc = 0 n_nuggets = -1 while n_nuggets < 50: n_nuggets += 1 cbc = cbc+1 if can_buy(n_nuggets) else 0 if cbc == 6: print n_nuggets - 6 break HTH, John From zyzhu2000 at gmail.com Sat Aug 14 13:40:13 2010 From: zyzhu2000 at gmail.com (GZ) Date: Sat, 14 Aug 2010 10:40:13 -0700 (PDT) Subject: minidom help -- line number References: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> Message-ID: <7231eedc-59e5-4275-bb87-e493ebfe1e00@i13g2000yqd.googlegroups.com> On Aug 14, 12:07?pm, Thomas Jollans wrote: > On Saturday 14 August 2010, it occurred to GZ to exclaim: > > > Hi All, > > > I am writing a little program that reads the minidom tree built from > > an xml file. I would like to print out the line number of the xml file > > on the parts of the tree that are not valid. But I do not seem to find > > a way to correspond minidom nodes to line numbers. > > The DOM does not contain things like line number information. You work with > the structure of the document, not the appearance of the file you happen to be > using as a source. You can't use line numbers with minidom. > > For stream-based parsers like SAX and eXpat (both in the standard library) > this makes more sense, and they both allow you to check the current line > number in one way or another. So I am basically out of luck if I want to tie back to the original file for file error reporting etc. sounds like a deficiency to me. From thomas at jollybox.de Sat Aug 14 13:56:45 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 14 Aug 2010 19:56:45 +0200 Subject: minidom help -- line number In-Reply-To: <7231eedc-59e5-4275-bb87-e493ebfe1e00@i13g2000yqd.googlegroups.com> References: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> <7231eedc-59e5-4275-bb87-e493ebfe1e00@i13g2000yqd.googlegroups.com> Message-ID: <201008141956.45918.thomas@jollybox.de> On Saturday 14 August 2010, it occurred to GZ to exclaim: > On Aug 14, 12:07 pm, Thomas Jollans wrote: > > On Saturday 14 August 2010, it occurred to GZ to exclaim: > > > Hi All, > > > > > > I am writing a little program that reads the minidom tree built from > > > an xml file. I would like to print out the line number of the xml file > > > on the parts of the tree that are not valid. But I do not seem to find > > > a way to correspond minidom nodes to line numbers. > > > > The DOM does not contain things like line number information. You work > > with the structure of the document, not the appearance of the file you > > happen to be using as a source. You can't use line numbers with minidom. > > > > For stream-based parsers like SAX and eXpat (both in the standard > > library) this makes more sense, and they both allow you to check the > > current line number in one way or another. > > So I am basically out of luck if I want to tie back to the original > file for file error reporting etc. sounds like a deficiency to me. The DOM is disjunct from the original file, stream, string, etc. That's in the nature of the DOM, and it's probably true for most, if not all, DOM implementations, in other programming languages as well as Python. If you want to stay close to the file, you're better of with SAX. (or a similar approach, like eXpat) From ian.g.kelly at gmail.com Sat Aug 14 14:11:56 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 14 Aug 2010 12:11:56 -0600 Subject: minidom help -- line number In-Reply-To: <201008141956.45918.thomas@jollybox.de> References: <179a21bc-dc9d-4ec4-b27e-09667a3628b2@z28g2000yqh.googlegroups.com> <7231eedc-59e5-4275-bb87-e493ebfe1e00@i13g2000yqd.googlegroups.com> <201008141956.45918.thomas@jollybox.de> Message-ID: On Sat, Aug 14, 2010 at 11:56 AM, Thomas Jollans wrote: > The DOM is disjunct from the original file, stream, string, etc. That's in the > nature of the DOM, and it's probably true for most, if not all, DOM > implementations, in other programming languages as well as Python. > If you want to stay close to the file, you're better of with SAX. (or a > similar approach, like eXpat) The minidom parse function can also accept any SAX2 parser, so it should be possible to create a customized parser that stashes the line numbers somewhere and use that together with minidom. I've never attempted this myself, so I won't be able to help with details. Cheers, Ian From pramo4d at gmail.com Sat Aug 14 14:18:50 2010 From: pramo4d at gmail.com (Pramod) Date: Sat, 14 Aug 2010 11:18:50 -0700 (PDT) Subject: problem in using linalg solver in numpy Message-ID: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> Hi Friends When run the below program in python i got error like this , Matrix [[ 8 -6 2] [-4 11 -7] [ 4 -7 6]] row vecotr X [[ 28 -40 33]] Traceback (most recent call last): File "solve.py", line 16, in print A*B File "/usr/lib/python2.6/dist-packages/numpy/core/defmatrix.py", line 290, in __mul__ return N.dot(self, asmatrix(other)) ValueError: objects are not aligned #!/usr/bin/python N=3 from numpy import linalg from numpy import matrix fr=open('mat.txt','r') A=matrix([[int(fr.readline()) for j in range(N)]for i in range(N)]) B=matrix([[int(fr.readline())for j in range(N)]]) print 'Matrix \n',A print 'row vecotr X\n',B #A=matrix([[3,4],[5,2]]) #B=matrix([[11],[9]]) print A*B #y=linalg.solve(A,B) #print 'Solution vectoris \n',y The input file is 8 -6 2 -4 11 -7 4 -7 6 28 -40 33 please try to fix the error in the program Thankx in advance From resourts85 at gmail.com Sat Aug 14 14:21:57 2010 From: resourts85 at gmail.com (iqbal iqbal) Date: Sat, 14 Aug 2010 11:21:57 -0700 (PDT) Subject: Chrome ore Sell Pakistani 30% - 52%, Message-ID: <6fea6efb-7b02-414c-84aa-620528849fe4@g6g2000pro.googlegroups.com> Chrome ore Sell Pakistani 30% - 52%, http://buy-sell-pakistani-minerals.blogspot.com From chare at labr.net Sat Aug 14 14:30:59 2010 From: chare at labr.net (Chris Hare) Date: Sat, 14 Aug 2010 13:30:59 -0500 Subject: Tk window and contents will not display Message-ID: <372B84B3-5563-4DD7-A679-95FD940F3AB5@labr.net> The scenario is this: I want to loop around all of the images in a given directory (which I know will be images, but I guess I should check), show an image in a window, wait 2 seconds and show the next one and repeat that indefinitley, which will be until the user closes the window. This is the code I extracted from the larger program and made work - sort of - in a standalone fashion. When I run the code, each of the file names gets displayed, and I can view the images, so it has to be something I am doing wrong with this chunk of code. However, I don't see what the problem is. from Tkinter import * import time import os import ImageTk import Image class externalLoopDisplay: def show(self): # # Create a frame # self.window = Tk() self.f = Frame(self.window, bg="Gray") self.f.grid() self.btnRefresh = Button(self.f, text="Close", command=self.window.destroy, bg="Gray",highlightbackground="Red", highlightcolor="Green") self.btnRefresh.grid(row=0, column=2) self.loopImage() def loopImage(self): dir = "Radar/net17" while 1: fileList = os.listdir(dir) number = len(fileList) c = 1 for gifFile in fileList: print "externalLoopDisplay.show:","top of for loop " + str(c) + " of " + str(number) print "externalLoopDisplay.show:","showing file " + dir + "/" + gifFile self.window.title("Image " + str(c) + " of " + str(number)) image = Image.open(dir + "/" + gifFile) canvasWidth, canvasHeight = image.size self.w = Canvas(self.f, width=canvasWidth, height=canvasHeight) photo = ImageTk.PhotoImage(image=image) netRadarImage = Label(self.w, image=photo) netRadarImage.image = photo self.w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) time.sleep(10) c = c + 1 self.w.destroy() loop=externalLoopDisplay() loop.show() From __peter__ at web.de Sat Aug 14 14:46:01 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Aug 2010 20:46:01 +0200 Subject: problem in using linalg solver in numpy References: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> Message-ID: Pramod wrote: > When run the below program in python i got error like this , > > > Matrix > [[ 8 -6 2] > [-4 11 -7] > [ 4 -7 6]] > row vecotr X > [[ 28 -40 33]] > Traceback (most recent call last): > File "solve.py", line 16, in > print A*B > File "/usr/lib/python2.6/dist-packages/numpy/core/defmatrix.py", > line 290, in __mul__ > return N.dot(self, asmatrix(other)) > ValueError: objects are not aligned > A=matrix([[int(fr.readline()) for j in range(N)]for i in range(N)]) > B=matrix([[int(fr.readline())for j in range(N)]]) > print A*B Row or column; I can't remember which is which either. Try again with B = matrix([[int(fr.readline())] for j in range(N)] or A*B.transpose() Peter From python at mrabarnett.plus.com Sat Aug 14 15:06:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 14 Aug 2010 20:06:25 +0100 Subject: problem in using linalg solver in numpy In-Reply-To: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> References: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> Message-ID: <4C66E931.4030201@mrabarnett.plus.com> Pramod wrote: > Hi Friends > > > When run the below program in python i got error like this , > > > Matrix > [[ 8 -6 2] > [-4 11 -7] > [ 4 -7 6]] > row vecotr X > [[ 28 -40 33]] > Traceback (most recent call last): > File "solve.py", line 16, in > print A*B > File "/usr/lib/python2.6/dist-packages/numpy/core/defmatrix.py", > line 290, in __mul__ > return N.dot(self, asmatrix(other)) > ValueError: objects are not aligned > [snip] If you're trying to multiply element-wise use the 'multiply' function. From iamforufriends at gmail.com Sat Aug 14 15:31:54 2010 From: iamforufriends at gmail.com (UR DREEM GIRL) Date: Sat, 14 Aug 2010 12:31:54 -0700 (PDT) Subject: want to see Babe with huge boobs hard sex Message-ID: want to see Babe with huge boobs hard sex http://hotttubs.blogspot.com/ http://hotttubs.blogspot.com/ http://hotttubs.blogspot.com/ http://hotttubs.blogspot.com/ From me+list/python at ixokai.io Sat Aug 14 15:56:45 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 12:56:45 -0700 Subject: Simple Python Sandbox In-Reply-To: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> Message-ID: <4C66F4FD.1010102@ixokai.io> On 8/13/10 8:04 PM, Steven D'Aprano wrote: > On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: > >> Howdy-ho. >> >> So, I'm working on a project which embeds Python into a bigger system to >> provide extensibility. In this project, there's basically two types of >> people who will be entering python code. >> >> The trusted folks, who write code which are in files, and which can do >> anything. >> >> The untrusted folks, who are writing very simple chunks of code which >> can only do limited things. > > I suggest that if the untrusted code is only supposed to be simple and > limited, you would be best off to write your own "mini-language" using > Python syntax. I considered it and rejected it. The return from the effort required doesn't even vaguely come close to making it worth it. My worst case fall-back plan is to embed /another/ language (be it Lua or JavaScript through V8) and offer it a very limited environment. But I don't want to do that (and considering I solved the while True: pass problem last night, I'm pretty sure I won't decide to). > The fact is that Python is not designed to be used by untrusted users, > and it is REALLY hard to keep it in a sandbox. There was an attempt to > sandbox Python, if I recall correctly it was the bastion module, but it > turned out to be so leaky that it was removed from the standard library > with extreme prejudice. Since then, others have been working on it, > including Google, but I don't know how successful they've been. I know all this -- but its not relevant really, I think. I'm not trying to create a safe yet relatively complete or functional Python. All those efforts to sandbox Python fail because of the incredible dynamic nature of the language has lots of enticing little holes in it. But I'm not interested in a full or even vaguely full subset of Python, and I'm not requiring that this security be done on the code-level. For example, when you go to save your bit of code, it will go in and if it finds __ anywhere in the text it just replaces it with xx. And, since getattr is not available, '_' + '_' won't get you anywhere. > Here's an example... suppose you wish to allow reading files, but not > writing them. Sounds simple? > > http://tav.espians.com/a-challenge-to-break-python-security.html Yeah, I'm aware of this little challenge-- but every one of those exploits calls for a special attribute call or method creation which is impossible(I think) in my setup. Although Paul Cannon's little exploit is very interesting, and I'm going to go brute force murder try/except in a similar way to __ above (in this context, exceptions aren't important) now. > Now, I'm not suggesting that the exploits there are directly applicable > to your sandbox, but they give a small idea of the sorts of things you > need to consider. I'm creating a much, much more restrictive subset of Python then most sandboxes try to do-- I could make my own custom mini-language, except good lord, that's a whole lot of work since there are real needs for *some* programming power here. Or I could embed another language in a more restrictive way then Python is embedded-- but good lord, now I have to handle three languages to get things done :) I just need a certain limited context where someone can be handed certain Python objects and manipulate them. I'd like people to be able to use some fundamental Python power -- the rich, beautiful data types for example (notably in this case, strings), list comprehensions and stuff, to do what they need to do. Python's very easy, I'd like them to be able to use that easy. But I don't need anywhere near full Python power, so sweeping rules like, 'no, you can't even type __' or, 'sorry, no exception handling for you', work well. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From __peter__ at web.de Sat Aug 14 16:14:22 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Aug 2010 22:14:22 +0200 Subject: Tk window and contents will not display References: Message-ID: Chris Hare wrote: > The scenario is this: > > I want to loop around all of the images in a given directory (which I know > will be images, but I guess I should check), show an image in a window, > wait 2 seconds and show the next one and repeat that indefinitley, which > will be until the user closes the window. > > This is the code I extracted from the larger program and made work - sort > of - in a standalone fashion. When I run the code, each of the file names > gets displayed, and I can view the images, so it has to be something I am > doing wrong with this chunk of code. > > However, I don't see what the problem is. I have not looked at your code in detail, but event loops and time.sleep() don't play together very well. Use after(delay_in_milliseconds, callable) instead. Here's a simple example that loops over images passed from the command line: import Image import ImageTk import os import sys import Tkinter as tk from itertools import cycle def next_image(): imagefile = next(imagefiles) image = Image.open(imagefile) w, h = image.size image = image.resize((700, 700*h//w)) label.image = label["image"] = ImageTk.PhotoImage(image=image) root.title("Now showing %s" % os.path.basename(imagefile)) root.after(2000, next_image) if __name__ == "__main__": imagefiles = sys.argv[1:] assert imagefiles imagefiles = cycle(imagefiles) root = tk.Tk() label = tk.Label(root) label.pack() root.after_idle(next_image) root.mainloop() From cs at zip.com.au Sat Aug 14 17:25:52 2010 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 15 Aug 2010 07:25:52 +1000 Subject: Simple Python Sandbox In-Reply-To: <4C66F4FD.1010102@ixokai.io> References: <4C66F4FD.1010102@ixokai.io> Message-ID: <20100814212552.GA30391@cskk.homeip.net> On 14Aug2010 12:56, Stephen Hansen wrote: | On 8/13/10 8:04 PM, Steven D'Aprano wrote: | > On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: | >> So, I'm working on a project which embeds Python into a bigger system to | >> provide extensibility. In this project, there's basically two types of | >> people who will be entering python code. | >> | >> The trusted folks, who write code which are in files, and which can do | >> anything. | >> | >> The untrusted folks, who are writing very simple chunks of code which | >> can only do limited things. | > | > I suggest that if the untrusted code is only supposed to be simple and | > limited, you would be best off to write your own "mini-language" using | > Python syntax. | | I considered it and rejected it. The return from the effort required | doesn't even vaguely come close to making it worth it. Ok, what about this: run the untrusted code in a separate process, if necessary running as a user with different privileges. Provide objects that need to be shared as some sort of proxy. Then your untrusted users can do whatever they like in python because they won't be presented with the inner parts of the privileged stuff. This is all rather vague because I don't know exactly what your untrusted users need to be able to do, nor how. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Computers in the future may weigh no more than 1.5 tons. --Popular Mechanics, forecasting the relentless march of science, 1949 From aahz at pythoncraft.com Sat Aug 14 17:46:33 2010 From: aahz at pythoncraft.com (Aahz) Date: 14 Aug 2010 14:46:33 -0700 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: In article <7xeieevrze.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >I'm not sure what the hiring issue is. I think anyone skilled in C++ or >Java can pick up Ada pretty easily. It's mostly a subset of C++ with >different surface syntax. Heck, I learned Ada as a sixteen-year-old knowing only BASIC and Pascal. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From debatem1 at gmail.com Sat Aug 14 17:57:46 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 14 Aug 2010 14:57:46 -0700 Subject: Simple Python Sandbox In-Reply-To: <4C66F4FD.1010102@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: On Sat, Aug 14, 2010 at 12:56 PM, Stephen Hansen wrote: > On 8/13/10 8:04 PM, Steven D'Aprano wrote: >> On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: >> >>> Howdy-ho. >>> >>> So, I'm working on a project which embeds Python into a bigger system to >>> provide extensibility. In this project, there's basically two types of >>> people who will be entering python code. >>> >>> The trusted folks, who write code which are in files, and which can do >>> anything. >>> >>> The untrusted folks, who are writing very simple chunks of code which >>> can only do limited things. >> >> I suggest that if the untrusted code is only supposed to be simple and >> limited, you would be best off to write your own "mini-language" using >> Python syntax. > > I considered it and rejected it. The return from the effort required > doesn't even vaguely come close to making it worth it. My worst case > fall-back plan is to embed /another/ language (be it Lua or JavaScript > through V8) and offer it a very limited environment. But I don't want to > do that (and considering I solved the while True: pass problem last > night, I'm pretty sure I won't decide to). > >> The fact is that Python is not designed to be used by untrusted users, >> and it is REALLY hard to keep it in a sandbox. There was an attempt to >> sandbox Python, if I recall correctly it was the bastion module, but it >> turned out to be so leaky that it was removed from the standard library >> with extreme prejudice. Since then, others have been working on it, >> including Google, but I don't know how successful they've been. > > I know all this -- but its not relevant really, I think. I'm not trying > to create a safe yet relatively complete or functional Python. All those > efforts to sandbox Python fail because of the incredible dynamic nature > of the language has lots of enticing little holes in it. But I'm not > interested in a full or even vaguely full subset of Python, and I'm not > requiring that this security be done on the code-level. > > For example, when you go to save your bit of code, it will go in and if > it finds __ anywhere in the text it just replaces it with xx. And, since > getattr is not available, '_' + '_' won't get you anywhere. > >> Here's an example... suppose you wish to allow reading files, but not >> writing them. Sounds simple? >> >> http://tav.espians.com/a-challenge-to-break-python-security.html > > Yeah, I'm aware of this little challenge-- but every one of those > exploits calls for a special attribute call or method creation which is > impossible(I think) in my setup. > > Although Paul Cannon's little exploit is very interesting, and I'm going > to go brute force murder try/except in a similar way to __ above (in > this context, exceptions aren't important) now. > >> Now, I'm not suggesting that the exploits there are directly applicable >> to your sandbox, but they give a small idea of the sorts of things you >> need to consider. > > I'm creating a much, much more restrictive subset of Python then most > sandboxes try to do-- I could make my own custom mini-language, except > good lord, that's a whole lot of work since there are real needs for > *some* programming power here. Or I could embed another language in a > more restrictive way then Python is embedded-- but good lord, now I have > to handle three languages to get things done :) > > I just need a certain limited context where someone can be handed > certain Python objects and manipulate them. I'd like people to be able > to use some fundamental Python power -- the rich, beautiful data types > for example (notably in this case, strings), list comprehensions and > stuff, to do what they need to do. Python's very easy, I'd like them to > be able to use that easy. > > But I don't need anywhere near full Python power, so sweeping rules > like, 'no, you can't even type __' or, 'sorry, no exception handling for > you', work well. I assume you're cutting out the import machinery? Geremy Condra From chare at labr.net Sat Aug 14 18:00:12 2010 From: chare at labr.net (Chris Hare) Date: Sat, 14 Aug 2010 17:00:12 -0500 Subject: Tk window and contents will not display In-Reply-To: References: Message-ID: On Aug 14, 2010, at 3:14 PM, Peter Otten wrote: > Chris Hare wrote: > >> The scenario is this: >> >> I want to loop around all of the images in a given directory (which I know >> will be images, but I guess I should check), show an image in a window, >> wait 2 seconds and show the next one and repeat that indefinitley, which >> will be until the user closes the window. >> >> This is the code I extracted from the larger program and made work - sort >> of - in a standalone fashion. When I run the code, each of the file names >> gets displayed, and I can view the images, so it has to be something I am >> doing wrong with this chunk of code. >> >> However, I don't see what the problem is. > > I have not looked at your code in detail, but event loops and time.sleep() > don't play together very well. Use after(delay_in_milliseconds, callable) > instead. > > Here's a simple example that loops over images passed from the command line: > > import Image > import ImageTk > import os > import sys > import Tkinter as tk > > from itertools import cycle > > def next_image(): > imagefile = next(imagefiles) > image = Image.open(imagefile) > > w, h = image.size > image = image.resize((700, 700*h//w)) > > label.image = label["image"] = ImageTk.PhotoImage(image=image) > root.title("Now showing %s" % os.path.basename(imagefile)) > > root.after(2000, next_image) > > if __name__ == "__main__": > imagefiles = sys.argv[1:] > assert imagefiles > imagefiles = cycle(imagefiles) > > root = tk.Tk() > label = tk.Label(root) > label.pack() > > root.after_idle(next_image) > root.mainloop() > Thanks Peter. I threw away what I started with and merged your code into my class: class externalLoopDisplay: def show(self): main.logging.debug("externalLoopDisplay.show:","start") self.window = Tk() self.btnClose = Button(self.window, text="Close", command=self.window.destroy, bg=backColor,highlightbackground=warnColor, highlightcolor=okColor) self.btnClose.grid(row=0, column=2) self.label = Label(self.window) self.label.grid(row=1, column=0, columnspan=3) dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. .../Radar/net17/net17-YYYYMMDDHHMMSS.gif self.imagefiles = glob.glob(dirName + "/*.gif") self.imagefiles = cycle(self.imagefiles) self.window.after_idle(self.next_image) def next_image(self): imagefile = next(self.imagefiles) image = Image.open(imagefile) w, h = image.size image = image.resize((600, 550*h//w)) self.label.image = self.label["image"] = ImageTk.PhotoImage(image=image) # <==== bails here self.window.title("Now showing %s" % os.path.basename(imagefile)) self.window.after(2000, next_image) I marked where the code bails with an error saying pyimage2 doesn't exist. All of the images exist and worked just fine with your standalone script. Suggestions? From __peter__ at web.de Sat Aug 14 18:49:45 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Aug 2010 00:49:45 +0200 Subject: Tk window and contents will not display References: Message-ID: Chris Hare wrote: > Thanks Peter. I threw away what I started with and merged your code into > my class: > > class externalLoopDisplay: > > def show(self): > main.logging.debug("externalLoopDisplay.show:","start") > > self.window = Tk() > > self.btnClose = Button(self.window, text="Close", > command=self.window.destroy, > bg=backColor,highlightbackground=warnColor, > highlightcolor=okColor) self.btnClose.grid(row=0, column=2) > self.label = Label(self.window) self.label.grid(row=1, column=0, > columnspan=3) > dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. > .../Radar/net17/net17-YYYYMMDDHHMMSS.gif > self.imagefiles = glob.glob(dirName + "/*.gif") > self.imagefiles = cycle(self.imagefiles) > self.window.after_idle(self.next_image) > > def next_image(self): > imagefile = next(self.imagefiles) > image = Image.open(imagefile) > > w, h = image.size > image = image.resize((600, 550*h//w)) > > self.label.image = self.label["image"] = > ImageTk.PhotoImage(image=image) # <==== bails here > self.window.title("Now showing %s" % os.path.basename(imagefile)) > > self.window.after(2000, next_image) > > > I marked where the code bails with an error saying pyimage2 doesn't exist. > All of the images exist and worked just fine with your standalone script. > > Suggestions? Google says you are calling Tkinter.Tk() more than once where you should instead use Tkinter.Toplevel(). As you didn't post that part of the code it's hard to verify, but when I add a second root = tk.Tk() to my example script I get a very similar exception: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 498, in callit func(*args) File "cycle_image.py", line 16, in next_image label.image = label["image"] = ImageTk.PhotoImage(image=image) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1212, in __setitem__ self.configure({key: value}) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1205, in configure return self._configure('configure', cnf, kw) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1196, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) TclError: image "pyimage1" doesn't exist By the way: for future posts please remember to cut and paste the traceback, don't paraphrase the error message. Peter From bob at mellowood.ca Sat Aug 14 19:05:05 2010 From: bob at mellowood.ca (bvdp) Date: Sat, 14 Aug 2010 16:05:05 -0700 (PDT) Subject: Pop return from stack? Message-ID: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Assuming I have a module 'foo.py' with something like this: def error(s): print "Error", s sys.exit(1) def func(s): ... do some processing ... call error() if bad .. go to system exit. ... more processing and then I write a new program, test.py, which: import foo def myerror(s): print "new error message" foo.error = myerror a = foo.func(..) Now, if an error is encountered myerror() is called. Fine. But execution resumes in func(). Not exactly what I wanted. I can "fix" this simply by wrapping the call to foo.func() in a try/ expect and have myerror() raise an exception. This appears to work, but I'm hesitant to use this out of fear that I'm building up some kind of stack overflow or something which will bite me later. Is there a better way? Simplest for an old assembler guy like me would be pop a return address off the stack ... but python isn't assembler :) I don't want to change stuff in the foo.py module since it's part of an existing program. But, if I must, I suppose I could. I'd prefer to just short-circuit this if possible. Thanks. From chare at labr.net Sat Aug 14 19:23:02 2010 From: chare at labr.net (Chris Hare) Date: Sat, 14 Aug 2010 18:23:02 -0500 Subject: Tk window and contents will not display In-Reply-To: References: Message-ID: On Aug 14, 2010, at 5:49 PM, Peter Otten wrote: > Chris Hare wrote: > >> Thanks Peter. I threw away what I started with and merged your code into >> my class: >> >> class externalLoopDisplay: >> >> def show(self): >> main.logging.debug("externalLoopDisplay.show:","start") >> >> self.window = Tk() >> >> self.btnClose = Button(self.window, text="Close", >> command=self.window.destroy, >> bg=backColor,highlightbackground=warnColor, >> highlightcolor=okColor) self.btnClose.grid(row=0, column=2) >> self.label = Label(self.window) self.label.grid(row=1, column=0, >> columnspan=3) >> dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. >> .../Radar/net17/net17-YYYYMMDDHHMMSS.gif >> self.imagefiles = glob.glob(dirName + "/*.gif") >> self.imagefiles = cycle(self.imagefiles) >> self.window.after_idle(self.next_image) >> >> def next_image(self): >> imagefile = next(self.imagefiles) >> image = Image.open(imagefile) >> >> w, h = image.size >> image = image.resize((600, 550*h//w)) >> >> self.label.image = self.label["image"] = >> ImageTk.PhotoImage(image=image) # <==== bails here >> self.window.title("Now showing %s" % os.path.basename(imagefile)) >> >> self.window.after(2000, next_image) >> >> >> I marked where the code bails with an error saying pyimage2 doesn't exist. >> All of the images exist and worked just fine with your standalone script. >> >> Suggestions? > > Google says you are calling Tkinter.Tk() more than once where you should > instead use Tkinter.Toplevel(). As you didn't post that part of the code > it's hard to verify, but when I add a second > > root = tk.Tk() > > to my example script I get a very similar exception: > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ > return self.func(*args) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 498, in callit > func(*args) > File "cycle_image.py", line 16, in next_image > label.image = label["image"] = ImageTk.PhotoImage(image=image) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1212, in __setitem__ > self.configure({key: value}) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1205, in configure > return self._configure('configure', cnf, kw) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1196, in _configure > self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) > TclError: image "pyimage1" doesn't exist > > By the way: for future posts please remember to cut and paste the traceback, > don't paraphrase the error message. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list Yes - you are bang on. Thanks. One final question if I may, how would you suggest I handle checking for new files and adding them to the list? For example, if the loop is playing and a new image is added, how can I detect it and then refresh the list of file? I am stuck on that part with this new approach. Chris From thomas at jollybox.de Sat Aug 14 19:23:11 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 15 Aug 2010 01:23:11 +0200 Subject: Pop return from stack? In-Reply-To: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: <201008150123.12038.thomas@jollybox.de> On Sunday 15 August 2010, it occurred to bvdp to exclaim: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > print "Error", s > sys.exit(1) > > def func(s): > ... do some processing > ... call error() if bad .. go to system exit. > ... more processing > > and then I write a new program, test.py, which: > > import foo > > def myerror(s): > print "new error message" > > foo.error = myerror > > a = foo.func(..) > > Now, if an error is encountered myerror() is called. Fine. But > execution resumes in func(). Not exactly what I wanted. > > I can "fix" this simply by wrapping the call to foo.func() in a try/ > expect and have myerror() raise an exception. This appears to work, > but I'm hesitant to use this out of fear that I'm building up some > kind of stack overflow or something which will bite me later. An exception will walk up the stack, calling any cleaning-up code that needs to be done (removing object references, executing finally: blocks, exiting context managers properly. It won't break anything. Don't be afraid of Python's high-level features! > > Is there a better way? Simplest for an old assembler guy like me would > be pop a return address off the stack ... but python isn't > assembler :) Now that has a decent chance of messing things up and you (if you wrote decent assembly ;-)) know it -- without properly cleaning up before resuming execution in the right place, you could end up in a right state with memory leaks, leaked file descriptors, half-arsed database transactions, etc etc. > > I don't want to change stuff in the foo.py module since it's part of > an existing program. But, if I must, I suppose I could. I'd prefer to > just short-circuit this if possible. Exceptions. Simple. In the end, all system.exit does is raise a SystemExit exception... - Thomas From r.koebler at yahoo.de Sat Aug 14 19:24:00 2010 From: r.koebler at yahoo.de (Roland Koebler) Date: Sun, 15 Aug 2010 01:24:00 +0200 Subject: Simple Python Sandbox In-Reply-To: <4C66F4FD.1010102@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: <20100814232400.GA5205@localhost> Hi, > I know all this -- but its not relevant really, I think. I'm not trying > to create a safe yet relatively complete or functional Python. All those > efforts to sandbox Python fail because of the incredible dynamic nature > of the language has lots of enticing little holes in it. But I'm not > interested in a full or even vaguely full subset of Python, and I'm not > requiring that this security be done on the code-level. I had the same problem, and so I created a "pseudo-sandbox" for embedding Python in templates. This "pseudo-sandbox" creates a restricted Python environment, where only whitelisted functions/classes are allowed. Additionally, it prevents things like '0 .__class__'. You can find some documentation at http://simple-is-better.org/template/pyratemp.html#evaluation, and the pseudo-sandbox itself in my template-engine, class "EvalPseudoSandbox" on the website above. (Please write me if you have any comments.) But note that this is not a real sandbox! As soon as you allow *any* unsafe function (e.g. open, import, eval, getattr etc.), you can easily break out. Also, don't directly pass complete modules to the pseudo-sandbox, since they may contain unsafe functions/classes/etc. And be warned: There *may* also be ways to break out of the pseudo-sandbox even without passing unsafe functions to it -- although I don't know any. If you know or find such a way: Please tell me! You could also take a look at Jinja (which is also a template-engine), and which claims to include a sandbox. But the Jinja-sandbox seems to be much more complicated than my pseudo-sandbox, and I haven't analyzed it and don't know how it works. > For example, when you go to save your bit of code, it will go in and if > it finds __ anywhere in the text it just replaces it with xx. And, since > getattr is not available, '_' + '_' won't get you anywhere. I don't think that searching the text is the right way; in my pseudo-sandbox, I compile the code and search co_names for such names instead. > I just need a certain limited context where someone can be handed > certain Python objects and manipulate them. I'd like people to be able > to use some fundamental Python power -- the rich, beautiful data types > for example (notably in this case, strings), list comprehensions and > stuff, to do what they need to do. Python's very easy, I'd like them to > be able to use that easy. I was in the exact same position ;). (Although I don't have fully untrusted/bad users, and so my pseudo-sandbox is sufficient for my cases, even though I haven't proved that it really is secure...) regards, Roland From jyoung79 at kc.rr.com Sat Aug 14 19:44:50 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Sat, 14 Aug 2010 23:44:50 +0000 Subject: Working with PDFs? Message-ID: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> Just curious if anyone knows if it's possible to work with pdf documents with Python? I'd like to do the following: - Pull out text from each PDF page (to search for specific words) - Combine separate pdf documents into one document - Add bookmarks (with destination settings) A few programs I've been looking at are pdfminer, pyPDF, etc from this link: http://pypi.python.org/pypi?%3Aaction=search&term=pdf&submit=search Originally, I was using AppleScript and JavaScript to do this in Acrobat. But now Acrobat 9 has broken this process and I can't seem to make it work. I'd like to find other workarounds instead of having to rely on Adobe. Thanks for your help. Jay From __peter__ at web.de Sat Aug 14 19:46:20 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Aug 2010 01:46:20 +0200 Subject: Tk window and contents will not display References: Message-ID: Chris Hare wrote: > > On Aug 14, 2010, at 5:49 PM, Peter Otten wrote: > >> Chris Hare wrote: >> >>> Thanks Peter. I threw away what I started with and merged your code >>> into my class: >>> >>> class externalLoopDisplay: >>> >>> def show(self): >>> main.logging.debug("externalLoopDisplay.show:","start") >>> >>> self.window = Tk() >>> >>> self.btnClose = Button(self.window, text="Close", >>> command=self.window.destroy, >>> bg=backColor,highlightbackground=warnColor, >>> highlightcolor=okColor) self.btnClose.grid(row=0, column=2) >>> self.label = Label(self.window) self.label.grid(row=1, column=0, >>> columnspan=3) >>> dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. >>> .../Radar/net17/net17-YYYYMMDDHHMMSS.gif > Thanks. One final question if I may, how would you suggest I handle > checking for new files and adding them to the list? For example, if the > loop is playing and a new image is added, how can I detect it and then > refresh the list of file? > > I am stuck on that part with this new approach. > > Chris Replacing >>> self.imagefiles = glob.glob(dirName + "/*.gif") >>> self.imagefiles = cycle(self.imagefiles) with self.imagefiles = image_cycler(os.path.join(dirname, "*.gif")) where image_cycler() looks as follows def image_cycler(pattern): while True: for fn in glob.glob(pattern): yield fn would be the simplest way. Peter From steve at REMOVE-THIS-cybersource.com.au Sat Aug 14 20:06:35 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 00:06:35 GMT Subject: Simple Python Sandbox References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: <4c672f8a$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 01:24:00 +0200, Roland Koebler wrote: > I had the same problem, and so I created a "pseudo-sandbox" for > embedding Python in templates. This "pseudo-sandbox" creates a > restricted Python environment, where only whitelisted functions/classes > are allowed. Additionally, it prevents things like '0 .__class__'. Hmmm... is that meant just as an illustration of a general technique, or do you actually have something against the class of 0? 0 .__class__ seems pretty innocuous to me: >>> type(0) is 0 .__class__ is int True [...] > But note that this is not a real sandbox! As soon as you allow *any* > unsafe function (e.g. open, import, eval, getattr etc.), you can easily > break out. Isn't that true of any sandbox though? Surely by definition, if you allow an unsafe function in any sandbox, it's no longer an effective sandbox. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 14 20:09:19 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 00:09:19 GMT Subject: Simple Python Sandbox References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> Message-ID: <4c67302f$0$11100$c3e8da3@news.astraweb.com> On Sat, 14 Aug 2010 12:56:45 -0700, Stephen Hansen wrote: >> I suggest that if the untrusted code is only supposed to be simple and >> limited, you would be best off to write your own "mini-language" using >> Python syntax. > > I considered it and rejected it. The return from the effort required > doesn't even vaguely come close to making it worth it. I suppose that depends on how simple the untrusted code will be, but I guess you're in the best position to make that call. > My worst case > fall-back plan is to embed /another/ language (be it Lua or JavaScript > through V8) and offer it a very limited environment. But I don't want to > do that (and considering I solved the while True: pass problem last > night, I'm pretty sure I won't decide to). I assume you mean you've solved the problem of DOS attacks from users running infinite loops. How did you do that? -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 14 20:11:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 00:11:11 GMT Subject: print v. print() References: <4C66B52E.3B49EC1@tesco.net> Message-ID: <4c67309f$0$11100$c3e8da3@news.astraweb.com> On Sat, 14 Aug 2010 11:44:22 -0400, Mel wrote: > The downside to a print() function is that assigning to `print` can mask > the function, and leave a neophyte without any way to get output out of > the program. On the other hand, the upside to a print() function is that assigning to `print` can monkey-patch the function, allowing the advanced user to modify it's functionality at runtime. Whether that's a feature or a shooting offence is a matter of opinion. (I think it's a feature, albeit one which is easy to misuse.) -- Steven From no.email at please.post Sat Aug 14 20:13:24 2010 From: no.email at please.post (kj) Date: Sun, 15 Aug 2010 00:13:24 +0000 (UTC) Subject: shelf-like list? References: Message-ID: In Raymond Hettinger writes: >On Aug 12, 1:37=A0pm, Thomas Jollans wrote: >> On Tuesday 10 August 2010, it occurred to kj to exclaim: >> >> > I'm looking for a module that implements "persistent lists": objects >> > that behave like lists except that all their elements are stored >> > on disk. =A0IOW, the equivalent of "shelves", but for lists rather >> > than a dictionaries. > . . . >> You could simply use pickle to save the data every once in a while. >That is a very reasonable solution. Sorry I don't follow. Some sample code would be helpful. TIA, ~K From python at mrabarnett.plus.com Sat Aug 14 20:18:37 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 15 Aug 2010 01:18:37 +0100 Subject: Working with PDFs? In-Reply-To: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> References: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> Message-ID: <4C67325D.8060706@mrabarnett.plus.com> jyoung79 at kc.rr.com wrote: > Just curious if anyone knows if it's possible to work with pdf documents > with Python? I'd like to do the following: > > - Pull out text from each PDF page (to search for specific words) > - Combine separate pdf documents into one document > - Add bookmarks (with destination settings) > > A few programs I've been looking at are pdfminer, pyPDF, etc from this > link: > http://pypi.python.org/pypi?%3Aaction=search&term=pdf&submit=search > > Originally, I was using AppleScript and JavaScript to do this in Acrobat. > But now Acrobat 9 has broken this process and I can't seem to make it > work. I'd like to find other workarounds instead of having to rely on > Adobe. > Have you tried OpenOffice? From steve at REMOVE-THIS-cybersource.com.au Sat Aug 14 20:23:18 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 00:23:18 GMT Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: <4c673375$0$11100$c3e8da3@news.astraweb.com> On Sat, 14 Aug 2010 16:05:05 -0700, bvdp wrote: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > print "Error", s > sys.exit(1) > > def func(s): > ... do some processing > ... call error() if bad .. go to system exit. ... more processing > > and then I write a new program, test.py, which: > > import foo > > def myerror(s): > print "new error message" > > foo.error = myerror > > a = foo.func(..) This general technique is called "monkey patching". > Now, if an error is encountered myerror() is called. Fine. But execution > resumes in func(). Not exactly what I wanted. Of course it does. Your new error handler fails to exit, so execution resumes like it does after any other function. You can either manually exit from your own error handler: def myerror(s): print "new error message" sys.exit(2) or call the original error handler: def myerror(s): print "new error message" foo._error(s) That second technique requires some preparation before hand. In module foo, after defining the error() function, you then need to create a second, private, name to it: _error = error > I can "fix" this simply by wrapping the call to foo.func() in a try/ > expect and have myerror() raise an exception. This appears to work, but > I'm hesitant to use this out of fear that I'm building up some kind of > stack overflow or something which will bite me later. Exceptions are the standard way of doing things. That's what sys.exit() does -- it raises SystemExit exception. With very few exceptions, if you're writing your own error handlers like this, you're doing it wrong. Your error handler throws away useful debugging information, and it gives you no extra information that a standard Python traceback couldn't give. > Is there a better way? Simplest for an old assembler guy like me would > be pop a return address off the stack ... but python isn't assembler :) Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in Python, even VB in Python, but this is the first time I've meet some one who wants to write assembler in Python :) -- Steven From no.email at please.post Sat Aug 14 20:25:25 2010 From: no.email at please.post (kj) Date: Sun, 15 Aug 2010 00:25:25 +0000 (UTC) Subject: How to add silent stretches to MP3 using Python? Message-ID: Here's the problem: I have about 25,000 mp3 files, each lasting, *on average*, only a few seconds, though the variance is wide (the longest one lasts around 20 seconds). (These files correspond to sample sentences for foreign language training.) The problem is that there is basically no padding before and after the sound signal. I want to prepend about 2 seconds of silence to each file, and append another silent stretch at the end lasting either 2 seconds or some multiplier of the duration of the original file, whichever is greater. I know that manipulating MP3 audio programmatically is usually not easy, but this has got to be one of the simplest manipulations possible, so I'm hoping I'll be able to pull it off with Python. But I have not had much luck finding a Python library to do this. If someone knows how to do this, and could give me some pointers, I'd appreciate it. TIA! ~K From lists at cheimes.de Sat Aug 14 20:36:47 2010 From: lists at cheimes.de (Christian Heimes) Date: Sun, 15 Aug 2010 02:36:47 +0200 Subject: Simple Python Sandbox In-Reply-To: <4C66F4FD.1010102@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: > For example, when you go to save your bit of code, it will go in and if > it finds __ anywhere in the text it just replaces it with xx. And, since > getattr is not available, '_' + '_' won't get you anywhere. That's not as secure as you might think. First of all you can write "_" in more way than you may think. >>> 2*chr(0x5f) + "insecure" + 2*chr(0x5f) '__insecure__' >>> "\x5f\x5finsecure\x5f\x5f" '__insecure__' >>> str(u"\N{LOW LINE}\N{LOW LINE}insecure\N{LOW LINE}\N{LOW LINE}") '__insecure__' If you have access to eval, exec or compile you can easily work around your restrictions: >>> getattribute = eval("object.__getattribute__") >>> getattribute(int, "__new__")(int, "3") 3 As you can see, black listing isn't the best approach here. Christian From chare at labr.net Sat Aug 14 20:50:25 2010 From: chare at labr.net (Chris Hare) Date: Sat, 14 Aug 2010 19:50:25 -0500 Subject: Tk window and contents will not display In-Reply-To: References: Message-ID: <6DDC6BAF-EED6-452A-A2B9-00C2210049E6@labr.net> On Aug 14, 2010, at 6:46 PM, Peter Otten wrote: > Chris Hare wrote: > >> >> On Aug 14, 2010, at 5:49 PM, Peter Otten wrote: >> >>> Chris Hare wrote: >>> >>>> Thanks Peter. I threw away what I started with and merged your code >>>> into my class: >>>> >>>> class externalLoopDisplay: >>>> >>>> def show(self): >>>> main.logging.debug("externalLoopDisplay.show:","start") >>>> >>>> self.window = Tk() >>>> >>>> self.btnClose = Button(self.window, text="Close", >>>> command=self.window.destroy, >>>> bg=backColor,highlightbackground=warnColor, >>>> highlightcolor=okColor) self.btnClose.grid(row=0, column=2) >>>> self.label = Label(self.window) self.label.grid(row=1, column=0, >>>> columnspan=3) >>>> dirName = getRadarPath() + "/net" + str(netNumber.get()) # e.g. >>>> .../Radar/net17/net17-YYYYMMDDHHMMSS.gif > >> Thanks. One final question if I may, how would you suggest I handle >> checking for new files and adding them to the list? For example, if the >> loop is playing and a new image is added, how can I detect it and then >> refresh the list of file? >> >> I am stuck on that part with this new approach. >> >> Chris > > Replacing > >>>> self.imagefiles = glob.glob(dirName + "/*.gif") >>>> self.imagefiles = cycle(self.imagefiles) > > with > > self.imagefiles = image_cycler(os.path.join(dirname, "*.gif")) > > where image_cycler() looks as follows > > def image_cycler(pattern): > while True: > for fn in glob.glob(pattern): > yield fn > > would be the simplest way. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list Perfect! Thank you From r.koebler at yahoo.de Sat Aug 14 20:51:28 2010 From: r.koebler at yahoo.de (Roland Koebler) Date: Sun, 15 Aug 2010 02:51:28 +0200 Subject: Simple Python Sandbox In-Reply-To: <4c672f8a$0$11100$c3e8da3@news.astraweb.com> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4c672f8a$0$11100$c3e8da3@news.astraweb.com> Message-ID: <20100815005128.GB5205@localhost> On Sun, Aug 15, 2010 at 12:06:35AM +0000, Steven D'Aprano wrote: > Hmmm... is that meant just as an illustration of a general technique, or > do you actually have something against the class of 0? It's a short illustration; 0 .__class__ itself is harmless, but e.g. 0 .__class__.__base__.__subclasses__() isn't. > > But note that this is not a real sandbox! As soon as you allow *any* > > unsafe function (e.g. open, import, eval, getattr etc.), you can easily > > break out. > > Isn't that true of any sandbox though? Surely by definition, if you allow > an unsafe function in any sandbox, it's no longer an effective sandbox. In my opinion, a "real" sandbox should allow to use "unsafe" functions (e.g. open(), import modules etc.) -- so you could run your normal code in it. But it should prevent the "bad" effects of the code, e.g. by redirecting I/O, limiting resources etc. regards, Roland From python.list at tim.thechases.com Sat Aug 14 20:57:54 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 14 Aug 2010 19:57:54 -0500 Subject: How to add silent stretches to MP3 using Python? In-Reply-To: References: Message-ID: <4C673B92.5090002@tim.thechases.com> > Here's the problem: I have about 25,000 mp3 files, each lasting, > *on average*, only a few seconds, though the variance is wide (the > longest one lasts around 20 seconds). (These files correspond to > sample sentences for foreign language training.) > > The problem is that there is basically no padding before and after > the sound signal. I want to prepend about 2 seconds of silence to > each file, and append another silent stretch at the end lasting > either 2 seconds or some multiplier of the duration of the original > file, whichever is greater. > > I know that manipulating MP3 audio programmatically is usually not > easy, but this has got to be one of the simplest manipulations > possible, so I'm hoping I'll be able to pull it off with Python. > > But I have not had much luck finding a Python library to do this. > If someone knows how to do this, and could give me some pointers, > I'd appreciate it. While it's (1) not 100% python and (2) doesn't allow for your "2 seconds...or some multiplier of the duration, whichever is greater", you can use mp3wrap[1] to losslessly join the files. If you happen to make a 2-seconds-of-silence MP3, you can then join your files together with the silence. For 25k files, you might have to stitch subsets of them together incrementally and then stitch together the resulting files. -tkc [1] http://mp3wrap.sourceforge.net/ or "apt-get install mp3wrap" here on my Debian box From pavlovevidence at gmail.com Sat Aug 14 22:26:09 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 14 Aug 2010 19:26:09 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: <88cb8d7f-efb6-4217-b65a-65e479fd4e5f@p22g2000pre.googlegroups.com> On Aug 14, 4:05?pm, bvdp wrote: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > ? ? print "Error", s > ? ? sys.exit(1) > > def func(s): > ? ? ... do some processing > ? ? ... call error() if bad .. go to system exit. > ? ? ... ?more processing > > and then I write a new program, test.py, which: > > import foo > > def myerror(s): > ? ? print "new error message" > > foo.error = myerror > > a = foo.func(..) > > Now, if an error is encountered myerror() is called. Fine. But > execution resumes in func(). Not exactly what I wanted. > > I can "fix" this simply by wrapping the call to foo.func() in a try/ > expect and have myerror() raise an exception. This appears to work, > but I'm hesitant to use this out of fear that I'm building up some > kind of stack overflow or something which will bite me later. What do you think a few words of data the stack are going to do? Just do it this way. Carl Banks From me+list/python at ixokai.io Sat Aug 14 22:43:13 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 19:43:13 -0700 Subject: Simple Python Sandbox In-Reply-To: <4c672f8a$0$11100$c3e8da3@news.astraweb.com> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4c672f8a$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4C675441.8090105@ixokai.io> On 8/14/10 5:06 PM, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 01:24:00 +0200, Roland Koebler wrote: > >> I had the same problem, and so I created a "pseudo-sandbox" for >> embedding Python in templates. This "pseudo-sandbox" creates a >> restricted Python environment, where only whitelisted functions/classes >> are allowed. Additionally, it prevents things like '0 .__class__'. > > Hmmm... is that meant just as an illustration of a general technique, or > do you actually have something against the class of 0? 0 .__class__ seems > pretty innocuous to me: > >>>> type(0) is 0 .__class__ is int > True Assuming you have a totally restricted environment, where none of the normal built-ins are available-- notably "type"-- in theory I thought once that you could exec pretty safely. Because there's just no access to anything! But, alas, someone showed me I was wrong. 0 .__class__ can lead you to "type". And type.__subclasses__ happily leads you to everything in the world. I solve this by just refusing to allow getattr, and __ anywhere in the file to be saved just gets turned into xx, so its impossible (I think) for users to access or use any special method. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From me+list/python at ixokai.io Sat Aug 14 22:48:14 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 19:48:14 -0700 Subject: Simple Python Sandbox In-Reply-To: <20100814212552.GA30391@cskk.homeip.net> References: <4C66F4FD.1010102@ixokai.io> <20100814212552.GA30391@cskk.homeip.net> Message-ID: <4C67556E.4080800@ixokai.io> On 8/14/10 2:25 PM, Cameron Simpson wrote: > Ok, what about this: run the untrusted code in a separate process, > if necessary running as a user with different privileges. Way too much overhead by a really significant margin: I need to do many, many, many, many, many very short (often very *very* short) little scripts. Doing IPC to separate processes, even if they're long-running, and handling proxying of my objects that these scripts need to read from and tweak in certain ways, would just kill performance. I really do need an embedded language -- and a very restricted subset of Python is really ideal for that, which is why I'm going for this. :) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From me+list/python at ixokai.io Sat Aug 14 22:54:11 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 19:54:11 -0700 Subject: Simple Python Sandbox In-Reply-To: <20100814232400.GA5205@localhost> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <20100814232400.GA5205@localhost> Message-ID: <4C6756D3.60205@ixokai.io> On 8/14/10 4:24 PM, Roland Koebler wrote: > You can find some documentation at > http://simple-is-better.org/template/pyratemp.html#evaluation, > and the pseudo-sandbox itself in my template-engine, class > "EvalPseudoSandbox" on the website above. > (Please write me if you have any comments.) How are you implementing refusing-names-beginning-with-underscore, out of curiosity? > You could also take a look at Jinja (which is also a template-engine), > and which claims to include a sandbox. But the Jinja-sandbox seems to > be much more complicated than my pseudo-sandbox, and I haven't analyzed > it and don't know how it works. I'll take a look. >> I just need a certain limited context where someone can be handed >> certain Python objects and manipulate them. I'd like people to be able >> to use some fundamental Python power -- the rich, beautiful data types >> for example (notably in this case, strings), list comprehensions and >> stuff, to do what they need to do. Python's very easy, I'd like them to >> be able to use that easy. > I was in the exact same position ;). > (Although I don't have fully untrusted/bad users, and so my pseudo-sandbox > is sufficient for my cases, even though I haven't proved that it really is > secure...) I don't *really* have a bunch fully untrusted / bad users, in fact I expect I will sort of trust all the people doing this level of coding -- but I believe that either incompetance and maliciousness is inevitable in any sort of online community, and making it at least as hard as possible to do damage while giving people as much freedom and tools to do great is the ideal goal. :) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From tjreedy at udel.edu Sat Aug 14 22:58:48 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Aug 2010 22:58:48 -0400 Subject: Working with PDFs? In-Reply-To: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> References: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> Message-ID: On 8/14/2010 7:44 PM, jyoung79 at kc.rr.com wrote: > Just curious if anyone knows if it's possible to work with pdf documents > with Python? I'd like to do the following: search python pdf library reportlab -- Terry Jan Reedy From me+list/python at ixokai.io Sat Aug 14 23:01:00 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 20:01:00 -0700 Subject: Simple Python Sandbox In-Reply-To: References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> Message-ID: <4C67586C.3020107@ixokai.io> On 8/14/10 5:36 PM, Christian Heimes wrote: >> For example, when you go to save your bit of code, it will go in and if >> it finds __ anywhere in the text it just replaces it with xx. And, since >> getattr is not available, '_' + '_' won't get you anywhere. > > That's not as secure as you might think. First of all you can write "_" > in more way than you may think. Well yes, I know-- but as I said in the original post, eval, exec, compile, getattr and such, are all unavailable. So its possible someone can write '_' in various ways (though I'm disallowing both chr and unichr for entirely different reasons), and they can even put them together so that there's a __ as a string in some variable, I can't find any way in which they would then be able to get to get a special method. Namely, type.__subclasses__ or object.__getattribute__. They can't enter any code which does blah.__class__, and they can't construct a string through twisty ways to then do getattr(blah, twisty) where twisty = "__class__". > If you have access to eval, exec or compile you can easily work around > your restrictions: I think its pretty much a given that if you're even trying to do some kind of restricted sandbox, eval and the like are the first things to go. :) > As you can see, black listing isn't the best approach here. But I have a two pronged strategy: the black list is only half of the equation. One, I'm blacklisting all the meta functions out of builtins. Eval, compile, getattr, and such. Then, I'm doing some blatant textual munging, making it so someone can not access any __special__ methods, or use exec. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From me+list/python at ixokai.io Sat Aug 14 23:07:37 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 20:07:37 -0700 Subject: Simple Python Sandbox In-Reply-To: <4c67302f$0$11100$c3e8da3@news.astraweb.com> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4c67302f$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4C6759F9.9040406@ixokai.io> On 8/14/10 5:09 PM, Steven D'Aprano wrote: >> My worst case >> fall-back plan is to embed /another/ language (be it Lua or JavaScript >> through V8) and offer it a very limited environment. But I don't want to >> do that (and considering I solved the while True: pass problem last >> night, I'm pretty sure I won't decide to). > > I assume you mean you've solved the problem of DOS attacks from users > running infinite loops. How did you do that? Since I only have to run this on Unix-isms, I'm using alarm()/signal(). The C code takes the hash of the source code that's going to be executed and marks it, then sets an alarm and executes the code (though its usually been compiled into a code object). There's no code which would -ever- in this situation take longer then 2 seconds to run (and that's extremely generous), but the alarm is 5: if the code doesn't return and cancel the alarm by then, I know the code is functionally broken. So, the signal handler records the hash of the code that failed -- it'll never be tried again -- logs an error message, and restarts the whole process (which happens seamlessly with virtually no user interruption, but this system is not architected in a way where its readily able to resume operation in the event of a signal interrupt). This isn't perfect: infinite loops it kills, but things like [0] * 10^^100 crash head first into the machine and bring it to a crawl. I haven't figured out a strategy for trying to address that yet, and ultimately, I may not find one. That's okay: perfection isn't my goal, infinite loops are easy enough to do on accident that halting them is important. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From clp2 at rebertia.com Sat Aug 14 23:08:17 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 14 Aug 2010 20:08:17 -0700 Subject: Pop return from stack? In-Reply-To: <4c673375$0$11100$c3e8da3@news.astraweb.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c673375$0$11100$c3e8da3@news.astraweb.com> Message-ID: On Sat, Aug 14, 2010 at 5:23 PM, Steven D'Aprano wrote: > Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in > Python, even VB in Python, but this is the first time I've meet some one > who wants to write assembler in Python :) +1 QOTW Cheers, Chris From debatem1 at gmail.com Sat Aug 14 23:11:48 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 14 Aug 2010 20:11:48 -0700 Subject: Simple Python Sandbox In-Reply-To: <4C6759F9.9040406@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4c67302f$0$11100$c3e8da3@news.astraweb.com> <4C6759F9.9040406@ixokai.io> Message-ID: On Sat, Aug 14, 2010 at 8:07 PM, Stephen Hansen wrote: > On 8/14/10 5:09 PM, Steven D'Aprano wrote: >>> My worst case >>> fall-back plan is to embed /another/ language (be it Lua or JavaScript >>> through V8) and offer it a very limited environment. But I don't want to >>> do that (and considering I solved the while True: pass problem last >>> night, I'm pretty sure I won't decide to). >> >> I assume you mean you've solved the problem of DOS attacks from users >> running infinite loops. How did you do that? > > Since I only have to run this on Unix-isms, I'm using alarm()/signal(). > The C code takes the hash of the source code that's going to be executed > and marks it, then sets an alarm and executes the code (though its > usually been compiled into a code object). > > There's no code which would -ever- in this situation take longer then 2 > seconds to run (and that's extremely generous), but the alarm is 5: if > the code doesn't return and cancel the alarm by then, I know the code is > functionally broken. > > So, the signal handler records the hash of the code that failed -- it'll > never be tried again -- logs an error message, and restarts the whole > process (which happens seamlessly with virtually no user interruption, > but this system is not architected in a way where its readily able to > resume operation in the event of a signal interrupt). > > This isn't perfect: infinite loops it kills, but things like [0] * > 10^^100 crash head first into the machine and bring it to a crawl. I > haven't figured out a strategy for trying to address that yet, and > ultimately, I may not find one. That's okay: perfection isn't my goal, > infinite loops are easy enough to do on accident that halting them is > important. cpulimit or a cgroups container can both be easy solutions here, depending on your exact needs. Geremy Condra From me+list/python at ixokai.io Sat Aug 14 23:18:14 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 14 Aug 2010 20:18:14 -0700 Subject: Simple Python Sandbox In-Reply-To: References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4c67302f$0$11100$c3e8da3@news.astraweb.com> <4C6759F9.9040406@ixokai.io> Message-ID: <4C675C76.7080708@ixokai.io> On 8/14/10 8:11 PM, geremy condra wrote: > cpulimit or a cgroups container can both be easy solutions here, > depending on your exact needs. Hmm! I wasn't aware of those, I'll check that out. Thanks. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From debatem1 at gmail.com Sat Aug 14 23:30:18 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 14 Aug 2010 20:30:18 -0700 Subject: Simple Python Sandbox In-Reply-To: <4C675C76.7080708@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4c67302f$0$11100$c3e8da3@news.astraweb.com> <4C6759F9.9040406@ixokai.io> <4C675C76.7080708@ixokai.io> Message-ID: On Sat, Aug 14, 2010 at 8:18 PM, Stephen Hansen wrote: > On 8/14/10 8:11 PM, geremy condra wrote: >> cpulimit or a cgroups container can both be easy solutions here, >> depending on your exact needs. > > Hmm! I wasn't aware of those, I'll check that out. Thanks. Np. I wrote a set of cgroups bindings in Python a few years ago that I could probably lay my hands on if they'd help, although they may be out of date by now. Geremy Condra From ldo at geek-central.gen.new_zealand Sat Aug 14 23:45:51 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 15:45:51 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <4d0d01b7-14ab-42b1-aeb2-49050ee5ab78@y11g2000yqm.googlegroups.com> <9da7j7-pv2.ln1@satorlaser.homedns.org> <4C61E9A1.5090800@v.loewis.de> <88t9j7-ri5.ln1@satorlaser.homedns.org> <44d30ac7-931e-4eb0-9aed-f664c872d438@l20g2000yqm.googlegroups.com> Message-ID: In message <44d30ac7-931e-4eb0-9aed-f664c872d438 at l20g2000yqm.googlegroups.com>, sturlamolden wrote: > A C++ compiler can use Python's header files and link with Python's C API > correctly. But it cannot compile Python's C source code. A C compiler > is required to compile and build Python. Since when do you find a C++ compiler not accompanied by a C one? From bob at mellowood.ca Sun Aug 15 00:36:29 2010 From: bob at mellowood.ca (bvdp) Date: Sat, 14 Aug 2010 21:36:29 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: > An exception will walk up the stack, calling any cleaning-up code that needs > to be done (removing object references, executing finally: blocks, exiting > context managers properly. It won't break anything. Don't be afraid of > Python's high-level features! Okay, I believe you (and the rest of the gang. In my trivial program the exception in working ... so I'll leave it alone. Thanks. > - Thomas From bob at mellowood.ca Sun Aug 15 00:41:34 2010 From: bob at mellowood.ca (bvdp) Date: Sat, 14 Aug 2010 21:41:34 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c673375$0$11100$c3e8da3@news.astraweb.com> Message-ID: <6fa333b1-6474-407b-951a-452543e827bd@f6g2000pro.googlegroups.com> On Aug 14, 5:23?pm, Steven D'Aprano wrote: > This general technique is called "monkey patching". > New term for me :) > > Now, if an error is encountered myerror() is called. Fine. But execution > > resumes in func(). Not exactly what I wanted. > > Of course it does. Your new error handler fails to exit, so execution > resumes like it does after any other function. I guess I wasn't being clear. I don't want to exit in my new bit of code. Just continue a loop (which I didn't show in the example). > Exceptions are the standard way of doing things. That's what sys.exit() > does -- it raises SystemExit exception. Okay, didn't know that exit() was really an exception. Good to know. But, like I said, I'm not looking to exit. > > With very few exceptions, if you're writing your own error handlers like > this, you're doing it wrong. Your error handler throws away useful > debugging information, and it gives you no extra information that a > standard Python traceback couldn't give. Yeah, but I really don't want a traceback printed out for a user just because a file can't be found, or he's got a bad bit of syntax in his file. So, that's why I have the specific error routine. Works fine in the main program. > Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in > Python, even VB in Python, but this is the first time I've meet some one > who wants to write assembler in Python :) Naw, I had my fun with assembler in the good old days. Never want to write another line of it :) From invalid at invalid.invalid Sun Aug 15 00:58:40 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 15 Aug 2010 04:58:40 +0000 (UTC) Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: On 2010-08-14, Aahz wrote: > Paul Rubin wrote: >> >>I'm not sure what the hiring issue is. I think anyone skilled in C++ or >>Java can pick up Ada pretty easily. It's mostly a subset of C++ with >>different surface syntax. > > Heck, I learned Ada as a sixteen-year-old knowing only BASIC and Pascal. Unfortunately, there just aren't that many Aahzes to hire (sixteen years old or otherwise), and of the non-Aahz progrommers out there it's shocking how many of them them are apparently incapable of learning a second language. Regardless of how easy something is to learn, management always wants to hire people who don't have to. -- Grant From zac256 at gmail.com Sun Aug 15 01:00:57 2010 From: zac256 at gmail.com (Zac Burns) Date: Sat, 14 Aug 2010 22:00:57 -0700 Subject: shelf-like list? In-Reply-To: References: Message-ID: This should help: http://docs.python.org/library/pickle.html -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games On Sat, Aug 14, 2010 at 5:13 PM, kj wrote: > In > Raymond Hettinger writes: > > >On Aug 12, 1:37=A0pm, Thomas Jollans wrote: > >> On Tuesday 10 August 2010, it occurred to kj to exclaim: > >> > >> > I'm looking for a module that implements "persistent lists": objects > >> > that behave like lists except that all their elements are stored > >> > on disk. =A0IOW, the equivalent of "shelves", but for lists rather > >> > than a dictionaries. > > . . . > >> You could simply use pickle to save the data every once in a while. > > >That is a very reasonable solution. > > Sorry I don't follow. Some sample code would be helpful. > TIA, > ~K > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 15 01:26:32 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 14 Aug 2010 22:26:32 -0700 Subject: shelf-like list? In-Reply-To: References: Message-ID: On Sat, Aug 14, 2010 at 5:13 PM, kj wrote: > In Raymond Hettinger writes: >>On Aug 12, 1:37=A0pm, Thomas Jollans wrote: >>> On Tuesday 10 August 2010, it occurred to kj to exclaim: >>> >>> > I'm looking for a module that implements "persistent lists": objects >>> > that behave like lists except that all their elements are stored >>> > on disk. =A0IOW, the equivalent of "shelves", but for lists rather >>> > than a dictionaries. >> . . . >>> You could simply use pickle to save the data every once in a while. > >>That is a very reasonable solution. > > Sorry I don't follow. ?Some sample code would be helpful. I would assume something along the lines of (untested): from pickle import dump MOD_THRESHOLD = 42 class PersistentList(list): def __init__(self, filepath): self.filepath = filepath self._mod_count = 0 def save(self): with open(self.filepath, 'w') as f: dump(self, f) self._mod_count = 0 def append(self, *args, **kwds): super(PersistentList, self).append(*args, **kwds) self._mod_count += 1 if self._mod_count >= MOD_THRESHOLD: # obviously time-since-last-dump or other # more sophisticated metrics might be used instead self.save() # define similar wrappers for list's other mutator methods: __delitem__, __iadd__, __imul__, __setitem__, extend, insert, pop, remove, etc. # using decorators should help decrease code duplication Cheers, Chris -- http://blog.rebertia.com From rami.chowdhury at gmail.com Sun Aug 15 02:32:24 2010 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sun, 15 Aug 2010 12:32:24 +0600 Subject: OpenCV_Problem In-Reply-To: References: Message-ID: On Sun, Aug 15, 2010 at 12:22, arihant nahata wrote: > Hi, > ?? ?I m new to python and openCV. I think you meant to send this to the list ;-) > i installed openCV and python and copied > the necessary folder. and even appended the sys.path. but then too the same > error. > > from opencv import cv > > File "C:\Python26\lib\site-packages\opencv\__init__.py", line 74,?in > > > from cv import * > File "C:\Python26\lib\site-packages\opencv\cv.py", line 25, in? > > _cv = swig_import_helper() > File "C:\Python26\lib\site-packages\opencv\cv.py", line 21, in > swig_import_helper > _mod = imp.load_module('_cv', fp, pathname, description) > ImportError: DLL load failed: The specified module could not be?found. > > can you help me with this?? > Regards, > > Arihant Is there a module _cv.dll in your sys.path? Regards, Rami From debatem1 at gmail.com Sun Aug 15 02:41:49 2010 From: debatem1 at gmail.com (geremy condra) Date: Sat, 14 Aug 2010 23:41:49 -0700 Subject: Working with PDFs? In-Reply-To: References: <20100814234450.JGUH1.145562.root@cdptpa-web21-z01> Message-ID: On Sat, Aug 14, 2010 at 7:58 PM, Terry Reedy wrote: > On 8/14/2010 7:44 PM, jyoung79 at kc.rr.com wrote: >> >> Just curious if anyone knows if it's possible to work with pdf documents >> with Python? ?I'd like to do the following: > > search python pdf library > reportlab I second the reportlab recommendation; while I've never had to search PDFs etc, I've produced some very good-looking ones with it and was very happy with how little effort it took. Geremy Condra From bchang2002 at gmail.com Sun Aug 15 03:45:06 2010 From: bchang2002 at gmail.com (dontcare) Date: Sun, 15 Aug 2010 00:45:06 -0700 (PDT) Subject: [ANN]VTD-XML 2.9 Message-ID: <1c76256b-0010-42e0-af92-ec8dbffc1bc0@l32g2000prn.googlegroups.com> VTD-XML 2.9, the next generation XML Processing API for SOA and Cloud computing, has been released. Please visit https://sourceforge.net/projects/vtd-xml/files/ to download the latest version. * Strict Conformance #VTD-XML now fully conforms to XML namespace 1.0 spec * Performance Improvement #Significantly improved parsing performance for small XML files * Expand Core VTD-XML API #Adds getPrefixString(), and toNormalizedString2() * Cutting/Splitting #Adds getSiblingElementFragment() * A number of bug fixes and code enhancement including: #Fixes a bug for reading very large XML documents on some platforms #Fixes a bug in parsing processing instruction #Fixes a bug in outputAndReparse() From martin at v.loewis.de Sun Aug 15 03:51:49 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 15 Aug 2010 09:51:49 +0200 Subject: shelf-like list? In-Reply-To: References: Message-ID: > Does anyone know of such a module? ZODB supports persistent lists. Regards, Martin From darragh.ssa at gmail.com Sun Aug 15 04:03:47 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Sun, 15 Aug 2010 01:03:47 -0700 (PDT) Subject: Deditor -- pythonic text-editor References: Message-ID: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> I've noticed that there were a lot of downloads since I posted this topic, but I don't get any response from anyone so I actually still don't know whether it is good, bad, ugly, pretty, easy to use,... So please help me! :) From kmaha85 at gmail.com Sun Aug 15 06:33:45 2010 From: kmaha85 at gmail.com (p.mahalakshmi maha) Date: Sun, 15 Aug 2010 03:33:45 -0700 (PDT) Subject: MOVIES SONGS FITNESS FRIENDSHIPS AND MORE Message-ID: new movies new songs new fitness tips new friendships new actress MMS new EXCLUSIVE and MORE FREE www.123maza.com/25/shirt156/ www.slim.com/go/g1246010/ From ldo at geek-central.gen.new_zealand Sun Aug 15 06:40:12 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 22:40:12 +1200 Subject: Why is python not written in C++ ? References: <4c55fe82$0$9111$426a34cc@news.free.fr> <7xmxt3uo4h.fsf@ruckus.brouhaha.com> <7xeieevrze.fsf@ruckus.brouhaha.com> Message-ID: In message , Aahz wrote: > Heck, I learned Ada as a sixteen-year-old knowing only BASIC and Pascal. Not so surprising, considering Ada was consciously modelled on Pascal. From ldo at geek-central.gen.new_zealand Sun Aug 15 06:49:42 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 22:49:42 +1200 Subject: Simple Python Sandbox References: <4C66F4FD.1010102@ixokai.io> <20100814212552.GA30391@cskk.homeip.net> Message-ID: In message , Stephen Hansen wrote: > On 8/14/10 2:25 PM, Cameron Simpson wrote: > >> Ok, what about this: run the untrusted code in a separate process, >> if necessary running as a user with different privileges. > > Way too much overhead by a really significant margin: I need to do many, > many, many, many, many very short (often very *very* short) little > scripts. Doing IPC to separate processes, even if they're long-running, > and handling proxying of my objects that these scripts need to read from > and tweak in certain ways, would just kill performance. Not necessarily. How about doing IPC via shared memory? From ldo at geek-central.gen.new_zealand Sun Aug 15 06:55:36 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 22:55:36 +1200 Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: In message <4c5db0ae$0$1641$742ec2ed at news.sonic.net>, John Nagle wrote: > The languages which have real multidimensional arrays, rather > than arrays of arrays, tend to use 1-based subscripts. That > reflects standard practice in mathematics. Actually I?d go one better, and say that the languages that have real multidimensional arrays allow you to explicitly specify both the lower and upper bounds of each dimension. E.g. Ada, ALGOL 68. Heck, even Pascal allowed you to do that. From no.email at please.post Sun Aug 15 06:58:14 2010 From: no.email at please.post (kj) Date: Sun, 15 Aug 2010 10:58:14 +0000 (UTC) Subject: shelf-like list? References: Message-ID: In Chris Rebert writes: >On Sat, Aug 14, 2010 at 5:13 PM, kj wrote: >> In Ra= >ymond Hettinger writes: >>>On Aug 12, 1:37=3DA0pm, Thomas Jollans wrote: >>>> On Tuesday 10 August 2010, it occurred to kj to exclaim: >>>> >>>> > I'm looking for a module that implements "persistent lists": objects >>>> > that behave like lists except that all their elements are stored >>>> > on disk. =3DA0IOW, the equivalent of "shelves", but for lists rather >>>> > than a dictionaries. >>> . . . >>>> You could simply use pickle to save the data every once in a while. >> >>>That is a very reasonable solution. >> >> Sorry I don't follow. =C2=A0Some sample code would be helpful. >I would assume something along the lines of (untested): >from pickle import dump >MOD_THRESHOLD =3D 42 >class PersistentList(list): > def __init__(self, filepath): > self.filepath =3D filepath > self._mod_count =3D 0 > def save(self): > with open(self.filepath, 'w') as f: > dump(self, f) > self._mod_count =3D 0 > def append(self, *args, **kwds): > super(PersistentList, self).append(*args, **kwds) > self._mod_count +=3D 1 > if self._mod_count >=3D MOD_THRESHOLD: > # obviously time-since-last-dump or other > # more sophisticated metrics might be used instead > self.save() Even though it is saved periodically to disk, it looks like the whole list remains in memory all the time? (If so, it's not what I'm looking for; the whole point of saving stuff to disk is to keep the list's memory footprint low.) ~K From no.email at please.post Sun Aug 15 06:58:44 2010 From: no.email at please.post (kj) Date: Sun, 15 Aug 2010 10:58:44 +0000 (UTC) Subject: shelf-like list? References: Message-ID: In "Martin v. Loewis" writes: >> Does anyone know of such a module? >ZODB supports persistent lists. Thanks; I'll check it out. ~K From ldo at geek-central.gen.new_zealand Sun Aug 15 07:00:15 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 23:00:15 +1200 Subject: Python "why" questions References: Message-ID: In message , Thomas Jollans wrote: > "Where it all started" is that 0-based indexing gives languages like C a > very nice property: a[i] and *(a+i) are equivalent in C. From a language > design viewpoint, I think that's quite a strong argument. It would be if pointers and arrays were the same thing in C. Only they?re not, quite. Which somewhat defeats the point of trying to make them look the same, don?t you think? From ldo at geek-central.gen.new_zealand Sun Aug 15 07:01:23 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 15 Aug 2010 23:01:23 +1200 Subject: Python "why" questions References: Message-ID: In message , Ian Kelly wrote: > The ability to change the minimum index is evil. Pascal allowed you to do that. And nobody ever characterized Pascal as ?evil?. Not for that reason, anyway... From peter at www.pjb.com.au Sun Aug 15 07:08:08 2010 From: peter at www.pjb.com.au (Peter Billam) Date: 15 Aug 2010 11:08:08 GMT Subject: writing \feff at the begining of a file References: <4C651438.50203@sequans.com> <4c65f752$0$28668$c3e8da3@news.astraweb.com> <4C667FCD.6040802@v.loewis.de> Message-ID: On 2010-08-14, Martin v. Loewis wrote: >> Is there a standard way to autodetect the encoding of a text file? > Use the chardet module: > http://chardet.feedparser.org/ Very timely: the python-chardet package just seems to have appeared on debian squeeze :-) After my latest "aptitude safe-upgrade": box8 (debian) ~> aptitude show python-chardet Package: python-chardet State: installed Automatically installed: yes Version: 2.0.1-1 Priority: optional Section: python Maintainer: Piotr O?arowski Uncompressed Size: 721k Depends: python, python-support (>= 0.90.0) Description: universal character encoding detector Chardet takes a sequence of bytes in an unknown character encoding, and attempts to determine the encoding. Supported encodings: * ASCII, UTF-8, UTF-16 (2 variants), UTF-32 (4 variants) * Big5, GB2312, EUC-TW, HZ-GB-2312, ISO-2022-CN (Traditional and Simplified Chinese) * EUC-JP, SHIFT_JIS, ISO-2022-JP (Japanese) * EUC-KR, ISO-2022-KR (Korean) * KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251 (Cyrillic) * ISO-8859-2, windows-1250 (Hungarian) * ISO-8859-5, windows-1251 (Bulgarian) * windows-1252 (English) * ISO-8859-7, windows-1253 (Greek) * ISO-8859-8, windows-1255 (Visual and Logical Hebrew) * TIS-620 (Thai) This library is a port of the auto-detection code in Mozilla. Homepage: http://chardet.feedparser.org/ Regards, Peter -- Peter Billam www.pjb.com.au www.pjb.com.au/comp/contact.html From downaold at gmail.com Sun Aug 15 07:55:10 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 15 Aug 2010 13:55:10 +0200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: > It would be if pointers and arrays were the same thing in C. Only > they?re > not, quite. Which somewhat defeats the point of trying to make them > look the > same, don?t you think? How are they not the same? The code snippet (in C/C++) below is valid, so arrays are just pointers. The only difference is that the notation x[4] reserves space for 4 (consecutive) ints, and the notation *y doesn't. int x[4]; int *y = x; Moreover, the following is valid (though unsafe) C/C++: int *x; int y = x[4]; Cheers, Roald From downaold at gmail.com Sun Aug 15 08:14:48 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 15 Aug 2010 14:14:48 +0200 Subject: Python "why" questions In-Reply-To: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: On Aug 7, 2010, at 9:14 PM, John Nagle wrote: > FORTRAN, MATLAB, and Octave all use 1-based subscripts. > > The languages which have real multidimensional arrays, rather > than arrays of arrays, tend to use 1-based subscripts. That > reflects standard practice in mathematics. True, but that something is "standard mathematical notation" doesn't mean it's preferable. For example, I have never seen keyword arguments in mathematical notation, and it's definitely not standard practice, but nobody would drop them in favor of standard mathematical notation. In fact, I think, regularly mathematical notation can be improved by standard programming notation. Moreover, I don't see what's so nice about 'real' multidimensional arrays; the way to construct multidimensional arrays from one- dimensional ones is more orthogonal. And you never *have* to think about them as being one-dimensional, it's just a bonus you can (sometimes) profit from. From debatem1 at gmail.com Sun Aug 15 08:16:45 2010 From: debatem1 at gmail.com (geremy condra) Date: Sun, 15 Aug 2010 05:16:45 -0700 Subject: Python "why" questions In-Reply-To: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> References: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> Message-ID: On Sun, Aug 15, 2010 at 4:55 AM, Roald de Vries wrote: > On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: >> >> It would be if pointers and arrays were the same thing in C. Only they?re >> not, quite. Which somewhat defeats the point of trying to make them look >> the >> same, don?t you think? > > How are they not the same? > > The code snippet (in C/C++) below is valid, so arrays are just pointers. The > only difference is that the notation x[4] reserves space for 4 (consecutive) > ints, and the notation *y doesn't. > > int x[4]; > int *y = x; > > Moreover, the following is valid (though unsafe) C/C++: > > int *x; > int y = x[4]; Just to demonstrate that they are different, the following code compiles cleanly: int main() { int *pointer; pointer++; return 0; } While this does not: int main() { int array[0]; array++; return 0; } Geremy Condra From downaold at gmail.com Sun Aug 15 08:20:53 2010 From: downaold at gmail.com (Roald de Vries) Date: Sun, 15 Aug 2010 14:20:53 +0200 Subject: Python "why" questions In-Reply-To: References: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> Message-ID: <04B8092A-81B8-4139-9FE7-7366AC9400AC@gmail.com> On Aug 15, 2010, at 2:16 PM, geremy condra wrote: > On Sun, Aug 15, 2010 at 4:55 AM, Roald de Vries > wrote: >> On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: >>> >>> It would be if pointers and arrays were the same thing in C. Only >>> they?re >>> not, quite. Which somewhat defeats the point of trying to make >>> them look >>> the >>> same, don?t you think? >> >> How are they not the same? >> >> The code snippet (in C/C++) below is valid, so arrays are just >> pointers. The >> only difference is that the notation x[4] reserves space for 4 >> (consecutive) >> ints, and the notation *y doesn't. >> >> int x[4]; >> int *y = x; >> >> Moreover, the following is valid (though unsafe) C/C++: >> >> int *x; >> int y = x[4]; > > Just to demonstrate that they are different, the following code > compiles cleanly: > > int main() { > int *pointer; > pointer++; > return 0; > } > > While this does not: > > int main() { > int array[0]; > array++; > return 0; > } Interesting! Thanks for the lesson ;-). Cheers, Roald From davea at ieee.org Sun Aug 15 08:30:54 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 15 Aug 2010 08:30:54 -0400 Subject: Pop return from stack? In-Reply-To: <4c673375$0$11100$c3e8da3@news.astraweb.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c673375$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4C67DDFE.7090703@ieee.org> Steven D'Aprano wrote: > On Sat, 14 Aug 2010 16:05:05 -0700, bvdp wrote: > > >> >> >> def error(s): >> print "Error", s >> sys.exit(1) >> >> > This general technique is called "monkey patching". > > > > You can either manually exit from your own error handler: > > def myerror(s): > print "new error message" > sys.exit(2) > > > or call the original error handler: > > > def myerror(s): > print "new error message" > foo._error(s) > > > That second technique requires some preparation before hand. In module > foo, after defining the error() function, you then need to create a > second, private, name to it: > > _error = error > > > > Small point. The OP's request was that he not modify the called module, which is why he was considering monkey-patching. And you can readily avoid adding that line to the file. Just do something like this: import foo _olderror_func = foo.error def myerror(s) print "new error message" _olderror_func(s) DaveA From davea at ieee.org Sun Aug 15 08:39:26 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 15 Aug 2010 08:39:26 -0400 Subject: shelf-like list? In-Reply-To: References: Message-ID: <4C67DFFE.2030903@ieee.org> kj wrote: > >> self.save() >> > > Even though it is saved periodically to disk, it looks like the > whole list remains in memory all the time? (If so, it's not what > I'm looking for; the whole point of saving stuff to disk is to keep > the list's memory footprint low.) > > ~K > > It sounds like we all made the wrong assumption about your requirements. It's not persistence you want, but low memory footprint ? Do you or don't you also want the data to survive multiple runs of the program? If you want the data to be in a persistent disk file, you probably should use a database. And if you don't, then you could either increase the size of your swapfile, or use a more complex scheme to do a memory mapped file while the program is running, and delete it on exit. The swapfile is likely to be execute more quickly than anything else you could cook up in pure python. DaveA From chrischia82 at gmail.com Sun Aug 15 08:47:04 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Sun, 15 Aug 2010 05:47:04 -0700 (PDT) Subject: Simple Problem but tough for me if i want it in linear time Message-ID: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> dataList = [a, b, c, ...] where a, b, c are objects of a Class X. In Class X, it contains self.name and self.number If i wish to test whether a number (let's say 100) appears in one of the object, and return that object, is that only fast way of solving this problem without iterating through every object to see the number value? dataList.__contains__ can only check my object instance name... anyone can solve this in linear complexity? From davea at ieee.org Sun Aug 15 08:50:48 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 15 Aug 2010 08:50:48 -0400 Subject: Python "why" questions In-Reply-To: <04B8092A-81B8-4139-9FE7-7366AC9400AC@gmail.com> References: <6CCB4766-90E5-45FE-A0BC-A9455DDBB259@gmail.com> <04B8092A-81B8-4139-9FE7-7366AC9400AC@gmail.com> Message-ID: <4C67E2A8.5010505@ieee.org> Roald de Vries wrote: >
On Aug > 15, 2010, at 2:16 PM, geremy condra wrote: >> On Sun, Aug 15, 2010 at 4:55 AM, Roald de Vries >> wrote: >>> On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: >>>> >>>> It would be if pointers and arrays were the same thing in C. Only >>>> they?re >>>> not, quite. Which somewhat defeats the point of trying to make them >>>> look >>>> the >>>> same, don?t you think? >>> >>> How are they not the same? >>> >>> The code snippet (in C/C++) below is valid, so arrays are just >>> pointers. The >>> only difference is that the notation x[4] reserves space for 4 >>> (consecutive) >>> ints, and the notation *y doesn't. >>> >>> int x[4]; >>> int *y =x; >>> >>> Moreover, the following is valid (though unsafe) C/C++: >>> >>> int *x; >>> int y = x[4]; >> >> Just to demonstrate that they are different, the following code >> compiles cleanly: >> >> int main() { >> int *pointer; >> pointer++; >> return 0; >> } >> >> While this does not: >> >> int main() { >> int array[0]; >> array++; >> return 0; >> } > > Interesting! Thanks for the lesson ;-). > > Cheers, Roald > > That particular example doesn't really matter; it just shows that array is a *const* pointer. One that does matter, sometimes drastically, is sizeof(array) vs. sizeof(pointer). One interesting other effect of the compiler (nearly always) treating pointers and arrays the same is expressions like: int hexdigit = ...something... char ch = "0123456789abcdef"[hexdigit]; char ch2 = hexdigit["0123456789abcdef"; both are valid assignments, and equivalent to char ch3 = hexdigit + &("0123456789abcdef"); From __peter__ at web.de Sun Aug 15 09:14:33 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Aug 2010 15:14:33 +0200 Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: ChrisChia wrote: > dataList = [a, b, c, ...] > where a, b, c are objects of a Class X. > In Class X, it contains self.name and self.number > > If i wish to test whether a number (let's say 100) appears in one of > the object, and return that object, > is that only fast way of solving this problem without iterating > through every object to see the number value? > > dataList.__contains__ can only check my object instance name... > anyone can solve this in linear complexity? Well, iteration as in next(item for item in dataList if item.number == 100) is O(n) and list.__contains__() has no magic way to do better. If you need O(1) lookup you can use a dict or collections.defaultdict that maps item.number to a list (or set) of X instances: lookup = {} for item in dataList: lookup.setdefault(item.number, []).append(item) print lookup[100] Peter From rami.chowdhury at gmail.com Sun Aug 15 09:14:34 2010 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sun, 15 Aug 2010 19:14:34 +0600 Subject: OpenCV_Problem In-Reply-To: References: Message-ID: <201008151914.34334.rami.chowdhury@gmail.com> Hi Arihant, Please make sure your response goes out to the list -- I suggest using 'reply all' rather than 'reply'. Also, please make sure the previous conversation is included in your email -- otherwise people might not understand your problem and be able to help. On Sunday 15 August 2010 12:35:27 arihant nahata wrote: > This is what i have, > > >>> print sys.path > > ['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', > 'C:\\Python27\ > \lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', > 'C:\\Python27 > ', 'C:\\Python27\\lib\\site-packages', > 'C:\\OpenCV2.0\\Python2.6\\Lib\\site-pack > ages'] Can you let us know if a file called '_cv.dll' is in 'C: \OpenCV2.0\Python2.6\Lib\site-packages'? ---- Rami Chowdhury "Any sufficiently advanced incompetence is indistinguishable from malice." -- Grey's Law +1-408-597-7068 / +44-7875-841-046 / +88-01819-245544 From python at mrabarnett.plus.com Sun Aug 15 09:29:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 15 Aug 2010 14:29:15 +0100 Subject: Simple Problem but tough for me if i want it in linear time In-Reply-To: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: <4C67EBAB.5090105@mrabarnett.plus.com> ChrisChia wrote: > dataList = [a, b, c, ...] > where a, b, c are objects of a Class X. > In Class X, it contains self.name and self.number > > If i wish to test whether a number (let's say 100) appears in one of > the object, and return that object, > is that only fast way of solving this problem without iterating > through every object to see the number value? > > dataList.__contains__ can only check my object instance name... > anyone can solve this in linear complexity? Put them into a dict where the key is the number and the value is a list of the objects with that number. From chrischia82 at gmail.com Sun Aug 15 10:22:25 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Sun, 15 Aug 2010 07:22:25 -0700 (PDT) Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem Message-ID: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Hi all, i am trying to do a GUI with Tkinter package, but i am stuck no matter what... The problem right now is that my GUI has a label= 'A' (where 'A' is the text on display) i wish to run a program with 2 threads... one for my GUI and the other for the terminal where the terminal will keep listening to the user input (let's say if he enters 'B'), the GUI will update it's label to 'B'. It's easy to let the terminal wait after the user has entered the input. But the problem is that when the GUI loads up... the root.mainloop() doesn't seem to release the control, hence my thread cannot work on GUI. Is there a way to solve this problem? 2 threads; 1 more GUI and 1 more terminal. From f2h2d2 at gmail.com Sun Aug 15 10:22:33 2010 From: f2h2d2 at gmail.com (nais-saudi) Date: Sun, 15 Aug 2010 07:22:33 -0700 (PDT) Subject: Mecca direct transfer 24 hours Message-ID: <7da9d2fd-92c8-42af-a82f-18a4ef67c257@s9g2000yqd.googlegroups.com> Mecca direct transfer 24 hours You will not believe your eyes what you feel that a direct http://ar.justin.tv/bidayatv#/w/312906784/30 Fairy scenes The sections that cried and asked YouTube viewers translation: http://www.youtube.com/v/IFq9cjtrWlQ&rel=0 http://www.youtube.com/v/y2BN73Q-AJw&rel=0 http://www.youtube.com/v/nNFMvznJ-4c&rel=0 http://www.youtube.com/v/qVB9HNQ-w2I&rel=0 http://www.youtube.com/v/RWfR9z91j8I&rel=0 http://www.todayislam.com/yusuf.htm http://islamtomorrow.com From kentilton at gmail.com Sun Aug 15 10:38:17 2010 From: kentilton at gmail.com (Kenneth Tilton) Date: Sun, 15 Aug 2010 10:38:17 -0400 Subject: math symbols in unicode (grouped by purpose) In-Reply-To: References: Message-ID: <4c67fbe3$0$7109$607ed4bc@cv.net> On 8/13/2010 5:18 PM, Xah Lee wrote: > some collection of math symbols in unicode. > > ? Math Symbols in Unicode > http://xahlee.org/comp/unicode_math_operators.html I am surprised you do not include the numeric character codes. kt > > ? Arrows in Unicode > http://xahlee.org/comp/unicode_arrows.html > > ? Matching Brackets in Unicode > http://xahlee.org/comp/unicode_matching_brackets.html > > these are grouped by the symbol's purpose as much as possible. > > i made them because i can't find unicode symbols grouped by purpose > elsewhere. > > The unicode ?plane -> block? structure does not group symbols well, > because the chars are added throughout the decades. Some symbols get > added in one block, but later on related symbols get added elsewhere. > For example, binary relational symbols are scattered in different > unicode blocks. Same for binary operators, or all symbols used for set > theory, etc. Sometimes a symbol has multiple uses in different math > fields, so which block it gets added into unicode is not well defined. > > hope it's useful to some one. > > Xah > ? http://xahlee.org/ > > ? -- http://www.stuckonalgebra.com "The best Algebra tutorial program I have seen... in a class by itself." Macworld From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 10:47:12 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 14:47:12 GMT Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: <4c67fdef$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 05:47:04 -0700, ChrisChia wrote: > dataList = [a, b, c, ...] > where a, b, c are objects of a Class X. In Class X, it contains > self.name and self.number > > If i wish to test whether a number (let's say 100) appears in one of the > object, and return that object, > is that only fast way of solving this problem without iterating through > every object to see the number value? > > dataList.__contains__ can only check my object instance name... > anyone can solve this in linear complexity? If all you want is *linear* time, then simply iterating over the items will do the job: for item in dataList: if item.number == 100: do_something_with(item) break If you want *less* than linear time, then keep the list sorted and do a binary search, which gives you O(log N) time. Don't sort the list each time, because that's O(N*log N). Or use a dict, which gives you O(1) time. -- Steven From emile at fenx.com Sun Aug 15 11:13:17 2010 From: emile at fenx.com (Emile van Sebille) Date: Sun, 15 Aug 2010 08:13:17 -0700 Subject: shelf-like list? In-Reply-To: References: Message-ID: On 8/15/2010 3:58 AM kj said... > In "Martin v. Loewis" writes: > >>> Does anyone know of such a module? > >> ZODB supports persistent lists. > > Thanks; I'll check it out. > I wouldn't expect a low memory footprint however. :) Emile From raoulbia at gmail.com Sun Aug 15 11:38:03 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 15 Aug 2010 08:38:03 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: Hi John, Thanks for your submission! I've improved a lot and everone's help so far has been thrilling amd is very good for my self-study motivation :) ok so i think i'm clear on how to approach this problem and on how to write basic but clean Python code to solve it. The next step is to generalise this code so that other pack quantities could be tested: "generalize this idea to work with any size packages of McNuggets, not just 6, 9, and 20. For simplicity, however, we will assume that nuggets are provided in three different sized packages" I thought this should be relatively straightforward and it does work if i test it for the values 6,9&20 but if i test for 2,3,4 i would expect the result to be 1 but it returns nothing def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/6+1): for b in range (0,n_nuggets/9+1): for c in range (0,n_nuggets/20+1): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(x,y,z): cbc=0 #cbc=can_buy counter packages =[x,y,z] for n_nuggets in range(50): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print "Largest number of McNuggets that cannot be bought in exact quantity: %d" %(solution) diophantine_nuggets(2,3,4) From raoulbia at gmail.com Sun Aug 15 11:44:15 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 15 Aug 2010 08:44:15 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: Hi John, Thanks for your submission! I've improved a lot and everone's help so far has been thrilling and is very good for my self-study motivation :) ok so i think i'm clear on how to approach this problem and on how to write basic but clean Python code to solve it. The next step is to generalise this code so that other pack quantities could be tested: "generalize this idea to work with any size packages of McNuggets, not just 6, 9, and 20. For simplicity, however, we will assume that nuggets are provided in three different sized packages" I thought this should be relatively straightforward and it does work if i test it for the values 6,9&20 but if i test for 2,3,4 i would expect the result to be 1 but it returns nothing def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/6+1): for b in range (0,n_nuggets/9+1): for c in range (0,n_nuggets/20+1): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(x,y,z): cbc=0 #cbc=can_buy counter packages =[x,y,z] for n_nuggets in range(50): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print "Largest number of McNuggets that cannot be bought in exact quantity: %d" %(solution) diophantine_nuggets(2,3,4) From emile at fenx.com Sun Aug 15 11:58:56 2010 From: emile at fenx.com (Emile van Sebille) Date: Sun, 15 Aug 2010 08:58:56 -0700 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: On 8/15/2010 8:44 AM Baba said... > Hi John, > > Thanks for your submission! I've improved a lot and everone's help so > far has been thrilling and is very good for my self-study > motivation :) > > ok so i think i'm clear on how to approach this problem and on how to > write basic but clean Python code to solve it. > > The next step is to generalise this code so that other pack quantities > could be tested: "generalize this idea to work with any size packages > of McNuggets, not just 6, 9, and 20. For simplicity, however, we will > assume that nuggets are provided in three different sized packages" > > I thought this should be relatively straightforward and it does work > if i test it for the values 6,9&20 but if i test for 2,3,4 i would > expect the result to be 1 but it returns nothing > Because can_buy still uses denominators 6,9&20 - try packages[0],[1]&[2] Emile > def can_buy(n_nuggets,packages): > for a in range (0,n_nuggets/6+1): > for b in range (0,n_nuggets/9+1): > for c in range (0,n_nuggets/20+1): > #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) > if packages[0]*a+packages[1]*b > +packages[2]*c==n_nuggets: > return True > return False > > def diophantine_nuggets(x,y,z): > cbc=0 #cbc=can_buy counter > packages =[x,y,z] > for n_nuggets in range(50): > result=can_buy(n_nuggets,packages) > if result: > cbc+=1 > else: > cbc=0 > if cbc==6: > solution=n_nuggets-6 > print "Largest number of McNuggets that cannot be bought in > exact quantity: %d" %(solution) > > diophantine_nuggets(2,3,4) From ian.g.kelly at gmail.com Sun Aug 15 12:04:27 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Aug 2010 10:04:27 -0600 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: On Sun, Aug 15, 2010 at 9:58 AM, Emile van Sebille wrote: > On 8/15/2010 8:44 AM Baba said... >> >> Hi John, >> >> Thanks for your submission! I've improved a lot and everone's help so >> far has been thrilling and is very good for my self-study >> motivation :) >> >> ok so i think i'm clear on how to approach this problem and on how to >> write basic but clean Python code to solve it. >> >> The next step is to generalise this code so that other pack quantities >> could be tested: "generalize this idea to work with any size packages >> of McNuggets, not just 6, 9, and 20. For simplicity, however, we will >> assume that nuggets are provided in three different sized packages" >> >> I thought this should be relatively straightforward and it does work >> if i test it for the values 6,9&20 but if i test for 2,3,4 i would >> expect the result to be 1 but it returns nothing >> > > Because can_buy still uses denominators 6,9&20 - try packages[0],[1]&[2] Also, note that testing for 6 buyable quantities in a row is correct for 6, 9, 20 but is not necessarily correct for other denominations. You should think about how many you need to find in sequence for any given input of x, y, and z. Cheers, Ian From nagle at animats.com Sun Aug 15 12:10:09 2010 From: nagle at animats.com (John Nagle) Date: Sun, 15 Aug 2010 09:10:09 -0700 Subject: Python "why" questions In-Reply-To: References: Message-ID: <4c681161$0$1624$742ec2ed@news.sonic.net> On 8/15/2010 4:00 AM, Lawrence D'Oliveiro wrote: > In message, Thomas > Jollans wrote: > >> "Where it all started" is that 0-based indexing gives languages like C a >> very nice property: a[i] and *(a+i) are equivalent in C. From a language >> design viewpoint, I think that's quite a strong argument. > > It would be if pointers and arrays were the same thing in C. Only they?re > not, quite. Which somewhat defeats the point of trying to make them look the > same, don?t you think? In retrospect, C's "pointer=array" concept was a terrible mistake. It's a historical artifact; early C (pre K&R, as shipped with "research UNIX" V6 and PWB) had no notion of typing; all "struct" pointers were interchangeable and elements of a "struct" were just offsets of a pointer. That was fixed, but arrays weren't. The fundamental problem with "array=pointer" is that it results in lying to the language. Consider the declaration of "read": int read(int fd, char* buf, size_t n); This is a a lie. "buf" is not a pointer to a character. It's an array. And, the bad part, the compiler doesn't know how big it is. The syntax should have been something like int read(int fd, &char[n] buf, size_t n); This says the type of the argument is an array of char of length n, and it's being passed by reference. "read" then knows how big "buf" is. This design error in C is the cause of most buffer overflow crashes and security holes. John Nagle From jjposner at optimum.net Sun Aug 15 12:24:42 2010 From: jjposner at optimum.net (John Posner) Date: Sun, 15 Aug 2010 12:24:42 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> Message-ID: <4C6814CA.6070503@optimum.net> On 8/15/2010 11:38 AM, Baba wrote: In addition to the points that Emile and Ian made ... > > def diophantine_nuggets(x,y,z): > cbc=0 #cbc=can_buy counter > packages =[x,y,z] You can take advantage of a nifty "syntax convenience feature" here. Instead of loading all of the function's arguments into a list "manually", you can make it happen automatically: def diophantine_nuggets(x,y,z): cbc = 0 packages =[x,y,z] ... becomes ... def diophantine_nuggets(*packages): cbc = 0 The asterisk (*) in the function's signature does the trick. > for n_nuggets in range(50): Careful -- in the general case, you might need to search beyond 50 for your answer! Best, John From chare at labr.net Sun Aug 15 12:39:37 2010 From: chare at labr.net (Chris Hare) Date: Sun, 15 Aug 2010 11:39:37 -0500 Subject: adding a "windows" item to a menu bar dynamically Message-ID: <0F5747FA-FB21-49A3-82FE-8176EA172791@labr.net> I want to add a "Windows" menu item to my menu bar, so when another Toplevel window is opened, I can add that to the menu bar in case the user accidentally clicks on a different window and moves the Toplevel under something else. Then when the window is closed, remove the window from the menu Any ideas on how to do this? Thanks From mback1 at live.se Sun Aug 15 12:56:31 2010 From: mback1 at live.se (Mikael B) Date: Sun, 15 Aug 2010 18:56:31 +0200 Subject: NZEC what is it? Message-ID: Hi I use, among other things, a site, http://www.codechef.com to learn python. I don't know what platform they use. I use linux. When I submit this little piece of code to them: import sys import math #main s=sys.stdin.read() int_list=s.split() for a in int_list[1:]: print math.factorial(int(a)) they generate a runtime error :NZEC but I don't (python 2.6) What is NZEC and what could cause it in these few lines of code? Regards Mikael -------------- next part -------------- An HTML attachment was scrubbed... URL: From raoulbia at gmail.com Sun Aug 15 13:11:48 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 15 Aug 2010 10:11:48 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> Message-ID: Hi All, @Emile tnx for spotting the mistake. Should have seen it myself. @John & Ian i had a look around but couldn't find a general version of below theorem If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in 6, 9 and 20 packs. I must admit that i'm not keen on spending too much time on purely mathematical questions. It seems that this has to do with Frobenius Number? re range the exercise seems to suggest to limit it to 200 so feel free to enlighten me on this last part. In the meantime the almost complete code is: def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/packages[0]+1): for b in range (0,n_nuggets/packages[1]+1): for c in range (0,n_nuggets/packages[2]+1): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(*packages): cbc=0 #cbc=can_buy counter #packages =[x,y,z] for n_nuggets in range(200): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print "Largest number of McNuggets that cannot be bought in exact quantity: %d" %(solution) break diophantine_nuggets(2,3,4) From python at mrabarnett.plus.com Sun Aug 15 13:22:54 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 15 Aug 2010 18:22:54 +0100 Subject: NZEC what is it? In-Reply-To: References: Message-ID: <4C68226E.7020809@mrabarnett.plus.com> Mikael B wrote: > Hi > I use, among other things, a site, http://www.codechef.com to learn > python. > I don't know what platform they use. I use linux. > > When I submit this little piece of code to them: > > import sys > import math > > #main > > s=sys.stdin.read() > > int_list=s.split() > > for a in int_list[1:]: > print math.factorial(int(a)) > > > they generate a runtime error :NZEC but I don't (python 2.6) > > What is NZEC and what could cause it in these few lines of code? > I googled for it and found that it means "non-zero exit code", perhaps due to an exception. Not a helpful message! :-) What happens if you deliberately raise an exception, eg: raise ValueError From xahlee at gmail.com Sun Aug 15 13:57:32 2010 From: xahlee at gmail.com (Xah Lee) Date: Sun, 15 Aug 2010 10:57:32 -0700 (PDT) Subject: math symbols in unicode (grouped by purpose) References: <4c67fbe3$0$7109$607ed4bc@cv.net> Message-ID: hi kenny! Xah Lee wrote: > some collection of math symbols in unicode. > ? Math Symbols in Unicode > ? ?http://xahlee.org/comp/unicode_math_operators.html Kenneth Tilton wrote: > I am surprised you do not include the numeric character codes. i thought about it, but the page would get unwieldy. To make it work well one might have to implement javascript so that mouse hover can popup a balloon with info about the char... my javascript isn't so great... maybe sometimes down the road. but if you want a unicode char browser: ? Emacs xub-mode; A Unicode Browser http://xahlee.org/emacs/unicode-browser.html i feel that's the best unicode browser/palette/codemap kinda app there is. (in my humble opinion, more useful than Apple's Character palette, or Windows charmap.) if you are not a emacs user, i'd even say download emacs and use it just for it just for browser unicode chars. (you'll need emacs23.1 at least) Xah From tjreedy at udel.edu Sun Aug 15 14:17:56 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Aug 2010 14:17:56 -0400 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: On 8/15/2010 10:22 AM, ChrisChia wrote: > Hi all, > i am trying to do a GUI with Tkinter package, but i am stuck no matter > what... > The problem right now is that my GUI has a label= 'A' (where 'A' is > the text on display) > > i wish to run a program with 2 threads... one for my GUI and the other > for the terminal where the terminal will keep listening to the user > input (let's say if he enters 'B'), the GUI will update it's label to > 'B'. Makes no sense to me. GUI = graphics user interface. Interface = input from and output to the user. Additional threads for for other activities that may block or be compute intensive, not a separate text user interface. > It's easy to let the terminal wait after the user has entered the > input. > But the problem is that when the GUI loads up... the > > root.mainloop() > > doesn't seem to release the control, That seems to be the point of a GUI -- Terry Jan Reedy From zdoor at xs4all.nl Sun Aug 15 14:24:07 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Sun, 15 Aug 2010 20:24:07 +0200 Subject: Opposite of split Message-ID: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> Looking for a method that does the opposite of 'split', i.e. elements in a list are automatically concatenated with a user selectable spacer in between e.g. '\t'. This is to prepare lines to be written to a sequential file by 'write'. All hints welcome. Regards, Alex van der Spek From the_mineo at web.de Sun Aug 15 14:27:35 2010 From: the_mineo at web.de (Wieland Hoffmann) Date: Sun, 15 Aug 2010 20:27:35 +0200 Subject: Opposite of split In-Reply-To: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> Message-ID: On 15.08.2010 20:24, Alex van der Spek wrote: > Looking for a method that does the opposite of 'split', i.e. elements in > a list are automatically concatenated with a user selectable spacer in > between e.g. '\t'. >>> " ".join(["i","am","a","list"]) 'i am a list' Wieland From gherron at islandtraining.com Sun Aug 15 14:35:15 2010 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 15 Aug 2010 11:35:15 -0700 Subject: Opposite of split In-Reply-To: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> Message-ID: <4C683363.3080305@islandtraining.com> On 08/15/2010 11:24 AM, Alex van der Spek wrote: > Looking for a method that does the opposite of 'split', i.e. elements > in a list are automatically concatenated with a user selectable spacer > in between e.g. '\t'. This is to prepare lines to be written to a > sequential file by 'write'. > > All hints welcome. > > Regards, > Alex van der Spek Strings have a join method for this: '\t'.join(someList) Gary Herron From mback1 at live.se Sun Aug 15 14:46:29 2010 From: mback1 at live.se (Mikael B) Date: Sun, 15 Aug 2010 20:46:29 +0200 Subject: NZEC what is it? In-Reply-To: References: , <4C68226E.7020809@mrabarnett.plus.com>, Message-ID: From: mback1 at live.se To: python at mrabarnett.plus.com Subject: RE: NZEC what is it? Date: Sun, 15 Aug 2010 19:58:44 +0200 > Date: Sun, 15 Aug 2010 18:22:54 +0100 > From: python at mrabarnett.plus.com > To: python-list at python.org > Subject: Re: NZEC what is it? > > Mikael B wrote: > > Hi > > I use, among other things, a site, http://www.codechef.com to learn > > python. > > I don't know what platform they use. I use linux. > > > > When I submit this little piece of code to them: > > > > import sys > > import math > > > > #main > > > > s=sys.stdin.read() > > > > int_list=s.split() > > > > for a in int_list[1:]: > > print math.factorial(int(a)) > > > > > > they generate a runtime error :NZEC but I don't (python 2.6) > > > > What is NZEC and what could cause it in these few lines of code? > > > I googled for it and found that it means "non-zero exit code", perhaps > due to an exception. Not a helpful message! :-) > > What happens if you deliberately raise an exception, eg: > > raise ValueError If I add to the end I just get 'ValueError' I tried to add '1/0' but got 'ZeroDivisionError' Maybe I should try to add 'sys.exit(0)' and see what happens if I submit again... > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacek2v at gmail.com Sun Aug 15 14:50:24 2010 From: jacek2v at gmail.com (jacek2v) Date: Sun, 15 Aug 2010 11:50:24 -0700 (PDT) Subject: Simple Python Sandbox References: Message-ID: <0c395f99-b66e-4099-a65d-734d10e6f072@f42g2000yqn.googlegroups.com> On Aug 14, 1:37?am, Stephen Hansen wrote: > Can you think of a way out of such a sandbox? A way to access disallowed > stuff, not a way to DOS. Hi, I have strange idea :): use Google Apps. You'll need prepare some interfaces for your apps (for example via WebServices) Maybe it is wrong way, maybe not :) Regards From skip at pobox.com Sun Aug 15 14:50:53 2010 From: skip at pobox.com (skip at pobox.com) Date: Sun, 15 Aug 2010 13:50:53 -0500 Subject: Programmers (esp. Windows) needed for SpamBayes Message-ID: <19560.14093.442876.487409@montanaro.dyndns.org> If you have some time to devote to a popular open source Python project, we can use some development help with SpamBayes, particularly on Windows and with Outlook 2010: http://wiki.python.org/moin/VolunteerOpportunities#SpamBayesProject Thanks, -- Skip Montanaro - skip at pobox.com - http://www.smontanaro.net/ From forever.arihant at gmail.com Sun Aug 15 14:54:50 2010 From: forever.arihant at gmail.com (arihant nahata) Date: Mon, 16 Aug 2010 00:24:50 +0530 Subject: OpenCV_Problem In-Reply-To: <201008151914.34334.rami.chowdhury@gmail.com> References: <201008151914.34334.rami.chowdhury@gmail.com> Message-ID: Hi, There is no file named _cv.dll file in the directory that you mentioned -------------- next part -------------- An HTML attachment was scrubbed... URL: From howe.steven at gmail.com Sun Aug 15 15:10:10 2010 From: howe.steven at gmail.com (Steven Howe) Date: Sun, 15 Aug 2010 12:10:10 -0700 Subject: Opposite of split In-Reply-To: <4C683363.3080305@islandtraining.com> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> Message-ID: <4C683B92.9060803@gmail.com> On 08/15/2010 11:35 AM, Gary Herron wrote: > On 08/15/2010 11:24 AM, Alex van der Spek wrote: >> Looking for a method that does the opposite of 'split', i.e. elements >> in a list are automatically concatenated with a user selectable >> spacer in between e.g. '\t'. This is to prepare lines to be written >> to a sequential file by 'write'. >> >> All hints welcome. >> >> Regards, >> Alex van der Spek > > Strings have a join method for this: > '\t'.join(someList) > > Gary Herron or maybe: ----------------------------------------- res = "" for item in myList: res = "%s\t%s" % ( res, item ) myList = ["abc","def","hjk"] res = "" for item in myList: res = "%s\t%s" % ( res, item ) res '\tabc\tdef\thjk' print res abc def hjk Note the leading tab. ----------------------------------------- So: >>> res.strip() 'abc\tdef\thjk' >>> print res.strip() abc def hjk simple enough. Strange you had to ask. sph From mwilson at the-wire.com Sun Aug 15 15:15:34 2010 From: mwilson at the-wire.com (Mel) Date: Sun, 15 Aug 2010 15:15:34 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> Message-ID: Baba wrote: > Hi All, > > @Emile tnx for spotting the mistake. Should have seen it myself. > > @John & Ian i had a look around but couldn't find a general version of > below theorem > If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some x, > then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in 6, 9 and 20 packs. Not that hard. When you can buy nuggets `n` to a pack (6 for example) then if you have schemes for buying k,k+1,k+2,...,k+n-1 nuggets, you can create a scheme for buying any number of nuggets >= k . At worst just buy packs of `n` until the number left to buy is between k and k+n-1 inclusive, then follow the scheme for that number. Mel. From forever.arihant at gmail.com Sun Aug 15 15:25:38 2010 From: forever.arihant at gmail.com (arihant nahata) Date: Mon, 16 Aug 2010 00:55:38 +0530 Subject: OpenCV_Problem In-Reply-To: <201008151914.34334.rami.chowdhury@gmail.com> References: <201008151914.34334.rami.chowdhury@gmail.com> Message-ID: Hi, There is no file named _cv.dll file in the directory that you mentioned -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Sun Aug 15 15:52:06 2010 From: nagle at animats.com (John Nagle) Date: Sun, 15 Aug 2010 12:52:06 -0700 Subject: Pop return from stack? In-Reply-To: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> Message-ID: <4c684566$0$1619$742ec2ed@news.sonic.net> On 8/14/2010 4:05 PM, bvdp wrote: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > print "Error", s > sys.exit(1) > > def func(s): > ... do some processing > ... call error() if bad .. go to system exit. > ... more processing Fix "func". That's terrible Python. No standard Python library module calls system exit to handle an error. So that must be in your code. Standard procedure for errors is to raise an exception. John Nagle From jerradgenson at gmail.com Sun Aug 15 15:59:08 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 12:59:08 -0700 (PDT) Subject: Tkinter/threading issue Message-ID: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Hello, I'm learning Tkinter, and I have an issue that I'd appreciate help with. I have a program that initializes a GUI (I'll call this the "GUI process"), then spawns another process that listens on a network via the TCP/IP protocol for incoming strings (I'll call this the "server process"). Everything works well up to this point. What I want to happen next is for the server process to update a label in the GUI process when it receives a message from the network. First I tried passing a control variable for the label's text into the server process, but when I updated the control variable, nothing happened(no error messages, no feedback of any kind). I tried piping the message from the server process into the GUI process using os.write() and os.read() - and this works, but not the way I need it to. I need the label to be updated automatically, without any intervention from the user (at the moment, it only works when the user clicks an "Update" button). I tried having the GUI process check the pipe for messages automatically, but when I do this it hangs when there's nothing in the pipe. I've tried other avenues as well, but probably nothing worth mentioning. If you have any suggestions, I would be very grateful. From jerradgenson at gmail.com Sun Aug 15 16:01:13 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 13:01:13 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Message-ID: <6853768f-1c0a-43b7-ad20-04010e47c4cb@m1g2000yqo.googlegroups.com> I should also mention that I'm running Ubuntu 10.04 and Python 2.6.5. From thomas at jollybox.de Sun Aug 15 16:28:44 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 15 Aug 2010 22:28:44 +0200 Subject: Tkinter/threading issue In-Reply-To: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Message-ID: <201008152228.45303.thomas@jollybox.de> On Sunday 15 August 2010, it occurred to Jerrad Genson to exclaim: > Hello, > > I'm learning Tkinter, and I have an issue that I'd appreciate help > with. I have a program that initializes a GUI (I'll call this the "GUI > process"), then spawns another process that listens on a network via > the TCP/IP protocol for incoming strings (I'll call this the "server > process"). Everything works well up to this point. Okay, so you want your TCP (or is it UDP? not that it matters - but "TCP/IP" is not a protocol) server to sit in a separate process. May I ask why? Either way, you first need to trigger something inside the GUI process when a network packet arrives. The easiest way would of course be to have the server in the same process... Anyway, IPC. You say you're using Ubuntu. If you're only targetting UNIX-like systems, you can use os.fork() to create the new process -- you're probably doing so anyway (?) -- and use socket.socketpair or os.pipe to create a pipe between parent and child. If you're launching the process with subprocess.Popen, you can simply use the standard files (stdin, stdout,...) as a pipe. If the processes are completely separate, you'd need to use some convention to create a socket between the two, eithe a AF_LOCAL/AF_UNIX socket, or, if you want to support Windows and the likes, a local loopback TCP socket (->127.0.0.1) Once you've got a pipe between the two processes - or the network server within your GUI process - you just have to wait for a message to come flying in, and then update the widget. There are a couple of ways of waiting for a message without disrupting the GUI: you can either create a separate thread in which you, wait for input, or you can add a piece of code to the main loop (I don't know how difficult this is with Tkinter -- shouldn't be too tricky) that checks if there's any news, typically by calling select.select with a zero timeout. > > What I want to happen next is for the server process to update a label > in the GUI process when it receives a message from the network. First > I tried passing a control variable for the label's text into the > server process, but when I updated the control variable, nothing > happened(no error messages, no feedback of any kind). > > I tried piping the message from the server process into the GUI > process using os.write() and os.read() - and this works, but not the > way I need it to. I need the label to be updated automatically, > without any intervention from the user (at the moment, it only works > when the user clicks an "Update" button). I tried having the GUI > process check the pipe for messages automatically, but when I do this > it hangs when there's nothing in the pipe. > > I've tried other avenues as well, but probably nothing worth > mentioning. If you have any suggestions, I would be very grateful. From raoulbia at gmail.com Sun Aug 15 16:36:03 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 15 Aug 2010 13:36:03 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> Message-ID: <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Hi Mel, indeed i thought of generalising the theorem as follows: If it is possible to buy n, n+1,?, n+(x-1) sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in x, y and z packs. so with diophantine_nuggets(7,10,21) i would need 7 passes result:53 but with (10,20,30) and 10 passes i get no result so i'm not sure i'm on the right path... From jerradgenson at gmail.com Sun Aug 15 16:53:08 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 13:53:08 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Message-ID: Thank you for the reply. When I said "TCP/IP" protocol, what I meant was this: http://en.wikipedia.org/wiki/Internet_Protocol_Suite. The reason the server is in a separate process is because it needs to continually be listening for network packets, which would disrupt the GUI. In any case, that part is working fine - I actually have everything you mentioned implemented already, in mostly the way you described it, except for the very last part where the GUI label gets updated. I tried creating a "listener" thread that waits for a message to appear on its pipe from the server process, and then updates the label using a control variable. Again, nothing happens. The program doesn't hang, or throw an exception, but the label isn't being updated either - I presume because I'm trying to set the control variable in a thread separate from the GUI. I'll post some of the code so you can see what I'm talking about. From jerradgenson at gmail.com Sun Aug 15 16:55:49 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 13:55:49 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> Message-ID: <69cab38e-76f6-40d8-ae36-6c930b0c3452@l6g2000yqb.googlegroups.com> class MessageServer: '''Creates a message server object that listens for textual information and sends it back to the main program. Intended to be spawned as a separate process. ''' def __init__(self, port_number, server_send, server_receive): '''@param server_send The pipe MessageServer uses to send text back to the main program. @param port_number The port the server listens on the network at. ''' self.server_send = server_send self.server_receive = server_receive self.client_socket = None self.address = None self.error_logger = errorlogger.ErrorLogger(program_name=PROGRAM_NAME) self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind(('localhost', port_number)) self.server_socket.listen(1) self.listen() def listen(self): # listen for messages until process is killed # if a message is received, send it back to the main program (self.client_socket, self.address) = self.server_socket.accept() while True: input_stream = str(self.client_socket.recv(1024)) if len(input_stream) != 0: os.write(self.server_send, input_stream) input_stream = None From jerradgenson at gmail.com Sun Aug 15 16:59:17 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 13:59:17 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> <69cab38e-76f6-40d8-ae36-6c930b0c3452@l6g2000yqb.googlegroups.com> Message-ID: def check_message(self, spawn=True): '''Method for pulling message from server process.''' if spawn: self.pid2 = os.fork() if self.pid2 == 0: if verbose: print('message checker initialized') # repeat message check forever while True: incoming_data = os.read(self.client_receive, 1024) if verbose: print('Message receive successful') if verbose: print('Message: ' + incoming_data) self.update_messages(incoming_data) def update_messages(self, new_text=False): '''Adds new string to conversation box. @param new_text The string to be added. ''' if not new_text: new_text = INCOMING_DATA try: current_text = self.chat_text.get() current_text += '\n' + new_text self.chat_text.set(current_text) except: error_details = 'Fatal Error. Message update failed. Program will now close.' tkMessageBox.showerror('Update Error', error_details) error_details += '\nINCOMING_DATA: ' + new_text error_details += '\ncurrent_text: ' + current_text stack_trace = traceback.format_stack() self.error_logger.log_error(stack=stack_trace, details=error_details) self.exit_program(force=True) From hpj at urpla.net Sun Aug 15 17:17:13 2010 From: hpj at urpla.net (Hans-Peter Jansen) Date: Sun, 15 Aug 2010 23:17:13 +0200 Subject: segfault with small pyqt script In-Reply-To: References: Message-ID: <201008152317.13757.hpj@urpla.net> On Thursday 12 August 2010, 01:07:25 Gelonida wrote: > Hi Guys, > I'm desperate. I'm having a real application, which fails rather often > when finishing it. I'm not sure, whether any serious problem could be > hidden behind it > > The script is a pyqt script, which segfaults most of the time on my > ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. > > Trying to create the smallest possible test case I ended up with > following script, which I named dodo.py and which i made executable with > chmod +x ./dodo.py > > #!/usr/bin/env python > from PyQt4.QtGui import > QDialog,QGridLayout,QLabel,QComboBox,QPushButton,QApplication > a = "one" > b = "unused" > c = "also unused" > d= "ans also unused" > e = "another var" > f = "something" > class MyForm(QDialog): > def __init__(self,parent=None,config=None,ini_info=None): > super(MyForm,self).__init__(parent=parent) > grid = QGridLayout() > quit_btn = QPushButton("Quit") > quit_btn.clicked.connect(self.quit) > grid.addWidget(quit_btn,0,0) > name = "a_name" > vals_box = QComboBox() > vals_box.addItem("one") > vals_box.addItem("two") > grid.addWidget(vals_box,0,1) > self.setLayout(grid) > def quit(self): > self.close() > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > print "last" > > > > In order to perform the test several times I typed on the command line: > > a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done > > As soon as the window shows up > I click twice (slowly ) on 'one' and then on quit. For a starter, tell us the versions of python-sip, and python-qt4 or however they're called in Ubuntu. For the record, python-sip-4.10.5-1.1 python-qt4-4.7.4-1.1 doesn't show this behavior. Pete From fons at kokkinizita.net Sun Aug 15 17:21:51 2010 From: fons at kokkinizita.net (fons at kokkinizita.net) Date: Sun, 15 Aug 2010 23:21:51 +0200 Subject: execfile() and locals() Message-ID: <20100815212150.GA4280@zita2> Hello all, The documentation on execfile() and locals() makes it clear that code executed from execfile() can not modify local variables in the function from wich execfile() was called. Two questions about this: 1. Is there some way to circumvent this limitation (apart from explicitly copying variables to/from a dictionary passed as locals to execfile()) ? 2. (for experts only I guess) I'd like to understand *why* this is the case. TIA, -- FA There are three of them, and Alleline. From ian.g.kelly at gmail.com Sun Aug 15 17:39:57 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Aug 2010 17:39:57 -0400 Subject: NZEC what is it? In-Reply-To: References: Message-ID: On Sun, Aug 15, 2010 at 12:56 PM, Mikael B wrote: > Hi > ?I use, among other things,? a site,? http://www.codechef.com? to learn > python. > I don't know what platform they use. I use? linux. > > When I submit this little piece of? code to them: > > import sys > import math > > #main > > s=sys.stdin.read() > > int_list=s.split() > > for a in int_list[1:]: > ??????? print math.factorial(int(a)) > > > they generate a runtime error :NZEC?? but I don't? (python 2.6) > > What is NZEC? and what could cause it in these few lines of code? Non-zero exit code. Unless you're calling sys.exit, this normally means your program raised an uncaught exception. In the case of your program, I believe that codechef currently uses Python 2.5. The math.factorial function was added in Python 2.6, so it would not be available. Cheers, Ian From ian.g.kelly at gmail.com Sun Aug 15 17:51:18 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Aug 2010 17:51:18 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Message-ID: On Sun, Aug 15, 2010 at 4:36 PM, Baba wrote: > Hi Mel, > > indeed i thought of generalising the theorem as follows: > If it is possible to buy n, n+1,?, n+(x-1) sets of McNuggets, for some > x, then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in x, y and z packs. > > so with diophantine_nuggets(7,10,21) i would need 7 passes > result:53 > > but with (10,20,30) and 10 passes i get no result You're on the right track. In the case of (10,20,30) there is no largest exactly purchasable quantity. Any quantity that does not end with a 0 will not be exactly purchasable. I suspect that there exists a largest unpurchasable quantity iff at least two of the pack quantities are relatively prime, but I have made no attempt to prove this. Cheers, Ian From thomas at jollybox.de Sun Aug 15 17:55:06 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 15 Aug 2010 23:55:06 +0200 Subject: execfile() and locals() In-Reply-To: <20100815212150.GA4280@zita2> References: <20100815212150.GA4280@zita2> Message-ID: <201008152355.06702.thomas@jollybox.de> On Sunday 15 August 2010, it occurred to fons at kokkinizita.net to exclaim: > Hello all, > > The documentation on execfile() and locals() makes it clear that code > executed from execfile() can not modify local variables in the function > from wich execfile() was called. Two questions about this: > > 1. Is there some way to circumvent this limitation (apart from explicitly > copying variables to/from a dictionary passed as locals to execfile()) ? > > 2. (for experts only I guess) I'd like to understand *why* this is the > case. You can't assign to local variables via locals(), or in any way at all, except by assigning locally. >>> def f(): ... x = 1 ... locals()['x'] = 2 ... return x ... >>> f() 1 >>> The reason is, I think, that local variable access is optimized: variables you assign inside the function are defined to be local (unless you specify otherwise), and a fetching a local variable doesn't involve an expensive may- or-may-not-work dict lookup: >>> x = 1 >>> def g(): ... x ... x = 2 ... >>> x 1 >>> g() Traceback (most recent call last): File "", line 1, in File "", line 2, in g UnboundLocalError: local variable 'x' referenced before assignment >>> If a local variable assignment were hidden behind an execfile(), or a "from foo import *", or a locals()[...] assignment, it wouldn't be possibly to tell if something is local or not. From mback1 at live.se Sun Aug 15 17:55:53 2010 From: mback1 at live.se (Mikael B) Date: Sun, 15 Aug 2010 23:55:53 +0200 Subject: NZEC what is it? In-Reply-To: References: , Message-ID: > From: ian.g.kelly at gmail.com > Date: Sun, 15 Aug 2010 17:39:57 -0400 > Subject: Re: NZEC what is it? > To: python-list at python.org > > On Sun, Aug 15, 2010 at 12:56 PM, Mikael B wrote: > > Hi > > I use, among other things, a site, http://www.codechef.com to learn > > python. > > I don't know what platform they use. I use linux. > > > > When I submit this little piece of code to them: > > > > import sys > > import math > > > > #main > > > > s=sys.stdin.read() > > > > int_list=s.split() > > > > for a in int_list[1:]: > > print math.factorial(int(a)) > > > > > > they generate a runtime error :NZEC but I don't (python 2.6) > > > > What is NZEC and what could cause it in these few lines of code? > > Non-zero exit code. Unless you're calling sys.exit, this normally > means your program raised an uncaught exception. > > In the case of your program, I believe that codechef currently uses > Python 2.5. The math.factorial function was added in Python 2.6, so > it would not be available. > > Cheers, > Ian Ahaa! Thank you. regards Mikael -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 19:24:25 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 23:24:25 GMT Subject: execfile() and locals() References: Message-ID: <4c687728$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 23:21:51 +0200, fons wrote: > Hello all, > > The documentation on execfile() and locals() makes it clear that code > executed from execfile() can not modify local variables in the function > from wich execfile() was called. Two questions about this: > > 1. Is there some way to circumvent this limitation (apart from > explicitly copying variables to/from a dictionary passed as locals to > execfile()) ? Chances are very good that if you're using exec or execfile inside a function, you probably don't need to. > 2. (for experts only I guess) I'd like to understand *why* this is the > case. As an optimization, local variables don't live inside a dict namespace. The space for those locals is allocated at compile time, and locals() returns a copy of the variables in a dict. However, the action of exec is a little more subtle, and mysterious, as seen by this example in Python 3.1: >>> def f(): ... x = 1 ... print(locals()) ... exec("x=2; y=0") ... print(locals()) ... >>> >>> f() {'x': 1} {'y': 0, 'x': 1} This shows that exec was able to create a new local variable, but not modify an existing one -- this is completely unintuitive to me. I would have guessed the opposite. And worse: >>> f.__code__.co_varnames ('x',) >>> f.__code__.co_nlocals 1 So where does the newly-created local `y` live, if not in a dict namespace and not in the usual variable slots? Curiouser and curiouser... -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 19:33:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2010 23:33:10 GMT Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> Message-ID: <4c687936$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 12:10:10 -0700, Steven Howe wrote: >> Strings have a join method for this: >> '\t'.join(someList) >> >> Gary Herron > or maybe: > ----------------------------------------- > res = "" > for item in myList: > res = "%s\t%s" % ( res, item ) Under what possible circumstances would you prefer this code to the built- in str.join method? Particularly since the code isn't even correct, as it adds a spurious tab character at the beginning of the result string. (By the way, your solution, to call res.strip(), is incorrect, as it removes too much.) -- Steven From chare at labr.net Sun Aug 15 19:41:11 2010 From: chare at labr.net (Chris Hare) Date: Sun, 15 Aug 2010 18:41:11 -0500 Subject: python strings and {} in Tkinter entry widgets Message-ID: I have some code that pulls a value from a database. In this case, it is three space delimited words. When I display the value in a Tkinter.Entry widget, the text has curly braces around it, even when there are none in the surrounding the text in the database. Is this normal, and how do I prevent it or remove them correctly before displaying the text in the Entry widget? Thanks From nadiasvertex at gmail.com Sun Aug 15 19:45:49 2010 From: nadiasvertex at gmail.com (Christopher) Date: Sun, 15 Aug 2010 16:45:49 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? Message-ID: I have the following problem: Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> t="Python26" >>> import re >>> re.sub(r"python\d\d", "Python27", t) 'Python26' >>> re.sub(r"python\d\d", "Python27", t, re.IGNORECASE) 'Python26' >>> re.sub(r"Python\d\d", "Python27", t, re.IGNORECASE) 'Python27' >>> --- Perhaps this is intended behavior, but it seems like the last two results should be the same, not the first two. In other words, the call to re.sub with re.IGNORECASE on should return "Python27" not "Python26". This appears to be the case when using compiled pattern matching: >>> r=re.compile(r"python\d\d", re.IGNORECASE) >>> r.sub("Python27", t) 'Python27' --- Is this a known bug? Is it by design for some odd reason? From roy at panix.com Sun Aug 15 19:58:54 2010 From: roy at panix.com (Roy Smith) Date: Sun, 15 Aug 2010 19:58:54 -0400 Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: In article <4c687936$0$11100$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 12:10:10 -0700, Steven Howe wrote: > > >> Strings have a join method for this: > >> '\t'.join(someList) > >> > >> Gary Herron > > or maybe: > > ----------------------------------------- > > res = "" > > for item in myList: > > res = "%s\t%s" % ( res, item ) > > > Under what possible circumstances would you prefer this code to the built- > in str.join method? > > Particularly since the code isn't even correct, as it adds a spurious tab > character at the beginning of the result string. I think you answered your own question. The possible circumstance would be a "find the bug" question on a programming interview :-) Actually, there is (at least) one situation where this produces the correct result, can you find it? The other problem is that the verbose version is O(n^2) and str.join() is O(n). From darcy at druid.net Sun Aug 15 20:03:55 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 15 Aug 2010 20:03:55 -0400 Subject: Opposite of split In-Reply-To: <4c687936$0$11100$c3e8da3@news.astraweb.com> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: <20100815200355.47f0ca2d.darcy@druid.net> On 15 Aug 2010 23:33:10 GMT Steven D'Aprano wrote: > Under what possible circumstances would you prefer this code to the built- > in str.join method? I assumed that it was a trap for someone asking for us to do his homework. I also thought that it was a waste of time because I knew that twenty people would jump in with the correct answer because of "finally, one that I can answer" syndrome. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 20:07:53 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 00:07:53 GMT Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: Message-ID: <4c688159$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 16:45:49 -0700, Christopher wrote: > I have the following problem: > >>>> t="Python26" >>>> import re >>>> re.sub(r"python\d\d", "Python27", t) > 'Python26' >>>> re.sub(r"python\d\d", "Python27", t, re.IGNORECASE) > 'Python26' >>>> re.sub(r"Python\d\d", "Python27", t, re.IGNORECASE) > 'Python27' > Is this a known bug? Is it by design for some odd reason? >>> help(re.sub) Help on function sub in module re: sub(pattern, repl, string, count=0) ... You're passing re.IGNORECASE (which happens to equal 2) as a count argument, not as a flag. Try this instead: >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) 'Python27' -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 15 20:10:31 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 00:10:31 GMT Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c6881f7$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 19:58:54 -0400, Roy Smith wrote: > Actually, > there is (at least) one situation where this produces the correct > result, can you find it? When myList is empty, it correctly gives the empty string. -- Steven From greg.ewing at canterbury.ac.nz Sun Aug 15 20:33:51 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 16 Aug 2010 12:33:51 +1200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <8crequF9tpU1@mid.individual.net> Ian Kelly wrote: > On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie > wrote: >> real sample[-500:750]; > Ugh, no. The ability to change the minimum index is evil. Not always; it can have its uses, particularly when you're using the array as a mapping rather than a collection. Pascal had a nice feature where you could use any ordinal type as an array index, and sometimes it was handy to have things like an array indexed by the characters 'A' to 'Z', or the values (Red, Green, Blue). Typically you didn't need to do arithmetic on the indices in those case, though. Python addresses this by having separate types for sequences and mappings. -- Greg From alex at moreati.org.uk Sun Aug 15 20:36:07 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Sun, 15 Aug 2010 17:36:07 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> Message-ID: <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> On Aug 16, 1:07?am, Steven D'Aprano wrote: > You're passing re.IGNORECASE (which happens to equal 2) as a count > argument, not as a flag. Try this instead: > > >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) > 'Python27' Basically right, but in-line flags must be placed at the start of a pattern, or the result is undefined. Also in Python 2.7 re.sub() has a flags argument. Python 2.7.0+ (release27-maint:83286, Aug 16 2010, 01:25:58) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> t = 'Python26' >>> re.sub(r'(?i)python\d\d', 'Python27', t) 'Python27' >>> re.sub(r'python\d\d', 'Python27', t, flags=re.IGNORECASE) 'Python27' Alex From hammer777123 at gmail.com Sun Aug 15 20:43:03 2010 From: hammer777123 at gmail.com (hammer777123) Date: Sun, 15 Aug 2010 17:43:03 -0700 (PDT) Subject: NewaveMoneyMaker__FREE 30 Day Trial__4,650 Followers In 7 days Message-ID: <5f75e005-e0fa-4d17-8e9d-d1d11de822e3@i13g2000yqd.googlegroups.com> NewaveMoneyMaker__FREE 30 Day Trial__4,650 Followers In 7 days http://tinyurl.com/2gx63ye Want Better Than The "Average" P_ _ _ _ Size? 2 FREE Bottles http://mhlnk.com/DF434BFB Free $5.00 to Join___$0.5 Paid Per Click http://tinyurl.com/3xanc6c From greg.ewing at canterbury.ac.nz Sun Aug 15 20:47:28 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 16 Aug 2010 12:47:28 +1200 Subject: Python "why" questions In-Reply-To: References: Message-ID: <8crfkeFdl0U1@mid.individual.net> Roald de Vries wrote: > On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: > >> Which somewhat defeats the point of trying to make them >> look the >> same, don?t you think? > > How are they not the same? One way to see that they're not *exactly* the same is the fact that sizeof("python rocks") is 13, not sizeof(char *). Arrays exist as a distinct concept in the type system. What is true is that when you use the name of an array in an expression, it evaluates to a pointer to its first element. And array indexing is defined in terms of what happens to the resulting pointer, rather than being done directly on the array itself. -- Greg From greg.ewing at canterbury.ac.nz Sun Aug 15 20:53:52 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 16 Aug 2010 12:53:52 +1200 Subject: Python "why" questions In-Reply-To: References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> Message-ID: <8crg0eFfbkU1@mid.individual.net> > On Aug 7, 2010, at 9:14 PM, John Nagle wrote: > >> The languages which have real multidimensional arrays, rather >> than arrays of arrays, tend to use 1-based subscripts. That >> reflects standard practice in mathematics. Not always -- mathematicians use whatever starting index is most convenient for the problem at hand. For example, the constant term of a polynomial is usually called term 0, not term 1. So to a mathematician, an array being used to hold polynomial coefficents would most naturally be indexed from 0. I suspect that part of the reason Fortran uses 1-based indexing is that people hadn't had enough experience with high-level languages back then to realise the awkwardness it often leads to, and they were relying on "common sense". -- Greg From roy at panix.com Sun Aug 15 20:59:36 2010 From: roy at panix.com (Roy Smith) Date: Sun, 15 Aug 2010 20:59:36 -0400 Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: In article <8crg0eFfbkU1 at mid.individual.net>, Gregory Ewing wrote: > Not always -- mathematicians use whatever starting index is > most convenient for the problem at hand. Which may be 0, 1, or something else. There are plenty of situations, for example, where you might want to use both positive and negative indices. Which work with Python lists, but not the way a mathematician would expect :-) In general, I've found, "Because that's the way they do it in math", to be an unreliable guide to, "How should we do it in a programming language?" It's often a reasonable place to start, but there are other considerations. From python at mrabarnett.plus.com Sun Aug 15 21:13:43 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 16 Aug 2010 02:13:43 +0100 Subject: Python 2.7 re.IGNORECASE broken in re.sub? In-Reply-To: <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> Message-ID: <4C6890C7.9040001@mrabarnett.plus.com> Alex Willmer wrote: > On Aug 16, 1:07 am, Steven D'Aprano cybersource.com.au> wrote: >> You're passing re.IGNORECASE (which happens to equal 2) as a count >> argument, not as a flag. Try this instead: >> >>>>> re.sub(r"python\d\d" + '(?i)', "Python27", t) >> 'Python27' > > Basically right, but in-line flags must be placed at the start of a > pattern, or the result is undefined. Also in Python 2.7 re.sub() has a > flags argument. > [snip] In re such flags apply to the entire regex, no matter where they appear. This even applies to the (?x) (VERBOSE) flag; if re sees it at the end of the regex then it has to re-scan the entire regex! For clarity and compatibility with other regex implementations, put it initially. From bob at mellowood.ca Sun Aug 15 21:43:49 2010 From: bob at mellowood.ca (bvdp) Date: Sun, 15 Aug 2010 18:43:49 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: On Aug 15, 12:52?pm, John Nagle wrote: > On 8/14/2010 4:05 PM, bvdp wrote: > > > Assuming I have a module 'foo.py' with something like this: > > > def error(s): > > ? ? ?print "Error", s > > ? ? ?sys.exit(1) > > > def func(s): > > ? ? ?... do some processing > > ? ? ?... call error() if bad .. go to system exit. > > ? ? ?... ?more processing > > ? ? Fix "func". ?That's terrible Python. ? No standard Python library > module calls system exit to handle an error. ?So that must be in > your code. ? Standard procedure for errors is to raise an > exception. Not to belabor the point .. but "func" is not a standard lib module. It's part of a much larger application ... and in that application it makes perfect sense to terminate the application if it encounters an error. I fail to see the problem with this. Why would an APPLICATION raise a error or not exit to the system? Does it help to note that error() as defined in the application prints out a helpful message, etc? The whole problem I was having is that I was trying to tie a small application (an helper to the main application) to use a bit of the existing code as a pseudo-library. Certainly, if the code I was interfacing with was a standar Python module ... well, then this thread would not exist in the first place. However, I have gotten hit with more than one comment like yours. So, could you please clarify? Is it bad form to exit an application with sys.exit(1) when an error in a file the application is processing is found? Honestly, I'm not trying to be argumentative ... just trying to understand. Thanks. From jerradgenson at gmail.com Sun Aug 15 22:03:00 2010 From: jerradgenson at gmail.com (Jerrad Genson) Date: Sun, 15 Aug 2010 19:03:00 -0700 (PDT) Subject: Tkinter/threading issue References: <4b71a036-f544-49f9-bfaf-e3460714b538@t2g2000yqe.googlegroups.com> <69cab38e-76f6-40d8-ae36-6c930b0c3452@l6g2000yqb.googlegroups.com> Message-ID: <904096b9-2348-4c5a-9869-90f2ff9e8eda@k10g2000yqa.googlegroups.com> Well, I figured it out. Thanks anyway for your help. From flebber.crue at gmail.com Sun Aug 15 23:30:02 2010 From: flebber.crue at gmail.com (flebber) Date: Sun, 15 Aug 2010 20:30:02 -0700 (PDT) Subject: Python XML and tables using math Message-ID: <81a2406a-af83-4904-ae26-a41bc626fe0e@u31g2000pru.googlegroups.com> I am looking at a project that will import and modify an XML file and then export it to a table. Currently a flat file table system should be fine. I want to export the modified data to the table and then perform a handful of maths(largely simple statistical functions) to the data and then print out the resultant modified tables. I was planning on using Python 2.7 for the project. Has anyone used a guide to acheive something similar? I would like to read up on it so I can assess my options and best methods, any hints or tips? From carey.tilden at gmail.com Mon Aug 16 00:01:04 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Sun, 15 Aug 2010 21:01:04 -0700 Subject: Pop return from stack? In-Reply-To: References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: On Sun, Aug 15, 2010 at 6:43 PM, bvdp wrote: > Not to belabor the point .. but "func" is not a standard lib module. > It's part of a much larger application ... and in that application it > makes perfect sense to terminate the application if it encounters an > error. I fail to see the problem with this. Why would an APPLICATION > raise a error or not exit to the system? For me, the main reason is to ensure the application has only one exit point. There's only one spot to maintain the code for closing files, cleaning up network connections, displaying errors to the user, etc. It makes it really easy to change your mind later about what to do with errors. It also lets you unify handling of your own errors with errors generated by 3rd party code. Carey From ldo at geek-central.gen.new_zealand Mon Aug 16 00:28:46 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 16 Aug 2010 16:28:46 +1200 Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: In message <8crg0eFfbkU1 at mid.individual.net>, Gregory Ewing wrote: > For example, the constant term of a polynomial is usually called term 0, > not term 1. That is not some kind of ordinal numbering of the terms, that is the power of the variable involved. And polynomials can have negative powers, too. From chrischia82 at gmail.com Mon Aug 16 00:36:01 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Sun, 15 Aug 2010 21:36:01 -0700 (PDT) Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: On Aug 16, 4:17?am, Terry Reedy wrote: > On 8/15/2010 10:22 AM, ChrisChia wrote: > > > Hi all, > > i am trying to do a GUI with Tkinter package, but i am stuck no matter > > what... > > The problem right now is that my GUI has a label= 'A' (where 'A' is > > the text on display) > > > i wish to run a program with 2 threads... one for my GUI and the other > > for the terminal where the terminal will keep listening to the user > > input (let's say if he enters 'B'), the GUI will update it's label to > > 'B'. > > Makes no sense to me. GUI = graphics user interface. Interface = input > from and output to the user. Additional threads for for other activities > that may block or be compute intensive, not a separate text user interface. > > > It's easy to let the terminal wait after the user has entered the > > input. > > But the problem is that when the GUI loads up... the > > > root.mainloop() > > > doesn't seem to release the control, > > That seems to be the point of a GUI > > -- > Terry Jan Reedy The idea has is that the interface acts as a window to display the text type from the terminal. It's a crazy idea but i wish to implement something that way. The GUI in the case will display any text that the user enters from the terminal... Any idea to make both the processes running and listening at the same time? From jemygraw at gmail.com Mon Aug 16 01:13:54 2010 From: jemygraw at gmail.com (=?GB2312?B?vfD2zvbO?=) Date: Mon, 16 Aug 2010 05:13:54 +0000 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: Hi Man, I have done that according to your requirements Here is the code {code} > #!/usr/bin/python > > import Tkinter > > import threading > > >> root=Tkinter.Tk() > > root.geometry("100x100") > > v=Tkinter.StringVar() > > label=Tkinter.Label(root,textvariable=v,fg="red") > > label.pack(fill=Tkinter.X,expand=1) > > >> >> def getInput(): > > while True: > > global v > > inputStr=raw_input("Enter>>") > > v.set(inputStr) > > t1=threading.Thread(target=getInput,args=()) > > t1.start() > > >> Tkinter.mainloop() > > > {code} 2010/8/16 ChrisChia > On Aug 16, 4:17 am, Terry Reedy wrote: > > On 8/15/2010 10:22 AM, ChrisChia wrote: > > > > > Hi all, > > > i am trying to do a GUI with Tkinter package, but i am stuck no matter > > > what... > > > The problem right now is that my GUI has a label= 'A' (where 'A' is > > > the text on display) > > > > > i wish to run a program with 2 threads... one for my GUI and the other > > > for the terminal where the terminal will keep listening to the user > > > input (let's say if he enters 'B'), the GUI will update it's label to > > > 'B'. > > > > Makes no sense to me. GUI = graphics user interface. Interface = input > > from and output to the user. Additional threads for for other activities > > that may block or be compute intensive, not a separate text user > interface. > > > > > It's easy to let the terminal wait after the user has entered the > > > input. > > > But the problem is that when the GUI loads up... the > > > > > root.mainloop() > > > > > doesn't seem to release the control, > > > > That seems to be the point of a GUI > > > > -- > > Terry Jan Reedy > > > The idea has is that the interface acts as a window to display the > text type from the terminal. > It's a crazy idea but i wish to implement something that way. > > The GUI in the case will display any text that the user enters from > the terminal... > > Any idea to make both the processes running and listening at the same > time? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jemygraw at gmail.com Mon Aug 16 01:17:21 2010 From: jemygraw at gmail.com (Jemy) Date: Mon, 16 Aug 2010 05:17:21 +0000 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: On Mon, Aug 16, 2010 at 5:13 AM, ??? wrote: > Hi Man, > I have done that according to your requirements > Here is the code > {code} > >> #!/usr/bin/python >> >> import Tkinter >> >> import threading >> >> >>> root=Tkinter.Tk() >> >> root.geometry("100x100") >> >> v=Tkinter.StringVar() >> >> label=Tkinter.Label(root,textvariable=v,fg="red") >> >> label.pack(fill=Tkinter.X,expand=1) >> >> >>> >>> def getInput(): >> >> while True: >> >> global v >> >> inputStr=raw_input("Enter>>") >> >> v.set(inputStr) >> >> t1=threading.Thread(target=getInput,args=()) >> >> t1.start() >> >> >>> Tkinter.mainloop() >> >> >> {code} > > 2010/8/16 ChrisChia > > On Aug 16, 4:17 am, Terry Reedy wrote: >> > On 8/15/2010 10:22 AM, ChrisChia wrote: >> > >> > > Hi all, >> > > i am trying to do a GUI with Tkinter package, but i am stuck no matter >> > > what... >> > > The problem right now is that my GUI has a label= 'A' (where 'A' is >> > > the text on display) >> > >> > > i wish to run a program with 2 threads... one for my GUI and the other >> > > for the terminal where the terminal will keep listening to the user >> > > input (let's say if he enters 'B'), the GUI will update it's label to >> > > 'B'. >> > >> > Makes no sense to me. GUI = graphics user interface. Interface = input >> > from and output to the user. Additional threads for for other activities >> > that may block or be compute intensive, not a separate text user >> interface. >> > >> > > It's easy to let the terminal wait after the user has entered the >> > > input. >> > > But the problem is that when the GUI loads up... the >> > >> > > root.mainloop() >> > >> > > doesn't seem to release the control, >> > >> > That seems to be the point of a GUI >> > >> > -- >> > Terry Jan Reedy >> >> >> The idea has is that the interface acts as a window to display the >> text type from the terminal. >> It's a crazy idea but i wish to implement something that way. >> >> The GUI in the case will display any text that the user enters from >> the terminal... >> >> Any idea to make both the processes running and listening at the same >> time? >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- Hi,I am Jemy -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: tkm.py Type: text/x-python Size: 371 bytes Desc: not available URL: From jemygraw at gmail.com Mon Aug 16 01:17:54 2010 From: jemygraw at gmail.com (Jemy) Date: Mon, 16 Aug 2010 05:17:54 +0000 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: I attached the source file On Mon, Aug 16, 2010 at 5:17 AM, Jemy wrote: > > > On Mon, Aug 16, 2010 at 5:13 AM, ??? wrote: > >> Hi Man, >> I have done that according to your requirements >> Here is the code >> {code} >> >>> #!/usr/bin/python >>> >>> import Tkinter >>> >>> import threading >>> >>> >>>> root=Tkinter.Tk() >>> >>> root.geometry("100x100") >>> >>> v=Tkinter.StringVar() >>> >>> label=Tkinter.Label(root,textvariable=v,fg="red") >>> >>> label.pack(fill=Tkinter.X,expand=1) >>> >>> >>>> >>>> def getInput(): >>> >>> while True: >>> >>> global v >>> >>> inputStr=raw_input("Enter>>") >>> >>> v.set(inputStr) >>> >>> t1=threading.Thread(target=getInput,args=()) >>> >>> t1.start() >>> >>> >>>> Tkinter.mainloop() >>> >>> >>> {code} >> >> 2010/8/16 ChrisChia >> >> On Aug 16, 4:17 am, Terry Reedy wrote: >>> > On 8/15/2010 10:22 AM, ChrisChia wrote: >>> > >>> > > Hi all, >>> > > i am trying to do a GUI with Tkinter package, but i am stuck no >>> matter >>> > > what... >>> > > The problem right now is that my GUI has a label= 'A' (where 'A' is >>> > > the text on display) >>> > >>> > > i wish to run a program with 2 threads... one for my GUI and the >>> other >>> > > for the terminal where the terminal will keep listening to the user >>> > > input (let's say if he enters 'B'), the GUI will update it's label to >>> > > 'B'. >>> > >>> > Makes no sense to me. GUI = graphics user interface. Interface = input >>> > from and output to the user. Additional threads for for other >>> activities >>> > that may block or be compute intensive, not a separate text user >>> interface. >>> > >>> > > It's easy to let the terminal wait after the user has entered the >>> > > input. >>> > > But the problem is that when the GUI loads up... the >>> > >>> > > root.mainloop() >>> > >>> > > doesn't seem to release the control, >>> > >>> > That seems to be the point of a GUI >>> > >>> > -- >>> > Terry Jan Reedy >>> >>> >>> The idea has is that the interface acts as a window to display the >>> text type from the terminal. >>> It's a crazy idea but i wish to implement something that way. >>> >>> The GUI in the case will display any text that the user enters from >>> the terminal... >>> >>> Any idea to make both the processes running and listening at the same >>> time? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> > > > -- > Hi,I am Jemy > -- Hi,I am Jemy -------------- next part -------------- An HTML attachment was scrubbed... URL: From jemygraw at gmail.com Mon Aug 16 01:24:26 2010 From: jemygraw at gmail.com (Jemy) Date: Mon, 16 Aug 2010 05:24:26 +0000 Subject: 2 threads; 1 more Tkinter and 1 more terminal. problem In-Reply-To: References: <97d0c020-42b5-4fc2-a08d-2dd3d0816c13@f6g2000pro.googlegroups.com> Message-ID: http://effbot.org/tkinterbook/label.htm Hope this url will be of some help to you all. Regards Jemy -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Mon Aug 16 01:44:48 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 15 Aug 2010 22:44:48 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: <40a6bfac-3f4b-43f4-990b-224cb2b654d3@i19g2000pro.googlegroups.com> On Aug 15, 6:43?pm, bvdp wrote: > On Aug 15, 12:52?pm, John Nagle wrote: > > > > > On 8/14/2010 4:05 PM, bvdp wrote: > > > > Assuming I have a module 'foo.py' with something like this: > > > > def error(s): > > > ? ? ?print "Error", s > > > ? ? ?sys.exit(1) > > > > def func(s): > > > ? ? ?... do some processing > > > ? ? ?... call error() if bad .. go to system exit. > > > ? ? ?... ?more processing > > > ? ? Fix "func". ?That's terrible Python. ? No standard Python library > > module calls system exit to handle an error. ?So that must be in > > your code. ? Standard procedure for errors is to raise an > > exception. > > Not to belabor the point .. but "func" is not a standard lib module. > It's part of a much larger application ... and in that application it > makes perfect sense to terminate the application if it encounters an > error. I fail to see the problem with this. Why would an APPLICATION > raise a error or not exit to the system? > > Does it help to note that error() as defined in the application prints > out a helpful message, etc? > > The whole problem I was having is that I was trying to tie a small > application (an helper to the main application) to use a bit of the > existing code as a pseudo-library. Certainly, if the code I was > interfacing with was a standar Python module ... well, then this > thread would not exist in the first place. > > However, I have gotten hit with more than one comment like yours. So, > could you please clarify? Is it bad form to exit an application with > sys.exit(1) when an error in a file the application is processing is > found? > > Honestly, I'm not trying to be argumentative ... just trying to > understand. The One Obvious Way to handle errors in Python is to raise an exception, and catching it wherever you can proceed. If you can't proceed, either don't catch it, or catch it at the top level. Example (Python 2.6): class MyException(Exception): pass def some_function deep in call tree(): # do some stuff if is_error(): # will be caught way up the stack, in main raise MyException(error_message) # do some stuff if there wasn't an error def main(): try: run_program() except MyException as exc: print >> sys.stderr, str(exc) sys.exit(1) If you call sys.exit() deep within your call tree, the world won't come to an end, but raising an exception is the preferred way to do it. FWIW, I think it perfectly reasonable to let an application print a traceback on an error. I've gotten a few bug reports on a little tool I maintain where the user copies the traceback to me, it it's helped me diagnose their issues a lot. Carl Banks From stefan_ml at behnel.de Mon Aug 16 02:00:30 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 16 Aug 2010 08:00:30 +0200 Subject: Python XML and tables using math In-Reply-To: <81a2406a-af83-4904-ae26-a41bc626fe0e@u31g2000pru.googlegroups.com> References: <81a2406a-af83-4904-ae26-a41bc626fe0e@u31g2000pru.googlegroups.com> Message-ID: flebber, 16.08.2010 05:30: > I am looking at a project that will import and modify an XML file and > then export it to a table. Currently a flat file table system should > be fine. > > I want to export the modified data to the table and then perform a > handful of maths(largely simple statistical functions) to the data and > then print out the resultant modified tables. > > I was planning on using Python 2.7 for the project. > > Has anyone used a guide to acheive something similar? I would like to > read up on it so I can assess my options and best methods, any hints > or tips? That can usually be done in a couple of lines in Python. The approach I keep recommending is to use cElementTree (in the stdlib), potentially its iterparse() function if the file is too large to easily fit into memory, but the code won't change much either way. You might want to skip through this list a bit, similar questions have been coming up every couple of weeks. The responses often include mostly complete implementations that you can borrow from. Stefan From bob.martin at excite.com Mon Aug 16 07:24:26 2010 From: bob.martin at excite.com (Bob Martin) Date: Mon, 16 Aug 2010 07:24:26 BST Subject: Python "why" questions References: Message-ID: <8cs3sqF18dU4@mid.individual.net> in 639663 20100815 120123 Lawrence D'Oliveiro wrote: >In message , Ian Kelly >wrote: > >> The ability to change the minimum index is evil. > >Pascal allowed you to do that. And nobody ever characterized Pascal as >???evil???. Not for that reason, anyway... Why do you refer to Pascal in the past tense? I use it most days (Delphi & Free Pascal). From alanwilter at gmail.com Mon Aug 16 03:06:20 2010 From: alanwilter at gmail.com (Alan) Date: Mon, 16 Aug 2010 08:06:20 +0100 Subject: errors and exception Message-ID: Hello, I am using things like: except Exception as inst: and with open("myfile.txt") as f: for line in f: print line Things that seems to be new in python 2.6 and higher, however reading http://docs.python.org/tutorial/errors.html and this not clear when this new syntaxes appeared. My trouble is that I want to make something similar above compatible with python 2.5, but when running python2.5 I got: except Exception as msg: ^ SyntaxError: invalid syntax If there's a way (e.g. from __future__ ..., inherited modified Exception class, etc) that could give a solution to keep my code in python 2.6 syntax as above but compatible with python 2.5, that would be appreciated. Many thanks in advance, Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From stndshp at gmail.com Mon Aug 16 03:20:17 2010 From: stndshp at gmail.com (Standish P) Date: Mon, 16 Aug 2010 00:20:17 -0700 (PDT) Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? Message-ID: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? Because a stack has push and pop, it is able to release and allocate memory. We envisage an exogenous stack which has malloc() associated with a push and free() associated with a pop. The algorithm using the stack would have to be "perfect" to prevent stack overflow or condition of infinite recursion depth. This would involve data type checking to filter out invalid input. The task must be casted in an algorithm that uses the stack. Then the algorithm must be shown to be heuristically or by its metaphor, to be correct using informal reasoning. Are there any standard textbooks or papers that show stacks implemented in C/C++/Python/Forth with malloc/free in push and pop ? If Forth is a general processing language based on stack, is it possible to convert any and all algorithms to stack based ones and thus avoid memory leaks since a pop automatically releases memory when free is an intrinsic part of it. K&R ANSI has the example of modular programming showing how to implement a stack but he uses a fixed length array. It is also possibly an endogenous stack. We look for an exogenous stack so that element size can vary. ======= Standish P From gelonida at gmail.com Mon Aug 16 03:22:27 2010 From: gelonida at gmail.com (Gelonida) Date: Mon, 16 Aug 2010 09:22:27 +0200 Subject: segfault with small pyqt script In-Reply-To: <201008152317.13757.hpj@urpla.net> References: <201008152317.13757.hpj@urpla.net> Message-ID: Hi Hans-Peter, It seems, that my other posts did not get through. On 08/15/2010 11:17 PM, Hans-Peter Jansen wrote: > For a starter, tell us the versions of python-sip, and python-qt4 or however > they're called in Ubuntu. For the record, > python-sip-4.10.5-1.1 > python-qt4-4.7.4-1.1 > doesn't show this behavior. > > Pete The problem seems to be known for 4.7.2. For simple code I managed to work around the issue. For the real more complicated I didn't. So it seems I'll have to avoid 4.7.2. Please see below: On 08/13/2010 09:11 AM, Gelonida wrote: > > Lee, > > > > On 08/13/2010 12:53 AM, Lee Harr wrote: >> >> >>> >>> I'm desperate. I'm having a real application, which fails rather often >>> >>> when finishing it. I'm not sure, whether any serious problem could be >>> >>> hidden behind it >>> >>> >>> >>> The script is a pyqt script, which segfaults most of the time on my >>> >>> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. >> >> >> >> >> >> Looks to be a known issue: >> >> http://www.google.com/search?q=pyqt+segfault+on+exit >> >> https://launchpad.net/bugs/561303 >> >> >> >> The last activity on that bug is almost 2 months ago... >> >> Hopefully the fix will be distributed soon. > > > > > > > > This seems to be the problem. > > > > > > In my case I can workaround the issue by adding one line. > > > > if __name__ == "__main__": > > app = QApplication([]) > > myform = MyForm() > > myform.show() > > retcode = app.exec_() > > myform = None # <<<< THIS IS THE WORK AROUND > > print "last" > > For more complex multi widget examples it doesn't seem enough to just destroy the main widget. probably I had to recursively assign all widgets / dialogues sub widgets to None. So I'll just try to stay away from this pyqt release and stick with older or newer ones. From gherron at islandtraining.com Mon Aug 16 03:29:26 2010 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 16 Aug 2010 00:29:26 -0700 Subject: errors and exception In-Reply-To: References: Message-ID: <4C68E8D6.2060908@islandtraining.com> On 08/16/2010 12:06 AM, Alan wrote: > Hello, > > I am using things like: > except Exception as inst: > and The old syntax for exceptions still works in Python2.x (all versions). The new syntax works in Python2.6+ and Python3. try: whatever except Exception,msg: # Old syntax print msg > > > with open("myfile.txt") as f: > for line in f: > print line You don't need the new fangled with statement if you want to be compatible with older versions of Python2. (It's nice and convenient, but not necessary.) f = open("myfile.txt") for line in f: print line f.close() # This is what the "with" statement guarantees; so now just do it yourself Gary Herron > Things that seems to be new in python 2.6 and higher, however reading > http://docs.python.org/tutorial/errors.html and this not clear when > this new syntaxes appeared. > > My trouble is that I want to make something similar above compatible > with python 2.5, but when running python2.5 I got: > > except Exception as msg: > ^ > SyntaxError: invalid syntax > If there's a way (e.g. from __future__ ..., inherited modified > Exception class, etc) that could give a solution to keep my code in > python 2.6 syntax as above but compatible with python 2.5, that would > be appreciated. > > Many thanks in advance, > > Alan > -- > Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate > Department of Biochemistry, University of Cambridge. > 80 Tennis Court Road, Cambridge CB2 1GA, UK. > >>http://www.bio.cam.ac.uk/~awd28 << -------------- next part -------------- An HTML attachment was scrubbed... URL: From alf.p.steinbach+usenet at gmail.com Mon Aug 16 03:38:57 2010 From: alf.p.steinbach+usenet at gmail.com (Alf P. Steinbach /Usenet) Date: Mon, 16 Aug 2010 09:38:57 +0200 Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: * Standish P, on 16.08.2010 09:20: > [garble garble] Nonsense article "We look for an exogenous stack" cross-posted to [comp.lang.c], [comp.lang.c++], [comp.theory], [comp.lang.python], [comp.lang.forth]. Please refrain from following up on Standish' article. Cheers, - Alf -- blog at From urban.dani at gmail.com Mon Aug 16 03:40:45 2010 From: urban.dani at gmail.com (Daniel Urban) Date: Mon, 16 Aug 2010 09:40:45 +0200 Subject: errors and exception In-Reply-To: <4C68E8D6.2060908@islandtraining.com> References: <4C68E8D6.2060908@islandtraining.com> Message-ID: > f = open("myfile.txt") > for line in f: > ? print line > f.close()?? # This is what the "with" statement guarantees; so now just do > it yourself Not exactly. More like: f = open("myfile.txt") try: for line in f: print line finally: f.close() Daniel From stefan_ml at behnel.de Mon Aug 16 03:40:47 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 16 Aug 2010 09:40:47 +0200 Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: Standish P, 16.08.2010 09:20: > We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. What's your use case? Stefan From clp2 at rebertia.com Mon Aug 16 03:42:17 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 16 Aug 2010 00:42:17 -0700 Subject: errors and exception In-Reply-To: <4C68E8D6.2060908@islandtraining.com> References: <4C68E8D6.2060908@islandtraining.com> Message-ID: On Mon, Aug 16, 2010 at 12:29 AM, Gary Herron wrote: > On 08/16/2010 12:06 AM, Alan wrote: >> Hello, >> I am using things like: >> with open("myfile.txt") as f: >> for line in f: >> print line > > You don't need the new fangled with statement if you want to be compatible > with older versions of Python2.? (It's nice and convenient, but not > necessary.) > > f = open("myfile.txt") > for line in f: > ? print line > f.close()?? # This is what the "with" statement guarantees; so now just do > it yourself Well, technically the equivalent would be: f = open("myfile.txt") try: for line in f: print line finally: f.close() It's just that the for-loop and print happen to be extremely unlikely to throw exceptions; presumably the OP's actual code is more complex. Cheers, Chris -- http://blog.rebertia.com From nikos.the.gr33k at gmail.com Mon Aug 16 03:45:59 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 16 Aug 2010 00:45:59 -0700 (PDT) Subject: Replace and inserting strings within .txt files with the use of regex References: <9e0ce936-e8e4-4209-85b8-21422a88754e@q35g2000yqn.googlegroups.com> <4c5e663f$0$28655$c3e8da3@news.astraweb.com> <93b067be-85d8-4bd2-b131-67c04fae7944@d17g2000yqb.googlegroups.com> <75a65399-4c9d-4fd5-b1d6-adb2430eca75@q35g2000yqn.googlegroups.com> <516a2b89-4ef5-4674-958f-d445eb2456e9@m1g2000yqo.googlegroups.com> <9f00bae6-0c95-4550-a93c-16a9ea39c9ae@p7g2000yqa.googlegroups.com> <82861b1d-e4e8-4dc8-be6d-f5e553726ad6@l14g2000yql.googlegroups.com> <3fc90e81-f569-48a2-a75f-4e7e0dcd29f0@s9g2000yqd.googlegroups.com> Message-ID: <69045ba4-f4cf-4426-abfd-8d5bd81b99d5@c10g2000yqi.googlegroups.com> On 10 ???, 01:43, MRAB wrote: > ????? wrote: > > D:\>convert.py > > ? File "D:\convert.py", line 34 > > SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line > > 34, but no > > ?encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor > > details > > > D:\> > > > What does it refering too? what character cannot be identified? > > > Line 34 is: > > > src_data = src_data.replace( '', '

> color=green> ??????? ??????????: %(counter)d ' ) > > Didn't you say that you're using Python 2.7 now? The default file > encoding will be ASCII, but your file isn't ASCII, it contains Greek > letters. Add the encoding line: > > ? ? ?# -*- coding: utf-8 -*- > > and check that the file is saved as UTF-8. > > > Also, > > > for currdir, files, dirs in os.walk('test'): > > > ? ?for f in files: sctually its for currdir, dirs, filesin os.walk('test'): thats whay ti couldnt run!! :-) After changifn this and made some other modification my convertion script finally run! Here it is for someone that might want a similar functionality. ====================================================================== #!/usr/bin/python # -*- coding: utf-8 -*- import re, os, sys count = 520 for currdir, dirs, files in os.walk('d:\\akis'): for f in files: if f.lower().endswith("php"): # get abs path to filename src_f = os.path.join(currdir, f) # open php src file f = open(src_f, 'r') src_data = f.read() f.close() # Grab the id number contained within the php code and insert it above all other data found = re.search( r'PageID = (\d+)', src_data ) if found: id = found.group(1) else: id = count =+ 1 src_data = ( '\n\n' % id ) + src_data # replace php tags and contents within src_data = re.sub( r'(?s)<\?(.*?)\?>', '', src_data ) # add template variables src_data = src_data.replace( '', '

??????? ??????????: %(counter)d ' ) # open same php file for storing modified data f = open(src_f, 'w') f.write(src_data) f.close() # rename edited .php file to .html extension dst_f = src_f.replace('.php', '.html') os.rename( src_f, dst_f ) print ( "renaming: %s => %s\n" % (src_f, dst_f) ) From nick_keighley_nospam at hotmail.com Mon Aug 16 03:47:44 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Mon, 16 Aug 2010 00:47:44 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> this is heavily x-posted I'm answering from comp.lang.c On 16 Aug, 08:20, Standish P wrote: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? I'm having trouble understanding your question (I read your whole post before replying). I strongly suspect the only connection your question has with C is that you are using C as your implementation language. I think you're trying to ask a question about memory management. You might be better off asking your question in a general programming new group such as comp.programming (sadly rather quiet these days). Note that C doesn't do automatic garbage collection. Memory is either freed on exit from a scope (stack-like memory lifetime) or explicitly (using free()). Static memory is, conceptually, never freed. > Because a stack has push and pop, it is able to release and allocate > memory. I'm not sure what you mean by some of the terms you use. In a sense a pop *is* a release. The memory is no longer available for use. > We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. "exogenous"? Why would you do this? Are you envisioning a stack of pointers? The pointers pointing to dynamically allocated memory? Well, yes, sure you could implement this in C. It isn't garbage collection by any standard definition of the term. > The algorithm using the stack would have to be "perfect" to prevent > stack overflow or condition of infinite recursion depth. the memory lifetimes must be stack-like (or close to stack-like) > This would > involve data type checking to filter out invalid input. I'd be more concerned about the memory allocation/dealllocation pattern rather than the data types. > The task must > be casted in an algorithm that uses the stack. Then the algorithm must > be shown to be heuristically or by its metaphor, to be correct using > informal reasoning. why informal reasoning? Why not formal reasoning? > Are there any standard textbooks or papers that show stacks > implemented in C/C++/Python/Forth with malloc/free in push and pop ? well it doesn't sound very hard... > If Forth is a general processing language based on stack, is it > possible to convert any and all algorithms to stack based ones and > thus avoid memory leaks since a pop automatically releases memory when > free is an intrinsic part of it. don't understand the question. - is forth a general purpose language? Yes - are all algorithms stack based? No some compuations simply need to hang onto memeory for a long time alloc (obj1) alloc (obj2) alloc (obj3) free (obj2) long_computation() free(obj3) free(obj1) this simply isn't stack based. the memory for obj2 cannot be reused on stack based scheme whilst long_computation() is going on. > K&R ANSI has the example of modular programming showing how to > implement a stack but he uses a fixed length array. It is also > possibly an endogenous stack. We look for an exogenous stack so that > element size can vary. malloc the memory? I see no garbage collection in your post From downaold at gmail.com Mon Aug 16 04:23:52 2010 From: downaold at gmail.com (Roald de Vries) Date: Mon, 16 Aug 2010 10:23:52 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Message-ID: <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> On Aug 15, 2010, at 11:51 PM, Ian Kelly wrote: > On Sun, Aug 15, 2010 at 4:36 PM, Baba wrote: >> Hi Mel, >> >> indeed i thought of generalising the theorem as follows: >> If it is possible to buy n, n+1,?, n+(x-1) sets of McNuggets, for >> some >> x, then it is possible to buy any number of McNuggets >= x, given >> that >> McNuggets come in x, y and z packs. >> >> so with diophantine_nuggets(7,10,21) i would need 7 passes >> result:53 >> >> but with (10,20,30) and 10 passes i get no result > > You're on the right track. In the case of (10,20,30) there is no > largest exactly purchasable quantity. Any quantity that does not end > with a 0 will not be exactly purchasable. > > I suspect that there exists a largest unpurchasable quantity iff at > least two of the pack quantities are relatively prime, but I have made > no attempt to prove this. That for sure is not correct; packs of 2, 4 and 7 do have a largest unpurchasable quantity. I'm pretty sure that if there's no common divisor for all three (or more) packages (except one), there is a largest unpurchasable quantity. That is: ? i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x| y) means "x is no divider of y" Cheers, Roald From stndshp at gmail.com Mon Aug 16 04:33:51 2010 From: stndshp at gmail.com (Standish P) Date: Mon, 16 Aug 2010 01:33:51 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> Message-ID: On Aug 16, 12:47?am, Nick Keighley wrote: > this is heavily x-posted I'm answering from comp.lang.c > > On 16 Aug, 08:20, Standish P wrote: > > > [Q] How far can stack [LIFO] solve do automatic garbage collection and > > prevent memory leak ? > > I'm having trouble understanding your question (I read your whole post > before replying). I strongly suspect the only connection your question > has with C is that you are using C as your implementation language. I > think you're trying to ask a question about memory management. You > might be better off asking your question in a general programming new > group such as comp.programming (sadly rather quiet these days). > > Note that C doesn't do automatic garbage collection. Memory is either > freed on exit from a scope (stack-like memory lifetime) or explicitly > (using free()). Static memory is, conceptually, never freed. > > > Because a stack has push and pop, it is able to release and allocate > > memory. > > I'm not sure what you mean by some of the terms you use. In a sense a > pop *is* a release. The memory is no longer available for use. > > > We envisage an exogenous stack which has malloc() associated > > with a push and free() associated with a pop. > > "exogenous"? Why would you do this? Are you envisioning a stack of > pointers? The pointers pointing to dynamically allocated memory? Well, > yes, sure you could implement this in C. It isn't garbage collection > by any standard definition of the term. I can clarify what I mean. Most books implement a stack with a fixed length array of chars and push chars into it, for eg k&r. I have a dynamically allocated array of pointers. The cons cell is allocated as well as the data is allocated for every push and the pointer points to its_curr_val.next. Similarly, every pop would move the pointer to its_curr_val.prev. It would also free the cons cell and the data after making a copy of the data. Below I explain your point on memory hanging. > > The algorithm using the stack would have to be "perfect" to prevent > > stack overflow or condition of infinite recursion depth. > > the memory lifetimes must be stack-like (or close to stack-like) > > > This would > > involve data type checking to filter out invalid input. > > I'd be more concerned about the memory allocation/dealllocation > pattern rather than the data types. > > > The task must > > be casted in an algorithm that uses the stack. Then the algorithm must > > be shown to be heuristically or by its metaphor, to be correct using > > informal reasoning. > > why informal reasoning? Why not formal reasoning? > > > Are there any standard textbooks or papers that show stacks > > implemented in C/C++/Python/Forth with malloc/free in push and pop ? > > well it doesn't sound very hard... > > > If Forth is a general processing language based on stack, is it > > possible to convert any and all algorithms to stack based ones and > > thus avoid memory leaks since a pop automatically releases memory when > > free is an intrinsic part of it. > > don't understand the question. > > ? ?- is forth a general purpose language? Yes > ? ?- are all algorithms stack based? No Does Forth uses stack for all algorithms ? Does it use pointers , ie indirect addressing ? If it can/must use stack then every algorithm could be made stack based. > some compuations simply need to hang onto memeory for a long time > > ? ? alloc (obj1) > ? ? alloc (obj2) > ? ? alloc (obj3) > > ? ? free (obj2) > ? ? long_computation() > ? ? free(obj3) > ? ? free(obj1) > > this simply isn't stack based. the memory for obj2 cannot be reused on > stack based scheme whilst long_computation() is going on. In theory the memory can be locked by a long_computation() . But a non- stacked based algorithm can also ignore freeing a memory and cause memory leak, just as an improper usage of stack cause the above problem. The purpose of a stack is to hold intermediate results ONLY. Only intermediate results should be below the long_computation, not those that need not wait for it. That is why heuristic or metaphorical thinking which considers all aspects simultaneously in a visual human brain thinking has less chance of error in conceiving such solutions than formal disjoint and symbolic thought. > > K&R ANSI has the example of modular programming showing how to > > implement a stack but he uses a fixed length array. It is also > > possibly an endogenous stack. We look for an exogenous stack so that > > element size can vary. > > malloc the memory? I see no garbage collection in your post a stack properly used does not need separate garbage collection. freeing is an automatic part of calling pop. Thats the superiority of a stack based algorithm over linked lists of unrestricted kinds. ======= Standish P From mahaboobnisha at gmail.com Mon Aug 16 04:45:03 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Mon, 16 Aug 2010 01:45:03 -0700 (PDT) Subject: comp.lang.python Message-ID: <2eda16fd-857f-4fe0-8402-89e52682888c@i4g2000prf.googlegroups.com> www.127760.blogspot.com From darragh.ssa at gmail.com Mon Aug 16 04:52:52 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 16 Aug 2010 01:52:52 -0700 (PDT) Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> Message-ID: <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> I still keep getting more downloads then usual which is awesome, but I still don't get any kind of response! please mail me or reply to this post with what you think, You can tell me that the program sucks but if you want to, do it in such a way that you also describe what exactly is the problem and not just say "the total" I really need some response because I'm working on version 0.2.1 and I want to know what there should be changed/added From nick_keighley_nospam at hotmail.com Mon Aug 16 05:25:06 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Mon, 16 Aug 2010 02:25:06 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> Message-ID: On 16 Aug, 09:33, Standish P wrote: > On Aug 16, 12:47?am, Nick Keighley > > On 16 Aug, 08:20, Standish P wrote: this is heavily x-posted I'm answering from comp.lang.c I also note that another poster has suggested you are a troll/loon you seem to be using some computer science-like terms but in an oddly non-standard manner > > > [Q] How far can stack [LIFO] solve do automatic garbage collection and > > > prevent memory leak ? no at all. How can a goldfish whistle? > > I'm having trouble understanding your question (I read your whole post > > before replying). I strongly suspect the only connection your question > > has with C is that you are using C as your implementation language. I > > think you're trying to ask a question about memory management. You > > might be better off asking your question in a general programming new > > group such as comp.programming (sadly rather quiet these days). this still applies > > Note that C doesn't do automatic garbage collection. Memory is either > > freed on exit from a scope (stack-like memory lifetime) or explicitly > > (using free()). Static memory is, conceptually, never freed. > > > > Because a stack has push and pop, it is able to release and allocate > > > memory. > > > I'm not sure what you mean by some of the terms you use. In a sense a > > pop *is* a release. The memory is no longer available for use. > > > > We envisage an exogenous stack which has malloc() associated > > > with a push and free() associated with a pop. > > > "exogenous"? Why would you do this? Are you envisioning a stack of > > pointers? The pointers pointing to dynamically allocated memory? Well, > > yes, sure you could implement this in C. It isn't garbage collection > > by any standard definition of the term. > > I can clarify what I mean. > > Most books implement a stack with a fixed length array of chars and > push chars into it, for eg k&r. this isn't inherent to a stack implementaion. A stack could be a malloced block of memory or a linked list. > I have a dynamically allocated array of pointers. The cons cell is that *what*? Are you trying to implement Lisp in C or something. Try comp.lang.lisp for some help there. Have you read "Lisp In Small Pieces"? Good fun. > allocated as well as the data is allocated for every push and the > pointer points to its_curr_val.next. I'm lost. What does a cons cell have to do with a fixed array of pointers? Why do you need dynamic memory? Aren't cons cells usually of fixed size? How can a Lisp-like language use a stack based memory allocation strategy? > Similarly, every pop would move the pointer to its_curr_val.prev. It > would also free the cons cell and the data after making a copy of the > data. Below I explain your point on memory hanging. > > > > The algorithm using the stack would have to be "perfect" to prevent > > > stack overflow or condition of infinite recursion depth. > > > the memory lifetimes must be stack-like (or close to stack-like) > > > > This would > > > involve data type checking to filter out invalid input. > > > I'd be more concerned about the memory allocation/dealllocation > > pattern rather than the data types. > > > > The task must > > > be casted in an algorithm that uses the stack. Then the algorithm must > > > be shown to be heuristically or by its metaphor, to be correct using > > > informal reasoning. > > > why informal reasoning? Why not formal reasoning? > > > > Are there any standard textbooks or papers that show stacks > > > implemented in C/C++/Python/Forth with malloc/free in push and pop ? > > > well it doesn't sound very hard... > > > > If Forth is a general processing language based on stack, is it > > > possible to convert any and all algorithms to stack based ones and > > > thus avoid memory leaks since a pop automatically releases memory when > > > free is an intrinsic part of it. > > > don't understand the question. > > > ? ?- is forth a general purpose language? Yes > > ? ?- are all algorithms stack based? No > > Does Forth uses stack for all algorithms ? don't know. Ask the Forth people. Some algoritms are fundamentally not stack based. If you try to implement them in Forth then either some memory isn't claimed as soon as possible (a leak) or there is some way to to have non-stack based memory management. > Does it use pointers , ie > indirect addressing ? If it can/must use stack then every algorithm > could be made stack based. > > > some compuations simply need to hang onto memeory for a long time > > > ? ? alloc (obj1) > > ? ? alloc (obj2) > > ? ? alloc (obj3) > > > ? ? free (obj2) > > ? ? long_computation() > > ? ? free(obj3) > > ? ? free(obj1) > > > this simply isn't stack based. the memory for obj2 cannot be reused on > > stack based scheme whilst long_computation() is going on. > > In theory the memory can be locked by a long_computation(). But a non- > stacked based algorithm can also ignore freeing a memory and cause > memory leak, just as an improper usage of stack cause the above > problem. The purpose of a stack is to hold intermediate results ONLY. no not really > Only intermediate results should be below the long_computation, not > those that need not wait for it. then you don't have stack-based memory allocation. Make your mind up. > That is why heuristic or metaphorical > thinking which considers all aspects simultaneously in a visual human > brain thinking has less chance of error in conceiving such solutions > than formal disjoint and symbolic thought. sorry, I thought we were talking about computer programming not hippy crustal healing. > > > K&R ANSI has the example of modular programming showing how to > > > implement a stack but he uses a fixed length array. It is also > > > possibly an endogenous stack. We look for an exogenous stack so that > > > element size can vary. > > > malloc the memory? I see no garbage collection in your post > > a stack properly used does not need separate garbage collection. > freeing is an automatic part of calling pop. > > Thats the superiority of a stack based algorithm over linked lists of > unrestricted kinds. and also its weakness. From egbert.bouwman at xs4all.nl Mon Aug 16 05:44:56 2010 From: egbert.bouwman at xs4all.nl (Egbert Bouwman) Date: Mon, 16 Aug 2010 11:44:56 +0200 Subject: When the first line of a file tells something about the other lines Message-ID: <1281951896.4744.2.camel@para.lan> Often the first line of a file tells how to read or interpret the other lines. Depending on the result, you then have to ... - skip the first line, or - treat the first line in another special way, or - treat the first line in the same way as the other lines. I can handle this by opening the file twice, the first time for reading the first line only. I suppose there exists a more elegant solution. Below is the structure of what I do now. Please comment. f = open(file_name,"r") # eerste opening file_line = f.readline() special = True if some_condition else False f.close() f = open(file_name,"r") # tweede opening if not special: # use first line, read previously stripped_line = file_line.strip() else: # skip first file_line, or treat in another special way: f.next() # read other lines: for file_line in f: stripped_line = file_line.strip() # now do something with stripped_line f.close() egbert -- Egbert Bouwman Keizersgracht 197-II 1016 DS Amsterdam Tel 0(031)20 6257991 From __peter__ at web.de Mon Aug 16 05:59:57 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Aug 2010 11:59:57 +0200 Subject: When the first line of a file tells something about the other lines References: Message-ID: Egbert Bouwman wrote: > Often the first line of a file tells how to read or interpret the other > lines. > Depending on the result, you then have to ... > - skip the first line, or > - treat the first line in another special way, or > - treat the first line in the same way as the other lines. > > I can handle this by opening the file twice, > the first time for reading the first line only. > I suppose there exists a more elegant solution. > Below is the structure of what I do now. > Please comment. > > f = open(file_name,"r") # eerste opening > file_line = f.readline() > special = True if some_condition else False > f.close() > > f = open(file_name,"r") # tweede opening > if not special: > # use first line, read previously > stripped_line = file_line.strip() > else: > # skip first file_line, or treat in another special way: > f.next() > # read other lines: > for file_line in f: > stripped_line = file_line.strip() > # now do something with stripped_line > f.close() with open(filename) as lines: first_line = next(lines, "") if special(first_line): # ... else: lines = itertools.chain([first_line], lines) for line in lines: # ... From prologic at shortcircuit.net.au Mon Aug 16 06:01:36 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 16 Aug 2010 20:01:36 +1000 Subject: GSM to ISO / UCS2 to ISO Message-ID: HI all, In an effort to avoid re-inventing the wheel so to speak I was wondering if anyone's come across libraries/tools, etc that achieve the same kind of functionality as the tools library in this java app. http://code.google.com/p/ipddump/source/browse/trunk/src/ipddump/tools/Gsm2Iso.java Thanks, cheers James -- -- James Mills -- -- "Problems are solved by method" From flebber.crue at gmail.com Mon Aug 16 06:11:24 2010 From: flebber.crue at gmail.com (flebber) Date: Mon, 16 Aug 2010 03:11:24 -0700 (PDT) Subject: Python XML and tables using math References: <81a2406a-af83-4904-ae26-a41bc626fe0e@u31g2000pru.googlegroups.com> Message-ID: On Aug 16, 4:00?pm, Stefan Behnel wrote: > flebber, 16.08.2010 05:30: > > > I am looking at a project that will import and modify an XML file and > > then export it to a table. Currently a flat file table system should > > be fine. > > > I want to export the modified data to the table and then perform a > > handful of maths(largely simple statistical functions) to the data and > > then print out the resultant modified tables. > > > I was planning on using Python 2.7 for the project. > > > Has anyone used a guide to acheive something similar? I would like to > > read up on it so I can assess my options and best methods, any hints > > or tips? > > That can usually be done in a couple of lines in Python. The approach I > keep recommending is to use cElementTree (in the stdlib), potentially its > iterparse() function if the file is too large to easily fit into memory, > but the code won't change much either way. > > You might want to skip through this list a bit, similar questions have been > coming up every couple of weeks. The responses often include mostly > complete implementations that you can borrow from. > > Stefan okay I found http://effbot.org/zone/celementtree.htm so I will have a read through there. I have been creating an every expanding macro/VBA project in Excel and due to slightly changin source document - the header order changes - it causes the project to crash out. I was hoping python and XML may be a bit more robust. From praveen.python.plone at gmail.com Mon Aug 16 06:17:06 2010 From: praveen.python.plone at gmail.com (Praveen) Date: Mon, 16 Aug 2010 03:17:06 -0700 (PDT) Subject: text to DB References: Message-ID: <86b95d78-fd4f-4ac0-8712-db77b749bff1@h40g2000pro.googlegroups.com> On Aug 14, 11:15?am, Dennis Lee Bieber wrote: > On Fri, 13 Aug 2010 09:46:34 -0700 (PDT), Praveen > declaimed the following in > gmane.comp.python.general: > > > I have a text file in this format > > PRA 1:13 2:20 3:5 > > SRA 1:45 2:75 3:9 > > TRA 1:2 2:65 3:45 > > > pattern is- Book Chapter:Verses > > > now i have my DB schema like this > > book_id ? ? ? ? ? ?chapter_id ? ? ? versed_id > > ? ? ? ? Off hand, I'd say that's an incomplete schema since there is not > enough information available to reconstruct the input data... > > ? ? ? ? I'd say there should be a second relation containing > > book_id book_name > > > > > could any one give me suggestion > > ? ? ? ? Is there a possibility that a given book "name" can appear multiple > times? > > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ f = open("/Users/Trellisys/Desktop//BibleDB/Booktable.txt","r") bk=[] cv = [] j=1 d={} for line in f: for l in line.split(): if l.isalnum(): bk.append(j) j = j+1 else: cv.append(l.split(":")) '''for i in l.split(":"): if i.isalpha(): #print i,j j = j+1 else: #print i''' print bk print cv output [1,2,3] but i am not getting how to map chapterId and versesId with bookId Regards, Praveen From bieffe62 at gmail.com Mon Aug 16 06:46:07 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Mon, 16 Aug 2010 03:46:07 -0700 (PDT) Subject: Comparing lists Message-ID: <5f89432d-47a0-405f-9601-7f04a7818248@c10g2000yqi.googlegroups.com> Hi all, anybody can point me to a description of how the default comparison of list objects (or other iterables) works? Apparently l1 < l2 is equivalent to all ( x < y for x,y in zip( l1, l2) ), has is shown in the following tests, but I can't find it described anywhere: >>> [1,2,3] < [1,3,2] True >>> [1,2,3] < [1,2,4] True >>> [1,2,3] < [2,2,3] True >>> [1,2,3] < [0,1,3] False >>> [1,2,3] < [0,2,3] False >>> [1,2,3] < [1,1,3] False >>> [1,2,3] < [1,2,2] False Ciao --- FB From nikos.the.gr33k at gmail.com Mon Aug 16 06:57:58 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Mon, 16 Aug 2010 03:57:58 -0700 (PDT) Subject: Problem checking an existing browser cookie Message-ID: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> # initialize cookie cookie = Cookie.SimpleCookie() cookie.load( os.environ.get('HTTP_COOKIE', '') ) mycookie = cookie.get('visitor') if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| yandex|13448|spider|crawl)', host ) is None: blabla... ======================== I checked and Chrome has a cookie names visitor with a value of nikos within. So, i have to ask why the if fails? Thank you. From efotinis at oohay.com Mon Aug 16 07:06:30 2010 From: efotinis at oohay.com (eliasf) Date: Mon, 16 Aug 2010 14:06:30 +0300 Subject: Comparing lists References: <5f89432d-47a0-405f-9601-7f04a7818248@c10g2000yqi.googlegroups.com> Message-ID: On Mon, 16 Aug 2010 13:46:07 +0300, Francesco Bochicchio wrote: > anybody can point me to a description of how the default comparison of > list objects (or other iterables) works? Sequences of the same type are compared using lexicographical ordering: http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types From hnsri49 at gmail.com Mon Aug 16 07:07:52 2010 From: hnsri49 at gmail.com (srinivas hn) Date: Mon, 16 Aug 2010 17:07:52 +0600 Subject: MS Word Document to html conversion Message-ID: Hi, I am working on application where it requires uploaded document from has to be converted to the html pages.Am searching for the suitable python package i dint found any thing apart from word2html.py.But the word2html.py is not available for download anywhere can any one suggest me how to solve this problem. Thanks in advance Srinivas HN -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:13:17 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:13:17 GMT Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> Message-ID: <4c691d4c$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 01:52:52 -0700, Kruptein wrote: > I still keep getting more downloads then usual which is awesome, but I > still don't get any kind of response! Welcome to the real world. For every user who sends you an email, you'll probably have 1000 who don't. Or 10,000. > please mail me or reply to this > post with what you think, You can tell me that the program sucks but if > you want to, do it in such a way that you also describe what exactly is > the problem and not just say "the total" You've asked for feedback at least three times now. It's probably time to stop hassling people. When you have another release ready, then you can ask again. Until then, be grateful that people are at least downloading it! > I really need some response because I'm working on version 0.2.1 and I > want to know what there should be changed/added If nobody asks for any changes, then just keep doing what you're doing. -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:17:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:17:11 GMT Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: <4c691e37$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 16:28:46 +1200, Lawrence D'Oliveiro wrote: > In message <8crg0eFfbkU1 at mid.individual.net>, Gregory Ewing wrote: > >> For example, the constant term of a polynomial is usually called term >> 0, not term 1. > > That is not some kind of ordinal numbering of the terms, that is the > power of the variable involved. > > And polynomials can have negative powers, too. Not so. Polynomials, by definition, are limited to non-negative integer powers. You're thinking of a "polynomial quotient", otherwise known as a "rational function". http://mathworld.wolfram.com/Polynomial.html -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:18:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:18:11 GMT Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: <4c691e73$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 21:01:04 -0700, Carey Tilden wrote: > On Sun, Aug 15, 2010 at 6:43 PM, bvdp wrote: > >> Not to belabor the point .. but "func" is not a standard lib module. >> It's part of a much larger application ... and in that application it >> makes perfect sense to terminate the application if it encounters an >> error. I fail to see the problem with this. Why would an APPLICATION >> raise a error or not exit to the system? > > For me, the main reason is to ensure the application has only one exit > point. There's only one spot to maintain the code for closing files, > cleaning up network connections, displaying errors to the user, etc. You mean all the things that Python's garbage collector already does for you? *wink* -- Steven From malcolm.mclean5 at btinternet.com Mon Aug 16 07:20:22 2010 From: malcolm.mclean5 at btinternet.com (Malcolm McLean) Date: Mon, 16 Aug 2010 04:20:22 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <93c048b8-013d-425f-ac69-c112f12ddaa3@v41g2000yqv.googlegroups.com> On Aug 16, 10:20?am, Standish P wrote: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? > Most programs can be written so that most of their memory allocations are matched by destructors at the same level. However the allocations that can't be written this way typically tend to be the small frequently-called ones used for nodes in dynamic graph objects, or small resizeable buffers to hold strings and the like. This is where you get the performance hit with repeated calls to malloc() and free(). So generally it's not worthwhile writing a stack allocator for a normal program. That's not to say there aren't a few individual cases where it can help performance. (See the chapter "Memory games" in my book Basic Agorithms for details about memory allocation strategies). From __peter__ at web.de Mon Aug 16 07:22:28 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Aug 2010 13:22:28 +0200 Subject: Comparing lists References: <5f89432d-47a0-405f-9601-7f04a7818248@c10g2000yqi.googlegroups.com> Message-ID: Francesco Bochicchio wrote: > Hi all, > > anybody can point me to a description of how the default comparison of > list objects (or other iterables) works? > > Apparently l1 < l2 is equivalent to all ( x < y for x,y in > zip( l1, l2) ), has is shown in the following tests, but I can't find > it described anywhere: > >>>> [1,2,3] < [1,3,2] > True >>>> [1,2,3] < [1,2,4] > True >>>> [1,2,3] < [2,2,3] > True >>>> [1,2,3] < [0,1,3] > False >>>> [1,2,3] < [0,2,3] > False >>>> [1,2,3] < [1,1,3] > False >>>> [1,2,3] < [1,2,2] > False > > > Ciao > --- > FB Quoting http://docs.python.org/reference/expressions.html """ Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length. If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]). """ From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:23:02 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:23:02 GMT Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> Message-ID: <4c691f96$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 17:36:07 -0700, Alex Willmer wrote: > On Aug 16, 1:07?am, Steven D'Aprano cybersource.com.au> wrote: >> You're passing re.IGNORECASE (which happens to equal 2) as a count >> argument, not as a flag. Try this instead: >> >> >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) >> 'Python27' > > Basically right, but in-line flags must be placed at the start of a > pattern, or the result is undefined. Pardon me, but that's clearly not correct, as proven by the fact that the above example works. You can say that the flags *should* go at the start, for the sake of efficiency, or ease of comprehension, or tradition, or to appease the Regex Cops who roam the streets beating up those who don't write regexes in the approved fashion. But it isn't true that they *must* go at the front. -- Steven From martin at address-in-sig.invalid Mon Aug 16 07:25:20 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Mon, 16 Aug 2010 11:25:20 +0000 (UTC) Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: On Mon, 16 Aug 2010 12:33:51 +1200, Gregory Ewing wrote: > Ian Kelly wrote: >> On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie >> wrote: > >>> real sample[-500:750]; > >> Ugh, no. The ability to change the minimum index is evil. > > Not always; it can have its uses, particularly when you're using the > array as a mapping rather than a collection. > Say you have intensity data captured from an X-ray goniometer from 160 degrees to 30 degrees at 0.01 degree resolution. Which is most evil of the following? 1) real intensity[16000:3000] for i from lwb intensity to upb intensity plot(i/100, intensity[i]); 2) double angle[13000]; double intensity[13000]; for (int i = 0; i < 13000; i++) plot(angle[i], intensity[i]); 3) struct { double angle; double intensity } measurement; measurement m[13000]; for (int i = 0; i < 13000; i++) plot(m[i].angle, m[i].intensity); 4) double intensity[13000]; for (int i = 0; i < 13000; i++) plot((16000 - i)/100, intensity[i]) To my mind (1) is much clearer to read and far less error-prone to write, while zero-based indexing forces you to use code like (2), (3) or (4), all of which obscure rather than clarify what the program is doing. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From __peter__ at web.de Mon Aug 16 07:26:09 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Aug 2010 13:26:09 +0200 Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> <4c691d4c$0$11100$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 16 Aug 2010 01:52:52 -0700, Kruptein wrote: > >> I still keep getting more downloads then usual which is awesome, but I >> still don't get any kind of response! > > Welcome to the real world. For every user who sends you an email, you'll > probably have 1000 who don't. Or 10,000. > > >> please mail me or reply to this >> post with what you think, You can tell me that the program sucks but if >> you want to, do it in such a way that you also describe what exactly is >> the problem and not just say "the total" > > You've asked for feedback at least three times now. It's probably time to > stop hassling people. When you have another release ready, then you can > ask again. Until then, be grateful that people are at least downloading > it! > > >> I really need some response because I'm working on version 0.2.1 and I >> want to know what there should be changed/added > > If nobody asks for any changes, then just keep doing what you're doing. Or you can introduce a bug; if your users don't start complaining you don't have any... Peter From __peter__ at web.de Mon Aug 16 07:31:31 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Aug 2010 13:31:31 +0200 Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> Message-ID: ????? wrote: > # initialize cookie > cookie = Cookie.SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > mycookie = cookie.get('visitor') > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > yandex|13448|spider|crawl)', host ) is None: > blabla... > ======================== > > I checked and Chrome has a cookie names visitor with a value of nikos > within. > So, i have to ask why the if fails? Maybe it's because != != == From nadiasvertex at gmail.com Mon Aug 16 07:40:12 2010 From: nadiasvertex at gmail.com (Christopher) Date: Mon, 16 Aug 2010 04:40:12 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> Message-ID: <0e5c2967-e617-4423-a0ee-675d76c8cb47@l6g2000yqb.googlegroups.com> On Aug 15, 8:07?pm, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 16:45:49 -0700, Christopher wrote: > > I have the following problem: > > >>>> t="Python26" > >>>> import re > >>>> re.sub(r"python\d\d", "Python27", t) > > 'Python26' > >>>> re.sub(r"python\d\d", "Python27", t, re.IGNORECASE) > > 'Python26' > >>>> re.sub(r"Python\d\d", "Python27", t, re.IGNORECASE) > > 'Python27' > > Is this a known bug? ?Is it by design for some odd reason? > >>> help(re.sub) > > Help on function sub in module re: > > ? ? sub(pattern, repl, string, count=0) > ? ? ... > > You're passing re.IGNORECASE (which happens to equal 2) as a count > argument, not as a flag. Try this instead: > > >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) > > 'Python27' > Thanks. Somehow I didn't notice that other argument after looking at it a million times. :-) From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 07:44:06 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 11:44:06 GMT Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: <4c692485$0$11100$c3e8da3@news.astraweb.com> On Sun, 15 Aug 2010 18:43:49 -0700, bvdp wrote: [...] > However, I have gotten hit with more than one comment like yours. So, > could you please clarify? Is it bad form to exit an application with > sys.exit(1) when an error in a file the application is processing is > found? My two cents worth... The distinction I like to make is between *planned* and *unplanned* exits. Planned exits are things like the user choosing Quit from the menu, or a command line tool exiting after printing a usage message. "Exit the application" is part of the application's user interface, and therefore it is appropriate to exit the application. These aren't errors, the exception isn't called "SystemError" but SystemExit, and it's not necessary to print a traceback. Such exits should usually only exist in the front-end (user-interface) code, rarely or never in the back-end. But *unplanned* exits are errors, and so you should not disguise them as planned exits by raising SystemExit, any more than you would disguise them as a keyboard interruption by raising KeyboardInterrupt. Raise an appropriate exception, and let Python's normal exception-handling code clean up and exit for you. I make one more design choice: if there's an unrecoverable error in user input (as opposed unexpectedly bad data or a program bug), I suppress the traceback, but any other unrecoverable error, I allow it to print. Something vaguely like this: if __name__ == '__main__': try: main() except getopt.GetoptError, e: # Unrecoverable error in command line options. print e.args[0] sys.exit(42) # or whatever value is appropriate except Exception, e: log_exception(e) # whatever... raise SystemExit won't be caught, and will just exit normally. Any other exception won't be caught either, but will lead to a traceback. -- Steven From jeanmichel at sequans.com Mon Aug 16 07:48:48 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 16 Aug 2010 13:48:48 +0200 Subject: Dump logging configuration In-Reply-To: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> References: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> Message-ID: <4C6925A0.8090701@sequans.com> Kxepal wrote: > Hi all! > Sorry for dumb question if it is - I'd tried to google it before but > have found nothing. > > Is there any way to dump current logging configuration for future > loading it via fileConfig/dictConfig? > I may be wrong but I don't think so. JM From cournape at gmail.com Mon Aug 16 07:54:21 2010 From: cournape at gmail.com (David Cournapeau) Date: Mon, 16 Aug 2010 20:54:21 +0900 Subject: Python "why" questions In-Reply-To: <8crg0eFfbkU1@mid.individual.net> References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing wrote: >> On Aug 7, 2010, at 9:14 PM, John Nagle wrote: >> >>> ?The languages which have real multidimensional arrays, rather >>> than arrays of arrays, tend to use 1-based subscripts. ?That >>> reflects standard practice in mathematics. > > Not always -- mathematicians use whatever starting index is > most convenient for the problem at hand. Yes, there are many engineering fields where index starts at 0. Partly for the reason you have stated concerning polynomials, especially since this extend to series, which are pervasive in numerical computing. In linear algebra, though, I remember to have always noted matrices indexes in the [1,n] range, not [0,n-1]. In general, I suspect this is much more a tradition than any kind of very reasoned thinking (and conversely, I find most arguments for 0-indexing and against one-indexing rather ... unconvincing. What's awkward is when you have to constantly change from one to the other). cheers, David From jah.alarm at gmail.com Mon Aug 16 08:05:34 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Mon, 16 Aug 2010 05:05:34 -0700 (PDT) Subject: Textvariable display in label (GUI design) Message-ID: <993d9560-564d-47f0-b2db-6f0c6404ae81@g6g2000pro.googlegroups.com> hi, pls help me out with the following issue: I wrote a function that uses a for loop that changes a value of a certain variable each iteration. What I want is by clicking a button in GUI (with the command bound to this function) this value each iteration is displayed in a textbox (label). So far only one (starting value) is displayed. thanks, Alex From spinoza1111 at yahoo.com Mon Aug 16 08:08:00 2010 From: spinoza1111 at yahoo.com (spinoza1111) Date: Mon, 16 Aug 2010 05:08:00 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: On Aug 16, 3:20?pm, Standish P wrote: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? > > Because a stack has push and pop, it is able to release and allocate > memory. We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. > > The algorithm using the stack would have to be "perfect" to prevent > stack overflow or condition of infinite recursion depth. This would > involve data type checking to filter out invalid input. The task must > be casted in an algorithm that uses the stack. Then the algorithm must > be shown to be heuristically or by its metaphor, to be correct using > informal reasoning. > > Are there any standard textbooks or papers that show stacks > implemented in C/C++/Python/Forth with malloc/free in push and pop ? > If Forth is a general processing language based on stack, is it > possible to convert any and all algorithms to stack based ones and > thus avoid memory leaks since a pop automatically releases memory when > free is an intrinsic part of it. > > K&R ANSI has the example of modular programming showing how to > implement a stack but he uses a fixed length array. It is also > possibly an endogenous stack. We look for an exogenous stack so that > element size can vary. > > ======= > Standish P Garbage collection doesn't use a stack. It uses a "heap", which is in the abstract a collection of memory blocks of different lengths, divided into two lists, generally represented as linked lists: 1. A list of blocks that are free and may be used to store new data 2. A list of blocks that are in use, or haven't been freed (yet) There is no way you could do memory management of all but the most trivial and fixed-length data chunks using a stack. Sure, you could reserve thousands of bytes on the stack for an array but suppose your language allows arrays to grow or shrink. To keep its property of being adjacent, you'd have to do something horrible such as move unrelated data allocated later, which raises all sorts of security issues, doesn't it. A stack, or something which works like a stack (that is, a stack) is a necessary but not sufficient condition for a working C runtime because C functions can call themselves recursively, whether directly or indirectly. If this last condition did not obtain, each function could give the functions it calls some of its own memory and the called function could save a fixed set of non-stacked general registers in that area; this was in fact the practice on IBM 370 and in assembler language at a time when many "data processing managers" though recursion was a Communist plot. However, data structures of variable size, or data structures that merely take up a lot of space, don't play nice with others on the stack, so, we place their address on the stack and store them in another place, which was named the heap, probably, as a sort of witticism. Gilbert and Sullivan: If anyone anything lacks He'll find it all ready in stacks was wrong, and needs to be brought up to date: You cannot do everything in a stack Unless you code an almighty hack If you're a coding Knight who says, "Neep", You'll probably need to implement a heap A pile a heap of benefits you'll reap If only my advice in your brain you'll keep And avoid memory leaks from which data doth seep By using a well-implemented, well structured, and well-documented Heap! [Chorus of Sailors] We will to heart your advice take, and always use a heap! [Soloist] Oh thank you do To this be true And always my sage advice do keep That you always need to use a heap! From spinoza1111 at yahoo.com Mon Aug 16 08:14:35 2010 From: spinoza1111 at yahoo.com (spinoza1111) Date: Mon, 16 Aug 2010 05:14:35 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <93c048b8-013d-425f-ac69-c112f12ddaa3@v41g2000yqv.googlegroups.com> Message-ID: <7e095f76-b69f-4abe-b5ae-53844972fc6c@g21g2000prn.googlegroups.com> On Aug 16, 7:20?pm, Malcolm McLean wrote: > On Aug 16, 10:20?am, Standish P wrote:> [Q] How far can stack [LIFO] solve do automatic garbage collection and > > prevent memory leak ? > > Most programs can be written so that most of their memory allocations > are matched by destructors at the same level. > > However the allocations that can't be written this way typically tend > to be the small frequently-called ones used for nodes in dynamic graph > objects, or small resizeable buffers to hold strings and the like. > This is where you get the performance hit with repeated calls to > malloc() and free(). > > So generally it's not worthwhile writing a stack allocator for a > normal program. That's not to say there aren't a few individual cases > where it can help performance. (See the chapter "Memory games" in my > book Basic Agorithms for details about memory allocation strategies). Even if it's a troll, it was droll. In a language that of necessity has a runtime stack or something that works like a stack (eg., a stack) one finds that the need for explicit stacks is lessened. For example, in my compiler for [start shameless plug] "Build Your Own .Net Language and Compiler [end shameless plug] I did not need to use an explicit stack to do recursive descent. Instead, I simply called finer grained procedures, passing the compiler state as a parameter, allowing the runtime stack to manage the return. To build an explicit stack in this program would have been folly, for it would have been necessary to either preallocate the stack and thus legislate the maximum complexity of source code, or use a lot of memory management in the pre-existing runtime heap. You didn't tell us you published a book. Can you identify the publisher? From efotinis at oohay.com Mon Aug 16 08:34:07 2010 From: efotinis at oohay.com (eliasf) Date: Mon, 16 Aug 2010 15:34:07 +0300 Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> <4c691d4c$0$11100$c3e8da3@news.astraweb.com> Message-ID: On Mon, 16 Aug 2010 14:26:09 +0300, Peter Otten <__peter__ at web.de> wrote: > Steven D'Aprano wrote: >> If nobody asks for any changes, then just keep doing what you're doing. > Or you can introduce a bug; if your users don't start complaining you don't > have any... Even that doesn't work. They may blog or tweet about it, complain on foreign forums, and set up petitions about it, but they will never, EVER send you an email. It's very disheartening. From alex at moreati.org.uk Mon Aug 16 08:46:17 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Mon, 16 Aug 2010 05:46:17 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> <4c691f96$0$11100$c3e8da3@news.astraweb.com> Message-ID: On Aug 16, 12:23?pm, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 17:36:07 -0700, Alex Willmer wrote: > > On Aug 16, 1:07?am, Steven D'Aprano > cybersource.com.au> wrote: > >> You're passing re.IGNORECASE (which happens to equal 2) as a count > >> argument, not as a flag. Try this instead: > > >> >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) > >> 'Python27' > > > Basically right, but in-line flags must be placed at the start of a > > pattern, or the result is undefined. > > Pardon me, but that's clearly not correct, as proven by the fact that the > above example works. Undefined includes 'might work sometimes'. I refer you to the Python documentation: "Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined." http://docs.python.org/library/re.html#regular-expression-syntax From neilc at norwich.edu Mon Aug 16 09:21:02 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 16 Aug 2010 13:21:02 GMT Subject: Python "why" questions References: <4c681161$0$1624$742ec2ed@news.sonic.net> Message-ID: <8css9uFn0pU1@mid.individual.net> On 2010-08-15, John Nagle wrote: > In retrospect, C's "pointer=array" concept was a terrible > mistake. C arrays are not pointers. -- Neil Cerutti From alex at moreati.org.uk Mon Aug 16 09:33:31 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Mon, 16 Aug 2010 06:33:31 -0700 (PDT) Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> <4c691f96$0$11100$c3e8da3@news.astraweb.com> Message-ID: <56d68b7b-ff6b-4fe8-88c7-a1b68bf0df76@c10g2000yqi.googlegroups.com> On Aug 16, 1:46?pm, Alex Willmer wrote: > "Note that the (?x) flag changes how the expression is parsed. It > should be used first in the expression string, or after one or more > whitespace characters. If there are non-whitespace characters before > the flag, the results are undefined. > "http://docs.python.org/library/re.html#regular-expression-syntax Hmm, I found a lot of instances that place (?iLmsux) after non- whitespace characters http://google.com/codesearch?hl=en&lr=&q=file:\.py[w]%3F$+[^[:space:]%22']%2B\(\%3F[iLmsux]%2B\) including two from the Python unit tests, re_test.py lines 109-110. Perhaps the documentation is overly cautious.. From r.koebler at yahoo.de Mon Aug 16 09:38:14 2010 From: r.koebler at yahoo.de (Roland Koebler) Date: Mon, 16 Aug 2010 15:38:14 +0200 Subject: Simple Python Sandbox In-Reply-To: <4C6756D3.60205@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <20100814232400.GA5205@localhost> <4C6756D3.60205@ixokai.io> Message-ID: <20100816133814.GA22789@localhost> On Sat, Aug 14, 2010 at 07:54:11PM -0700, Stephen Hansen wrote: > How are you implementing refusing-names-beginning-with-underscore, out > of curiosity? I compile the expressions and look into co_names, e.g.: >>> expr = "0 .__class__" >>> c=compile(expr,"","eval") >>> c.co_names ('__class__',) regards, Roland From q_crack at yahoo.com Mon Aug 16 09:38:59 2010 From: q_crack at yahoo.com (Alexandru Ionescu) Date: Mon, 16 Aug 2010 06:38:59 -0700 (PDT) Subject: About UpdateLayeredWindow Message-ID: <272482.95979.qm@web53502.mail.re2.yahoo.com> Hello, In the last two weeks I've been trying to properly use UpdateLayeredWindow in Python but I'm only getting errors. I searched a lot on the internet and you are the only person who posted about using ULW in Python. I tried with ctypes and I also tried with win32gui & win32api. I got all kinds of errors. In the end I got to error code 5 (ERROR_ACCESS_DENIED) and nothing appears on the screen. Please send me a small working example in Python of UpdateLayeredWindow, either using ctypes or win32gui & win32api. My email address is q_crack at yahoo.com Thank you, Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From vikas.mahajan12 at gmail.com Mon Aug 16 09:40:06 2010 From: vikas.mahajan12 at gmail.com (Vikas Mahajan) Date: Mon, 16 Aug 2010 19:10:06 +0530 Subject: passing variables as object attributes Message-ID: Hello to all I am new to python. I am facing problem to use variables as object attributes. I have to use loop and dynamically add attributes to a object and for this purpose I have to use variables with object names. For example-: Let us say object car has an attribute engine, then varname = "engine" car.varname = "dummy value" is giving me Error: object car does not have attribute varname. Please tell me how can I use variables as objects attributes. Thanks. From nitinpawar432 at gmail.com Mon Aug 16 09:53:39 2010 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Mon, 16 Aug 2010 19:23:39 +0530 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: you would need to define a class first with its attiributes and then you may want to initiate the variables by calling the class initilializer On Mon, Aug 16, 2010 at 7:10 PM, Vikas Mahajan wrote: > Hello to all > > I am new to python. I am facing problem to use variables as object > attributes. I have to use loop and dynamically add attributes to a > object and for this purpose I have to use variables with object names. > > For example-: > Let us say object car has an attribute engine, then > varname = "engine" > car.varname = "dummy value" > is giving me Error: object car does not have attribute varname. > > Please tell me how can I use variables as objects attributes. > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.koebler at yahoo.de Mon Aug 16 10:01:42 2010 From: r.koebler at yahoo.de (Roland Koebler) Date: Mon, 16 Aug 2010 16:01:42 +0200 Subject: Simple Python Sandbox In-Reply-To: <4C67586C.3020107@ixokai.io> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4C67586C.3020107@ixokai.io> Message-ID: <20100816140142.GB22789@localhost> On Sat, Aug 14, 2010 at 08:01:00PM -0700, Stephen Hansen wrote: > > As you can see, black listing isn't the best approach here. > > But I have a two pronged strategy: the black list is only half of the > equation. One, I'm blacklisting all the meta functions out of builtins. But blacklists are *never* secure. Sorry, but you should fully understand this before even thinking about more detailed security. Why are you blacklisting the "known-bad" functions instead of whitelising the allowed ones?? regards, Roland From egbertum at xs4all.nl Mon Aug 16 10:02:35 2010 From: egbertum at xs4all.nl (egbert) Date: Mon, 16 Aug 2010 16:02:35 +0200 Subject: When the first line of a file tells something about the other lines In-Reply-To: References: Message-ID: <20100816140235.GA9843@xs4all.nl> On Mon, Aug 16, 2010 at 11:59:57AM +0200, Peter Otten wrote: > > with open(filename) as lines: > first_line = next(lines, "") > if special(first_line): > # ... > else: > lines = itertools.chain([first_line], lines) > for line in lines: > # ... Beautiful. And a nice suggestion to read the itertools docs. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From vikas.mahajan12 at gmail.com Mon Aug 16 10:08:15 2010 From: vikas.mahajan12 at gmail.com (Vikas Mahajan) Date: Mon, 16 Aug 2010 19:38:15 +0530 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: On 16 August 2010 19:23, Nitin Pawar wrote: > you would need to define a class first with its attiributes and then you may > want to initiate the variables by calling the class initilializer > Actually I have to dynamically add attributes to a object. I am writing python script for FreeCAD software. I am using loop to create multiple cylinders and I am writing following code-: cyname = "Cylinder" FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) FreeCAD.ActiveDocument.cyname.Radius= .5 FreeCAD.ActiveDocument.cyname.Height= 10 And I am getting this error-: AttributeError: 'App.Document' object has no attribute 'cyname' But when I use Cylinder in place of cyname, I am not getting any error. Please help. Thanks. From stef.mientki at gmail.com Mon Aug 16 10:27:53 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 16 Aug 2010 16:27:53 +0200 Subject: does someone has a binary 32-bit windows installer for arac ? Message-ID: <4C694AE9.2000907@gmail.com> thanks, Stef Mientki From pruebauno at latinmail.com Mon Aug 16 10:28:10 2010 From: pruebauno at latinmail.com (nn) Date: Mon, 16 Aug 2010 07:28:10 -0700 (PDT) Subject: passing variables as object attributes References: Message-ID: <53e8ac38-57f5-4830-889e-5295ee9e7dbf@q22g2000yqm.googlegroups.com> On Aug 16, 10:08?am, Vikas Mahajan wrote: > On 16 August 2010 19:23, Nitin Pawar wrote:> you would need to define a class first with its attiributes and then you may > > want to initiate the variables by calling the class initilializer > > Actually I have to dynamically add attributes to a object. I am > writing python script for ?FreeCAD software. I am using loop to create > multiple cylinders and I am writing following code-: > cyname = "Cylinder" > FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) > FreeCAD.ActiveDocument.cyname.Radius= .5 > FreeCAD.ActiveDocument.cyname.Height= 10 > > And I am getting this error-: > AttributeError: 'App.Document' object has no attribute 'cyname' > > But when I use Cylinder in place of cyname, I am not getting any error. > > Please help. > > Thanks. From pruebauno at latinmail.com Mon Aug 16 10:30:07 2010 From: pruebauno at latinmail.com (nn) Date: Mon, 16 Aug 2010 07:30:07 -0700 (PDT) Subject: passing variables as object attributes References: Message-ID: On Aug 16, 10:08?am, Vikas Mahajan wrote: > On 16 August 2010 19:23, Nitin Pawar wrote:> you would need to define a class first with its attiributes and then you may > > want to initiate the variables by calling the class initilializer > > Actually I have to dynamically add attributes to a object. I am > writing python script for ?FreeCAD software. I am using loop to create > multiple cylinders and I am writing following code-: > cyname = "Cylinder" > FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) > FreeCAD.ActiveDocument.cyname.Radius= .5 > FreeCAD.ActiveDocument.cyname.Height= 10 > > And I am getting this error-: > AttributeError: 'App.Document' object has no attribute 'cyname' > > But when I use Cylinder in place of cyname, I am not getting any error. > > Please help. > > Thanks. This might work: cyname = "Cylinder" FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) getattr(FreeCAD.ActiveDocument,cyname).Radius= .5 getattr(FreeCAD.ActiveDocument,cyname).Height= 10 From chrischia82 at gmail.com Mon Aug 16 10:30:08 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Mon, 16 Aug 2010 07:30:08 -0700 (PDT) Subject: how to switch image in tkinter? making it mutable? how? Message-ID: <414ff6dd-73ef-48df-bd2b-080a2c710e5b@h17g2000pri.googlegroups.com> I have this: image1 = ImageTk.PhotoImage(file = "c:\\f1.jpg") image2 = ImageTk.PhotoImage(file = "c:\\f2.jpg") imagelist.append(image1) imagelist.append(image2) self.label = tk.Label(image = imagelist[0]) is there a way that i can create a method to switch the display the image2 (imagelist 2nd element) without using label.bind? can i make an image mutable? From jeanmichel at sequans.com Mon Aug 16 10:53:44 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 16 Aug 2010 16:53:44 +0200 Subject: Dump logging configuration In-Reply-To: <4C6925A0.8090701@sequans.com> References: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> <4C6925A0.8090701@sequans.com> Message-ID: <4C6950F8.1050205@sequans.com> Jean-Michel Pichavant wrote: > Kxepal wrote: >> Hi all! >> Sorry for dumb question if it is - I'd tried to google it before but >> have found nothing. >> >> Is there any way to dump current logging configuration for future >> loading it via fileConfig/dictConfig? >> > I may be wrong but I don't think so. > > JM Please understand that I don't think such feature exists (to oppose to thinking that I'm not wrong :o) ) JM From jackokring at gmail.com Mon Aug 16 10:59:40 2010 From: jackokring at gmail.com (jacko) Date: Mon, 16 Aug 2010 07:59:40 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: > is it possible to convert any and all algorithms to stack based ones and thus avoid memory leaks? No, not really. If you keep the allocated things and free them in reverse order on exit, then well yes, but practically, early free() frees memory for reuse on low memory systems. In this sense not 'reversed' out of order free is essential in some contexts. The question then becomes what is the best heap fragmentation/ compaction strategy and what is the best allocation algorithm to allocate addresses? From ian.g.kelly at gmail.com Mon Aug 16 11:04:29 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 16 Aug 2010 11:04:29 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> Message-ID: On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries wrote: >> I suspect that there exists a largest unpurchasable quantity iff at >> least two of the pack quantities are relatively prime, but I have made >> no attempt to prove this. > > That for sure is not correct; packs of 2, 4 and 7 do have a largest > unpurchasable quantity. 2 and 7 are relatively prime, so this example fits my hypothesis. > I'm pretty sure that if there's no common divisor for all three (or more) > packages (except one), there is a largest unpurchasable quantity. That is: ? > i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x|y) means "x is no divider of y" No. If you take the (2,4,7) example and add another pack size of 14, it does not cause quantities that were previously purchasable to become unpurchasable. Ian From steve.ferg.bitbucket at gmail.com Mon Aug 16 11:17:20 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Mon, 16 Aug 2010 08:17:20 -0700 (PDT) Subject: question about pdb assignment statements Message-ID: In this little script:
 import pdb
 pdb.set_trace()
 def main():
     xm = 123
     print("Hello,world!")
 main()
 
When I run this, I use pdb to step through it until I reach the point in main() where the xm variable has been initialized, and then I try to use pdb to reset the value of xm, and I can't. Does anybody know why? As I understand the documentation, http://docs.python.org/library/pdb.html I *should* be able to do this. [!]statement Execute the (one-line) statement in the context of the current stack frame. Is there something about "in the context of the current stack frame" that I don't understand? Or is it a bug (or a limitation) in pdb? From eric.brunel at pragmadev.nospam.com Mon Aug 16 11:27:17 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Mon, 16 Aug 2010 17:27:17 +0200 Subject: how to switch image in tkinter? making it mutable? how? References: <414ff6dd-73ef-48df-bd2b-080a2c710e5b@h17g2000pri.googlegroups.com> Message-ID: In article <414ff6dd-73ef-48df-bd2b-080a2c710e5b at h17g2000pri.googlegroups.com>, ChrisChia wrote: > I have this: > image1 = ImageTk.PhotoImage(file = "c:\\f1.jpg") > image2 = ImageTk.PhotoImage(file = "c:\\f2.jpg") > > imagelist.append(image1) > imagelist.append(image2) > > self.label = tk.Label(image = imagelist[0]) > > is there a way that i can create a method to switch the display the > image2 (imagelist 2nd element) > without using label.bind? > > can i make an image mutable? Unfortunately, I don't know the package ImageTk you're using. But at tk level, images are mutable without problem. It seems however that the tcl commands allowing to read an existing image from a file are not exposed at Tkinter level. But it is still possible to send the command to the underlying tcl interpreter to do it: from Tkinter import * root = Tk() image = PhotoImage(file='f1.gif') label = Label(root, image=image) ## When you want to change the image: root.tk.call(image, 'read', 'f2.gif', '-shrink') This will only work with image formats supported in the tcl/tk core, which are basically only GIF so far. BTW, I don't understand why you talk about label.bind? If you need to do anything when the label is clicked, you have to make a binding on the label whatever it is. HTH anyway. - Eric - From malcolm.mclean5 at btinternet.com Mon Aug 16 11:31:48 2010 From: malcolm.mclean5 at btinternet.com (Malcolm McLean) Date: Mon, 16 Aug 2010 08:31:48 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <93c048b8-013d-425f-ac69-c112f12ddaa3@v41g2000yqv.googlegroups.com> <7e095f76-b69f-4abe-b5ae-53844972fc6c@g21g2000prn.googlegroups.com> Message-ID: On Aug 16, 3:14?pm, spinoza1111 wrote: > > To build an explicit stack in this program would have been folly, for > it would have been necessary to either preallocate the stack and thus > legislate the maximum complexity of source code, or use a lot of > memory management in the pre-existing runtime heap. > The problem is that if you reallocate the stack, you invalidate all pointers to objects on it. So you have to use handles instead. At which point you might as well admit that you are no longer programming in C. > > > You didn't tell us you published a book. Can you identify the > publisher?- Hide quoted text - > It's a print on demand, by Lulu. O'Reilley said they liked it but they couldn't sell books on C. (I've an open invitation to write a computer book for them in another language). I don't really recommend print on demand. The nice thing is that you can sell the book for about half the price it would cost under a traditional publishing model. The problem is that people still use acceptance by a traditional publisher as a filter. From eric.brunel at pragmadev.nospam.com Mon Aug 16 11:32:51 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Mon, 16 Aug 2010 17:32:51 +0200 Subject: Textvariable display in label (GUI design) References: <993d9560-564d-47f0-b2db-6f0c6404ae81@g6g2000pro.googlegroups.com> Message-ID: In article <993d9560-564d-47f0-b2db-6f0c6404ae81 at g6g2000pro.googlegroups.com>, Jah_Alarm wrote: > hi, > > pls help me out with the following issue: I wrote a function that uses > a for loop that changes a value of a certain variable each iteration. > What I want is by clicking a button in GUI (with the command bound to > this function) this value each iteration is displayed in a textbox > (label). So far only one (starting value) is displayed. > > thanks, > > Alex First, with posts like this, you're highly unlikely to get any useful answer: please strip down your code to the smallest part that displays the problem, post this code here, explaining what you're expecting and what you're getting. Otherwise, people just won't know what you're talking about unless they have a crystal ball? Now using my own crystal ball: if you don't return the control to the GUI each time your variable is increased, the GUI won't get a chance to update itself. Since you seem to use Tkinter (another wild guess?), you probably need a call to the update_idletasks method on any Tkinter widget each time you change your TextVariable. HTH - Eric - From daniel.harjanto at gmail.com Mon Aug 16 11:34:08 2010 From: daniel.harjanto at gmail.com (misterdi) Date: Mon, 16 Aug 2010 08:34:08 -0700 (PDT) Subject: passing variables as object attributes References: Message-ID: On Aug 16, 8:40?pm, Vikas Mahajan wrote: > Hello to all > > I am new to python. I am facing problem to use variables as object > attributes. I have to use loop and dynamically add attributes to a > object and for this purpose I have to use variables with object names. > > For example-: > Let us say object car has an attribute engine, then > varname = "engine" > car.varname = "dummy value" > is giving me Error: object car does not have attribute varname. > > Please tell me how can I use variables as objects attributes. > > Thanks. I'm not a python expert, so this may not be accurate For me it is easier to define a class that represent the object, and then set attribute for the object. for example : # define a class with no attribute class Car(): pass # instance the class mycar = Car() # dynamically set attribute to the instance newattr = "engine" setattr(mycar, newattr, "dummy value") # or dynamically set attribute to the Class so every instance will inherit it classattr = "color" setattr(mycar, classattr, "yellow") But as I mention, I'm not an expert so maybe it's not a pythonic way to add attribute to an object. Cheers, From kxepal at gmail.com Mon Aug 16 11:40:50 2010 From: kxepal at gmail.com (Kxepal) Date: Mon, 16 Aug 2010 08:40:50 -0700 (PDT) Subject: Dump logging configuration References: <7dffa259-043c-4353-bdb4-15b958f9e430@t2g2000yqe.googlegroups.com> <4C6925A0.8090701@sequans.com> Message-ID: <7093a1d9-294e-4831-a2bf-4e68285d25e3@v8g2000yqe.googlegroups.com> On Aug 16, 6:53?pm, Jean-Michel Pichavant wrote: > Jean-Michel Pichavant wrote: > > Kxepal wrote: > >> Hi all! > >> Sorry for dumb question if it is - I'd tried to google it before but > >> have found nothing. > > >> Is there any way todumpcurrentloggingconfiguration for future > >> loading it via fileConfig/dictConfig? > > > I may be wrong but I don't think so. > > > JM > > Please understand that I don't think such feature exists (to oppose to > thinking that I'm not wrong :o) ) > > JM Ah, you have break my dream, but thanks(: It's a pity, because it very handy feature, but now I see a lot of problems to implement it with current logging flexibility. From darragh.ssa at gmail.com Mon Aug 16 11:41:25 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 16 Aug 2010 08:41:25 -0700 (PDT) Subject: Deditor -- pythonic text-editor References: <82d1692f-53dc-4263-ba5a-3cc47e559ee9@g17g2000yqe.googlegroups.com> <9bee45d9-caff-417c-be48-6d07fd3bde59@z28g2000yqh.googlegroups.com> <4c691d4c$0$11100$c3e8da3@news.astraweb.com> Message-ID: <82fc086c-4a07-404b-a7c2-744c7dc70b6a@x25g2000yqj.googlegroups.com> on steven, peter and eliasf: Well okay I'm new to the world of developing programs, if I encounter problems I directly post a bug on the relevant page, that's maybe why I was a bit frustrated :) but what you three say is indeed true.. From ian.g.kelly at gmail.com Mon Aug 16 11:42:25 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 16 Aug 2010 11:42:25 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> Message-ID: On Mon, Aug 16, 2010 at 11:04 AM, Ian Kelly wrote: > On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries wrote: >>> I suspect that there exists a largest unpurchasable quantity iff at >>> least two of the pack quantities are relatively prime, but I have made >>> no attempt to prove this. >> >> That for sure is not correct; packs of 2, 4 and 7 do have a largest >> unpurchasable quantity. > > 2 and 7 are relatively prime, so this example fits my hypothesis. Although now that I think about it some more, there are counter-examples. For example, the pack sizes (6, 10, 15) have a largest unpurchasable quantity of 29, but no two of those are relatively prime. I'm going to revise my hypothesis to state that a largest unpurchasable quantity exists iff some there exists some relatively prime subset of the pack sizes of cardinality 2 or greater. Cheers, Ian From carey.tilden at gmail.com Mon Aug 16 12:03:30 2010 From: carey.tilden at gmail.com (Carey Tilden) Date: Mon, 16 Aug 2010 09:03:30 -0700 Subject: Pop return from stack? In-Reply-To: <4c691e73$0$11100$c3e8da3@news.astraweb.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> <4c691e73$0$11100$c3e8da3@news.astraweb.com> Message-ID: On Mon, Aug 16, 2010 at 4:18 AM, Steven D'Aprano wrote: > > On Sun, 15 Aug 2010 21:01:04 -0700, Carey Tilden wrote: > >> On Sun, Aug 15, 2010 at 6:43 PM, bvdp wrote: >> >>> Not to belabor the point .. but "func" is not a standard lib module. >>> It's part of a much larger application ... and in that application it >>> makes perfect sense to terminate the application if it encounters an >>> error. I fail to see the problem with this. Why would an APPLICATION >>> raise a error or not exit to the system? >> >> For me, the main reason is to ensure the application has only one exit >> point. ?There's only one spot to maintain the code for closing files, >> cleaning up network connections, displaying errors to the user, etc. > > You mean all the things that Python's garbage collector already does for > you? Are you actually disagreeing with the point or just poking fun at my examples? If the former, well, phooey. If the latter, c'est la vie. > *wink* :-P Carey From jeanmichel at sequans.com Mon Aug 16 12:20:51 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 16 Aug 2010 18:20:51 +0200 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: <4C696563.90401@sequans.com> Vikas Mahajan wrote: > On 16 August 2010 19:23, Nitin Pawar wrote: > >> you would need to define a class first with its attiributes and then you may >> want to initiate the variables by calling the class initilializer >> >> > Actually I have to dynamically add attributes to a object. I am > writing python script for FreeCAD software. I am using loop to create > multiple cylinders and I am writing following code-: > cyname = "Cylinder" > FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) > FreeCAD.ActiveDocument.cyname.Radius= .5 > FreeCAD.ActiveDocument.cyname.Height= 10 > > And I am getting this error-: > AttributeError: 'App.Document' object has no attribute 'cyname' > > But when I use Cylinder in place of cyname, I am not getting any error. > > Please help. > > Thanks. > obj.attribute = 5 <=> setattr(obj, "attribute", 5) obj.attribute <=> getattr(obj, "attribute") So considering your example, getattr(FreeCAD.ActiveDocument, cyname).Radius = .5 should do the trick. JM From zdoor at xs4all.nl Mon Aug 16 12:26:46 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Mon, 16 Aug 2010 18:26:46 +0200 Subject: Opposite of split In-Reply-To: References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl><4C683363.3080305@islandtraining.com><4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c6966c8$0$22937$e4fe514c@news.xs4all.nl> Thanks much, Nope, no homework. This was a serious question from a serious but perhaps simple physicist who grew up with Algol, FORTRAN and Pascal, taught himself VB(A) and is looking for a replacement of VB and finding that in Python. You can guess my age now. Most of my work I do in R nowadays but R is not flexible enough for some file manipulation operations. I use the book by Lutz ("Learning Python"). The join method for strings is in there. I did not have the book at hand and I was jetlagged too. I do apologize for asking a simple question. I had no idea that some would go to the extent of giving trick solutions for simple, supposedly homework questions. Bear in mind Python is a very feature rich language. You cannot expect all newbies to remember everything. By the way, I had a working program that did what I wanted using still simpler string concatenation. Replaced that now by tab.join([lines[i][k][2] for i in range(5)]), k being a loop counter. Judge for yourself. That is the level I am at after 6 weeks of doing excercises from my programming book on Pascal in Python. Thanks for the help. I do hope there is no entry level for using this group. If there is, I won't meet it for a while. Alex van der Spek "D'Arcy J.M. Cain" wrote in message news:mailman.2159.1281917130.1673.python-list at python.org... > On 15 Aug 2010 23:33:10 GMT > Steven D'Aprano wrote: >> Under what possible circumstances would you prefer this code to the >> built- >> in str.join method? > > I assumed that it was a trap for someone asking for us to do his > homework. I also thought that it was a waste of time because I knew > that twenty people would jump in with the correct answer because of > "finally, one that I can answer" syndrome. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From zdoor at xs4all.nl Mon Aug 16 12:29:06 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Mon, 16 Aug 2010 18:29:06 +0200 Subject: EOFError with fileinput Message-ID: <4c696751$0$22940$e4fe514c@news.xs4all.nl> Using the fileinput module to process lists of files: >>>for line in fileinput.input(logs): Unfortunately, EOFError does not seem to indicate the end-of-file condition correctly when using fileinput. How would you find the EOF file for all the files in the file list 'logs'? Thank you, Alex van der Spek From jeff.hobbs at gmail.com Mon Aug 16 12:40:01 2010 From: jeff.hobbs at gmail.com (Jeff Hobbs) Date: Mon, 16 Aug 2010 09:40:01 -0700 (PDT) Subject: python strings and {} in Tkinter entry widgets References: Message-ID: <64720a7d-35a7-4e00-afc1-ed33bc9810ec@g6g2000pro.googlegroups.com> On Aug 15, 4:41?pm, Chris Hare wrote: > I have some code that pulls a value from a database. ?In this case, it is three space delimited words. ?When I display the value in a Tkinter.Entry widget, the text has curly braces around it, even when there are none in the surrounding the text in the database. > > Is this normal, and how do I prevent it or remove them correctly before displaying the text in the Entry widget? Python ['', '', ''] == Tcl {{} {} {}} Python 'a word' == Tcl {a word} You are getting a literal translation occurring, and you need to split/ join or index the items properly. Without being more clear how you want to represent your data, what you need isn't clear. Perhaps you just need to reference the first index of the variable, or ... who knows, there are lots of possibilities. Jeff From downaold at gmail.com Mon Aug 16 12:43:48 2010 From: downaold at gmail.com (Roald de Vries) Date: Mon, 16 Aug 2010 18:43:48 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> Message-ID: On Aug 16, 2010, at 5:04 PM, Ian Kelly wrote: > On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries > wrote: >>> I suspect that there exists a largest unpurchasable quantity iff at >>> least two of the pack quantities are relatively prime, but I have >>> made >>> no attempt to prove this. >> >> That for sure is not correct; packs of 2, 4 and 7 do have a largest >> unpurchasable quantity. > > 2 and 7 are relatively prime, so this example fits my hypothesis. I now notice I misread your post (as 'iff the least two pack quantities are relatively prime') >> I'm pretty sure that if there's no common divisor for all three (or >> more) >> packages (except one), there is a largest unpurchasable quantity. >> That is: ? >> i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x|y) means "x is no >> divider of y" > > No. If you take the (2,4,7) example and add another pack size of 14, > it does not cause quantities that were previously purchasable to > become unpurchasable. Then what is the common divisor of 2, 4, 7 and 14? Not 2 because ?(2| 7), not anything higher than 2 because that's no divisor of 2. Cheers, Roald From zdoor at xs4all.nl Mon Aug 16 12:44:08 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Mon, 16 Aug 2010 18:44:08 +0200 Subject: Opposite of split In-Reply-To: References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl><4C683363.3080305@islandtraining.com><4c687936$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c696ada$0$22941$e4fe514c@news.xs4all.nl> Perhaps the ones here who think I was trying to make you do my homework can actually help me for real. Since I run my own company (not working for any of the big ones) I can't afford official training in anything. So I teach myself, help is always welcome and sought for. If that feels like doing homework for me, so be it. The fact is that I do try to learn Python. It can do things I thought required much more coding. Look at the attached. It builds a concordance table first. That was an excercise from a book on Pascal programming. In Pascal the solution is 2 pages of code. In Python it is 8 lines. Beautiful! Anybody catches any other ways to improve my program (attached), you are most welcome. Help me learn, that is one of the objectives of this newsgroup, right? Or is it all about exchanging the next to impossible solution to the never to happen unreal world problems? Regards, Alex van der Spek "D'Arcy J.M. Cain" wrote in message news:mailman.2159.1281917130.1673.python-list at python.org... > On 15 Aug 2010 23:33:10 GMT > Steven D'Aprano wrote: >> Under what possible circumstances would you prefer this code to the >> built- >> in str.join method? > > I assumed that it was a trap for someone asking for us to do his > homework. I also thought that it was a waste of time because I knew > that twenty people would jump in with the correct answer because of > "finally, one that I can answer" syndrome. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: MergeLog2Auto.py URL: From fuglyducky at gmail.com Mon Aug 16 12:47:44 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Mon, 16 Aug 2010 09:47:44 -0700 (PDT) Subject: Newbie: strftime object error message Message-ID: I am trying to call a function with a couple additional parameters. Unfortunately, for whatever reason I am unable to get this to work. I am assuming that line is not passing correctly but I don't understand why??? I can't share all of the code because it has IP in it but below are the pertinent snippets. Thanks in advance! ################################################################################## PY: 3.1.2 FUNCTION CALL: text_file = open(file_name, "r") for line in text_file: new_foo = pop_time(current_time, line) # current_time = datetime.datetime.now() FUNCTION: def pop_time(line, cur_time): global new_string global current_time # Generate random time between 0 and 30 seconds # Changes the time delta every time function is run rand_time = random.randint(0, 30) delta_time = datetime.timedelta(seconds=rand_time) # Sets the time format for string output format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") ERROR MSG: format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") AttributeError: 'str' object has no attribute 'strftime' NOTE: current_time prints within the function, line does not From jeff.hobbs at gmail.com Mon Aug 16 12:57:47 2010 From: jeff.hobbs at gmail.com (Jeff Hobbs) Date: Mon, 16 Aug 2010 09:57:47 -0700 (PDT) Subject: how to switch image in tkinter? making it mutable? how? References: <414ff6dd-73ef-48df-bd2b-080a2c710e5b@h17g2000pri.googlegroups.com> Message-ID: On Aug 16, 7:30?am, ChrisChia wrote: > I have this: > image1 = ImageTk.PhotoImage(file = "c:\\f1.jpg") > image2 = ImageTk.PhotoImage(file = "c:\\f2.jpg") > > imagelist.append(image1) > imagelist.append(image2) > > self.label ?= tk.Label(image = imagelist[0]) > > is there a way that i can create a method to switch the display the > image2 (imagelist 2nd element) > without using label.bind? > > can i make an image mutable? self.label.configure(image = imagelist[1]) will change the image displayed. With PIL images, you can use image1.fromstring(...) that should have a similar effect, in that it changes the underlying image data and the label will display that. Whether you need to label.bind or something else to effect this change is up to you. You could have it happen on a timer, triggered by an event, or randomly effected by solar flares, depending on your application's needs. Jeff From breamoreboy at yahoo.co.uk Mon Aug 16 12:58:35 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 16 Aug 2010 17:58:35 +0100 Subject: EOFError with fileinput In-Reply-To: <4c696751$0$22940$e4fe514c@news.xs4all.nl> References: <4c696751$0$22940$e4fe514c@news.xs4all.nl> Message-ID: On 16/08/2010 17:29, Alex van der Spek wrote: > Using the fileinput module to process lists of files: > >>>> for line in fileinput.input(logs): > > Unfortunately, EOFError does not seem to indicate the end-of-file > condition correctly when using fileinput. > > How would you find the EOF file for all the files in the file list 'logs'? > > Thank you, > Alex van der Spek I'm not sure exactly what you're asking here. Could you a brief description as to what you're trying to achieve, then put the question again. Cheers. Mark Lawrence. From darcy at druid.net Mon Aug 16 13:04:07 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 16 Aug 2010 13:04:07 -0400 Subject: Opposite of split In-Reply-To: <4c6966c8$0$22937$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c6966c8$0$22937$e4fe514c@news.xs4all.nl> Message-ID: <20100816130407.2ca17c15.darcy@druid.net> On Mon, 16 Aug 2010 18:26:46 +0200 "Alex van der Spek" wrote: > Nope, no homework. This was a serious question from a serious but perhaps > simple physicist who grew up with Algol, FORTRAN and Pascal, taught himself > VB(A) and is looking for a replacement of VB and finding that in Python. You > can guess my age now. > > Most of my work I do in R nowadays but R is not flexible enough for some > file manipulation operations. I use the book by Lutz ("Learning Python"). > The join method for strings is in there. I did not have the book at hand and > I was jetlagged too. I do apologize for asking a simple question. I'm not actually the one that presented the convuluted example. I think the one who did just felt that someone had a question and they were passing it to the group instead of doing a simple Google search. The "solution" he posted looked like something designed to make the teacher scratch his head and ask embarrassing questions of the student. > Thanks for the help. I do hope there is no entry level for using this group. > If there is, I won't meet it for a while. I think that the only thing people expect is that you do a quick search first and show that you have tried first. Some questions have been asked and answered so many times that a search of the archives finds what you want without waiting for an answer. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From vikas.mahajan12 at gmail.com Mon Aug 16 13:05:46 2010 From: vikas.mahajan12 at gmail.com (Vikas Mahajan) Date: Mon, 16 Aug 2010 22:35:46 +0530 Subject: passing variables as object attributes In-Reply-To: <4C696563.90401@sequans.com> References: <4C696563.90401@sequans.com> Message-ID: @All Thanks a lot. getattr and setattr functions solved my problem. From jacky.chao.wang at gmail.com Mon Aug 16 13:06:57 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 10:06:57 -0700 (PDT) Subject: How to convert bytearray into integer? Message-ID: Hi there, Recently I'm facing a problem to convert 4 bytes on an bytearray into an 32-bit integer. So far as I can see, there're 3 ways: a) using struct module, b) using ctypes module, and c) manually manipulation. Are there any other ways? My sample is as following: ----- import struct import ctypes def test_struct(buf, offset): return struct.unpack_from("I", buf, offset)[0] def test_ctypes(buf, offset): return ctypes.c_uint32.from_buffer(buf, offset).value def test_multi(buf, offset): return buf[offset] + (buf[offset+1] << 8) + (buf[offset+2] << 16) + (buf[offset+3] << 24) buf_w = bytearray(5) buf_w[1] = 1 buf_r = buffer(buf_w) if __name__ == '__main__': import timeit t1 = timeit.Timer("test_struct(buf_r, 1)", "from __main__ import test_struct, buf_r") t2 = timeit.Timer("test_ctypes(buf_w, 1)", "from __main__ import test_ctypes, buf_w") t3 = timeit.Timer("test_multi(buf_w, 1)", "from __main__ import test_multi, buf_w") print t1.timeit(number=1000) print t2.timeit(number=1000) print t3.timeit(number=1000) ----- Yet the results are bit confusing: ----- number = 10000 0.0081958770752 0.012549161911 0.0112121105194 number = 1000 0.00087308883667 0.00125789642334 0.00110197067261 number = 100 0.0000917911529541 # 9.17911529541e-05 0.000133991241455 0.00011420249939 number = 10 1.69277191162e-05 2.19345092773e-05 1.69277191162e-05 number = 1 1.00135803223e-05 1.00135803223e-05 5.96046447754e-06 ----- As the number of benchmarking loops decreasing, method c which is manually manipulating overwhelms the former 2 methods. However, if number == 10K, the struct method wins. Why does it happen? Thanks, Jacky (jacky.chao.wang#gmail.com) From chare at labr.net Mon Aug 16 13:11:58 2010 From: chare at labr.net (Chris Hare) Date: Mon, 16 Aug 2010 12:11:58 -0500 Subject: python strings and {} in Tkinter entry widgets In-Reply-To: <64720a7d-35a7-4e00-afc1-ed33bc9810ec@g6g2000pro.googlegroups.com> References: <64720a7d-35a7-4e00-afc1-ed33bc9810ec@g6g2000pro.googlegroups.com> Message-ID: <11151F2F-7BEA-4D75-95B7-B64FB47D4EA5@labr.net> On Aug 16, 2010, at 11:40 AM, Jeff Hobbs wrote: > On Aug 15, 4:41 pm, Chris Hare wrote: >> I have some code that pulls a value from a database. In this case, it is three space delimited words. When I display the value in a Tkinter.Entry widget, the text has curly braces around it, even when there are none in the surrounding the text in the database. >> >> Is this normal, and how do I prevent it or remove them correctly before displaying the text in the Entry widget? > > Python ['', '', ''] == Tcl {{} {} {}} > Python 'a word' == Tcl {a word} > > You are getting a literal translation occurring, and you need to split/ > join or index the items properly. Without being more clear how you > want to represent your data, what you need isn't clear. Perhaps you > just need to reference the first index of the variable, or ... who > knows, there are lots of possibilities. > > Jeff > -- > http://mail.python.org/mailman/listinfo/python-list Actually I want all of the words, as they form the name of an organization entered by the user. So the space delimited words should be displayed without the {} in the tkinker entry box. The contents of the widget is a persons first and last name, space delimited From darcy at druid.net Mon Aug 16 13:17:29 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 16 Aug 2010 13:17:29 -0400 Subject: Opposite of split In-Reply-To: <4c696ada$0$22941$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> Message-ID: <20100816131729.aa587dc3.darcy@druid.net> On Mon, 16 Aug 2010 18:44:08 +0200 "Alex van der Spek" wrote: > Perhaps the ones here who think I was trying to make you do my homework can You keep replying to my message but as I pointed out in my previous message, I'm not the one who thought that you posted a homework question. I'm the one who thought that the other poster thought that you posted a homework question. Honestly, while I thought it was a question that could have been answered faster with a Google search, it did not look like a homework question to me. > actually help me for real. Since I run my own company (not working for any > of the big ones) I can't afford official training in anything. So I teach > myself, help is always welcome and sought for. If that feels like doing > homework for me, so be it. Well, it is "home" work but there is nothing wrong with asking for help anyway. When people complain about homework questions it is generally because someone has posted the question verbatim from the assignment and asks for a complete solution. That's annoying. What you have done here is good because you show some work and ask for help with it. Slightly better would be to ask specific questions about areas that you are struggling with but this is good. > The fact is that I do try to learn Python. It can do things I thought > required much more coding. Look at the attached. It builds a concordance > table first. That was an excercise from a book on Pascal programming. In > Pascal the solution is 2 pages of code. In Python it is 8 lines. Beautiful! I guess the real entry level test here is that you have to be smart enough to choose Python since it is the best language. You pass. :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From patrickwasp at gmail.com Mon Aug 16 13:17:51 2010 From: patrickwasp at gmail.com (Waspinator) Date: Mon, 16 Aug 2010 10:17:51 -0700 (PDT) Subject: How can I bundle a PyGTK program in windows so my users don't need to install Python or the GTK+ libs? Message-ID: <58dcc52c-e3d8-483c-8a95-f59928d61fad@c16g2000vbp.googlegroups.com> I found this question on http://faq.pygtk.org/index.py?file=faq21.005.htp&req=show but the answer did not help me. For example I have a simple program below that I would like to 'compile' with py2exe (or anything else if it's simpler) to run in windows as a single bundled executable file with no installation (no INNO setup), and no requirements for gtk or python installations. I doesn't matter if the .exe file is 30 MB to only display a hello world app, as long as it works. (although the smaller the better) The application already works in my windows test environment because I have installed python 2.6 with pygtk and a gtk bundle. Can someone please provide some simple and clear instructions on how I can do this? Thanks, Waspinator simple.py ------------------------------------------------------------------- import gtk window = gtk.Window() window.set_title("PyGTK Test Window") window.connect("destroy", gtk.main_quit) window.show_all() gtk.main() ------------------------------------------------------------------- From paddy3118 at googlemail.com Mon Aug 16 13:21:12 2010 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 16 Aug 2010 10:21:12 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> Message-ID: <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> On 14 Aug, 18:14, Raymond Hettinger wrote: > On Aug 12, 1:20?pm, Paddy wrote: > > > I find myself needing to calculate the difference between two Counters > > or multisets or bags. > > > I want those items that are unique to each bag. > > Tell us about your use cases. ?I'm curious how a program would ascribe > semantic meaning to the result. ?The phrase "unique to each bag" > doesn't quite cover it, perhaps something like "number in either > source above the minimum held in common". > > AFAICT, I've never needed something like this as a primitive. ?Even > the xor operation for regular sets is rarely used. > > > I know how to > > calculate it: > > > ? ? >>> b = Counter(a=1, b=2) > > ? ? >>> c = Counter(a=3, b=1) > > ? ? >>> diff = (b - c) + (c - b) > > ? ? >>> diff > > ? ? Counter({'a': 2, 'b': 1}) > > That seems simple enough. > You could also use: > > ?diff = (b | c) - (b & c) ? # max(b,c) - min(b,c) > > Raymond Hi Raymond and others, Lets say you have two *sets* of integers representing two near-copies of some system, then a measure of their difference could be calculated as: len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 % If the two collections of integers are allowed duplicates then you need a Counter/bag/multi-set type and the diff calculation I gave originally. Thanks. From breamoreboy at yahoo.co.uk Mon Aug 16 13:27:21 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 16 Aug 2010 18:27:21 +0100 Subject: Newbie: strftime object error message In-Reply-To: References: Message-ID: On 16/08/2010 17:47, fuglyducky wrote: > I am trying to call a function with a couple additional parameters. > Unfortunately, for whatever reason I am unable to get this to work. I > am assuming that line is not passing correctly but I don't understand > why??? > > I can't share all of the code because it has IP in it but below are > the pertinent snippets. > > Thanks in advance! > > ################################################################################## > > PY: 3.1.2 > > > FUNCTION CALL: > text_file = open(file_name, "r") > for line in text_file: > new_foo = pop_time(current_time, line) > # current_time = datetime.datetime.now() > > > FUNCTION: > def pop_time(line, cur_time): Look at the two arguments to pop_time, when you make the actual call they are swapped. > global new_string > global current_time > > > # Generate random time between 0 and 30 seconds > # Changes the time delta every time function is run > rand_time = random.randint(0, 30) > delta_time = datetime.timedelta(seconds=rand_time) > > # Sets the time format for string output > format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") > > > ERROR MSG: > format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") > AttributeError: 'str' object has no attribute 'strftime' > > > NOTE: current_time prints within the function, line does not HTH. Mark Lawrence. From zdoor at xs4all.nl Mon Aug 16 13:27:32 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Mon, 16 Aug 2010 19:27:32 +0200 Subject: EOFError with fileinput In-Reply-To: <4c696751$0$22940$e4fe514c@news.xs4all.nl> References: <4c696751$0$22940$e4fe514c@news.xs4all.nl> Message-ID: <4c697506$0$22918$e4fe514c@news.xs4all.nl> Here is an excerpt. It works because the end condition is a fixed number (ln==10255), the approximate number of data lines in a file. If I replace that condition by EOFError, the program does not do the intended work. It appears as if EOFError is always true in this case. +++++++++++++++++++++++++++++++++++++++++++ for line in fileinput.input(logs): if line.split()[0]=='DataID': datsec=True ln=0 if datsec: lines[fn].append(line.split()) ln+=1 if ln==10255: datsec=False fileinput.nextfile() fn+=1 print fileinput.filename().rsplit('\\',1)[1] fileinput.close() +++++++++++++++++++++++++++++++++++++++++++ Regards, Alex van der Spek "Alex van der Spek" wrote in message news:4c696751$0$22940$e4fe514c at news.xs4all.nl... > Using the fileinput module to process lists of files: > >>>>for line in fileinput.input(logs): > > Unfortunately, EOFError does not seem to indicate the end-of-file > condition correctly when using fileinput. > > How would you find the EOF file for all the files in the file list 'logs'? > > Thank you, > Alex van der Spek From cbrown at cbrownsystems.com Mon Aug 16 13:28:13 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Mon, 16 Aug 2010 10:28:13 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Message-ID: <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> On Aug 16, 1:23?am, Roald de Vries wrote: > On Aug 15, 2010, at 11:51 PM, Ian Kelly wrote: > > > > > On Sun, Aug 15, 2010 at 4:36 PM, Baba wrote: > >> Hi Mel, > > >> indeed i thought of generalising the theorem as follows: > >> If it is possible to buy n, n+1,?, n+(x-1) sets of McNuggets, for ? > >> some > >> x, then it is possible to buy any number of McNuggets >= x, given ? > >> that > >> McNuggets come in x, y and z packs. > > >> so with diophantine_nuggets(7,10,21) i would need 7 passes > >> result:53 > > >> but with (10,20,30) and 10 passes i get no result > > > You're on the right track. ?In the case of (10,20,30) there is no > > largest exactly purchasable quantity. ?Any quantity that does not end > > with a 0 will not be exactly purchasable. > > > I suspect that there exists a largest unpurchasable quantity iff at > > least two of the pack quantities are relatively prime, but I have made > > no attempt to prove this. > > That for sure is not correct; packs of 2, 4 and 7 do have a largest ? > unpurchasable quantity. > But 2 is coprime to 7. I think a better counterexample is 6, 10, 15; no two are coprime, but there is a largest unpurchasable quantity. > I'm pretty sure that if there's no common divisor for all three (or ? > more) packages (except one), there is a largest unpurchasable ? > quantity. That is: ? i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x| > y) means "x is no divider of y" > It's easy to prove that there is a largest unpurchasble quantity iff gcd(x,y,z) = 1. First, suppose d = gcd(x, y, z); then for some x', y', z' we have that x = d*x', y = d*y', z = d*z'; and so for any a, b, c: a*x + b*y + c*z = a*d*x' + b*d*y' + c*d*z' = d*(a*x' + b*y' + c*z') which means that d must always divide the total number of nuggets purchasable; thus if d >1, there is no largest unpurchasable quantity (you cannot purchase n*d + 1 nuggets for any n). To go the other way, if d = 1, then there exists integers (not neccessarily positive) such that a*x + b*y + c*z = 1 so therefore (a*x)*x + (b*x)*y + (c*x)*z = x Choose A, B, and C to be positive integers with A + a*x >= 0 B + b*x >= 0 C + c*x >= 0 Then we get a sequence of x consecutive numbers, all purchasable, via (A + i*a)*x + (B + i*b)*x + (C + i*c)*z = (Ax + By + Cz) + i*(ax + by cz) = (Ax + By + Cz) + i with i in range(x). The next consecutive number is then achieved via (Ax + By + Cz) + x = (A+1)x + By + Cz and so on. Cheers - Chas From python at mrabarnett.plus.com Mon Aug 16 13:28:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 16 Aug 2010 18:28:32 +0100 Subject: Newbie: strftime object error message In-Reply-To: References: Message-ID: <4C697540.6070408@mrabarnett.plus.com> fuglyducky wrote: > I am trying to call a function with a couple additional parameters. > Unfortunately, for whatever reason I am unable to get this to work. I > am assuming that line is not passing correctly but I don't understand > why??? > [snip] The function's parameters are the wrong way round. From python.koda at gmail.com Mon Aug 16 13:42:22 2010 From: python.koda at gmail.com (Alban Nona) Date: Mon, 16 Aug 2010 13:42:22 -0400 Subject: os.stat st_mtime problem Message-ID: Hello, Im stuck with this problem: I would like to os.stat st_mtime to copy only the files that have different modification date. so I found something on internet using this kind of line: if os.stat(dest).st_mtime - os.stat(src).st_mtime > 1: shutil.copy2 (src, dst) So I adapted it to my script like that: if sys.argv[1] == 'update': if os.stat(localPath).st_mtime != os.stat(networkPath).st_mtime: os.system('xcopy /E /I /Q /Y "%s" "%s"' % (networkPath, localPath)) else: print "Everything match" localPath is equal to : "c:\test\prod\" and networkPath to : "d:\test\prod\" the content of this paths is another directory: "v001", where there some tga files. Now I dont even know if os.stat compare the modified version of every files contained in localPath and networkPath, or does it compare only the v001 info ? If there a way to do it for every file ? Thank you ! (PS: I want to avoid filecmp :p) -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollybox.de Mon Aug 16 13:50:14 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 16 Aug 2010 19:50:14 +0200 Subject: How to convert bytearray into integer? In-Reply-To: References: Message-ID: <201008161950.14956.thomas@jollybox.de> On Monday 16 August 2010, it occurred to Jacky to exclaim: > Hi there, > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > an 32-bit integer. So far as I can see, there're 3 ways: > a) using struct module, Yes, that's what it's for, and that's what you should be using. > b) using ctypes module, and Yeeaah, that would work, but that's really not what it's for. from_buffer wants a writable buffer interface, which is unlikely to be what you want. > c) manually manipulation. Well, yes, you can do that, but it gets messy when you're working with more complex data structures, or you have to consider byte order. > Are there any other ways? You could write a C extension module tailored to your specific purpose ;-) > number = 1 > 1.00135803223e-05 > 1.00135803223e-05 > 5.96046447754e-06 > ----- > > As the number of benchmarking loops decreasing, method c which is > manually manipulating overwhelms the former 2 methods. However, if > number == 10K, the struct method wins. > > Why does it happen? struct wins because it's built for the job. As for the small numbers: don't take these numbers seriously. Just don't. This may be caused by the way your OS's scheduler handles things for all I know. If there is an explanation for this unscientific observation, I have two guesses what it might be: * struct and ctypes still need to do some setup work, or something * somebody is optimising something, but doesn't know what they should be optimising in the first place after only a few iterations. From iamforufriends at gmail.com Mon Aug 16 13:54:49 2010 From: iamforufriends at gmail.com (babe-with-huge-boobs-hard-sex) Date: Mon, 16 Aug 2010 10:54:49 -0700 (PDT) Subject: just click and meet ur dearest girl nearest u Message-ID: <65fd9dc3-c9d5-4b50-83b8-f34a5f841c46@u31g2000pru.googlegroups.com> just click and meet ur dearest girl nearest u morethen 34 million active members r waiting 4 live hot chat, dating ... free.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From ian.g.kelly at gmail.com Mon Aug 16 13:55:01 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 16 Aug 2010 13:55:01 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <3006BB22-FCE0-48BE-B318-1AEE62368CE4@gmail.com> Message-ID: On Mon, Aug 16, 2010 at 12:43 PM, Roald de Vries wrote: >>> I'm pretty sure that if there's no common divisor for all three (or more) >>> packages (except one), there is a largest unpurchasable quantity. That >>> is: ? >>> i>1: ?(i|a) ? ?(i|b) ? ?(i|c), where ?(x|y) means "x is no divider of y" >> >> No. ?If you take the (2,4,7) example and add another pack size of 14, >> it does not cause quantities that were previously purchasable to >> become unpurchasable. > > Then what is the common divisor of 2, 4, 7 and 14? Not 2 because ?(2|7), not > anything higher than 2 because that's no divisor of 2. Ah, I misread what you meant as well. From tjreedy at udel.edu Mon Aug 16 14:03:28 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 16 Aug 2010 14:03:28 -0400 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: On 8/16/2010 9:40 AM, Vikas Mahajan wrote: > Hello to all > I am new to python. Hi, welcome to Python. Hint 1: 'Variable' is a rather loose term with many meanings. Better to think in terms of 'name' ('identifier'), which is specifically defined, and 'object'. > I am facing problem to use variables as object attributes. Your problem is that you have a attribute name stored in a string object, rather than being an unquoted literal in the code. > I have to use loop and dynamically add attributes to a > object and for this purpose I have to use variables with object names. You have to use strings with attribute names. Not uncommon > For example-: > Let us say object car has an attribute engine, then > varname = "engine" > car.varname = "dummy value" setattr(car, varname, "dummy value") is the runtime replacement for car.engine = "dummy value" Note that 'setattr(car, "engine", "dummy value")' would work but is never needed, since if you have the attribute name itself, you just write the assignment. hasattr and getattr are similar. -- Terry Jan Reedy From raoulbia at gmail.com Mon Aug 16 14:04:27 2010 From: raoulbia at gmail.com (Baba) Date: Mon, 16 Aug 2010 11:04:27 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> Message-ID: Hi Chas, Roald, These are all complicated formula that i believe are not expected at this level. If you look at the source (see my first submission) you will see that this exercise is only the second in a series called "Introduction to Programming". Therefore i am convinced that there is a much simpler solution. Now, i believe that the number of consecutive passes required to make this work is equal to the smallest number of pack sizes. So if we have packs of (9,12,21) the number of passes needed would be 9 and the theorem would read "If it is possible to buy n,n+1,n+2,...n+8 nuggets it is possible to buy any number of nuggets >= 9 given that they come in packs of 9,12,21" However i turn in circles because i don't seem to get any results for some random pack combinations like (9,12,21) or (10,20,30). The must always be a solution i'm thinking, be it the smallest pack - 1 Thoughts? tnx Raoul From erather at forth.com Mon Aug 16 14:09:57 2010 From: erather at forth.com (Elizabeth D Rather) Date: Mon, 16 Aug 2010 08:09:57 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> Message-ID: On 8/15/10 10:33 PM, Standish P wrote: ... I don't understand a lot of your post (and it's clear that I'm not alone). I don't know whether it's a (human) language problem or simply an issue of your having read too many books and not having enough practical experience, but at least I can try to address the Forth questions. >>> If Forth is a general processing language based on stack, is it >>> possible to convert any and all algorithms to stack based ones and >>> thus avoid memory leaks since a pop automatically releases memory when >>> free is an intrinsic part of it. Forth uses two stacks. The "data stack" is used for passing parameters between subroutines ("words") and is completely under the control of the programmer. Words expect parameters on this stack; they remove them, and leave only explicit results. The "return stack" is used primarily for return addresses when words are called, although it is also available for auxiliary uses under guidelines which respect the primary use for return addresses. Although implementations vary, in most Forths stacks grow from a fixed point (one for each stack) into otherwise-unused memory. The space involved is allocated when the program is launched, and is not managed as a heap and allocated or deallocated by any complicated mechanism. On multitasking Forth systems, each task has its own stacks. Where floating point is implemented (Forth's native arithmetic is integer-based), there is usually a separate stack for floats, to take advantage of hardware FP stacks. >> - is forth a general purpose language? Yes >> - are all algorithms stack based? No > > Does Forth uses stack for all algorithms ? Does it use pointers , ie > indirect addressing ? If it can/must use stack then every algorithm > could be made stack based. Forth uses its data stack for parameter passing and storage of temporary values. It is also possible to define variables, strings, and arrays in memory, in which case their addresses may be passed on the data stack. Forth is architecturally very simple. Memory allocations for variables, etc., are normally static, although some implementations include facilities for heaps as needed by applications. Hope this helps. If you are interested in learning more about Forth, there are several books available (try Amazon). Get one of the more recent ones, some of which I wrote. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From stndshp at gmail.com Mon Aug 16 14:21:16 2010 From: stndshp at gmail.com (Standish P) Date: Mon, 16 Aug 2010 11:21:16 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <6ef9faad-b067-4940-8e96-28d2cb8141a8@q22g2000yqm.googlegroups.com> On Aug 16, 12:38?am, "Alf P. Steinbach /Usenet" wrote: > * Standish P, on 16.08.2010 09:20: > > > [garble garble] > > Nonsense article "We look for an exogenous stack" cross-posted to > > ? ?[comp.lang.c], > ? ?[comp.lang.c++], > ? ?[comp.theory], > ? ?[comp.lang.python], > ? ?[comp.lang.forth]. > > Please refrain from following up on Standish' article. I am sorry that I did not post one of those porn baiting spams featuring YOUR MOTHER NUDE that you so like for others to see - AND - that you never complain about. Go and continue with your work and dont mess in my threads. Cheers, Standish > > Cheers, > > - Alf > > -- > blog at From fuglyducky at gmail.com Mon Aug 16 14:25:03 2010 From: fuglyducky at gmail.com (fuglyducky) Date: Mon, 16 Aug 2010 11:25:03 -0700 (PDT) Subject: Newbie: strftime object error message References: Message-ID: On Aug 16, 10:27?am, Mark Lawrence wrote: > On 16/08/2010 17:47, fuglyducky wrote: > > > > > I am trying to call a function with a couple additional parameters. > > Unfortunately, for whatever reason I am unable to get this to work. I > > am assuming that line is not passing correctly but I don't understand > > why??? > > > I can't share all of the code because it has IP in it but below are > > the pertinent snippets. > > > Thanks in advance! > > > ################################################################################## > > > PY: 3.1.2 > > > FUNCTION CALL: > > text_file = open(file_name, "r") > > for line in text_file: > > ? ? ?new_foo = pop_time(current_time, line) > > # current_time = datetime.datetime.now() > > > FUNCTION: > > def pop_time(line, cur_time): > > Look at the two arguments to pop_time, when you make the actual call > they are swapped. > > > > > ? ? ?global new_string > > ? ? ?global current_time > > > ? ? ?# Generate random time between 0 and 30 seconds > > ? ? ?# Changes the time delta every time function is run > > ? ? ?rand_time = random.randint(0, 30) > > ? ? ?delta_time = datetime.timedelta(seconds=rand_time) > > > ? ? ?# Sets the time format for string output > > ? ? ?format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") > > > ERROR MSG: > > ? ? ?format_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") > > AttributeError: 'str' object has no attribute 'strftime' > > > NOTE: current_time prints within the function, line does not > > HTH. > > Mark Lawrence. Oh jeez!!! Thanks! Man...looking at this stuff for so long it's easy to miss the obvious!!! Thanks and sorry for the waste of time. From jjposner at optimum.net Mon Aug 16 14:33:14 2010 From: jjposner at optimum.net (John Posner) Date: Mon, 16 Aug 2010 14:33:14 -0400 Subject: Opposite of split In-Reply-To: <4c696ada$0$22941$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl><4C683363.3080305@islandtraining.com><4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> Message-ID: <4C69846A.2020605@optimum.net> On 8/16/2010 12:44 PM, Alex van der Spek wrote: > > Anybody catches any other ways to improve my program (attached), you are > most welcome. 1. You don't need to separate out special characters (TABs, NEWLINEs, etc.) in a string. So: bt='-999.25'+'\t''-999.25'+'\t''-999.25'+'\t''-999.25'+'\t'+'-999.25' ... can be ... bt='-999.25\t-999.25\t-999.25\t-999.25\t-999.25' BTW, I think you made a couple of "lucky errors" in this statement. Where there are two consecutive apostrophe (') characters, did you mean to put a plus sign in between? Your statement is valid because the Python interpreter concatenates strings for you: >>> x = 'foo''bar' >>> x == 'foobar' True >>> x = 'foo' 'bar' >>> x == 'foobar' True 2. Take a look at the functions in the os.path module: http://docs.python.org/library/os.path.html These functions might simplify your pathname manipulations. (I didn't look closely enough to know for sure.) 3. An alternative to: alf.write(tp+'\t'+vf+'\t'+vq+'\t'+al+'\t'+bt+'\t'+vs+'\n') ... is ... alf.write("\t".join((tp, vf, vq, al, bt, vs)) + "\n") 4. I suggest using a helper function to bring that super-long column-heading line (alf.write('Timestamp ...) under control: def multi_field_names(base_name, count, sep_string): names = [base_name + " " + str(i) for i in range(1, count+1)] return sep_string.join(names) HTH, John From python at mrabarnett.plus.com Mon Aug 16 14:35:08 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 16 Aug 2010 19:35:08 +0100 Subject: os.stat st_mtime problem In-Reply-To: References: Message-ID: <4C6984DC.3030509@mrabarnett.plus.com> Alban Nona wrote: > Hello, > > Im stuck with this problem: > I would like to os.stat st_mtime to copy only the files that have > different modification date. > so I found something on internet using this kind of line: > > if os.stat(dest).st_mtime - os.stat(src).st_mtime > 1: > shutil.copy2 (src, dst) > So I adapted it to my script like that: > > if sys.argv[1] == 'update': > if os.stat(localPath).st_mtime != os.stat(networkPath).st_mtime: > os.system('xcopy /E /I /Q /Y "%s" "%s"' % (networkPath, > localPath)) > else: > print "Everything match" > > localPath is equal to : "c:\test\prod\" > and networkPath to : "d:\test\prod\" > > the content of this paths is another directory: "v001", where there some > tga files. > > Now I dont even know if os.stat compare the modified version of every > files contained in localPath and networkPath, or does it compare only > the v001 info ? > If there a way to do it for every file ? > os.stat doesn't compare anything, it just returns info about a single file or directory. From anthra.norell at bluewin.ch Mon Aug 16 14:40:52 2010 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Mon, 16 Aug 2010 20:40:52 +0200 Subject: Simple Problem but tough for me if i want it in linear time In-Reply-To: References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: <1281984052.2354.8.camel@hatchbox-one> On Sun, 2010-08-15 at 15:14 +0200, Peter Otten wrote: > ChrisChia wrote: > > > dataList = [a, b, c, ...] > > where a, b, c are objects of a Class X. > > In Class X, it contains self.name and self.number > > > > If i wish to test whether a number (let's say 100) appears in one of > > the object, and return that object, > > is that only fast way of solving this problem without iterating > > through every object to see the number value? > > > > dataList.__contains__ can only check my object instance name... > > anyone can solve this in linear complexity? > > Well, iteration as in > > next(item for item in dataList if item.number == 100) > > is O(n) and list.__contains__() has no magic way to do better. If you need > O(1) lookup you can use a dict or collections.defaultdict that maps > item.number to a list (or set) of X instances: > > lookup = {} > for item in dataList: > lookup.setdefault(item.number, []).append(item) > > print lookup[100] > > > Peter > How about >>> [obj for obj in dataList if obj.number == 100] That should create a list of all objects whose .number is 100. No need to cycle through a loop. If .number doesn't repeat get your object at index 0. The approach may seem inefficient for the purpose of extracting a single item, but the list needs to be gone through in any case and the list comprehension is surely the most efficient way to do it. Frederic From jacky.chao.wang at gmail.com Mon Aug 16 15:08:34 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 12:08:34 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: Hi Thomas, Thanks for your comments! Please check mine inline. On Aug 17, 1:50?am, Thomas Jollans wrote: > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > Hi there, > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > an 32-bit integer. ?So far as I can see, there're 3 ways: > > a) using struct module, > > Yes, that's what it's for, and that's what you should be using. My concern is that struct may need to parse the format string, construct the list, and de-reference index=0 for this generated list to get the int out. There should be some way more efficient? > > > b) using ctypes module, and > > Yeeaah, that would work, but that's really not what it's for. from_buffer > wants a writable buffer interface, which is unlikely to be what you want. Actually my buffer is writable --- it's an bytearray. Turning it into a R/O one make me to do extra effort: wrapping the bytearray into buffer(). My question is, this operation seems like to be much simpler than the former one, and it's very straightforward as well. Why is it slow? > > > c) manually manipulation. > > Well, yes, you can do that, but it gets messy when you're working with more > complex data structures, or you have to consider byte order. agree. :) > > > Are there any other ways? > > You could write a C extension module tailored to your specific purpose ;-) Ha, yes. Actually I've already modified socketmodule.c myself --- it's hard to image why socket object provides the interface: socket.recv_from(buf[, num_bytes[, flags]]) but forget the more generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]]) So do socket.send(...). > > > number = 1 > > 1.00135803223e-05 > > 1.00135803223e-05 > > 5.96046447754e-06 > > ----- > > > As the number of benchmarking loops decreasing, method c which is > > manually manipulating overwhelms the former 2 methods. ?However, if > > number == 10K, the struct method wins. > > > Why does it happen? > > struct wins because it's built for the job. > > As for the small numbers: don't take these numbers seriously. Just don't. This > may be caused by the way your OS's scheduler handles things for all I know. If > there is an explanation for this unscientific observation, I have two guesses > what it might be: > ?* struct and ctypes still need to do some setup work, or something > ?* somebody is optimising something, but doesn't know what they should be > ? ?optimising in the first place after only a few iterations. Agree. Thanks. - Jacky From dickinsm at gmail.com Mon Aug 16 15:36:26 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 16 Aug 2010 12:36:26 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: On Aug 16, 8:08?pm, Jacky wrote: > Hi Thomas, > > Thanks for your comments! ?Please check mine inline. > > On Aug 17, 1:50?am, Thomas Jollans wrote: > > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > > Hi there, > > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > > an 32-bit integer. ?So far as I can see, there're 3 ways: > > > a) using struct module, > > > Yes, that's what it's for, and that's what you should be using. > > My concern is that struct may need to parse the format string, > construct the list, and de-reference index=0 for this generated list > to get the int out. > > There should be some way more efficient? Well, you can improve on the struct solution by using the struct.Struct class to avoid parsing the format string repeatedly: >>> import struct >>> S = struct.Struct('>> S.unpack_from(buffer(bytearray([1,2,3,4,5]))) (67305985,) This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit build of Python 2.6) though; it's probably more effective for long format strings. Adding: def test_struct2(buf, offset, S=struct.Struct(' References: Message-ID: <201008162138.00980.thomas@jollybox.de> On Monday 16 August 2010, it occurred to Jacky to exclaim: > Hi Thomas, > > Thanks for your comments! Please check mine inline. > > On Aug 17, 1:50 am, Thomas Jollans wrote: > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > Hi there, > > > > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > > an 32-bit integer. So far as I can see, there're 3 ways: > > > a) using struct module, > > > > Yes, that's what it's for, and that's what you should be using. > > My concern is that struct may need to parse the format string, > construct the list, and de-reference index=0 for this generated list > to get the int out. > > There should be some way more efficient? The struct module is written in C, not in Python. It does have to parse a string, yes, so, if you wrote your own, limited, C function to do the job, it might be marginally faster. > > > > b) using ctypes module, and > > > > Yeeaah, that would work, but that's really not what it's for. from_buffer > > wants a writable buffer interface, which is unlikely to be what you want. > > Actually my buffer is writable --- it's an bytearray. Turning it into > a R/O one make me to do extra effort: wrapping the bytearray into > buffer(). > > My question is, this operation seems like to be much simpler than the > former one, and it's very straightforward as well. Why is it slow? Unlike struct, it constructs an object you're not actually interested in around your int. > it's hard to image why socket object provides the interface: > socket.recv_from(buf[, num_bytes[, flags]]) but forget the more > generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]]) Well, that's what pointer arithmetic (in C) or slices (in Python) are for! There's an argument to be made for sticking close to the traditional (originally C) interface here - it's familiar. - Thomas From mwilson at the-wire.com Mon Aug 16 15:52:41 2010 From: mwilson at the-wire.com (Mel) Date: Mon, 16 Aug 2010 15:52:41 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> Message-ID: Baba wrote: [ ... ] > Now, i believe that the number of consecutive passes required to make > this work is equal to the smallest number of pack sizes. So if we have > packs of (9,12,21) the number of passes needed would be 9 and the > theorem would read > > "If it is possible to buy n,n+1,n+2,...n+8 nuggets it is possible to > buy any number of nuggets >= 9 given that they come in packs of > 9,12,21" That's the proper statement. > > However i turn in circles because i don't seem to get any results for > some random pack combinations like (9,12,21) or (10,20,30). That "if it is possible" is the big if. If every package you can buy has a multiple of 3, then every possible purchase will be a multiple of 3. Nothing that leaves a remainder of 1 or 2 will ever show up. > > The must always be a solution i'm thinking, be it the smallest pack - > 1 The set (9/3, 12/3, 21/3) settles down pretty quickly: >>> s = nuggets.buyable_set ((3, 4, 7)) >>> nuggets.print_from (s, xrange(20)) 0 set([]) 3 set([0]) 4 set([0]) 6 set([3]) 7 set([0, 3, 4]) 8 set([4]) 9 set([6]) 10 set([3, 6, 7]) 11 set([8, 4, 7]) 12 set([8, 9]) 13 set([9, 10, 6]) 14 set([10, 11, 7]) 15 set([8, 11, 12]) 16 set([9, 12, 13]) 17 set([10, 13, 14]) 18 set([11, 14, 15]) 19 set([16, 12, 15]) >>> The printout here is the 'genaeology' of each purchase -- the set of smaller purchases from which you can reach each one. After ...,6,7,8,... every larger number can be reached. Mel. From dickinsm at gmail.com Mon Aug 16 15:53:21 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 16 Aug 2010 12:53:21 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: On Aug 16, 8:36?pm, Mark Dickinson wrote: > On Aug 16, 8:08?pm, Jacky wrote: > > My concern is that struct may need to parse the format string, > > construct the list, and de-reference index=0 for this generated list > > to get the int out. > > > There should be some way more efficient? > > Well, you can improve on the struct solution by using the > struct.Struct class to avoid parsing the format string repeatedly: > > >>> import struct > >>> S = struct.Struct(' >>> S.unpack_from(buffer(bytearray([1,2,3,4,5]))) > > (67305985,) > > This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit > build of Python 2.6) though; ?it's probably more effective for long > format strings. Sorry, this was inaccurate: this makes almost *no* significant difference on my machine for large test runs (10000 and up). For small ones, though, it's faster. The reason is that the struct module caches (up to 100, in the current implementation) previously used format strings, so with your tests you're only ever parsing the format string once anyway. Internally, the struct module converts that format string to a Struct object, and squirrels that Struct object away into its cache, which is implemented as a dict from format strings to Struct objects. So the next time that the format string is used it's simply looked up in the cache, and the Struct object retrieved. By the way, in Python 3.2 there's yet another fun way to do this, using int.from_bytes. >>> int.from_bytes(bytearray([1,2,3,4]), 'little') 67305985 -- Mark From giacomo.boffi at polimi.it Mon Aug 16 15:57:59 2010 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Mon, 16 Aug 2010 21:57:59 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> Message-ID: <868w46qqig.fsf@aiuole.stru.polimi.it> Baba writes: > Hi Mel, > > indeed i thought of generalising the theorem as follows: > If it is possible to buy n, n+1,~, n+(x-1) sets of McNuggets, for some > x, then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in x, y and z packs. > > so with diophantine_nuggets(7,10,21) i would need 7 passes > result:53 > > but with (10,20,30) and 10 passes i get no result you need at least an odd number in your set, because summing even numbers only you'll never get an odd result From raoulbia at gmail.com Mon Aug 16 16:18:39 2010 From: raoulbia at gmail.com (Baba) Date: Mon, 16 Aug 2010 13:18:39 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <868w46qqig.fsf@aiuole.stru.polimi.it> Message-ID: <8e7ad85e-750b-48ef-9ca8-36690fa2cbcf@p7g2000yqa.googlegroups.com> well i still believe that the key is the smallest sized pack and there's no need to go into higher mathematics to solve this problem. I think below code works within the limits of the exercise which states to look at a maximum range of 200 in order not to search forever. packages=[2,103,105] min_size=min(packages[0],packages[1],packages[2]) cbc=0 #cbc=can_buy counter for n_nuggets in range(1,200): if cbc>=min_size: break can_buy=False for a in range (n_nuggets/packages[0]+1): for b in range (n_nuggets/packages[1]+1): for c in range (n_nuggets/packages[2]+1): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b+packages[2]*c==n_nuggets: can_buy=True break if can_buy==True: cbc+=1 else: cbc=0 sol=n_nuggets print sol Baba From jjposner at optimum.net Mon Aug 16 16:52:35 2010 From: jjposner at optimum.net (John Posner) Date: Mon, 16 Aug 2010 16:52:35 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <8e7ad85e-750b-48ef-9ca8-36690fa2cbcf@p7g2000yqa.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4c630c9a$0$5445$426a74cc@news.free.fr> <43fbefb6-bb99-4ea6-896e-c79d887267b5@p7g2000yqa.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <868w46qqig.fsf@aiuole.stru.polimi.it> <8e7ad85e-750b-48ef-9ca8-36690fa2cbcf@p7g2000yqa.googlegroups.com> Message-ID: <4C69A513.1050802@optimum.net> On 8/16/2010 4:18 PM, Baba wrote: > > packages=[2,103,105] > min_size=min(packages[0],packages[1],packages[2]) or: min_size = min(packages) -John From rantingrick at gmail.com Mon Aug 16 18:36:35 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 16 Aug 2010 15:36:35 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: <8fa1a70c-c40b-40fd-8dc7-2cb155fbc8b1@l6g2000yqb.googlegroups.com> Message-ID: <07f2804d-c212-4f84-b0de-dd0e80ab5bca@u26g2000yqu.googlegroups.com> On Aug 9, 8:19?am, Mike Kent wrote: > On Aug 8, 8:43?pm, rantingrick wrote: > Xah, this is really you, isn't it. ?Come on, confess. *MOI*, How could *I* be xah. I really don't like Ruby however he gushes over it all the time. And he does not like Python that much either. We are total opposites, really. From kevin.p.dwyer at gmail.com Mon Aug 16 18:37:55 2010 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Mon, 16 Aug 2010 22:37:55 +0000 (UTC) Subject: question about pdb assignment statements References: Message-ID: On Mon, 16 Aug 2010 08:17:20 -0700, Steve Ferg wrote: > In this little script: > >
>  import pdb
>  pdb.set_trace()
>  def main():
>      xm = 123
>      print("Hello,world!")
>  main()
>  
> > When I run this, I use pdb to step through it until I reach the point in > main() where the xm variable has been initialized, and then I try to use > pdb to reset the value of xm, and I can't. > > Does anybody know why? > > As I understand the documentation, > http://docs.python.org/library/pdb.html I *should* be able to do this. > > [!]statement > Execute the (one-line) statement in the context of the current stack > frame. > > Is there something about "in the context of the current stack frame" > that I don't understand? Or is it a bug (or a limitation) in pdb? I think this may be the issue raised in bug 5215 (http://bugs.python.org/issue5215), committed in r71006. Displaying a changed variable using the "p" command reverts the variable to its previous value. If you try pdb.set_trace() def main(): xm = 123 print("Hello,world!") print xm and change xm before it's printed (but do not display using "p") it seems to work as expected. Hope that helps, Kev From kevin.p.dwyer at gmail.com Mon Aug 16 18:39:58 2010 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Mon, 16 Aug 2010 22:39:58 +0000 (UTC) Subject: question about pdb assignment statements References: Message-ID: On Mon, 16 Aug 2010 08:17:20 -0700, Steve Ferg wrote: > In this little script: > >
>  import pdb
>  pdb.set_trace()
>  def main():
>      xm = 123
>      print("Hello,world!")
>  main()
>  
> > When I run this, I use pdb to step through it until I reach the point in > main() where the xm variable has been initialized, and then I try to use > pdb to reset the value of xm, and I can't. > > Does anybody know why? > > As I understand the documentation, > http://docs.python.org/library/pdb.html I *should* be able to do this. > > [!]statement > Execute the (one-line) statement in the context of the current stack > frame. > > Is there something about "in the context of the current stack frame" > that I don't understand? Or is it a bug (or a limitation) in pdb? I should have added my version: Python 2.6.2 (r262:71600, Jun 17 2010, 13:37:45) [GCC 4.4.1 [gcc-4_4-branch revision 150839]] on linux2 From rantingrick at gmail.com Mon Aug 16 18:58:15 2010 From: rantingrick at gmail.com (rantingrick) Date: Mon, 16 Aug 2010 15:58:15 -0700 (PDT) Subject: Python -Vs- Ruby: A regexp match to the death! References: <4c5f5693$0$28663$c3e8da3@news.astraweb.com> Message-ID: <61fb7586-d8c0-4d65-8e82-d9c6b313511a@a36g2000yqc.googlegroups.com> On Aug 8, 8:15?pm, Steven D'Aprano wrote: > On Sun, 08 Aug 2010 17:43:03 -0700, rantingrick wrote: > > Ruby has what they > > call a "Here Doc". Besides picking the most boneheaded name for such an > > object > > It's standard terminology that has been around for a long time in many > different languages. Just because something has been around around for a long time does not necessarily mean it's was a good idea to begin with. STRAWMAN! > > As you can see it is another example of tacked on functionality that was > > not carefully considered before hand. > > I disagree. It's an old and venerable technique, and very useful on the > rare occasion that you have lots of quotation marks in a string. (...snip...) > ? Python strings have four delimiters: > ? (1) single quote ' > ? (2) double quote " > ? (3) single-quote here-doc ''' > ? (4) double-quote here-doc """ > > ? plus equivalent raw-strings of each kind. > > Trying writing that as a single literal in Python without escapes. There > are work-arounds, of course, like using implicit concatenation, but > they're ugly. Yes, with the choices we have today writing strings like you mention is terribly asinine. And don't forget about filepaths and regexps too with all the backslashing nonsense! However, there is a simple solution to this mess. Python "double quote strings" and Python """multiline strings"""(that are delimited by leading and trailing double quote triplets) should behave as they do today. However Python 'single quote strings' and Python '''multiline strings'''(that are delimited by leading and trailing single quote triplets) should be raw so that they do not interpret escape sequences. Yes i know this would break backwards compatibility *again* but this functionality should have been made available in Py3000 since we were already breaking it anyhow. Why do we need both """X""" AND '''X''' this if they do exactly the same thing? Also why do we need both "X" AND 'X' if they do exactly the same thing. A real chance to make something special was missed and i hope one day we come to the realization that this proposed functionality of strings (raw and normal) is sorely needed in Python. > In Ruby they decided to be more general, so you can define whatever > heredoc you need to quote whatever literal string you need. That's not > bone-headed. The fact that Ruby has multi line strings (*ahem*... HEREDOC's) is not at all the point i take issue with. I take issue with the boneheaded syntax. Have you ever tried to grep Ruby heredocs? It would have been so much easier if they had made a spec like this... mystring = :{ blah blah blah blahblah blah blah blah blah }: Or at least *some* static token instead of just creating something on the fly each time.... now thats boneheaded! From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 19:10:41 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 23:10:41 GMT Subject: Python 2.7 re.IGNORECASE broken in re.sub? References: <4c688159$0$11100$c3e8da3@news.astraweb.com> <3b5dac9c-c48f-41c0-a9fd-e1e4bb57ee15@l14g2000yql.googlegroups.com> <4c691f96$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c69c571$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 05:46:17 -0700, Alex Willmer wrote: > On Aug 16, 12:23?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sun, 15 Aug 2010 17:36:07 -0700, Alex Willmer wrote: >> > On Aug 16, 1:07?am, Steven D'Aprano > > cybersource.com.au> wrote: >> >> You're passing re.IGNORECASE (which happens to equal 2) as a count >> >> argument, not as a flag. Try this instead: >> >> >> >>> re.sub(r"python\d\d" + '(?i)', "Python27", t) >> >> 'Python27' >> >> > Basically right, but in-line flags must be placed at the start of a >> > pattern, or the result is undefined. >> >> Pardon me, but that's clearly not correct, as proven by the fact that >> the above example works. > > Undefined includes 'might work sometimes'. I refer you to the Python > documentation: > > "Note that the (?x) flag changes how the expression is parsed. It should > be used first in the expression string, or after one or more whitespace > characters. If there are non-whitespace characters before the flag, the > results are undefined." > http://docs.python.org/library/re.html#regular-expression-syntax Well so it does. I stand corrected. I note though that even the docs say "should" rather than "must". I wonder whether the documentation author is just being cautious, because I've seen comments on the python-dev list that imply that the current behaviour of flags (that their effect is global to the regex) is supported. E.g.: http://code.activestate.com/lists/python-dev/98681/ At the point that people are seriously considering changing the behaviour of a replacement re engine in order to support the current "undefined" behaviour, perhaps that behaviour isn't quite so undefined and the docs need to be re-written? -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 19:17:41 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 23:17:41 GMT Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> Message-ID: <4c69c715$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 20:40:52 +0200, Frederic Rentsch wrote: > How about > >>>> [obj for obj in dataList if obj.number == 100] > > That should create a list of all objects whose .number is 100. No need > to cycle through a loop. What do you think the list comprehension does, if not cycle through a loop? -- Steven From fons at kokkinizita.net Mon Aug 16 19:19:42 2010 From: fons at kokkinizita.net (fons at kokkinizita.net) Date: Tue, 17 Aug 2010 01:19:42 +0200 Subject: execfile() and locals() In-Reply-To: <4c687728$0$11100$c3e8da3@news.astraweb.com> References: <4c687728$0$11100$c3e8da3@news.astraweb.com> Message-ID: <20100816231942.GA4219@zita2> On Sun, Aug 15, 2010 at 11:24:25PM +0000, Steven D'Aprano wrote: > On Sun, 15 Aug 2010 23:21:51 +0200, fons wrote: > > > The documentation on execfile() and locals() makes it clear that code > > executed from execfile() can not modify local variables in the function > > from wich execfile() was called. Two questions about this: > > > > 1. Is there some way to circumvent this limitation (apart from > > explicitly copying variables to/from a dictionary passed as locals to > > execfile()) ? > > Chances are very good that if you're using exec or execfile inside a > function, you probably don't need to. In this case that would probably be true (see below). > As an optimization, local variables don't live inside a dict namespace. > The space for those locals is allocated at compile time, and locals() > returns a copy of the variables in a dict. > > However, the action of exec is a little more subtle, and mysterious, as > seen by this example in Python 3.1: > > >>> def f(): > ... x = 1 > ... print(locals()) > ... exec("x=2; y=0") > ... print(locals()) > ... > >>> > >>> f() > {'x': 1} > {'y': 0, 'x': 1} > > This shows that exec was able to create a new local variable, but not > modify an existing one -- this is completely unintuitive to me. I would > have guessed the opposite. And worse: > > >>> f.__code__.co_varnames > ('x',) > >>> f.__code__.co_nlocals > 1 > > So where does the newly-created local `y` live, if not in a dict > namespace and not in the usual variable slots? > > Curiouser and curiouser... Indeed... and I tried your example also in 2.6, and there it 'just works'. I've been reading a bit on execfile() and friends on various locations on the web, and there seems to be some controversy about it. One poster even wrote 'If you need execfile() you have a design problem'. I don't agree - in this case I use an interpreted language exactly to be able to do such things as made possible by execfile(). The application is a GUI one used to control electronic musical instruments and audio processors in a 'live performance' situation. Its main window shows a collection of buttons, rotary controls, sliders, etc., which trigger things when used. For example, clicking on a button could start a timed sequence of actions, each action being e.g. a message sent to a synthesis program or an audio processor, and/or some changes to the GUI itself. Such a sequence could be quite complex, defining it may require loops and conditions, or even interaction with other sequences, so the natural way is to define it as code and not as data. Users of the system are assumed to know basic Python, without being experts or expected to understand things such as the ones we are discussing. Sequences will run for some time, many of them can run at the same time, so each of them will be executed in a separate thread if required. A basic requirement for the system is that all actions can be redefined while the program is running, hence the need for execfile() or something similar. Shift-click on a GUI item presents a menu with options to modify its actions, one of them is to edit the file defining the code associated with the item. Now there are two ways to use execfile() or equivalent: 1. Actually execute the file when e.g. a button is clicked. 2. Execute it when the action is defined (i.e. when the user has finished editing the file). In the case the file should define a function which will be executed when triggered. I'll probably use the second way - the function will be precompiled, and most errors will show up before it is actually executed. Ciao, -- FA There are three of them, and Alleline. From ldo at geek-central.gen.new_zealand Mon Aug 16 19:30:18 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 17 Aug 2010 11:30:18 +1200 Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: In message <5fa7b287-0199-4349-ae0d-c34c8461cdcd at 5g2000yqz.googlegroups.com>, Standish P wrote: > We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. Since when are malloc(3) and free(3) exogenous? From alon.sebastian at gmail.com Mon Aug 16 19:45:52 2010 From: alon.sebastian at gmail.com (Sebastian Alonso) Date: Mon, 16 Aug 2010 20:45:52 -0300 Subject: Running pygtk app under windows. Message-ID: Hey everyone, I'm trying to be able to run my app, which uses pygtk, under windows, but unfortunately I'm having big problems with it. The main purpose of this is to later on make an .exe file but i havent even been able to run the app at least. I've followed every single step from this faq http://faq.pygtk.org/index.py?file=faq21.001.htp&req=show and when i try to run the example the example they offer I get this: "Traceback (most recent call last): File "", line 1, in import gtk File "C:\Python26\lib\site-packages\gtk-2.0\gtk\__init__.py", line 30, in import gobject as _gobject File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 26, in from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, \ File "C:\Python26\lib\site-packages\gtk-2.0\glib\__init__.py", line 22, in from glib._glib import * ImportError: DLL load failed: Specified module cannot be found." Do you have any clue on what could be happening ? I've tried most of the things you would expect to make anything work on windows, reboot, unistall everything and re-install everything again, yet it wont work... Thanks in advanced. Seba -------------- next part -------------- An HTML attachment was scrubbed... URL: From jah.alarm at gmail.com Mon Aug 16 19:46:37 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Mon, 16 Aug 2010 16:46:37 -0700 (PDT) Subject: Textvariable display in label (GUI design) References: <993d9560-564d-47f0-b2db-6f0c6404ae81@g6g2000pro.googlegroups.com> Message-ID: On Aug 17, 3:32?am, Eric Brunel wrote: > In article > <993d9560-564d-47f0-b2db-6f0c6404a... at g6g2000pro.googlegroups.com>, > > ?Jah_Alarm wrote: > > hi, > > > pls help me out with the following issue: I wrote a function that uses > > a for loop that changes a value of a certain variable each iteration. > > What I want is by clicking a button in GUI (with the command bound to > > this function) this value each iteration is displayed in a textbox > > (label). So far only one (starting value) is displayed. > > > thanks, > > > Alex > > First, with posts like this, you're highly unlikely to get any useful > answer: please strip down your code to the smallest part that displays > the problem, post this code here, explaining what you're expecting and > what you're getting. Otherwise, people just won't know what you're > talking about unless they have a crystal ball? > > Now using my own crystal ball: if you don't return the control to the > GUI each time your variable is increased, the GUI won't get a chance to > update itself. Since you seem to use Tkinter (another wild guess?), you > probably need a call to the update_idletasks method on any Tkinter > widget each time you change your TextVariable. > > HTH > ?- Eric - Thanks, but where is this command used, in the button than runs the algorithm, the label or the function itself? From steve at REMOVE-THIS-cybersource.com.au Mon Aug 16 19:51:44 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2010 23:51:44 GMT Subject: EOFError with fileinput References: <4c696751$0$22940$e4fe514c@news.xs4all.nl> <4c697506$0$22918$e4fe514c@news.xs4all.nl> Message-ID: <4c69cf10$0$11100$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 19:27:32 +0200, Alex van der Spek wrote: > Here is an excerpt. It works because the end condition is a fixed number > (ln==10255), the approximate number of data lines in a file. If I > replace that condition by EOFError, the program does not do the intended > work. It appears as if EOFError is always true in this case. I don't understand what you mean by "replace that condition by EOFError". I can only guess you mean what you say literally, and replace the test: if ln==10255: with the test: if EOFError: If not, then I have no idea what you mean. But if that is what you're doing, then you're doing it completely wrong! Exceptions aren't flags that get set globally by magic. You have completely misunderstood Python's programming model. In this case, the point of using fileinput is so you don't need to care about the EOF of each file. fileinput takes care of that for you, automatically detecting the end of file and switching to the next file as needed. You only need to call fileinput.nextfile() if you want to switch to the next file *before* reaching end-of-file. The usual way to use fileinput is something like: import fileinput for line in fileinput.input(list_of_filenames): process(line) which will process all the lines in each file in turn. I'm not entirely sure what you are attempting to do in your example code. It doesn't help that you are using variable names like fn and ln. But I will take a guess. Here's my attempt to re-write and simplify it, by changing the condition from "is this the last line?" to "is this the first line?". import fileinput import os file_number = -1 lines = [ [] for i in len(logs)) ] for line in fileinput.input(logs): if fileinput.isfirstline(): file_number += 1 pathname, filename = os.path.split(fileinput.filename()) print filename words = line.split() if not words: # Line was blank (just whitespace) and can be ignored. continue if word[0] == 'DataID': lines[file_number].append(words) fileinput.close() -- Steven From jah.alarm at gmail.com Mon Aug 16 20:37:45 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Mon, 16 Aug 2010 17:37:45 -0700 (PDT) Subject: random number generation Message-ID: <7d76d377-6a55-4320-afa4-8425719d8e6e@n19g2000prf.googlegroups.com> hi, I need to generate a binary array with a specified average proportion of 1s (e.g. [1 0 0 0 0 1 0 0] has this proportion = 25%). In Matlab I run something like random(m,n)

References: <7d76d377-6a55-4320-afa4-8425719d8e6e@n19g2000prf.googlegroups.com> Message-ID: <51CFE393-93EC-465D-8F1D-9F72721B2690@bryant.edu> On Aug 16, 2010, at 20:37 , Jah_Alarm wrote: > hi, > > I need to generate a binary array with a specified average proportion > of 1s (e.g. [1 0 0 0 > > 0 1 0 0] has this proportion = 25%). In Matlab I run something like > random(m,n)

> between 0 and 1. I'm trying to use random.randint(0,2,size=[m,n]), but > I don't understand how to specify this proportion p. > if you're coming from matlab, then you should use the numpy package (and you can post questions on the numpy list). In that case, you can do: from numpy import * random.rand(5,7)<0.25 array([[False, True, True, False, False, True, False], [False, False, False, False, True, False, False], [ True, False, False, False, False, False, True], [ True, False, True, False, False, False, False], [False, False, False, False, False, False, False]], dtype=bool) just like matlab. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais http://bblais.blogspot.com/ From jacky.chao.wang at gmail.com Mon Aug 16 20:57:45 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 17:57:45 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: Hi Mark, Thanks for your reply. Agree and I'll use your suggestions. Thanks! -Jacky On Aug 17, 3:36?am, Mark Dickinson wrote: > On Aug 16, 8:08?pm, Jacky wrote: > > > Hi Thomas, > > > Thanks for your comments! ?Please check mine inline. > > > On Aug 17, 1:50?am, Thomas Jollans wrote: > > > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > > > Hi there, > > > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > > > an 32-bit integer. ?So far as I can see, there're 3 ways: > > > > a) using struct module, > > > > Yes, that's what it's for, and that's what you should be using. > > > My concern is that struct may need to parse the format string, > > construct the list, and de-reference index=0 for this generated list > > to get the int out. > > > There should be some way more efficient? > > Well, you can improve on the struct solution by using the > struct.Struct class to avoid parsing the format string repeatedly: > > >>> import struct > >>> S = struct.Struct(' >>> S.unpack_from(buffer(bytearray([1,2,3,4,5]))) > > (67305985,) > > This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit > build of Python 2.6) though; ?it's probably more effective for long > format strings. Adding: > > def test_struct2(buf, offset, S=struct.Struct(' ? ? return S.unpack_from(buf, offset)[0] > > to your test code, I see a speedup of around 8% over your test_struct. > > By the way, you may want to consider using an explicit byte-order/size > marker in your format string; ?i.e., use ' forces a 4-byte little-endian interpretation, regardless of the > platform you're running Python on. > > -- > Mark- Hide quoted text - > > - Show quoted text - From jacky.chao.wang at gmail.com Mon Aug 16 21:00:09 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 18:00:09 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: <38b3c3b4-5a06-4fe1-9e5f-7194142a3606@f20g2000pro.googlegroups.com> On Aug 17, 3:38?am, Thomas Jollans wrote: > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > > > > > Hi Thomas, > > > Thanks for your comments! ?Please check mine inline. > > > On Aug 17, 1:50 am, Thomas Jollans wrote: > > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > > Hi there, > > > > > Recently I'm facing a problem to convert 4 bytes on an bytearray into > > > > an 32-bit integer. ?So far as I can see, there're 3 ways: > > > > a) using struct module, > > > > Yes, that's what it's for, and that's what you should be using. > > > My concern is that struct may need to parse the format string, > > construct the list, and de-reference index=0 for this generated list > > to get the int out. > > > There should be some way more efficient? > > The struct module is written in C, not in Python. It does have to parse a > string, yes, so, if you wrote your own, limited, C function to do the job, it > might be marginally faster. > > > > > > > b) using ctypes module, and > > > > Yeeaah, that would work, but that's really not what it's for. from_buffer > > > wants a writable buffer interface, which is unlikely to be what you want. > > > Actually my buffer is writable --- it's an bytearray. ?Turning it into > > a R/O one make me to do extra effort: wrapping the bytearray into > > buffer(). > > > My question is, this operation seems like to be much simpler than the > > former one, and it's very straightforward as well. ?Why is it slow? > > Unlike struct, it constructs an object you're not actually interested in > around your int. > > > it's hard to image why socket object provides the interface: > > socket.recv_from(buf[, num_bytes[, flags]]) but forget the more > > generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]]) > > Well, that's what pointer arithmetic (in C) or slices (in Python) are for! > There's an argument to be made for sticking close to the traditional > (originally C) interface here - it's familiar. Hi Thomas, - I'm not quite follow you. It will be great if you could show me some code no this part... > > ?- Thomas- Hide quoted text - > > - Show quoted text - From roy at panix.com Mon Aug 16 21:00:17 2010 From: roy at panix.com (Roy Smith) Date: Mon, 16 Aug 2010 21:00:17 -0400 Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: In article , Martin Gregorie wrote: > Say you have intensity data captured from an X-ray goniometer from 160 > degrees to 30 degrees at 0.01 degree resolution. Which is most evil of > the following? > > 1) real intensity[16000:3000] > for i from lwb intensity to upb intensity > plot(i/100, intensity[i]); How about (totally inventing syntax as I go along): 5) real intensity[160.0 : 30.0 : 0.01] for index, value in intensity: plot(index, value) From jacky.chao.wang at gmail.com Mon Aug 16 21:05:26 2010 From: jacky.chao.wang at gmail.com (Jacky) Date: Mon, 16 Aug 2010 18:05:26 -0700 (PDT) Subject: How to convert bytearray into integer? References: Message-ID: On Aug 17, 3:53?am, Mark Dickinson wrote: > On Aug 16, 8:36?pm, Mark Dickinson wrote: > > > > > > > On Aug 16, 8:08?pm, Jacky wrote: > > > My concern is that struct may need to parse the format string, > > > construct the list, and de-reference index=0 for this generated list > > > to get the int out. > > > > There should be some way more efficient? > > > Well, you can improve on the struct solution by using the > > struct.Struct class to avoid parsing the format string repeatedly: > > > >>> import struct > > >>> S = struct.Struct(' > >>> S.unpack_from(buffer(bytearray([1,2,3,4,5]))) > > > (67305985,) > > > This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit > > build of Python 2.6) though; ?it's probably more effective for long > > format strings. > > Sorry, this was inaccurate: ?this makes almost *no* significant > difference on my machine for large test runs (10000 and up). ?For > small ones, though, it's faster. ?The reason is that the struct module > caches (up to 100, in the current implementation) previously used > format strings, so with your tests you're only ever parsing the format > string once anyway. ?Internally, the struct module converts that > format string to a Struct object, and squirrels that Struct object > away into its cache, which is implemented as a dict from format > strings to Struct objects. ?So the next time that the format string is > used it's simply looked up in the cache, and the Struct object > retrieved. > > By the way, in Python 3.2 there's yet another fun way to do this, > using int.from_bytes. > > >>> int.from_bytes(bytearray([1,2,3,4]), 'little') Thanks! It looks pretty like the ctypes way. ;) > > 67305985 > > -- > Mark- Hide quoted text - > > - Show quoted text - From python at rcn.com Mon Aug 16 21:10:27 2010 From: python at rcn.com (Raymond Hettinger) Date: Mon, 16 Aug 2010 18:10:27 -0700 (PDT) Subject: random number generation References: <7d76d377-6a55-4320-afa4-8425719d8e6e@n19g2000prf.googlegroups.com> Message-ID: On Aug 16, 5:37?pm, Jah_Alarm wrote: > hi, > > I need to generate a binary array with a specified average proportion > of 1s (e.g. [1 0 0 0 > > 0 1 0 0] has this proportion = 25%). In Matlab I run something like > random(m,n)

> between 0 and 1. I'm trying to use random.randint(0,2,size=[m,n]), but > I don't understand how to specify this proportion p. Try this: >>> from random import random >>> [1 if random() < 0.25 else 0 for i in range(20)] [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0] Raymond From ariel.bys at gmail.com Mon Aug 16 21:19:28 2010 From: ariel.bys at gmail.com (AlphaBravo) Date: Mon, 16 Aug 2010 18:19:28 -0700 (PDT) Subject: 2 Regex Questions Message-ID: <4f350848-9f12-4c0d-aaaa-a35467b3f3a4@c10g2000yqi.googlegroups.com> Hello Comp.Lang,Python, 1) How do I parse Basic Posix RE's in Python (i need it because of some old scripts and a specific OS developed in Seattle) 2) How can I split a string into sections that MATCH a regex (rather then splitting by seperator). Tokenizer-style but ignoring every place from where I can't start a match? - Thanks, Ariel Ben-Yehuda -- - Ariel Ben-Yehuda From python at rcn.com Mon Aug 16 21:29:33 2010 From: python at rcn.com (Raymond Hettinger) Date: Mon, 16 Aug 2010 18:29:33 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> Message-ID: <2abafeea-78e6-454c-8c3d-debe888d2bc7@h40g2000pro.googlegroups.com> [Paddy] > Lets say you have two *sets* of integers representing two near-copies > of some system, then a measure of their difference could be calculated > as: > > len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 % > > If the two collections of integers are allowed duplicates then you > need a Counter/bag/multi-set type and the diff calculation I gave > originally. Thanks for sharing your use case. It's unlikely that I will add this method to the Counter API because the rarity of use case does not warrant the added API complexity. IMO, adding a method like this makes the class harder to learn, understand and remember. It doesn't seem like much of a win over using the existing alternatives: * (b - c) + (c - b) * (b | c) - (b & c) * DIY using the two counters as simple dicts * writing a subclass providing additional binary operations I would like to see someone post a subclass to the ASPN Cookbook that adds a number of interesting, though not common operations. Your symmetric_difference() method could be one. A dot_product() operation could be another. Elementwise arithmetic is another option (we already have add and subtract, but could possibly use multiply, divide, etc). Scaling operations are another possibility (multiple all elements by five, for example). The Counter() class has low aspirations. It is a dictionary that fills-in missing values with zero and is augmented by a handful of basic methods for managing the counts. Raymond From chrischia82 at gmail.com Mon Aug 16 21:38:06 2010 From: chrischia82 at gmail.com (ChrisChia) Date: Mon, 16 Aug 2010 18:38:06 -0700 (PDT) Subject: how to switch image in tkinter? making it mutable? how? References: <414ff6dd-73ef-48df-bd2b-080a2c710e5b@h17g2000pri.googlegroups.com> Message-ID: On Aug 17, 2:57?am, Jeff Hobbs wrote: > On Aug 16, 7:30?am, ChrisChia wrote: > > > I have this: > > image1 = ImageTk.PhotoImage(file = "c:\\f1.jpg") > > image2 = ImageTk.PhotoImage(file = "c:\\f2.jpg") > > > imagelist.append(image1) > > imagelist.append(image2) > > > self.label ?= tk.Label(image = imagelist[0]) > > > is there a way that i can create a method to switch the display the > > image2 (imagelist 2nd element) > > without using label.bind? > > > can i make an image mutable? > > self.label.configure(image = imagelist[1]) will change the image > displayed. > With PIL images, you can use image1.fromstring(...) that should have a > similar effect, in that it changes the underlying image data and the > label will display that. > > Whether you need to label.bind or something else to effect this change > is up to you. ?You could have it happen on a timer, triggered by an > event, or randomly effected by solar flares, depending on your > application's needs. > > Jeff Yes... I don't intend to make it mutable anymore... thanks to Jeff for the self.label.configure i don't even know about the configure method. I m very new to tkinter. Thanks everyone!!! From hammer777123 at gmail.com Mon Aug 16 21:53:50 2010 From: hammer777123 at gmail.com (hammer777123) Date: Mon, 16 Aug 2010 18:53:50 -0700 (PDT) Subject: RECEIVE $60 JUST FOR JOINING FREE MEMBERS Message-ID: RECEIVE $60 JUST FOR JOINING FREE MEMBERS http://tinyurl.com/2dwcgxf Join for Free and Get $10 http://www.geostring.com/?1226648 NewaveMoneyMaker__FREE 30 Day Trial__4,650 Followers In 7 days http://tinyurl.com/2gx63ye Want Better Than The "Average" P_ _ _ _ Size? 2 FREE Bottles http://mhlnk.com/DF434BFB Free $5.00 to Join___$0.5 Paid Per Click http://tinyurl.com/3xanc6c From ldo at geek-central.gen.new_zealand Mon Aug 16 22:00:32 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 17 Aug 2010 14:00:32 +1200 Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: In message , Roy Smith wrote: > 5) real intensity[160.0 : 30.0 : 0.01] How many elements in that array? a) 2999 b) 3000 c) neither of the above From roy at panix.com Mon Aug 16 22:29:27 2010 From: roy at panix.com (Roy Smith) Date: Mon, 16 Aug 2010 22:29:27 -0400 Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message , Roy Smith wrote: > > > 5) real intensity[160.0 : 30.0 : 0.01] > > How many elements in that array? > > a) 2999 > b) 3000 > c) neither of the above c) neither of the above. More specifically, 13,001 (if I counted correctly). From andrei.avk at gmail.com Mon Aug 16 22:35:49 2010 From: andrei.avk at gmail.com (AK) Date: Mon, 16 Aug 2010 22:35:49 -0400 Subject: 79 chars or more? Message-ID: <4C69F585.5050504@gmail.com> As monitors are getting bigger, is there a general change in opinion on the 79 chars limit in source files? I've experimented with 98 characters per line and I find it quite a bit more comfortable to work with that length, even though sometimes I have to edit files in 80 width terminals, it's still easier to adapt to some inconvenience when that happens than the other way around, since about 95% of time or more, I do use wider editor window or terminal. Is going over 79 still a terrible thing to do? -andrei From prologic at shortcircuit.net.au Mon Aug 16 22:42:19 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 17 Aug 2010 12:42:19 +1000 Subject: 79 chars or more? In-Reply-To: <4C69F585.5050504@gmail.com> References: <4C69F585.5050504@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: > As monitors are getting bigger, is there a general change in opinion on > the 79 chars limit in source files? I've experimented with 98 characters > per line and I find it quite a bit more comfortable to work with that > length, even though sometimes I have to edit files in 80 width > terminals, it's still easier to adapt to some inconvenience when that > happens than the other way around, since about 95% of time or more, I do > use wider editor window or terminal. > > Is going over 79 still a terrible thing to do? ?-andrei My personal opinion (despite monitors being wider) is the horizontal scrolling isn't worth it. Stick to a 80-char width. cheers james -- -- James Mills -- -- "Problems are solved by method" From roy at panix.com Mon Aug 16 22:50:57 2010 From: roy at panix.com (Roy Smith) Date: Mon, 16 Aug 2010 22:50:57 -0400 Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> Message-ID: In article , James Mills wrote: > On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: > > As monitors are getting bigger, is there a general change in opinion on > > the 79 chars limit in source files? I've experimented with 98 characters > > per line and I find it quite a bit more comfortable to work with that > > length, even though sometimes I have to edit files in 80 width > > terminals, it's still easier to adapt to some inconvenience when that > > happens than the other way around, since about 95% of time or more, I do > > use wider editor window or terminal. > > > > Is going over 79 still a terrible thing to do? ??-andrei > > My personal opinion (despite monitors being wider) is > the horizontal scrolling isn't worth it. Stick to a 80-char width. I disagree with James. I have no problem with going wider than 80, if it improves readability by not forcing you to fold lines in unnatural places. There's more important things to worry about. From andrei.avk at gmail.com Mon Aug 16 22:59:17 2010 From: andrei.avk at gmail.com (AK) Date: Mon, 16 Aug 2010 22:59:17 -0400 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> Message-ID: <4C69FB05.7070307@gmail.com> On 08/16/2010 10:42 PM, James Mills wrote: > On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: >> As monitors are getting bigger, is there a general change in opinion on >> the 79 chars limit in source files? I've experimented with 98 characters >> per line and I find it quite a bit more comfortable to work with that >> length, even though sometimes I have to edit files in 80 width >> terminals, it's still easier to adapt to some inconvenience when that >> happens than the other way around, since about 95% of time or more, I do >> use wider editor window or terminal. >> >> Is going over 79 still a terrible thing to do? -andrei > > My personal opinion (despite monitors being wider) is > the horizontal scrolling isn't worth it. Stick to a 80-char width. But.. why horizontal scrolling, isn't autowrap much better than that? -andrei From prologic at shortcircuit.net.au Mon Aug 16 23:00:51 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 17 Aug 2010 13:00:51 +1000 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 12:50 PM, Roy Smith wrote: > I disagree with James. ?I have no problem with going wider than 80, if > it improves readability by not forcing you to fold lines in unnatural > places. > > There's more important things to worry about. Roy, under normal circumstances I would agree with you and have a different opinion. However being vision impaired restricts the available width (irregardless of the width of the monitor) of text I'm able to view at once. :) cheers James -- -- James Mills -- -- "Problems are solved by method" From sigma.z.1980 at gmail.com Mon Aug 16 23:07:14 2010 From: sigma.z.1980 at gmail.com (Aram Ter-Sarkissov) Date: Mon, 16 Aug 2010 20:07:14 -0700 (PDT) Subject: array manipulation- Message-ID: hi, this is probably a very silly question, but I can't get my hear around it unfortunately( I have an array (say, mat=rand(3,5)) from which I 'pull out' a row (say, s1=mat[1,]). The problem is, the shape of this row s1 is not [1,5], as I would expect, but rather [5,], which means that I can't, for example, concateante mat and s1 rowwise. thanks for the help From kreglet at gmail.com Mon Aug 16 23:33:55 2010 From: kreglet at gmail.com (kreglet) Date: Mon, 16 Aug 2010 22:33:55 -0500 Subject: bash: syntax error near unexpected token Message-ID: Hello, I started learning python last year. All of this time i have used the terminal and gedit to create, modify, and test my applications and modules. For some reason I can not do this any more. I'll try to do my best to explain whats happening. I have a script modtest.py which has a function to test if an int is even or odd. Before: desktop:~/bin$ modtest.py desktop:~/bin$ evenodd(45) 45 is odd Now: desktop:~/bin$ modtest.py desktop:~/bin$ evenodd(45) bash: syntax error near unexpected token `45' The above is just an example. ALL of my scripts that worked before no longer work in the terminal yet they work in the python interpreter. Does anyone know what the problem might be and how I can fix it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Mon Aug 16 23:40:42 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 16 Aug 2010 23:40:42 -0400 Subject: bash: syntax error near unexpected token In-Reply-To: References: Message-ID: On Mon, Aug 16, 2010 at 11:33 PM, kreglet wrote: > Hello, > > I started learning python last year. All of this time i have used the > terminal and gedit to create, modify, and test my applications and modules. > For some reason I can not do this any more. > I'll try to do my best to explain whats happening. > > I have a script modtest.py which has a function to test if an int is even or > odd. > > Before: > desktop:~/bin$ modtest.py > desktop:~/bin$ evenodd(45) > 45 is odd > That never worked. You can execute Python scripts from the shell, but not arbitrary Python functions. Perhaps you were calling Python using the -i flag, which runs the interactive interpreter after the script is finished executing. $ python -i modtest.py >>> evenodd(45) 45 is odd > Now: > desktop:~/bin$ modtest.py > desktop:~/bin$ evenodd(45) > bash: syntax error near unexpected token `45' > And this is what's supposed to happen any time you try this in any shell. When you call evenodd, bash looks for a program or shell built-in called evenodd. Which doesn't exist. > The above is just an example. ALL of my scripts that worked before no longer > work in the terminal yet they work in the python interpreter. > > Does anyone know what the problem might be and how I can fix it? > > From steve-REMOVE-THIS at cybersource.com.au Mon Aug 16 23:51:19 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 17 Aug 2010 03:51:19 GMT Subject: 79 chars or more? References: Message-ID: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 22:35:49 -0400, AK wrote: > As monitors are getting bigger, is there a general change in opinion on > the 79 chars limit in source files? I've experimented with 98 characters > per line and I find it quite a bit more comfortable to work with that > length, even though sometimes I have to edit files in 80 width > terminals, it's still easier to adapt to some inconvenience when that > happens than the other way around, since about 95% of time or more, I do > use wider editor window or terminal. > > Is going over 79 still a terrible thing to do? -andrei For your own code, you are free to do anything you like :) But if you want to submit code to the Python standard library, you have to restrict lines to 79 characters. This is no different from any other project -- you need to stick to the project's coding conventions. There are still good reasons to stick with 79 chars, even on large screen monitors. People with poor vision will appreciate being able to increase the font size. Others might like to have two windows side-by-side, each showing 79 characters. Some people don't have wide monitors. -- Steven From robert.kern at gmail.com Mon Aug 16 23:56:20 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 16 Aug 2010 22:56:20 -0500 Subject: Python "why" questions In-Reply-To: References: <8crequF9tpU1@mid.individual.net> Message-ID: On 8/16/10 9:29 PM, Roy Smith wrote: > In article, > Lawrence D'Oliveiro wrote: > >> In message, Roy Smith wrote: >> >>> 5) real intensity[160.0 : 30.0 : 0.01] >> >> How many elements in that array? >> >> a) 2999 >> b) 3000 >> c) neither of the above > > c) neither of the above. More specifically, 13,001 (if I counted > correctly). 13000, actually. Floating point is a bitch. [~/Movies] |1> import numpy [~/Movies] |2> len(numpy.r_[160.0:30.0:-0.01]) 13000 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Mon Aug 16 23:58:33 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 16 Aug 2010 22:58:33 -0500 Subject: array manipulation- In-Reply-To: References: Message-ID: On 8/16/10 10:07 PM, Aram Ter-Sarkissov wrote: > hi, this is probably a very silly question, but I can't get my hear > around it unfortunately( > > I have an array (say, mat=rand(3,5)) from which I 'pull out' a row > (say, s1=mat[1,]). The problem is, the shape of this row s1 is not > [1,5], as I would expect, but rather [5,], which means that I can't, > for example, concateante mat and s1 rowwise. > > thanks for the help You can ask numpy questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From jah.alarm at gmail.com Tue Aug 17 00:07:09 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Mon, 16 Aug 2010 21:07:09 -0700 (PDT) Subject: update of elements in GUI Message-ID: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> hi, I've already asked this question but so far the progress has been small. I'm running Tkinter. I have some elements on the screen (Labels, most importantly) which content has to be updated every iteration of the algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm using the update_idletasks() command in the function itself after the variable.set(...) command. The variable type is IntVar(), and the mistake I'm getting is 'IntVar instance has no attribute 'update_idletasks'. No updates are displayed, of course. Without the GUI the algorithm (it's a genetic algorithm) is working fine, but I need to make it available to other people via GUI cheers, Alex From steve-REMOVE-THIS at cybersource.com.au Tue Aug 17 00:10:31 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 17 Aug 2010 04:10:31 GMT Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> Message-ID: <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> On Mon, 16 Aug 2010 22:56:20 -0500, Robert Kern wrote: > On 8/16/10 9:29 PM, Roy Smith wrote: >> In article, >> Lawrence D'Oliveiro wrote: >> >>> In message, Roy Smith wrote: >>> >>>> 5) real intensity[160.0 : 30.0 : 0.01] >>> >>> How many elements in that array? >>> >>> a) 2999 >>> b) 3000 >>> c) neither of the above >> >> c) neither of the above. More specifically, 13,001 (if I counted >> correctly). > > 13000, actually. Floating point is a bitch. > > [~/Movies] > |1> import numpy > > [~/Movies] > |2> len(numpy.r_[160.0:30.0:-0.01]) > 13000 Actually, the answer is 0, not 13000, because the step size is given as 0.01, not -0.01. >>> import numpy >>> len(numpy.r_[160.0:30.0:-0.01]) 13000 >>> len(numpy.r_[160.0:30.0:0.01]) 0 -- Steven From tom.harris at setec.com.au Tue Aug 17 00:11:40 2010 From: tom.harris at setec.com.au (Tom Harris) Date: Tue, 17 Aug 2010 14:11:40 +1000 Subject: Eval cannot see globals from another module Message-ID: <668645A55F306549B1C6D0D0602A2F9C831230@mail1.mel.setec.com.au> Greetings, I want a debugging function with the effect of the function below (in a seperate module): def dump(expr): print expr, '=', eval(expr) foo = 33 dump('foo') Of course this fails when called from another module because eval does not know the globals or locals of the caller. Is there a way to make this work? TomH -------- Email from setec.com.au does not necessarily represent the official policy of SETEC Pty Ltd. See http://www.setec.com.au/emaildisclaimer20060629.html for details. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrei.avk at gmail.com Tue Aug 17 00:12:47 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 00:12:47 -0400 Subject: 79 chars or more? In-Reply-To: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> Message-ID: <4C6A0C3F.9060900@gmail.com> On 08/16/2010 11:51 PM, Steven D'Aprano wrote: > On Mon, 16 Aug 2010 22:35:49 -0400, AK wrote: > >> As monitors are getting bigger, is there a general change in opinion on >> the 79 chars limit in source files? I've experimented with 98 characters >> per line and I find it quite a bit more comfortable to work with that >> length, even though sometimes I have to edit files in 80 width >> terminals, it's still easier to adapt to some inconvenience when that >> happens than the other way around, since about 95% of time or more, I do >> use wider editor window or terminal. >> >> Is going over 79 still a terrible thing to do? -andrei > > For your own code, you are free to do anything you like :) > > But if you want to submit code to the Python standard library, you have > to restrict lines to 79 characters. This is no different from any other > project -- you need to stick to the project's coding conventions. > > > There are still good reasons to stick with 79 chars, even on large screen > monitors. People with poor vision will appreciate being able to increase > the font size. Others might like to have two windows side-by-side, each > showing 79 characters. Some people don't have wide monitors. There's no doubt that there are pro's and con's, but to be fair, it's not like code becomes unreadable over 79 chars - the difference is that when your terminal is 80 chars, it's less convenient for you to read code that's wider and when your terminal is wider, it's less convenient to read code that's 79 chars. I guess I'm just curious what percentage of people prefer 79chars - is it 5/95% or 15/85% or 50/50? -andrei > > > > From prologic at shortcircuit.net.au Tue Aug 17 00:26:29 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 17 Aug 2010 14:26:29 +1000 Subject: 79 chars or more? In-Reply-To: <4C6A0C3F.9060900@gmail.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 2:12 PM, AK wrote: > There's no doubt that there are pro's and con's, but to be fair, it's > not like code becomes unreadable over 79 chars - the difference is that > when your terminal is 80 chars, it's less convenient for you to read > code that's wider and when your terminal is wider, it's less convenient > to read code that's 79 chars. I guess there are two-sides to the coin here so to speak. See I'm vision impaired so I prefer a 79 char width in my own projects and expect those that work with me to use the same standards (stick to project standards as Steven says). The other side is this... I'm of the opinion that if you're writing a line of code that's excessively long (>80char or say >100chars), then you might want to reconsider what you're doing :) (It might be wrong). cheers james -- -- James Mills -- -- "Problems are solved by method" From cbrown at cbrownsystems.com Tue Aug 17 00:31:50 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Mon, 16 Aug 2010 21:31:50 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> Message-ID: <97d677a0-8d15-4d18-9e06-74eef08bd39c@q16g2000prf.googlegroups.com> On Aug 16, 11:04?am, Baba wrote: > Hi Chas, Roald, > > These are all complicated formula that i believe are not expected at > this level. If you look at the source (see my first submission) you > will see that this exercise is only the second in a series called > "Introduction to Programming". Therefore i am convinced that there is > a much simpler solution. The question I was responding to (a different one than your original question) was whether there was a proof of Baba's conjecture that a largest unobtainable quantity was possible if, and only if, the three numbers in question had a gcd of 1. Roald had something like a "gut feeling" that it was true, but such things are generally much more clear cut than "gut feelings" - they can often easily be /proven/ to be true or false, given the right mental tools. In this case, that proof I gave doesn't immediately yield a concrete answer to your /original/ question - assuming that a largest obtainable solution is possible, /how/ do we find the largest unobtainable solution? But it certainly identifies the conditions whereby we can easily and quickly say that there is no such solution, or conversely that such a solution must exist; and that is often extremely helpful to finding an algorithm that /does/ answer your original question. (One thing it does provide is an upper bound to the space of solutions that you should be looking at - and finding upper bounds and lower bounds is a common programming task. Again, this isn't something that you might be "expected" to know about at your level of study, but it doesn't hurt you to be aware of it either :)!) > > Now, i believe that the number of consecutive passes required to make > this work is equal to the smallest number of pack sizes. That is your belief, your intuition; and developing good intuitions is good... BUT... > So if we have > packs of (9,12,21) the number of passes needed would be 9 and... ... and now whatever you might go on to add is simply "going off into the weeds", because I have just proven that there can be /no/ such solution in that case: all three of those numbers are divisible by 3, so you are not "on the trail" when trying to figure out a general solution by considering examples of the type you mention. At your level of study, such things may seem overly complicated (and are certainly /not/ required to simply answer the question as originally stated). But consider the thread in this group called "python interview questions": http://groups.google.com/group/comp.lang.python/browse_frm/thread/bb4d3514e9842f9e# The "FizzBuzz" question involves a similar very basic grasp of the type of mathematical reasoning and thinking that is most valued in programmers in the job market. Of course, your Python class is not the right place to be focusing exclusively on this sort of mathematics, but I would encourage you to simultaneously educate yourself both in the /language/ learning of Python (which is what your class is largely about), along with the more universally applicable skill set that comes from understanding the mathematical justifications of a "good" algorithm That additional knowledge will serve you equally well whether you are programming in Python, Perl, Ruby, Java, C++, D, F, R, and so on (surely someone will claim "Z" as a language soon, if they haven't already...). > ... the > theorem would read > > "If it is possible to buy n,n+1,n+2,...n+8 nuggets it is possible to > buy any number of nuggets >= 9 given that they come in packs of > 9,12,21" > So I would ask as a simple exercise: how would you go about /proving/ that your assertion is actually a /theorem/, and not just a pretty solid hunch that your statement is true because for small enough numbers you can easily "do it in your head"? Yes, it's "clearly true", but that is not a proof! That is the muscle which is exercised by mathematical reasoning. > However i turn in circles because i don't seem to get any results for > some random pack combinations like (9,12,21) or (10,20,30). > Well, your intuitions are certainly close to the mark. But if you added to your study a course on discrete mathematics, then you would also immediately see why such turning in circles obviously can bear no fruit, and that would give you a great advantage in solving far more difficult and yet common problems of this type. Cheers - Chas From woooee at gmail.com Tue Aug 17 00:47:24 2010 From: woooee at gmail.com (woooee) Date: Mon, 16 Aug 2010 21:47:24 -0700 (PDT) Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> Message-ID: On Aug 16, 9:07?pm, Jah_Alarm wrote: I have some elements on the screen (Labels, most > importantly) which content has to be updated every iteration of the > algorithm The variable type is IntVar() You would use int_var_name.set(some_number) From andrei.avk at gmail.com Tue Aug 17 00:50:39 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 00:50:39 -0400 Subject: 79 chars or more? In-Reply-To: References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> Message-ID: <4C6A151F.7070803@gmail.com> On 08/17/2010 12:26 AM, James Mills wrote: > On Tue, Aug 17, 2010 at 2:12 PM, AK wrote: >> There's no doubt that there are pro's and con's, but to be fair, it's >> not like code becomes unreadable over 79 chars - the difference is that >> when your terminal is 80 chars, it's less convenient for you to read >> code that's wider and when your terminal is wider, it's less convenient >> to read code that's 79 chars. > > I guess there are two-sides to the coin here so to speak. See I'm > vision impaired > so I prefer a 79 char width in my own projects and expect those that work > with me to use the same standards (stick to project standards as Steven says). > > The other side is this... I'm of the opinion that if you're writing a > line of code > that's excessively long (>80char or say>100chars), then you might want to > reconsider what you're doing :) (It might be wrong). I stay away from ugly cramped one-liners; I mostly run over 79 when I have a few `and` and `or` clauses or long strings. I've also noticed something interesting: going from 79 to 99 affects a relatively large number of lines, but going over 99 (i.e. 99 to 132) is much, much rarer. By the way, the reason I asked is that we're working on a python tutorial and I realized that even though I'm used to 99, I wasn't sure if it's ok to teach that to new users or not.. -andrei From prologic at shortcircuit.net.au Tue Aug 17 01:08:53 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 17 Aug 2010 15:08:53 +1000 Subject: 79 chars or more? In-Reply-To: <4C6A151F.7070803@gmail.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <4C6A151F.7070803@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 2:50 PM, AK wrote: > By the way, the reason I asked is that we're working on a python > tutorial and I realized that even though I'm used to 99, I wasn't sure > if it's ok to teach that to new users or not.. In my opinion it would be "okay" to teach. However: Bare in mind other considerations for smaller width conventions and the reasons for them. Make your students aware of standards and get them into the habit of following standards early on. cheers James -- -- James Mills -- -- "Problems are solved by method" From torriem at gmail.com Tue Aug 17 01:15:53 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 16 Aug 2010 23:15:53 -0600 Subject: 79 chars or more? In-Reply-To: <4C69FB05.7070307@gmail.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> Message-ID: <4C6A1B09.6070905@gmail.com> On 08/16/2010 08:59 PM, AK wrote: > But.. why horizontal scrolling, isn't autowrap much better than that? Wouldn't it really make a visual mess of Python code if lines wrapped? Maybe if they wrapped smartly. In general, the only time I find my lines longer than 75 characters are strings or sometimes conditionals for if statements. But normally I can wrap them manually so that things look neat and tidy. In general if I find myself consistently going longer than 75 or 80 characters, I need to refactor my code to make it more manageable. If I have to scroll up five pages to find the beginning of a block, that normally means my code could be simplified and improved. From torriem at gmail.com Tue Aug 17 01:20:51 2010 From: torriem at gmail.com (Michael Torrie) Date: Mon, 16 Aug 2010 23:20:51 -0600 Subject: 79 chars or more? In-Reply-To: <4C6A151F.7070803@gmail.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <4C6A151F.7070803@gmail.com> Message-ID: <4C6A1C33.8040206@gmail.com> On 08/16/2010 10:50 PM, AK wrote: > I stay away from ugly cramped one-liners; I mostly run over 79 when I > have a few `and` and `or` clauses or long strings. I've also noticed > something interesting: going from 79 to 99 affects a relatively large > number of lines, but going over 99 (i.e. 99 to 132) is much, much rarer. I have found something similar, despite my previous post. But you can normally break the and and or long clauses with backslash line-continuators. You can also break strings similarly: a = "This is a really long line that ordinarily would " \ "be long. Test message: %s " % ( message_string) > By the way, the reason I asked is that we're working on a python > tutorial and I realized that even though I'm used to 99, I wasn't sure > if it's ok to teach that to new users or not.. I wouldn't worry about it if I were you. Once they know how to program in Python then you can work on that. Probably more important to be taught the reasons behind PEP8. You could probably say that many coders recommend that lines not exceed 80 characters, and state that code in the standard library has to be less than that, but that on occasion longer lines are probably not going to kill them. From eric.brunel at pragmadev.nospam.com Tue Aug 17 03:19:59 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Tue, 17 Aug 2010 09:19:59 +0200 Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> Message-ID: In article <24dc97b3-a8b5-4638-9cf5-a397f1eae295 at q16g2000prf.googlegroups.com>, Jah_Alarm wrote: > hi, I've already asked this question but so far the progress has been > small. > > I'm running Tkinter. I have some elements on the screen (Labels, most > importantly) which content has to be updated every iteration of the > algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm > using the update_idletasks() command in the function itself after the > variable.set(...) command. The variable type is IntVar(), and the > mistake I'm getting is 'IntVar instance has no attribute > 'update_idletasks'. No updates are displayed, of course. You have to call update_idletasks on a Tkinter *widget*, not a variable. You can call it on your window (Tk or Toplevel instance) or on your label for example. This way, it should work. > Without the GUI the algorithm (it's a genetic algorithm) is working > fine, but I need to make it available to other people via GUI > > cheers, > > Alex From eric.brunel at pragmadev.nospam.com Tue Aug 17 03:21:59 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Tue, 17 Aug 2010 09:21:59 +0200 Subject: Textvariable display in label (GUI design) References: <993d9560-564d-47f0-b2db-6f0c6404ae81@g6g2000pro.googlegroups.com> Message-ID: In article , Jah_Alarm wrote: > On Aug 17, 3:32??am, Eric Brunel > wrote: > > In article > > <993d9560-564d-47f0-b2db-6f0c6404a... at g6g2000pro.googlegroups.com>, > > > > ??Jah_Alarm wrote: > > > hi, > > > > > pls help me out with the following issue: I wrote a function that uses > > > a for loop that changes a value of a certain variable each iteration. > > > What I want is by clicking a button in GUI (with the command bound to > > > this function) this value each iteration is displayed in a textbox > > > (label). So far only one (starting value) is displayed. > > > > > thanks, > > > > > Alex > > > > First, with posts like this, you're highly unlikely to get any useful > > answer: please strip down your code to the smallest part that displays > > the problem, post this code here, explaining what you're expecting and > > what you're getting. Otherwise, people just won't know what you're > > talking about unless they have a crystal ball?? > > > > Now using my own crystal ball: if you don't return the control to the > > GUI each time your variable is increased, the GUI won't get a chance to > > update itself. Since you seem to use Tkinter (another wild guess??), you > > probably need a call to the update_idletasks method on any Tkinter > > widget each time you change your TextVariable. > > > > HTH > > ??- Eric - > > Thanks, but where is this command used, in the button than runs the > algorithm, the label or the function itself? Wherever you want, the only requirement being that you should have a widget at hand, in a class attribute or a global variable or whatever. I would put it just after I do any my_variable.set(???) if possible. From __peter__ at web.de Tue Aug 17 03:23:09 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Aug 2010 09:23:09 +0200 Subject: 2 Regex Questions References: <4f350848-9f12-4c0d-aaaa-a35467b3f3a4@c10g2000yqi.googlegroups.com> Message-ID: AlphaBravo wrote: > 2) How can I split a string into sections that MATCH a regex (rather > then splitting by seperator). Tokenizer-style but ignoring every place > from where I can't start a match? >>> import re >>> re.compile("[abc]+").findall("abcxaaa! abba") ['abc', 'aaa', 'abba'] From ldo at geek-central.gen.new_zealand Tue Aug 17 03:47:38 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 17 Aug 2010 19:47:38 +1200 Subject: 79 chars or more? References: Message-ID: In message , AK wrote: > As monitors are getting bigger, is there a general change in opinion on > the 79 chars limit in source files? WHAT 79-character limit in source files? I currently have my Emacs windows set at 100 characters wide, and I?m thinking of going wider. Remember, the old hardcopy terminals used to produce 132-character-wide listings. From michele.simionato at gmail.com Tue Aug 17 03:59:12 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 17 Aug 2010 00:59:12 -0700 (PDT) Subject: 79 chars or more? References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> Message-ID: <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> On Aug 17, 6:50?am, AK wrote: > On 08/17/2010 12:26 AM, James Mills wrote: > By the way, the reason I asked is that we're working on a python > tutorial and I realized that even though I'm used to 99, I wasn't sure > if it's ok to teach that to new users or not.. > > ? ?-andrei It is certainly NOT useful to teach a convention which is explicitly discouraged in the Python guidelines (PEP 8). Having said that, I particularly *hate* people using long lines, and I usually reindent the code of my coworkers not following that convention. The reason is that my Emacs is set to 79 chars and longer code looks ugly, that I look at two-side diffs all the time, and that sometimes I want to print on paper the code I have to work with. OTOH, I do not see a single advantage in using long lines. Michele Simionato From torbenm at diku.dk Tue Aug 17 04:17:58 2010 From: torbenm at diku.dk (Torben Ægidius Mogensen) Date: Tue, 17 Aug 2010 10:17:58 +0200 Subject: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <7zaaolzm89.fsf@ask.diku.dk> Standish P writes: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? > > Because a stack has push and pop, it is able to release and allocate > memory. We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. See http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 http://portal.acm.org/citation.cfm?doid=174675.177855 http://www.springerlink.com/content/m2074884n6gt612h/ Torben From giacomo.boffi at polimi.it Tue Aug 17 04:48:51 2010 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Tue, 17 Aug 2010 10:48:51 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <7x1va4tbtm.fsf@ruckus.brouhaha.com> Message-ID: <86wrrppqto.fsf@aiuole.stru.polimi.it> Paul Rubin writes: > Baba writes: >> exercise: given that packs of McNuggets can only be bought in 6, 9 or >> 20 packs, write an exhaustive search to find the largest number of >> McNuggets that cannot be bought in exact quantity. > > Is that a homework problem? yes, and no it was a homework problem, assigned in 2008, as clearly stated by the OP most of what was discussed on the ng was clearly stated in the introduction to the actual problem, so that we can thank Baba for NOT having read the text of the assignment, leavin' us a couple of days of amusing and interesting posts -- Mangiate pure le vostre carote, noi mangeremo le nostre salsicce! -- Claud, in IHC From hpj at urpla.net Tue Aug 17 05:08:39 2010 From: hpj at urpla.net (Hans-Peter Jansen) Date: Tue, 17 Aug 2010 11:08:39 +0200 Subject: segfault with small pyqt script In-Reply-To: References: <201008152317.13757.hpj@urpla.net> Message-ID: <201008171108.39638.hpj@urpla.net> On Monday 16 August 2010, 09:22:27 Gelonida wrote: > Hi Hans-Peter, > > > It seems, that my other posts did not get through. > > On 08/15/2010 11:17 PM, Hans-Peter Jansen wrote: > > For a starter, tell us the versions of python-sip, and python-qt4 or > > however they're called in Ubuntu. For the record, > > python-sip-4.10.5-1.1 > > python-qt4-4.7.4-1.1 > > doesn't show this behavior. > > > > The problem seems to be known for 4.7.2. > For simple code I managed to work around the issue. > For the real more complicated I didn't. So it seems > I'll have to avoid 4.7.2. > [...] > > For more complex multi widget examples it doesn't seem enough to just > destroy the main widget. > probably I had to recursively assign all widgets / dialogues sub widgets > to None. > > So I'll just try to stay away from this pyqt release and stick with > older or newer ones. If you test sip 4.10.5 by chance, it would be nice to leave a brief note about the outcome. As long as you replace (qscintilla, if you use it), sip and PyQt, the probability of a bad influence on your system is pretty small. Replacing PyKDE aka kdebindings4 might not be that easy, though.. I might even get around also building Ubuntu packages in openSUSE build service one day... Various openSUSE builds are available here: http://download.opensuse.org/repositories/home:/frispete:/pyqt/ Pete From jeanmichel at sequans.com Tue Aug 17 05:28:33 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 17 Aug 2010 11:28:33 +0200 Subject: 79 chars or more? In-Reply-To: <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> Message-ID: <4C6A5641.4070109@sequans.com> Michele Simionato wrote: > On Aug 17, 6:50 am, AK wrote: > >> On 08/17/2010 12:26 AM, James Mills wrote: >> By the way, the reason I asked is that we're working on a python >> tutorial and I realized that even though I'm used to 99, I wasn't sure >> if it's ok to teach that to new users or not.. >> >> -andrei >> > > It is certainly NOT useful to teach a convention which is explicitly > discouraged in the Python guidelines (PEP 8). Having said that, I > particularly *hate* people using long lines, and I usually reindent > the code of my coworkers not following that convention. > The reason is that my Emacs is set to 79 chars and longer code looks > ugly, that I look at two-side diffs all the time, and that sometimes I > want to print on paper the code I have to work with. OTOH, I do not > see a single advantage in using long lines. > > Michele Simionato > Using long lines can sometimes improve readability, procude better shaped code, 'cause wrapping code to 79 chars may not be "natural" in all cases. We do have a strong habit using meaningfull & plain names in our code, no i, j, k ; cmdLine is always replaced by commandLine. So lines can easily exceed 79 chars and wrapping it would'nt be easy. I'm not saying wrapping to 79 is wrong, I'm just saying that they are advantages of using long lines (the 1st obvious one being not to care about wrapping text). Saying that, if one intend to distribute its code, he should stick to 80 chars per line. JM From ariel.bys at gmail.com Tue Aug 17 05:35:24 2010 From: ariel.bys at gmail.com (AlphaBravo) Date: Tue, 17 Aug 2010 02:35:24 -0700 (PDT) Subject: 2 Regex Questions References: <4f350848-9f12-4c0d-aaaa-a35467b3f3a4@c10g2000yqi.googlegroups.com> Message-ID: On Aug 17, 10:23?am, Peter Otten <__pete... at web.de> wrote: > AlphaBravo wrote: > > ?2) How can I split a string into sections that MATCH a regex (rather > > then splitting by seperator). Tokenizer-style but ignoring every place > > from where I can't start a match? > >>> import re > >>> re.compile("[abc]+").findall("abcxaaa! abba") > > ['abc', 'aaa', 'abba'] Thanks for 2 From jah.alarm at gmail.com Tue Aug 17 05:49:46 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Tue, 17 Aug 2010 02:49:46 -0700 (PDT) Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> Message-ID: <26c363c8-11d7-49b9-a1c1-251ab5ff934e@p22g2000pre.googlegroups.com> thanks. The thing is, the objects actually get updated without this command, but when I run the GUI outside of python shell (i.e. in command prompt as python filename.py or compile it to .exe file) the objects do not get updated. I tried Label(mainframe,textvariable=var).grid(column=1,row=1).update_idletasks() and mainframe.update_idletasks() but it still doesn't work. On Aug 17, 7:19?pm, Eric Brunel wrote: > In article > <24dc97b3-a8b5-4638-9cf5-a397f1eae... at q16g2000prf.googlegroups.com>, > > ?Jah_Alarm wrote: > > hi, I've already asked this question but so far the progress has been > > small. > > > I'm running Tkinter. I have some elements on the screen (Labels, most > > importantly) which content has to be updated every iteration of the > > algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm > > using the update_idletasks() command in the function itself after the > > variable.set(...) command. The variable type is IntVar(), and the > > mistake I'm getting is 'IntVar instance has no attribute > > 'update_idletasks'. No updates are displayed, of course. > > You have to call update_idletasks on a Tkinter *widget*, not a variable. > You can call it on your window (Tk or Toplevel instance) or on your > label for example. This way, it should work. > > > > > Without the GUI the algorithm (it's a genetic algorithm) is working > > fine, but I need to make it available to other people via GUI > > > cheers, > > > Alex From tania786786 at gmail.com Tue Aug 17 05:53:58 2010 From: tania786786 at gmail.com (tania tani) Date: Tue, 17 Aug 2010 02:53:58 -0700 (PDT) Subject: EARN 10$ PER ADVERTISEMENT OF 60 SEC Message-ID: MESSAGE NO 1 FOR YOU READ IT. http://www.fineptc.com/index.php?ref=imranraza460 Hello my dear friend, I hope you will be fine. i want to tell you the authentic way to make money with no investment. Here you can make 60 dollars in just six minutes. No investment its free.....Trial is essential... 1 Just click on the obove link 2 create your account on the website. ( it will take 2 or three minutesits absouloutely free no subscription fee ) 3 Now loging with your username and the password 4 Then click on the "" view adds"" tab 5 There will be 6 or 7 adds links ( consisting 60 seconds each ) 6 Click on a particular add and watch it for 1 min. (when you click on a add link , remember open one add at a time. a new window will be open and a countdown timing for one minute will be start on upper left side of the web page when its staps you will be asked to click a specific number eg click 1 1 2 3 4. you have to click on it) 7 This one minute add will give you 10 US $ DOLLAR. 8 Hence watch other adds one by one. 9 Finally you will find 60 dollars on you status by checking "' my account "' 10 You have earned 60 dollars you can repeat you view adds again on next day moreover if you introduce a new guy with your reffence you will be entitled to get 50% of the refferal(which means that if the person reffered by you take his /her adds daily he will receives dollars you will be 50% of his/her daily work. Trust me its free and its really works 11 This is not a Fake.This is 100% sure you will get your money. CLICK ON THE ABOVE LINK NEAR "MESSAGE NO 1 FOR YOU"..........RIGHT NOW IMPORTANT INSTRUCTIONS: YOU CAN TAKE YOUR UNIQUE REFFERAL LINK BY CLICKING ON "PROMOTE" OPTION ON THE WEB SITE. YOU CAN FEED BACK ME ON THIS E MAIL ID. "imran.raza460 at gmail.com" ____________________________________________________________________________________________ MESSAGE NO 2 FOR YOU READ IT. http://www.buxbillionaire.com/?ref=imranraza460 Hello my dear friend, I hope you will be fine. i want to tell you the authentic way to make money with no investment. Here you can make 80 OR 40 US $ dollars in just six minutes. No investment its free.....Trial is essential... 1 Just click on the obove link 2 create your account on the website. ( it will take 2 or three minutesits absouloutely free no subscription fee ) 3 Now loging with your username and the password 4 Then click on the "" view adds"" tab 5 There will be 4 or 8 adds links ( consisting 60 seconds each ) 6 Click on a particular add and watch it for 1 min. (when you click on a add link , remember open one add at a time. a new window will be open and a countdown timing for one minute will be start ons upper left side of the web page when its staps you will be asked to click a specific number eg click 05 05 02 03 04. click on 05 you have to click on it) 7 This one minute add will give you 10 US $ DOLLAR. 8 Hence watch other adds one by one. 9 Finally you will find 40 or some time 80 US $ dollars on you status by checking "' my account "' 10 You have earned 60 dollars you can repeat your view adds again on next day moreover if you introduce a new guy with your reffence you will be entitled to get 10 $ per click of the reffferal(which means that if the person reffered by you take his /her adds daily you will be received 10 $ per add of his/ her daily work.means equal to him/her Trust me its free and its really works 11 This is not a Fake.This is 100% sure you will get your money. CLICK ON THE ABOVE LINK near " MESSAGE NO 2 FOR YOU..........RIGHT NOW IMPORTANT INSTRUCTIONS: YOU CAN TAKE YOUR UNIQUE REFFERAL LINK BY CLICKING ON "PROMOTION TOLLS" OPTION ON THE WEB SITE. YOU CAN FEED BACK ME ON THIS E MAIL ID. "imran.raza460 at gmail.com" _____________________________________________________________________________________________ MESSAGE NO 3 FOR YOU READ IT. http://www.buxmillionaire.com/?ref=imranraza460 Hello my dear friend, I hope you will be fine. i want to tell you the authentic way to make money with no investment. Here you can make 230 US $ dollars in just 23 minutes. No investment its free.....Trial is essential... 1 Just click on the obove link 2 create your account on the website. ( it will take 2 or three minutesits absouloutely free no subscription fee ) 3 Now loging with your username and the password ( also enter security code shown below password ) 4 Then click on the "" view adds"" tab 5 There will be 4 or 8 adds links ( consisting 60 seconds each ) 6 Click on a particular add and watch it for 1 min. (when you click on a add link , remember open one add at a time. a new window will be open and a countdown timing for one minute will be start ons upper left side of the web page when its staps you will be asked to click a specific number eg click 05 05 02 03 04. click on 05 you have to click on it) 7 This one minute add will give you 10 US $ DOLLAR. 8 Hence watch other adds one by one. 9 Finally you will find 230 US $ dollars per day on your status by checking "' my account "' 10 You have earned 230 dollars you can repeat your view adds again on next day moreover if you introduce a new guy with your reffence you will be entitled to get 10 $ per click of the reffferal (which means that if the person reffered by you take his /her adds daily you will be received dollars. 10 $ per add of his/her daily work. Trust me its free and its really works 11 This is not a Fake.This is 100% sure you will get your money. CLICK ON THE ABOVE LINK near " MESSAGE NO 2 FOR YOU..........RIGHT NOW IMPORTANT INSTRUCTIONS: YOU CAN TAKE YOUR UNIQUE REFFERAL LINK BY CLICKING ON "PROMOTION TOLLS" OPTION ON THE WEB SITE. YOU CAN FEED BACK ME ON THIS E MAIL ID. "imran.raza460 at gmail.com" ________________________________________________________________________________________________ Another link for making money is here also try this one also http://www.bigextracash.com/aft/9b6cc578.html From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 17 06:42:00 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 17 Aug 2010 12:42:00 +0200 Subject: passing variables as object attributes In-Reply-To: References: Message-ID: <4c6a6773$0$9118$426a74cc@news.free.fr> Vikas Mahajan a ?crit : > On 16 August 2010 19:23, Nitin Pawar wrote: >> you would need to define a class first with its attiributes and then you may >> want to initiate the variables by calling the class initilializer >> > Actually I have to dynamically add attributes to a object. I am > writing python script for FreeCAD software. I am using loop to create > multiple cylinders and I am writing following code-: > cyname = "Cylinder" > FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) > FreeCAD.ActiveDocument.cyname.Radius= .5 > FreeCAD.ActiveDocument.cyname.Height= 10 > > And I am getting this error-: > AttributeError: 'App.Document' object has no attribute 'cyname' Indeed. > But when I use Cylinder in place of cyname, I am not getting any error. Of course. > Please help. I don't have FreeCAD installed, I won't install it, and I'm not going to read FreeCAD's doc neither, but you may want to check whether FreeCAD.ActiveDocument.addObject actually returns the newly created objet (which would be a sensible behaviour). If so, you'd just have to keep a ref to this object, ie: cylinder = FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) cylinder.Radius = 0.5 # etc Else, you can always get this ref using getattr, ie: FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname) cylinder = getattr(FreeCAD.ActiveDocument, cyname) cylinder.Radius = 0.5 # etc And while you're at it, you could save on both typing and execution time by keepin a ref to the document object itself: doc = FreeCAD.ActiveDocument for cyname in ("cylinder1, "cylinder2", "cylinderN"): doc.addObject("Part::Cylinder",cyname) cylinder = getattr(doc, cyname) cylinder.Radius = 0.5 # etc HTH From bartc at freeuk.com Tue Aug 17 06:50:32 2010 From: bartc at freeuk.com (BartC) Date: Tue, 17 Aug 2010 11:50:32 +0100 Subject: 79 chars or more? In-Reply-To: References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com><4C6A0C3F.9060900@gmail.com> Message-ID: "James Mills" wrote in message news:mailman.2222.1282019212.1673.python-list at python.org... > On Tue, Aug 17, 2010 at 2:12 PM, AK wrote: >> There's no doubt that there are pro's and con's, but to be fair, it's >> not like code becomes unreadable over 79 chars - the difference is that >> when your terminal is 80 chars, it's less convenient for you to read >> code that's wider and when your terminal is wider, it's less convenient >> to read code that's 79 chars. > > I guess there are two-sides to the coin here so to speak. See I'm > vision impaired > so I prefer a 79 char width in my own projects That's not a good argument for everyone else to do the same. Someone else might prefer 40 columns for similar reasons. (Anyway can't a 100-column width be squeezed into the same angular field as 80-columns, just by using a narrower font, when necessary? Assuming the problem is field width rather than acuity) > The other side is this... I'm of the opinion that if you're writing a > line of code > that's excessively long (>80char or say >100chars), then you might want to > reconsider what you're doing :) (It might be wrong). I generally use 100 columns. It's useful for being able to write same-line comments with meaningful content... (I've used 80-column hardware (teletypes and such) years ago, I thought such restrictions had vanished long ago) -- Bartc From jah.alarm at gmail.com Tue Aug 17 07:02:23 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Tue, 17 Aug 2010 04:02:23 -0700 (PDT) Subject: message box in Tkinter Message-ID: <61cbd1cb-bd6d-49aa-818f-d28c460980ea@x18g2000pro.googlegroups.com> I need to display a message box at the click of a button. I od the following: from Tkinter import * def msg1(): messagebox.showinfo(message='Have a good day') Button(mainframe,text="About",command=msg1()).grid(column=360,row=36,sticky=W) I get the error msg 'global name 'messagebox' is not defined' When I try importing messagebox from Tkinter i get an error message that this module doesn't exist. thanks From matt at scotweb.co.uk Tue Aug 17 07:20:52 2010 From: matt at scotweb.co.uk (Matt Saxton) Date: Tue, 17 Aug 2010 12:20:52 +0100 Subject: message box in Tkinter In-Reply-To: <61cbd1cb-bd6d-49aa-818f-d28c460980ea@x18g2000pro.googlegroups.com> References: <61cbd1cb-bd6d-49aa-818f-d28c460980ea@x18g2000pro.googlegroups.com> Message-ID: <20100817122052.7bff8ae9.matt@scotweb.co.uk> On Tue, 17 Aug 2010 04:02:23 -0700 (PDT) Jah_Alarm wrote: > > When I try importing messagebox from Tkinter i get an error message > that this module doesn't exist. > I believe what you want is Tkinter.Message -- Matt Saxton From eric.brunel at pragmadev.nospam.com Tue Aug 17 08:12:01 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Tue, 17 Aug 2010 14:12:01 +0200 Subject: message box in Tkinter References: <61cbd1cb-bd6d-49aa-818f-d28c460980ea@x18g2000pro.googlegroups.com> Message-ID: In article <61cbd1cb-bd6d-49aa-818f-d28c460980ea at x18g2000pro.googlegroups.com>, Jah_Alarm wrote: > I need to display a message box at the click of a button. I od the > following: > > from Tkinter import * > > def msg1(): > messagebox.showinfo(message='Have a good day') > > > Button(mainframe,text="About",command=msg1()).grid(column=360,row=36,sticky=W) > > I get the error msg 'global name 'messagebox' is not defined' > > When I try importing messagebox from Tkinter i get an error message > that this module doesn't exist. > > thanks Where did you find any reference to something called messagebox? The actual module name is tkMessageBox and it should be imported separately: import tkMessageBox tkMessageBox.showinfo(message='Have a good day') Should work that way. HTH - Eric - From jah.alarm at gmail.com Tue Aug 17 08:16:06 2010 From: jah.alarm at gmail.com (Jah_Alarm) Date: Tue, 17 Aug 2010 05:16:06 -0700 (PDT) Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> <26c363c8-11d7-49b9-a1c1-251ab5ff934e@p22g2000pre.googlegroups.com> Message-ID: <6b659d20-670f-4952-bfd6-684faf1ec0cf@i18g2000pro.googlegroups.com> In MATLAB this command is drawnow, just in case On Aug 17, 9:49?pm, Jah_Alarm wrote: > thanks. The thing is, the objects actually get updated without this > command, but when I run the GUI outside of python shell (i.e. in > command prompt as python filename.py or compile it to .exe file) the > objects do not get updated. I tried > Label(mainframe,textvariable=var).grid(column=1,row=1).update_idletasks() > and mainframe.update_idletasks() but it still doesn't work. > > On Aug 17, 7:19?pm, Eric Brunel > wrote: > > > > > In article > > <24dc97b3-a8b5-4638-9cf5-a397f1eae... at q16g2000prf.googlegroups.com>, > > > ?Jah_Alarm wrote: > > > hi, I've already asked this question but so far the progress has been > > > small. > > > > I'm running Tkinter. I have some elements on the screen (Labels, most > > > importantly) which content has to be updated every iteration of the > > > algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm > > > using the update_idletasks() command in the function itself after the > > > variable.set(...) command. The variable type is IntVar(), and the > > > mistake I'm getting is 'IntVar instance has no attribute > > > 'update_idletasks'. No updates are displayed, of course. > > > You have to call update_idletasks on a Tkinter *widget*, not a variable. > > You can call it on your window (Tk or Toplevel instance) or on your > > label for example. This way, it should work. > > > > Without the GUI the algorithm (it's a genetic algorithm) is working > > > fine, but I need to make it available to other people via GUI > > > > cheers, > > > > Alex From eric.brunel at pragmadev.nospam.com Tue Aug 17 08:19:25 2010 From: eric.brunel at pragmadev.nospam.com (Eric Brunel) Date: Tue, 17 Aug 2010 14:19:25 +0200 Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> <26c363c8-11d7-49b9-a1c1-251ab5ff934e@p22g2000pre.googlegroups.com> Message-ID: (Top-post corrected; please don't do that, it makes messages very hard to read via usenet?) In article <26c363c8-11d7-49b9-a1c1-251ab5ff934e at p22g2000pre.googlegroups.com>, Jah_Alarm wrote: > On Aug 17, 7:19?pm, Eric Brunel > wrote: > > You have to call update_idletasks on a Tkinter *widget*, not a variable. > > You can call it on your window (Tk or Toplevel instance) or on your > > label for example. This way, it should work. > > > thanks. The thing is, the objects actually get updated without this > command, but when I run the GUI outside of python shell (i.e. in > command prompt as python filename.py or compile it to .exe file) the > objects do not get updated. I tried > Label(mainframe,textvariable=var).grid(column=1,row=1).update_idletasks() > and mainframe.update_idletasks() but it still doesn't work. I think you're really misunderstanding something here: the call to update_idletasks is a one shot call to the GUI to basically tell it to refresh itself. So each time you change anything that should be displayed, you have to call that method again, or your changes will only be seen when the control returns to the GUI, which is basically at the end of your processing. The fact that it works when you're doing it interactively is normal. In this mode, you don't have a GUI event loop running, so the GUI updates itself all the time automatically. This is never true in programs you run the 'normal' way, i.e via: python filename.py And by the way, Label(?).grid(?).update_idletasks() had no chance to work anyway: the grid method doesn't return anything, so you're trying to call the update_idletasks method on None here? HTH - Eric - From neilc at norwich.edu Tue Aug 17 08:42:15 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 17 Aug 2010 12:42:15 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> Message-ID: <8cved7Fr7qU3@mid.individual.net> On 2010-08-17, Michael Torrie wrote: > In general if I find myself consistently going longer than 75 > or 80 characters, I need to refactor my code to make it more > manageable. If I have to scroll up five pages to find the > beginning of a block, that normally means my code could be > simplified and improved. Looking through my code, the split-up lines almost always include string literals or elimination of meaningless temporary variables, e.g.: self.expiration_date = translate_date(find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') The other cases are when indentation levels get the best of me, but I'm too lazy to refactor. -- Neil Cerutti From roy at panix.com Tue Aug 17 09:05:50 2010 From: roy at panix.com (Roy Smith) Date: Tue, 17 Aug 2010 09:05:50 -0400 Subject: 79 chars or more? References: Message-ID: In article , Lawrence D'Oliveiro wrote: > In message , AK wrote: > > > As monitors are getting bigger, is there a general change in opinion on > > the 79 chars limit in source files? > > WHAT 79-character limit in source files? > > I currently have my Emacs windows set at 100 characters wide, and I???m > thinking of going wider. > > Remember, the old hardcopy terminals used to produce 132-character-wide > listings. Those of you who think "old hardcopy terminals" did 132 wide obviously don't remember the ASR-33 :-) From martin at address-in-sig.invalid Tue Aug 17 10:01:42 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Tue, 17 Aug 2010 14:01:42 +0000 (UTC) Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> Message-ID: On Tue, 17 Aug 2010 13:00:51 +1000, James Mills wrote: > Roy, under normal circumstances I would agree with you and have a > different opinion. However being vision impaired restricts the available > width (irregardless of the width of the monitor) of text I'm able to > view at once. > I'm with James here because: 1) ssh terminal windows generally come up as 24 x 80 2) at 24 x 80 I can get more ssh terminal windows on the desktop with minimal overlap than I can do with longer/wider windows. BTW, James, would it be a bore to add a space after the two hyphens at the top of your sig, i.e. use "-- ", not "--"? That way most news readers will automatically remove your sig when replying to your post. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From sschwarzer at sschwarzer.net Tue Aug 17 10:14:05 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 17 Aug 2010 16:14:05 +0200 Subject: Opposite of split In-Reply-To: <4c696ada$0$22941$e4fe514c@news.xs4all.nl> References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl><4C683363.3080305@islandtraining.com><4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> Message-ID: <4C6A992D.5020802@sschwarzer.net> Hi Alex, On 2010-08-16 18:44, Alex van der Spek wrote: > Anybody catches any other ways to improve my program (attached), you are > most welcome. Help me learn, that is one of the objectives of this > newsgroup, right? Or is it all about exchanging the next to impossible > solution to the never to happen unreal world problems? I don't know what a concordance table is, and I haven't looked a lot into your program, but anyway here are some things I noticed at a glance: | #! usr/bin/env python | # Merge log files to autolog file | import os | import fileinput | #top='C:\\Documents and Settings\\avanderspek\\My Documents\\CiDRAdata\\Syncrude\\CSL\\August2010' | top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010' If you have backslashes in strings, you might want to use "raw strings". Instead of "c:\\Users\\ZDoor" you'd write r"c:\Users\ZDoor" (notice the r in front of the string). | i,j,k=0,0,0 | date={} I suggest to use more spacing to make the code more readable. Have a look at http://www.python.org/dev/peps/pep-0008/ for more formatting (and other) tips. | fps=0.3048 | tab='\t' | | bt='-999.25'+'\t''-999.25'+'\t''-999.25'+'\t''-999.25'+'\t'+'-999.25' If these numbers are always the same, you should use something like NUMBER = "-999.25" COLUMNS = 5 bt = "\t".join(COLUMNS * [NUMBER]) (with better naming, of course). Why don't you use `tab` here? I _highly_ recommend to use longer (unabbreviated) names. | al='Status'+'\t'+'State'+'\t'+'-999.25' | | for root,dirs,files in os.walk(top): | #Build a concordance table of days on which data was collected | for name in files: | ext=name.split('.',1)[1] There's a function `splitext` in `os.path`. | if ext=='txt': | dat=name.split('_')[1].split('y')[1] | if dat in date.keys(): You can just write `if dat in date` (in Python versions >= 2.2, I think). | date[dat]+=1 | else: | date[dat]=1 | print 'Concordance table of days:' | print date | print 'List of files processed:' | #Build a list of same day filenames, 5 max for a profile meter,skip first and last days | for f in sorted(date.keys())[2:-1]: | logs=[] | for name in files: | ext=name.split('.')[1] | if ext=='txt': | dat=name.split('_')[1].split('y')[1] I guess I'd move the parsing stuff (`x.split(s)[i]` etc.) into small functions with meaningful names. After that I'd probably notice there's much redundancy and refactor them. ;) | if dat==f: | logs.append(os.path.join(root,name)) | #Open the files and read line by line | datsec=False | lines=[[] for i in range(5)] One thing to watch out for: The above is different from `[[]] * 5` which uses the _same_ empty list for all entries. Probably the semantics you chose is correct. | fn=0 | for line in fileinput.input(logs): | if line.split()[0]=='DataID': | datsec=True | ln=0 | if datsec: | lines[fn].append(line.split()) | ln+=1 | if ln==10255: This looks like a "magic number" and should be turned into a constant. | datsec=False | fileinput.nextfile() | fn+=1 | print fileinput.filename().rsplit('\\',1)[1] | fileinput.close() | aut='000_AutoLog'+f+'.log' | out=os.path.join(root,aut) | alf=open(out,'w') | alf.write('Timestamp (mm/dd/yyyy hh:mm:ss) VF 1 VF 2 VF 3 VF 4 VF 5 Q 1 Q 2 Q 3 Q 4 Q 5 Status State Metric Band Temperature 1 Band Temperature 2 Band Temperature 3 Band Temperature 4 Band Temperature 5 SPL 1 SPL 2 SPL 3 SPL 4 SPL 5'+'\n') | for wn in range(1,10255,1): You don't need to write the step argument if it's 1. | for i in range(5): | lines[i][wn][2]=str(float(lines[i][wn][2])/fps) | tp=lines[0][wn][0]+' '+lines[0][wn][1] | vf=tab.join([lines[i][wn][2] for i in range(5)]) | vq=tab.join([lines[i][wn][3] for i in range(5)]) | vs=tab.join([lines[i][wn][4] for i in range(5)]) | #sf=tab.join([lines[i][wn][5] for i in range(5)]) | #sq=tab.join([lines[i][wn][6] for i in range(5)]) | #ss=tab.join([lines[i][wn][7] for i in range(5)]) Maybe use an extra function? def choose_a_better_name(): return tab.join([lines[index][wn][2] for index in range(5)]) Moreover, the repetition of this line looks as if you wanted to put the right hand sides of the assignments in a list, instead of assigning to distinct names (`vf` etc.). By the way, you use the number 5 a lot. I guess this should be a constant, too. | alf.write(tp+'\t'+vf+'\t'+vq+'\t'+al+'\t'+bt+'\t'+vs+'\n') Suggestion: Use tab.join([tp, vf, vq, al, bt, vs]) + "\n" Again, not using distinct variables would have an advantage here. | alf.close() | print "Done" Stefan From awaretek at gmail.com Tue Aug 17 10:21:23 2010 From: awaretek at gmail.com (Ron) Date: Tue, 17 Aug 2010 07:21:23 -0700 (PDT) Subject: Python for MultiTouch! Message-ID: Along with the news of Unbuntu supporting multitouch, I saw this and just had to share, I think its really nice: PyMT http://the-space-station.com/2010/8/16/python-multitouch:-pymt-0-5-released From sschwarzer at sschwarzer.net Tue Aug 17 10:28:02 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 17 Aug 2010 16:28:02 +0200 Subject: 79 chars or more? In-Reply-To: <8cved7Fr7qU3@mid.individual.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> Message-ID: <4C6A9C72.4040708@sschwarzer.net> Hi Neil, On 2010-08-17 14:42, Neil Cerutti wrote: > On 2010-08-17, Michael Torrie wrote: >> In general if I find myself consistently going longer than 75 >> or 80 characters, I need to refactor my code to make it more >> manageable. If I have to scroll up five pages to find the >> beginning of a block, that normally means my code could be >> simplified and improved. > > Looking through my code, the split-up lines almost always include > string literals or elimination of meaningless temporary > variables, e.g.: > > self.expiration_date = translate_date(find(response, > 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') I'd probably reformat this to self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') or even self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') for consistency. This not only limits the width but also makes the nesting of the calls more visible. Stefan From awaretek at gmail.com Tue Aug 17 10:29:28 2010 From: awaretek at gmail.com (Ron) Date: Tue, 17 Aug 2010 07:29:28 -0700 (PDT) Subject: scrapelib for web scraping Message-ID: Shameless plug for a web scraping tool my son is involved in creating, called scrapelib. He is on leave from university and is a consultant for the Sunlight Foundation creating something called the Fifty States Project to monitor lobbyist money to state governments in the USA. http://github.com/mikejs/scrapelib From awaretek at gmail.com Tue Aug 17 10:33:59 2010 From: awaretek at gmail.com (Ron) Date: Tue, 17 Aug 2010 07:33:59 -0700 (PDT) Subject: Podcast about Python's versions and implementations Message-ID: <53e47b75-c046-451a-8c14-94f2ba7e3abb@z30g2000prg.googlegroups.com> New podcast up is a look at the various versions and implementations of Python, including Python 3, Python 2, PyPy, IronPython, Jython, Stackless, Psycho, Shedskin, Cython, Unladen Swallow, Berp, etc. http://www.awaretek.com/python/ Ron From lie.1296 at gmail.com Tue Aug 17 10:59:05 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 18 Aug 2010 00:59:05 +1000 Subject: Python "why" questions In-Reply-To: References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: <4c6a8cff$1@dnews.tpgi.com.au> On 08/16/10 21:54, David Cournapeau wrote: > On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing > wrote: >>> On Aug 7, 2010, at 9:14 PM, John Nagle wrote: >>> >>>> The languages which have real multidimensional arrays, rather >>>> than arrays of arrays, tend to use 1-based subscripts. That >>>> reflects standard practice in mathematics. >> >> Not always -- mathematicians use whatever starting index is >> most convenient for the problem at hand. > > Yes, there are many engineering fields where index starts at 0. Partly > for the reason you have stated concerning polynomials, especially > since this extend to series, which are pervasive in numerical > computing. In linear algebra, though, I remember to have always noted > matrices indexes in the [1,n] range, not [0,n-1]. I'm sure some would prefer to denote it as [0, n) From robert.kern at gmail.com Tue Aug 17 11:22:27 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 17 Aug 2010 10:22:27 -0500 Subject: Python "why" questions In-Reply-To: <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> References: <8crequF9tpU1@mid.individual.net> <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> Message-ID: On 8/16/10 11:10 PM, Steven D'Aprano wrote: > On Mon, 16 Aug 2010 22:56:20 -0500, Robert Kern wrote: > >> On 8/16/10 9:29 PM, Roy Smith wrote: >>> In article, >>> Lawrence D'Oliveiro wrote: >>> >>>> In message, Roy Smith wrote: >>>> >>>>> 5) real intensity[160.0 : 30.0 : 0.01] >>>> >>>> How many elements in that array? >>>> >>>> a) 2999 >>>> b) 3000 >>>> c) neither of the above >>> >>> c) neither of the above. More specifically, 13,001 (if I counted >>> correctly). >> >> 13000, actually. Floating point is a bitch. >> >> [~/Movies] >> |1> import numpy >> >> [~/Movies] >> |2> len(numpy.r_[160.0:30.0:-0.01]) >> 13000 > > > Actually, the answer is 0, not 13000, because the step size is given as > 0.01, not -0.01. > >>>> import numpy >>>> len(numpy.r_[160.0:30.0:-0.01]) > 13000 >>>> len(numpy.r_[160.0:30.0:0.01]) > 0 Roy wasn't using numpy/Python semantics but made-up semantics (following Martin Gregorie's made-up semantics to which he was replying) which treat the step size as a true size, not a size and direction. The direction is determined from the start and stop parameters. It's an almost-reasonable design. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From neilc at norwich.edu Tue Aug 17 11:31:54 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 17 Aug 2010 15:31:54 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <8cvobaF1r0U2@mid.individual.net> On 2010-08-17, Stefan Schwarzer wrote: > Hi Neil, > > On 2010-08-17 14:42, Neil Cerutti wrote: >> Looking through my code, the split-up lines almost always >> include string literals or elimination of meaningless >> temporary variables, e.g.: >> >> self.expiration_date = translate_date(find(response, >> 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') > > I'd probably reformat this to > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', '%m%d%Y') > > or even > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') > > for consistency. > > This not only limits the width but also makes the nesting of > the calls more visible. Those are nice improvements. Thanks! -- Neil Cerutti From neilc at norwich.edu Tue Aug 17 11:36:57 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 17 Aug 2010 15:36:57 GMT Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> <4C6A992D.5020802@sschwarzer.net> Message-ID: <8cvokpF1r0U3@mid.individual.net> On 2010-08-17, Stefan Schwarzer wrote: > Hi Alex, > > On 2010-08-16 18:44, Alex van der Spek wrote: >> Anybody catches any other ways to improve my program (attached), you are >> most welcome. Help me learn, that is one of the objectives of this >> newsgroup, right? Or is it all about exchanging the next to impossible >> solution to the never to happen unreal world problems? > > I don't know what a concordance table is, and I haven't > looked a lot into your program, but anyway here are some > things I noticed at a glance: > >| #! usr/bin/env python >| # Merge log files to autolog file >| import os >| import fileinput >| #top='C:\\Documents and Settings\\avanderspek\\My Documents\\CiDRAdata\\Syncrude\\CSL\\August2010' >| top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010' > > If you have backslashes in strings, you might want to use "raw > strings". Instead of "c:\\Users\\ZDoor" you'd write > r"c:\Users\ZDoor" (notice the r in front of the string). That's good general advice. But in the specific case of file paths, using '/' as the separator is supported, and somewhat preferable. -- Neil Cerutti From darcy at druid.net Tue Aug 17 11:42:56 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 17 Aug 2010 11:42:56 -0400 Subject: 79 chars or more? In-Reply-To: <4C6A9C72.4040708@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <20100817114256.d960549b.darcy@druid.net> On Tue, 17 Aug 2010 16:28:02 +0200 Stefan Schwarzer wrote: > I'd probably reformat this to > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', '%m%d%Y') > > or even > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') You can extend this if there are complicated sub-calls. Probably overkill for this example but here is the idea. self.expiration_date = translate_date( find( response, 'MPNExpirationDate', ).text, '%Y-%m-%d', '%m%d%Y' ) I also moved the closing brace down to align with the line that opened that block. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From zdoor at xs4all.nl Tue Aug 17 11:44:57 2010 From: zdoor at xs4all.nl (Alex van der Spek) Date: Tue, 17 Aug 2010 17:44:57 +0200 Subject: EOFError with fileinput In-Reply-To: References: <4c696751$0$22940$e4fe514c@news.xs4all.nl> Message-ID: <4c6aae79$0$22942$e4fe514c@news.xs4all.nl> Thanks all! I understand better now. I had no idea that EOFError was an exception. I was looking for a function to tell me when the end of a sequential file is reached as in all of the 4 programming languages that I do know this is a requirement. Will modify my program accordingly. Alex van der Spek From andrei.avk at gmail.com Tue Aug 17 11:44:58 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 11:44:58 -0400 Subject: 79 chars or more? In-Reply-To: <4C6A9C72.4040708@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <4C6AAE7A.70109@gmail.com> On 08/17/2010 10:28 AM, Stefan Schwarzer wrote: > Hi Neil, > > On 2010-08-17 14:42, Neil Cerutti wrote: >> On 2010-08-17, Michael Torrie wrote: >>> In general if I find myself consistently going longer than 75 >>> or 80 characters, I need to refactor my code to make it more >>> manageable. If I have to scroll up five pages to find the >>> beginning of a block, that normally means my code could be >>> simplified and improved. >> >> Looking through my code, the split-up lines almost always include >> string literals or elimination of meaningless temporary >> variables, e.g.: >> >> self.expiration_date = translate_date(find(response, >> 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') > > I'd probably reformat this to > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', '%m%d%Y') > > or even > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') > > for consistency. > > This not only limits the width but also makes the nesting of > the calls more visible. > > Stefan Doesn't this create the problem of functions growing too long to fit in a screen? I think it's very useful to try to keep function size low enough so that you can view the whole function without having to scroll up and down. (even though that's not always possible) -ak From invalid at invalid.invalid Tue Aug 17 11:46:31 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 17 Aug 2010 15:46:31 +0000 (UTC) Subject: Opposite of split References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> <4C6A992D.5020802@sschwarzer.net> <8cvokpF1r0U3@mid.individual.net> Message-ID: On 2010-08-17, Neil Cerutti wrote: > On 2010-08-17, Stefan Schwarzer wrote: >> Hi Alex, >> >> On 2010-08-16 18:44, Alex van der Spek wrote: >>> Anybody catches any other ways to improve my program (attached), you are >>> most welcome. Help me learn, that is one of the objectives of this >>> newsgroup, right? Or is it all about exchanging the next to impossible >>> solution to the never to happen unreal world problems? >> >> I don't know what a concordance table is, and I haven't >> looked a lot into your program, but anyway here are some >> things I noticed at a glance: >> >>| #! usr/bin/env python >>| # Merge log files to autolog file >>| import os >>| import fileinput >>| #top='C:\\Documents and Settings\\avanderspek\\My Documents\\CiDRAdata\\Syncrude\\CSL\\August2010' >>| top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010' >> >> If you have backslashes in strings, you might want to use "raw >> strings". Instead of "c:\\Users\\ZDoor" you'd write >> r"c:\Users\ZDoor" (notice the r in front of the string). > > That's good general advice. But in the specific case of file > paths, using '/' as the separator is supported, and somewhat > preferable. Unless you're going to be passing them to cmd.exe or other utilities via subprocess/popen. -- Grant Edwards grant.b.edwards Yow! MY income is ALL at disposable! gmail.com From moss.rich at gmail.com Tue Aug 17 12:07:28 2010 From: moss.rich at gmail.com (Rich Moss) Date: Tue, 17 Aug 2010 09:07:28 -0700 (PDT) Subject: Python Developer - HFT Trading firm - Chicago, IL Message-ID: Python developer needed for math/trading applications and research at leading HFT firm. The person we are searching for will have a strong background with python programming and the ability to work with very large historical datasets. You should have a very strong math background as well. This can involve writing very complicated python scripts and programs! You will work very closely with traders and quantitative analysts in their equities trading group on state-of-the- art trading strategy and execution systems. Requires: Strong python programming experience developing applications and scripts using complex regular expressions Strong math knowledge and education Experience working with massive datatsets/historical data This company is a top-tier electronic, algorithmic trading firm, located in Chicago, IL. This firm is one of the most advanced high frequency electronic trading firms in the world and uses python throughout the company, as well as other languages. This firm has a culture that rewards creativity and hard work. No third parties, please. We will not consider candidates from outside the USA. No telecommuting. We offer very generous compensation (best in the industry), fantastic benefits and very generous relocation packages. Please contact me immediately with a resume! Send resumes to: Rich Moss rich at mossltd.com From sschwarzer at sschwarzer.net Tue Aug 17 12:21:53 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 17 Aug 2010 18:21:53 +0200 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <4C6AB721.3060603@sschwarzer.net> On 2010-08-17 17:44, AK wrote: > On 08/17/2010 10:28 AM, Stefan Schwarzer wrote: >> I'd probably reformat this to >> >> self.expiration_date = translate_date( >> find(response, 'MPNExpirationDate').text, >> '%Y-%m-%d', '%m%d%Y') >> >> or even >> >> self.expiration_date = translate_date( >> find(response, 'MPNExpirationDate').text, >> '%Y-%m-%d', >> '%m%d%Y') >> >> for consistency. >> >> This not only limits the width but also makes the nesting of >> the calls more visible. > > Doesn't this create the problem of functions growing too long to fit in > a screen? I think it's very useful to try to keep function size low > enough so that you can view the whole function without having to scroll > up and down. (even though that's not always possible) -ak I think I'd extract some part of the function into a new function then. In my opinion, the reasoning is similar to the case, "Can't I use two spaces per indentation level? That way I don't run so easily into the right margin if I have more than five indentations in a function." ;-) Stefan From rodrick.brown at gmail.com Tue Aug 17 12:40:39 2010 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Tue, 17 Aug 2010 12:40:39 -0400 Subject: Open a command pipe for reading Message-ID: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> I have a fairly large file 1-2GB in size that I need to process line by line but I first need to convert the file to text using a 3rd party tool that prints the records also line by line. I've tried using Popen to do this with no luck. I'm trying to simulate /bin/foo myfile.dat And as the records are being printed do some calculations. pipe = Popen(exttool,shell=True,stdout=PIPE).stdout for data in pipe.readlines(): print data, This operation blocks forever I'm guessing it's trying to process the entire file at once. Sent from my iPhone 4. From andrei.avk at gmail.com Tue Aug 17 12:43:02 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 12:43:02 -0400 Subject: 79 chars or more? In-Reply-To: <4C6AB721.3060603@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> Message-ID: <4C6ABC16.4070006@gmail.com> On 08/17/2010 12:21 PM, Stefan Schwarzer wrote: > On 2010-08-17 17:44, AK wrote: >> On 08/17/2010 10:28 AM, Stefan Schwarzer wrote: >>> I'd probably reformat this to >>> >>> self.expiration_date = translate_date( >>> find(response, 'MPNExpirationDate').text, >>> '%Y-%m-%d', '%m%d%Y') >>> >>> or even >>> >>> self.expiration_date = translate_date( >>> find(response, 'MPNExpirationDate').text, >>> '%Y-%m-%d', >>> '%m%d%Y') >>> >>> for consistency. >>> >>> This not only limits the width but also makes the nesting of >>> the calls more visible. >> >> Doesn't this create the problem of functions growing too long to fit in >> a screen? I think it's very useful to try to keep function size low >> enough so that you can view the whole function without having to scroll >> up and down. (even though that's not always possible) -ak > > I think I'd extract some part of the function into a new > function then. In my opinion, the reasoning is similar to > the case, "Can't I use two spaces per indentation level? > That way I don't run so easily into the right margin if I > have more than five indentations in a function." ;-) I think to some extent it's a matter of taste. I bet most people would agree that on the balance, 2-space indentations makes code much less readable, despite saving a bit of space. But let me ask you, would you really prefer to have: >>> self.expiration_date = translate_date( >>> find(response, 'MPNExpirationDate').text, >>> '%Y-%m-%d', '%m%d%Y') (or the 4-line version of this above), even when it necessitates creation of a new function, rather than have this code on two lines? After all, I think it's a matter of balance between readability, expressiveness and succinctness. If I split a function in two, that still means that understanding the functionality of the code will require scrolling around and looking at the second function. I guess what I'm trying to say that we shouldn't just care about readability of lines but also readability of functions and blocks of functionality (that may include several functions that accomplish a single "task".) -andrei From neilc at norwich.edu Tue Aug 17 13:07:14 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 17 Aug 2010 17:07:14 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> Message-ID: <8cvtu2F6v3U1@mid.individual.net> On 2010-08-17, AK wrote: > After all, I think it's a matter of balance between > readability, expressiveness and succinctness. If I split a > function in two, that still means that understanding the > functionality of the code will require scrolling around and > looking at the second function. I guess what I'm trying to say > that we shouldn't just care about readability of lines but also > readability of functions and blocks of functionality (that may > include several functions that accomplish a single "task".) When considering creating variables and functions, I try to use the same rule of thumb: If I can come up with a good name for it relatively quickly, then it probably deserves to exist. If all I can think of is 'func' or 'x', then it's an artifact that I hope to avoid. Splitting a function in two need not obscure the meaning, and may even improve it, *if* the names of the new functions are good. -- Neil Cerutti From stndshp at gmail.com Tue Aug 17 13:10:57 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 10:10:57 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <93c048b8-013d-425f-ac69-c112f12ddaa3@v41g2000yqv.googlegroups.com> Message-ID: <74bce7c5-8a97-4a45-8d85-2ae48145b4e1@x21g2000yqa.googlegroups.com> On Aug 16, 4:20?am, Malcolm McLean wrote: > On Aug 16, 10:20?am, Standish P wrote:> [Q] How far can stack [LIFO] solve do automatic garbage collection and > > prevent memory leak ? > > Most programs can be written so that most of their memory allocations > are matched by destructors at the same level. > > However the allocations that can't be written this way typically tend > to be the small frequently-called ones used for nodes in dynamic graph > objects, or small resizeable buffers to hold strings and the like. > This is where you get the performance hit with repeated calls to > malloc() and free(). > > So generally it's not worthwhile writing a stack allocator for a > normal program. That's not to say there aren't a few individual cases > where it can help performance. (See the chapter "Memory games" in my > book Basic Agorithms for details about memory allocation strategies). all the page numbers in your books TOC have a little varying offset from actual, pictures are nice for kids .. From vikas.mahajan12 at gmail.com Tue Aug 17 13:19:16 2010 From: vikas.mahajan12 at gmail.com (Vikas Mahajan) Date: Tue, 17 Aug 2010 22:49:16 +0530 Subject: passing variables as object attributes In-Reply-To: <4c6a6773$0$9118$426a74cc@news.free.fr> References: <4c6a6773$0$9118$426a74cc@news.free.fr> Message-ID: I got the concept to get and set object attributes and now can handle similar problems effectively. Thanks to all for your help. From stndshp at gmail.com Tue Aug 17 13:21:11 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 10:21:11 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> > Garbage collection doesn't use a stack. It uses a "heap", which is in > the abstract a collection of memory blocks of different lengths, > divided into two lists, generally represented as linked lists: > > 1. ?A list of blocks that are free and may be used to store new data > > 2. ?A list of blocks that are in use, or haven't been freed (yet) Is this all that a heap is or is there more to it ? I have been looking for simple but complete explanation of heap for a while and not gotten to it. I think I am looking for a stack allocation on the same pattern. In a disk, a file is fragmented in many contiguous blocks and is accessed automatically. > There is no way you could do memory management of all but the most > trivial and fixed-length data chunks using a stack. Sure, you could > reserve thousands of bytes on the stack for an array but suppose your > language allows arrays to grow or shrink. To keep its property of > being adjacent, you'd have to do something horrible such as move > unrelated data allocated later, which raises all sorts of security > issues, doesn't it. > A stack, or something which works like a stack (that is, a stack) is a > necessary but not sufficient condition for a working C runtime because > C functions can call themselves recursively, whether directly or > indirectly. If this last condition did not obtain, each function could > give the functions it calls some of its own memory and the called > function could save a fixed set of non-stacked general registers in > that area; this was in fact the practice on IBM 370 and in assembler > language at a time when many "data processing managers" though > recursion was a Communist plot. > > However, data structures of variable size, or data structures that > merely take up a lot of space, don't play nice with others on the > stack, so, we place their address on the stack and store them in > another place, which was named the heap, probably, as a sort of > witticism. > > Gilbert and Sullivan: > > If anyone anything lacks > He'll find it all ready in stacks This you might want to take this to the Forth people because they are marketing their language as a cure for all that plagues programming today. > was wrong, and needs to be brought up to date: > > You cannot do everything in a stack > Unless you code an almighty hack > If you're a coding Knight who says, "Neep", > You'll probably need to implement a heap > A pile a heap of benefits you'll reap > If only my advice in your brain you'll keep > And avoid memory leaks from which data doth seep > By using a well-implemented, well structured, and well-documented > Heap! > > [Chorus of Sailors] > We will to heart your advice take, and always use a heap! > > [Soloist] > Oh thank you do > To this be true > And always my sage advice do keep > That you always need to use a heap!- Hide quoted text - > > - Show quoted text - From iamforufriends at gmail.com Tue Aug 17 13:29:22 2010 From: iamforufriends at gmail.com (babe is waiting) Date: Tue, 17 Aug 2010 10:29:22 -0700 (PDT) Subject: easy to fine a hot girl from your city, Message-ID: <83f704eb-7946-4758-9b5d-bec366094dc6@l25g2000prn.googlegroups.com> easy to fine a hot girl from your city, just follow the girl.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From stndshp at gmail.com Tue Aug 17 13:34:04 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 10:34:04 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> Message-ID: <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> On Aug 16, 11:09?am, Elizabeth D Rather wrote: > On 8/15/10 10:33 PM, Standish P wrote: > > >>> If Forth is a general processing language based on stack, is it > >>> possible to convert any and all algorithms to stack based ones and > >>> thus avoid memory leaks since a pop automatically releases memory when > >>> free is an intrinsic part of it. > > Forth uses two stacks. ?The "data stack" is used for passing parameters > between subroutines ("words") and is completely under the control of the > programmer. ?Words expect parameters on this stack; they remove them, > and leave only explicit results. ?The "return stack" is used primarily > for return addresses when words are called, although it is also > available for auxiliary uses under guidelines which respect the primary > use for return addresses. > > Although implementations vary, in most Forths stacks grow from a fixed > point (one for each stack) into otherwise-unused memory. ?The space > involved is allocated when the program is launched, and is not managed > as a heap and allocated or deallocated by any complicated mechanism. ?On > multitasking Forth systems, each task has its own stacks. ?Where > floating point is implemented (Forth's native arithmetic is > integer-based), there is usually a separate stack for floats, to take > advantage of hardware FP stacks. > > >> ? ? - is forth a general purpose language? Yes > >> ? ? - are all algorithms stack based? No > > > Does Forth uses stack for all algorithms ? Does it use pointers , ie > > indirect addressing ? If it can/must use stack then every algorithm > > could be made stack based. > > Forth uses its data stack for parameter passing and storage of temporary > values. ?It is also possible to define variables, strings, and arrays in > memory, in which case their addresses may be passed on the data stack. > > Forth is architecturally very simple. ?Memory allocations for variables, > etc., are normally static, although some implementations include > facilities for heaps as needed by applications. > although some implementations include facilities for heaps as needed by applications. How are these heaps being implemented ? Is there some illustrative code or a book showing how to implement these heaps in C for example ? Are dictionaries of forth and postscript themselves stacks if we consider them as nested two column tables which lisp's lists are in essence, but only single row. Multiple rows would just be multiple instances of it at the same level inside parens. we can peek into stacks which is like car. if it is not unusually costly computation, why not allow it ? there is no need to restrict to push and pop. roll( stack_name, num) itself can give all those postfix permutations that push and pop cant generate with a single stack. Can we use dictionaries to generate multiple stacks inside one global stack ? From martin at address-in-sig.invalid Tue Aug 17 13:36:13 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Tue, 17 Aug 2010 17:36:13 +0000 (UTC) Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> Message-ID: On Tue, 17 Aug 2010 10:22:27 -0500, Robert Kern wrote: > On 8/16/10 11:10 PM, Steven D'Aprano wrote: >> On Mon, 16 Aug 2010 22:56:20 -0500, Robert Kern wrote: >> >>> On 8/16/10 9:29 PM, Roy Smith wrote: >>>> In article, >>>> Lawrence D'Oliveiro wrote: >>>> >>>>> In message, Roy Smith >>>>> wrote: >>>>> >>>>>> 5) real intensity[160.0 : 30.0 : 0.01] >>>>> >>>>> How many elements in that array? >>>>> >>>>> a) 2999 >>>>> b) 3000 >>>>> c) neither of the above >>>> >>>> c) neither of the above. More specifically, 13,001 (if I counted >>>> correctly). >>> >>> 13000, actually. Floating point is a bitch. >>> >>> [~/Movies] >>> |1> import numpy >>> >>> [~/Movies] >>> |2> len(numpy.r_[160.0:30.0:-0.01]) >>> 13000 >> >> >> Actually, the answer is 0, not 13000, because the step size is given as >> 0.01, not -0.01. >> >>>>> import numpy >>>>> len(numpy.r_[160.0:30.0:-0.01]) >> 13000 >>>>> len(numpy.r_[160.0:30.0:0.01]) >> 0 > > Roy wasn't using numpy/Python semantics but made-up semantics (following > Martin Gregorie's made-up semantics to which he was replying) which > treat the step size as a true size, not a size and direction. The > direction is determined from the start and stop parameters. It's an > almost-reasonable design. That wasn't a made-up example: AFAICR and ignoring a missing semi-colon it was an Algol 68 snippet. The semantics of the for statement and the use of lwb and upb operators to extract the bounds from a 1-dimensional array are correct A68, but OTOH its a very long time since I last programmed in that language. I used that rather than Python because Algol 68 supports the non-zero lower bound and treats the array limits as attributes of the array. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From james.kanze at gmail.com Tue Aug 17 13:44:27 2010 From: james.kanze at gmail.com (James Kanze) Date: Tue, 17 Aug 2010 10:44:27 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: On Aug 17, 6:21 pm, Standish P wrote: > > Garbage collection doesn't use a stack. It uses a "heap", > > which is in the abstract a collection of memory blocks of > > different lengths, divided into two lists, generally > > represented as linked lists: > > 1. A list of blocks that are free and may be used to store > > new data > > 2. A list of blocks that are in use, or haven't been freed (yet) > Is this all that a heap is or is there more to it ? There are many different ways to implement a heap. The above is not a good one, and I doubt that it's really used anywhere. > I have been looking for simple but complete explanation of > heap for a while and not gotten to it. Complete in what sense? The basic principle of how to use it is simple. As for how to implement it, there are many different algorithms that can be used. > I think I am looking for a stack allocation on the same > pattern. Stack allocation is far, far simpler (usually). > In a disk, a file is fragmented in many contiguous blocks and > is accessed automatically. At the system level, the same thing holds for memory, and the actual physical memory is "fragmented" into contiguous blocks, each the size of a page. The MMU (hardware) makes this transparent to user programs, however. > > There is no way you could do memory management of all but the most > > trivial and fixed-length data chunks using a stack. The length isn't the issue. The order of allocation and freeing is. (For many specific uses, stack based allocators can and have been used, but they don't work for generally allocation.) -- James Kanze From drodrig at magicbrain.com Tue Aug 17 14:03:05 2010 From: drodrig at magicbrain.com (drodrig) Date: Tue, 17 Aug 2010 11:03:05 -0700 (PDT) Subject: [SOLVED]: Copying a file with a question mark in it's name in Windows References: Message-ID: <549b2846-004d-4977-a2e9-20667182aefb@v8g2000yqe.googlegroups.com> On Aug 12, 9:16?am, Aleksey wrote: > On 12 ???, 18:49,drodrig wrote: > > > A python script I use to backup files on a Windows 2003 server > > occasionally fails to retrieve the size of a file with a question mark > > in the name. The exception I get is "OSError #123 The filename, > > directory name, or volume label syntax is incorrect". I realize that > > technically a question mark in the name of a file on Windows is > > illegal, but nevertheless these files exist on the file system. It > > seems that they are created by Office 2007 Word, for the most part. (Sorry for the late reply) Thank you. The questions marks are indeed placeholders for unprintable characters. The glob module did the trick. > > If "?" is a placeholder for an unprintable character you can try view > real file name in IDLE: > > ? import glob > ? print glob.glob(u'e:/full/path/to/file?') > > In path to file you must instead question use wild "?". > Will be printed all like files. > > ----------------------------- > Under Windows I too have similar problem: windows sometimes (from any > programs - e.g. Firefox) save files with wrong names, but later > do not manipulate with it. From stndshp at gmail.com Tue Aug 17 14:20:11 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 11:20:11 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <7zaaolzm89.fsf@ask.diku.dk> Message-ID: <89467860-45ac-4a3b-ac17-f11a19429187@i13g2000yqd.googlegroups.com> On Aug 17, 1:17?am, torb... at diku.dk (Torben ?gidius Mogensen) wrote: > Standish P writes: > > [Q] How far can stack [LIFO] solve do automatic garbage collection and > > prevent memory leak ? > > > Because a stack has push and pop, it is able to release and allocate > > memory. We envisage an exogenous stack which has malloc() associated > > with a push and free() associated with a pop. > > See How many programmers have applied the ideas of these papers in their programming practice ? I paste the abstract for convenience > http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 Abstract: This paper describes a memory management discipline for programs that perform dynamic memory allocation and de-allocation. At runtime, all values are put into regions. The store consists of a stack of regions. All points of region allocation and deallocation are inferred automatically, using a type and effect based program analysis. The scheme does not assume the presence of a garbage collector. The scheme was first presented by Tofte and Talpin (1994); subsequently, it has been tested in The ML Kit with Regions, a region-based, garbage- collection free implementation of the Standard ML Core language, which includes recursive datatypes, higher-order functions and updatable references (Birkedal et al. 96, Elsman and Hallenberg 95). This paper defines a region-based dynamic semantics for a skeletal programming language extracted from Standard ML. We present the inference system which specifies where regions can be allocated and de-allocated and a detailed proof that the system is sound wi... > > http://portal.acm.org/citation.cfm?doid=174675.177855 ABSTRACT We present a translation scheme for the polymorphically typed call-by- value &lgr;-calculus. All runtime values, including function closures, are put into regions. The store consists of a stack of regions. Region inference and effect inference are used to infer where regions can be allocated and de-allocated. Recursive functions are handled using a limited form of polymorphic recursion. The translation is proved correct with respect to a store semantics, which models as a region- based run-time system. Experimental results suggest that regions tend to be small, that region allocation is frequent and that overall memory demands are usually modest, even without garbage collection. > > http://www.springerlink.com/content/m2074884n6gt612h/ > Abstract We report on our experience with designing, implementing, proving correct, and evaluating a region-based memory management system. dynamic storage management - regions - Standard ML > ? ? ? ? Torben From almar.klein at gmail.com Tue Aug 17 14:26:12 2010 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 17 Aug 2010 20:26:12 +0200 Subject: 79 chars or more? In-Reply-To: <4C6ABC16.4070006@gmail.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6ABC16.4070006@gmail.com> Message-ID: On 17 August 2010 18:43, AK wrote: > On 08/17/2010 12:21 PM, Stefan Schwarzer wrote: > >> On 2010-08-17 17:44, AK wrote: >> >>> On 08/17/2010 10:28 AM, Stefan Schwarzer wrote: >>> >>>> I'd probably reformat this to >>>> >>>> self.expiration_date = translate_date( >>>> find(response, 'MPNExpirationDate').text, >>>> '%Y-%m-%d', '%m%d%Y') >>>> >>>> or even >>>> >>>> self.expiration_date = translate_date( >>>> find(response, 'MPNExpirationDate').text, >>>> '%Y-%m-%d', >>>> '%m%d%Y') >>>> >>>> for consistency. >>>> >>>> This not only limits the width but also makes the nesting of >>>> the calls more visible. >>>> >>> >>> Doesn't this create the problem of functions growing too long to fit in >>> a screen? I think it's very useful to try to keep function size low >>> enough so that you can view the whole function without having to scroll >>> up and down. (even though that's not always possible) -ak >>> >> >> I think I'd extract some part of the function into a new >> function then. In my opinion, the reasoning is similar to >> the case, "Can't I use two spaces per indentation level? >> That way I don't run so easily into the right margin if I >> have more than five indentations in a function." ;-) >> > > I think to some extent it's a matter of taste. I bet most people would > agree that on the balance, 2-space indentations makes code much less > readable, despite saving a bit of space. > > But let me ask you, would you really prefer to have: > > > self.expiration_date = translate_date( >>>> find(response, 'MPNExpirationDate').text, >>>> '%Y-%m-%d', '%m%d%Y') >>>> >>> > (or the 4-line version of this above), even when it necessitates > creation of a new function, rather than have this code on two lines? > > After all, I think it's a matter of balance between readability, > expressiveness and succinctness. If I split a function in two, that > still means that understanding the functionality of the code will > require scrolling around and looking at the second function. I guess > what I'm trying to say that we shouldn't just care about readability of > lines but also readability of functions and blocks of functionality > (that may include several functions that accomplish a single "task".) > > -andrei > > -- > http://mail.python.org/mailman/listinfo/python-list > I am in favor of the 80-char limit also. Besides the arguments listed above, when using an IDE it gives you that extra horizontal space to fit some IDE specific tools (such as source structure). I must admit that I'm sometimes slightly frustrated when an expression is JUST 81 chars, and I *need* to reformat to two lines. On the other hand, very long lines are hard to read also. I guess the limit must be placed somewhere, and for historical reasons, 80 chars makes the most sense IMO. On a related note, why is the limit mentioned in PEP8 79 chars, and not 80? I never understood this :) Cheers, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From hwfwguy at gmail.com Tue Aug 17 14:29:36 2010 From: hwfwguy at gmail.com (Brad) Date: Tue, 17 Aug 2010 11:29:36 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> Message-ID: On Aug 17, 10:34?am, Standish P wrote: > On Aug 16, 11:09?am, Elizabeth D Rather wrote: > > How are these heaps being implemented ? Is there some illustrative > code or a book showing how to implement these heaps in C for example ? > Forth does not use a heap, except maybe to implement malloc/free which many Forth apps do not use. The dictionary is a linked list structure. Now seems like a good time for you to teach yourself Forth (by studying the best commercial implementation you can find) since you seem to be working with a clean slate. But I will say a few things about stacks in general. There are many ways to implement stacks. The simplest is to declare some space for the stack and then post-increment or pre-decrement a stack pointer depending on whether you're pushing or popping. Normally you make the memory for them big enough that they don't overflow. If you are concerned about stack overflow you can change the implementation. Add bounds checking, for example. Another trick is to use an 8-bit stack pointer. Then you will have a circular stack. If there is underflow or overflow it at least will not step on other data. It will only return bad data, which you may find preferable to an ugly crash. OTOH, bugs that cause spectacular failures tend to be discovered. You can also initialize the stack memory with a pattern like 0xDEAD and then after sufficiently exercising the code, examine the memory contents to see the "high water mark" of the stack pointer. -Brad From tjreedy at udel.edu Tue Aug 17 14:47:32 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Aug 2010 14:47:32 -0400 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6ABC16.4070006@gmail.com> Message-ID: On 8/17/2010 2:26 PM, Almar Klein wrote: > On a related note, why is the limit mentioned in PEP8 79 chars, and not > 80? I never understood this :) A newline char or block or underline cursor makes 80. The importance depended on the terminal. 80 chars on the last line could especially be a problem. -- Terry Jan Reedy From stndshp at gmail.com Tue Aug 17 14:53:27 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 11:53:27 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: On Aug 16, 12:20?am, Standish P wrote: > [Q] How far can stack [LIFO] solve do automatic garbage collection and > prevent memory leak ? > Because a stack has push and pop, it is able to release and allocate > memory. We envisage an exogenous stack which has malloc() associated > with a push and free() associated with a pop. > The algorithm using the stack would have to be "perfect" to prevent > stack overflow or condition of infinite recursion depth. This would > involve data type checking to filter out invalid input. The task must > be casted in an algorithm that uses the stack. Then the algorithm must > be shown to be heuristically or by its metaphor, to be correct using > informal reasoning. > Are there any standard textbooks or papers that show stacks > implemented in C/C++/Python/Forth with malloc/free in push and pop ? > If Forth is a general processing language based on stack, is it > possible to convert any and all algorithms to stack based ones and > thus avoid memory leaks since a pop automatically releases memory when > free is an intrinsic part of it. > K&R ANSI has the example of modular programming showing how to > implement a stack but he uses a fixed length array. It is also > possibly an endogenous stack. We look for an exogenous stack so that > element size can vary. > > ======= > Standish P Another way to pose my question, as occurred to me presently is to ask if a stack is a good abstraction for programming ? Certainly, it is the main abstraction in Forth and Postscript and implementable readily in C,C++ and I assume python. It is true that the other languages such as F/PS also have borrowed lists from lisp in the name of nested-dictionaries and mathematica calls them nested-tables as its fundamental data structure. I am asking for a characterization of algorithms that benefit from this abstraction or programming paradigm and comparison with others. The whole case of OOP is the clustering of thought, ie book-keeping, in the mind of the programmer around fewer objects than ten or twenty fold functions. so the name of the game is the same, ie to help the programmer keep track of things for writing fault free code without chasing every case, easy visualization, easy recall and communication with fellow programmers of abstract concepts in terms of real world objects and easy modification and code reuse. From python at mrabarnett.plus.com Tue Aug 17 14:56:28 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 17 Aug 2010 19:56:28 +0100 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6ABC16.4070006@gmail.com> Message-ID: <4C6ADB5C.70300@mrabarnett.plus.com> Almar Klein wrote: > [snip] > > I am in favor of the 80-char limit also. Besides the arguments listed > above, when using an IDE it gives you that extra horizontal space to fit > some IDE specific tools (such as source structure). > > I must admit that I'm sometimes slightly frustrated when an expression > is JUST 81 chars, and I *need* to reformat to two lines. On the other > hand, very long lines are hard to read also. I guess the limit must be > placed somewhere, and for historical reasons, 80 chars makes the most > sense IMO. > > On a related note, why is the limit mentioned in PEP8 79 chars, and not > 80? I never understood this :) > If the display is limited to 80 characters then after printing the 80th the cursor will be at the start of the next line and the newline will cause the display to leave a blank line (unless the display has some intelligence and supports pending newlines, of course). From tjreedy at udel.edu Tue Aug 17 14:57:22 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Aug 2010 14:57:22 -0400 Subject: 79 chars or more? In-Reply-To: References: Message-ID: On 8/17/2010 3:47 AM, Lawrence D'Oliveiro wrote: > In message, AK wrote: > >> As monitors are getting bigger, is there a general change in opinion on >> the 79 chars limit in source files? > > WHAT 79-character limit in source files? Only for stdlib. Python itself has no particular limit. The dev discussed the issue perhaps a year ago. Enough people wanted or needed the current stdlib limit that they decided to stick with it. A reason not mentioned much is that some people have trouble following packed lines that are too much longer. Wide-page textbooks routinely put text in two columns for easier reading. This is less of a factor with jagged edge text, but if the limit were increased to say 150, there would be people writing multi-line 150 char wide text blocks. -- Terry Jan Reedy From hansmu at xs4all.nl Tue Aug 17 14:59:25 2010 From: hansmu at xs4all.nl (Hans Mulder) Date: Tue, 17 Aug 2010 20:59:25 +0200 Subject: bash: syntax error near unexpected token In-Reply-To: References: Message-ID: <4c6adc4c$0$22918$e4fe514c@news.xs4all.nl> Benjamin Kaplan wrote: > On Mon, Aug 16, 2010 at 11:33 PM, kreglet wrote: >> desktop:~/bin$ modtest.py >> desktop:~/bin$ evenodd(45) >> bash: syntax error near unexpected token `45' >> > > And this is what's supposed to happen any time you try this in any > shell. When you call evenodd, bash looks for a program or shell > built-in called evenodd. Which doesn't exist. That's not what "syntax error means". If the problem were that evenodd does not exist as a shell function, the error would have been "bash: evenodd: command not found". I do not understand why bash says the token `45' is unexpected. The '(' token is the problem. It's a syntax error because in bash syntax function arguments are not enclosed in parentheses: $ function evenodd { > if (( $1 % 2 )) > then echo $1 is odd > else echo $1 is even > fi > } $ evenodd 45 45 is odd $ evenodd(45) bash: syntax error near unexpected token `45' $ Of course, this is completely off-topic. -- HansM From news1234 at free.fr Tue Aug 17 15:14:34 2010 From: news1234 at free.fr (News123) Date: Tue, 17 Aug 2010 21:14:34 +0200 Subject: Opposite of split In-Reply-To: References: <4c6830c7$0$22916$e4fe514c@news.xs4all.nl> <4C683363.3080305@islandtraining.com> <4c687936$0$11100$c3e8da3@news.astraweb.com> <4c696ada$0$22941$e4fe514c@news.xs4all.nl> <4C6A992D.5020802@sschwarzer.net> <8cvokpF1r0U3@mid.individual.net> Message-ID: <4c6adf9a$0$12224$426a74cc@news.free.fr> On 08/17/2010 05:46 PM, Grant Edwards wrote: > On 2010-08-17, Neil Cerutti wrote: >> On 2010-08-17, Stefan Schwarzer wrote: >>> Hi Alex, >>> >>> On 2010-08-16 18:44, Alex van der Spek wrote: >>>> Anybody catches any other ways to improve my program (attached), you are >>>> most welcome. Help me learn, that is one of the objectives of this >>>> newsgroup, right? Or is it all about exchanging the next to impossible >>>> solution to the never to happen unreal world problems? >>> >>> I don't know what a concordance table is, and I haven't >>> looked a lot into your program, but anyway here are some >>> things I noticed at a glance: >>> >>> | #! usr/bin/env python >>> | # Merge log files to autolog file >>> | import os >>> | import fileinput >>> | #top='C:\\Documents and Settings\\avanderspek\\My Documents\\CiDRAdata\\Syncrude\\CSL\\August2010' >>> | top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010' >>> >>> If you have backslashes in strings, you might want to use "raw >>> strings". Instead of "c:\\Users\\ZDoor" you'd write >>> r"c:\Users\ZDoor" (notice the r in front of the string). >> >> That's good general advice. But in the specific case of file >> paths, using '/' as the separator is supported, and somewhat >> preferable. > > Unless you're going to be passing them to cmd.exe or other utilities > via subprocess/popen. > in that case you could use os.path.normpath() prior to passing it to an external program und use slashies internally. A little less performant, but in my opinion nicer typing. From jak at isp2dial.com Tue Aug 17 15:14:50 2010 From: jak at isp2dial.com (John Kelly) Date: Tue, 17 Aug 2010 19:14:50 +0000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <8onl66tuq3k7a500atbpjtlj2bgbnpe0dq@4ax.com> On Tue, 17 Aug 2010 11:53:27 -0700 (PDT), Standish P wrote: >Another way to pose my question, as occurred to me presently is to ask >if a stack is a good abstraction for programming ? Certainly, it is >the main abstraction in Forth and Postscript and implementable readily >in C,C++ and I assume python. >so the name of the game is the same, ie to help the programmer keep >track of things for writing fault free code without chasing every >case, easy visualization, easy recall and communication with fellow >programmers of abstract concepts in terms of real world objects and >easy modification and code reuse. "Go is an attempt to combine the ease of programming of an interpreted, dynamically typed language with the efficiency and safety of a statically typed, compiled language. It also aims to be modern, with support for networked and multicore computing" "To make the stacks small, Go's run-time uses segmented stacks. A newly minted goroutine is given a few kilobytes, which is almost always enough. When it isn't, the run-time allocates (and frees) extension segments automatically" http://golang.org/doc/go_lang_faq.html -- Web mail, POP3, and SMTP http://www.beewyz.com/freeaccounts.php From almar.klein at gmail.com Tue Aug 17 15:31:07 2010 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 17 Aug 2010 21:31:07 +0200 Subject: 79 chars or more? In-Reply-To: References: Message-ID: > > A reason not mentioned much is that some people have trouble following > packed lines that are too much longer. Wide-page textbooks routinely put > text in two columns for easier reading. This is less of a factor with jagged > edge text, but if the limit were increased to say 150, there would be people > writing multi-line 150 char wide text blocks. > You're right. From Lshort (the introduction to Latex): "On average, no line should be longer than 66 characters." This applies to regular text, not for code per see, but it makes a strong case against (very) long lines. Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From john.passaniti at gmail.com Tue Aug 17 15:32:00 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Tue, 17 Aug 2010 12:32:00 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> Message-ID: <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> On Aug 17, 2:53?pm, Standish P wrote: > Another way to pose my question, as occurred to me presently is > to ask if a stack is a good abstraction for programming ? > Certainly, it is the main abstraction in Forth and Postscript > and implementable readily in C,C++ and I assume python. A stack is a fine abstraction for some kinds of programming. It fails for others. In languages where functions are first-class entities that can be stored and passed around like any other kind of data, stacks can be problematic because a function can out-live the stack frame they were created in. > It is true that the other languages such as F/PS also have borrowed > lists from lisp in the name of nested-dictionaries and mathematica > calls them nested-tables as its fundamental data structure. No. > The whole case of OOP is the clustering of thought, ie book-keeping, > in the mind of the programmer around fewer objects than ten or twenty > fold functions. That's one view of OOP. It's not the only one. > so the name of the game is the same, ie to help the programmer keep > track of things for writing fault free code without chasing every > case, easy visualization, easy recall and communication with fellow > programmers of abstract concepts in terms of real world objects and > easy modification and code reuse. You, like probably everyone else who has thought about how to "simplify" languages will eventually end up at the same place-- you'll have a model that meets your objectives, but with some programmers will find is unnecessarily limiting. More importantly, you'll run into some classes of problems for which your simple model makes things inordinately complicated relative to what other languages and paradigms offer. Here's a better idea: Become familiar with the languages you've cited, and more. I would recommend Forth, Lisp, Smalltalk or Ruby, Lua or JavaScript. Learn each and then come back and tell us if you think limiting the programmer to objects with stack-ordered lifetimes is enough. Oh, and while you're at it, dip your toes into a problem domain you don't normally do any work in. If you're an embedded systems guy, then spend some time writing a non-trivial web application. Go outside your comfort zone and find a problem domain where cherished idioms and tools no longer apply. I think it will open your eyes. From sschwarzer at sschwarzer.net Tue Aug 17 15:32:14 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 17 Aug 2010 21:32:14 +0200 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> Message-ID: <4C6AE3BE.5040908@sschwarzer.net> Hi Andrei, On 2010-08-17 18:43, AK wrote: > But let me ask you, would you really prefer to have: > >>>> self.expiration_date = translate_date( >>>> find(response, 'MPNExpirationDate').text, >>>> '%Y-%m-%d', '%m%d%Y') > > (or the 4-line version of this above), even when it necessitates > creation of a new function, rather than have this code on two lines? Given that the reformatted code is three lines and the former code two lines, I probably wouldn't change anything but the formatting as shown. :) > After all, I think it's a matter of balance between readability, > expressiveness and succinctness. If I split a function in two, that > still means that understanding the functionality of the code will > require scrolling around and looking at the second function. I guess > what I'm trying to say that we shouldn't just care about readability of > lines but also readability of functions and blocks of functionality > (that may include several functions that accomplish a single "task".) I think you're right here; you should keep the overall readability or (maintainability on the whole) in mind. I agree with Neil that good refactoring can _improve_ the understandability of the code, and it won't necessarily require you to look up the code of the extracted function or method. Stefan From almar.klein at gmail.com Tue Aug 17 15:33:12 2010 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 17 Aug 2010 21:33:12 +0200 Subject: 79 chars or more? In-Reply-To: <4C6ADB5C.70300@mrabarnett.plus.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6ABC16.4070006@gmail.com> <4C6ADB5C.70300@mrabarnett.plus.com> Message-ID: > If the display is limited to 80 characters then after printing the 80th > the cursor will be at the start of the next line and the newline will > cause the display to leave a blank line (unless the display has some > intelligence and supports pending newlines, of course). Ahah! So Windows users should actually limit their text to 78 chars? :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrei.avk at gmail.com Tue Aug 17 15:54:23 2010 From: andrei.avk at gmail.com (AK) Date: Tue, 17 Aug 2010 15:54:23 -0400 Subject: 79 chars or more? In-Reply-To: <4C6AE3BE.5040908@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4C6AB721.3060603@sschwarzer.net> <4C6AE3BE.5040908@sschwarzer.net> Message-ID: <4C6AE8EF.9050506@gmail.com> On 08/17/2010 03:32 PM, Stefan Schwarzer wrote: > Hi Andrei, > > On 2010-08-17 18:43, AK wrote: >> But let me ask you, would you really prefer to have: >> >>>>> self.expiration_date = translate_date( >>>>> find(response, 'MPNExpirationDate').text, >>>>> '%Y-%m-%d', '%m%d%Y') >> >> (or the 4-line version of this above), even when it necessitates >> creation of a new function, rather than have this code on two lines? > > Given that the reformatted code is three lines and the > former code two lines, I probably wouldn't change anything > but the formatting as shown. :) > >> After all, I think it's a matter of balance between readability, >> expressiveness and succinctness. If I split a function in two, that >> still means that understanding the functionality of the code will >> require scrolling around and looking at the second function. I guess >> what I'm trying to say that we shouldn't just care about readability of >> lines but also readability of functions and blocks of functionality >> (that may include several functions that accomplish a single "task".) > > I think you're right here; you should keep the overall > readability or (maintainability on the whole) in mind. > > I agree with Neil that good refactoring can _improve_ the > understandability of the code, and it won't necessarily > require you to look up the code of the extracted > function or method. I can certainly agree with that - although this sort of refactoring (when I do it) is driven by the logic of the code rather than the need to spread a long line over several lines :-). -andrei From barry at python.org Tue Aug 17 15:55:20 2010 From: barry at python.org (Barry Warsaw) Date: Tue, 17 Aug 2010 15:55:20 -0400 Subject: Python 2.6.6 release candidate 2 now available. Message-ID: <20100817155520.0d02675f@heresy> Hello fellow Python enthusiasts, The source tarballs and Windows installers for the second (and hopefully last) Python 2.6.6 release candidate is now available: http://www.python.org/download/releases/2.6.6/ We've had a handful of important fixes since rc1, and of course a huge number of bugs have been fixed since 2.6.5, with the full NEWS file available here: http://www.python.org/download/releases/2.6.6/NEWS.txt We would love it if you can download, install, and test this version with your favorite projects and on your favorite platforms. We expect to release Python 2.6.6 final on August 24, 2010. Please note that with the release of Python 2.7 final on July 3, 2010, and in accordance with Python policy, Python 2.6.6 is the last scheduled bug fix maintenance release of the 2.6 series. Because of this, your testing of this release candidate will help immensely. We plan on continuing to support source-only security fixes in Python 2.6 for the next five years. My thanks go out to everyone who has contributed with code, testing and bug tracker gardening for Python 2.6.6. The excellent folks on #python-dev are true Pythonic heros. Enjoy, -Barry (on behalf of the Python development community) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: not available URL: From ringemup at gmail.com Tue Aug 17 15:55:21 2010 From: ringemup at gmail.com (Nan) Date: Tue, 17 Aug 2010 12:55:21 -0700 (PDT) Subject: subprocess.Popen calling httpd reload never finishes Message-ID: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Hi folks -- I have a Python script running under Apache/mod_wsgi that needs to reload Apache configs as part of its operation. The script continues to execute after the subprocess.Popen call. The communicate() method returns the correct text ("Reloading httpd: [ OK ]"), and I get a returncode of 0. But the python script (Django) that calls Popen never seems to complete (by returning an HTTP response. Any other Popen call I've tried exits properly. Here's some sample code: args = ['sudo /etc/init.d/httpd reload'] proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, close_fds=True) (stdout_txt, stderr_txt) = proc.communicate("") proc.wait() logging.debug('%d %s


%s' % (proc.returncode, stdout_txt, stderr_txt)) logging.debug('still executing') return HttpResponse('done') The logging statements are output, but the script doesn't exit. If you substitute "sudo ls -l" or "sudo /etc/init.d/httpd configtest" for "sudo /etc/init.d/httpd reload", the exits properly. Any idea what I might be doing wrong? Thanks! From clp2 at rebertia.com Tue Aug 17 15:57:43 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 17 Aug 2010 12:57:43 -0700 Subject: Open a command pipe for reading In-Reply-To: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> References: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 9:40 AM, Rodrick Brown wrote: > I have a fairly large file 1-2GB in size that I need to process line by line but I first need to convert the file to text using a 3rd party tool that prints the records also line by line. > > I've tried using Popen to do this with no luck. I'm trying to simulate > > /bin/foo myfile.dat > > And as the records are being printed do some calculations. > > pipe = Popen(exttool,shell=True,stdout=PIPE).stdout I'd strongly suggest trying to avoid shell=True. > for data in pipe.readlines(): for data in pipe: > ? ?print data, > > This operation blocks forever I'm guessing it's trying to process the entire file at once. Indeed, that's how readlines() works, so don't use it. http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects Cheers, Chris -- http://blog.rebertia.com From thomas at jollybox.de Tue Aug 17 16:05:24 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 17 Aug 2010 22:05:24 +0200 Subject: Open a command pipe for reading In-Reply-To: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> References: <1FD1B648-8D18-4374-A301-6E59594FA105@gmail.com> Message-ID: <201008172205.27126.thomas@jollybox.de> On Tuesday 17 August 2010, it occurred to Rodrick Brown to exclaim: > I have a fairly large file 1-2GB in size that I need to process line by > line but I first need to convert the file to text using a 3rd party tool > that prints the records also line by line. > > I've tried using Popen to do this with no luck. I'm trying to simulate > > /bin/foo myfile.dat > > And as the records are being printed do some calculations. > > pipe = Popen(exttool,shell=True,stdout=PIPE).stdout > > for data in pipe.readlines(): > print data, > > This operation blocks forever I'm guessing it's trying to process the > entire file at once. Yes. It is. That's what you're telling it to do: file.readline returns a list of all the lines in the file. What you want to do is iterate over the stream, as in: for line in pipe: process(line) Also, there's probably no need to use shell=True. > > Sent from my iPhone 4. Is that a fact? This is so interesting. Phones these days. Almost as annoyingly obnoxious as gmx and yahoo mail. From stndshp at gmail.com Tue Aug 17 16:19:23 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 13:19:23 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> Message-ID: <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> On Aug 17, 12:32?pm, John Passaniti wrote: > On Aug 17, 2:53?pm, Standish P wrote: > > > Another way to pose my question, as occurred to me presently is > > to ask if a stack is a good abstraction for programming ? > > Certainly, it is the main abstraction in Forth and Postscript > > and implementable readily in C,C++ and I assume python. > > A stack is a fine abstraction for some kinds of programming. ?It fails > for others. ?In languages where functions are first-class entities > that can be stored and passed around like any other kind of data, > stacks can be problematic because a function can out-live the stack > frame they were created in. > > > It is true that the other languages such as F/PS also have borrowed > > lists from lisp in the name of nested-dictionaries and mathematica > > calls them nested-tables as its fundamental data structure. > > No. you are contradicting an earlier poster from forth who admitted the part on dicts. > > > The whole case of OOP is the clustering of thought, ie book-keeping, > > in the mind of the programmer around fewer objects than ten or twenty > > fold functions. > > That's one view of OOP. ?It's not the only one. and what can you add to enlighten the readers on the other view ? > > > so the name of the game is the same, ie to help the programmer keep > > track of things for writing fault free code without chasing every > > case, easy visualization, easy recall and communication with fellow > > programmers of abstract concepts in terms of real world objects and > > easy modification and code reuse. > > You, like probably everyone else who has thought about how to > "simplify" languages will eventually end up at the same place-- you'll > have a model that meets your objectives, but with some programmers > will find is unnecessarily limiting. ?More importantly, you'll run > into some classes of problems for which your simple model makes things > inordinately complicated relative to what other languages and > paradigms offer. The objective is to discuss those cases via specific examples (not generalities), and talk ABOUT them, not AROUND them. > Here's a better idea: ? Its a very fine wild goose chase project statement. > Become familiar with the languages you've > cited, and more. ?I would recommend Forth, Lisp, Smalltalk or Ruby, > Lua or JavaScript. ?Learn each and then come back and tell us if you > think limiting the programmer to objects with stack-ordered lifetimes > is enough. ?Oh, and while you're at it, dip your toes into a problem > domain you don't normally do any work in. ?If you're an embedded > systems guy, then spend some time writing a non-trivial web > application. ?Go outside your comfort zone and find a problem domain > where cherished idioms and tools no longer apply. ?I think it will > open your eyes. From a.j.romanista at gmail.com Tue Aug 17 16:19:53 2010 From: a.j.romanista at gmail.com (ata.jaf) Date: Tue, 17 Aug 2010 13:19:53 -0700 (PDT) Subject: Looking for an appropriate encoding standard that supports all languages Message-ID: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> I am developing a little program in Mac with wxPython. But I have problems with the characters that are not in ASCII. Like some special characters in French or Turkish. So I am looking for a way to solve this. Like an encoding standard that supports all languages. Or some other way. Thanks Ata Jafari From stndshp at gmail.com Tue Aug 17 16:22:09 2010 From: stndshp at gmail.com (Standish P) Date: Tue, 17 Aug 2010 13:22:09 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On Aug 17, 1:19?pm, Standish P wrote: > On Aug 17, 12:32?pm, John Passaniti wrote: > > > > > > > On Aug 17, 2:53?pm, Standish P wrote: > > > > Another way to pose my question, as occurred to me presently is > > > to ask if a stack is a good abstraction for programming ? > > > Certainly, it is the main abstraction in Forth and Postscript > > > and implementable readily in C,C++ and I assume python. > > > A stack is a fine abstraction for some kinds of programming. ?It fails > > for others. ?In languages where functions are first-class entities > > that can be stored and passed around like any other kind of data, > > stacks can be problematic because a function can out-live the stack > > frame they were created in. > > > > It is true that the other languages such as F/PS also have borrowed > > > lists from lisp in the name of nested-dictionaries and mathematica > > > calls them nested-tables as its fundamental data structure. > > > No. > > you are contradicting an earlier poster from forth who admitted the > part on dicts. > > > > > > The whole case of OOP is the clustering of thought, ie book-keeping, > > > in the mind of the programmer around fewer objects than ten or twenty > > > fold functions. > > > That's one view of OOP. ?It's not the only one. > > and what can you add to enlighten the readers on the other view ? > > > > > > so the name of the game is the same, ie to help the programmer keep > > > track of things for writing fault free code without chasing every > > > case, easy visualization, easy recall and communication with fellow > > > programmers of abstract concepts in terms of real world objects and > > > easy modification and code reuse. > > > You, like probably everyone else who has thought about how to > > "simplify" languages will eventually end up at the same place-- you'll > > have a model that meets your objectives, but with some programmers > > will find is unnecessarily limiting. ?More importantly, you'll run > > into some classes of problems for which your simple model makes things > > inordinately complicated relative to what other languages and > > paradigms offer. > > The objective is to discuss those cases via specific examples (not > generalities), and talk ABOUT them, not AROUND them. > > > Here's a better idea: ? > > Its a very fine wild goose chase project statement. > > > > > Become familiar with the languages you've > > cited, and more. ?I would recommend Forth, Lisp, Smalltalk or Ruby, > > Lua or JavaScript. ?Learn each and then come back and tell us if you > > think limiting the programmer to objects with stack-ordered lifetimes > > is enough. ?Oh, and while you're at it, dip your toes into a problem > > domain you don't normally do any work in. ?If you're an embedded > > systems guy, then spend some time writing a non-trivial web > > application. ?Go outside your comfort zone and find a problem domain > > where cherished idioms and tools no longer apply. ?I think it will > > open your eyes program a universe simulator using a turing machine. From erather at forth.com Tue Aug 17 16:37:17 2010 From: erather at forth.com (Elizabeth D Rather) Date: Tue, 17 Aug 2010 10:37:17 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On 8/17/10 10:19 AM, Standish P wrote: > On Aug 17, 12:32 pm, John Passaniti wrote: ... >>> It is true that the other languages such as F/PS also have borrowed >>> lists from lisp in the name of nested-dictionaries and mathematica >>> calls them nested-tables as its fundamental data structure. >> >> No. > > you are contradicting an earlier poster from forth who admitted the > part on dicts. Not at all. A Forth dictionary is a simple linked list, not the complicated kind of nested structures you're referring to. You really seem addicted to very complex structures. They really aren't necessary for general programming. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From thomas at jollybox.de Tue Aug 17 16:55:42 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 17 Aug 2010 22:55:42 +0200 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> Message-ID: <201008172255.46662.thomas@jollybox.de> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > I am developing a little program in Mac with wxPython. > But I have problems with the characters that are not in ASCII. Like > some special characters in French or Turkish. > So I am looking for a way to solve this. Like an encoding standard > that supports all languages. Or some other way. Anything that supports all of Unicode will do. Like UTF-8. If your text is mostly Latin, then just go for UTF-8, if you use other alphabets extensively, you might want to consider UTF-16, which might the use a little less space. From raoulbia at gmail.com Tue Aug 17 17:44:22 2010 From: raoulbia at gmail.com (Baba) Date: Tue, 17 Aug 2010 14:44:22 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> Message-ID: <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> On Aug 16, 6:28?pm, "cbr... at cbrownsystems.com" wrote: > First, suppose d = gcd(x, y, z); then for some x', y', z' we have that > x = d*x', y = d*y', z = d*z'; and so for any a, b, c: > could you explain the notation? what is the difference btw x and x' ? what is x = d*x', y supposed to say? > To go the other way, if d = 1, then there exists integers (not > neccessarily positive) such that > > a*x + b*y + c*z = 1 > what's the link with 6*a+9*b+20*c=n except the similarity? furthermore i came across this: For k = 3, efficient algorithms have been given by Greenberg and Davison ; if x1 < x2 < x3, these algorithms run in time bounded by a polynomial in log x3. Kannan gave a very complicated algorithm that runs in polynomial time in log xk if k is fixed, but is wildly exponential in k. However, Ram??rez Alfons??n proved that the general problem is NP-hard, under Turing reductions, by reducing from the integer knapsack problem. So it seems very likely that there is no simple formula for computing g(x1, x2, . . . , xk) for arbitrary k. source: http://arxiv.org/PS_cache/arxiv/pdf/0708/0708.3224v1.pdf i would be interested in the answer to problem 3: explain in English why the theorem is true @Giacomo: when you say that i have not read the text of the assignment i tend to disagree. Therefore could you point out what it is i overlooked that should help me prove my assumption for the generalisation? Enjoy the sausages btw :) tnx Baba From paddy3118 at googlemail.com Tue Aug 17 17:47:55 2010 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 17 Aug 2010 14:47:55 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> <2abafeea-78e6-454c-8c3d-debe888d2bc7@h40g2000pro.googlegroups.com> Message-ID: On 17 Aug, 02:29, Raymond Hettinger wrote: > [Paddy] > > > Lets say you have two *sets* of integers representing two near-copies > > of some system, then a measure of their difference could be calculated > > as: > > > len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 % > > > If the two collections of integers are allowed duplicates then you > > need a Counter/bag/multi-set type and the diff calculation I gave > > originally. > > Thanks for sharing your use case. > > It's unlikely that I will add this method to the Counter API because > the rarity of use case does not warrant the added API complexity. > IMO, adding a method like this makes the class harder to learn, > understand and remember. ?It doesn't seem like much of a win over > using the existing alternatives: > > ?* (b - c) + (c - b) > ?* (b | c) - (b & c) > ?* DIY using the two counters as simple dicts > ?* writing a subclass providing additional binary operations > > I would like to see someone post a subclass to the ASPN Cookbook that > adds a number of interesting, though not common operations. ?Your > symmetric_difference() method could be one. ?A dot_product() operation > could be another. ?Elementwise arithmetic is another option (we > already have add and subtract, but could possibly use multiply, > divide, etc). ?Scaling operations are another possibility (multiple > all elements by five, for example). > > The Counter() class has low aspirations. ?It is a dictionary that > fills-in missing values with zero and is augmented by a handful of > basic methods for managing the counts. > > Raymond I created this that could be an addition to the bottom of the Python 3 collections.Counter class definition: def __xor__(self, other): ''' symmetric difference: Subtract count, but keep only abs results with non-zero counts. >>> Counter('abbbc') ^ Counter('bccd') Counter({'b': 2, 'a': 1, 'c': 1, 'd': 1}) >>> a, b = Counter('abbbc'), Counter('bccd') >>> (a-b) + (b - a) == a ^ b True ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem in set(self) | set(other): newcount = self[elem] - other[elem] if newcount != 0: result[elem] = newcount if newcount > 0 else -newcount return result - Paddy. From roy at panix.com Tue Aug 17 17:54:29 2010 From: roy at panix.com (Roy Smith) Date: Tue, 17 Aug 2010 17:54:29 -0400 Subject: Python "why" questions References: <8crequF9tpU1@mid.individual.net> <4c6a0bb7$0$28672$c3e8da3@news.astraweb.com> Message-ID: In article , Martin Gregorie wrote: > > Roy wasn't using numpy/Python semantics but made-up semantics (following > > Martin Gregorie's made-up semantics to which he was replying) which > > treat the step size as a true size, not a size and direction. The > > direction is determined from the start and stop parameters. It's an > > almost-reasonable design. > > That wasn't a made-up example: AFAICR and ignoring a missing semi-colon > it was an Algol 68 snippet. It was a made up example. Any similarity to a real programming language, living or dead, was purely a coincidence. I suspect I've probably also written a viable code snippet in Whitespace as well (http://compsoc.dur.ac.uk/whitespace/). That, too, is a coincidence. From roy at panix.com Tue Aug 17 17:55:35 2010 From: roy at panix.com (Roy Smith) Date: Tue, 17 Aug 2010 17:55:35 -0400 Subject: Python "why" questions References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> <4c6a8cff$1@dnews.tpgi.com.au> Message-ID: In article <4c6a8cff$1 at dnews.tpgi.com.au>, Lie Ryan wrote: > On 08/16/10 21:54, David Cournapeau wrote: > > On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing > > wrote: > >>> On Aug 7, 2010, at 9:14 PM, John Nagle wrote: > >>> > >>>> The languages which have real multidimensional arrays, rather > >>>> than arrays of arrays, tend to use 1-based subscripts. That > >>>> reflects standard practice in mathematics. > >> > >> Not always -- mathematicians use whatever starting index is > >> most convenient for the problem at hand. > > > > Yes, there are many engineering fields where index starts at 0. Partly > > for the reason you have stated concerning polynomials, especially > > since this extend to series, which are pervasive in numerical > > computing. In linear algebra, though, I remember to have always noted > > matrices indexes in the [1,n] range, not [0,n-1]. > > I'm sure some would prefer to denote it as [0, n) Only if there's an emacs mode which can do the parenthesis matching correctly ;-) From nobody at nowhere.com Tue Aug 17 17:58:09 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 17 Aug 2010 22:58:09 +0100 Subject: 79 chars or more? References: Message-ID: On Mon, 16 Aug 2010 22:35:49 -0400, AK wrote: > As monitors are getting bigger, is there a general change in opinion on > the 79 chars limit in source files? I've experimented with 98 characters > per line and I find it quite a bit more comfortable to work with that > length, even though sometimes I have to edit files in 80 width > terminals, it's still easier to adapt to some inconvenience when that > happens than the other way around, since about 95% of time or more, I do > use wider editor window or terminal. > > Is going over 79 still a terrible thing to do? -andrei If the the limit isn't 79, then what is it? Or are 1000-column lines okay? Often, simply having a convention is more important than the precise details. E.g. I don't particularly care how I configure my text editor's auto-formatting settings, but I do care about not having to change those settings for each file. For code which will never be read or edited by anyone other than yourself, use whatever conventions you want. If you're going to publish the code, it's a good idea to stick to established standards (80-column lines, 8-column tabs, no gratuitous use of non-ASCII characters, etc). Apart from "altruistic" reasons, bear in mind that the next time you apply for a job, the employer may look at your code not just to determine your programming competence, but also whether you're likely to be a "team player". Code which doesn't follow normal conventions says "I've only ever worked on my own, not with other people". I can't stress enough how big a factor this is. Writing code by yourself and working as part of a team are almost entirely different skills. Anyone who regularly hires programmers will be only too aware of the difference. From debatem1 at gmail.com Tue Aug 17 18:04:43 2010 From: debatem1 at gmail.com (geremy condra) Date: Tue, 17 Aug 2010 15:04:43 -0700 Subject: Python "why" questions In-Reply-To: <4c6a8cff$1@dnews.tpgi.com.au> References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> <4c6a8cff$1@dnews.tpgi.com.au> Message-ID: On Tue, Aug 17, 2010 at 7:59 AM, Lie Ryan wrote: > On 08/16/10 21:54, David Cournapeau wrote: >> On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing >> wrote: >>>> On Aug 7, 2010, at 9:14 PM, John Nagle wrote: >>>> >>>>> ?The languages which have real multidimensional arrays, rather >>>>> than arrays of arrays, tend to use 1-based subscripts. ?That >>>>> reflects standard practice in mathematics. >>> >>> Not always -- mathematicians use whatever starting index is >>> most convenient for the problem at hand. >> >> Yes, there are many engineering fields where index starts at 0. Partly >> for the reason you have stated concerning polynomials, especially >> since this extend to series, which are pervasive in numerical >> computing. In linear algebra, though, I remember to have always noted >> matrices indexes in the [1,n] range, not [0,n-1]. > > I'm sure some would prefer to denote it as [0, n) Count me in on that, that'd be great. Geremy Condra From abhijeet.thatte at gmail.com Tue Aug 17 18:21:38 2010 From: abhijeet.thatte at gmail.com (abhijeet thatte) Date: Tue, 17 Aug 2010 15:21:38 -0700 Subject: Need to import stuff Message-ID: Hi, I need to import few files depending on the user input. For eg if user gives an input as "abcd" then I will have * import "abcd.py".* Can not have any hard coding in the code. Does any one know how to solve the problem. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Aug 17 18:27:39 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 17 Aug 2010 18:27:39 -0400 Subject: Need to import stuff In-Reply-To: References: Message-ID: On Tue, Aug 17, 2010 at 6:21 PM, abhijeet thatte wrote: > Hi, > I need to import few files depending on the user input. For eg if user gives > an input as "abcd" then I will have??import "abcd.py". > Can not have any hard coding in the code. Does any one know how to solve the > problem. Use the __import__ function ( http://docs.python.org/library/functions.html#__import__ ), like this: user_module = __import__("abdc") user_module.do_stuff() -- Jerry From paddy3118 at googlemail.com Tue Aug 17 18:27:45 2010 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 17 Aug 2010 15:27:45 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> <2abafeea-78e6-454c-8c3d-debe888d2bc7@h40g2000pro.googlegroups.com> Message-ID: <79c11629-1092-4c6c-9fe9-4fdea65f4f33@s9g2000yqd.googlegroups.com> On Aug 17, 10:47?pm, Paddy wrote: > On 17 Aug, 02:29, Raymond Hettinger wrote: > > > > > [Paddy] > > > > Lets say you have two *sets* of integers representing two near-copies > > > of some system, then a measure of their difference could be calculated > > > as: > > > > len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 % > > > > If the two collections of integers are allowed duplicates then you > > > need a Counter/bag/multi-set type and the diff calculation I gave > > > originally. > > > Thanks for sharing your use case. > > > It's unlikely that I will add this method to the Counter API because > > the rarity of use case does not warrant the added API complexity. > > IMO, adding a method like this makes the class harder to learn, > > understand and remember. ?It doesn't seem like much of a win over > > using the existing alternatives: > > > ?* (b - c) + (c - b) > > ?* (b | c) - (b & c) > > ?* DIY using the two counters as simple dicts > > ?* writing a subclass providing additional binary operations > > > I would like to see someone post a subclass to the ASPN Cookbook that > > adds a number of interesting, though not common operations. ?Your > > symmetric_difference() method could be one. ?A dot_product() operation > > could be another. ?Elementwise arithmetic is another option (we > > already have add and subtract, but could possibly use multiply, > > divide, etc). ?Scaling operations are another possibility (multiple > > all elements by five, for example). > > > The Counter() class has low aspirations. ?It is a dictionary that > > fills-in missing values with zero and is augmented by a handful of > > basic methods for managing the counts. > > > Raymond > > I created this that could be an addition to the bottom of the Python 3 > collections.Counter class definition: > > ? ? def __xor__(self, other): > ? ? ? ? ''' symmetric difference: Subtract count, but keep only abs > results with non-zero counts. > > ? ? ? ? >>> Counter('abbbc') ^ Counter('bccd') > ? ? ? ? Counter({'b': 2, 'a': 1, 'c': 1, 'd': 1}) > ? ? ? ? >>> a, b = Counter('abbbc'), Counter('bccd') > ? ? ? ? >>> (a-b) + (b - a) == a ^ b > ? ? ? ? True > > ? ? ? ? ''' > ? ? ? ? if not isinstance(other, Counter): > ? ? ? ? ? ? return NotImplemented > ? ? ? ? result = Counter() > ? ? ? ? for elem in set(self) | set(other): > ? ? ? ? ? ? newcount = self[elem] - other[elem] > ? ? ? ? ? ? if newcount != 0: > ? ? ? ? ? ? ? ? result[elem] = newcount if newcount > 0 else -newcount > ? ? ? ? return result > > - Paddy. And heres the cartesian product/multiply: def __mul__(self, other): '''Multiply counts by an integer; or cartesioan product of two counters. >>> Counter('abbb') * 3 Counter({'b': 9, 'a': 3}) >>> Counter('12') * Counter('21') Counter({('2', '1'): 1, ('1', '2'): 1, ('1', '1'): 1, ('2', '2'): 1}) >>> Counter('122') * Counter('211') Counter({('2', '1'): 4, ('1', '1'): 2, ('2', '2'): 2, ('1', '2'): 1}) ''' if isinstance(other, int): return Counter(**dict((k, v*other) for k,v in self.items())) elif isinstance(other, Counter): return Counter( (x, y) for x in self.elements() for y in other.elements() ) else: return NotImplemented (Although I don't have a use case for this one). - Paddy. From abhijeet.thatte at gmail.com Tue Aug 17 18:40:28 2010 From: abhijeet.thatte at gmail.com (abhijeet thatte) Date: Tue, 17 Aug 2010 15:40:28 -0700 Subject: Fwd: Need to import stuff In-Reply-To: References: Message-ID: Hi, Thanks for the reply. But I guess it does not support nested file paths. If user gives 'abcd' then I need to import "*/Do/Stuff/abcd*". Out of which only *"abcd" is taken run time. Do and Stuff are fixed. * *I got an error "*ImportError: Import by filename is not supported.". Any solution?? On Tue, Aug 17, 2010 at 3:27 PM, Jerry Hill wrote: > On Tue, Aug 17, 2010 at 6:21 PM, abhijeet thatte > wrote: > > Hi, > > I need to import few files depending on the user input. For eg if user > gives > > an input as "abcd" then I will have import "abcd.py". > > Can not have any hard coding in the code. Does any one know how to solve > the > > problem. > > Use the __import__ function ( > http://docs.python.org/library/functions.html#__import__ ), like this: > > user_module = __import__("abdc") > user_module.do_stuff() > > -- > Jerry > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at googlemail.com Tue Aug 17 18:46:17 2010 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 17 Aug 2010 15:46:17 -0700 (PDT) Subject: EXOR or symmetric difference for the Counter class References: <51463649-dc0f-497a-8bf3-72a76fa2f819@f6g2000yqa.googlegroups.com> <19f79193-dd54-485a-ad0b-a826506ed39b@l6g2000yqb.googlegroups.com> <2abafeea-78e6-454c-8c3d-debe888d2bc7@h40g2000pro.googlegroups.com> Message-ID: <37830391-3813-4591-bbcb-91038bf6f432@5g2000yqz.googlegroups.com> On Aug 17, 2:29?am, Raymond Hettinger wrote: > I would like to see someone post a subclass to the ASPN Cookbook that > adds a number of interesting, though not common operations. ?Your > symmetric_difference() method could be one. ?A dot_product() operation > could be another. ?Elementwise arithmetic is another option (we > already have add and subtract, but could possibly use multiply, > divide, etc). ?Scaling operations are another possibility (multiple > all elements by five, for example). > > > Raymond Sample code is at http://code.activestate.com/recipes/577362-extension-to-python-3-counter-class/ From rodrick.brown at gmail.com Tue Aug 17 19:49:28 2010 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Tue, 17 Aug 2010 19:49:28 -0400 Subject: 0 length field in time string References: <61ACDB22F695024F87600CD2255B3F6B6307FC8C5D@NYWEXMBX2127.msad.ms.com> Message-ID: Anyone know why I'm getting the following error when trying to parse the following string is there a better method to use? #57=2010081708240065 - sample string passed to fmt_datetime def fmt_datetime(tag57): tag57 = tag57[3:len(tag57)] year = int ( tag57[0:4] ) mon = int ( tag57[4:6] ) day = int ( tag57[6:8]) hour = int ( tag57[8:10] ) min = int ( tag57[10:12] ) sec = int ( tag57[12:14] ) msec = int ( tag57[14:16] ) dt = datetime.datetime(year,mon,day,hour,min,sec) return '{:%Y-%m-%d %H:%M:%S}'.format(dt) File "./delta_delay.py", line 27, in fmt_datetime return '{:%Y-%m-%d %H:%M:%S}'.format(dt) ValueError: zero length field name in format -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 17 20:12:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 01:12:52 +0100 Subject: 0 length field in time string In-Reply-To: References: <61ACDB22F695024F87600CD2255B3F6B6307FC8C5D@NYWEXMBX2127.msad.ms.com> Message-ID: <4C6B2584.1060602@mrabarnett.plus.com> Rodrick Brown wrote: > Anyone know why I'm getting the following error when trying to parse the > following string is there a better method to use? > > #57=2010081708240065 - sample string passed to fmt_datetime > > def fmt_datetime(tag57): > tag57 = tag57[3:len(tag57)] > year = int ( tag57[0:4] ) > mon = int ( tag57[4:6] ) > day = int ( tag57[6:8]) > hour = int ( tag57[8:10] ) > min = int ( tag57[10:12>] ) > sec = int ( tag57[12:14>] ) > msec = int ( tag57[14:16] ) > You could use: dt = datetime.datetime.strptime(tag57[3 : 17], "%Y%m%d%H%M%S") > dt = datetime.datetime(year,mon,day,hour,min,sec) > return '{:%Y-%m-%d %H:%M:%S}'.format(dt) > > File "./delta_delay.py", line 27, in fmt_datetime > return '{:%Y-%m-%d %H:%M:%S}'.format(dt) > ValueError: zero length field name in format > You haven't supplied an argument name or position (required in Python 2.6): return '{0:%Y-%m-%d %H:%M:%S}'.format(dt) From marduk at letterboxes.org Tue Aug 17 20:14:29 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 17 Aug 2010 20:14:29 -0400 Subject: subprocess.Popen calling httpd reload never finishes In-Reply-To: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> References: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Message-ID: <1282090469.456104.35.camel@paska> On Tue, 2010-08-17 at 12:55 -0700, Nan wrote: > Hi folks -- > > I have a Python script running under Apache/mod_wsgi that needs to > reload Apache configs as part of its operation. The script continues > to execute after the subprocess.Popen call. The communicate() method > returns the correct text ("Reloading httpd: [ OK ]"), and I get a > returncode of 0. But the python script (Django) that calls Popen > never seems to complete (by returning an HTTP response. > > Any other Popen call I've tried exits properly. Here's some sample > code: > > args = ['sudo /etc/init.d/httpd reload'] > proc = subprocess.Popen(args, stdin=subprocess.PIPE, > stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, > close_fds=True) > (stdout_txt, stderr_txt) = proc.communicate("") > proc.wait() > logging.debug('%d %s
%s' % (proc.returncode, stdout_txt, > stderr_txt)) > logging.debug('still executing') > return HttpResponse('done') > > The logging statements are output, but the script doesn't exit. If > you substitute "sudo ls -l" or "sudo /etc/init.d/httpd configtest" for > "sudo /etc/init.d/httpd reload", the exits properly. > > Any idea what I might be doing wrong? > > Thanks! Django runs inside apache. It's kinda weird to have an apache process restart itself and expect it to return to the caller. If the init script does like mine, "reload" executes "apachectl -k graceful" What that instructs apache to do is to restart, but only kill the process(es) when there are no more connections. So apache is waiting for your connection to close, but you are inside an HTTP request waiting for apache to restart. So you have a race condition here. It's not advisable to have apache kill itself and expect it to send a status back to you telling you it's dead. See the apache docs[1] for a better explanation. http://httpd.apache.org/docs/2.0/stopping.html#graceful From woooee at gmail.com Tue Aug 17 20:55:52 2010 From: woooee at gmail.com (woooee) Date: Tue, 17 Aug 2010 17:55:52 -0700 (PDT) Subject: update of elements in GUI References: <24dc97b3-a8b5-4638-9cf5-a397f1eae295@q16g2000prf.googlegroups.com> Message-ID: On Aug 16, 9:07?pm, Jah_Alarm wrote: > hi, I've already asked this question but so far the progress has been > small. > > I'm running Tkinter. I have some elements on the screen (Labels, most > importantly) which content has to be updated every iteration of the > algorithm run, e.g. "Iteration =" [i] for i in range(n), n=100. I'm > using the update_idletasks() command in the function itself after the > variable.set(...) command. The variable type is IntVar(), and the > mistake I'm getting is 'IntVar instance has no attribute > 'update_idletasks'. No updates are displayed, of course. > > Without the GUI the algorithm (it's a genetic algorithm) is working > fine, but I need to make it available to other people via GUI > > cheers, > > Alex This program I had lying around and it will hopefully make things clearer. The integer under the second label (i.e. the 3rd label) increases by on every time you click the "Print Contents" button. The variable associated with the second label and the entry box update as you change the entry box's contents, all with no calls to update_idletasks(). class EntryTest: """ shows using the same StringVar in the second list box and in the entry box """ def __init__(self): self.top = Tkinter.Tk() self.top.title("Test of Entry") self.top.geometry("200x150+10+10") self.str_1 = Tkinter.StringVar() label_lit = Tkinter.StringVar() self.int_lit = Tkinter.IntVar() label_1 = Tkinter.Label(self.top, textvariable = label_lit ) label_1.pack() label_lit.set( "Test of Label") label_2 = Tkinter.Label(self.top, textvariable = self.str_1 ) label_2.pack() label_3 = Tkinter.Label(self.top, textvariable = self.int_lit ) label_3.pack() self.int_lit.set(0) entry_1 = Tkinter.Entry(self.top, textvariable=self.str_1) entry_1.pack() self.str_1.set( "Entry Initial Value" ) print_button = Tkinter.Button(self.top, text='PRINT CONTENTS', command=self.getit, bg='blue', fg='white' ) print_button.pack(fill=Tkinter.X, expand=1) exit_button= Tkinter.Button(self.top, text='EXIT', command=self.top.quit, bg='red', fg='white' ) exit_button.pack(fill=Tkinter.X, expand=1) entry_1.focus_set() self.top.mainloop() ##----------------------------------------------------------------- def getit(self) : print "getit: variable passed =", self.str_1.get() x = self.int_lit.get() self.int_lit.set(x+1) ##=============================================================== if "__main__" == __name__ : ET=EntryTest() print "under __main__ =", ET.str_1.get() From steve.ferg.bitbucket at gmail.com Tue Aug 17 21:20:41 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Tue, 17 Aug 2010 18:20:41 -0700 (PDT) Subject: question about pdb assignment statements References: Message-ID: Thanks mucho!! From john.passaniti at gmail.com Tue Aug 17 21:38:39 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Tue, 17 Aug 2010 18:38:39 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On Aug 17, 4:19?pm, Standish P wrote: > > > It is true that the other languages such as F/PS also have borrowed > > > lists from lisp in the name of nested-dictionaries and mathematica > > > calls them nested-tables as its fundamental data structure. > > > No. > > you are contradicting an earlier poster from forth who admitted the > part on dicts. Then they are wrong. You asked if Forth "borrowed" lists from Lisp. It did not. In Lisp, lists are constructed with pair of pointers called a "cons cell". That is the most primitive component that makes up a list. Forth has no such thing; in Forth, the dictionary (which is traditionally, but not necessarily a list) is a data structure that links to the previous word with a pointer. This is in fact one of the nice things about Lisp; because all lists are created out of the same primitive cons cell, you can consistently process any list in the system. In Forth, any lists (such as the dictionary, if it is a list) are specific to their purpose and have to be treated individually. I don't know what you mean by "nested-dictionaries." There is no such thing in Forth. Dictionaries don't nest. You can create wordlists, but each wordlist is flat. When most people think of a nested dictionary, they would think of a structure that would allow any arbitrary level of nesting, not a string of flat wordlists. > > > The whole case of OOP is the clustering of thought, ie book-keeping, > > > in the mind of the programmer around fewer objects than ten or twenty > > > fold functions. > > > That's one view of OOP. ?It's not the only one. > > and what can you add to enlighten the readers on the other view ? How one views OOP depends on the language and implementation. Your statement about having fewer than "ten or twenty fold" functions is completely arbitrary and is more a matter of style and skill in decomposition than an intrinsic quality about objects. The poetic "clustering of thought" is vague but a I guess could be an informal notion of the bundling of related state and methods. And referring to it as "book-keeping" suggests some kind of static relationship between state and methods, although that is not the case in architectures that stress dynamic relationships. Many people only know OOP through static, class-based models (such as in languages like C++). But there are other models. Objects can also be represented not with classes but by cloning existing objects and then mutating them as needed. Objects can also be represented with a functional interface using a closure around an environment. In such cases, objects may be far more fluid than in static class-based models, and shift over time into different roles. In such systems, "book-keeping" isn't static. Or put another way, the language and implementation drive the flavor that a particular object has. > > You, like probably everyone else who has thought about how to > > "simplify" languages will eventually end up at the same place-- you'll > > have a model that meets your objectives, but with some programmers > > will find is unnecessarily limiting. ?More importantly, you'll run > > into some classes of problems for which your simple model makes things > > inordinately complicated relative to what other languages and > > paradigms offer. > > The objective is to discuss those cases via specific examples (not > generalities), and talk ABOUT them, not AROUND them. I'd be happy to discuss specific examples, but your understanding of Forth is flawed, and until you learn more about Forth, I don't think it would be helpful. And actually, I did provide a specific example. You apparently didn't understand it, so let me be more explicit. Here is a function in Scheme: (define (hello name) (lambda () (begin (display "Hello ") (display name)))) This defines a function that returns another function. You can think of this as a constructor for a light-weight object that has one value ("name") and one default method (to print "Hello "). The function that is returned can be stored, passed around, and otherwise out-live the invocation of this function. For example: (define example (hello "John")) In your stack mindset, the value "John" would disappear after the call to "hello". But in Scheme, the value lives on, as it is part of the closure captured at the time the function was created. A stack mindset would not allow this. And this would eliminate the vast majority of functional programming from your language's abilities. Maybe you don't care, or maybe you still don't see the value in this. In that case, I suggest you learn the language and then think about what your stack mindset prevents. > > Here's a better idea: ? > > Its a very fine wild goose chase project statement. No, it is a vivid example of what you don't know-- and what you don't know is what will limit you later. From russ.paielli at gmail.com Tue Aug 17 22:15:54 2010 From: russ.paielli at gmail.com (Russ P.) Date: Tue, 17 Aug 2010 19:15:54 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> Message-ID: <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> On Aug 7, 5:54?am, "D'Arcy J.M. Cain" wrote: > Would said beginner also be surprised that a newborn baby is zero years > old or would it be more natural to call them a one year old? ?Zero > based counting is perfectly natural. You're confusing continuous and discrete variables. Time is a continuous variable, but a list index is discrete. Take a look at any numbered list, such as the top ten football teams or the top ten software companies. Have you ever seen such a list start with zero? If so, where? I sure haven't. When I studied linear algebra way back, vector and matrix indices also always started with one, and I assume they still do. The convention of starting with zero may have had some slight performance advantage in the early days of computing, but the huge potential for error that it introduced made it a poor choice in the long run, at least for high-level languages. From nikos.the.gr33k at gmail.com Tue Aug 17 23:15:24 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Tue, 17 Aug 2010 20:15:24 -0700 (PDT) Subject: String substitution VS proper mysql escaping Message-ID: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> =============================== cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) =============================== Someone told me NOT to do string substitution ("%") on SQL statements and to let MySQLdb do it for me, with proper escaping like the following =============================== cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s ORDER BY date DESC''', (page,)) =============================== The difference is that if some external source can control "page", and they put in a value like 100 ; DELETE FROM visitors; SELECT * FROM visitors i will be losing my database table data. a) I wanted to ask what is proper escaping mean and why after variable page syntax has a comma and as i have the script now why don't my code as i have it now for string reproduction =============================== http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors " =============================== don't reproduce the problem of actual deleting my data. I don't care losing it! I just want to see that happening with my own eyes! From dan.kluev at gmail.com Wed Aug 18 00:26:32 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Wed, 18 Aug 2010 15:26:32 +1100 Subject: String substitution VS proper mysql escaping In-Reply-To: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> References: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> Message-ID: 2010/8/18 ????? > a) I wanted to ask what is proper escaping mean and > > Proper escaping means that value is wrapped in quotes properly, and quotes and backslashes (or any other special to RDBMS symbol) are escaped with backslashes. why after variable page syntax has a comma > Comma just means its tuple. (page) is equal to page, while (page,) is one-element tuple which contains page: >>> ('123') '123' >>> ('123',) ('123',) > why don't my code as i have it now for string reproduction > > =============================== > http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT > * FROM visitors " > =============================== > > don't reproduce the problem of actual deleting my data. I don't care > losing it! > > I just want to see that happening with my own eyes! > > Your script there just throws an exception for any page data, and most likely does not run any query at all: > 28 # open current html template and get the page ID number > 29 # > ================================================================================================================= > 30 f = open( '/home/webville/public_html/' + page ) > 31 > 32 # read first line of the file > f undefined, builtin open = , page = ['index.html', '100'] > TypeError: cannot concatenate 'str' and 'list' objects > Besides, using user-provided data and just concatenating it to filename like that is definitely bad idea. You should use os.path.join() at least. Regarding that kind of SQL injection, typically driver will stop it to happen when you provide 2 queries at once delimited by ';', so drop table would not work. However its possible to issue UNION's to retrieve sensitive data from your database. -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Wed Aug 18 00:31:22 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 18 Aug 2010 14:31:22 +1000 Subject: String substitution VS proper mysql escaping In-Reply-To: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> References: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> Message-ID: <20100818043122.GA27336@cskk.homeip.net> On 17Aug2010 20:15, ????? wrote: | =============================== | cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = | '%s' ORDER BY date DESC ''' % (page) ) | =============================== | | Someone told me NOT to do string substitution ("%") on SQL statements | and to let MySQLdb do it | for me, with proper escaping like the following | | =============================== | cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s | ORDER BY date DESC''', (page,)) | =============================== | | The difference is that if some external source can control "page", | and | they put in a value like | 100 ; DELETE FROM visitors; SELECT * FROM visitors | i will be losing my database table data. That other difference is that the mysql dialect support knows how to correctly escape a string for insertion into an SQL statement. You may not, or may forget to pre-escape the string, etc. Using the MySQLdb stuff do it for you is reliable and robust. | a) I wanted to ask what is proper escaping mean and why after variable | page syntax has a comma Because this: (page) means the same thing as: page i.e. the argument to the "%" operator is just the string in page. This: (page,) is a _tuple_ containing a single element, the page variable. A bit like: [page] which is a list containing a single element. The trailing comma is needed to tell python you want to use a tuple, not the bare string. The "%" operator has special knowledge that is it is passed as string instead of a list or tuple or other sequence then it should act _as_ _if_ it had been passed a single element tuple containing the string. Otherwise, because a string _is_ a sequence the "%" might want to treat the string "foo" as the sequence: ("f", "o", "o") Run these three loops to see the difference: for s in "foo": print s for s in ("foo"): print s for s in ("foo",): print s Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ I couldn't think of anything else to do with it, so I put it on the web. From dan.kluev at gmail.com Wed Aug 18 00:39:06 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Wed, 18 Aug 2010 15:39:06 +1100 Subject: Need to import stuff In-Reply-To: References: Message-ID: On Wed, Aug 18, 2010 at 9:40 AM, abhijeet thatte wrote: > Hi, > > Thanks for the reply. But I guess it does not support nested file paths. > If user gives 'abcd' then I need to import "*/Do/Stuff/abcd*". Out of > which only *"abcd" is taken run time. Do and Stuff are fixed. * > *I got an error "*ImportError: Import by filename is not supported.". Any > solution?? > > For complex importing, you can use imp module, http://docs.python.org/library/imp.html Like this: module_desc = imp.find_module(name, [base_path]) module = imp.load_module(full_name, *module_desc) -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From bidda.gowda at gmail.com Wed Aug 18 03:19:31 2010 From: bidda.gowda at gmail.com (Bidda Gowda) Date: Wed, 18 Aug 2010 12:49:31 +0530 Subject: Call Java Code from python Message-ID: Hi, I have a project coming up where i have to integrate our existing Python based web application with Java Programs. Basically i should be able to call Java programs which comes in the form of jars. Whats the best way to call these jars from python ? I looked at jpype and tried with small program and it works. Are there any other tools which can do the same or if any how are they compared to jpype ? -- B Gowda. From nagle at animats.com Wed Aug 18 03:29:41 2010 From: nagle at animats.com (John Nagle) Date: Wed, 18 Aug 2010 00:29:41 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <89467860-45ac-4a3b-ac17-f11a19429187@i13g2000yqd.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <7zaaolzm89.fsf@ask.diku.dk> <89467860-45ac-4a3b-ac17-f11a19429187@i13g2000yqd.googlegroups.com> Message-ID: <4c6b8be3$0$1588$742ec2ed@news.sonic.net> On 8/17/2010 11:20 AM, Standish P wrote: > On Aug 17, 1:17 am, torb... at diku.dk (Torben ?gidius Mogensen) wrote: >> Standish P writes: >>> [Q] How far can stack [LIFO] solve do automatic garbage collection and >>> prevent memory leak ? >> >>> Because a stack has push and pop, it is able to release and allocate >>> memory. We envisage an exogenous stack which has malloc() associated >>> with a push and free() associated with a pop. >> >> See > > How many programmers have applied the ideas of these papers in their > programming practice ? I paste the abstract for convenience > >> http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 > > Abstract: > This paper describes a memory management discipline for programs that > perform dynamic memory allocation and de-allocation. At runtime, all > values are put into regions. The store consists of a stack of regions. > All points of region allocation and deallocation are inferred > automatically, using a type and effect based program analysis. The > scheme does not assume the presence of a garbage collector. That's actually an interesting idea. If you can figure out object lifetimes at compile time, allocation can be made far more efficient. One of the basic questions is whether a function will ever "keep" an object. That is, will the function ever keep a reference to an object that outlives the return from the function? In many cases, one can easily determine at compile time that a function will never keep a passed object. In such a case, you don't have to do reference count updates on the object. Most math functions have this property, even vector and matrix math functions - they have no persistent state. Python could use a bit of this. If a function argument can be identified as "non-kept", then the function doesn't need to do reference count updates on it. If a local variable in a function is used only by "non-keep" functions and operations, it can be created on the stack and released cheaply at block exit. One can go much further in lifetime inference than this, as the papers demonstrate. There's a big win in the simple optimization of identifying "non-keep" parameters, especially in mathematical work where they're very common. It's not clear that getting fancier than that is a win. Does Shed Skin have this optimization? It should. John Nagle From torbenm at diku.dk Wed Aug 18 03:39:12 2010 From: torbenm at diku.dk (Torben Ægidius Mogensen) Date: Wed, 18 Aug 2010 09:39:12 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <7zaaolzm89.fsf@ask.diku.dk> <89467860-45ac-4a3b-ac17-f11a19429187@i13g2000yqd.googlegroups.com> Message-ID: <7zk4noe5en.fsf@ask.diku.dk> Standish P writes: > On Aug 17, 1:17?am, torb... at diku.dk (Torben ?gidius Mogensen) wrote: >> Standish P writes: >> > [Q] How far can stack [LIFO] solve do automatic garbage collection and >> > prevent memory leak ? >> >> See > >> http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 >> http://portal.acm.org/citation.cfm?doid=174675.177855 >> http://www.springerlink.com/content/m2074884n6gt612h/ >> ? ? ? ? Torben > How many programmers have applied the ideas of these papers in their > programming practice ? The method was built into a SML compiler which was used (among other things) to build a web server, which was used (among other things) to make the web pages and course administrative system at the IT University of Copenhagen, Denmark. Good enough for you? Torben From sschwarzer at sschwarzer.net Wed Aug 18 03:44:14 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 18 Aug 2010 09:44:14 +0200 Subject: Call Java Code from python In-Reply-To: References: Message-ID: <4C6B8F4E.90503@sschwarzer.net> Hi Bidda, On 2010-08-18 09:19, Bidda Gowda wrote: > I have a project coming up where i have to integrate our existing > Python based web application with Java Programs. Basically i should be > able to call Java programs which comes in the form of jars. Whats the > best way to call these jars from python ? > > I looked at jpype and tried with small program and it works. Are there > any other tools which can do the same or if any how are they compared > to jpype ? Here are some slides from a talk by Andreas Schreiber, "Mixing Python and Java", which might help: http://www.slideshare.net/onyame/mixing-python-and-java Personally, I've used JCC for accessing Lucene (a search engine framework implemented in Java). It was a bit rough in some places, but overall quite usable. Stefan From andresen.nils at googlemail.com Wed Aug 18 04:09:38 2010 From: andresen.nils at googlemail.com (Nils) Date: Wed, 18 Aug 2010 01:09:38 -0700 (PDT) Subject: use of gtk in a nautilus extension Message-ID: <0408bd91-a578-400a-82ab-2329e129faef@j8g2000yqd.googlegroups.com> Hi, I am having some trouble opening a simple message/dialog to the user from a natilus extension.. I have written a simple nautilus extension using python. It adds one MenuItem to the context menu. for testing I wanted to open a simple dialog when the user clicks this menuitem. (The code can be found - with some nice formatting here: http://stackoverflow.com/questions/3325772/use-gtk-in-a-nautilus-extension-using-python) The code is as follows: --- cut --- import gtk import nautilus import os def alert(message): """A function to debug""" dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, message) dialog.run() dialog.destroy() class TestExtension(nautilus.MenuProvider): def __init__(self): pass def get_file_items(self, window, files): items = [] """Called when the user selects a file in Nautilus.""" item = nautilus.MenuItem("NautilusPython::test_item", "Test", "Test") item.connect("activate", self.menu_activate_cb, files) items.append(item) return items def menu_activate_cb(self, menu, files): """Called when the user selects the menu.""" for name in files: alert(name) --- cut --- When I click on the menuitem nothing happens... But when I replace def alert(message) like this: def alert(message): """A function to debug""" easygui.msgbox(message) and obviously drop import gtk and add import easygui, The dialog does appear. Can someone tell me why this is ?? Yours, Nils From ldo at geek-central.gen.new_zealand Wed Aug 18 04:16:33 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 18 Aug 2010 20:16:33 +1200 Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> Message-ID: In message , Martin Gregorie wrote: > 1) ssh terminal windows generally come up as 24 x 80 My terminal windows come up by default at something like 40 lines by 100 characters. > 2) at 24 x 80 I can get more ssh terminal windows on the desktop with > minimal overlap than I can do with longer/wider windows. I have 8 terminal windows open at once, they all fit fine, with room for an Emacs window and whatever else I might occasionally squeeze into there. Hint: I use tabs as well as windows. From nick_keighley_nospam at hotmail.com Wed Aug 18 04:39:09 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Wed, 18 Aug 2010 01:39:09 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> Message-ID: <518b97c6-78ad-4ce9-9967-c7f72ea74109@5g2000yqz.googlegroups.com> On 17 Aug, 18:34, Standish P wrote: > On Aug 16, 11:09?am, Elizabeth D Rather wrote: > > On 8/15/10 10:33 PM, Standish P wrote: > > > >>> If Forth is a general processing language based on stack, is it > > >>> possible to convert any and all algorithms to stack based ones and > > >>> thus avoid memory leaks since a pop automatically releases memory when > > >>> free is an intrinsic part of it. > > > Forth uses two stacks. ?The "data stack" is used for passing parameters > > between subroutines ("words") and is completely under the control of the > > programmer. ?Words expect parameters on this stack; they remove them, > > and leave only explicit results. ?The "return stack" is used primarily > > for return addresses when words are called, although it is also > > available for auxiliary uses under guidelines which respect the primary > > use for return addresses. > > > Although implementations vary, in most Forths stacks grow from a fixed > > point (one for each stack) into otherwise-unused memory. ?The space > > involved is allocated when the program is launched, and is not managed > > as a heap and allocated or deallocated by any complicated mechanism. ?On > > multitasking Forth systems, each task has its own stacks. ?Where > > floating point is implemented (Forth's native arithmetic is > > integer-based), there is usually a separate stack for floats, to take > > advantage of hardware FP stacks. > > > >> ? ? - is forth a general purpose language? Yes > > >> ? ? - are all algorithms stack based? No > > > > Does Forth uses stack for all algorithms ? Does it use pointers , ie > > > indirect addressing ? If it can/must use stack then every algorithm > > > could be made stack based. > > > Forth uses its data stack for parameter passing and storage of temporary > > values. ?It is also possible to define variables, strings, and arrays in > > memory, in which case their addresses may be passed on the data stack. > > > Forth is architecturally very simple. ?Memory allocations for variables, > > etc., are normally static, although some implementations include > > facilities for heaps as needed by applications. > > although some implementations include facilities for heaps as needed by applications. > > How are these heaps being implemented ? Is there some illustrative > code or a book showing how to implement these heaps in C for example ? any book of algorithms I'd have thought http://en.wikipedia.org/wiki/Dynamic_memory_allocation http://www.flounder.com/inside_storage_allocation.htm I've no idea how good either of these is > Are dictionaries of forth and postscript themselves stacks if we > consider them as nested two column tables which lisp's lists are in > essence, but only single row. Multiple rows would just be multiple > instances of it at the same level inside parens. I can't make much sense of that. But you seem to see Lisp data structures in all sorts of strange places. I don't see that Lisp lists are "nested two column tables" > we can peek into stacks which is like car. no. > if it is not unusually > costly computation, why not allow it ? there is no need to restrict to > push and pop. some stacks have a top() operation. > roll( stack_name, num) > > itself can give all those postfix permutations that push and pop cant > generate with a single stack. Can we use dictionaries to generate > multiple stacks inside one global stack ? I've no idea what you on about From landimatte at gmail.com Wed Aug 18 04:54:43 2010 From: landimatte at gmail.com (Matteo Landi) Date: Wed, 18 Aug 2010 10:54:43 +0200 Subject: Python Developer - HFT Trading firm - Chicago, IL In-Reply-To: References: Message-ID: Hi Rich, I think it's better for you to post the message here ( http://www.python.org/community/jobs/ ). Regards, On Tue, Aug 17, 2010 at 6:07 PM, Rich Moss wrote: > > Python developer needed for math/trading applications and research at > leading HFT firm. The person we are searching for will have a strong > background with python programming and the ability to work with very > large historical datasets. You should have a very strong math > background as well. This can involve writing very complicated python > scripts and programs! You will work very closely with traders and > quantitative analysts in their equities trading group on state-of-the- > art trading strategy and execution systems. > > Requires: > > Strong python programming experience developing applications and > scripts using complex regular expressions > > Strong math knowledge and education > Experience working with massive datatsets/historical data > > This company is a top-tier electronic, algorithmic trading firm, > located in Chicago, IL. This firm is one of the most advanced high > frequency electronic trading firms in the world and uses python > throughout the company, as well as other languages. This firm has a > culture that rewards creativity and hard work. No third parties, > please. We will not consider candidates from outside the USA. No > telecommuting. We offer very generous compensation (best in the > industry), fantastic benefits and very generous relocation packages. > Please contact me immediately with a resume! > > Send resumes to: > > Rich Moss > rich at mossltd.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From jeanmichel at sequans.com Wed Aug 18 04:57:00 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 18 Aug 2010 10:57:00 +0200 Subject: 79 chars or more? In-Reply-To: <20100817114256.d960549b.darcy@druid.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <20100817114256.d960549b.darcy@druid.net> Message-ID: <4C6BA05C.2000906@sequans.com> D'Arcy J.M. Cain wrote: > On Tue, 17 Aug 2010 16:28:02 +0200 > Stefan Schwarzer wrote: > >> I'd probably reformat this to >> >> self.expiration_date = translate_date( >> find(response, 'MPNExpirationDate').text, >> '%Y-%m-%d', '%m%d%Y') >> >> or even >> >> self.expiration_date = translate_date( >> find(response, 'MPNExpirationDate').text, >> '%Y-%m-%d', >> '%m%d%Y') >> > > You can extend this if there are complicated sub-calls. Probably > overkill for this example but here is the idea. > > self.expiration_date = translate_date( > find( > response, > 'MPNExpirationDate', > ).text, > '%Y-%m-%d', > '%m%d%Y' > ) > > I also moved the closing brace down to align with the line that opened > that block. > > If this is supposed to convice 80+ chars users, that's an epic failure :) This is exactly the kind of layout I'm happy to not use by not caring about the line width. At least, if you still want to stick with 79 chars, do something like text = find(response, 'MPNExpirationDate', ).text self.expiration_date = translate_date(text,'%Y-%m-%d', '%m%d%Y') JM From nick_keighley_nospam at hotmail.com Wed Aug 18 05:02:01 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Wed, 18 Aug 2010 02:02:01 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: <19ff939d-6cc0-4b27-b0a2-85406967434d@l6g2000yqb.googlegroups.com> On 17 Aug, 21:37, Elizabeth D Rather wrote: > On 8/17/10 10:19 AM, Standish P wrote > > On Aug 17, 12:32 pm, John Passaniti ?wrote: > >>> It is true that the other languages such as F/PS also have borrowed > >>> lists from lisp in the name of nested-dictionaries and mathematica > >>> calls them nested-tables as its fundamental data structure. > > >> No. > > > you are contradicting an earlier poster from forth who admitted the > > part on dicts. he's saying a forth dictionary isn't a lisp s-exp. Well it isn't. > Not at all. ?A Forth dictionary is a simple linked list, not the > complicated kind of nested structures you're referring to. ?You really > seem addicted to very complex structures. I thought he had the opposite problem! I thought it was trying to knock in all his programming nails with same stack-based hammer. > ?They really aren't necessary for general programming. whaever *that* is From nikos.the.gr33k at gmail.com Wed Aug 18 05:07:16 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Wed, 18 Aug 2010 12:07:16 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <20100818043122.GA27336@cskk.homeip.net> References: <3046f7fd-c4d3-4d40-a5ea-44407e724731@i31g2000yqm.googlegroups.com> <20100818043122.GA27336@cskk.homeip.net> Message-ID: <4C6BA2C4.4000309@gmail.com> ???? 18/8/2010 7:31 ??, ?/? Cameron Simpson ??????: > On 17Aug2010 20:15, ????? wrote: > | =============================== > | cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = > | '%s' ORDER BY date DESC ''' % (page) ) > | =============================== > | > | Someone told me NOT to do string substitution ("%") on SQL statements > | and to let MySQLdb do it > | for me, with proper escaping like the following > | > | =============================== > | cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s > | ORDER BY date DESC''', (page,)) > | =============================== > | > | The difference is that if some external source can control "page", > | and > | they put in a value like > | 100 ; DELETE FROM visitors; SELECT * FROM visitors > | i will be losing my database table data. > > That other difference is that the mysql dialect support knows how to > correctly escape a string for insertion into an SQL statement. You may > not, or may forget to pre-escape the string, etc. Using the MySQLdb > stuff do it for you is reliable and robust. Can you please tell me what escaping means by giving me an example of what is escaped and whats isn't? Also hwo can i delete my data for testing purposes as? http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors" I get an error... > | a) I wanted to ask what is proper escaping mean and why after variable > | page syntax has a comma > > Because this: > > (page) > > means the same thing as: > > page > > i.e. the argument to the "%" operator is just the string in page. > > This: > > (page,) > > is a _tuple_ containing a single element, the page variable. > A bit like: > > [page] > > which is a list containing a single element. The trailing comma is > needed to tell python you want to use a tuple, not the bare string. > > The "%" operator has special knowledge that is it is passed as string instead > of a list or tuple or other sequence then it should act _as_ _if_ it had been > passed a single element tuple containing the string. > %s and %d is behaving the same due to % expecting a string instead of an integer? > Otherwise, because a string _is_ a sequence the "%" might want to treat > the string "foo" as the sequence: > > ("f", "o", "o") cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s ORDER BY date DESC''', page) But it alss might treat it an entity, i mean since 'page' is a variable containing a string why not just 'page' as it is expecting 'page' variable to give its value when asked? > Run these three loops to see the difference: > > for s in "foo": > print s > for s in ("foo"): > print s > for s in ("foo",): > print s > > Cheers, >>> for s in "nikos": print s n i k o s # this handles the string "nikos" as a series of chars right? >>> for s in ("nikos"): print s n i k o s # this handles the string "nikos" as a series of chars too but what si the difference with the above in htis with the parentheses? is "nikos" is handles still as string here? >>> for s in ("nikos",): print s nikos # Here yes it handles "nikos" as the 1st item of a tuple nikos >>> for s in ["nikos"]: print s nikos # Here? why is it behaving fifferent than the above ("nikos") and is proccessign it all chars in one? >>> for s in ["nikos",]: print s nikos # Here it handles "nikos" as the 1st item of a list right? From sschwarzer at sschwarzer.net Wed Aug 18 05:11:09 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 18 Aug 2010 11:11:09 +0200 Subject: 79 chars or more? In-Reply-To: <4c6b956e@dnews.tpgi.com.au> References: <4C69F585.5050504@gmail.com> <4c6b956e@dnews.tpgi.com.au> Message-ID: <4C6BA3AD.3050500@sschwarzer.net> Hi Lie, On 2010-08-18 12:02, Lie Ryan wrote: > On 08/17/10 12:59, AK wrote: >> On 08/16/2010 10:42 PM, James Mills wrote: >>> My personal opinion (despite monitors being wider) is >>> the horizontal scrolling isn't worth it. Stick to a 80-char width. >> >> But.. why horizontal scrolling, isn't autowrap much better than that? > > Do you seriously use autowrapper when writing code? I think he means wrapping on the screen, not actually inserting line breaks. Stefan From as at sci.fi Wed Aug 18 05:40:07 2010 From: as at sci.fi (Anssi Saari) Date: Wed, 18 Aug 2010 12:40:07 +0300 Subject: Working with PDFs? References: Message-ID: writes: > - Pull out text from each PDF page (to search for specific words) > - Combine separate pdf documents into one document > - Add bookmarks (with destination settings) PDF Shuffler is a Python app which does PDF merging and splitting very well. I don't think it does anything else, though, but maybe that's where your code comes in? From cs at zip.com.au Wed Aug 18 05:50:17 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 18 Aug 2010 19:50:17 +1000 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6BA2C4.4000309@gmail.com> References: <4C6BA2C4.4000309@gmail.com> Message-ID: <20100818095017.GA30475@cskk.homeip.net> On 18Aug2010 12:07, Nik Gr wrote: | ???? 18/8/2010 7:31 ??, ?/? Cameron Simpson ??????: | >On 17Aug2010 20:15, ????? wrote: | >| =============================== | >| cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = | >| '%s' ORDER BY date DESC ''' % (page) ) | >| =============================== | >| | >| Someone told me NOT to do string substitution ("%") on SQL statements | >| and to let MySQLdb do it | >| for me, with proper escaping like the following | >| | >| =============================== | >| cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s | >| ORDER BY date DESC''', (page,)) | >| =============================== | >| | >| The difference is that if some external source can control "page", | >| and | >| they put in a value like | >| 100 ; DELETE FROM visitors; SELECT * FROM visitors | >| i will be losing my database table data. | > | >That other difference is that the mysql dialect support knows how to | >correctly escape a string for insertion into an SQL statement. You may | >not, or may forget to pre-escape the string, etc. Using the MySQLdb | >stuff do it for you is reliable and robust. | | Can you please tell me what escaping means by giving me an example | of what is escaped and whats isn't? In your plain substitution example above: cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) Supposing page is the string "100". This will produce the SQL statement: SELECT host, hits, date FROM visitors WHERE page = '100' ORDER BY date DESC which looks ok. But suppose page was the string: bill o'reilly Then your SQL statement looks like this: SELECT host, hits, date FROM visitors WHERE page = 'bill o'reilly' ORDER BY date DESC To the SQL engine this looks like the string "bill o" followed by an SQL instruction named "reilly", and then the opening quote for another string. Invalid SQL. The procedure used to avoid this problem (to insert an _arbitrary_ string into the SQL statement) is to "escape" problematic characters in strings when placing them into SQL statements. In this case, the quote character in the string is the SQL "end string" character. Therefore the string must be modified in the SQL statement to be correctly expressed. IIRC, SQL uses the quote doubling convention for strings, so this: SELECT host, hits, date FROM visitors WHERE page = 'bill o''reilly' ORDER BY date DESC is how one would write the literal SQL for that. The MySQLdb library will do this and a host of other equivalent things automatically and correctly and consistently when you pass page as a parameter to the execute() method, needing no special attention or detailed syntactic knowledge on your part when you write your program. [...snip...] | >The "%" operator has special knowledge that is it is passed as string instead | >of a list or tuple or other sequence then it should act _as_ _if_ it had been | >passed a single element tuple containing the string. | > | %s and %d is behaving the same due to % expecting a string instead | of an integer? I haven't checked. I make a point of using the (page,) form (i.e. always use a tuple, even with just one argument) these days. That way there is no ambiguity. | >Otherwise, because a string _is_ a sequence the "%" might want to treat | >the string "foo" as the sequence: | > | > ("f", "o", "o") | cursor.execute('''SELECT host, hits, date FROM visitors WHERE | page=%s ORDER BY date DESC''', page) | | But it alss might treat it an entity, i mean since 'page' is a | variable containing a string why not just 'page' as it is expecting | 'page' variable to give its value when asked? A string is also a sequence of characters. | >Run these three loops to see the difference: | > | > for s in "foo": | > print s | > for s in ("foo"): | > print s | > for s in ("foo",): | > print s | > | >Cheers, | >>> for s in "nikos": | print s | | | n | i | k | o | s | | # this handles the string "nikos" as a series of chars right? Yes. | >>> for s in ("nikos"): | print s | | | n | i | k | o | s | | # this handles the string "nikos" as a series of chars too but what | si the difference with the above in htis with the parentheses? is | "nikos" is handles still as string here? It is exactly the same as the first loop. Just as: 1 + 3 is exactly the same as: (1) + (3) | >>> for s in ("nikos",): | print s | | nikos | | # Here yes it handles "nikos" as the 1st item of a tuple Yep. | >>> for s in ["nikos"]: | print s | | nikos | | # Here? why is it behaving fifferent than the above ("nikos") and is | proccessign it all chars in one? ("nikos",) is a single element tuple. ["nikos"] is a single element list. ["nikos",] is also a single element list, just written like the tuple. You don't see the ["nikos",] form very often because ["nikos"] is not ambiguous. It is only because ("nikos") gets reduced to plain "nikos" just like the arithmetic above that you see the ("nikos",) form - the comma makes it a tuple. | >>> for s in ["nikos",]: | print s | | | nikos | | # Here it handles "nikos" as the 1st item of a list right? Yes. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Everything is gone; Your life's work has been destroyed. Squeeze trigger (yes/no)? - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From lie.1296 at gmail.com Wed Aug 18 06:02:40 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 18 Aug 2010 20:02:40 +1000 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> Message-ID: <4c6b956e@dnews.tpgi.com.au> On 08/17/10 12:59, AK wrote: > On 08/16/2010 10:42 PM, James Mills wrote: >> On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: >>> As monitors are getting bigger, is there a general change in opinion on >>> the 79 chars limit in source files? I've experimented with 98 characters >>> per line and I find it quite a bit more comfortable to work with that >>> length, even though sometimes I have to edit files in 80 width >>> terminals, it's still easier to adapt to some inconvenience when that >>> happens than the other way around, since about 95% of time or more, I do >>> use wider editor window or terminal. >>> >>> Is going over 79 still a terrible thing to do? -andrei >> >> My personal opinion (despite monitors being wider) is >> the horizontal scrolling isn't worth it. Stick to a 80-char width. > > But.. why horizontal scrolling, isn't autowrap much better than that? Do you seriously use autowrapper when writing code? From spinoza1111 at yahoo.com Wed Aug 18 06:09:14 2010 From: spinoza1111 at yahoo.com (spinoza1111) Date: Wed, 18 Aug 2010 03:09:14 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> On Aug 18, 1:21?am, Standish P wrote: > > Garbage collection doesn't use a stack. It uses a "heap", which is in > > the abstract a collection of memory blocks of different lengths, > > divided into two lists, generally represented as linked lists: > > > 1. ?A list of blocks that are free and may be used to store new data > > > 2. ?A list of blocks that are in use, or haven't been freed (yet) > > Is this all that a heap is or is there more to it ? I have been > looking for simple but complete explanation of heap for a while and > not gotten to it. I think I am looking for a stack allocation on the > same pattern. In a disk, a file is fragmented in many contiguous > blocks and is accessed automatically. > > > > > > > There is no way you could do memory management of all but the most > > trivial and fixed-length data chunks using a stack. Sure, you could > > reserve thousands of bytes on the stack for an array but suppose your > > language allows arrays to grow or shrink. To keep its property of > > being adjacent, you'd have to do something horrible such as move > > unrelated data allocated later, which raises all sorts of security > > issues, doesn't it. > > A stack, or something which works like a stack (that is, a stack) is a > > necessary but not sufficient condition for a working C runtime because > > C functions can call themselves recursively, whether directly or > > indirectly. If this last condition did not obtain, each function could > > give the functions it calls some of its own memory and the called > > function could save a fixed set of non-stacked general registers in > > that area; this was in fact the practice on IBM 370 and in assembler > > language at a time when many "data processing managers" though > > recursion was a Communist plot. > > > However, data structures of variable size, or data structures that > > merely take up a lot of space, don't play nice with others on the > > stack, so, we place their address on the stack and store them in > > another place, which was named the heap, probably, as a sort of > > witticism. > > > Gilbert and Sullivan: > > > If anyone anything lacks > > He'll find it all ready in stacks > > This you might want to take this to the Forth people because they are > marketing their language as a cure for all that plagues programming > today. No, they're not. Stack based languages have seen better days and Forth (and the SL/1 language I supported with compilers at Bell-Northern Research) were last in fashion in the 1970s. Processors seldom could multitask, so it wasn't recognized that the stack could be a performance bottleneck, where stack operations cannot be pipelined or executed in parallel. John Hennessy of Stanford and MIPS made the stack must die case at ACM ASPLOS in 1987. Niklaus Wirth was also at this conference at which I was a fly on the wall, maintaining that the stack was good for reliability and verifiability of software. Forth had a snowball's chance because it forces ordinary programmers to think in Reverse Polish notation and is for the above reasons hard to pipeline, although of course it can be pipelined. > > > > > was wrong, and needs to be brought up to date: > > > You cannot do everything in a stack > > Unless you code an almighty hack > > If you're a coding Knight who says, "Neep", > > You'll probably need to implement a heap > > A pile a heap of benefits you'll reap > > If only my advice in your brain you'll keep > > And avoid memory leaks from which data doth seep > > By using a well-implemented, well structured, and well-documented > > Heap! > > > [Chorus of Sailors] > > We will to heart your advice take, and always use a heap! > > > [Soloist] > > Oh thank you do > > To this be true > > And always my sage advice do keep > > That you always need to use a heap!- Hide quoted text - > > > - Show quoted text - From bartc at freeuk.com Wed Aug 18 06:38:11 2010 From: bartc at freeuk.com (BartC) Date: Wed, 18 Aug 2010 11:38:11 +0100 Subject: 79 chars or more? In-Reply-To: References: Message-ID: "Roy Smith" wrote in message news:roy-319E47.09055017082010 at news.panix.com... > In article , > Lawrence D'Oliveiro wrote: > >> In message , AK >> wrote: >> >> > As monitors are getting bigger, is there a general change in opinion on >> > the 79 chars limit in source files? >> >> WHAT 79-character limit in source files? >> >> I currently have my Emacs windows set at 100 characters wide, and I??Tm >> thinking of going wider. >> >> Remember, the old hardcopy terminals used to produce 132-character-wide >> listings. > > Those of you who think "old hardcopy terminals" did 132 wide obviously > don't remember the ASR-33 :-) ASR33s I think might have been 72 columns wide (and punched cards had a similar restriction). However, lineprinter output was more likely to be 132 columns. -- bartc From python.list at tim.thechases.com Wed Aug 18 06:45:37 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 18 Aug 2010 05:45:37 -0500 Subject: String substitution VS proper mysql escaping In-Reply-To: <20100818095017.GA30475@cskk.homeip.net> References: <4C6BA2C4.4000309@gmail.com> <20100818095017.GA30475@cskk.homeip.net> Message-ID: <4C6BB9D1.8070806@tim.thechases.com> On 08/18/10 04:50, Cameron Simpson wrote: > ("nikos",) is a single element tuple. > ["nikos"] is a single element list. > ["nikos",] is also a single element list, just written like the tuple. > > You don't see the ["nikos",] form very often because ["nikos"] is not > ambiguous. I most frequently see/use the trailing comma in a one-item list when I expect additional items will be accrued later, so it makes my version-control diffs tidier: items = [ "nikos", ] Then a month later, I add items = [ "nikos", "cameron", ] My diff is just items = [ "nikos", + "cameron", ] which is quite easy to understand. However if my original was items = [ "nikos" ] and I later want to make it items = [ "nikos", "cameron" ] the diff then becomes items = [ - "nikos" + "nikos", + "cameron" ] which isn't nearly as easy to read & understand because I now have to notice the inter-linear differences ("did something more than the new-comma happen?"). -tkc From ldo at geek-central.gen.new_zealand Wed Aug 18 07:18:06 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 18 Aug 2010 23:18:06 +1200 Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: In message <4C6A9C72.4040708 at sschwarzer.net>, Stefan Schwarzer wrote: > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') Might I suggest (guessing at the argument keywords here) : self.expiration_date = translate_date \ ( TheText = find(response, 'MPNExpirationDate').text, ToFormat ='%Y-%m-%d', FromFormat ='%m%d%Y' ) Presumably FromFormat should be localizable, rather than hard-coded. See, that?s the kind of thing you notice when you think about the code in this way. From news1234 at free.fr Wed Aug 18 07:20:49 2010 From: news1234 at free.fr (News123) Date: Wed, 18 Aug 2010 13:20:49 +0200 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: <4c6bc211$0$9876$426a34cc@news.free.fr> On 08/17/2010 11:44 PM, Baba wrote: > On Aug 16, 6:28 pm, "cbr... at cbrownsystems.com" > wrote: > >> First, suppose d = gcd(x, y, z); then for some x', y', z' we have that >> x = d*x', y = d*y', z = d*z'; and so for any a, b, c: >> > > > could you explain the notation? > > what is the difference btw x and x' ? > > what is x = d*x', y supposed to say? > > gcd(x,y,z) determines the greates number by which all three numbers can be devided. 2,4,6 for example are all divided by 2 thus d=2 now you dived x,y,z by d and call them x' , y' , z' The point is if x,y,z have a gcd grater than one, then you know for sure, that you will never be able to find the a finit greates amount, which cannot be bought if xmymz are all divisible by d, then any combination will also be dividible by d thas any number not dividible by d ( for d > 1) for example n*d + 1 can not be bought From paulo.jpinto at gmail.com Wed Aug 18 07:54:44 2010 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: Wed, 18 Aug 2010 04:54:44 -0700 (PDT) Subject: Python 2.7 support for PyWin32 Message-ID: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Hi everyone, does anyone know when PyWin is going to support Python 2.7? I tried to look for information, but to no avail. Thanks in advance, Paulo From roy at panix.com Wed Aug 18 07:57:18 2010 From: roy at panix.com (Roy Smith) Date: Wed, 18 Aug 2010 07:57:18 -0400 Subject: 79 chars or more? References: Message-ID: In article , "BartC" wrote: > >> Remember, the old hardcopy terminals used to produce 132-character-wide > >> listings. > > > > Those of you who think "old hardcopy terminals" did 132 wide obviously > > don't remember the ASR-33 :-) > > ASR33s I think might have been 72 columns wide (and punched cards had a > similar restriction). Yeah, I was trying to remember if it was 72 or 80. Hmmm, looks like you're right, it *is* 72 (http://www.pdp8.net/asr33/asr33.shtml). Punched cards (at least the common ones used by an 029 or 129 punch machine) were 80 columns. The 72 column restriction was an artificial one imposed by some programming languages such as Fortran. Columns 73-80 could be used to punch a sequence number, so that if you dropped your deck, you could re-assemble it by running it through a card sorter. > However, lineprinter output was more likely to be 132 columns. Yeah, but I wouldn't call a line printer a "terminal". From roy at panix.com Wed Aug 18 08:00:24 2010 From: roy at panix.com (Roy Smith) Date: Wed, 18 Aug 2010 08:00:24 -0400 Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4c6b956e@dnews.tpgi.com.au> Message-ID: In article <4c6b956e at dnews.tpgi.com.au>, Lie Ryan wrote: > On 08/17/10 12:59, AK wrote: > > On 08/16/2010 10:42 PM, James Mills wrote: > >> On Tue, Aug 17, 2010 at 12:35 PM, AK wrote: > >>> As monitors are getting bigger, is there a general change in opinion on > >>> the 79 chars limit in source files? I've experimented with 98 characters > >>> per line and I find it quite a bit more comfortable to work with that > >>> length, even though sometimes I have to edit files in 80 width > >>> terminals, it's still easier to adapt to some inconvenience when that > >>> happens than the other way around, since about 95% of time or more, I do > >>> use wider editor window or terminal. > >>> > >>> Is going over 79 still a terrible thing to do? -andrei > >> > >> My personal opinion (despite monitors being wider) is > >> the horizontal scrolling isn't worth it. Stick to a 80-char width. > > > > But.. why horizontal scrolling, isn't autowrap much better than that? > > > Do you seriously use autowrapper when writing code? I absolutely use auto-indent, parenthesis matching, and syntax coloring. >From time to time, I turn on auto-wrap, but generally find it more annoying than useful and turn it back off again. From breamoreboy at yahoo.co.uk Wed Aug 18 08:33:32 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 18 Aug 2010 13:33:32 +0100 Subject: Python 2.7 support for PyWin32 In-Reply-To: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> References: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Message-ID: On 18/08/2010 12:54, paulo.jpinto at gmail.com wrote: > Hi everyone, > > does anyone know when PyWin is going to support Python 2.7? > > I tried to look for information, but to no avail. > > Thanks in advance, > Paulo It was created on 2009-07-08!!! See:- http://sourceforge.net/projects/pywin32/files/pywin32/ Cheers. Mark Lawrence. From bauketilma at gmail.com Wed Aug 18 08:56:27 2010 From: bauketilma at gmail.com (Duim) Date: Wed, 18 Aug 2010 05:56:27 -0700 (PDT) Subject: when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray' Message-ID: Although I'm sure somewhere this issue is discussed in this (great) group, I didn't know the proper search words for it (although I tried). I'm using python (2.6) scientifically mostly, and created a simple class to store time series (my 'Signal' class). I need this class to have a possibility to get multiplied by an array, but pre and post multiplication have different mathematical outcomes ( basically A* B != B*A ) . Post multiplication by an array works fine defining __mul__ in the Signal class, but pre multiplication does not. It keeps trying to multiply all elements separately instead to send this array to my __rmul__ function. How can I fix this without the need for a separate 'multiplysignal(A,B)' function? To make things easy I've made a small example: [code] import numpy as np class Signal(object): def __init__(self,data,dt): self.data=data self.dt=dt def Nch(self): return self.data.shape[0] def __mul__(self,other): print 'mul called! ',other if isinstance(other,type(np.array([1,2]))): #it's an array: use dot product: return Signal(np.dot(self.data,other),self.dt) if other.__class__.__name__=='Signal': # do something pass def __rmul__(self,other): print 'rmul called! ',other if isinstance(other,type(np.array([1,2]))): #it's an array: use dot product: return Signal(np.dot(other,self.data),self.dt) if other.__class__.__name__=='Signal': # do something pass mySignal=Signal(np.array([[1.,2],[4,5]]),1.) myArray=np.array([[1.,2.],[4.,3.]]) result_mul = mySignal*myArray result_rmul = myArray*mySignal #called 4 times for all members once! #result: #mul called! [[ 1. 2.] # [ 4. 3.]] #rmul called! 1.0 #rmul called! 2.0 #rmul called! 4.0 #rmul called! 3.0 [/code] From morfeokmg at gmail.com Wed Aug 18 09:12:40 2010 From: morfeokmg at gmail.com (Mauricio Martinez Garcia) Date: Wed, 18 Aug 2010 08:12:40 -0500 Subject: error Compile libxml2 from python 2.6.4 Message-ID: <4C6BDC48.6030806@gmail.com> Hi!. Have the next error on install libxml2. python/bin/python setup.py install failed to find headers for libxml2: update includes_dir This my version of python ==> /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python/bin/python Python 2.6.5 (r265:79063, Jul 21 2010, 13:05:40) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. I'm Installing libxml2 for python 2.6.5, and this error break the install. The python path prefix is /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python, and i don't privileges of root. The configuration to be personalized, in prefix path. My compile line is: ./configure --with-python=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python \ --prefix=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml \ --with-libxml-include-prefix=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/pythonPruebas/libxml2/libxml2-INC/usr/local/include/libxml2/libxml This is the output when finalize compiling this is message: Enabled Schemas/Relax-NG support configure: creating ./config.status config.status: creating libxml2.spec config.status: creating Makefile config.status: creating include/Makefile config.status: creating include/libxml/Makefile config.status: creating doc/Makefile config.status: creating doc/examples/Makefile config.status: creating example/Makefile config.status: creating python/Makefile config.status: creating python/tests/Makefile config.status: creating include/libxml/xmlversion.h config.status: creating xml2-config config.status: creating libxml-2.0.pc config.status: creating libxml-2.0-uninstalled.pc config.status: creating xml2Conf.sh config.status: creating python/setup.py config.status: creating config.h config.status: config.h is unchanged config.status: executing depfiles commands And this is output of make install: Libraries have been installed in: /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python/lib/python2.6/site-packages If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the `-LLIBDIR' flag during linking and do at least one of the following: - add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution - use the `-LLIBDIR' linker flag See any operating system documentation about shared libraries for more information, such as the ld(1) and ld.so(8) manual pages. Making install in tests No suffix list. No suffix list. /bin/sh ../../mkinstalldirs /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples mkdir -p -- /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples (for test in build.py attribs.py tst.py tstxpath.py xpathext.py push.py pushSAX.py pushSAXhtml.py error.py serialize.py validate.py tstURI.py cutnpaste.py xpathret.py xpath.py outbuf.py inbuf.py resolver.py regexp.py reader.py reader2.py reader3.py reader4.py reader5.py reader6.py reader7.py walker.py ctxterror.py readererr.py relaxng.py thread2.py tst.xml valid.xml invalid.xml; \ do ../.././install-sh -c -m 0644 ./$test /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples ; done) This an issue?, or bug? Greetings. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bartc at freeuk.com Wed Aug 18 09:34:22 2010 From: bartc at freeuk.com (BartC) Date: Wed, 18 Aug 2010 14:34:22 +0100 Subject: 79 chars or more? In-Reply-To: References: Message-ID: "Roy Smith" wrote in message news:roy-181632.07571818082010 at news.panix.com... > In article , > "BartC" wrote: > >> >> Remember, the old hardcopy terminals used to produce >> >> 132-character-wide >> >> listings. >> > >> > Those of you who think "old hardcopy terminals" did 132 wide obviously >> > don't remember the ASR-33 :-) >> >> ASR33s I think might have been 72 columns wide (and punched cards had a >> similar restriction). > > Yeah, I was trying to remember if it was 72 or 80. Hmmm, looks like > you're right, it *is* 72 (http://www.pdp8.net/asr33/asr33.shtml). > > Punched cards (at least the common ones used by an 029 or 129 punch > machine) were 80 columns. The 72 column restriction was an artificial > one imposed by some programming languages such as Fortran. Columns > 73-80 could be used to punch a sequence number, so that if you dropped > your deck, you could re-assemble it by running it through a card sorter. I'm sure there was a continuation column too. That would mean long lines had to be split up, but if the width was longer, that would not be necessary. >> However, lineprinter output was more likely to be 132 columns. > > Yeah, but I wouldn't call a line printer a "terminal". Source code tended to be perused and marked up on a printout, then corrected at a terminal. So the terminal's width was less important, until fast VDUs came in then printouts were used less, and it made sense to adjust to common 25x80 displays. (I tend to use 60x100 now, sometimes even wider; editing using 25x80 now is like doing keyhole surgery...) -- bartc From ringemup at gmail.com Wed Aug 18 09:58:27 2010 From: ringemup at gmail.com (Nan) Date: Wed, 18 Aug 2010 06:58:27 -0700 (PDT) Subject: subprocess.Popen calling httpd reload never finishes References: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Message-ID: On Aug 17, 8:14?pm, Albert Hopkins wrote: > On Tue, 2010-08-17 at 12:55 -0700, Nan wrote: > > Hi folks -- > > > I have a Python script running under Apache/mod_wsgi that needs to > > reload Apache configs as part of its operation. ?The script continues > > to execute after the subprocess.Popen call. ?The communicate() method > > returns the correct text ("Reloading httpd: [ ?OK ?]"), and I get a > > returncode of 0. ?But the python script (Django) that calls Popen > > never seems to complete (by returning an HTTP response. > > > Any other Popen call I've tried exits properly. ?Here's some sample > > code: > > > ? ? ? ? ? ?args = ['sudo /etc/init.d/httpd reload'] > > ? ? ? ? ? ?proc = subprocess.Popen(args, stdin=subprocess.PIPE, > > stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, > > close_fds=True) > > ? ? ? ? ? ?(stdout_txt, stderr_txt) = proc.communicate("") > > ? ? ? ? ? ?proc.wait() > > ? ? ? ? ? ?logging.debug('%d %s
%s' % (proc.returncode, stdout_txt, > > stderr_txt)) > > ? ? ? ? ? ?logging.debug('still executing') > > ? ? ? ? ? ?return HttpResponse('done') > > > The logging statements are output, but the script doesn't exit. ?If > > you substitute "sudo ls -l" or "sudo /etc/init.d/httpd configtest" for > > "sudo /etc/init.d/httpd reload", the exits properly. > > > ?Any idea what I might be doing wrong? > > > Thanks! > > Django runs inside apache. ?It's kinda weird to have an apache process > restart itself and expect it to return to the caller. > > If the init script does like mine, "reload" executes "apachectl -k > graceful" ? What that instructs apache to do is to restart, but only > kill the process(es) when there are no more connections. ?So apache is > waiting for your connection to close, but you are inside an HTTP request > waiting for apache to restart. ?So you have a race condition here. > > It's not advisable to have apache kill itself and expect it to send a > status back to you telling you it's dead. > > See the apache docs[1] for a better explanation. > > http://httpd.apache.org/docs/2.0/stopping.html#graceful Ah, I'd been told that there would be no conflict, and that this was just reloading the configuration, not restarting Apache. I do need the web app to instruct Apache to reload because just before this it's creating new VirtualHosts that need to be recognized. Is there a better way to do this (e.g. to say "start doing this once I'm finished")? I'm getting a status code and output from the call before the Django script stops executing... Is there a way to stop waiting for the process to complete once I have those? From andrei.avk at gmail.com Wed Aug 18 10:01:15 2010 From: andrei.avk at gmail.com (AK) Date: Wed, 18 Aug 2010 10:01:15 -0400 Subject: 79 chars or more? In-Reply-To: <4C6BA3AD.3050500@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4c6b956e@dnews.tpgi.com.au> <4C6BA3AD.3050500@sschwarzer.net> Message-ID: <4C6BE7AB.5070105@gmail.com> On 08/18/2010 05:11 AM, Stefan Schwarzer wrote: > Hi Lie, > > On 2010-08-18 12:02, Lie Ryan wrote: >> On 08/17/10 12:59, AK wrote: >>> On 08/16/2010 10:42 PM, James Mills wrote: >>>> My personal opinion (despite monitors being wider) is >>>> the horizontal scrolling isn't worth it. Stick to a 80-char width. >>> >>> But.. why horizontal scrolling, isn't autowrap much better than that? >> >> Do you seriously use autowrapper when writing code? > > I think he means wrapping on the screen, not actually > inserting line breaks. > > Stefan Yes, exactly (:set wrap in Vim). -andrei From anthra.norell at bluewin.ch Wed Aug 18 10:03:58 2010 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Wed, 18 Aug 2010 16:03:58 +0200 Subject: Simple Problem but tough for me if i want it in linear time In-Reply-To: <4c69c715$0$11100$c3e8da3@news.astraweb.com> References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> <4c69c715$0$11100$c3e8da3@news.astraweb.com> Message-ID: <1282140238.2398.99.camel@hatchbox-one> On Mon, 2010-08-16 at 23:17 +0000, Steven D'Aprano wrote: > On Mon, 16 Aug 2010 20:40:52 +0200, Frederic Rentsch wrote: > > > How about > > > >>>> [obj for obj in dataList if obj.number == 100] > > > > That should create a list of all objects whose .number is 100. No need > > to cycle through a loop. > > What do you think the list comprehension does, if not cycle through a > loop? > > > -- > Steven What I think is that list comprehensions cycle through a loop a lot faster than a coded loop (for n in ...:). As at the time of my post only coded loops had been proposed and the OP was concerned about speed, I thought I'd propose a list comprehension. I guess my explanation was poorly phrased. Thanks for the reminder. Frederic From mail at timgolden.me.uk Wed Aug 18 10:28:15 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 18 Aug 2010 15:28:15 +0100 Subject: Python 2.7 support for PyWin32 In-Reply-To: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> References: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Message-ID: <4C6BEDFF.5060403@timgolden.me.uk> On 18/08/2010 12:54, paulo.jpinto at gmail.com wrote: > Hi everyone, > > does anyone know when PyWin is going to support Python 2.7? > > I tried to look for information, but to no avail. > > Thanks in advance, > Paulo It already does and has done for a while: http://sourceforge.net/projects/pywin32/files/ TJG From darcy at druid.net Wed Aug 18 10:38:24 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 18 Aug 2010 10:38:24 -0400 Subject: 79 chars or more? In-Reply-To: References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <20100818103824.3a2796ae.darcy@druid.net> On Wed, 18 Aug 2010 23:18:06 +1200 Lawrence D'Oliveiro wrote: > Might I suggest (guessing at the argument keywords here) : > > self.expiration_date = translate_date \ > ( > TheText = find(response, 'MPNExpirationDate').text, > ToFormat ='%Y-%m-%d', > FromFormat ='%m%d%Y' > ) I sometimes use a backslash continuation but it always feels like a failure to me. It's an irrational reaction and I'm not sure why I feel like that. However, if you are going to do it in order to line up the parenthese I would prefer this style. self.expiration_date = translate_date \ ( TheText = find(response, 'MPNExpirationDate').text, ToFormat ='%Y-%m-%d', FromFormat ='%m%d%Y' ) This way you can see not only the block structure at a glance but also the block starter that it is part of. > > Presumably FromFormat should be localizable, rather than hard-coded. > > See, that?s the kind of thing you notice when you think about the code in > this way. The other thing that jumps out at me is having the input format different than the output format. In any case you need a better date input function. There's no reason in this day and age to force users into a particular input form. You should think about creating a utility function that converts any date that is unambiguous. My scripts generally accept all of the following. Sep 1 2010 september 1, 2010 2010-9-1 (I have never seen "Y/D/M" format) 2010/9/1 2010 9 1 12/25/2010 25/12/2010 2010/12/25 It fails on the following. sep 31 2010 (impossible) 2010/25/12 (impossible - Y/D/M never happens) 9/1/2010 (ambiguous - there is no consistiency when year is last field) foo (not a date) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Wed Aug 18 10:49:51 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 18 Aug 2010 10:49:51 -0400 Subject: 79 chars or more? In-Reply-To: <4C6BA05C.2000906@sequans.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <20100817114256.d960549b.darcy@druid.net> <4C6BA05C.2000906@sequans.com> Message-ID: <20100818104951.506a0d2b.darcy@druid.net> On Wed, 18 Aug 2010 10:57:00 +0200 Jean-Michel Pichavant wrote: > D'Arcy J.M. Cain wrote: > > You can extend this if there are complicated sub-calls. Probably > > overkill for this example but here is the idea. > > > > self.expiration_date = translate_date( > > find( > > response, > > 'MPNExpirationDate', > > ).text, > > '%Y-%m-%d', > > '%m%d%Y' > > ) > > > > I also moved the closing brace down to align with the line that opened > > that block. > > > If this is supposed to convice 80+ chars users, that's an epic failure :) > This is exactly the kind of layout I'm happy to not use by not caring > about the line width. As I said above, this was overkill designed to show the idea. Of course I would never split up short calls like that in real code. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From peterwfh2000 at gmail.com Wed Aug 18 11:04:54 2010 From: peterwfh2000 at gmail.com (PETER WONG F H (+971 50 8320722)) Date: Wed, 18 Aug 2010 08:04:54 -0700 (PDT) Subject: Required Buy Palm Jumeirah aprt AND Springs villa, 050-8320722 Message-ID: Dear I have a client who is looking to buy apartment and Villa : 1. the palm jumeirah 3 bed + maid room sea view only (any building) 2. springs type 3E 3. springs type 3M 4. springs type 4E Please send me your direct availabilities, or call me, viewing tomorrow, thank you! Peter Wong F.H ??? (????RERA BRN: 8866) Mob ?? : +971 50 83 20 722 Fax ?? : +971 4 32 30 895 E-mail ?? : peterwfh2000 at gmail.com Company ?? : Pinky Real Estate Broker????? (????RERA ORN: 1866) Website : http://groups.google.com/group/dubai-property-club From paulo.jpinto at gmail.com Wed Aug 18 11:14:20 2010 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: Wed, 18 Aug 2010 08:14:20 -0700 (PDT) Subject: Python 2.7 support for PyWin32 References: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Message-ID: Thanks for the heads up. My error was to only look for the green download button. There you still get 2.6 as default download. -- Paulo On Aug 18, 4:28?pm, Tim Golden wrote: > On 18/08/2010 12:54, paulo.jpi... at gmail.com wrote: > > > Hi everyone, > > > does anyone know when PyWin is going to support Python 2.7? > > > I tried to look for information, but to no avail. > > > Thanks in advance, > > Paulo > > It already does and has done for a while: > > ? ?http://sourceforge.net/projects/pywin32/files/ > > TJG From marduk at letterboxes.org Wed Aug 18 12:37:22 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 18 Aug 2010 12:37:22 -0400 Subject: subprocess.Popen calling httpd reload never finishes In-Reply-To: References: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Message-ID: <1282149442.216434.19.camel@paska> On Wed, 2010-08-18 at 06:58 -0700, Nan wrote: > Ah, I'd been told that there would be no conflict, and that this was > just reloading the configuration, not restarting Apache. > > I do need the web app to instruct Apache to reload because just before > this it's creating new VirtualHosts that need to be recognized. Is > there a better way to do this (e.g. to say "start doing this once I'm > finished")? > > I'm getting a status code and output from the call before the Django > script stops executing... Is there a way to stop waiting for the > process to complete once I have those? I have a wireless router with a built in web server. Sometimes it needs to "reload" it's config. Basically what it's doing is rebooting the entire router (I can see this if I'm actuall watching the router). All it is doing, I'm pretty sure, is calling some program that forks another process and then exits the main program. The forked process then reboots the router. Meanwhile before that happens the web server sends a response. Basically in the response it sends an HTTP Refresh with x number of seconds. Presumably x is longer than the time it requires for the router to reboot. The router reboots, the browser refreshes and viola. You probably need to so something similar in that your request calls a program that forks off and restarts apaches. It should probably not do so immediately so that your request has time to send a response with a refresh header (but that shouldn't take long). After a second or so, apache will have restarted and the browser will have refreshed. so (untested): def reload(request): subprocess.call(['my_apache_reloader']) # this should fork and exit response = HttpResponse() response['Refresh']='3; url=%s' % reverse(home) # chk back in 3 secs return response BTW There is a Django mailing list where this might be more appropriate to discuss. -a From randrange at gmail.com Wed Aug 18 12:49:53 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 09:49:53 -0700 Subject: Problem Creating NewLines in PDF Message-ID: Hello I am generating a PDF in web2py but its ignoring my line breaks. randname = random.randrange(1, 10001) styles = getSampleStyleSheet() title = "My Title" doc = SimpleDocTemplate("primer.pdf") story = [] story.append(Paragraph(strftime("%a, %d %b %Y %H:%M:%S", gmtime()),styles["Heading2"])) para = ParagraphStyle(name="output", fontName='Helvetica', fontSize=12) story.append(Paragraph(str(result_list), para)) doc.build(story) response.headers['Content-Type']='application/pdf' response.headers['Content-Disposition'] = 'attachment;filename='+str(randname)+'-.pdf' return response.stream(open("primer.pdf", 'rb')) result_list is a generated list. The pdf ignores line breaks and outputs it as a list so [' '] are included also. Any idea how I can create line breaks and get rid of the [' '] *cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Aug 18 13:10:23 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 18:10:23 +0100 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: <4C6C13FF.2050807@mrabarnett.plus.com> Andrew Evans wrote: > Hello I am generating a PDF in web2py but its ignoring my line breaks. > > randname = random.randrange(1, 10001) > styles = getSampleStyleSheet() > title = "My Title" > doc = SimpleDocTemplate("primer.pdf") > story = [] > story.append(Paragraph(strftime("%a, %d %b %Y %H:%M:%S", > gmtime()),styles["Heading2"])) > para = ParagraphStyle(name="output", fontName='Helvetica', > fontSize=12) > story.append(Paragraph(str(result_list), para)) str(result_list) is converting the list into a string. Did you mean to do that? > doc.build(story) > response.headers['Content-Type']='application/pdf' > response.headers['Content-Disposition'] = > 'attachment;filename='+str(randname)+'-.pdf' > return response.stream(open("primer.pdf", 'rb')) > > > result_list is a generated list. The pdf ignores line breaks and outputs > it as a list so [' '] are included also. Any idea how I can create line > breaks and get rid of the [' '] > From brandon.harris at reelfx.com Wed Aug 18 13:37:11 2010 From: brandon.harris at reelfx.com (Brandon Harris) Date: Wed, 18 Aug 2010 12:37:11 -0500 Subject: Using re.sub with %s In-Reply-To: References: Message-ID: <4C6C1A47.9020907@reelfx.com> Having trouble using %s with re.sub test = '/my/word/whats/wrong' re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) return is /my/@0/whats/wrong however if I cast a value with letters as opposed to numbers re.sub('(/)word(/)', r'\1\%s\2'%'gosh', test) return is /my/gosh/whats/wrong Any help would be good. I've tried passing the value as an int, or recasting that value as something else, passing it as a raw string, removing the r and just double escaping the groups. Brandon L. Harris From neilc at norwich.edu Wed Aug 18 13:37:45 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 18 Aug 2010 17:37:45 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <8d2k39Fuv2U2@mid.individual.net> On 2010-08-18, D'Arcy J.M. Cain wrote: > The other thing that jumps out at me is having the input format > different than the output format. In any case you need a > better date input function. There's no reason in this day and > age to force users into a particular input form. You should > think about creating a utility function that converts any date > that is unambiguous. My scripts generally accept all of the > following. Under the hood, translate_date just use strptime and strftime, so the formats are whatever those functions support. Moreover, I'm converting one known format (the one in the XML) to another required format (the one required by another program). There's no need to guess the format. -- Neil Cerutti From cbrown at cbrownsystems.com Wed Aug 18 13:38:11 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Wed, 18 Aug 2010 10:38:11 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: On Aug 17, 2:44?pm, Baba wrote: > On Aug 16, 6:28?pm, "cbr... at cbrownsystems.com" > > wrote: > > First, suppose d = gcd(x, y, z); then for some x', y', z' we have that > > x = d*x', y = d*y', z = d*z'; and so for any a, b, c: > > ? ?could you explain the notation? > > ? ?what is the difference btw x and x' ? > > ? ?what is x = d*x', y supposed to say? x', y', z' are names for three natural numbers; I could have chosen r, s, t. "x=d*x'" above simply notes that since x is divisible by d, it can be written as the product of d and some other natural number, and the same is true for both y and z. therefore sums of multiples of x, y and z are always divisible by d. > > > To go the other way, if d = 1, then there exists integers (not > > neccessarily positive) such that > > > a*x + b*y + c*z = 1 > > ? ?what's the link with 6*a+9*b+20*c=n except the similarity? > The link is that it shows that if we have some u, v, and w with 6*u + 9*v + 20*w = n, and we can find some a, b, and c which satisfy 6*a + 9*b + 20*c = 1 then if we let r = u + a, s = v + b, and t = w + c, we get that 6*r + 9*s + 20*t = n+1 although r, s, and t are not neccessarily positive numbers (as they must be to solve your original problem). However, if u, v, and w are sufficiently large compared to a, b, and c, then r, s and t WILL all be positive. But we can only find such an a,b, and c because the gcd of 6, 9, and 20 is equal to 1; that is why you can't solve this problem for nugget pack sizes 6, 12, and 21. Note that if there is one solution (a,b,c) to the gcd equation, there infinitely many tuples (a,b,c) which satisfy the gcd equation, for example: 6*0 + 9*9 + 20*(-4) = 1 6*(-5) + 9*(-1) + 20*2 = 1 6*2 + 9*1 + 20*(-1) = 1 So the proof I gave regarded the /existence/ of a largest unobtainable, not an algorithm for obtaining one. However from the last of those three examples, we can see (details are in my original proof) that the largest unobtainable must be less than 6*0 + 9*0 + 20*(1*5) = 100 so it is potentially helpful for finding an upper bound to the problem. > furthermore i came across this: > > For k = 3, efficient algorithms > have been given by Greenberg and Davison ; if x1 < x2 < x3, these > algorithms run in > time bounded by a polynomial in log x3. Kannan ?gave a very > complicated algorithm > that runs in polynomial time in log xk if k is fixed, but is wildly > exponential in k. However, > Ram??rez Alfons??n proved that the general problem is NP-hard, under > Turing reductions, > by reducing from the integer knapsack problem. So it seems very likely > that there is no > simple formula for computing g(x1, x2, . . . , xk) for arbitrary k. > > source:http://arxiv.org/PS_cache/arxiv/pdf/0708/0708.3224v1.pdf > > i would be interested in the answer to problem 3: explain in English > why the theorem is true > I haven't looked at the link; but to be honest it's unlikely you would understand it if you are having trouble with the much simpler question regarding solutions in the case of 6, 12, and 21. Cheers - Chas From randrange at gmail.com Wed Aug 18 13:48:54 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 10:48:54 -0700 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: Hello yes This line doesn't seem to want to accept a list for some strange reason story.append(Paragraph(str(result_list), para)) *cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From raoulbia at gmail.com Wed Aug 18 13:52:35 2010 From: raoulbia at gmail.com (Baba) Date: Wed, 18 Aug 2010 10:52:35 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: Hi Chas Thanks for that and i agree on your last remark :) re the number of required consecutive passes required: The number of required consecutive passes is equal to the smallest number because after that you can get any amount of nuggets by just adding the smallest nugget pack to some other number. This is only true if gcd(a,b,c)=1. Thanks to all for the help in getting to the bottom of the exercise. I have truly enjoyed this and most importantly i have learned some new things. Hadn't really done any mathematics in a long time and only starting programming so this was good to get up to speed. kind regards to everyone! Baba From thomas at jollybox.de Wed Aug 18 14:21:32 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 18 Aug 2010 20:21:32 +0200 Subject: Using re.sub with %s In-Reply-To: <4C6C1A47.9020907@reelfx.com> References: <4C6C1A47.9020907@reelfx.com> Message-ID: <201008182021.35465.thomas@jollybox.de> On Wednesday 18 August 2010, it occurred to Brandon Harris to exclaim: > Having trouble using %s with re.sub > > test = '/my/word/whats/wrong' > re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) > > return is /my/@0/whats/wrong > This has nothing to do with %, of course: >>> re.sub('(/)word(/)', r'\1\%d\2'%1000, test) '/my/@0/whats/wrong' >>> re.sub('(/)word(/)', r'\1\1000\2', test) '/my/@0/whats/wrong' let's see if we can get rid of that zero: >>> re.sub('(/)word(/)', r'\1\100\2', test) '/my/@/whats/wrong' so '\100' appears to be getting replaced with '@'. Why? >>> '\100' '@' This is Python's way of escaping characters using octal numbers. >>> chr(int('100', 8)) '@' How to avoid this? Well, if you wanted the literal backslash, you'll need to escape it properly: >>> print(re.sub('(/)word(/)', r'\1\\1000\2', test)) /my/\1000/whats/wrong >>> If you didn't want the backslash, then why on earth did you put it there? You have to be careful with backslashes, they bite ;-) Anyway, you can simply do the formatting after the match. >>> re.sub('(/)word(/)', r'\1%d\2', test) % 1000 '/my/1000/whats/wrong' >>> Or work with match objects to construct the resulting string by hand. - Thomas From nfdisco at gmail.com Wed Aug 18 14:24:41 2010 From: nfdisco at gmail.com (ernest) Date: Wed, 18 Aug 2010 11:24:41 -0700 (PDT) Subject: expression in an if statement Message-ID: Hi, In this code: if set(a).union(b) == set(a): pass Does Python compute set(a) twice? Thanks in advance. Ernest From __peter__ at web.de Wed Aug 18 14:34:17 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Aug 2010 20:34:17 +0200 Subject: expression in an if statement References: Message-ID: ernest wrote: > In this code: > > if set(a).union(b) == set(a): pass > > Does Python compute set(a) twice? >>> a = "abc" >>> b = "def" >>> _set = set >>> def set(x): ... print "computing set(%r)" % x ... return _set(x) ... >>> if set(a).union(b) == set(a): pass ... computing set('abc') computing set('abc') So yes, set(a) is computed twice. Peter From cbrown at cbrownsystems.com Wed Aug 18 14:40:57 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Wed, 18 Aug 2010 11:40:57 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: On Aug 18, 10:52?am, Baba wrote: > Hi Chas > > Thanks for that and i agree on your last remark :) > > re the number of required consecutive passes required: > > The number of required consecutive passes is equal to the smallest > number because after that you can get any amount of nuggets by just > adding the smallest nugget pack to some other number. > > This is only true if gcd(a,b,c)=1. > > Thanks to all for the help in getting to the bottom of the exercise. I > have truly enjoyed this and most importantly i have learned some new > things. Hadn't really done any mathematics in a long time and only > starting programming so this was good to get up to speed. > > kind regards to everyone! > Baba Happy to be of service! Cheers - Chas From blog at rivadpm.com Wed Aug 18 14:49:11 2010 From: blog at rivadpm.com (Alex McDonald) Date: Wed, 18 Aug 2010 11:49:11 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> Message-ID: On 18 Aug, 11:09, spinoza1111 wrote: > On Aug 18, 1:21?am, Standish P wrote: > > > This you might want to take this to the Forth people because they are > > marketing their language as a cure for all that plagues programming > > today. > > No, they're not. That I agree with. > Stack based languages have seen better days and Forth > (and the SL/1 language I supported with compilers at Bell-Northern > Research) were last in fashion in the 1970s. Processors seldom could > multitask, so it wasn't recognized that the stack could be a > performance bottleneck, where stack operations cannot be pipelined or > executed in parallel. > > John Hennessy of Stanford and MIPS made the stack must die case at ACM > ASPLOS in 1987. Niklaus Wirth was also at this conference at which I > was a fly on the wall, maintaining that the stack was good for > reliability and verifiability of software. > > Forth had a snowball's chance because it forces ordinary programmers > to think in Reverse Polish notation and is for the above reasons hard > to pipeline, although of course it can be pipelined. I really don't understand much of what you're saying here; Forth can be implemented on processors that have several hardware assisted stacks, 1 stack or even no stack at all. Multitasking? Why's that a problem? And why is it hard to pipeline? Are you thinking of a specific processor? From python at mrabarnett.plus.com Wed Aug 18 14:50:20 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 19:50:20 +0100 Subject: Using re.sub with %s In-Reply-To: <201008182021.35465.thomas@jollybox.de> References: <4C6C1A47.9020907@reelfx.com> <201008182021.35465.thomas@jollybox.de> Message-ID: <4C6C2B6C.7010709@mrabarnett.plus.com> Thomas Jollans wrote: > On Wednesday 18 August 2010, it occurred to Brandon Harris to exclaim: >> Having trouble using %s with re.sub >> >> test = '/my/word/whats/wrong' >> re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) >> >> return is /my/@0/whats/wrong >> > > This has nothing to do with %, of course: > >>>> re.sub('(/)word(/)', r'\1\%d\2'%1000, test) > '/my/@0/whats/wrong' >>>> re.sub('(/)word(/)', r'\1\1000\2', test) > '/my/@0/whats/wrong' > > let's see if we can get rid of that zero: > >>>> re.sub('(/)word(/)', r'\1\100\2', test) > '/my/@/whats/wrong' > > so '\100' appears to be getting replaced with '@'. Why? > >>>> '\100' > '@' > > This is Python's way of escaping characters using octal numbers. > >>>> chr(int('100', 8)) > '@' > > How to avoid this? Well, if you wanted the literal backslash, you'll need to > escape it properly: > >>>> print(re.sub('(/)word(/)', r'\1\\1000\2', test)) > /my/\1000/whats/wrong > > If you didn't want the backslash, then why on earth did you put it there? You > have to be careful with backslashes, they bite ;-) > > Anyway, you can simply do the formatting after the match. > >>>> re.sub('(/)word(/)', r'\1%d\2', test) % 1000 > '/my/1000/whats/wrong' > > Or work with match objects to construct the resulting string by hand. > You can stop group references which are followed by digits from turning into octal escapes in the replacement template by using \g instead: >>> print r'\1%s' % '00' \100 >>> print r'\g<1>%s' % '00' \g<1>00 From jjposner at optimum.net Wed Aug 18 14:50:32 2010 From: jjposner at optimum.net (John Posner) Date: Wed, 18 Aug 2010 14:50:32 -0400 Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 In-Reply-To: References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <4C645959.7010207@free.fr> <2882c967-9456-473a-94a0-400f7036be90@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> Message-ID: <4C6C2B78.40606@optimum.net> On 8/18/2010 1:38 PM, cbrown at cbrownsystems.com wrote: >>> To go the other way, if d = 1, then there exists integers (not >>> neccessarily positive) such that >> >>> a*x + b*y + c*z = 1 That fact is non-trivial, although the proof isn't *too* hard [1]. I found it interesting to demonstrate the simpler case (a*x + b*y = 1) by "instrumenting" the classic Python implementation of Euclid's Algorithm: def show_gcd(a,b): """ find GCD of two integers, showing intermediate steps in both remainder and linear-combination forms """ while b: if a%b > 0: rem_form = "%d == %d*(%d), rem %d" % (a, b, a/b, a%b) equ_form = "%d == %d*(1) + %d*(-%d)" % (a%b, a, b, a/b) print "%3d %3d %-30s %s" % (a,b, rem_form, equ_form) a,b = b, a%b print "\nGCD is", a >>> show_gcd(124, 39) 124 39 124 == 39*(3), rem 7 7 == 124*(1) + 39*(-3) 39 7 39 == 7*(5), rem 4 4 == 39*(1) + 7*(-5) 7 4 7 == 4*(1), rem 3 3 == 7*(1) + 4*(-1) 4 3 4 == 3*(1), rem 1 1 == 4*(1) + 3*(-1) Performing successive substitutions, bottom to top, using the equations in the right-hand column: 1 == 4*(1) + 3*(-1) == 4*(1) + (7*(1) + 4*(-1))*(-1) == 4*(2) + 7*(-1) == (39*(1) + 7*(-5))*(2) + 7*(-1) == 39*(2) + 7*(-11) == 39*(2) + (124*(1) + 39*(-3))*(-11) == 39*(35) + 124*(-11) What could be simpler! :-) -John [1] http://math453fall2008.wikidot.com/lecture-3 ("GCD as a linear combonation" [sic]) From python at mrabarnett.plus.com Wed Aug 18 15:02:09 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 20:02:09 +0100 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: <4C6C2E31.30304@mrabarnett.plus.com> Andrew Evans wrote: > Hello yes > > This line doesn't seem to want to accept a list for some strange reason > > > story.append(Paragraph(str(result_list), para)) > From the documentation it appears that you need to pass a string. You're just passing the result of str(result_list), which isn't giving you what you want: >>> result_list = ['hello', 'world'] >>> print str(result_list) ['hello', 'world'] But what do you want? Do you just want to concatenate the entries into a single string (assuming they're all strings)? >>> print "".join(result_list) helloworld Or with some kind of separator between them? >>> print " ".join(result_list) hello world From randrange at gmail.com Wed Aug 18 15:17:24 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 12:17:24 -0700 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: Hello ty for the fast replies This is the string I am using for the PDF I was able to create new lines using the HTML "br" tag which is what I wanted a method to create new lines search_str="Position: (%d) - Keyword: (%s) - Domain (%s)

" % (idx+1, target_keyword, session.target_domain) result_list.append(search_str) however it maintains these characters in the text of the generated PDF [' ', ' '] with the string in between those I just want to be able to out put the string with no extra characters I assume these characters are there because its a list .............. >From the documentation it appears that you need to pass a string. You're just passing the result of str(result_list), which isn't giving you what you want: -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Aug 18 15:17:29 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Aug 2010 15:17:29 -0400 Subject: Python 2.7 support for PyWin32 In-Reply-To: References: <6ff947f2-8ce9-4236-b0b2-a4563613e65b@i13g2000yqd.googlegroups.com> Message-ID: On 8/18/2010 8:33 AM, Mark Lawrence wrote: > On 18/08/2010 12:54, paulo.jpinto at gmail.com wrote: >> Hi everyone, >> >> does anyone know when PyWin is going to support Python 2.7? >> >> I tried to look for information, but to no avail. >> >> Thanks in advance, >> Paulo > > It was created on 2009-07-08!!! See:- > > http://sourceforge.net/projects/pywin32/files/pywin32/ Considering that that is months before the first alpha release and a year before the final of 2.7, truly amazing. -- Terry Jan Reedy From python at mrabarnett.plus.com Wed Aug 18 15:28:38 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Aug 2010 20:28:38 +0100 Subject: Problem Creating NewLines in PDF In-Reply-To: References: Message-ID: <4C6C3466.4060305@mrabarnett.plus.com> Andrew Evans wrote: > Hello ty for the fast replies > > This is the string I am using for the PDF I was able to create new lines > using the HTML "br" tag which is what I wanted a method to create new lines > > search_str="Position: (%d) - Keyword: (%s) - Domain (%s)

" % > (idx+1, target_keyword, session.target_domain) > result_list.append(search_str) > > however it maintains these characters in the text of the generated PDF > > [' > ', ' > '] with the string in between those > > I just want to be able to out put the string with no extra characters I > assume these characters are there because its a list > As I said, if you just want to join a list of strings into one string, then use "".join(result_list): story.append(Paragraph("".join(result_list), para)) From erather at forth.com Wed Aug 18 15:30:40 2010 From: erather at forth.com (Elizabeth D Rather) Date: Wed, 18 Aug 2010 09:30:40 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> Message-ID: On 8/18/10 12:09 AM, spinoza1111 wrote: > On Aug 18, 1:21 am, Standish P wrote: >>> Garbage collection doesn't use a stack. It uses a "heap", which is in >>> the abstract a collection of memory blocks of different lengths, >>> divided into two lists, generally represented as linked lists: >> >>> 1. A list of blocks that are free and may be used to store new data >> >>> 2. A list of blocks that are in use, or haven't been freed (yet) >> >> Is this all that a heap is or is there more to it ? I have been >> looking for simple but complete explanation of heap for a while and >> not gotten to it. I think I am looking for a stack allocation on the >> same pattern. In a disk, a file is fragmented in many contiguous >> blocks and is accessed automatically. Stacks (at least as far as Forth uses them) and heaps are fundamentally different things. ... >>> However, data structures of variable size, or data structures that >>> merely take up a lot of space, don't play nice with others on the >>> stack, so, we place their address on the stack and store them in >>> another place, which was named the heap, probably, as a sort of >>> witticism. In Forth, they go in "data space", which might or might not be in the dictionary, and is almost never in a dynamically managed heap; certainly not on a stack. ... > > No, they're not. Stack based languages have seen better days and Forth > (and the SL/1 language I supported with compilers at Bell-Northern > Research) were last in fashion in the 1970s. Processors seldom could > multitask, so it wasn't recognized that the stack could be a > performance bottleneck, where stack operations cannot be pipelined or > executed in parallel. Lol. Forth supported multitasking on every processor it was implemented on in the 70's, with blazing speed compared to competitive techniques. I have never seen stack operations to be a bottleneck. ... > Forth had a snowball's chance because it forces ordinary programmers > to think in Reverse Polish notation and is for the above reasons hard > to pipeline, although of course it can be pipelined. Mostly it had a "snowball's chance" because it was never picked up by the CS gurus who, AFAIK, never really took a serious look at it. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From aahz at pythoncraft.com Wed Aug 18 15:32:59 2010 From: aahz at pythoncraft.com (Aahz) Date: 18 Aug 2010 12:32:59 -0700 Subject: scipy / stats : quantiles using sample weights from survey data References: <94bb6313-1b09-4eeb-9969-07d76048a361@m35g2000prn.googlegroups.com> Message-ID: In article <94bb6313-1b09-4eeb-9969-07d76048a361 at m35g2000prn.googlegroups.com>, Christopher Barrington-Leigh wrote: > >There is a function scipy.stats.mstats.mquantiles that returns >quantiles for a vector of data. >But my data should not be uniformly weighted in an estimate of the >distribution, since they are from a survey and come with estimated >sampling weights based on the stratification used in sampling. > >Is there a routine to calculate these quantiles taking into account >the survey weights? I can find nothing, so maybe you have had the >same problem and written something. You should ask on the scipy mailing list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From aahz at pythoncraft.com Wed Aug 18 15:38:08 2010 From: aahz at pythoncraft.com (Aahz) Date: 18 Aug 2010 12:38:08 -0700 Subject: assigning variables from list data References: Message-ID: In article , Chris Hare wrote: > >cursor.execute('select * from net where NetNumber > 0') Unless your table is guaranteed to never change layout, I suggest that instead listing fields is a Good Idea: cursor.execute('select netNumber, netType, .... from net where NetNumber > 0') Then the tuple unpack suggested by other posters will never fail. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From cbrown at cbrownsystems.com Wed Aug 18 16:02:23 2010 From: cbrown at cbrownsystems.com (cbrown at cbrownsystems.com) Date: Wed, 18 Aug 2010 13:02:23 -0700 (PDT) Subject: looping through possible combinations of McNuggets packs of 6, 9 and 20 References: <29d2d922-cc2e-4057-bea1-c268a52a06c8@s9g2000yqd.googlegroups.com> <9d731602-ae7e-4c2d-a941-09f8d67641c6@s9g2000yqd.googlegroups.com> <4C66D219.4040407@optimum.net> <4C6814CA.6070503@optimum.net> <0b87bc04-e354-4f8f-b860-e8a200de93b1@k10g2000yqa.googlegroups.com> <64382d90-a317-4043-8914-0155a352dc9d@g21g2000prn.googlegroups.com> <21fb706e-cfaf-402f-bcf7-73101b0223e7@v8g2000yqe.googlegroups.com> <4C6C2B78.40606@optimum.net> Message-ID: <2c14d0e6-04fd-457e-a581-bfb4740d9c27@t20g2000yqa.googlegroups.com> On Aug 18, 11:50?am, John Posner wrote: > On 8/18/2010 1:38 PM, cbr... at cbrownsystems.com wrote: > > >>> To go the other way, if d = 1, then there exists integers (not > >>> neccessarily positive) such that > > >>> a*x + b*y + c*z = 1 > > That fact is non-trivial, although the proof isn't *too* hard [1]. I > found it interesting to demonstrate the simpler case (a*x + b*y = 1)... And to get the more general case, if we write (a,b) for gcd of and b, we can think of the "," as a binary operator that you can show is associative: ((a,b), c) = (a, (b,c)) = (a, b, c) and so a proof that exists x,y with a*x + b*y = (a,b) can then be extended to a proof for an arbitrary number of elements. (Oddly, "," is also distributive over itself: ((a,b), c) = ((a,c), (b,c))...) Cheers - Chas From nobody at nowhere.com Wed Aug 18 16:03:19 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 18 Aug 2010 21:03:19 +0100 Subject: when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray' References: Message-ID: On Wed, 18 Aug 2010 05:56:27 -0700, Duim wrote: > Although I'm sure somewhere this issue is discussed in this (great) > group, I didn't know the proper search words for it (although I > tried). > > I'm using python (2.6) scientifically mostly, and created a simple > class to store time series (my 'Signal' class). > I need this class to have a possibility to get multiplied by an array, > but pre and post multiplication have different mathematical outcomes > ( basically A* B != B*A ) . > > Post multiplication by an array works fine defining __mul__ in the > Signal class, but pre multiplication does not. It keeps trying to > multiply all elements separately instead to send this array to my > __rmul__ function. > > How can I fix this without the need for a separate > 'multiplysignal(A,B)' function? Make Signal a subclass of numpy.ndarray. If one operand is a subclass of the other, its __rmul__ will be preferred to the parent's __mul__. In the absence of a subclass-superclass relationship, the LHS's __mul__ is preferred to the RHS's __rmul__, so the RHS's __rmul__ is only called if the LHS lacks a __mul__ method or if the method refuses its argument (returns NotImplemented). Likewise for other "reflected" methods. From ringemup at gmail.com Wed Aug 18 16:12:47 2010 From: ringemup at gmail.com (Nan) Date: Wed, 18 Aug 2010 13:12:47 -0700 (PDT) Subject: subprocess.Popen calling httpd reload never finishes References: <99f9f605-7dc7-4b70-a2f5-9595d57ee9d7@g17g2000yqe.googlegroups.com> Message-ID: <3e1dc02b-2cf8-4c9d-bb61-6c38faa38b45@d8g2000yqf.googlegroups.com> On Aug 18, 12:37?pm, Albert Hopkins wrote: > On Wed, 2010-08-18 at 06:58 -0700, Nan wrote: > > Ah, I'd been told that there would be no conflict, and that this was > > just reloading the configuration, not restarting Apache. > > > I do need the web app to instruct Apache to reload because just before > > this it's creating new VirtualHosts that need to be recognized. ?Is > > there a better way to do this (e.g. to say "start doing this once I'm > > finished")? > > > I'm getting a status code and output from the call before the Django > > script stops executing... Is there a way to stop waiting for the > > process to complete once I have those? > > I have a wireless router with a built in web server. ?Sometimes it needs > to "reload" it's config. ?Basically what it's doing is rebooting the > entire router (I can see this if I'm actuall watching the router). ?All > it is doing, I'm pretty sure, is calling some program that forks another > process and then exits the main program. ?The forked process then > reboots the router. ?Meanwhile before that happens the web server sends > a response. Basically in the response it sends an HTTP Refresh with x > number of seconds. ?Presumably x is longer than the time it requires for > the router to reboot. ?The router reboots, the browser refreshes and > viola. > > You probably need to so something similar in that your request calls a > program that forks off and restarts apaches. ?It should probably not do > so immediately so that your request has time to send a response with a > refresh header (but that shouldn't take long). ?After a second or so, > apache will have restarted and the browser will have refreshed. > > so (untested): > > def reload(request): > ? ? subprocess.call(['my_apache_reloader']) # this should fork and exit > ? ? response = HttpResponse() > ? ? response['Refresh']='3; url=%s' % reverse(home) # chk back in 3 secs > ? ? return response > > BTW There is a Django mailing list where this might be more appropriate > to discuss. > > -a Sadly, questions about subprocess spawning on the Django lists seem to get referred back to the Python lists when they get an answer at all. You've been very helpful, though, so thank you. I think I'll have to mark in the database when the server needs restarting, and run a cron job to check that and reload Apache from a non-Apache process. It will mean delayed creation of the Virtual Hosts and no immediate feedback to indicate success or failure, but it doesn't look like there's much alternative. From python at rcn.com Wed Aug 18 16:16:48 2010 From: python at rcn.com (Raymond Hettinger) Date: Wed, 18 Aug 2010 20:16:48 GMT Subject: q.join() is probably the wrong method for you References: Message-ID: <2010818161635usenet@eggheadcafe.com> The join() method is all about waiting for all the tasks to be done. If you don't care whether the tasks have actually finished, you can periodically poll the unfinished task count: stop = time() + timeout while q.unfinished_tasks and time() < stop: sleep(1) This loop will exist either when the tasks are done or when the timeout period has elapsed. Raymond > On Thursday, June 17, 2010 5:52 PM pacopyc wrote: > Hi, I am trying to work with threads and I need your help. This is > code: > > from threading import Thread > from Queue import Queue > import time > import random > > def test_fun (k,q,t): > time.sleep(t) > print "hello world from thread " + str(q.get()) + " (sleep time = > " + str(t) + " sec.)" > q.task_done() > > queue = Queue() > for i in range (1,10): > queue.put(i) > for j in range(queue.qsize()): > num = random.randint(1,30) > worker = Thread(target=test_fun, args=(j,queue,num)) > worker.setDaemon(True) > worker.start() > queue.join() > > > Execution: > > hello world from thread 1 (sleep time = 5 sec.) > hello world from thread 2 (sleep time = 5 sec.) > hello world from thread 3 (sleep time = 6 sec.) > hello world from thread 4 (sleep time = 8 sec.) > hello world from thread 5 (sleep time = 10 sec.) > hello world from thread 6 (sleep time = 13 sec.) > hello world from thread 7 (sleep time = 18 sec.) > hello world from thread 8 (sleep time = 19 sec.) > hello world from thread 9 (sleep time = 20 sec.) > > Some questions for you: > > 1) Why order is always the same (thread 1, thread 2, thread 3 .... > thread 9) and also seconds are always increasing? I do not understand. > 2) I'd like to decide a max time for each thread. If max time = 7 sec. > I want to print only threads with sleep time <= 7 sec. How can I do? > Can you modify my code? > > Thank you very much >> On Thursday, June 17, 2010 7:04 PM MRAB wrote: >> pacopyc wrote: >> >> 1) >> >> First it puts the numbers 1..9 into 'queue', then it starts 9 threads, >> giving each a number 'num'. >> >> Each thread waits for 'num' seconds ('t' in the thread). >> >> The thread with the lowest value of 'num' wakes first, gets the first >> entry from 'queue' (the value 1), and therefore prints "thread 1". >> >> The thread with the second-lowest value of 'num' wakes next, gets the >> second entry from 'queue' (the value 2), and therefore prints "thread >> 2". >> >> And so on. >> >> 2) >> >> If a thread is given a value of 'num' of more than a maximum, that >> thread should not print its output, but it should still get the entry >> from the queue (assuming that you want it to still behave the same >> otherwise). >>> On Friday, June 18, 2010 5:45 PM pacopyc wrote: >>> =3D >>> . >>> >>> Ok, the problem is that I want fix a time max for each thread. For >>> example run 10 threads (each can terminate its work in 10 sec. max >>> fixed time) and wait them. If they finish its work in < 10 sec. (for >>> example 2 sec.) very good ... go on immediately (do not wait >>> unnecessary time), but if a thread use more than 10 sec. stop wait (I >>> kill it) .... when all threads have finished their work or when they >>> have used all their available time (10 sec.) the program must go on >>> (do not wait). >>>> On Friday, June 18, 2010 6:27 PM MRAB wrote: >>>> pacopyc wrote: >>>> [snip] >>>> >>>> it is not possible to kill a thread. If you want a thread to have a >>>> maximum time, the thread must check occasionally how long it has been >>>> running and terminate if necessary. >>>> >>>> Another programming language (Java) originally had the ability to kill >>>> threads, but that was later deprecated because it caused problems due to >>>> not knowing what the thread was doing when it was killed (it might have >>>> been in the middle of updating something at the time, for example, >>>> leaving the system in an inconsistent state). >>>>> On Friday, June 18, 2010 6:58 PM pacopyc wrote: >>>>> Ok, I understand. But is possible fix max wait time (for example 60 >>>>> sec.) in main thread and check queue for task done and at the same >>>>> time the remaining time. When all task have done or wait time has >>>>> expired main thread go on. Is it possible? Can you write code? >>>>> Thank you very much. >>>>>> On Friday, June 18, 2010 7:45 PM MRAB wrote: >>>>>> pacopyc wrote: >>>>>> >>>>>> The documentation says that queue.join() cannot have a timeout, so you >>>>>> might have to think of another way to achieve the same effect. >>>>>> >>>>>> You could, for example, have a results queue into which a thread puts >>>>>> something to indicate when it has finished, and then use the .get method >>>>>> on it in the main thread (the .get method can have a timeout). >>>>>> Submitted via EggHeadCafe - Software Developer Portal of Choice >>>>>> Custom Favorites Web Site with MongoDb and NoRM >>>>>> http://www.eggheadcafe.com/tutorials/aspnet/7fbc7a01-5d30-4cd3-b373-51d4a0e1afa8/custom-favorites-web-site-with-mongodb-and-norm.aspx From no.email at nospam.invalid Wed Aug 18 16:32:30 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 18 Aug 2010 13:32:30 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> Message-ID: <7xwrrnmzkx.fsf@ruckus.brouhaha.com> Elizabeth D Rather writes: >> Processors seldom could multitask, so it wasn't recognized that the >> stack could be a performance bottleneck > Lol. Forth supported multitasking on every processor it was > implemented on in the 70's, with blazing speed compared to competitive > techniques. I have never seen stack operations to be a bottleneck. I think "multitasking" in that post refers to superscalar execution, which wasn't done in the 1970's except on supercomputers. That the stack is a bottleneck is the precise reason that optimizing Forth compilers do complicated flow analysis to translate stack operations into register operations. From andrei.avk at gmail.com Wed Aug 18 16:56:22 2010 From: andrei.avk at gmail.com (AK) Date: Wed, 18 Aug 2010 16:56:22 -0400 Subject: Python "why" questions In-Reply-To: <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> Message-ID: <4C6C48F6.3040309@gmail.com> On 08/17/2010 10:15 PM, Russ P. wrote: > On Aug 7, 5:54 am, "D'Arcy J.M. Cain" wrote: > >> Would said beginner also be surprised that a newborn baby is zero years >> old or would it be more natural to call them a one year old? Zero >> based counting is perfectly natural. > > You're confusing continuous and discrete variables. Time is a > continuous variable, but a list index is discrete. > > Take a look at any numbered list, such as the top ten football teams > or the top ten software companies. Have you ever seen such a list > start with zero? If so, where? I sure haven't. > > When I studied linear algebra way back, vector and matrix indices also > always started with one, and I assume they still do. > > The convention of starting with zero may have had some slight > performance advantage in the early days of computing, but the huge > potential for error that it introduced made it a poor choice in the > long run, at least for high-level languages. I have to agree, there's innumerable number of examples where sequential number of an item in a series is counted starting with one. Second loaf of bread; third day of vacation, first cup of tea today, first gray hair, 50th anniversary, 2nd century AD, and approximately a gazillion other examples. Contrast this with _one_ example that was repeated in this thread of there being ground floor, 1st floor, 2nd, and so on. However! Consider that ground floor is kind of different from the other floors. It's the floor that's not built up over ground, but is already there -- in case of the most primitive dwelling, you can put some sawdust over the ground, put a few boards overhead and it's a "home", although probably not a "house". But does it really have what can be officially called a "floor"? On a more practical angle, ground floors usually have the lobby, receptionists, storefronts and stores, etc; while 1st floor and up are business/residential. I think different numbering from pretty much all other things out there gives you a hint that the ground floor is a different animal. -andrei From andrei.avk at gmail.com Wed Aug 18 17:01:20 2010 From: andrei.avk at gmail.com (AK) Date: Wed, 18 Aug 2010 17:01:20 -0400 Subject: Python "why" questions In-Reply-To: <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> Message-ID: <4C6C4A20.8080208@gmail.com> On 08/17/2010 10:15 PM, Russ P. wrote: > On Aug 7, 5:54 am, "D'Arcy J.M. Cain" wrote: > >> Would said beginner also be surprised that a newborn baby is zero years >> old or would it be more natural to call them a one year old? Zero >> based counting is perfectly natural. > > You're confusing continuous and discrete variables. Time is a > continuous variable, but a list index is discrete. > > Take a look at any numbered list, such as the top ten football teams > or the top ten software companies. Have you ever seen such a list > start with zero? If so, where? I sure haven't. > > When I studied linear algebra way back, vector and matrix indices also > always started with one, and I assume they still do. > > The convention of starting with zero may have had some slight > performance advantage in the early days of computing, but the huge > potential for error that it introduced made it a poor choice in the > long run, at least for high-level languages. Besides that, the way things are now, it's almost an Abbot & Costello routine: - How many folders are there? - 5 - Ok, give me the fourth one. - Here. - No, that's the last one! - That's what you said! - No, I said, fourth one! - That's what I did! - How many are there in all? - I already said, five! - You gave me the last one!! - Just like you said - fourth!!!! From nagle at animats.com Wed Aug 18 17:14:15 2010 From: nagle at animats.com (John Nagle) Date: Wed, 18 Aug 2010 14:14:15 -0700 Subject: expression in an if statement In-Reply-To: References: Message-ID: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> On 8/18/2010 11:24 AM, ernest wrote: > Hi, > > In this code: > > if set(a).union(b) == set(a): pass > > Does Python compute set(a) twice? CPython does. Shed Skin might optimize. Don't know about Iron Python. John Nagle From nagle at animats.com Wed Aug 18 17:21:15 2010 From: nagle at animats.com (John Nagle) Date: Wed, 18 Aug 2010 14:21:15 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <7xwrrnmzkx.fsf@ruckus.brouhaha.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <7xwrrnmzkx.fsf@ruckus.brouhaha.com> Message-ID: <4c6c4ec8$0$1623$742ec2ed@news.sonic.net> On 8/18/2010 1:32 PM, Paul Rubin wrote: > Elizabeth D Rather writes: >>> Processors seldom could multitask, so it wasn't recognized that the >>> stack could be a performance bottleneck >> Lol. Forth supported multitasking on every processor it was >> implemented on in the 70's, with blazing speed compared to competitive >> techniques. I have never seen stack operations to be a bottleneck. > > I think "multitasking" in that post refers to superscalar execution, > which wasn't done in the 1970's except on supercomputers. That the > stack is a bottleneck is the precise reason that optimizing Forth > compilers do complicated flow analysis to translate stack operations > into register operations. Some small FORTH machines had dedicated stack hardware. On each CPU cycle, the CPU could do one stack access, one main memory access, and one return stack access. This was before cacheing; those CPUs were slow relative to their memory, so a non-cached one-instruction-per-clock machine made sense. In the superscalar era, there's not much of an advantage to avoiding stack accesses. x86 superscalar machines have many registers not visible to the program, as the fastest level of cache. In practice, the top of the stack is usually in CPU registers. The "huge number of programmer-visible register" machines like SPARCs turned out to be a dead end. So did making all the instructions the same width; it makes the CPU simpler, but not faster, and it bulks up the program by 2x or so. John Nagle From russ.paielli at gmail.com Wed Aug 18 17:47:08 2010 From: russ.paielli at gmail.com (Russ P.) Date: Wed, 18 Aug 2010 14:47:08 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> Message-ID: <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> On Aug 18, 2:01?pm, AK wrote: > On 08/17/2010 10:15 PM, Russ P. wrote: > > > > > On Aug 7, 5:54 am, "D'Arcy J.M. Cain" ?wrote: > > >> Would said beginner also be surprised that a newborn baby is zero years > >> old or would it be more natural to call them a one year old? ?Zero > >> based counting is perfectly natural. > > > You're confusing continuous and discrete variables. Time is a > > continuous variable, but a list index is discrete. > > > Take a look at any numbered list, such as the top ten football teams > > or the top ten software companies. Have you ever seen such a list > > start with zero? If so, where? I sure haven't. > > > When I studied linear algebra way back, vector and matrix indices also > > always started with one, and I assume they still do. > > > The convention of starting with zero may have had some slight > > performance advantage in the early days of computing, but the huge > > potential for error that it introduced made it a poor choice in the > > long run, at least for high-level languages. > > Besides that, the way things are now, it's almost an Abbot & Costello > routine: > > - How many folders are there? > - 5 > - Ok, give me the fourth one. > - Here. > - No, that's the last one! > - That's what you said! > - No, I said, fourth one! > - That's what I did! > - How many are there in all? > - I already said, five! > - You gave me the last one!! > - Just like you said - fourth!!!! Yes, it's confusing. Which element of a list is the "first" element? Wait, "first" is sometimes abbreviated as "1st". So is the 1st element the 0 element or the 1 element? I honestly don't know. Is the top team in the league the number 1 team -- or the number 0 team? I have yet to hear anyone call the best team the number 0 team! Unfortunately, we're stuck with this goofy numbering system in many languages. Fortunately, the trend is away from explicit indexing and toward "for" loops when possible. From cmpython at gmail.com Wed Aug 18 18:07:20 2010 From: cmpython at gmail.com (CM) Date: Wed, 18 Aug 2010 15:07:20 -0700 (PDT) Subject: exception handling with sqlite db errors References: <2a47b306-45d1-474a-9f8e-5b71eba629c9@p11g2000prf.googlegroups.com> Message-ID: On Aug 12, 3:31?pm, a... at pythoncraft.com (Aahz) wrote: > In article <2a47b306-45d1-474a-9f8e-5b71eba62... at p11g2000prf.googlegroups.com>, > > CM? wrote: > > >Maybe it's not much of an issue, but I think it would be a shame if > >occasional hangs/crashes could be caused by these (rare?) database > >conflicts if there is a good approach for avoiding them. ?I guess I > >could put every last write to the db in a try/except block but I > >thought there should be a more general solution, since that will > >require many such exceptions and seems inelegant. > > Wrap all your uses of sqlite into a function that does the try/except; > you only write the code once, then. ?As you progress, you can also > change the code to retry operations. ?Here's some ugly code I wrote on > top of SQLObject: > > from sqlobject.dbconnection import registerConnection > from sqlobject.sqlite.sqliteconnection import SQLiteConnection > > class RetrySQLiteConnection(SQLiteConnection): > ? ? """ > ? ? Because SQLite is not really concurrent, having multiple processes > ? ? read/write can result in locked DB failures. ?In addition, SQLObject > ? ? doesn't properly protect operations in transations, so you can get > ? ? spurious DB errors claiming that the DB is corrupt because of > ? ? foreign key integrity failures. > > ? ? This subclass retries DatabaseError and OperationalError > ? ? exceptions. > ? ? """ > ? ? MAX_RETRIES = 4 > ? ? SAFE_DB_ERROR = [ > ? ? ? ? 'database disk image is malformed', > ? ? ? ? 'file is encrypted or is not a database', > ? ? ? ? ] > > ? ? def _safe_db_error(self,exception): > ? ? ? ? err = str(exception).lower() > ? ? ? ? for safe_err in self.SAFE_DB_ERROR: > ? ? ? ? ? ? if safe_err in err: > ? ? ? ? ? ? ? ? return True > ? ? ? ? return False > > ? ? def _check_integrity(self): > ? ? ? ? conn = self.getConnection() > ? ? ? ? try: > ? ? ? ? ? ? i = 0 > ? ? ? ? ? ? while True: > ? ? ? ? ? ? ? ? i += 1 > ? ? ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? ? ? cursor = conn.cursor() > ? ? ? ? ? ? ? ? ? ? query = "pragma integrity_check" > ? ? ? ? ? ? ? ? ? ? SQLiteConnection._executeRetry(self, conn, cursor, query) > ? ? ? ? ? ? ? ? ? ? result = cursor.fetchall() > ? ? ? ? ? ? ? ? ? ? if result == [('ok',)]: > ? ? ? ? ? ? ? ? ? ? ? ? return True > ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? logging.error("Bad integrity result: %s", result) > ? ? ? ? ? ? ? ? ? ? ? ? return False > ? ? ? ? ? ? ? ? except DatabaseError, e: > ? ? ? ? ? ? ? ? ? ? if i < self.MAX_RETRIES: > ? ? ? ? ? ? ? ? ? ? ? ? logging.info('integrity_check, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? ? ? time.sleep(2) > ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? logging.error('integrity_check, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? finally: > ? ? ? ? ? ? self.releaseConnection(conn) > > ? ? def _executeRetry(self, conn, cursor, query): > ? ? ? ? i = 0 > ? ? ? ? while True: > ? ? ? ? ? ? i += 1 > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? return SQLiteConnection._executeRetry(self, conn, cursor, query) > ? ? ? ? ? ? except OperationalError, e: > ? ? ? ? ? ? ? ? if i < self.MAX_RETRIES: > ? ? ? ? ? ? ? ? ? ? logging.warn('OperationalError, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? time.sleep(10) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? logging.error('OperationalError, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? except DatabaseError, e: > ? ? ? ? ? ? ? ? if e.__class__ is not DatabaseError: > ? ? ? ? ? ? ? ? ? ? # Don't retry e.g. IntegrityError > ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? ? ? if not self._safe_db_error(e): > ? ? ? ? ? ? ? ? ? ? # Only retry specific errors > ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? ? ? if not self._check_integrity(): > ? ? ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? ? ? if i < self.MAX_RETRIES: > ? ? ? ? ? ? ? ? ? ? logging.warn('DatabaseError, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? time.sleep(0.5) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? logging.error('DatabaseError, try #%s: %s', i, e) > ? ? ? ? ? ? ? ? ? ? raise > > def conn_builder(): > ? ? return RetrySQLiteConnection > > registerConnection(['retrysqlite'], conn_builder) > > def init(): > ? ? dbpath = os.path.join(common.getSyncDataPath(), app.dbname) > ? ? connection_string = "retrysqlite:" + dbpath > ? ? global _connection > ? ? _connection = connectionForURI(connection_string) > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "...if I were on life-support, I'd rather have it run by a Gameboy than a > Windows box." ?--Cliff Wells Thanks, Aahz, I'll try to implement something along these lines. Che From breamoreboy at yahoo.co.uk Wed Aug 18 18:07:29 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 18 Aug 2010 23:07:29 +0100 Subject: Python "why" questions In-Reply-To: <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> Message-ID: On 18/08/2010 22:47, Russ P. wrote: > On Aug 18, 2:01 pm, AK wrote: >> On 08/17/2010 10:15 PM, Russ P. wrote: >> >> >> >>> On Aug 7, 5:54 am, "D'Arcy J.M. Cain" wrote: >> >>>> Would said beginner also be surprised that a newborn baby is zero years >>>> old or would it be more natural to call them a one year old? Zero >>>> based counting is perfectly natural. >> >>> You're confusing continuous and discrete variables. Time is a >>> continuous variable, but a list index is discrete. >> >>> Take a look at any numbered list, such as the top ten football teams >>> or the top ten software companies. Have you ever seen such a list >>> start with zero? If so, where? I sure haven't. >> >>> When I studied linear algebra way back, vector and matrix indices also >>> always started with one, and I assume they still do. >> >>> The convention of starting with zero may have had some slight >>> performance advantage in the early days of computing, but the huge >>> potential for error that it introduced made it a poor choice in the >>> long run, at least for high-level languages. >> >> Besides that, the way things are now, it's almost an Abbot& Costello >> routine: >> >> - How many folders are there? >> - 5 >> - Ok, give me the fourth one. >> - Here. >> - No, that's the last one! >> - That's what you said! >> - No, I said, fourth one! >> - That's what I did! >> - How many are there in all? >> - I already said, five! >> - You gave me the last one!! >> - Just like you said - fourth!!!! > > Yes, it's confusing. Which element of a list is the "first" element? > Wait, "first" is sometimes abbreviated as "1st". So is the 1st element > the 0 element or the 1 element? I honestly don't know. > > Is the top team in the league the number 1 team -- or the number 0 > team? I have yet to hear anyone call the best team the number 0 team! > > Unfortunately, we're stuck with this goofy numbering system in many > languages. Fortunately, the trend is away from explicit indexing and > toward "for" loops when possible. > Bring back Coral 66, all is forgiven. http://www.xgc.com/manuals/xgc-c66-rm/x357.html Cheers. Mark Lawrence. From thomas at jollybox.de Wed Aug 18 18:12:31 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 19 Aug 2010 00:12:31 +0200 Subject: expression in an if statement In-Reply-To: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> Message-ID: <201008190012.32074.thomas@jollybox.de> On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: > On 8/18/2010 11:24 AM, ernest wrote: > > Hi, > > > > In this code: > > > > if set(a).union(b) == set(a): pass > > > > Does Python compute set(a) twice? > > CPython does. Shed Skin might optimize. Don't know > about Iron Python. I doubt any actual Python implementation optimizes this -- how could it? The object "set" is clearly being called twice, and it happens to be called with the object "a" as a sole argument twice. What if "set" has side effects? A compiler could only exclude this possibility if it knew exactly what "set" will be at run time, which it can't. I expect that "set" and "a" have to be looked up twice, actually: "set(a).union(b)" might rebind either one of them. This would be considered a very rude and inappropriate thing to do, but Python usually guarantees to allow bad taste and behaviour. I might be wrong on some points here, but this is what I expect the expression (set(a).union(b) == set(a)) has to do, in any conforming implementation of Python. Please correct me if I'm wrong. 1. find out which object "set" refers to 2. find out which object "a" refers to 3. call (set) with the single positional argument (a), no keyword arguments 4. get the attribute "union" of the return value of [3] 5. find out which object "b" refers to 6. call (.union) with the single positional argument (b). 7. look up __eq__ in the __class__ of the return value of [6] 8. find out which object "set" refers to 9. find out which object "a" refers to 10. call (set) with the single positional argument (a), no keyword arguments 11. call [7] with two positional arguments: the return values [6] & [10] I'm not 100% sure if there are any guarantees as to when (5) is taken care of -- what would happen if set(a) or even set(a).__getattr__ changed the global "b"? My list there is obviously referring to Python 3.x, so there is no __cmp__ to worry about. From randrange at gmail.com Wed Aug 18 19:35:23 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 16:35:23 -0700 Subject: Unsupported Format Character '&' (0x26) Message-ID: I get an error message "Unsupported Format Character '&' (0x26)" I narrowed it down to these two variables any idea how to fix it? SEARCH_URL_0 = " http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)&fr=sfp&fr2=&iscqry= " NEXT_PAGE_0 = " http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)&fr=sfp&xargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2E&pstart=%(start)&b=11 " Not sure why its doing it the value in parenthesis should work %(query) etc Any ideas cheeers -------------- next part -------------- An HTML attachment was scrubbed... URL: From dikermail at gmail.com Wed Aug 18 19:43:31 2010 From: dikermail at gmail.com (Dmitriy Sergeevich) Date: Wed, 18 Aug 2010 16:43:31 -0700 (PDT) Subject: Top world brands shop Message-ID: http://groups.google.com/group/dikermail From randrange at gmail.com Wed Aug 18 19:55:20 2010 From: randrange at gmail.com (Andrew Evans) Date: Wed, 18 Aug 2010 16:55:20 -0700 Subject: Unsupported Format Character '&' (0x26) In-Reply-To: References: Message-ID: nvm I got it by adding s and d respectively after each value eg %(query)s thank you all On Wed, Aug 18, 2010 at 4:35 PM, Andrew Evans wrote: > I get an error message "Unsupported Format Character '&' (0x26)" I narrowed > it down to these two variables > > any idea how to fix it? > > SEARCH_URL_0 = " > http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)&fr=sfp&fr2=&iscqry= > " > NEXT_PAGE_0 = " > http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)&fr=sfp&xargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2E&pstart=%(start)&b=11 > " > > > > Not sure why its doing it the value in parenthesis should work %(query) etc > > Any ideas cheeers > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stndshp at gmail.com Wed Aug 18 20:13:22 2010 From: stndshp at gmail.com (Standish P) Date: Wed, 18 Aug 2010 17:13:22 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> Message-ID: <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> On Aug 18, 12:30?pm, Elizabeth D Rather wrote: > On 8/18/10 12:09 AM, spinoza1111 wrote: > > > On Aug 18, 1:21 am, Standish P ?wrote: > >>> Garbage collection doesn't use a stack. It uses a "heap", which is in > >>> the abstract a collection of memory blocks of different lengths, > >>> divided into two lists, generally represented as linked lists: > > >>> 1. ?A list of blocks that are free and may be used to store new data > > >>> 2. ?A list of blocks that are in use, or haven't been freed (yet) > > >> Is this all that a heap is or is there more to it ? I have been > >> looking for simple but complete explanation of heap for a while and > >> not gotten to it. I think I am looking for a stack allocation on the > >> same pattern. In a disk, a file is fragmented in many contiguous > >> blocks and is accessed automatically. > > Stacks (at least as far as Forth uses them) and heaps are fundamentally > different things. > > ... > > >>> However, data structures of variable size, or data structures that > >>> merely take up a lot of space, don't play nice with others on the > >>> stack, so, we place their address on the stack and store them in > >>> another place, which was named the heap, probably, as a sort of > >>> witticism. > > In Forth, they go in "data space", which might or might not be in the > dictionary, and is almost never in a dynamically managed heap; certainly > not on a stack. > ... > > > > > No, they're not. Stack based languages have seen better days and Forth > > (and the SL/1 language I supported with compilers at Bell-Northern > > Research) were last in fashion in the 1970s. Processors seldom could > > multitask, so it wasn't recognized that the stack could be a > > performance bottleneck, where stack operations cannot be pipelined or > > executed in parallel. > > Lol. ?Forth supported multitasking on every processor it was implemented > on in the 70's, with blazing speed compared to competitive techniques. > I have never seen stack operations to be a bottleneck. > > > > Forth had a snowball's chance because it forces ordinary programmers > > to think in Reverse Polish notation and is for the above reasons hard > > to pipeline, although of course it can be pipelined. > > Mostly it had a "snowball's chance" because it was never picked up by > the CS gurus who, AFAIK, never really took a serious look at it. Its quite possible that the criticism is unfair, but dont you think that in part some responsibility must be borne by your organization in not doing a good job of education ? I have looked at this book you authored in the past few weeks and found a link for your convenience now. This is entitled Advanced ..... http://www.amazon.com/Forth-Application-Techniques-5th-Notebook/dp/1419685767/ref=sr_1_1?ie=UTF8&s=books&qid=1282175842&sr=8-1#reader_1419685767 Show me on what page does it explain how Forth implements dynamic binding or lexical binding and takes care of the scope of definition of the "nouns" ? Provide me with a link, if you kindly would, that can take me to a tutorial of Forth internals or discusses this issue. > Cheers, > Elizabeth She is quite humble. Take a look at this page, http://www.forth.com/resources/evolution/index.html She is currently the number 1 in the forth world and if there was a nobel prize in forth, it would go to these three. Authors Elizabeth D. Rather FORTH, Inc. 5959 W. Century Blvd. Suite 700 Los Angeles, CA 90045 Elizabeth Rather is the co-founder of FORTH, Inc. and is a leading expert in the Forth programming language. Elizabeth was a colleague of Chuck Moore back when he worked at NRAO in the early 1970s. During his development of Forth, she became the second ever Forth programmer. Since then, she has become a leading expert in the language and one of its main proponents. Elizabeth was the chair of the ANSI Technical Committee that produced the ANSI Standard for Forth (1994). She is an author of several books on Forth and gives regular training seminars on its usage. Donald R. Colburn c/o Digital Media Magic 14712 Westbury Rd. Rockville, MD 20853 Don Colburn was one of the earliest Forth users. He was one of the founders of the Forth Interest Group, and contributed to the development of the first public-domain figForth. Subsequently, he founded Creative Solutions, Inc. (CSI), which introduced MacForth? in 1984. MacForth was the first programming language capable of running on the Macintosh when it was first introduced. Don was a member of the ANSI Technical Committee that produced the ANSI Standard for Forth (1994). He died in 2009. Charles H. Moore Computer Cowboys 40 Cedar Lane P.O. Box 127 Sierra City, CA 96125 Chuck Moore is Chairman and CTO of Green Arrays, Inc. He co-founded FORTH, Inc., in 1971 and went on to develop a Forth-based chip (RTX2000) in the mid 1980s, derivatives of which are still being used widely by NASA. At Computer Cowboys, Mr. Moore designed the Sh-Boom microprocessor and then co-founded iTv, an Internet Appliance manufacturer. During the 1990s, he used his own CAD software to design several custom VLSI chips, including the F21 processor with a network interface. More recently, he invented colorForth and ported his VLSI design tools to it. Moore served as CTO for IntellaSys during development of the S40 multi-computer chip. From stndshp at gmail.com Wed Aug 18 20:23:02 2010 From: stndshp at gmail.com (Standish P) Date: Wed, 18 Aug 2010 17:23:02 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On Aug 17, 6:38?pm, John Passaniti wrote: > You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > lists are constructed with pair of pointers called a "cons cell". > That is the most primitive component that makes up a list. ?Forth has > no such thing; in Forth, the dictionary (which is traditionally, but > not necessarily a list) is a data structure that links to the previous > word with a pointer. ? Would you show me a picture, ascii art or whatever for Forth ? I know what lisp lists look like so I dont need that for comparison. Forth must have a convention and a standard or preferred practice for its dicts. However, let me tell you that in postscript the dictionaries can be nested inside other dictionaries and any such hiearchical structure is a nested associative list, which is what linked list, nested dictionaries, nested tables are. > This is in fact one of the nice things about > Lisp; because all lists are created out of the same primitive cons > cell, you can consistently process any list in the system. ?In Forth, > any lists (such as the dictionary, if it is a list) are specific to > their purpose and have to be treated individually. > > I don't know what you mean by "nested-dictionaries." ?There is no such > thing in Forth. ?Dictionaries don't nest. ?You can create wordlists, > but each wordlist is flat. ?When most people think of a nested > dictionary, they would think of a structure that would allow any > arbitrary level of nesting, not a string of flat wordlists. From kst-u at mib.org Wed Aug 18 20:38:24 2010 From: kst-u at mib.org (Keith Thompson) Date: Wed, 18 Aug 2010 17:38:24 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> Message-ID: Standish P writes: > On Aug 18, 12:30?pm, Elizabeth D Rather wrote: [...] >> Mostly it had a "snowball's chance" because it was never picked up by >> the CS gurus who, AFAIK, never really took a serious look at it. > > Its quite possible that the criticism is unfair, but dont you think > that in part some responsibility must be borne by your organization in > not doing a good job of education ? [snip] > Show me on what page does it explain how Forth implements dynamic > binding or lexical binding and takes care of the scope of definition > of the "nouns" ? [...] Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, or comp.lang.python. Please trim the Newsgroups line. -- Keith Thompson (The_Other_Keith) kst-u at mib.org Nokia "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" From margieroginski at gmail.com Wed Aug 18 21:20:12 2010 From: margieroginski at gmail.com (Margie Roginski) Date: Wed, 18 Aug 2010 18:20:12 -0700 (PDT) Subject: How to see intermediate fail results from unittest as tests are running? Message-ID: Hi, I am using unittest in a fairly basic way, where I have a single file that simply defines a class that inherits from unittest.TestCase and then within that class I have a bunch of methods that start with "test". Within that file, at the bottom I have: if __name__ == "__main__": unittest.main() This works fine and it runs all of the testxx() methods in my file. As it runs it prints if the tests passed or failed, but if they fail, it does not print the details of the assert that made them fail. It collects this info up and prints it all at the end. Ok - my question: Is there any way to get unittest to print the details of the assert that made a test fail, as the tests are running? IE, after a test fails, I would like to see why, rather than waiting until all the tests are done. I've searched the doc and even looked at the code, and it seems the answer is no, but I'm just wondering if I'm missing something. Thanks! Margie From dan at tombstonezero.net Wed Aug 18 21:50:04 2010 From: dan at tombstonezero.net (Dan Sommers) Date: Thu, 19 Aug 2010 01:50:04 +0000 (UTC) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4C6C48F6.3040309@gmail.com> Message-ID: On Wed, 18 Aug 2010 16:56:22 -0400, AK wrote: > Contrast this with _one_ example that was repeated in this thread of > there being ground floor, 1st floor, 2nd, and so on. However! Consider > that ground floor is kind of different from the other floors. It's the > floor that's not built up over ground, but is already there -- in case > of the most primitive dwelling, you can put some sawdust over the > ground, put a few boards overhead and it's a "home", although probably > not a "house". But does it really have what can be officially called a > "floor"? That's the perfect example, although perhaps for an [apparently] unintended reason : I think that the notion of a qualitatively different "ground floor" is European, or at least that's the way I remember it from my high school French class way back in the late 1970s. In the U.S., when you walk into a building (even a very tall commercial building), that's the first floor, and when you go up a level, that's the second floor, and all the room/suite/office numbers are two hundred and something. I also seem to recall that some European buildings have a mezzanine floor between the ground floor and the floor whose reference number is 1, but again, high school was a long time ago. Dan From steve-REMOVE-THIS at cybersource.com.au Wed Aug 18 22:47:28 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 02:47:28 GMT Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> <4c69c715$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c6c9b3f$0$28637$c3e8da3@news.astraweb.com> On Wed, 18 Aug 2010 16:03:58 +0200, Frederic Rentsch wrote: > On Mon, 2010-08-16 at 23:17 +0000, Steven D'Aprano wrote: >> On Mon, 16 Aug 2010 20:40:52 +0200, Frederic Rentsch wrote: >> >> > How about >> > >> >>>> [obj for obj in dataList if obj.number == 100] >> > >> > That should create a list of all objects whose .number is 100. No >> > need to cycle through a loop. >> >> What do you think the list comprehension does, if not cycle through a >> loop? >> >> >> -- >> Steven > > What I think is that list comprehensions cycle through a loop a lot > faster than a coded loop (for n in ...:). I think measurement beats intuition: [steve at wow-wow ~]$ python -m timeit '[str(i) for i in xrange(100000)]' 10 loops, best of 3: 84 msec per loop [steve at wow-wow ~]$ python -m timeit 'L=[] > for i in xrange(100000): > L.append(str(i)) > ' 10 loops, best of 3: 105 msec per loop But wait... we're not comparing apples with apples. There's an extra name lookup in the for-loop that the list comp doesn't have. We can fix that: [steve at wow-wow ~]$ python -m timeit 'L=[]; append = L.append for i in xrange(100000): append(str(i)) ' 10 loops, best of 3: 86.7 msec per loop The difference between 84 and 86 msec is essentially measurement error. Hell, the difference between 84 and 104 msec is not terribly significant either. > As at the time of my post only > coded loops had been proposed and the OP was concerned about speed, I > thought I'd propose a list comprehension. Yes, but the OP was concerned with asymptotic speed (big-oh notation), and both a for-loop and a list-comp are both O(N). Frankly, I think the OP doesn't really know what he wants, other than premature optimization. It's amazing how popular that is :) -- Steven From steve-REMOVE-THIS at cybersource.com.au Wed Aug 18 22:58:12 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 02:58:12 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> Message-ID: <4c6c9dc4$0$28637$c3e8da3@news.astraweb.com> On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote: > Is the top team in the league the number 1 team -- or the number 0 team? > I have yet to hear anyone call the best team the number 0 team! Why is the top team the one with the lowest number? > Unfortunately, we're stuck with this goofy numbering system in many > languages. Fortunately, the trend is away from explicit indexing and > toward "for" loops when possible. Agreed on the second sentence there, but not on the first. There's nothing "goofy" about indexing items from 0. Yes, it does lead to slight more difficulty when discussing which item you want in *human* languages, but not in *programming* languages. The nth item is always the nth item. The only difference is whether n starts at 0 or 1, and frankly, if you (generic you, not you personally) can't learn which to use, you have no business pretending to be a programmer. -- Steven From erather at forth.com Wed Aug 18 23:05:24 2010 From: erather at forth.com (Elizabeth D Rather) Date: Wed, 18 Aug 2010 17:05:24 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: On 8/18/10 2:23 PM, Standish P wrote: > On Aug 17, 6:38 pm, John Passaniti wrote: > >> You asked if Forth "borrowed" lists from Lisp. It did not. In Lisp, >> lists are constructed with pair of pointers called a "cons cell". >> That is the most primitive component that makes up a list. Forth has >> no such thing; in Forth, the dictionary (which is traditionally, but >> not necessarily a list) is a data structure that links to the previous >> word with a pointer. > > Would you show me a picture, ascii art or whatever for Forth ? I know > what lisp lists look like so I dont need that for comparison. Forth > must have a convention and a standard or preferred practice for its > dicts. However, let me tell you that in postscript the dictionaries > can be nested inside other dictionaries and any such hiearchical > structure is a nested associative list, which is what linked list, > nested dictionaries, nested tables are. You indicated that you have a copy of Forth Application Techniques. Sections 8.1 and 8.2 cover this topic, with some drawings. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From python.list at tim.thechases.com Wed Aug 18 23:19:14 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 18 Aug 2010 22:19:14 -0500 Subject: Simple Problem but tough for me if i want it in linear time In-Reply-To: <4c6c9b3f$0$28637$c3e8da3@news.astraweb.com> References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> <4c69c715$0$11100$c3e8da3@news.astraweb.com> <4c6c9b3f$0$28637$c3e8da3@news.astraweb.com> Message-ID: <4C6CA2B2.5010406@tim.thechases.com> On 08/18/10 21:47, Steven D'Aprano wrote: > Frankly, I think the OP doesn't really know what he wants, other than > premature optimization. It's amazing how popular that is :) You see, the trick to prematurely optimizing is to have a good algorithm for prematurely optimizing...the real question them becomes "How can I optimize my premature-optimization algorithms to O(1) instead of O(newsgroup)?" :-) -tkc PS: I'm not positive, but O(newsgroup) may asymptotically approach O(log n) if the question is well formed, but O(2^n) if flaming, indentation/line-length preferences, the meaning of OOP, SQL-parameter escaping, McNugget combinations, or suggestions that Python is "just a scripting language" are involved... From dan.kluev at gmail.com Thu Aug 19 00:29:20 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Thu, 19 Aug 2010 15:29:20 +1100 Subject: expression in an if statement In-Reply-To: <201008190012.32074.thomas@jollybox.de> References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> <201008190012.32074.thomas@jollybox.de> Message-ID: On Thu, Aug 19, 2010 at 9:12 AM, Thomas Jollans wrote: > I doubt any actual Python implementation optimizes this -- how could it? > The > object "set" is clearly being called twice, and it happens to be called > with > the object "a" as a sole argument twice. What if "set" has side effects? A > compiler could only exclude this possibility if it knew exactly what "set" > will be at run time, which it can't. > > I expect that "set" and "a" have to be looked up twice, actually: > "set(a).union(b)" might rebind either one of them. This would be considered > a > very rude and inappropriate thing to do, but Python usually guarantees to > allow bad taste and behaviour. > > Yep. >>> def test(): ... a = [1] ... b = [1] ... if set(a).union(b) == set(a): pass ... >>> dis.dis(test) 2 0 LOAD_CONST 1 (1) 3 BUILD_LIST 1 6 STORE_FAST 0 (a) 3 9 LOAD_CONST 1 (1) 12 BUILD_LIST 1 15 STORE_FAST 1 (b) 4 18 LOAD_GLOBAL 0 (set) 21 LOAD_FAST 0 (a) 24 CALL_FUNCTION 1 27 LOAD_ATTR 1 (union) 30 LOAD_FAST 1 (b) 33 CALL_FUNCTION 1 36 LOAD_GLOBAL 0 (set) 39 LOAD_FAST 0 (a) 42 CALL_FUNCTION 1 45 COMPARE_OP 2 (==) 48 JUMP_IF_FALSE 4 (to 55) 51 POP_TOP 52 JUMP_FORWARD 1 (to 56) >> 55 POP_TOP >> 56 LOAD_CONST 0 (None) 59 RETURN_VALUE > I might be wrong on some points here, but this is what I expect the > expression > (set(a).union(b) == set(a)) has to do, in any conforming implementation of > Python. Please correct me if I'm wrong. > You can use dis module to let Python do compiling and explaining for you -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From russ.paielli at gmail.com Thu Aug 19 00:55:30 2010 From: russ.paielli at gmail.com (Russ P.) Date: Wed, 18 Aug 2010 21:55:30 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> <4c6c9dc4$0$28637$c3e8da3@news.astraweb.com> Message-ID: On Aug 18, 7:58?pm, Steven D'Aprano wrote: > On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote: > > Is the top team in the league the number 1 team -- or the number 0 team? > > I have yet to hear anyone call the best team the number 0 team! > > Why is the top team the one with the lowest number? How could it be otherwise? What is the highest number? Here's a couple of things I'd like to see just once before I die: 1. The winner of the championship game chanting, "We're number zero! We're number zero! 2. The loser of the championship game chanting, "We're number one! We're number one! > > > Unfortunately, we're stuck with this goofy numbering system in many > > languages. Fortunately, the trend is away from explicit indexing and > > toward "for" loops when possible. > > Agreed on the second sentence there, but not on the first. There's > nothing "goofy" about indexing items from 0. Yes, it does lead to slight > more difficulty when discussing which item you want in *human* languages, > but not in *programming* languages. The nth item is always the nth item. > The only difference is whether n starts at 0 or 1, and frankly, if you > (generic you, not you personally) can't learn which to use, you have no > business pretending to be a programmer. Maybe "goofy" was too derogatory, but I think you are rationalizing a bad decision, at least for high-level languages. I don't think programming languages should always mimic human languages, but this is one case where there is no advantage to doing otherwise. Why do you think "off by one" errors are so common? Because the darn indexing convention is off by one! And I'd still like to know if the "1st" element of aList is aList[0] or aList[1]. From abhijeet.thatte at gmail.com Thu Aug 19 00:59:07 2010 From: abhijeet.thatte at gmail.com (Abhijeet) Date: Wed, 18 Aug 2010 21:59:07 -0700 Subject: Need to import stuff In-Reply-To: References: Message-ID: <4C6CBA1B.2040701@gmail.com> Hi, Used imp. It worked. Thanks Daniel Kluev wrote: > > On Wed, Aug 18, 2010 at 9:40 AM, abhijeet thatte > > wrote: > > Hi, > > Thanks for the reply. But I guess it does not support nested file > paths. > If user gives 'abcd' then I need to import "//*Do/Stuff/abcd*/". > Out of which only /"abcd" is taken run time. Do and Stuff are fixed. / > /I got an error "/ImportError: Import by filename is not > supported.". Any solution?? > > > For complex importing, you can use imp module, > http://docs.python.org/library/imp.html > > Like this: > module_desc = imp.find_module(name, [base_path]) > module = imp.load_module(full_name, *module_desc) > > -- > With best regards, > Daniel Kluev > From ldo at geek-central.gen.new_zealand Thu Aug 19 01:05:44 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 19 Aug 2010 17:05:44 +1200 Subject: 79 chars or more? References: Message-ID: In message , BartC wrote: > (I tend to use 60x100 now, sometimes even wider; editing using 25x80 now > is like doing keyhole surgery...) And yet some people still think sticking to fewer columns is a good idea. From magguru.bangarayya at gmail.com Thu Aug 19 01:06:32 2010 From: magguru.bangarayya at gmail.com (Hot sex) Date: Wed, 18 Aug 2010 22:06:32 -0700 (PDT) Subject: Simple hack to get $5000 to your Paypal account Message-ID: <7238a8e3-e107-47cb-8914-bb993ef81079@i18g2000pro.googlegroups.com> Simple hack to get $5000 to your Paypal account At http://simplelivevideos.tk i have hidden the Paypal Form link in an image. in that website on Right Side below search box, click on image and enter your name and Paypal ID. From anthra.norell at bluewin.ch Thu Aug 19 02:40:08 2010 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Thu, 19 Aug 2010 08:40:08 +0200 Subject: expression in an if statement In-Reply-To: <201008190012.32074.thomas@jollybox.de> References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> <201008190012.32074.thomas@jollybox.de> Message-ID: <1282200008.2386.23.camel@hatchbox-one> On Thu, 2010-08-19 at 00:12 +0200, Thomas Jollans wrote: > On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: > > On 8/18/2010 11:24 AM, ernest wrote: > > > Hi, > > > > > > In this code: > > > > > > if set(a).union(b) == set(a): pass > > > > > > Does Python compute set(a) twice? > > > > CPython does. Shed Skin might optimize. Don't know > > about Iron Python. > > I doubt any actual Python implementation optimizes this -- how could it? And why should it if a programmer uses its facilities inefficiently. I would write >>> if set(a).issuperset (b): pass Frederic From nikos.the.gr33k at gmail.com Thu Aug 19 02:55:38 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Wed, 18 Aug 2010 23:55:38 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6BA2C4.4000309@gmail.com> Message-ID: I would expect that: "nikos" is a string, while, ("nikos") is a single element tuple. ["nikos"] is a single element list. That way we wouldn't be needing comma seperators. I just don't like it when "nikos" and ("nikos") is the same thing exactly. Parentheses are to be used to define a tuple and square brackets to define a list. Also i want to ask whats the difference between 'nikos', "nikos" and '''nikos''' for Python and whats the best way to use to enclose a string. ================================== if in my example instead of | cursor.execute('''SELECT host, hits, date FROM visitors WHERE | page=%s ORDER BY date DESC''', (page,) ) i use | cursor.execute('''SELECT host, hits, date FROM visitors WHERE | page=%s ORDER BY date DESC''', page) instead which i tend to like more, would there i have a problem? Also how how this part here page=%s doesn't need to be written as page='%s' which is the way i used to have it written with myssql string substitution? ========================================== And last but not least :-) is that http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors" =============================== don't reproduce the problem of actual deleting my data. I don't care losing it! I just want to see that happening with my own eyes! but if you try it you get an error. Maybe die to whitespace in the value of the page? How to write that propetly? Thank again fellows for ALL your help! From nikos.the.gr33k at gmail.com Thu Aug 19 03:10:00 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Thu, 19 Aug 2010 00:10:00 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6BA2C4.4000309@gmail.com> Message-ID: On 18 ???, 12:50, Cameron Simpson wrote: > > ("nikos",) is a single element tuple. > ["nikos"] is a single element list. > ["nikos",] is also a single element list, just written like the tuple. It makes more sense if i: "nikos" is just a string ("nikos") is a single element tuple ["nikos"] is also a single element list After all () used to define tuples and [] usedd to define lists. Why commas? Also is there a difference between 'nikos' or "nikos" or '''nikos''' ? What's and why best to use to enclose strings? =========================== Why in mysql string substitution example i have to use page='%s' and in the comma way(automatic mysql converetion i dont need the single quotes page=%s ? What is the diff? =========================== Why http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors" don't reproduce the problem of actual deleting my data to demonstrate the wrongness of string substitution in mysql queries? I don't care losing my data! The page is there to helpe me learn python and mysql. I just want to see that happening with my own eyes! Thanks again fols for all your precious help and explanations. From __peter__ at web.de Thu Aug 19 03:41:02 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 09:41:02 +0200 Subject: How to see intermediate fail results from unittest as tests are running? References: Message-ID: Margie Roginski wrote: > I am using unittest in a fairly basic way, where I have a single file > that simply defines a class that inherits from unittest.TestCase and > then within that class I have a bunch of methods that start with > "test". Within that file, at the bottom I have: > > if __name__ == "__main__": > unittest.main() > > This works fine and it runs all of the testxx() methods in my file. > As it runs it prints if the tests passed or failed, but if they fail, > it does not print the details of the assert that made them fail. It > collects this info up and prints it all at the end. > > Ok - my question: Is there any way to get unittest to print the > details of the assert that made a test fail, as the tests are > running? IE, after a test fails, I would like to see why, rather than > waiting until all the tests are done. Not exactly what you're asking for, but 2.7 has grown a --failfast option that tells unittest to stop on the first failure. For older Python versions you can use nose nosetests -x myscript.py at http://somethingaboutorange.com/mrl/projects/nose/0.11.2/ or the unittest backport at http://pypi.python.org/pypi/unittest2 Peter From forever.arihant at gmail.com Thu Aug 19 03:47:34 2010 From: forever.arihant at gmail.com (arihant nahata) Date: Thu, 19 Aug 2010 13:17:34 +0530 Subject: OpenCV_Problem In-Reply-To: References: <201008151914.34334.rami.chowdhury@gmail.com> Message-ID: > There is no file named _cv.dll file in the directory that you mentioned > what to do now.??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve-REMOVE-THIS at cybersource.com.au Thu Aug 19 03:52:30 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 07:52:30 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> <4c6c9dc4$0$28637$c3e8da3@news.astraweb.com> Message-ID: <4c6ce2be$0$11111$c3e8da3@news.astraweb.com> On Wed, 18 Aug 2010 21:55:30 -0700, Russ P. wrote: > On Aug 18, 7:58?pm, Steven D'Aprano T... at cybersource.com.au> wrote: >> On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote: >> > Is the top team in the league the number 1 team -- or the number 0 >> > team? I have yet to hear anyone call the best team the number 0 team! >> >> Why is the top team the one with the lowest number? > > How could it be otherwise? What is the highest number? If there are N teams, then the highest number is obviously N (if counting from 1) or N-1 (if from 0). In other words... why do we rank sporting teams Best to Worst rather than the other way around? [...] > Maybe "goofy" was too derogatory, but I think you are rationalizing a > bad decision, at least for high-level languages. I don't think > programming languages should always mimic human languages, but this is > one case where there is no advantage to doing otherwise. > > Why do you think "off by one" errors are so common? Because the darn > indexing convention is off by one! But you have that exactly backwards. Counting from 0 leads to fewer off by one errors for many tasks. (Of course, avoiding indexing in favour of iteration leads to even fewer off by one errors.) Anyway, in a feeble attempt to move this discussion somewhere -- anywhere! -- else: http://c2.com/cgi/wiki?FencePostError http://c2.com/cgi/wiki?WhyNumberingShouldStartAtZero http://c2.com/cgi/wiki?WhyNumberingShouldStartAtOne http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/zero and of course: http://xkcd.com/163/ -- Steven From stndshp at gmail.com Thu Aug 19 03:56:35 2010 From: stndshp at gmail.com (Standish P) Date: Thu, 19 Aug 2010 00:56:35 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> Message-ID: <8a12e419-447b-475d-9ec2-216f2d97c3cb@v41g2000yqv.googlegroups.com> On Aug 18, 5:38?pm, Keith Thompson wrote: > Standish P writes: > > On Aug 18, 12:30?pm, Elizabeth D Rather wrote: > [...] > >> Mostly it had a "snowball's chance" because it was never picked up by > >> the CS gurus who, AFAIK, never really took a serious look at it. > > > Its quite possible that the criticism is unfair, but dont you think > > that in part some responsibility must be borne by your organization in > > not doing a good job of education ? > [snip] > > Show me on what page does it explain how Forth implements dynamic > > binding or lexical binding and takes care of the scope of definition > > of the "nouns" ? > > [...] > > Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, > or comp.lang.python. ?Please trim the Newsgroups line. provide a rigorous proof that people are more interested in the nauseating nude pictures that you post of your mother in the newsgroups than in the subject of forth implementation. as a matter of fact a lot of people in various language groups are interested in implementation aspects and the languages borrow ideas from each other. now, get away from my thread and take away your odious posts which positively cause me nausea and vomiting. we will soon find out the game of stacks. > -- > Keith Thompson (The_Other_Keith) ks... at mib.org ? > Nokia > "We must do something. ?This is something. ?Therefore, we must do this." > ? ? -- Antony Jay and Jonathan Lynn, "Yes Minister" From mahaboobnisha at gmail.com Thu Aug 19 04:08:40 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Thu, 19 Aug 2010 01:08:40 -0700 (PDT) Subject: comp.lang.python Message-ID: www.127760.blogspot.com From a.j.romanista at gmail.com Thu Aug 19 04:29:51 2010 From: a.j.romanista at gmail.com (ata.jaf) Date: Thu, 19 Aug 2010 01:29:51 -0700 (PDT) Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> Message-ID: <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> On Aug 17, 11:55?pm, Thomas Jollans wrote: > On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > > > I am developing a little program in Mac with wxPython. > > But I have problems with the characters that are not in ASCII. Like > > some special characters in French or Turkish. > > So I am looking for a way to solve this. Like an encoding standard > > that supports all languages. Or some other way. > > Anything that supports all of Unicode will do. Like UTF-8. If your text is > mostly Latin, then just go for UTF-8, if you use other alphabets extensively, > you might want to consider UTF-16, which might the use a little less space. OK, I used UTF-8. I write a line of strings in the source code and I want my program to show that as an output on GUI. And this line of strings includes a character like "?". But I see that in GUI this character is replaced with another strange characters. I mean it doesn't work. And when I try to use UTF-16, I get an syntax error that declares "UTF-16 stream does not start with BOM". From jak at isp2dial.com Thu Aug 19 04:31:34 2010 From: jak at isp2dial.com (John Kelly) Date: Thu, 19 Aug 2010 08:31:34 +0000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> <8a12e419-447b-475d-9ec2-216f2d97c3cb@v41g2000yqv.googlegroups.com> Message-ID: On Thu, 19 Aug 2010 00:56:35 -0700 (PDT), Standish P wrote: >On Aug 18, 5:38?pm, Keith Thompson wrote: >> Standish P writes: >> > Show me on what page does it explain how Forth implements dynamic >> > binding or lexical binding and takes care of the scope of definition >> > of the "nouns" ? >> Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, >> or comp.lang.python. ?Please trim the Newsgroups line. >fact a lot of people in various language groups are interested in >implementation aspects and the languages borrow ideas from each other. Standish sounds like Spinoza in disguise. Nevertheless, ngs like c.l.c need more diversity. Standards minutia is boring. -- Web mail, POP3, and SMTP http://www.beewyz.com/freeaccounts.php From steve-REMOVE-THIS at cybersource.com.au Thu Aug 19 04:48:06 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 08:48:06 GMT Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: <4c6cefc6$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote: > On Aug 17, 11:55?pm, Thomas Jollans wrote: >> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: >> >> > I am developing a little program in Mac with wxPython. But I have >> > problems with the characters that are not in ASCII. Like some special >> > characters in French or Turkish. So I am looking for a way to solve >> > this. Like an encoding standard that supports all languages. Or some >> > other way. >> >> Anything that supports all of Unicode will do. Like UTF-8. If your text >> is mostly Latin, then just go for UTF-8, if you use other alphabets >> extensively, you might want to consider UTF-16, which might the use a >> little less space. > > OK, I used UTF-8. > I write a line of strings in the source code Do you have a source code encoding line at the start of your script? http://www.python.org/dev/peps/pep-0263/ > and I want my program to > show that as an output on GUI. And this line of strings includes a > character like "?". But I see that in GUI this character is replaced > with another strange characters. I mean it doesn't work. And when I try > to use UTF-16, I get an syntax error that declares "UTF-16 stream does > not start with BOM". What GUI are you using? Please COPY AND PASTE (do not retype) the EXACT error message you get, including the entire traceback. -- Steven From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 19 04:53:57 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 19 Aug 2010 10:53:57 +0200 Subject: Pop return from stack? In-Reply-To: <4c673375$0$11100$c3e8da3@news.astraweb.com> References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c673375$0$11100$c3e8da3@news.astraweb.com> Message-ID: <4c6cf114$0$3325$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > > Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in > Python, even VB in Python, but this is the first time I've meet some one > who wants to write assembler in Python :) > +1 QOTW From martin at v.loewis.de Thu Aug 19 04:55:54 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Thu, 19 Aug 2010 10:55:54 +0200 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: <4C6CF19A.2060703@v.loewis.de> > I write a line of strings in the source code and I want my program to > show that as an output on GUI. And this line of strings includes a > character like "?". Make sure you use Unicode literals in your source code, i.e. u"?". HTH, Martin From bauketilma at gmail.com Thu Aug 19 04:56:02 2010 From: bauketilma at gmail.com (Duim) Date: Thu, 19 Aug 2010 01:56:02 -0700 (PDT) Subject: when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray' References: Message-ID: On Aug 18, 10:03?pm, Nobody wrote: > On Wed, 18 Aug 2010 05:56:27 -0700, Duim wrote: > > Although I'm sure somewhere this issue is discussed in this (great) > > group, I didn't know the proper search words for it (although I > > tried). > > > I'm using python (2.6) scientifically mostly, and created a simple > > class to store time series (my 'Signal' class). > > I need this class to have a possibility to get multiplied by an array, > > but pre and post multiplication have different mathematical outcomes > > ( basically A* B != B*A ) . > > > Post multiplication by an array works fine defining __mul__ in the > > Signal class, but pre multiplication does not. It keeps trying to > > multiply all elements separately instead to send this array to my > > __rmul__ function. > > > How can I fix this without the need for a separate > > 'multiplysignal(A,B)' function? > > Make Signal a subclass of numpy.ndarray. If one operand is a subclass of > the other, its __rmul__ will be preferred to the parent's __mul__. > > In the absence of a subclass-superclass relationship, the LHS's __mul__ is > preferred to the RHS's __rmul__, so the RHS's __rmul__ is only called if > the LHS lacks a __mul__ method or if the method refuses its argument > (returns NotImplemented). > > Likewise for other "reflected" methods. Great, many thanks. It seems to work well. For others looking into the same issue: http://www.scipy.org/Subclasses From iamforufriends at gmail.com Thu Aug 19 05:29:22 2010 From: iamforufriends at gmail.com (only adults no kids plzzz) Date: Thu, 19 Aug 2010 02:29:22 -0700 (PDT) Subject: adults only... no kida please. wanna meet me, sex with me. come...... Message-ID: <4f19162c-c645-430d-b3f8-d099caa783b1@h17g2000pri.googlegroups.com> adults only... no kida please. wanna meet me, sex with me. come...... just click.... start.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From fetchinson at googlemail.com Thu Aug 19 06:25:17 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 19 Aug 2010 12:25:17 +0200 Subject: path to data files Message-ID: If a python module requires a data file to run how would I reference this data file in the source in a way that does not depend on whether the module is installed system-wide, installed in $HOME/.local or is just placed in a directory from where the interpreter is fired up? I'd like to always keep the python source and the data file in the same directory, be it /usr/lib/python2.6/site-packages, $HOME/.local/lib/python2.6/site-packages or /arbitrary/path/to/somewhere. If the data file is called 'foo' and I simply do open('foo') in the python source file this will not work if they are both installed either system-wide or locally. More precisely if the module is called 'foo.py', data file called 'foo', they are both in /usr/lib/python2.6/site-packages and if foo.py I have open('foo') I'll get a file not found error. Any ideas? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From dan.kluev at gmail.com Thu Aug 19 06:32:49 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Thu, 19 Aug 2010 21:32:49 +1100 Subject: path to data files In-Reply-To: References: Message-ID: On Thu, Aug 19, 2010 at 9:25 PM, Daniel Fetchinson < fetchinson at googlemail.com> wrote: > If a python module requires a data file to run how would I reference > this data file in the source in a way that does not depend on whether > the module is installed system-wide, installed in $HOME/.local or is > just placed in a directory from where the interpreter is fired up? I'd > like to always keep the python source and the data file in the same > directory, be it /usr/lib/python2.6/site-packages, > $HOME/.local/lib/python2.6/site-packages or > /arbitrary/path/to/somewhere. > open(os.path.join(os.path.dirname(__file__), 'foo')) -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From spinoza1111 at yahoo.com Thu Aug 19 07:14:42 2010 From: spinoza1111 at yahoo.com (spinoza1111) Date: Thu, 19 Aug 2010 04:14:42 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: On Aug 18, 1:44?am, James Kanze wrote: > On Aug 17, 6:21 pm, Standish P wrote: > > > > Garbage collection doesn't use a stack. It uses a "heap", > > > which is in the abstract a collection of memory blocks of > > > different lengths, divided into two lists, generally > > > represented as linked lists: > > > 1. ?A list of blocks that are free and may be used to store > > > new data > > > 2. ?A list of blocks that are in use, or haven't been freed (yet) > > Is this all that a heap is or is there more to it ? > > There are many different ways to implement a heap. ?The above is > not a good one, and I doubt that it's really used anywhere. Actually, that's the only way to implement a heap in the abstract. Forest and trees, mate. Mathematically a heap is a block of storage, a list of free blocks and a list of allocated blocks. All the rest is detail for the little techies to normally, get wrong. The confusion between scientific and technical progress is a mirror of the (far more serious) confusion between scientific progress and ethical advance. Sure, when you free a block it is a good idea to see if you can join it with its neighbors to get the biggest "bang for the buck". This, again, is a detail relative to the grand plan which gives only techies a hard-on, because the way scientific is confused with technical progress is, in Foucault's terms, capillary. Part of ethical regression is the overemphasis on efficiency and metaphors taken from America's genocidal first use of nuclear weapons. > > > I have been looking for simple but complete explanation of > > heap for a while and not gotten to it. > > Complete in what sense? ?The basic principle of how to use it is > simple. ?As for how to implement it, there are many different > algorithms that can be used. Correct, for a change. > > > I think I am looking for a stack allocation on the same > > pattern. > > Stack allocation is far, far simpler (usually). And very different. > > > In a disk, a file is fragmented in many contiguous blocks and > > is accessed automatically. > > At the system level, the same thing holds for memory, and the > actual physical memory is "fragmented" into contiguous blocks, > each the size of a page. ?The MMU (hardware) makes this > transparent to user programs, however. > > > > There is no way you could do memory management of all but the most > > > trivial and fixed-length data chunks using a stack. > > The length isn't the issue. ?The order of allocation and freeing > is. ?(For many specific uses, stack based allocators can and > have been used, but they don't work for generally allocation.) > > -- > James Kanze From fetchinson at googlemail.com Thu Aug 19 07:18:15 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 19 Aug 2010 13:18:15 +0200 Subject: path to data files In-Reply-To: References: Message-ID: >> If a python module requires a data file to run how would I reference >> this data file in the source in a way that does not depend on whether >> the module is installed system-wide, installed in $HOME/.local or is >> just placed in a directory from where the interpreter is fired up? I'd >> like to always keep the python source and the data file in the same >> directory, be it /usr/lib/python2.6/site-packages, >> $HOME/.local/lib/python2.6/site-packages or >> /arbitrary/path/to/somewhere. >> > > open(os.path.join(os.path.dirname(__file__), 'foo')) Thanks a lot! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From python.list at tim.thechases.com Thu Aug 19 07:32:55 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Aug 2010 06:32:55 -0500 Subject: String substitution VS proper mysql escaping In-Reply-To: References: <4C6BA2C4.4000309@gmail.com> Message-ID: <4C6D1667.7090904@tim.thechases.com> On 08/19/10 02:10, ????? wrote: >> ("nikos",) is a single element tuple. >> ["nikos"] is a single element list. >> ["nikos",] is also a single element list, just written like the tuple. > > It makes more sense if i: > > "nikos" is just a string > ("nikos") is a single element tuple > ["nikos"] is also a single element list > > After all () used to define tuples and [] usedd to define lists. Why > commas? You have to look at the other side: what *else* they're used for. Python also uses () to override order of operations (and to call functions, but that's contextually different) which can occur in the same context as tuples, while [] are used only within contexts where they can be disambiguated. Going back to one of the originals example posted in this thread: (1) + (2) do you think this should yield (1, 2) or 3? It would be crazy if evaluation of (3*14) + (7*21) was reduced, treated as "(42) + (147)" and then reduced to "(42,147)" instead of 189. So Python needs a way to express that you *explicitly* mean "this is one of those rare one-element tuples, not an order of operations prioritization": (1,) + (2,) to return "(1,2)" > Also is there a difference between 'nikos' or "nikos" or '''nikos''' ? > What's and why best to use to enclose strings? Internally, there's no difference other than how easily you can include " or ' characters in your string. Thus you might write: with_dquote = 'He said "Hello"' with_apos = "It's 2:00am" with_both1 = """She said "Don't touch me" to her boss""" with_both2 = '''She said "Don't touch me" to her boss''' You can also prefix any of them with "r" such as file_path = r"c:\path\to\file.txt" file_path = r'c:\path\to\file.txt file_path = r"""c:\path\to\file.txt""" file_path = r'''c:\path\to\file.txt''' to alter how "\" are treated. Otherwise, if it doesn't make a difference, I tend to use C-ish conventions of using " for strings and ' for single characters: if 'w' in "hello world": but the important/kind thing is to be internally consistent to make your own life easier. :) -tkc From __peter__ at web.de Thu Aug 19 07:35:01 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 13:35:01 +0200 Subject: Unsupported Format Character '&' (0x26) References: Message-ID: Andrew Evans wrote: > On Wed, Aug 18, 2010 at 4:35 PM, Andrew Evans wrote: > >> I get an error message "Unsupported Format Character '&' (0x26)" I >> narrowed it down to these two variables >> >> any idea how to fix it? >> >> SEARCH_URL_0 = "http://search.yahoo.com/search...?p=%(query)..." > nvm I got it by adding s and d respectively after each value eg %(query)s If you want to handle this reliably have a look at urllib.urlencode(). Peter From sschwarzer at sschwarzer.net Thu Aug 19 07:41:11 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 19 Aug 2010 13:41:11 +0200 Subject: String substitution VS proper mysql escaping In-Reply-To: References: <4C6BA2C4.4000309@gmail.com> Message-ID: <4C6D1857.1070307@sschwarzer.net> Hi ?????, On 2010-08-19 09:10, ????? wrote: > On 18 ???, 12:50, Cameron Simpson wrote: >> >> ("nikos",) is a single element tuple. >> ["nikos"] is a single element list. >> ["nikos",] is also a single element list, just written like the tuple. > > It makes more sense if i: > > "nikos" is just a string > ("nikos") is a single element tuple > ["nikos"] is also a single element list > > After all () used to define tuples and [] usedd to define lists. Why > commas? Because parentheses are also used to group expressions. For example, >>> 2 * (1+2) 6 If it were as you would like, the result would have been (3, 3) So because inside parentheses already denotes an expression you have to add a comma to distinguish a one-element tuple from an expression. Stefan From agidak at gmail.com Thu Aug 19 08:22:23 2010 From: agidak at gmail.com (Agida Kerimova) Date: Thu, 19 Aug 2010 17:22:23 +0500 Subject: How do I make python test.py work without a syntax error msg? Message-ID: I am new to programming/python and have been having some difficulties getting started. I can't seem to run scripts without a syntax error msg. When I drag the file to the IDLE launcher or run the module it works, but when I actually type it I get an error msg. I've been told that the path to python executable is missing or that i have to specify the path but im not sure how to do this. I read some articles online but they are not very clear. A lot of the articles talk about doing this on windows but i have a mac. Also when I type python at the prompt it starts. Can someone please let me know what Im doing wrong or give me some advice? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.gonnerman at newcenturycomputers.net Thu Aug 19 08:30:03 2010 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 19 Aug 2010 07:30:03 -0500 Subject: [Python] Unsupported Format Character '&' (0x26) In-Reply-To: References: Message-ID: <4C6D23CB.70805@newcenturycomputers.net> On 08/18/2010 06:35 PM, Andrew Evans wrote: > I get an error message "Unsupported Format Character '&' (0x26)" I > narrowed it down to these two variables > > any idea how to fix it? > > SEARCH_URL_0 = > "http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)&fr=sfp&fr2=&iscqry= > " > NEXT_PAGE_0 = > "http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)&fr=sfp&xargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2E&pstart=%(start)&b=11 > " > Not %(query) Should be %(query)s The 's' means "string." -- Chris. From alain at dpt-info.u-strasbg.fr Thu Aug 19 08:30:34 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 19 Aug 2010 14:30:34 +0200 Subject: path to data files References: Message-ID: <87wrrm9445.fsf@dpt-info.u-strasbg.fr> Daniel Fetchinson writes: > If a python module requires a data file to run how would I reference > this data file in the source in a way that does not depend on whether > the module is installed system-wide, installed in $HOME/.local or is > just placed in a directory from where the interpreter is fired up? sys.path[0] is supposed to contain the script's directory. -- Alain. From smirnoffs at gmail.com Thu Aug 19 08:53:30 2010 From: smirnoffs at gmail.com (Sergey Smirnov) Date: Thu, 19 Aug 2010 15:53:30 +0300 Subject: How do I make python test.py work without a syntax error msg? In-Reply-To: References: Message-ID: *when I actually * *type it I get an error msg* Did you type python commands in a bash console? In case you did, you should run python interactive console instead. Just type python in terminal window and than you'll be able interactively run statements. If you have your script saved in a file, for instance, script.py, to run it on your Mac you should type: $ python script.py It would be easier to understand you if you'll post errors messages here. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anton at mips.complang.tuwien.ac.at Thu Aug 19 09:45:07 2010 From: anton at mips.complang.tuwien.ac.at (Anton Ertl) Date: Thu, 19 Aug 2010 13:45:07 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <7xwrrnmzkx.fsf@ruckus.brouhaha.com> <4c6c4ec8$0$1623$742ec2ed@news.sonic.net> Message-ID: <2010Aug19.154507@mips.complang.tuwien.ac.at> John Nagle writes: > In the superscalar era, there's not much of an advantage to avoiding >stack accesses. Apart from 4stack, I am not aware of a superscalar stack machine (and 4stack is more of an LIW than a superscalar). OTOH, if by stack accesses you mean memory accesses through the stack pointer on a register machine, then evidence contradicts your claim. E.g., if we can keep one or two more of Gforth's VM's registers in real registers rather than on the stack of an IA32 CPU, we see significant speedups (like a factor of 2). >x86 superscalar machines have many registers not >visible to the program, as the fastest level of cache. They have a data cache for memory accesses (about 3 cycles load-to-use latency on current CPUs for these architectures), and they have rename registers (not visible to programmers) that don't cache memory. They also have a store buffer with store-to-load forwarding, but that still has no better load-to-use latency. >In practice, >the top of the stack is usually in CPU registers. Only if the Forth system is written that way. > The "huge number >of programmer-visible register" machines like SPARCs turned out to be >a dead end. Really? Architectures with 32 programmer-visible registers like SPARC (but, unlike SPARC, without register windows) are quite successful in embedded systems (e.g., MIPS, SPARC). >So did making all the instructions the same width; it >makes the CPU simpler, but not faster, and it bulks up the program >by 2x or so. In the beginning it also made the CPU faster. As for the bulk, here's some data from <2007Dec11.202937 at mips.complang.tuwien.ac.at>; it's the text (code) size of /usr/bin/dpkg in a specific version of the dpkg package: .text section 98132 dpkg_1.14.12_hurd-i386.deb 230024 dpkg_1.14.12_m68k.deb 249572 dpkg_1.14.12_amd64.deb 254984 dpkg_1.14.12_arm.deb 263596 dpkg_1.14.12_i386.deb 271832 dpkg_1.14.12_s390.deb 277576 dpkg_1.14.12_sparc.deb 295124 dpkg_1.14.12_hppa.deb 320032 dpkg_1.14.12_powerpc.deb 351968 dpkg_1.14.12_alpha.deb 361872 dpkg_1.14.12_mipsel.deb 371584 dpkg_1.14.12_mips.deb 615200 dpkg_1.14.12_ia64.deb Sticking with the Linux packages (i.e., not the Hurd one), the range in code size increase over the i386 code is 0.97 (ARM) to 1.41 (MIPS) for the classical architectures with fixed-size instructions (RISCs). Only the IA64 has a code size increase by a factor of 2.33. Note that code size is not everything that's in a program binary, and the rest should be unaffected by whether the instructions are fixed-size or variable-sized, so the overall effect on the binary will be smaller. - anton -- M. Anton Ertl http://www.complang.tuwien.ac.at/anton/home.html comp.lang.forth FAQs: http://www.complang.tuwien.ac.at/forth/faq/toc.html New standard: http://www.forth200x.org/forth200x.html EuroForth 2010: http://www.euroforth.org/ef10/ From benjamin.kaplan at case.edu Thu Aug 19 10:08:28 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 19 Aug 2010 10:08:28 -0400 Subject: How do I make python test.py work without a syntax error msg? In-Reply-To: References: Message-ID: On Thu, Aug 19, 2010 at 8:22 AM, Agida Kerimova wrote: > I am new to programming/python and have been having some difficulties > getting started. I can't seem to run scripts without a syntax error msg. > When I drag the file to the IDLE launcher or run the module it works, but > when I actually type it I get an error msg. I've been told ?that the path to > python executable is missing or that i have to specify the path but im not > sure how to do this. I read some articles online but they are not very > clear. A lot of the articles talk about doing this on windows but i have a > mac. Also when I type python at the prompt it starts. Can someone please let > me know what Im doing wrong or give me some advice? > Thanks! > -- Are you trying to run ./test.py? If so, make sure you use a shebang line. The Unix shell doesn't care about those silly little things called file extensions- that's just part of the file name, after all. Any executed file will use the shell (bash on OS X) unless you specify otherwise. Add the following line to the top of the file: #!/usr/bin/env python Or, just call the Python interpreter directly python test.py From smirnoffs at gmail.com Thu Aug 19 10:15:19 2010 From: smirnoffs at gmail.com (Sergey Smirnov) Date: Thu, 19 Aug 2010 17:15:19 +0300 Subject: How do I make python test.py work without a syntax error msg? In-Reply-To: References: Message-ID: I see. Your script begins with a string: $ python test.py It's not a valid python code. Maybe you just copied this text to your script accidentally. Try to delete the first string. Can you send a few first strings of your script? On Thu, Aug 19, 2010 at 17:05, Agida Kerimova wrote: > this is what it looks like > > > On Thu, Aug 19, 2010 at 7:01 PM, Agida Kerimova wrote: > >> Hi, I don't know how to work in a non bash console... I typed python in a >> terminal window and all but it didn't work... >> >> >> >> >> >> >> On Thu, Aug 19, 2010 at 5:53 PM, Sergey Smirnov wrote: >> >>> *when I actually * >>> >>> *type it I get an error msg* >>> >>> Did you type python commands in a bash console? In case you did, you >>> should run python interactive console instead. Just type python in terminal >>> window and than you'll be able interactively run statements. >>> >>> If you have your script saved in a file, for instance, script.py, to run >>> it on your Mac you should type: >>> $ python script.py >>> >>> It would be easier to understand you if you'll post errors messages here. >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwutzke at web.de Thu Aug 19 10:21:56 2010 From: kwutzke at web.de (Karsten Wutzke) Date: Thu, 19 Aug 2010 07:21:56 -0700 (PDT) Subject: Contains/equals Message-ID: Hello, I have an object which has a list of other complex objects. How do I best achieve a complex "contains" comparison based on the object's class? In Java terms, I'm looking for an equivalent to equals(Object) in Python. Does a similar thing exist? Directions appreciated. Karsten From kara at kara-moon.com Thu Aug 19 10:27:34 2010 From: kara at kara-moon.com (Rony) Date: Thu, 19 Aug 2010 07:27:34 -0700 (PDT) Subject: Creating a PYD file Message-ID: Is a PYD file created from Pyrex faster in execution then a PYD file created from python source ? Tia Rony From invalid at invalid.invalid Thu Aug 19 10:42:06 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 19 Aug 2010 14:42:06 +0000 (UTC) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <298dc1af-9feb-4e18-bbe1-7201e7fb2fe5@q22g2000yqm.googlegroups.com> <4c6c9dc4$0$28637$c3e8da3@news.astraweb.com> Message-ID: On 2010-08-19, Russ P. wrote: > And I'd still like to know if the "1st" element of aList is aList[0] > or aList[1]. aList[0] -- Grant Edwards grant.b.edwards Yow! I'm definitely not at in Omaha! gmail.com From downaold at gmail.com Thu Aug 19 10:42:32 2010 From: downaold at gmail.com (Roald de Vries) Date: Thu, 19 Aug 2010 16:42:32 +0200 Subject: 79 chars or more? In-Reply-To: <4C6BA05C.2000906@sequans.com> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <20100817114256.d960549b.darcy@druid.net> <4C6BA05C.2000906@sequans.com> Message-ID: <18620C4D-A6F9-4248-ADF7-5CE3EDDE4491@gmail.com> Dear Jean-Michel, On Aug 18, 2010, at 10:57 AM, Jean-Michel Pichavant wrote: > At least, if you still want to stick with 79 chars, do something like > > text = find(response, 'MPNExpirationDate', ).text > self.expiration_date = translate_date(text,'%Y-%m-%d', '%m%d%Y') I don't necessarily like this example *so* much. I have no real problem with it, and maybe would write it myself sometimes, but I'm curious what people think of the following reasoning. I think that, for optimal readability, variable names should reflect the role if the function/class/module of the variable they refer to. If you stick to this convention, a function can normally be read very easily by just scanning through the left part of assignment statements. In your case, it looks like text would better be called expiration_text, or something like that. But what I would like better, is: self.expiration_date = translate_date( text = find(response, 'MPNExpirationDate', ).text, format1 = '%Y-%m-%d', # I don't know the argument name format2 = '%m%d%Y', # ... and of this one neither ) Moreover, the 'text = ...'-like statement, that are only used in the one statement after it, often interrupt a (more) logical sequence of variable assignments, and make your program a bit less readable. Cheers, Roald From __peter__ at web.de Thu Aug 19 10:47:46 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 16:47:46 +0200 Subject: Contains/equals References: Message-ID: Karsten Wutzke wrote: > I have an object which has a list of other complex objects. How do I > best achieve a complex "contains" comparison based on the object's > class? In Java terms, I'm looking for an equivalent to equals(Object) > in Python. Does a similar thing exist? Directions appreciated. I can't infer from your question whether you already know about __contains__(). So there: >>> class Cornucopia: ... def __contains__(self, other): ... return True ... >>> c = Cornucopia() >>> 42 in c True >>> "cherry pie" in c True >>> c in c True From kwutzke at web.de Thu Aug 19 10:53:32 2010 From: kwutzke at web.de (Karsten Wutzke) Date: Thu, 19 Aug 2010 07:53:32 -0700 (PDT) Subject: Contains/equals References: Message-ID: <8b1f1392-9d94-46cf-bd1b-5b041d0cb508@f42g2000yqn.googlegroups.com> On Aug 19, 4:47?pm, Peter Otten <__pete... at web.de> wrote: > Karsten Wutzke wrote: > > I have an object which has a list of other complex objects. How do I > > best achieve a complex "contains" comparison based on the object's > > class? In Java terms, I'm looking for an equivalent to equals(Object) > > in Python. Does a similar thing exist? Directions appreciated. > > I can't infer from your question whether you already know about > __contains__(). So there: > > >>> class Cornucopia: > > ... ? ? def __contains__(self, other): > ... ? ? ? ? ? ? return True > ...>>> c = Cornucopia() > >>> 42 in c > True > >>> "cherry pie" in c > True > >>> c in c > > True Whoops that easy... Thanks! Karsten From mehgcap at gmail.com Thu Aug 19 11:00:03 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 19 Aug 2010 11:00:03 -0400 Subject: Contains/equals In-Reply-To: References: Message-ID: On 8/19/10, Peter Otten <__peter__ at web.de> wrote: > Karsten Wutzke wrote: > >> I have an object which has a list of other complex objects. How do I >> best achieve a complex "contains" comparison based on the object's >> class? In Java terms, I'm looking for an equivalent to equals(Object) >> in Python. Does a similar thing exist? Directions appreciated. > > I can't infer from your question whether you already know about > __contains__(). So there: > >>>> class Cornucopia: > ... def __contains__(self, other): > ... return True > ... >>>> c = Cornucopia() >>>> 42 in c > True >>>> "cherry pie" in c > True >>>> c in c > True You may also want to use the double equals operator; in Java, one thing I wish I could do is String s="abc"; String t="def"; if(s==t)... In Python, as I understand it, you can define this behavior. class c(object): def __init__(self, a=1, b=2): self.a=a; self.b=b def __eq__(self, obj): if self.a==obj.a and self.b==obj.b: return True return False You can now say: obj1=c() obj2=c() print(obj1==obj2) #prints True > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From cri at tiac.net Thu Aug 19 11:25:51 2010 From: cri at tiac.net (Richard Harter) Date: Thu, 19 Aug 2010 15:25:51 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> <518b97c6-78ad-4ce9-9967-c7f72ea74109@5g2000yqz.googlegroups.com> Message-ID: <4c6d356f.608280081@text.giganews.com> On Wed, 18 Aug 2010 01:39:09 -0700 (PDT), Nick Keighley wrote: >On 17 Aug, 18:34, Standish P wrote: >> How are these heaps being implemented ? Is there some illustrative >> code or a book showing how to implement these heaps in C for example ? > >any book of algorithms I'd have thought > >http://en.wikipedia.org/wiki/Dynamic_memory_allocation >http://www.flounder.com/inside_storage_allocation.htm > >I've no idea how good either of these is The wikipedia page is worthless. The flounder page has substantial meat, but the layout and organization is a mess. A quick google search didn't turn up much that was general - most articles are about implementations in specific environments. From lists at cheimes.de Thu Aug 19 11:27:05 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 19 Aug 2010 17:27:05 +0200 Subject: Contains/equals In-Reply-To: References: Message-ID: Am 19.08.2010 17:00, schrieb Alex Hall: > In Python, as I understand it, you can define this behavior. > > class c(object): > def __init__(self, a=1, b=2): > self.a=a; self.b=b > > def __eq__(self, obj): > if self.a==obj.a and self.b==obj.b: return True > return False Yes, but you have to return NotImplemented when your type doesn't know how to handle the other type. class C(object): def __eq__(self, other): if not isinstance(other, C): return NotImplemented return self.a == other.a Christian From nikos.the.gr33k at gmail.com Thu Aug 19 11:42:02 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Thu, 19 Aug 2010 18:42:02 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D1667.7090904@tim.thechases.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> Message-ID: <4C6D50CA.5060604@gmail.com> ???? 19/8/2010 2:32 ??, ?/? Tim Chase ??????: > So Python needs a way to express that you *explicitly* mean "this is > one of those rare one-element tuples, not an order of operations > prioritization": > > (1,) + (2,) > to return "(1,2)" Yes i can see the difference now!! I just had to look at the big picture here! There is no other way of seperating this for that. > You can also prefix any of them with "r" such as > > file_path = r"c:\path\to\file.txt" > file_path = r'c:\path\to\file.txt > file_path = r"""c:\path\to\file.txt""" > file_path = r'''c:\path\to\file.txt''' 'r' is to avoid escaping backslashes only or other special charcaters as well? As for the string i noticed that if i'am to mix single quotes and double quotes(any number of them not just always pairs) and backslashes and other special stuff in them then i'm best off using 3-sinlge-quotes like name='''My name is "Nikos" and i'am from Thessaloniki\Greece''' The above example can only be written by using 3-single quoting right? Not by pairs of single or double quotes, correct? And i dont have to use the 'r' in fornt of it too. ======================= Also if you please comment on my mysql string substitution example i've posted in my previous post just to make it work. I want it to be able to delete my data but it fails when i try to http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * FROM visitors" please try it yourself, i dont mind lossign the data i just want to see if this mysql in jection can actually work. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Thu Aug 19 11:44:29 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Thu, 19 Aug 2010 18:44:29 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D1667.7090904@tim.thechases.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> Message-ID: <4C6D515D.2020304@gmail.com> ???? 19/8/2010 2:32 ??, ?/? Tim Chase ??????: > (1,) + (2,) > > to return "(1,2)" This is actually joining two single element tuples (1,) and (2, ) to a new bigger tuple of two elements, correct? From margieroginski at gmail.com Thu Aug 19 11:45:52 2010 From: margieroginski at gmail.com (Margie Roginski) Date: Thu, 19 Aug 2010 08:45:52 -0700 (PDT) Subject: How to see intermediate fail results from unittest as tests are running? References: Message-ID: <7cc5e61e-604e-4b10-87f0-4104296ca909@v41g2000yqv.googlegroups.com> On Aug 19, 12:41?am, Peter Otten <__pete... at web.de> wrote: > Margie Roginski wrote: > > I am using unittest in a fairly basic way, where I have a single file > > that simply defines a class that inherits from unittest.TestCase and > > then within that class I have a bunch of methods that start with > > "test". ?Within that file, at the bottom I have: > > > if __name__ == "__main__": > > ? ? unittest.main() > > > This works fine and it runs all of the testxx() methods in my file. > > As it runs it prints if the tests passed or failed, but if they fail, > > it does not print the details of the assert that made them fail. ?It > > collects this info up and prints it all at the end. > > > Ok - my question: Is there any way to get unittest to print the > > details of the assert that made a test fail, as the tests are > > running? ?IE, after a test fails, I would like to see why, rather than > > waiting until all the tests are done. > > Not exactly what you're asking for, but 2.7 has grown a --failfast option > that tells unittest to stop on the first failure. For older Python versions > you can use nose > > nosetests -x myscript.py > > athttp://somethingaboutorange.com/mrl/projects/nose/0.11.2/ > or the unittest backport athttp://pypi.python.org/pypi/unittest2 > > Peter Thanks for the pointers, I will give those a try. Margie From vicente.soler at gmail.com Thu Aug 19 11:55:09 2010 From: vicente.soler at gmail.com (vsoler) Date: Thu, 19 Aug 2010 08:55:09 -0700 (PDT) Subject: Reading the access attributes of directories in Windows Message-ID: Hello everyone! I need to read, for each of the directories in a shared file server unit, who has access to the directories and what type of access privileges. This is something that I can easily do interactively in my Windows Document Explorer by right clicking a single directory, clicking on Properties, then on Security. There I can see the Users and Group of Users that have access to the selected directory, as well as the type of access to that directory (Read/Write/eXecute etc.) Since I have to prepare a new access scheme, I first need to read what the current situation is. I've been looking in the "os" library, and found the "os.chmod" method but I am not sure that it is going to give me what I need. Should I also used library "stat"? So far I have not been able to find my way to the solution of this problem. Googling the web, I have seen that some examples provive some kind of information but using codes (755 or 0577) that I shoud translate to some form of understandable text messages. I think that my problem consists of finding the correct library/method to get the solution. Can anybody help? Thank you Using Python 3.1 on Windows Vista From python.list at tim.thechases.com Thu Aug 19 11:58:07 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Aug 2010 10:58:07 -0500 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D50CA.5060604@gmail.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> <4C6D50CA.5060604@gmail.com> Message-ID: <4C6D548F.2050303@tim.thechases.com> On 08/19/10 10:42, Nik Gr wrote: >> You can also prefix any of them with "r" such as >> >> file_path = r"c:\path\to\file.txt" >> file_path = r'c:\path\to\file.txt >> file_path = r"""c:\path\to\file.txt""" >> file_path = r'''c:\path\to\file.txt''' > > 'r' is to avoid escaping backslashes only or other special charcaters as > well? Yes, just backslashes. > As for the string i noticed that if i'am to mix single quotes and double > quotes(any number of them not just always pairs) > and backslashes and other special stuff in them then i'm best off using > 3-sinlge-quotes like > > name='''My name is "Nikos" and i'am from Thessaloniki\Greece''' > > The above example can only be written by using 3-single quoting right? > Not by pairs of single or double quotes, correct? It can be written as a non-3-quote string, you just have to escape the inner quotes (single & double) and the backslash to be seen: name = 'My name is Nikos and I\'m from Thessaloniki\\Greece' name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece" > And i dont have to use the 'r' in fornt of it too. Using the 'r' in front would make it much more challenging, because it would prevent the backslashes from being seen as escaping. :) >> (1,) + (2,) >> >> to return "(1,2)" > > This is actually joining two single element tuples (1,) and (2, ) to a > new bigger tuple of two elements, correct? Correct. > Also if you please comment on my mysql string substitution example i've > posted in my previous post just to make it work. There's a number of variables which can impact the exact string that would need to be passed, so it's not a trivial thing to do. You may or may not be un-escaping HTML entities in the GET parameters ("%20" -> a space, etc), and I don't have a readily available way to duplicate your environment, so testing becomes a bit harder. Hopefully others on the list can give you a hand on breaking your code. -tkc From chris at simplistix.co.uk Thu Aug 19 11:58:30 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 19 Aug 2010 16:58:30 +0100 Subject: bug? context managers vs ImportErrors Message-ID: <4C6D54A6.4060107@simplistix.co.uk> Hi All, Am I right in thinking this is a bug: class MyContextManager: def __enter__(self): pass def __exit__(self,t,e,tb): print type(t),t print type(e),e with MyContextManager(): import foo.bar.baz ...when executed, gives me: No module named foo.bar.baz Why is 'e' ending up as a string rather than the ImportError object? This is with Python 2.6.5 if that makes a difference... Chris From info at egenix.com Thu Aug 19 11:59:29 2010 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 19 Aug 2010 17:59:29 +0200 Subject: ANN: eGenix mxODBC - Python ODBC Database Interface 3.1.0 Message-ID: <4C6D54E1.1090606@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC - Python ODBC Database Interface Version 3.1.0 mxODBC is our commercially supported Python extension providing ODBC database connectivity to Python applications on Windows, Mac OS X, Unix and BSD platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-3.1.0-GA.html ________________________________________________________________________ INTRODUCTION mxODBC provides an easy-to-use, high-performance, reliable and robust Python interface to ODBC compatible databases such as MS SQL Server, MS Access, Oracle Database, IBM DB2 and Informix , Sybase ASE and Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many more: http://www.egenix.com/products/python/mxODBC/ The "eGenix mxODBC - Python ODBC Database Interface" product is a commercial extension to our open-source eGenix mx Base Distribution: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ NEWS The new mxODBC 3.1.0 release comes with many new features and supports more ODBC drivers, manager and platforms than ever before. Release Highlights ------------------ * We've added Python 2.7 support and builds for all platforms. * mxODBC 3.1 adds native support for the Windows 64-bit platforms as well as the Mac OS X 10.6 (Snow Leopard) 64-bit builds of Python. * mxODBC now fully supports the Oracle Instant Client ODBC driver. * We have updated the support for the latest IBM DB2 9.7 ODBC drivers and enhanced compatibility of mxODBC with the MS SQL Server Native Client ODBC driver on Windows and the Sybase ASE 15 ODBC drivers on Unix. * mxODBC 3.1 adds support for large-scale data warehouse databases Netezza and Teradata. * In addition to the Windows, Mac OS X, iODBC and unixODBC ODBC driver managers, we now also include support for the DataDirect ODBC manager. * The 64-bit support on Unix platforms was updated to support the new unixODBC 2.3.0 version. * We've improved the documentation on how to connect to various popular databases and now include many tips & tricks for each database/driver. * The Python 2.7 memoryview object is now supported as binary data container. * We have simplified handling of database warnings using a new customizable .warningformat attribute. * The catalog methods now accept both Unicode and 8-bit strings as parameters. * You can now select whether to use ANSI (8-bit) or Unicode ODBC APIs in the ODBC drivers, removing unnecessary data conversions and enhancing ODBC driver compatibility. For the full set of changes please check the mxODBC change log: http://www.egenix.com/products/python/mxODBC/changelog.html Feature Highlights ------------------ * Python Database API 2.0 Compliance: the mxODBC API is fully Python DB-API 2.0 compatible and implements a large number of powerful extensions. * Support for all popular ODBC Drivers: mxODBC includes adjustments and work-arounds to support MS SQL Server Native Client, MS SQL Server ODBC Driver, FreeTDS ODBC Driver, Oracle Instant Client ODBC Driver, IBM DB2 ODBC Driver, Sybase ASE ODBC Driver, Netezza ODBC Driver, Teradata ODBC Driver, PostgreSQL ODBC Driver, MySQL ODBC Driver, .MaxDB ODBC Driver as well as the ODBC driver sets of EasySoft, DataDirect, OpenLink, Actual Technologies. * Support for all popular ODBC Driver Managers: mxODBC comes with subpackages for the native Windows and Mac OS X ODBC managers, as well as the ODBC managers unixODBC, iODBC and DataDirect, which are commonly used on Unix systems. * Stable, robust and reliable:the mxODBC API has been in active production use for more than 10 years. * Full Python Support: mxODBC works with Python 2.3, 2.4, 2.5, 2.6 and 2.7. * Full 64-bit Support: mxODBC runs on the following 64-bit platforms: Windows, Linux, FreeBSD and Mac OS X. For the full set of features mxODBC has to offer, please see: http://www.egenix.com/products/python/mxODBC/#Features New mxODBC Editions ------------------- Due to popular demand, we have extended the set of available mxODBC editions and included a new low-cost standard edition. mxODBC is now available in thesethree editions: * The low-cost Standard Edition which provides data connectivity to a selected set of database backends. * The Professional Edition, which gives full access to all mxODBC features. * The Product Development Edition, which allows including mxODBC in applications you develop. At the same time we have simplified our license terms to clarify the situation on multi-core and virtual machines. In most cases, you no longer need to purchase more than one license per processor or virtual machine, scaling down the overall license costs significantly compared to earlier mxODBC releases. For a complete overview of the new editions, please see the product page. http://www.egenix.com/products/python/mxODBC/#mxODBCEditions ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/mxODBC/ In order to use the eGenix mxODBC package you will first need to install the eGenix mx Base package: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ UPGRADING Users are encouraged to upgrade to this latest mxODBC release to benefit from the new features and updated ODBC driver support. We have taken special care, not to introduce backwards incompatible changes, making the upgrade experience as smooth as possible. Customers who have purchased mxODBC 2.0, 2.1 or 3.0 licenses can upgrade their licenses using the mxODBC Professional Edition Upgrade License. If you want to try the new release before purchace, you can request 30-day evaluation licenses by visiting our web-site http://www.egenix.com/products/python/mxODBC/#Evaluation or by writing to sales at egenix.com, stating your name (or the name of the company) and the number of eval licenses that you need. _______________________________________________________________________ SUPPORT Commercial support for this product is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. _______________________________________________________________________ INFORMATION About Python (http://www.python.org/): Python is an object-oriented Open Source programming language which runs on all modern platforms. By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for today's IT challenges. About eGenix (http://www.egenix.com/): eGenix is a software project, consulting and product company focusing on expert services and professional quality products for companies, Python users and developers. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 19 2010) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From kst-u at mib.org Thu Aug 19 12:00:52 2010 From: kst-u at mib.org (Keith Thompson) Date: Thu, 19 Aug 2010 09:00:52 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> <8a12e419-447b-475d-9ec2-216f2d97c3cb@v41g2000yqv.googlegroups.com> Message-ID: Standish P writes: > On Aug 18, 5:38?pm, Keith Thompson wrote: [...] >> Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, >> or comp.lang.python. ?Please trim the Newsgroups line. > > provide a rigorous proof that people are more interested in the > nauseating nude pictures that you post of your mother in the > newsgroups than in the subject of forth implementation. [snip] *plonk* -- Keith Thompson (The_Other_Keith) kst-u at mib.org Nokia "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" From jbbrown at sunflower.kuicr.kyoto-u.ac.jp Thu Aug 19 12:07:53 2010 From: jbbrown at sunflower.kuicr.kyoto-u.ac.jp (J.B. Brown) Date: Fri, 20 Aug 2010 01:07:53 +0900 Subject: Python "why" questions In-Reply-To: <4C5EF1DF.3090007@mrabarnett.plus.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> Message-ID: 2010/8/9 MRAB : > Default User wrote: >> >> Not to prolong a good "food fight", but IIRC, many years ago in QBasic, >> one could choose >> >> OPTION BASE 0 >> >> or >> >> OPTION BASE 1 >> When I wrote my own C++ 2-D matrix class, I wrote a member function which did exactly this - allow you to specify the initial index value. Then users of my class (mainly my research lab coworkers) could specify whichever behavior they wanted. In terms of providing readable code and removing beginning programmer confusion, why not extend python lists by using something similar to (but not necessarily identical to) the C++ STL containers: C++ int myX[ ] = { 1,2,3,4,5 }; std::vector vectorX( myX, &myX[ sizeof( myX ) - 1 ] ); std::cout << vectorX.begin() << std::endl; std::cout << vectorX.end() << std::endl; Python x = [ 1 , 2 , 3 , 4 , 5 ] print x.first() print x.last() , where the first and last behavior of python is to return a deep copy of the object, and not a pointer. It seems that this would avoid complaints about the 0/1 issue. Of course, the problem is the behavior of: myList = [ myObject1, myObject2, myObject3, ... , myObjectLast ] print myList.first() + 5 , in which one will conceptually might want to get the 6th item in a list, though if first() is defined to return the object, then we get the returned object plus 5, if such behavior is defined to exist. I completely acknowledge that the behavior is not well defined, and that is why I am not proposing this as a final implementation, but rather as a concept and motivation. For those who don't like Python's 0-based indexing, why not just build a wrapper type which features an item() method that handles the internal conversion from 1 to 0 as the starting index? Better yet, include a method which sets/specifies the 0/1 behavior, and have item() reference the 0/1 setting to obtain the proper offset. Just a thought. J.B. Brown Kyoto University From randrange at gmail.com Thu Aug 19 12:34:08 2010 From: randrange at gmail.com (Andrew Evans) Date: Thu, 19 Aug 2010 09:34:08 -0700 Subject: Python module Code returns empty list any ideas how to fix Message-ID: Hello I am trying to modify Python xgoogle module to use yahoo I have hit a road block where I receive no error messages the code I use to test just returns an empty list. and I don't know how to trouble shoot it the module code is here http://pastebin.com/iTibRs1R and the code I am using to test is this import re from urlparse import urlparse from xyahoo.search import YahooSearch, SearchError gs = YahooSearch("quick and dirty") print gs gs.results_per_page = 50 results = gs.get_results() print results for res in results: print res.title.encode("utf8") print res.desc.encode("utf8") print res.url.encode("utf8") Any idea how to fix the module *cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Thu Aug 19 13:18:19 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 19 Aug 2010 17:18:19 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> Message-ID: <8d57arFph0U1@mid.individual.net> On 2010-08-19, J.B. Brown wrote: > When I wrote my own C++ 2-D matrix class, I wrote a member > function which did exactly this - allow you to specify the > initial index value. Then users of my class (mainly my research > lab coworkers) could specify whichever behavior they wanted. I did something similar in a library that needs to read "positions" from the specification for a fixed-length fields plain text database. The printed specs for these document types often start counting character positions at 1, but not universally. > For those who don't like Python's 0-based indexing, why not > just build a wrapper type which features an item() method that > handles the internal conversion from 1 to 0 as the starting > index? Better yet, include a method which sets/specifies the > 0/1 behavior, and have item() reference the 0/1 setting to > obtain the proper offset. Because they know deep down they wouldn't win anything. -- Neil Cerutti From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 13:38:50 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 17:38:50 GMT Subject: bug? context managers vs ImportErrors References: Message-ID: <4c6d6c29$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 16:58:30 +0100, Chris Withers wrote: > Hi All, > > Am I right in thinking this is a bug: > > class MyContextManager: > > def __enter__(self): > pass > > def __exit__(self,t,e,tb): > print type(t),t > print type(e),e > > > with MyContextManager(): > import foo.bar.baz > > ...when executed, gives me: > > > No module named foo.bar.baz > > Why is 'e' ending up as a string rather than the ImportError object? Because e is the exception value, not an exception instance. In other words, if you call t(e) you will get the instance you're expecting. See the docs: http://docs.python.org/library/stdtypes.html#contextmanager.__exit__ The three arguments exc_type, exc_value, exc_tb are the same three arguments you can pass to the raise statement: http://docs.python.org/reference/simple_stmts.html#the-raise-statement (BTW, I'm not suggesting you should do that from inside the __exit__ method.) So, no, this is not a bug. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 13:42:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 17:42:37 GMT Subject: Contains/equals References: Message-ID: <4c6d6d0c$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote: > def __eq__(self, obj): > if self.a==obj.a and self.b==obj.b: return True > return False That would be the same as: def __eq__(self, obj): return self.a==obj.a and self.b==obj.b -- Steven From ethan at stoneleaf.us Thu Aug 19 13:44:19 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 19 Aug 2010 10:44:19 -0700 Subject: bug? context managers vs ImportErrors In-Reply-To: <4C6D54A6.4060107@simplistix.co.uk> References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: <4C6D6D73.9050206@stoneleaf.us> Chris Withers wrote: > Hi All, > > Am I right in thinking this is a bug: > > class MyContextManager: > > def __enter__(self): > pass > > def __exit__(self,t,e,tb): > print type(t),t > print type(e),e > > > with MyContextManager(): > import foo.bar.baz > > ...when executed, gives me: > > > No module named foo.bar.baz > > Why is 'e' ending up as a string rather than the ImportError object? > > This is with Python 2.6.5 if that makes a difference... I don't have an answer, just some more examples across different versions/exceptions: class MyContextManager: def __enter__(self): pass def __exit__(self,t,e,tb): print ('--------') print (type(t),t) print (type(e),e) return True with MyContextManager(): import foo.bar.baz with MyContextManager(): 1/0 with MyContextManager(): not_here() c:\temp>\python25\python test.py [0] -------- (, ) (, 'No module named bar.baz') -------- (, ) (, 'integer division or modulo by zero') -------- (, ) (, "name 'not_here' is not defined") c:\temp>\python26\python test.py [0] -------- (, ) (, 'No module named bar.baz') -------- (, ) (, 'integer division or modulo by zero') -------- (, ) (, "name 'not_here' is not defined") c:\temp>\python27\python test.py [0] -------- (, ) (, ImportError('No module named bar.baz',)) -------- (, ) (, ZeroDivisionError('integer division or modulo by zero',)) -------- (, ) (, NameError("name 'not_here' is not defined",)) c:\temp>\python31\python test.py -------- invalid syntax (foo.py, line 3) -------- int division or modulo by zero -------- name 'not_here' is not defined As an aside, does anyone know why the 2.x versions are printing the [0] as the first line? 3.1 does not. From russ.paielli at gmail.com Thu Aug 19 14:03:53 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 11:03:53 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> Message-ID: <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> On Aug 19, 9:07?am, "J.B. Brown" wrote: > 2010/8/9 MRAB : > > > Default User wrote: > > >> Not to prolong a good "food fight", but IIRC, many years ago in QBasic, > >> one could choose > > >> OPTION BASE 0 > > >> or > > >> OPTION BASE 1 > > When I wrote my own C++ 2-D matrix class, I wrote a member function > which did exactly this - allow you to specify the initial index value. > Then users of my class (mainly my research lab coworkers) could > specify whichever behavior they wanted. > > In terms of providing readable code and removing beginning programmer > confusion, why not extend python lists by using something similar to > (but not necessarily identical to) ?the C++ STL containers: > > C++ > int myX[ ] ?= { 1,2,3,4,5 }; > std::vector vectorX( myX, &myX[ ?sizeof( myX ) - 1 ] ); > std::cout << vectorX.begin() << std::endl; > std::cout << vectorX.end() << std::endl; > > Python > x = [ 1 , 2 , 3 , 4 , 5 ] > print x.first() > print x.last() ? ?, Many years ago I wrote a fairly comprehensive vector/matrix class in C+ +. (It was an exercise to learn the intricacies of C++, and I also really needed it.) I used a system of offset pointers to realize indexing that starts with 1. Years later, after I had quit using it, I decided that I should have just bit the bullet and let the indexing start with zero for simplicity. I believe that zero-based indexing is a mistake, but attempts to fix it require additional boilerplate that is prone to error and inefficiency. Short of a major language overhaul, we are essentially stuck with zero-based indexing. But that doesn't mean we should pretend that it was the right choice. For those who insist that zero-based indexing is a good idea, why you suppose mathematical vector/matrix notation has never used that convention? I have studied and used linear algebra extensively, and I have yet to see a single case of vector or matrix notation with zero- based indexing in a textbook or a technical paper. Also, mathematical summation is traditionally shown as "1 to N", not "0 to N-1". Are mathematicians just too simple-minded and unsophisticated to understand the value of zero-based indexing? Or have you perhaps been mislead? From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 14:04:49 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 18:04:49 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> Message-ID: <4c6d7241$0$11111$c3e8da3@news.astraweb.com> On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote: > The convention of starting with zero may have had some slight > performance advantage in the early days of computing, but the huge > potential for error that it introduced made it a poor choice in the long > run, at least for high-level languages. People keep saying this, but it's actually the opposite. Signpost errors and off-by-one errors are more common in languages that count from one. A simple example: Using zero-based indexing, suppose you want to indent the string "spam" so it starts at column 4. How many spaces to you prepend? 0123456789 spam Answer: 4. Nice and easy and almost impossible to get wrong. To indent to position n, prepend n spaces. Now consider one-based indexing, where the string starts at column 5: 1234567890 spam Answer: 5-1 = 4. People are remarkably bad at remembering to subtract the 1, hence the off-by-one errors. Zero-based counting doesn't entirely eliminate off-by-one errors, but the combination of that plus half-open on the right intervals reduces them as much as possible. The intuitive one-based closed interval notation used in many natural languages is terrible for encouraging off-by-one errors. Quick: how many days are there between Friday 20th September and Friday 27th September inclusive? If you said seven, you fail. One-based counting is the product of human intuition. Zero-based counting is the product of human reason. -- Steven From __peter__ at web.de Thu Aug 19 14:08:13 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 20:08:13 +0200 Subject: bug? context managers vs ImportErrors References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: Ethan Furman wrote: > Chris Withers wrote: >> Hi All, >> >> Am I right in thinking this is a bug: >> >> class MyContextManager: >> >> def __enter__(self): >> pass >> >> def __exit__(self,t,e,tb): >> print type(t),t >> print type(e),e >> >> >> with MyContextManager(): >> import foo.bar.baz >> >> ...when executed, gives me: >> >> >> No module named foo.bar.baz >> >> Why is 'e' ending up as a string rather than the ImportError object? >> >> This is with Python 2.6.5 if that makes a difference... > > I don't have an answer, just some more examples across different > versions/exceptions: > > > class MyContextManager: > def __enter__(self): > pass > def __exit__(self,t,e,tb): > print ('--------') > print (type(t),t) > print (type(e),e) > return True > > with MyContextManager(): > import foo.bar.baz > with MyContextManager(): > 1/0 > with MyContextManager(): > not_here() > > > > c:\temp>\python25\python test.py > [0] > -------- > (, ) > (, 'No module named bar.baz') > -------- > (, ) > (, 'integer division or modulo by zero') > -------- > (, ) > (, "name 'not_here' is not defined") > > c:\temp>\python26\python test.py > [0] > -------- > (, ) > (, 'No module named bar.baz') > -------- > (, ) > (, 'integer division or modulo by zero') > -------- > (, ) > (, "name 'not_here' is not defined") > > c:\temp>\python27\python test.py > [0] > -------- > (, ) > (, ImportError('No module named bar.baz',)) > -------- > (, ) > (, ZeroDivisionError('integer > division or modulo by zero',)) > -------- > (, ) > (, NameError("name 'not_here' is not > defined",)) > > c:\temp>\python31\python test.py > -------- > > invalid syntax (foo.py, line 3) > -------- > > int division or modulo by zero > -------- > > name 'not_here' is not defined > > > > As an aside, does anyone know why the 2.x versions are printing the [0] > as the first line? 3.1 does not. If reading the error messages carefully doesn't help scroll down for a hint;) Look into foo.py From dodo_do_not_wake_up at yahoo.fr Thu Aug 19 14:25:41 2010 From: dodo_do_not_wake_up at yahoo.fr (Dodo) Date: Thu, 19 Aug 2010 20:25:41 +0200 Subject: Django 1.2.1 - stuck with CSRF verification Message-ID: Hi all, I followed the tutorial but at page 4 I can't get rid of CSRF errors, even though I followed everything in this page : http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ Any idea? Dorian From ethan at stoneleaf.us Thu Aug 19 14:25:54 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 19 Aug 2010 11:25:54 -0700 Subject: bug? context managers vs ImportErrors In-Reply-To: References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: <4C6D7732.5070203@stoneleaf.us> Peter Otten wrote: > Ethan Furman wrote: >> As an aside, does anyone know why the 2.x versions are printing the [0] >> as the first line? 3.1 does not. > > If reading the error messages carefully doesn't help scroll down for a > hint;) > . > . > . > Look into foo.py AH hahahahahahah. That's what I get for being in a hurry. Thanks for catching that, Peter! ~Ethan~ From russ.paielli at gmail.com Thu Aug 19 14:27:18 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 11:27:18 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: On Aug 19, 11:04?am, Steven D'Aprano wrote: > On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote: > > The convention of starting with zero may have had some slight > > performance advantage in the early days of computing, but the huge > > potential for error that it introduced made it a poor choice in the long > > run, at least for high-level languages. > > People keep saying this, but it's actually the opposite. Signpost errors > and off-by-one errors are more common in languages that count from one. > > A simple example: Using zero-based indexing, suppose you want to indent > the string "spam" so it starts at column 4. How many spaces to you > prepend? > > 0123456789 > ? ? spam > > Answer: 4. Nice and easy and almost impossible to get wrong. To indent to > position n, prepend n spaces. > > Now consider one-based indexing, where the string starts at column 5: > > 1234567890 > ? ? spam > > Answer: 5-1 = 4. People are remarkably bad at remembering to subtract the > 1, hence the off-by-one errors. > > Zero-based counting doesn't entirely eliminate off-by-one errors, but the > combination of that plus half-open on the right intervals reduces them as > much as possible. > > The intuitive one-based closed interval notation used in many natural > languages is terrible for encouraging off-by-one errors. Quick: how many > days are there between Friday 20th September and Friday 27th September > inclusive? If you said seven, you fail. The error mode you refer to is much less common than the typical off- by-one error mode. In the far more common error mode, zero-based indexing is far more error prone. > One-based counting is the product of human intuition. Zero-based counting > is the product of human reason. I suggest you take that up with mathematicians, who have used one- based indexing all along. That's why it was used in Fortran and Matlab, among other more mathematical and numerically oriented and languages. From russ.paielli at gmail.com Thu Aug 19 14:39:05 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 11:39:05 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: <40cea402-30ac-472c-ab1e-27e2050ec25b@y11g2000yqm.googlegroups.com> I just checked, and Mathematica uses one-based indexing. Apparently they want their notation to look mathematical. From thomas at jollybox.de Thu Aug 19 14:40:50 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 19 Aug 2010 20:40:50 +0200 Subject: Django 1.2.1 - stuck with CSRF verification In-Reply-To: References: Message-ID: <201008192040.50998.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to Dodo to exclaim: > Hi all, > I followed the tutorial but at page 4 I can't get rid of CSRF errors, > even though I followed everything in this page : > http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ > what kind of errors? Any exception tracebacks you can show us maybe? From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 14:42:45 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 18:42:45 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> Message-ID: <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote: > For those who insist that zero-based indexing is a good idea, why you > suppose mathematical vector/matrix notation has never used that > convention? I have studied and used linear algebra extensively, and I > have yet to see a single case of vector or matrix notation with zero- > based indexing in a textbook or a technical paper. Also, mathematical > summation is traditionally shown as "1 to N", not "0 to N-1". In my experience, it's more likely to be "0 to N" than either of the above, thus combining the worst of both notations. > Are > mathematicians just too simple-minded and unsophisticated to understand > the value of zero-based indexing? No, mathematicians are addicted to tradition. Unlike computer scientists, who create new languages with radically different notation and syntax at the drop of a hat, mathematicians almost never change existing notation. Sometimes they *add* new notation, but more often they just re-use old notation in a new context. E.g. if you see (5, 8), does that mean a coordinate pair, a two-tuple, an open interval, or something else? Additionally, mathematical notation isn't chosen for its ability to encourage or discourage errors. It seems often to be chosen arbitrarily, or for convenience, but mostly out of tradition and convention. Why do we use "x" for "unknown"? Why do we use i for an integer value, but not r for a real or c for a complex value? Mathematicians are awfully lazy -- laziness is one of the cardinal virtues of the mathematician, as it is of programmers -- but they value brevity and conciseness over notation that improves readability and robustness. That's why they (e.g.) they use implicit multiplication, a plethora of "line noise" symbols that would boggle even Perl programmers, and two-dimensional syntax where the meaning of tokens depends on where they are written relative to some other token. (E.g. subscript, superscript, and related forms.) There is one slightly mainstream language that uses mathematical notation: APL. The result isn't pretty. -- Steven From thomas at jollybox.de Thu Aug 19 14:47:10 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 19 Aug 2010 20:47:10 +0200 Subject: Creating a PYD file In-Reply-To: References: Message-ID: <201008192047.10460.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to Rony to exclaim: > Is a PYD file created from Pyrex faster in execution then a PYD file > created from python source ? How do you plan to create an extension module (*.so, *.pyd on Windows) from Python source then? From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 14:47:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 18:47:26 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <40cea402-30ac-472c-ab1e-27e2050ec25b@y11g2000yqm.googlegroups.com> Message-ID: <4c6d7c3e$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:39:05 -0700, Russ P. wrote: > I just checked, and Mathematica uses one-based indexing. Apparently they > want their notation to look mathematical. Well duh. It's called MATHematica, not PROGematica. -- Steven From nikos.the.gr33k at gmail.com Thu Aug 19 14:50:53 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Thu, 19 Aug 2010 21:50:53 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D548F.2050303@tim.thechases.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> <4C6D50CA.5060604@gmail.com> <4C6D548F.2050303@tim.thechases.com> Message-ID: <4C6D7D0D.7040703@gmail.com> ???? 19/8/2010 6:58 ??, ?/? Tim Chase ??????: > It can be written as a non-3-quote string, you just have to escape the > inner quotes (single & double) and the backslash to be seen: > > name = 'My name is "Nikos" and I\'m from Thessaloniki\\Greece' > name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece" > So if i enclose the string in double quotes the inner double quotes have to be escaped while if i enclose the string in single quotes the inner single quotes have to be escaped. But in 3-single-quoting thing became easier since i don't have to escape all kind of quotes right? just the backslashes. >> And i dont have to use the 'r' in fornt of it too. > > Using the 'r' in front would make it much more challenging, because it > would prevent the backslashes from being seen as escaping. :) So the best way to write the above assignment statement would be: name = r'''My name is "Nikos" and I'm from Thessaloniki\Greece''' It cannot get any easier that that can it? :) ''' ''' helps avoid escaping all kind of quotes! 'r' avoid escaping backslashes! ============================= Why does the page variable which is actually a string needs to be a tuple or a list and not just as a string which is what it actually is? I have a strong desire to use it like this: cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page ) opposed to tuple. Would i might facing a problem? Of what? MySQLdb instead of give the whole value to the placeholder to give just a single char? Also do i need 3-single-quoting here as well or it can be written qith signle/double quotes? What appleis to strings apply to mysql queries as well? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu Aug 19 14:53:36 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Aug 2010 13:53:36 -0500 Subject: Contains/equals In-Reply-To: <4c6d6d0c$0$11111$c3e8da3@news.astraweb.com> References: <4c6d6d0c$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4C6D7DB0.1030304@tim.thechases.com> On 08/19/10 12:42, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote: > >> def __eq__(self, obj): >> if self.a==obj.a and self.b==obj.b: return True >> return False > > That would be the same as: > > def __eq__(self, obj): > return self.a==obj.a and self.b==obj.b Or, if you have lots of attributes and 2.5+ def __eq__(self, other): return all( getattr(self, attr) == getattr(other, attr) for attr in ['a', 'b', 'c', ...] ) or even something like def __eq__(self, other): return all( getattr(self, attr) == getattr(other, attr) for attr in dir(self) if not attr.startswith("__") and not attr.endswith("__") ) -tkc From mail at timgolden.me.uk Thu Aug 19 14:55:38 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 19 Aug 2010 19:55:38 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: <4C6D7E2A.9010703@timgolden.me.uk> On 19/08/2010 4:55 PM, vsoler wrote: > I need to read, for each of the directories in a shared file server > unit, who has access to the directories and what type of access > privileges. > > This is something that I can easily do interactively in my Windows > Document Explorer by right clicking a single directory, clicking on > Properties, then on Security. > > There I can see the Users and Group of Users that have access to the > selected directory, as well as the type of access to that directory > (Read/Write/eXecute etc.) Here you have one of those occasions when the Windows GUI does a very good job of presenting a simplified but perfectly usable interface layer on top of a moderately complex security scheme. It's not as easy as you think. > I've been looking in the "os" library, and found the "os.chmod" method > but I am not sure that it is going to give me what I need. Should I > also used library "stat"? No. Both of these are basically doing a best-endeavours job of mapping certain Windows attributes to some Posix equivalent. They're essentially useless for anything beyond the most trivial tasks. Have a read here which will at least put you on the path of knowing what terminology you need to search for: http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html and if you're interested, this is the kind of thing my winsys package is reasonably good at: http://timgolden.me.uk/python/winsys/security.html#module-security TJG From russ.paielli at gmail.com Thu Aug 19 14:57:53 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 11:57:53 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> Message-ID: <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> On Aug 19, 11:42?am, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote: > > For those who insist that zero-based indexing is a good idea, why you > > suppose mathematical vector/matrix notation has never used that > > convention? I have studied and used linear algebra extensively, and I > > have yet to see a single case of vector or matrix notation with zero- > > based indexing in a textbook or a technical paper. Also, mathematical > > summation is traditionally shown as "1 to N", not "0 to N-1". > > In my experience, it's more likely to be "0 to N" than either of the > above, thus combining the worst of both notations. > > > Are > > mathematicians just too simple-minded and unsophisticated to understand > > the value of zero-based indexing? > > No, mathematicians are addicted to tradition. That is probably true. But computer languages are addicted to more than tradition. They're addicted to compatibility and familiarity. I don't know where zero-based indexing started, but I know that C used it very early, probably for some minuscule performance advantage. When C++ came along, it tried to be somewhat compatible with C, so it continued using zero-based indexing. Then Java was loosely modeled after C++, so the convention continued. Python was written in C, so zero-based indexing was "natural." So the whole thing is based on a decision by some guy who was writing a language for operating systems, not mathematics or application programming. > Unlike computer scientists, who create new languages with radically > different notation and syntax at the drop of a hat, mathematicians almost > never change existing notation. Sometimes they *add* new notation, but > more often they just re-use old notation in a new context. E.g. if you > see (5, 8), does that mean a coordinate pair, a two-tuple, an open > interval, or something else? > > Additionally, mathematical notation isn't chosen for its ability to > encourage or discourage errors. It seems often to be chosen arbitrarily, > or for convenience, but mostly out of tradition and convention. Why do we > use "x" for "unknown"? Why do we use i for an integer value, but not r > for a real or c for a complex value? > > Mathematicians are awfully lazy -- laziness is one of the cardinal > virtues of the mathematician, as it is of programmers -- but they value > brevity and conciseness over notation that improves readability and > robustness. That's why they (e.g.) they use implicit multiplication, a > plethora of "line noise" symbols that would boggle even Perl programmers, > and two-dimensional syntax where the meaning of tokens depends on where > they are written relative to some other token. (E.g. subscript, > superscript, and related forms.) > > There is one slightly mainstream language that uses mathematical > notation: APL. The result isn't pretty. As I wrote above, the use of zero-based indexing in C++, Java, and Python are all simply based on the fact that C used it. I wouldn't have guessed that APL is a "mainstream" language. As I wrote in recent posts, Fortran, Matlab, and Mathematica all used one- based indexing. Maybe Basic too, but I haven't checked. From russ.paielli at gmail.com Thu Aug 19 15:13:06 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 12:13:06 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> Message-ID: <8c9a626e-cf15-4b42-bfbc-e32622777b4b@l14g2000yql.googlegroups.com> Yes, apparently Basic uses one-based indexing too. As for Ada, apparently, the programmer needs to explicitly define the index range for every array. Weird. But I get the impression that one- based indexing is used much more than zero-based indexing. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 15:13:50 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 19:13:50 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c6d826e$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:27:18 -0700, Russ P. wrote: [...] >> Zero-based counting doesn't entirely eliminate off-by-one errors, but >> the combination of that plus half-open on the right intervals reduces >> them as much as possible. >> >> The intuitive one-based closed interval notation used in many natural >> languages is terrible for encouraging off-by-one errors. Quick: how >> many days are there between Friday 20th September and Friday 27th >> September inclusive? If you said seven, you fail. > > The error mode you refer to is much less common than the typical off- > by-one error mode. In the far more common error mode, zero-based > indexing is far more error prone. So you say, and yet you don't give any examples of this "far more common" error mode. >> One-based counting is the product of human intuition. Zero-based >> counting is the product of human reason. > > I suggest you take that up with mathematicians, who have used one- based > indexing all along. That's why it was used in Fortran and Matlab, among > other more mathematical and numerically oriented and languages. Mathematics is an ancient art that values tradition and convention. It doesn't matter how hard it was to come up with a proof, or how difficult to verify it. Mathematicians value logical correctness and some undefinable sense of elegance over how easy it is to verify, the readability of the notation, resistance to errors, and the ability of mediocre mathematicians to make useful contributions. Mathematical notation and conventions are not, by any stretch of the imagination, designed to reduce errors. Mathematicians consider it a good thing that they are still mostly using the same notation invented by (say) Leibniz. Programming language design is a young art that values reliability and ease of use over tradition. While correctness of the code is important, equally important (if not more so) is readability, resistance to errors, and the ability of mediocre programmers to write code that works. Or at least code that can be hammered into working by slightly less mediocre programmers. Maintenance of code is usually more difficult than writing it in the first place, and consequently languages often are designed specifically to reduce errors rather than to use the exact same notation than Grace Hopper or Charles Babbage used. While businesses are conservative in which languages they choose, language designers are not conservative in the design features they come up with. That there has been a gradual (although as yet incomplete) convergence towards zero-based indexing in languages aimed at programmers, and one-based indexing in languages aimed at non- programmers, tells you everything you need to know. -- Steven From andrei.avk at gmail.com Thu Aug 19 15:18:23 2010 From: andrei.avk at gmail.com (AK) Date: Thu, 19 Aug 2010 15:18:23 -0400 Subject: Python "why" questions In-Reply-To: <4c6d7241$0$11111$c3e8da3@news.astraweb.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4C6D837F.3010803@gmail.com> On 08/19/2010 02:04 PM, Steven D'Aprano wrote: > On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote: > >> The convention of starting with zero may have had some slight >> performance advantage in the early days of computing, but the huge >> potential for error that it introduced made it a poor choice in the long >> run, at least for high-level languages. > > People keep saying this, but it's actually the opposite. Signpost errors > and off-by-one errors are more common in languages that count from one. > > A simple example: Using zero-based indexing, suppose you want to indent > the string "spam" so it starts at column 4. How many spaces to you > prepend? > > 0123456789 > spam Doesn't it start at column 5 as shown? Anyway, it's far more common, I think, to iterate over a sequence and say "my list is 12 items long. I need to check if I'm on 12th item and do something special. Doh, I mean, 11th item." In my view, this is far, far more common, especially for people new to programming, and isn't one of Python mottos "programming for everybody"? In other words, starting with 0 leads to implicit error every time you simply pause and think "at which item am I now and how many items have I got so far?" which are the two most basic questions involved in iteration. I'm not saying that 1-th indexing is necessarily better in programming than 0-th indexing, all things considered. It's an arguable question, it depends on what kind of operations are more common, and I can't know this for everyone. I am saying that it is much more natural for people new to programming and outside of programming to count from 1, and I imagine the reason for this is simply that it's most useful in vast majority of real usage people deal with. It's just annoying that people bring up, for example, ground floor/ first floor as proof that both are equally natural. (I don't mean you, I know you said you agree that 1-th indexing is more intuitive). -ak From lists at cheimes.de Thu Aug 19 15:20:50 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 19 Aug 2010 21:20:50 +0200 Subject: Contains/equals In-Reply-To: <4C6D7DB0.1030304@tim.thechases.com> References: <4c6d6d0c$0$11111$c3e8da3@news.astraweb.com> <4C6D7DB0.1030304@tim.thechases.com> Message-ID: Am 19.08.2010 20:53, schrieb Tim Chase: > On 08/19/10 12:42, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote: >> >>> def __eq__(self, obj): >>> if self.a==obj.a and self.b==obj.b: return True >>> return False >> >> That would be the same as: >> >> def __eq__(self, obj): >> return self.a==obj.a and self.b==obj.b > > Or, if you have lots of attributes and 2.5+ > > def __eq__(self, other): > return all( > getattr(self, attr) == getattr(other, attr) > for attr in ['a', 'b', 'c', ...] > ) > > or even something like > > def __eq__(self, other): > return all( > getattr(self, attr) == getattr(other, attr) > for attr in dir(self) > if not attr.startswith("__") and not attr.endswith("__") > ) > or simpler if you don't take slots and class attributes into account. def __eq__(self, other): return self.__dict__ == other.__dict__ Christian From russ.paielli at gmail.com Thu Aug 19 15:25:50 2010 From: russ.paielli at gmail.com (Russ P.) Date: Thu, 19 Aug 2010 12:25:50 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> Message-ID: <9015ea75-e67c-46d2-b5ce-b9745aab1317@x25g2000yqj.googlegroups.com> On Aug 19, 12:13?pm, Steven D'Aprano While businesses are conservative in which languages they choose, > language designers are not conservative in the design features they come > up with. That there has been a gradual (although as yet incomplete) > convergence towards zero-based indexing in languages aimed at > programmers, and one-based indexing in languages aimed at non- > programmers, tells you everything you need to know. I beg to differ. I remember reading Bjarne Stroustrup's rationale for adopting all sorts of junk from C that he really didn't want, just to make C++ reasonably compatible with it. Had he not done that, C++ probably would have died on the vine. I'm sure the same was true of Java and Python too. In any case, I need to drop this discussion and move on. Mr. D'Aprano, I usually find your posts enlightening and amusing, but in this case just don't seem to be converging. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 15:32:41 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2010 19:32:41 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> Message-ID: <4c6d86d9$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 11:57:53 -0700, Russ P. wrote: > I don't > know where zero-based indexing started, but I know that C used it very > early, probably for some minuscule performance advantage. In C, zero based indexing was used because it made pointer arithmetic elegant and reduced bugs. > When C++ came > along, it tried to be somewhat compatible with C, so it continued using > zero-based indexing. And because a feature that isn't broken doesn't need to be "fixed". > Then Java was loosely modeled after C++, so the > convention continued. Python was written in C, so zero-based indexing > was "natural." So the whole thing is based on a decision by some guy who > was writing a language for operating systems, not mathematics or > application programming. Python is vastly different from C. It has just as many similarities to Pascal as C, which uses 1-based indexing. No surprise there -- Python, like both Pascal and C, is a member of the Algol family of languages. It is interesting to see that Nicholas Wirth's first language, Pascal, used one-based indexing, and his latest, Oberon, uses zero-based. Say what you like about Wirth, but he's not influenced by the desire to be like C. Oberon uses the same zero-based half-open on the right indexing as Python: VAR a: ARRAY 10 OF INTEGER; creates an array a[0]...a[9]. If Wirth has moved to the Python convention, it is because it *works*, not because he's trying to ape C. Not all languages are based on Algol. Languages derived from Lisp also start array indexing at 0. So does Forth. So that's at least three significantly different language families which have independently converged on zero-based indexing. [...] > I wouldn't have guessed that APL is a "mainstream" language. I said "slightly". It was surprisingly popular in it's time, and there are still multiple APL compilers and interpreters for Windows, Linux and Mac. -- Steven From kara at kara-moon.com Thu Aug 19 15:41:30 2010 From: kara at kara-moon.com (Rony) Date: Thu, 19 Aug 2010 12:41:30 -0700 (PDT) Subject: Creating a PYD file References: Message-ID: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> Sorry that was a typo... The question actually is, is a PYD file created from C faster then a PYD file from Pyrex ? I know it will depend on how it is written, but let's imagine a tiny example, like (Pseudo code) result = arg1 + arg2 return result Tia Rony On 19 ao?t, 20:47, Thomas Jollans wrote: > On Thursday 19 August 2010, it occurred to Rony to exclaim: > > > Is a PYD file created from Pyrex faster in execution then a PYD file > > created from python source ? > > How do you plan to create an extension module (*.so, *.pyd on Windows) from > Python source then? From python at mrabarnett.plus.com Thu Aug 19 15:43:51 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Aug 2010 20:43:51 +0100 Subject: Python "why" questions In-Reply-To: <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> Message-ID: <4C6D8977.2030700@mrabarnett.plus.com> Russ P. wrote: > On Aug 19, 11:42 am, Steven D'Aprano cybersource.com.au> wrote: >> On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote: >>> For those who insist that zero-based indexing is a good idea, why you >>> suppose mathematical vector/matrix notation has never used that >>> convention? I have studied and used linear algebra extensively, and I >>> have yet to see a single case of vector or matrix notation with zero- >>> based indexing in a textbook or a technical paper. Also, mathematical >>> summation is traditionally shown as "1 to N", not "0 to N-1". >> In my experience, it's more likely to be "0 to N" than either of the >> above, thus combining the worst of both notations. >> >>> Are >>> mathematicians just too simple-minded and unsophisticated to understand >>> the value of zero-based indexing? >> No, mathematicians are addicted to tradition. > > That is probably true. But computer languages are addicted to more > than tradition. They're addicted to compatibility and familiarity. I > don't know where zero-based indexing started, but I know that C used > it very early, probably for some minuscule performance advantage. When > C++ came along, it tried to be somewhat compatible with C, so it > continued using zero-based indexing. Then Java was loosely modeled > after C++, so the convention continued. Python was written in C, so > zero-based indexing was "natural." So the whole thing is based on a > decision by some guy who was writing a language for operating systems, > not mathematics or application programming. > [snip] C was derived ultimately from BCPL. In C array indexing is syntactic sugar for pointer arithmetic with dereferencing, so: p[i] means the same as: *(p + i) BCPL, IIRC, didn't use the familiar indexing syntax. !p was the equivalent of *p and p!i was short for !(p + i), the equivalent of p[i]. From python at mrabarnett.plus.com Thu Aug 19 15:49:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Aug 2010 20:49:32 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D7D0D.7040703@gmail.com> References: <4C6BA2C4.4000309@gmail.com> <4C6D1667.7090904@tim.thechases.com> <4C6D50CA.5060604@gmail.com> <4C6D548F.2050303@tim.thechases.com> <4C6D7D0D.7040703@gmail.com> Message-ID: <4C6D8ACC.2050108@mrabarnett.plus.com> Nik Gr wrote: [snip] > Why does the page variable which is actually a string needs to be a > tuple or a list and not just as a string which is what it actually is? > I have a strong desire to use it like this: > > cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page ) > > opposed to tuple. Would i might facing a problem? Of what? MySQLdb > instead of give the whole value to the placeholder to give just a single > char? When there's more than one value you provide a tuple. It's makes sense from the point of view of consistency that you also provide a tuple when there's only one value. > Also do i need 3-single-quoting here as well or it can be written qith > signle/double quotes? > What appleis to strings apply to mysql queries as well? > It's just a normal string literal. From lists at cheimes.de Thu Aug 19 15:50:24 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 19 Aug 2010 21:50:24 +0200 Subject: bug? context managers vs ImportErrors In-Reply-To: <4C6D54A6.4060107@simplistix.co.uk> References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: > Why is 'e' ending up as a string rather than the ImportError object? > > This is with Python 2.6.5 if that makes a difference... It's a known bug in Python 2.6 and earlier. See http://docs.python.org/whatsnew/2.7.html#porting-to-python-2-7 Due to a bug in Python 2.6, the exc_value parameter to __exit__() methods was often the string representation of the exception, not an instance. This was fixed in 2.7, so exc_value will be an instance as expected. (Fixed by Florent Xicluna; issue 7853.) From info at wingware.com Thu Aug 19 15:54:26 2010 From: info at wingware.com (Wingware) Date: Thu, 19 Aug 2010 15:54:26 -0400 Subject: Wing IDE 3.2.10 released Message-ID: <4C6D8BF2.7040009@wingware.com> Hi, Wingware has released version 3.2.10 of Wing IDE, an integrated development environment designed specifically for the Python programming language. This release includes the following improvements: * Several vi mode fixes and other key binding enhancements * Copy from selected text in Exceptions tool and Testing tool * Fix Perforce support to run client command in project directory * Fix debug attach to remote host * Don't output XML when debugging unit tests * About 20 other bug fixes (see CHANGELOG.txt for details) See the change log at http://wingware.com/pub/wingide/3.2.10/CHANGELOG.txt for details of other recent changes. *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product. Wing IDE 101 can be used free of charge. Wing IDE Pro 3.2.10 http://wingware.com/downloads/wingide/3.2 Wing IDE Personal 3.2.10 http://wingware.com/downloads/wingide-personal/3.2 Wing IDE 101 3.2.10 http://wingware.com/downloads/wingide-101/3.2 *About Wing IDE* Wing IDE is an integrated development environment designed specifically for the Python programming language. It provides powerful editing, testing, and debugging features that help reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE can be used to develop Python code for web, GUI, and embedded scripting applications. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. Version 3.2 of Wing IDE Professional includes the following major features: * Professional quality code editor with vi, emacs, and other keyboard personalities * Code intelligence for Python: Auto-completion, call tips, goto-definition, error indicators, smart indent and re-wrapping, and source navigation * Advanced multi-threaded debugger with graphical UI, command line interaction, conditional breakpoints, data value tool tips over code, watch tool, and externally launched and remote debugging * Powerful search and replace options including keyboard driven and graphical UIs, multi-file, wild card, and regular expression search and replace * Version control integration for Subversion, CVS, Bazaar, git, Mercurial, and Perforce * Integrated unit testing for the unittest, nose, and doctest frameworks * Many other features including project manager, bookmarks, code snippets, OS command integration, indentation manager, PyLint integration, and perspectives * Extremely configurable and may be extended with Python scripts Please refer to the feature list at http://wingware.com/wingide/features for a detailed listing of features by product level. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE supports Python versions 2.0.x through 3.1.x and Stackless Python. For more information, see http://wingware.com/products *Purchasing and Upgrading* Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Version 2.x licenses cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- Wingware | Python IDE The Intelligent Development Environment for Python Programmers www.wingware.com From python at mrabarnett.plus.com Thu Aug 19 15:55:09 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Aug 2010 20:55:09 +0100 Subject: Python "why" questions In-Reply-To: <8c9a626e-cf15-4b42-bfbc-e32622777b4b@l14g2000yql.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> <8c9a626e-cf15-4b42-bfbc-e32622777b4b@l14g2000yql.googlegroups.com> Message-ID: <4C6D8C1D.3080203@mrabarnett.plus.com> Russ P. wrote: > Yes, apparently Basic uses one-based indexing too. > For arrays, yes and no. Traditionally, DIM A(10) has 11 elements, starting at 0, although it might depend on the version of Basic. For strings, yes. > As for Ada, apparently, the programmer needs to explicitly define the > index range for every array. Weird. But I get the impression that one- > based indexing is used much more than zero-based indexing. From ericjvandervelden at gmail.com Thu Aug 19 15:57:04 2010 From: ericjvandervelden at gmail.com (Eric J. Van der Velden) Date: Thu, 19 Aug 2010 12:57:04 -0700 (PDT) Subject: tkinter Message-ID: Hello, I have python2.7 .I have compiled tcl en tk and installed them in my home directory, say /home/eric/tcl and /home/eric/tk . I have edited $ vi Modules/Setup ... _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ -L/home/eric/tcl/lib \ -L/home/eric/tk/lib \ -I/home/eric/tcl/include \ -I/home/eric/tcl/include \ -I/usr/include \ -ltcl8.6 -ltk8.6 \ -L/usr/lib \ -lX11 But setup.py does self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) When I pdb setup.py I see (Pdb) p inc_dirs ['/home/eric/Unix/Python/Python-2.7-install/include', '.', 'Include', './Include', '/usr/local/include', '/home/eric/Unix/Python/Python-2.7- install/include/python2.7', '/usr/include'] (Pdb) p lib_dirs ['/home/eric/Unix/Python/Python-2.7-install/lib', '/usr/local/lib', '/ lib64', '/usr/lib64', '/lib', '/usr/lib'] So no tcl or tk libraries or header files. Is my Modules/Setup not OK? Thanks, Eric J. From debatem1 at gmail.com Thu Aug 19 16:12:13 2010 From: debatem1 at gmail.com (geremy condra) Date: Thu, 19 Aug 2010 13:12:13 -0700 Subject: Python "why" questions In-Reply-To: <4c6d86d9$0$11111$c3e8da3@news.astraweb.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> <240b3bcf-95cf-4a7b-b715-b580676cda67@z28g2000yqh.googlegroups.com> <4c6d7b24$0$11111$c3e8da3@news.astraweb.com> <3081dc57-1996-43f1-8ed0-370d6104ef41@a36g2000yqc.googlegroups.com> <4c6d86d9$0$11111$c3e8da3@news.astraweb.com> Message-ID: On Thu, Aug 19, 2010 at 12:32 PM, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 11:57:53 -0700, Russ P. wrote: > >> I don't >> know where zero-based indexing started, but I know that C used it very >> early, probably for some minuscule performance advantage. > > In C, zero based indexing was used because it made pointer arithmetic > elegant and reduced bugs. That's because in C, an array 'index' is not an ordinal, but a distance. Distances are easier to work with if you are comparing indices and performing arithmetic on them, while ordinals are easier to work with for straightforward I'd-like-this-element-please. I'm personally glad that Python uses the former. Geremy Condra From vicente.soler at gmail.com Thu Aug 19 16:17:40 2010 From: vicente.soler at gmail.com (vsoler) Date: Thu, 19 Aug 2010 13:17:40 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: Message-ID: On Aug 19, 8:55?pm, Tim Golden wrote: > On 19/08/2010 4:55 PM, vsoler wrote: > > > I need to read, for each of the directories in a shared file server > > unit, who has access to the directories and what type of access > > privileges. > > > This is something that I can easily do interactively in my Windows > > Document Explorer by right clicking a single directory, clicking on > > Properties, then on Security. > > > There I can see the Users and Group of Users that have access to the > > selected directory, as well as the type of access to that directory > > (Read/Write/eXecute etc.) > > Here you have one of those occasions when the Windows GUI does > a very good job of presenting a simplified but perfectly usable > interface layer on top of a moderately complex security scheme. > > It's not as easy as you think. > > > I've been looking in the "os" library, and found the "os.chmod" method > > but I am not sure that it is going to give me what I need. Should I > > also used library "stat"? > > No. Both of these are basically doing a best-endeavours job of mapping > certain Windows attributes to some Posix equivalent. They're essentially > useless for anything beyond the most trivial tasks. > > Have a read here which will at least put you on the path of knowing > what terminology you need to search for: > > ? ?http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html > ? ?http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.... > > and if you're interested, this is the kind of thing my winsys > package is reasonably good at: > > ? ?http://timgolden.me.uk/python/winsys/security.html#module-security > > TJG Thank you very much, Tim, for your answer. It looks as though it is going to suit my needs. Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and 2.6. File WinSys-0.4.zip should be for the same versions of Python, probably. What about your WinSys-0.5beta.win32.exe file? is it for python 3? I currently have python 3 in my pc. Do I need to install a previous version of python? Thank you for your help Vicente Soler From dodo_do_not_wake_up at yahoo.fr Thu Aug 19 16:36:04 2010 From: dodo_do_not_wake_up at yahoo.fr (Dodo) Date: Thu, 19 Aug 2010 22:36:04 +0200 Subject: Django 1.2.1 - stuck with CSRF verification In-Reply-To: References: Message-ID: Le 19/08/2010 20:40, Thomas Jollans a ?crit : > On Thursday 19 August 2010, it occurred to Dodo to exclaim: >> Hi all, >> I followed the tutorial but at page 4 I can't get rid of CSRF errors, >> even though I followed everything in this page : >> http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ >> > > what kind of errors? Any exception tracebacks you can show us maybe? Well I fill the form, submit via POST then : Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: No CSRF or session cookie. From nagle at animats.com Thu Aug 19 16:50:43 2010 From: nagle at animats.com (John Nagle) Date: Thu, 19 Aug 2010 13:50:43 -0700 Subject: String substitution VS proper mysql escaping In-Reply-To: References: <4C6BA2C4.4000309@gmail.com> Message-ID: <4c6d991f$0$1661$742ec2ed@news.sonic.net> On 8/18/2010 2:50 AM, Cameron Simpson wrote: > On 18Aug2010 12:07, Nik Gr wrote: > | ???? 18/8/2010 7:31 ??, ?/? Cameron Simpson ??????: > |>On 17Aug2010 20:15, ????? wrote: > |>| =============================== > |>| cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = > |>| '%s' ORDER BY date DESC ''' % (page) ) > |>| =============================== > |>| > |>| Someone told me NOT to do string substitution ("%") on SQL statements > |>| and to let MySQLdb do it > |>| for me, with proper escaping like the following > |>| > |>| =============================== > |>| cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s > |>| ORDER BY date DESC''', (page,)) > |>| =============================== > |>| > |>| The difference is that if some external source can control "page", > |>| and > |>| they put in a value like > |>| 100 ; DELETE FROM visitors; SELECT * FROM visitors > |>| i will be losing my database table data. > |> > |>That other difference is that the mysql dialect support knows how to > |>correctly escape a string for insertion into an SQL statement. You may > |>not, or may forget to pre-escape the string, etc. Using the MySQLdb > |>stuff do it for you is reliable and robust. > | > | Can you please tell me what escaping means by giving me an example > | of what is escaped and whats isn't? > > In your plain substitution example above: > > cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = > '%s' ORDER BY date DESC ''' % (page) ) > > Supposing page is the string "100". This will produce the SQL statement: > > SELECT host, hits, date FROM visitors WHERE page = '100' ORDER BY date DESC > > which looks ok. But suppose page was the string: > > bill o'reilly > > Then your SQL statement looks like this: > > SELECT host, hits, date FROM visitors WHERE page = 'bill o'reilly' ORDER BY date DESC > > To the SQL engine this looks like the string "bill o" followed by an SQL > instruction named "reilly", and then the opening quote for another string. > Invalid SQL. > > The procedure used to avoid this problem (to insert an _arbitrary_ > string into the SQL statement) is to "escape" problematic characters in > strings when placing them into SQL statements. In this case, the quote > character in the string is the SQL "end string" character. Therefore the > string must be modified in the SQL statement to be correctly expressed. > > IIRC, SQL uses the quote doubling convention for strings, so this: > > SELECT host, hits, date FROM visitors WHERE page = 'bill o''reilly' ORDER BY date DESC > > is how one would write the literal SQL for that. > > The MySQLdb library will do this and a host of other equivalent things > automatically and correctly and consistently when you pass page as a > parameter to the execute() method, needing no special attention or > detailed syntactic knowledge on your part when you write your program. Right. There's much mystery about this, but it's really simple. All MySQLdb is doing for cursor.execute(sqlstring, values) is quotedstr = sqlstring % map(MySQLdb.escape_string, values) cursor.execute(quotedstr) It just applies "MySQLdb.escape_string to each arg. If PHP did that, we'd have far fewer "SQL injection attacks". Most programs shouldn't use "MySQLdb.escape", and should let the built-in call do it. It's useful, though, if you're constructing a data file for LOAD DATA to do a bulk database load. The same escaping works for LOAD DATA INFILE with the default input format. John Nagle From tjreedy at udel.edu Thu Aug 19 16:57:52 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Aug 2010 16:57:52 -0400 Subject: Creating a PYD file In-Reply-To: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> References: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> Message-ID: On 8/19/2010 3:41 PM, Rony wrote: > is a PYD file created from C faster then a PYD file from Pyrex ? Since a .pyd file from Pyrex is also from C, the question is ill-posed. It is equivalent to "Does the C code generated by Pyrex compile to faster or slower machine code than the C code generated by some other person or program?". Leaving compiler variations aside, the answer depend on the proficiency of the other source in relation to the particular function being computed. Perhaps you already answered this... > I know it will depend on how it is written, depending on what you meant by 'it'. To be fair, the two code have to have exactly the same input/output relationships, including exception raising. -- Terry Jan Reedy From mail at timgolden.me.uk Thu Aug 19 16:59:04 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 19 Aug 2010 21:59:04 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: <4C6D9B18.6070308@timgolden.me.uk> On 19/08/2010 9:17 PM, vsoler wrote: > On Aug 19, 8:55 pm, Tim Golden wrote: >> On 19/08/2010 4:55 PM, vsoler wrote: >> >>> I need to read, for each of the directories in a shared file server >>> unit, who has access to the directories and what type of access >>> privileges. >> >>> This is something that I can easily do interactively in my Windows >>> Document Explorer by right clicking a single directory, clicking on >>> Properties, then on Security. >> >>> There I can see the Users and Group of Users that have access to the >>> selected directory, as well as the type of access to that directory >>> (Read/Write/eXecute etc.) >> >> Here you have one of those occasions when the Windows GUI does >> a very good job of presenting a simplified but perfectly usable >> interface layer on top of a moderately complex security scheme. >> >> It's not as easy as you think. >> >>> I've been looking in the "os" library, and found the "os.chmod" method >>> but I am not sure that it is going to give me what I need. Should I >>> also used library "stat"? >> >> No. Both of these are basically doing a best-endeavours job of mapping >> certain Windows attributes to some Posix equivalent. They're essentially >> useless for anything beyond the most trivial tasks. >> >> Have a read here which will at least put you on the path of knowing >> what terminology you need to search for: >> >> http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html >> http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.... >> >> and if you're interested, this is the kind of thing my winsys >> package is reasonably good at: >> >> http://timgolden.me.uk/python/winsys/security.html#module-security >> >> TJG > > Thank you very much, Tim, for your answer. > > It looks as though it is going to suit my needs. > > Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and > 2.6. > File WinSys-0.4.zip should be for the same versions of Python, > probably. > What about your WinSys-0.5beta.win32.exe file? is it for python 3? > > I currently have python 3 in my pc. Do I need to install a previous > version of python? > > Thank you for your help > > Vicente Soler I have a subversion branch for Python 3. If you have subversion access, try: http://winsys.googlecode.com/svn/branches/py3k and do the python setup.py install dance. If you can't get that working, let me know and I'll publish an installer somewhere. TJG From raoulbia at gmail.com Thu Aug 19 17:12:44 2010 From: raoulbia at gmail.com (Baba) Date: Thu, 19 Aug 2010 14:12:44 -0700 (PDT) Subject: Iterative vs. Recursive coding Message-ID: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Level: Beginner exercise source: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf I am looking at the first problem in the above assignment. The assignemnt deals, amongst others, with the ideas of iterative vs. recursive coding approaches and i was wondering what are the advantages of each and how to best chose between both options? I had a go at the first part of the exercise and it seems that i can handle it. However i think my Recursive version can be improved. By the way, is my code actually proper recursive code? part 1 iterative approach: from string import * def countSubStringMatch(target,key): counter=0 fsi=0 #fsi=find string index while fsi Message-ID: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> On Aug 19, 10:59?pm, Tim Golden wrote: > On 19/08/2010 9:17 PM, vsoler wrote: > > > > > On Aug 19, 8:55 pm, Tim Golden ?wrote: > >> On 19/08/2010 4:55 PM, vsoler wrote: > > >>> I need to read, for each of the directories in a shared file server > >>> unit, who has access to the directories and what type of access > >>> privileges. > > >>> This is something that I can easily do interactively in my Windows > >>> Document Explorer by right clicking a single directory, clicking on > >>> Properties, then on Security. > > >>> There I can see the Users and Group of Users that have access to the > >>> selected directory, as well as the type of access to that directory > >>> (Read/Write/eXecute etc.) > > >> Here you have one of those occasions when the Windows GUI does > >> a very good job of presenting a simplified but perfectly usable > >> interface layer on top of a moderately complex security scheme. > > >> It's not as easy as you think. > > >>> I've been looking in the "os" library, and found the "os.chmod" method > >>> but I am not sure that it is going to give me what I need. Should I > >>> also used library "stat"? > > >> No. Both of these are basically doing a best-endeavours job of mapping > >> certain Windows attributes to some Posix equivalent. They're essentially > >> useless for anything beyond the most trivial tasks. > > >> Have a read here which will at least put you on the path of knowing > >> what terminology you need to search for: > > >> ? ?http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html > >> ? ?http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.... > > >> and if you're interested, this is the kind of thing my winsys > >> package is reasonably good at: > > >> ? ?http://timgolden.me.uk/python/winsys/security.html#module-security > > >> TJG > > > Thank you very much, Tim, for your answer. > > > It looks as though it is going to suit my needs. > > > Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and > > 2.6. > > File WinSys-0.4.zip should be for the same versions of Python, > > probably. > > What about your WinSys-0.5beta.win32.exe file? is it for python 3? > > > I currently have python 3 in my pc. Do I need to install a previous > > version of python? > > > Thank you for your help > > > Vicente Soler > > I have a subversion branch for Python 3. If you have subversion > access, try: > > ? ?http://winsys.googlecode.com/svn/branches/py3k > > and do the python setup.py install dance. > > If you can't get that working, let me know and I'll publish > an installer somewhere. > > TJG I currently do not have subversion access in my PC. I could try to install a free copy of it. But it you could ptovide an installer, it certainly would do things easier. Please let me know if it is possible. Vicente Soler From chris at simplistix.co.uk Thu Aug 19 17:25:56 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 19 Aug 2010 22:25:56 +0100 Subject: bug? context managers vs ImportErrors In-Reply-To: References: <4C6D54A6.4060107@simplistix.co.uk> Message-ID: <4C6DA164.4000608@simplistix.co.uk> Christian Heimes wrote: >> Why is 'e' ending up as a string rather than the ImportError object? >> >> This is with Python 2.6.5 if that makes a difference... > > It's a known bug in Python 2.6 and earlier. See > http://docs.python.org/whatsnew/2.7.html#porting-to-python-2-7 When was it introduced? I've been relying on the value being an exception a lot in 2.5, and only hit problems in 2.6 with ImportError, everything else seems fine, which doesn't agree with Florent's statements in #7853... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From emile at fenx.com Thu Aug 19 17:31:14 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Aug 2010 14:31:14 -0700 Subject: Reading the access attributes of directories in Windows In-Reply-To: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> Message-ID: On 8/19/2010 2:17 PM vsoler said... > On Aug 19, 10:59 pm, Tim Golden wrote: >> I have a subversion branch for Python 3. If you have subversion >> access, try: >> >> http://winsys.googlecode.com/svn/branches/py3k >> >> and do the python setup.py install dance. >> >> If you can't get that working, let me know and I'll publish >> an installer somewhere. >> >> TJG > > I currently do not have subversion access in my PC. I could try to > install a free copy of it. I like this one for windows... http://tortoisesvn.net/downloads Emile From benjamin at python.org Thu Aug 19 17:33:11 2010 From: benjamin at python.org (Benjamin Peterson) Date: Thu, 19 Aug 2010 21:33:11 +0000 (UTC) Subject: bug? context managers vs ImportErrors References: <4C6D54A6.4060107@simplistix.co.uk> <4C6DA164.4000608@simplistix.co.uk> Message-ID: Chris Withers simplistix.co.uk> writes: > When was it introduced? It depends on how the exception was raised. From thomas at jollybox.de Thu Aug 19 17:41:36 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Thu, 19 Aug 2010 23:41:36 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <201008192341.36445.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to Baba to exclaim: > def countSubStringMatchRecursive(target,key): > counter=0 > fsi=0 #fsi=find string index > if len(key)==len(target): #base case > if key==target: > counter+=1 > elif len(key) while fsi fsi=target.find(key,fsi) > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > else: > print 'key is longer than target...' > > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcat > atgc") This is not recursive. In fact, it's exactly the same approach as the first one, plus a bit of an if statement. Take another good look at the definition of "recursion" I'm sure you were given. To sum it up: "iterate": use a loop. and again. and again. and again. and again. and aga.... "recurse": consider. recurse. This is another good one: http://mytechquest.com/blog/wp-content/uploads/2010/05/From-a-Programming-Book.jpg - Thomas PS: If you think you're thinking, then you're really only thinking that you're thinking. Or are you? From python at mrabarnett.plus.com Thu Aug 19 17:45:53 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Aug 2010 22:45:53 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4C6DA611.5090300@mrabarnett.plus.com> Baba wrote: > Level: Beginner > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf > > I am looking at the first problem in the above assignment. The > assignemnt deals, amongst others, with the ideas of iterative vs. > recursive coding approaches and i was wondering what are the > advantages of each and how to best chose between both options? > > I had a go at the first part of the exercise and it seems that i can > handle it. However i think my Recursive version can be improved. By > the way, is my code actually proper recursive code? > > part 1 iterative approach: > > from string import * > def countSubStringMatch(target,key): > counter=0 > fsi=0 #fsi=find string index > while fsi fsi=target.find(key,fsi) > #print fsi > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatch("atgacatgcacaagtatgcat","zzz") > > > part 2 recursive approach: > > > def countSubStringMatchRecursive(target,key): > counter=0 > fsi=0 #fsi=find string index > if len(key)==len(target): #base case > if key==target: > counter+=1 > elif len(key) while fsi fsi=target.find(key,fsi) > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > else: > print 'key is longer than target...' > > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcatatgc") > 'countSubStringMatchRecursive' isn't recursive at all. From dan.kluev at gmail.com Thu Aug 19 17:48:33 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Fri, 20 Aug 2010 08:48:33 +1100 Subject: Iterative vs. Recursive coding In-Reply-To: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 8:12 AM, Baba wrote: > Level: Beginner > > exercise source: > > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf > > I am looking at the first problem in the above assignment. The > assignemnt deals, amongst others, with the ideas of iterative vs. > recursive coding approaches and i was wondering what are the > advantages of each and how to best chose between both options? > > With Python, I'd avoid using recursions unless it is absolutely needed / much simpler than iteration and depth is known in advance, and not exceeds the limit. Reason is that Python does not optimize recursion calls, and even tail recursions get own stack frame on each call. It is more expensive than iteration and risks to exceed max recursion depth. part 2 recursive approach: > > > def countSubStringMatchRecursive(target,key): > counter=0 > fsi=0 #fsi=find string index > if len(key)==len(target): #base case > if key==target: > counter+=1 > elif len(key) while fsi fsi=target.find(key,fsi) > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > else: > print 'key is longer than target...' > > print '%s is %d times in the target string' %(key,counter) > > > countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcatatgc") > Maybe I'm missing something, but this one seems to be iterative too. Recursive is one which calls itself, like def countSubString(haystack, needle): def checkMatch(haystack, needle): if not needle: return True elif not haystack: return False elif haystack[0] == needle[0]: return checkMatch(haystack[1:], needle[1:]) else: return False return len(filter(bool, map(lambda i: checkMatch(haystack[i:], needle), range(len(haystack))))) Where checkMatch would be called recursively to match needle over particular part of haystack. -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Thu Aug 19 17:53:16 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Thu, 19 Aug 2010 23:53:16 +0200 Subject: Creating a PYD file In-Reply-To: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> References: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> Message-ID: > (Pseudo code) > > result = arg1 + arg2 > return result For this code, the manually-written version will most likely be faster than the Pyrex-generated one. This is, most likely, because the manually-written version will assume a specific data type for the arguments (e.g. int), which Pyrex will not. As a consequence, the manually-written version will be more restricted than the Pyrex one, and most likely, that will be acceptable in your application. Theoretically speaking. Regards, Martin From martin at address-in-sig.invalid Thu Aug 19 18:00:16 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Thu, 19 Aug 2010 22:00:16 +0000 (UTC) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: On Thu, 19 Aug 2010 14:12:44 -0700, Baba wrote: > Level: Beginner > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer- science/6-00-introduction-to-computer-science-and-programming-fall-2008/ assignments/pset3.pdf > > I am looking at the first problem in the above assignment. The > assignemnt deals, amongst others, with the ideas of iterative vs. > recursive coding approaches and i was wondering what are the advantages > of each and how to best chose between both options? > > I had a go at the first part of the exercise and it seems that i can > handle it. However i think my Recursive version can be improved. By the > way, is my code actually proper recursive code? > No, it isn't. By way of a hint, here are two versions of the classic example of recursion: calculating factorials. Recursion can be quite a trick to get your mind round at first, so compare the two and follow through their operation step by step... ------------------------------------------------- def i_factorial(n): "Iterative factorial calculation" f = 1; for n in range(1, n+1): f = f * n return f def r_factorial(n): "Recursive factorial calculation" if (n > 1): return n * r_factorial(n - 1) else: return 1 print i_factorial.__doc__ for n in range(1,10): print "%d! = %d" % (n, i_factorial(n)) print r_factorial.__doc__ for n in range(1,10): print "%d! = %d" % (n, r_factorial(n)) ----------------------------------------- In case you're wondering "print i_factorial.__doc__" prints the docstring out of the i_factorial subroutine. You probably haven't covered that yet, but run it and see. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From thomas at jollybox.de Thu Aug 19 18:04:29 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 20 Aug 2010 00:04:29 +0200 Subject: Reading the access attributes of directories in Windows In-Reply-To: <4C6D7E2A.9010703@timgolden.me.uk> References: <4C6D7E2A.9010703@timgolden.me.uk> Message-ID: <201008200004.30289.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to Tim Golden to exclaim: > On 19/08/2010 4:55 PM, vsoler wrote: > > I've been looking in the "os" library, and found the "os.chmod" method > > but I am not sure that it is going to give me what I need. Should I > > also used library "stat"? > > No. Both of these are basically doing a best-endeavours job of mapping > certain Windows attributes to some Posix equivalent. They're essentially > useless for anything beyond the most trivial tasks. This brings up an interesting, but probably quite complicated question: is it reasonable to try to express Windows permissions using full POSIX ACLs (not the traditional UNIX mode, the full-featured complex beast that most users know nothing about and that many file systems don't enable by default) -- or is it, maybe, possible to express the Windows permissions model as a subset of POSIX ACL? I'm no expert either, but the basic idea is that you replace the traditional UNIX model with one where not only does every file have an owner and an owning group, and r/w/x permission bits for owner, group, and "the rest", but you can also specify permissions for arbitrary users and groups, in addition to the standard set. I'm leaving out all the details, of course, first and foremost those I don't know about myself, but that's essentially it. Do Windows NT permissions do anything more? Or, apart from the "executable" bit, anything less, for that matter? Just asking. Maybe there are some experts around. - Thomas From davea at ieee.org Thu Aug 19 18:15:15 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 19 Aug 2010 18:15:15 -0400 Subject: Iterative vs. Recursive coding In-Reply-To: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4C6DACF3.3010103@ieee.org> Baba wrote: > Level: Beginner > > exercise source: > http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf > > I am looking at the first problem in the above assignment. The > assignemnt deals, amongst others, with the ideas of iterative vs. > recursive coding approaches and i was wondering what are the > advantages of each and how to best chose between both options? > > I had a go at the first part of the exercise and it seems that i can > handle it. However i think my Recursive version can be improved. By > the way, is my code actually proper recursive code? > > part 1 iterative approach: > > from string import * > def countSubStringMatch(target,key): > counter=0 > fsi=0 #fsi=find string index > while fsi fsi=target.find(key,fsi) > #print fsi > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatch("atgacatgcacaagtatgcat","zzz") > > > part 2 recursive approach: > > > def countSubStringMatchRecursive(target,key): > counter=0 > fsi=0 #fsi=find string index > if len(key)==len(target): #base case > if key==target: > counter+=1 > elif len(key) while fsi fsi=target.find(key,fsi) > if fsi!=-1: > counter+=1 > else: > break > fsi=fsi+1 > else: > print 'key is longer than target...' > > print '%s is %d times in the target string' %(key,counter) > > countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcatatgc") > > > tnx > Baba > > A function that doesn't call itself (directly or indirectly) isn't recursive. So you don't have any recursion here. An example of recursion might be where your function simply compares the key to the beginning of the target, then calls itself with a substring of the target ( target[1:] ) Don't forget to return 0 if the target is smaller than the key. And take the print out of the recursive function. Write a separate function that does that, after calling the worker function. DaveA From nobody at nowhere.com Thu Aug 19 18:40:15 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 19 Aug 2010 23:40:15 +0100 Subject: path to data files References: <87wrrm9445.fsf@dpt-info.u-strasbg.fr> Message-ID: On Thu, 19 Aug 2010 14:30:34 +0200, Alain Ketterlin wrote: >> If a python module requires a data file to run how would I reference >> this data file in the source in a way that does not depend on whether >> the module is installed system-wide, installed in $HOME/.local or is >> just placed in a directory from where the interpreter is fired up? > > sys.path[0] is supposed to contain the script's directory. One caveat: if you use wxPython, wxversion.select() pushes the directory containing the selected version at the front of sys.path, so that a subsequent "import wx" will import the correct version. It's possible that other functions may do likewise, so if you're relying upon sys.path[0] to find the script's directory, it's a good idea to make a copy of sys.path[0] before importing any modules (other than sys). From python at mrabarnett.plus.com Thu Aug 19 19:04:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 20 Aug 2010 00:04:26 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: <201008192341.36445.thomas@jollybox.de> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <201008192341.36445.thomas@jollybox.de> Message-ID: <4C6DB87A.5040100@mrabarnett.plus.com> Thomas Jollans wrote: [snip] > "iterate": use a loop. and again. and again. and again. and again. and aga.... > > "recurse": consider. recurse. > > This is another good one: > > http://mytechquest.com/blog/wp-content/uploads/2010/05/From-a-Programming-Book.jpg > The definition for recursion looks a lot like that for infinite loop. Perhaps because it's tail-recursive? From nobody at nowhere.com Thu Aug 19 19:08:03 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 20 Aug 2010 00:08:03 +0100 Subject: Reading the access attributes of directories in Windows References: <4C6D7E2A.9010703@timgolden.me.uk> Message-ID: On Fri, 20 Aug 2010 00:04:29 +0200, Thomas Jollans wrote: > This brings up an interesting, but probably quite complicated question: is it > reasonable to try to express Windows permissions using full POSIX ACLs > Do Windows NT permissions do anything more? Or, apart from the > "executable" bit, anything less, for that matter? 1. There are far more permission types than just "rwx". Specifically: For files: Execute File Read Data Write Data Append Data For folders: Traverse Folder List Folder Create Files Create Folders Delete Subfolders and Files For both: Full Control Read Attributes Read Extended Attributes Write Attributes Write Extended Attributes Delete Read Permissions Change Permissions Take Ownership Note that files/folders have a distinct "Delete" permission, as well as the "Delete Subfolders and Files" permission on the parent folder. Unix lacks the "Append Data" permission for files, and the "Create Files", "Create Folders" and "Delete Subfolders and Files" correspond to having write permission on a directory. On Unix, you can read permissions (and attributes if the filesystem has them) for any file which you can "reach" (i.e. have "x" permission on all ancestor directories). You can only change permissions (and some attributes) if you own the file, and only root can change ownership (and change some attributes). 2. Permissions can be inherited from the "parent object" (which isn't necessarily the parent folder). If you change a permission on the parent object, it automatically affects any file or folder which inherits the permission. 3. The owner can be either a user or a group. 4. On Windows, a file cannot be "given away" either by its owner or an administrator. You can grant the "Take Ownership" permission, but the recipient still has to explicitly change the ownership. From tundra at tundraware.com Thu Aug 19 19:27:11 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 19 Aug 2010 18:27:11 -0500 Subject: Using String Methods In Jump Tables Message-ID: Problem: Given tuples in the form (key, string), use 'key' to determine what string method to apply to the string: key operation ----------------------- l lower() u upper() t title() ... Commentary: Easy, right? Well ... except that I would really, really like to avoid cascading ifs or eval based solutions. I'd like to implement this as a jump table dictionary: jt = { 'l' : lower_function reference, 'u' : upper_function reference, ... } So I could then do this: string = jt[key](string) But There's A Problem: I tried to do this: jt = {'l', "".lower, 'u', "".upper, ... } You can get away with this because all string objects appear to point to common method objects. That is,: id("a".lower) == id("b".lower) HOWEVER, you cannot then do this: string = jt[key](string) Why? Because the methods of a string, while common to all strings *do not accept an arg*. They are implemented to "know" about the string instance they "belong to" (that contains them). (Forgive me here, I am probably not using some of the OO arcana properly...) I realize that the string module has many of the same functions that are found as methods on strings. But it doesn't have all of them - the .title() method is notably absent. If this were not the case, I could happily do things like 'l' : string.lower and my approach would work fine. Even if I could use the string module, I'd still be curious though: How do you get a reference to a method found in one object instance, but actually apply it to another instance of the same class? I'm guessing this may involve fiddling with some of the internal __ variables, but I'm not quite sure where to go next. As I said, I know I could do this as a set of cascading ifs or even as an eval, but I'm loathe to use such approaches. I like jump tables as a structural construct because they are easy to understand and maintain. I also realize that what I'm asking may be violating some deeply held notion of OO purity, but, well, now I'm just curious if there is a way to do this ... ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From nfdisco at gmail.com Thu Aug 19 19:39:10 2010 From: nfdisco at gmail.com (ernest) Date: Thu, 19 Aug 2010 16:39:10 -0700 (PDT) Subject: expression in an if statement References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> <201008190012.32074.thomas@jollybox.de> Message-ID: <8c31eb1c-bf5e-4774-aec0-5fca14547482@j18g2000yqd.googlegroups.com> On 19 Ago, 08:40, Frederic Rentsch wrote: > On Thu, 2010-08-19 at 00:12 +0200, Thomas Jollans wrote: > > On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: > > > On 8/18/2010 11:24 AM, ernest wrote: > > > > Hi, > > > > > In this code: > > > > > if set(a).union(b) == set(a): pass > > > > > Does Python compute set(a) twice? > > > > ? ? CPython does. ?Shed Skin might optimize. ?Don't know > > > about Iron Python. > > > I doubt any actual Python implementation optimizes this -- how could it? > > And why should it if a programmer uses its facilities inefficiently. I > would write > > >>> if set(a).issuperset (b): pass > > Frederic Yes, maybe the example is silly, but situations like this arise frequently and it's good to know. Thanks for the answers. Ernest From clp2 at rebertia.com Thu Aug 19 19:41:27 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 19 Aug 2010 16:41:27 -0700 Subject: Using String Methods In Jump Tables In-Reply-To: References: Message-ID: On Thu, Aug 19, 2010 at 4:27 PM, Tim Daneliuk wrote: > Problem: > > ?Given tuples in the form (key, string), use 'key' to determine > ?what string method to apply to the string: > > ? ?key ? ? ? ? ? operation > ? ?----------------------- > > ? ? l ? ? ? ? ? ?lower() > ? ? u ? ? ? ? ? ?upper() > ? ? t ? ? ? ? ? ?title() > ? ? ... > > Commentary: > > ? Easy, right? ?Well ... except that I would really, really like > ? to avoid cascading ifs or eval based solutions. ?I'd like to implement > ? this as a jump table dictionary: > > ? ? jt = { 'l' : lower_function reference, > ? ? ? ? ? ?'u' : upper_function reference, > ? ? ? ? ? ? ... > ? ? ? ? ?} > > ? So I could then do this: > > ? ? string = jt[key](string) > > But There's A Problem: > > ? I tried to do this: > > ? ? jt = {'l', "".lower, > ? ? ? ? ? 'u', "".upper, > ? ? ? ? ? ... > ? ? ? ? ?} > > ? You can get away with this because all string objects appear to point to common > ? method objects. ?That is,: id("a".lower) == id("b".lower) > > ? HOWEVER, you cannot then do this: > > ? ? string = jt[key](string) > > ? Why? ?Because the methods of a string, while common to all strings > ? *do not accept an arg*. ?They are implemented to "know" about the > ? string instance they "belong to" (that contains them). Right; by looking the method up on an instance you get a "bound" method that is "bound" to the instance you got it from and already has self filled-in. > (Forgive me here, I am probably not using some of the OO arcana properly...) > > > ? How do you get a reference to a method found in one object instance, but > ? actually apply it to another instance of the same class? ?I'm guessing this may > ? involve fiddling with some of the internal __ variables, but I'm not > ? quite sure where to go next. You must access the method from the class rather than the instance; this produces an "unbound" method that is not bound to a specific instance and does not have self already filled-in. In your dictionary, replace "".lower with str.lower, and so on for the other methods. Cheers, Chris -- http://blog.rebertia.com From doulos05 at gmail.com Thu Aug 19 19:42:50 2010 From: doulos05 at gmail.com (JonathanB) Date: Thu, 19 Aug 2010 16:42:50 -0700 (PDT) Subject: extra rows in a CSV module output when viewed in excel 2007 References: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> Message-ID: <8e0e7501-ffd7-4faa-ada8-1a6c097d01f3@f6g2000pro.googlegroups.com> On Aug 13, 3:52?pm, alex23 wrote: > On Aug 13, 4:22?pm, JonathanB wrote: > > > ? ? ? ? writer = csv.writer(open(output, 'w'), dialect='excel') > > I think - not able to test atm - that if you open the file in 'wb' > mode instead it should be fine. changed that to writer = csv.writer(open(output,'wb'),dialect='excel') Now I get this error: TypeError: must be bytes or buffer, not str I'm using Python 3.1, maybe that changes things? From python at mrabarnett.plus.com Thu Aug 19 20:10:29 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 20 Aug 2010 01:10:29 +0100 Subject: extra rows in a CSV module output when viewed in excel 2007 In-Reply-To: <8e0e7501-ffd7-4faa-ada8-1a6c097d01f3@f6g2000pro.googlegroups.com> References: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> <8e0e7501-ffd7-4faa-ada8-1a6c097d01f3@f6g2000pro.googlegroups.com> Message-ID: <4C6DC7F5.5000300@mrabarnett.plus.com> JonathanB wrote: > On Aug 13, 3:52 pm, alex23 wrote: >> On Aug 13, 4:22 pm, JonathanB wrote: >> >>> writer = csv.writer(open(output, 'w'), dialect='excel') >> I think - not able to test atm - that if you open the file in 'wb' >> mode instead it should be fine. > > changed that to > writer = csv.writer(open(output,'wb'),dialect='excel') > > Now I get this error: > > TypeError: must be bytes or buffer, not str > > I'm using Python 3.1, maybe that changes things? You want to open the file in text mode, but not write Windows line endings (CRLF) for each newline: writer = csv.writer(open(output, 'w', newline=''), dialect='excel') From doulos05 at gmail.com Thu Aug 19 20:15:47 2010 From: doulos05 at gmail.com (JonathanB) Date: Thu, 19 Aug 2010 17:15:47 -0700 (PDT) Subject: extra rows in a CSV module output when viewed in excel 2007 References: <2c3e09ce-b64b-4aa8-83a2-b2fe8c7a6cae@u31g2000pru.googlegroups.com> <8e0e7501-ffd7-4faa-ada8-1a6c097d01f3@f6g2000pro.googlegroups.com> Message-ID: On Aug 20, 9:10?am, MRAB wrote: > JonathanB wrote: > > On Aug 13, 3:52 pm, alex23 wrote: > >> On Aug 13, 4:22 pm, JonathanB wrote: > > >>> ? ? ? ? writer = csv.writer(open(output, 'w'), dialect='excel') > >> I think - not able to test atm - that if you open the file in 'wb' > >> mode instead it should be fine. > > > changed that to > > writer = csv.writer(open(output,'wb'),dialect='excel') > > > Now I get this error: > > > TypeError: must be bytes or buffer, not str > > > I'm using Python 3.1, maybe that changes things? > > You want to open the file in text mode, but not write Windows line > endings (CRLF) for each newline: > > ? ? ?writer = csv.writer(open(output, 'w', newline=''), dialect='excel') That was it! Thank you, I knew it was something stupid. It's been so long (6 months) since I coded, I forgot about how Windows/Mac mangle line endings. From cri at tiac.net Thu Aug 19 20:18:29 2010 From: cri at tiac.net (Richard Harter) Date: Fri, 20 Aug 2010 00:18:29 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: <4c6d56b0.616794210@text.giganews.com> On Thu, 19 Aug 2010 04:14:42 -0700 (PDT), spinoza1111 wrote: >On Aug 18, 1:44=A0am, James Kanze wrote: >> On Aug 17, 6:21 pm, Standish P wrote: >> >> > > Garbage collection doesn't use a stack. It uses a "heap", >> > > which is in the abstract a collection of memory blocks of >> > > different lengths, divided into two lists, generally >> > > represented as linked lists: >> > > 1. =A0A list of blocks that are free and may be used to store >> > > new data >> > > 2. =A0A list of blocks that are in use, or haven't been freed (yet) >> > Is this all that a heap is or is there more to it ? >> >> There are many different ways to implement a heap. =A0The above is >> not a good one, and I doubt that it's really used anywhere. > >Actually, that's the only way to implement a heap in the abstract. >Forest and trees, mate. Mathematically a heap is a block of storage, a >list of free blocks and a list of allocated blocks. All the rest is >detail for the little techies to normally, get wrong. The confusion >between scientific and technical progress is a mirror of the (far more >serious) confusion between scientific progress and ethical advance. > >Sure, when you free a block it is a good idea to see if you can join >it with its neighbors to get the biggest "bang for the buck". [snip] I appreciate your desire to provide a "mathematical" definition but the one you gave won't quite do. Your definition does not specify what is meant by a block. The notion of defining a heap as a list of free list and a list of allocated blocks is unfortunate. Neither a free list nor a list of allocated blocks is of the essence. It isn't easy to give a good definition of a heap (in the sense of a storage heap) but here is a shot at it. A heap is a data structure consisting of a pair (H,B) of substructures, operations (split,join), and attribute A where: H is a set of sequentially addressable elements. That is, the elements form a sequence, each element has an integer associated with it (its address) and the difference between the addresses of successive elements is a constant, w. Let h_i be the address of the initial element of H and h_f be the address of the final element of H. B is a set of integers such that (1) each element b of B is an address of an element of H, and (2) h_i and h_f are elements of B. From this definition we can define the successor succ(b) of each element (h_f has no successor) and we can order B if we wish. Given the construction of succ on B we can define block(b) as the set of elements in H such that their addresses a satisfy b <= a < succ(a) It is trivial to prove that the blocks of B divide H into disjoint subsets that cover H. The attribute A is defined for elements of B. A(b) may have either of two values - free and inuse. A block b is said to be free if A(b) = free and in use if A(b) = inuse. An address, h, of H is said to be free if A(largest address b in B that is <= h) = free and in use otherwise. Now for the two operations: The join operator operates on all free elements of b except h_f. It removes the successor of an element of b. The effect is to set succ(b) := succ(succ(b)). The split operator operates on all free element addresses in H that are not element addresses in B. Let s be the argument for split. Split adds s to B. The effect of split is to find the largest address b in B that is smaller than s, set succ(s) := succ(b) and succ(b) := s. Note that the successor changes implicitly follow from the definitions of H, B, split, and join. The above definition covers defining a storage heap. It establishes what blocks are, what the sequence of blocks is, and how to alter the sequence of blocks. The important thing here is that free lists/allocated lists are not basic abstractions; rather they are derived concepts based on the primitive concept of a block and the operations performed on a set of blocks. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 20:23:57 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2010 00:23:57 GMT Subject: Using String Methods In Jump Tables References: Message-ID: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: > Problem: > > Given tuples in the form (key, string), use 'key' to determine what > string method to apply to the string: >>> table = {'l': str.lower, 'u': str.upper} >>> table['u']('hello world') 'HELLO WORLD' [...] > As I said, I know I could do this as a set of cascading ifs or even as > an eval, but I'm loathe to use such approaches. I like jump tables as a > structural construct because they are easy to understand and maintain. I > also realize that what I'm asking may be violating some deeply held > notion of OO purity, but, well, now I'm just curious if there is a way > to do this This is Python, not some "pure" OO language. We have functional programming constructs, procedural constructs, and probably other programming models as well. Screw the deeply held notion of OO purity :) But seriously, Python's object model includes bound and unbound methods precisely so you can do this sort of thing, and the above table-based approach is very common and recommended as an alternative to case/switch statements. It's a very common Pythonic idiom, so never fear that people will stone you for using it. The only thing that is a bit unusual is that you call it a jump table. In my experience, "Jump Table" is used for low-level languages where the table values are memory addresses. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 20:26:45 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2010 00:26:45 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: > Recursion can be quite a trick to get your mind round at first Really? Do people actually find the *concept* of recursion to be tricky? If I remember correctly, my puzzlement about recursion lasted about 15 seconds. I remember thinking "How does the function foo know that there is a function foo when foo doesn't fully exist yet?", but once I accepted the fact that it just does it all just seemed obvious. Getting recursion *right* is sometimes tricky, but the idea itself isn't. But then, I grew up watching Doctor Who, and had no problem with the idea that the TARDIS could materialise *inside itself*. And from a very early age, I was familiar with a particular brand of Advocaat liquor where the label on the bottle contained a picture of a rooster holding a bottom of Advocaat, whose label contained a picture of a rooster holding a bottle of Advocaat, whose label contained a picture of a rooster holding a bottle, whose label ... well, you can see where that is going. -- Steven From tundra at tundraware.com Thu Aug 19 20:51:33 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 19 Aug 2010 19:51:33 -0500 Subject: Using String Methods In Jump Tables In-Reply-To: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: On 8/19/2010 7:23 PM, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: > >> Problem: >> >> Given tuples in the form (key, string), use 'key' to determine what >> string method to apply to the string: > >>>> table = {'l': str.lower, 'u': str.upper} >>>> table['u']('hello world') > 'HELLO WORLD' > Aha! That's just what I was looking for. > > [...] >> As I said, I know I could do this as a set of cascading ifs or even as >> an eval, but I'm loathe to use such approaches. I like jump tables as a >> structural construct because they are easy to understand and maintain. I >> also realize that what I'm asking may be violating some deeply held >> notion of OO purity, but, well, now I'm just curious if there is a way >> to do this > > This is Python, not some "pure" OO language. We have functional > programming constructs, procedural constructs, and probably other > programming models as well. Screw the deeply held notion of OO purity :) Yeah, I've never been much impressed with the OO purists. One of the best speeches on the subject I ever saw was by David Korn (of ksh fame) who did a presentation at USENIX one year called "Objecting To Objects". He documented an attempt to write a compiler using purely OO constructs and the many rings of hell that ensued. > > But seriously, Python's object model includes bound and unbound methods > precisely so you can do this sort of thing, and the above table-based > approach is very common and recommended as an alternative to case/switch > statements. It's a very common Pythonic idiom, so never fear that people > will stone you for using it. +1 > > The only thing that is a bit unusual is that you call it a jump table. In > my experience, "Jump Table" is used for low-level languages where the > table values are memory addresses. > > Yeah ... those old assembler memories never quite fade do they. I dunno what you might call this. A Function Dispatch Table perhaps? Thanks to both you and Chris for setting me straight :) -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From tundra at tundraware.com Thu Aug 19 20:52:29 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 19 Aug 2010 19:52:29 -0500 Subject: Using String Methods In Jump Tables In-Reply-To: References: Message-ID: On 8/19/2010 6:41 PM, Chris Rebert wrote: > >> >> How do you get a reference to a method found in one object instance, but >> actually apply it to another instance of the same class? I'm guessing this may >> involve fiddling with some of the internal __ variables, but I'm not >> quite sure where to go next. > > You must access the method from the class rather than the instance; > this produces an "unbound" method that is not bound to a specific > instance and does not have self already filled-in. > In your dictionary, replace "".lower with str.lower, and so on for the > other methods. > > Cheers, > Chris > -- > http://blog.rebertia.com Thanks Chris - just what I needed ... -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From ahleniusm at gmail.com Thu Aug 19 22:02:57 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Thu, 19 Aug 2010 19:02:57 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? Message-ID: Hi, I am relatively new to doing serious work in python. I am using it to access a large number of log files. Some of the logs get corrupted and I need to detect that when processing them. This code seems to work for quite a few of the logs (all same structure) It also correctly identifies some corrupt logs but then it identifies others as being corrupt when they are not. example error msg from below code: Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' Exception: CRC check\ failed 0x8967e931 != 0x4e5f1036L When I manually examine the supposed corrupt log file and use "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " on it, it opens just fine. Is there anything wrong with how I am using this module? (extra code removed for clarity) if tarfile.is_tarfile( file ): try: xf = tarfile.open( file, "r:gz" ) for locFile in xf: logfile = xf.extractfile( locFile ) validFileFlag = True # iterate through each log file, grab the first and the last lines lines = iter( logfile ) firstLine = lines.next() for nextLine in lines: .... continue logfile.close() ... xf.close() except Exception, e: validFileFlag = False msg = "\nCould not open the log file: " + repr(file) + " Exception: " + str(e) + "\n" else: validFileFlag = False lTime = extractFileNameTime( file ) msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive \n" print msg From ldo at geek-central.gen.new_zealand Thu Aug 19 23:09:39 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 20 Aug 2010 15:09:39 +1200 Subject: 79 chars or more? References: Message-ID: In message , Terry Reedy wrote: > A reason not mentioned much is that some people have trouble following > packed lines that are too much longer. Wide-page textbooks routinely put > text in two columns for easier reading. But even 79 columns is too wide for them. So what? From ldo at geek-central.gen.new_zealand Thu Aug 19 23:15:56 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 20 Aug 2010 15:15:56 +1200 Subject: path to data files References: Message-ID: In message , Daniel Fetchinson wrote: > If a python module requires a data file to run how would I reference > this data file in the source in a way that does not depend on whether > the module is installed system-wide, installed in $HOME/.local or is > just placed in a directory from where the interpreter is fired up? You may want to look at the XDG Base Directory Specification . There is a python- xdg module which implements this. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 19 23:49:05 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2010 03:49:05 GMT Subject: 79 chars or more? References: Message-ID: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 15:09:39 +1200, Lawrence D'Oliveiro wrote: > In message , Terry > Reedy wrote: > >> A reason not mentioned much is that some people have trouble following >> packed lines that are too much longer. Wide-page textbooks routinely >> put text in two columns for easier reading. > > But even 79 columns is too wide for them. So what? I think you're wrong. I just opened a random text book at a random page, and the first line I counted had 84 columns of text. ("Data Structures and Program Design", 2nd Edition, by Robert L Kruse.) Of course source code is written in a monospaced typeface, which is a little wider and consequently fewer characters per page. The book uses right-justified comments, making it easy to count that the maximum line- width used for source code is 79 columns. Most lines are *much* shorter. Excluding comments, the longest line of code I spotted was 64 columns, with a typical line being more like 40 columns. -- Steven From nagle at animats.com Fri Aug 20 00:53:55 2010 From: nagle at animats.com (John Nagle) Date: Thu, 19 Aug 2010 21:53:55 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4c6e0a5e$0$1647$742ec2ed@news.sonic.net> On 8/19/2010 2:41 PM, Thomas Jollans wrote: > On Thursday 19 August 2010, it occurred to Baba to exclaim: > This is not recursive. In fact, it's exactly the same approach as > the first one, plus a bit of an if statement. Right. The original poster seems to be getting their ideas from "http://stackoverflow.com/questions/2308696/substring-recursive-algorithm-not-working" which is a rather confused article, or http://talkbinary.com/programming/c/c-recursion-palindrome/ which really has a recursive, although inefficient, example. If you're really interested in this area, read up on the Boyer-Moore Fast String Search Algorithm, which is the fast way to do this for long strings. For Python, a quick solution is def countSubStringMatch(target, key) : esckey = re.sub(r'(\W)',r'\\\1',key) # put \ escapes into key cnt = len(re.findall(esckey, target)) # find all key and count print('%s is %d times in the target string' %(key,cnt)) >>> countSubStringMatch("atgacatgcacaagtatgcat","ca") ca is 4 times in the target string Enjoy. John Nagle From jrmy.lnrd at gmail.com Fri Aug 20 01:13:18 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Thu, 19 Aug 2010 22:13:18 -0700 (PDT) Subject: Assert statements in python 3.1 Message-ID: This is more of a curiosity question then anything else... I was just wondering why in version 3 of python assertions weren't converted to use parenthesis, since print was. I am just asking because it seems the following line of code would seem more readable as a function: assert 2 + 2 == 5, "Only for very large values of 2." From cs at zip.com.au Fri Aug 20 01:22:43 2010 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 20 Aug 2010 15:22:43 +1000 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C6D7D0D.7040703@gmail.com> References: <4C6D7D0D.7040703@gmail.com> Message-ID: <20100820052243.GA23046@cskk.homeip.net> On 19Aug2010 21:50, Nik Gr wrote: | ???? 19/8/2010 6:58 ??, ?/? Tim Chase ??????: | >It can be written as a non-3-quote string, you just have to escape | >the inner quotes (single & double) and the backslash to be seen: | > | > name = 'My name is "Nikos" and I\'m from Thessaloniki\\Greece' | > name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece" | | So if i enclose the string in double quotes the inner double quotes | have to be escaped while | if i enclose the string in single quotes the inner single quotes | have to be escaped. | | But in 3-single-quoting thing became easier since i don't have to | escape all kind of quotes right? just the backslashes. Well, unless you have the misfortune to want three single quotes in a row inside your 3-single-quoting string... [...snip...] | Why does the page variable which is actually a string needs to be a | tuple or a list and not just as a string which is what it actually | is? With regard to the "%" operator, it considers the string on the left to be a format string with multiple %blah things in it to replace. The thing on the right is a sequence of items to place into the format string. So the thing on the right is _supposed_ to | I have a strong desire to use it like this: | cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page ) | opposed to tuple. Hmm. This isn't the python "%" format operator at all. This is the database API's .execute() method. If it expects its second argument to be a sequence of parameters (which is does) then you need to supply a sequence of parameters. It is that simple! In you usage above you're supplying "page" instead of "(page,)". The latter matches the .execute() method's requirements. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ The fabs of the future will be pressrooms. - overhead by WIRED at the Intelligent Printing conference Oct2006 From nagle at animats.com Fri Aug 20 02:03:03 2010 From: nagle at animats.com (John Nagle) Date: Thu, 19 Aug 2010 23:03:03 -0700 Subject: expression in an if statement In-Reply-To: References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> Message-ID: <4c6e1a93$0$1658$742ec2ed@news.sonic.net> On 8/18/2010 3:12 PM, Thomas Jollans wrote: > On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: >> On 8/18/2010 11:24 AM, ernest wrote: >>> Hi, >>> >>> In this code: >>> >>> if set(a).union(b) == set(a): pass >>> >>> Does Python compute set(a) twice? >> >> CPython does. Shed Skin might optimize. Don't know >> about Iron Python. > > I doubt any actual Python implementation optimizes this -- how could it? The > object "set" is clearly being called twice, and it happens to be called with > the object "a" as a sole argument twice. What if "set" has side effects? A > compiler could only exclude this possibility if it knew exactly what "set" > will be at run time, which it can't. That just reflects the rather lame state of Python implementations. For some other languages, there are JIT compilers that can optimize such things. If you rebind a function at run time, the compiled code has to be invalidated and recompiled with the new binding. The HotSpot Java JIT compiler did this. See http://books.google.com/books?id=GBISkhhrHh8C&pg=PA786&lpg=PA786&dq=JIT+compiler+rebinding&source=bl&ots=GhZa3XbrNu&sig=OVBOnu0vwlVN_B1QC6jc2ltHk_w&hl=en&ei=IhluTLCXOIymsQOW6vy1Cw&sa=X&oi=book_result&ct=result&resnum=9&ved=0CDsQ6AEwCA#v=onepage&q&f=false It's really tough to get this right. There's a huge overhead in either performance or complexity for allowing rebinding of functions during execution. It's also a feature very seldom used after program startup. I was talking to the Facebook guys doing the compiler for PHP, and they said that it was a huge win for them that PHP doesn't allow dynamically replacing a function. John Nagle From nikos.the.gr33k at gmail.com Fri Aug 20 02:04:16 2010 From: nikos.the.gr33k at gmail.com (Nik Gr) Date: Fri, 20 Aug 2010 09:04:16 +0300 Subject: String substitution VS proper mysql escaping In-Reply-To: <20100820052243.GA23046@cskk.homeip.net> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> Message-ID: <4C6E1AE0.1000604@gmail.com> ???? 20/8/2010 8:22 ??, ?/? Cameron Simpson ??????: > [...snip...] > | Why does the page variable which is actually a string needs to be a > | tuple or a list and not just as a string which is what it actually > | is? > > With regard to the "%" operator, it considers the string on the left to > be a format string with multiple %blah things in it to replace. The > thing on the right is a sequence of items to place into the format > string. > I didn't undersatnd. > So the thing on the right is_supposed_ to > | I have a strong desire to use it like this: > | cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page ) > | opposed to tuple. > > Hmm. This isn't the python "%" format operator at all. > This is the database API's .execute() method. > If it expects its second argument to be a sequence of parameters > (which is does) then you need to supply a sequence of parameters. > It is that simple! > > In you usage above you're supplying "page" instead of "(page,)". > The latter matches the .execute() method's requirements. I don't follow either. From Kai.Borgolte at gmx.de Fri Aug 20 03:09:16 2010 From: Kai.Borgolte at gmx.de (Kai Borgolte) Date: Fri, 20 Aug 2010 09:09:16 +0200 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: Russ P. wrote: >> A simple example: Using zero-based indexing, suppose you want to indent >> the string "spam" so it starts at column 4. How many spaces to you >> prepend? No, you won't want to indent a string so it starts at column 4. You simply want to indent the string by four spaces. Like in PEP 8: /Use 4 spaces per indentation level./ > 0123456789 > ? ? spam And of course your text editor will number the columns beginning with one, so the string starts at column 5. 123456789 ? ? spam -- Kai Borgolte, Bonn From stndshp at gmail.com Fri Aug 20 03:13:04 2010 From: stndshp at gmail.com (Standish P) Date: Fri, 20 Aug 2010 00:13:04 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> <518b97c6-78ad-4ce9-9967-c7f72ea74109@5g2000yqz.googlegroups.com> <4c6d356f.608280081@text.giganews.com> Message-ID: <8f5c181f-9333-468c-b44c-9d54672d06e1@f42g2000yqn.googlegroups.com> On Aug 19, 8:25?am, c... at tiac.net (Richard Harter) wrote: > On Wed, 18 Aug 2010 01:39:09 -0700 (PDT), Nick Keighley > > wrote: > >On 17 Aug, 18:34, Standish P wrote: > >> How are these heaps being implemented ? Is there some illustrative > >> code or a book showing how to implement these heaps in C for example ? > >any book of algorithms I'd have thought > >http://en.wikipedia.org/wiki/Dynamic_memory_allocation > >http://www.flounder.com/inside_storage_allocation.htm > >I've no idea how good either of these is > The wikipedia page is worthless. ?The flounder page has > substantial meat, but the layout and organization is a mess. ?A > quick google search didn't turn up much that was general - most > articles are about implementations in specific environments. I second your assessment. What we have is blind leading the blind. "Keith Thompson" A CORPORATE MINDER - with multiple accounts - on a Crusade to limit discussions of useful nature on the usenet, must be giving anti-education, pro- illiteracy corporatists (who did much of studies and development on TAX-PAYER MONEY, maybe from now on we should fund Indian/Chinese/ Vietnamese/Russian/Cuban companies that have a tradition of sharing knowledge from the socialist value system) ,lots of joy because that means more market for their "user-friendly" , "thought-killing" products and high priced courses. You will see how consistently, she gives short replies, that have ZILCH educational contents, compared to the volume of details they boast on their websites they claim know. From Kai.Borgolte at gmx.de Fri Aug 20 03:21:25 2010 From: Kai.Borgolte at gmx.de (Kai Borgolte) Date: Fri, 20 Aug 2010 09:21:25 +0200 Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: Sorry about my previous posting with wrong references, this one should be better. Steven D'Aprano wrote: >A simple example: Using zero-based indexing, suppose you want to indent >the string "spam" so it starts at column 4. How many spaces to you >prepend? No, you won't want to indent a string so it starts at column 4. You simply want to indent the string by four spaces. Like in PEP 8: /Use 4 spaces per indentation level./ >0123456789 > spam And of course your text editor will number the columns beginning with one, so the string starts at column 5. 123456789 ? ? spam -- Kai Borgolte, Bonn From dickinsm at gmail.com Fri Aug 20 03:27:14 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 20 Aug 2010 00:27:14 -0700 (PDT) Subject: Assert statements in python 3.1 References: Message-ID: On Aug 20, 6:13?am, genxtech wrote: > This is more of a curiosity question then anything else... ?I was just > wondering why in version 3 of python assertions weren't converted to > use parenthesis, since print was. > > I am just asking because it seems the following line of code would > seem more readable as a function: > ? ?assert 2 + 2 == 5, "Only for very large values of 2." Well, part of the idea of asserts is that when you're running with optimizations turned on (python -O), asserts should be disabled. But if assert were a normal function then in assert(expensive_check) the argument expensive_check would be evaluated both with 'python' and with 'python -O'. -- Mark From mail at timgolden.me.uk Fri Aug 20 03:36:12 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Aug 2010 08:36:12 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> Message-ID: <4C6E306C.20101@timgolden.me.uk> > I currently do not have subversion access in my PC. I could try to > install a free copy of it. But it you could ptovide an installer, it > certainly would do things easier. Please let me know if it is > possible. Vicente, can you just confirm that you received the installer I sent offlist? I'll try to put winsys on PyPI with installers; just haven't got round to it yes :) TJG From news1234 at free.fr Fri Aug 20 03:47:30 2010 From: news1234 at free.fr (News123) Date: Fri, 20 Aug 2010 09:47:30 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c6e3313$0$16599$426a74cc@news.free.fr> On 08/20/2010 02:26 AM, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: > >> Recursion can be quite a trick to get your mind round at first > > Really? Do people actually find the *concept* of recursion to be tricky? Is this a sincere surprise or are you just boasting? > > If I remember correctly, my puzzlement about recursion lasted about 15 > seconds. I remember thinking "How does the function foo know that there > is a function foo when foo doesn't fully exist yet?", but once I accepted > the fact that it just does it all just seemed obvious. Getting recursion > *right* is sometimes tricky, but the idea itself isn't. Well there's two things where I remember, that at least quite some people in our class (at least the ones who didn't do maths or programming in their spare time) had problems with. This were recursion and Mathematical induction. (quite the same though) The fact, that you didn't have the issue doens't mean it's easy for others. From kara at kara-moon.com Fri Aug 20 04:16:56 2010 From: kara at kara-moon.com (Rony) Date: Fri, 20 Aug 2010 01:16:56 -0700 (PDT) Subject: A question to experienced Pythoneers Message-ID: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Here's the story : I've been hired by a company as a consultant to reorganise there development department. The actual situation is : The manager of the development has been fired, main reason (what they told me) is that they have big big troubles in keeping deadlines ! For there last product, for which they estimated 3 man years of development they had 9 months extra effort, and the product was delivered a year to late. I basicaly have 'carte blanche' :) One of my plans is to introduce Python as development tool. They mostly develop back-office software, and at the moment they do it all in C with MFC. Another new requirement they have, is that the new product should run on Win & Mac. So, my strategie would be : - Use Python and wxpython for the GUI - Develop critical routines in Pyrex or in C and make PYD's from it which will be imported by the main Python programm. - Distribute with py2exe on Win & py2app for Mac. What do you think of this ? Another point of attention is that the software isn't Open Source, it is a commercial package. So protection of sources is important. Now I know that anything can be decompiled, even C. The only question is, how hard is it and how much effort must someone do to decompile and retro engineer code to understand it. I think by putting all program logic in Pyd files that I would be quite secure ? On a side note : Is it harder to decompile PYD files then PYC files ? I allready had a meeting with the developpers and did a presentation of python with wxwindow, mostly with an open source project where I contribute to the development. They didn't see any big problems to learn Python fast and they allready know C. All opinions, advice here is welcome :) Tia Rony From martin.braun at kit.edu Fri Aug 20 04:23:08 2010 From: martin.braun at kit.edu (Martin Braun) Date: Fri, 20 Aug 2010 10:23:08 +0200 Subject: Python "why" questions In-Reply-To: <4c6d826e$0$11111$c3e8da3@news.astraweb.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> Message-ID: <20100820082308.GA3258@int.uni-karlsruhe.de> On Thu, Aug 19, 2010 at 07:13:50PM +0000, Steven D'Aprano wrote: > Mathematics is an ancient art that values tradition and convention. It > doesn't matter how hard it was to come up with a proof, or how difficult > to verify it. Mathematicians value logical correctness and some > undefinable sense of elegance over how easy it is to verify, the > readability of the notation, resistance to errors, and the ability of > mediocre mathematicians to make useful contributions. Mathematical > notation and conventions are not, by any stretch of the imagination, > designed to reduce errors. Mathematicians consider it a good thing that > they are still mostly using the same notation invented by (say) Leibniz. Another thing worth mentioning (I guess here is a good a place as any other) is the fact that programming and mathematics are still pretty different things, despite how much we programmers would like to think ourselves as some kind of mathematician. Fields-medal winners are not likely to be writing database applications in their spare time, or to save up money for blackboards and pencils. But mathematics is a wide field, and one area I'm very familiar in is signal processing, which has taken a lot of mathematics to make our algorithms work. In fact, of all electrical engineering disciplines, signal processing is probably the most mathematical. I find this thread extremely interesting, but what surprised me that everyone seems to agree that mathematics is 1-based, but we Pythoneers should stick to zero-based. I disagree. To make sure I'm not going crazy, I took the top five books lying on my desk, which were the DSP book by Oppenheim/Schafer, two books by Stephen M. Kay (Spectral Estimation and Estimation Theory) and the Channel Coding book by Lin & Costello. This is isn't pure mathematics (as in proving the Goldbach conjecture), but nevertheless, this is serious mathematics and, surprise, they most exclusively use zero-based notation. You probably don't have those books in grabbing distance, so here's some examples for zero-based stuff: - The definition of the FFT and one-sided z-transform (practically everywhere I've seen) - Time indices for time-discrete signals usually start at 0 for causal signals, same goes for filters (impulse responses) - Vector representation of polynomials - The Levinson-Durbin recursion algorithm is way more readable with zero-based indices (step 0 is an initialisation step) - Even most matrices used in the context for coding use zero-based indexing (i.e., the left-most column is column zero). I would like to add that dealing with linear algebra in GF2 is a bit different from handling complex signals as in the previous examples, so this is something to consider. I realize a lot of this has it's root in the application, e.g. shift-registers (index 0 means it's run through 0 shift registers). But it's been adopted for the mathematics because it's useful there as well (e.g. because x^0 = 1 for any non-zero value of x). Both mathematics and programming have two kinds of iterations: where index matters, and where it doesn't (why not iterate 'apple', 'banana', 'cherry' etc.). In practically all cases I deal with where the index matters, zero-based suits me better. The one-based indexing Matlab uses drives me crazy, and that's specifically designed for engineers. Martin -- Karlsruhe Institute of Technology (KIT) Communications Engineering Lab (CEL) Dipl.-Ing. Martin Braun Research Associate Kaiserstra?e 12 Building 05.01 76131 Karlsruhe Phone: +49 721 608-3790 Fax: +49 721 608-6071 www.cel.kit.edu KIT -- University of the State of Baden-W?rttemberg and National Laboratory of the Helmholtz Association -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From navkirats at gmail.com Fri Aug 20 04:24:30 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 20 Aug 2010 13:54:30 +0530 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6e3313$0$16599$426a74cc@news.free.fr> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> Message-ID: On 20-Aug-2010, at 1:17 PM, News123 wrote: > On 08/20/2010 02:26 AM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be tricky? > Is this a sincere surprise or are you just boasting? >> >> If I remember correctly, my puzzlement about recursion lasted about 15 >> seconds. I remember thinking "How does the function foo know that there >> is a function foo when foo doesn't fully exist yet?", but once I accepted >> the fact that it just does it all just seemed obvious. Getting recursion >> *right* is sometimes tricky, but the idea itself isn't. > > Well there's two things where I remember, that at least quite some > people in our class (at least the ones who didn't do maths or > programming in their spare time) had problems with. > > This were recursion and Mathematical induction. (quite the same though) > > The fact, that you didn't have the issue doens't mean it's easy for others. > > > > -- > http://mail.python.org/mailman/listinfo/python-list Well I guess why you did not have a problem understanding recursion is because you took for granted that it is the way it is. Most people, like me, try to reason why something is the way it is ! Hence, the delay in understanding the concept fully. From debatem1 at gmail.com Fri Aug 20 04:30:45 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 20 Aug 2010 01:30:45 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6e3313$0$16599$426a74cc@news.free.fr> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> Message-ID: On Fri, Aug 20, 2010 at 12:47 AM, News123 wrote: > On 08/20/2010 02:26 AM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be tricky? > Is this a sincere surprise or are you just boasting? I think his point is that the confusion is on how to do it right, not the concept of it. Geremy Condra From debatem1 at gmail.com Fri Aug 20 05:25:07 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 20 Aug 2010 02:25:07 -0700 Subject: A question to experienced Pythoneers In-Reply-To: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 1:16 AM, Rony wrote: > Here's the story : > I've been hired by a company as a consultant to reorganise there > development department. > The actual situation is : > The manager of the development has been fired, main reason (what they > told me) is that they have big big troubles in keeping deadlines ! For > there last product, for which they estimated 3 man years of > development they had 9 months extra effort, and the product was > delivered a year to late. > > I basicaly have 'carte blanche' :) > > One of my plans is to introduce Python as development tool. > They mostly develop back-office software, and at the moment they do it > all in C with MFC. > Another new requirement they have, is that the new product should run > on Win & Mac. > > So, my strategie would be : > - Use Python and wxpython for the GUI > - Develop critical routines in Pyrex or in C and make PYD's from it > which will be imported by the main Python programm. > - Distribute with py2exe on Win & py2app for Mac. > > What do you think of this ? > Another point of attention is that the software isn't Open Source, it > is a commercial package. So protection of sources is important. > Now I know that anything can be decompiled, even C. The only question > is, how hard is it and how much effort must someone do to decompile > and retro engineer code to understand it. > I think by putting all program logic in Pyd files that I would be > quite secure ? > On a side note : Is it harder to decompile PYD files then PYC files ? > > I allready had a meeting with the developpers and did a presentation > of python with wxwindow, mostly with an open source project where I > contribute to the development. They didn't see any big problems to > learn Python fast and they allready know C. > > All opinions, advice here is welcome :) 1) Don't take this the wrong way, but get in the habit of using proper grammar and spelling. Especially as a consultant. It will make the job of convincing people to take you seriously that much easier. 2) Use the tools at hand. If your developers don't know Python, you could wind up wasting a lot of talent turning a top-notch C developer into a bottom-tier Python developer, assuming you don't lose them altogether. 3) Don't rewrite critical code in a new language unless you have somebody who really knows what the hell they're doing. All you've done is turn programming's usual first-order ignorance into a much harder second-order problem. 4) Don't fool yourself into thinking that your code can't be decompiled. Odds are your code isn't worth decompiling, but it isn't hard, and a surprising number of people have the requisite skills. It certainly isn't 'secure'. Also- in my experience when people say 'I don't see a problem' to a consultant, what they really mean is 'I don't think you'll be around long enough for this to be a problem for me', but you may have the tools to deal with that. Happy hunting, Geremy Condra From kara at kara-moon.com Fri Aug 20 05:31:20 2010 From: kara at kara-moon.com (Rony) Date: Fri, 20 Aug 2010 02:31:20 -0700 (PDT) Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: <1664f7f2-fa30-4c12-b5a8-d095bed41e2c@5g2000yqz.googlegroups.com> On Aug 20, 11:25?am, geremy condra wrote: > 1) Don't take this the wrong way, but get in the habit of using proper > grammar and spelling. Especially as a consultant. It will make the job > of convincing people to take you seriously that much easier. I don't take it the wrong way but have an answer :) I'm French and doing my best to write understandable English... Thank you for your answers. > Also- in my experience when people say 'I don't see a problem' to a > consultant, what they really mean is 'I don't think you'll be around > long enough for this to be a problem for me', but you may have the > tools to deal with that. > I'll keep this in mind Thank you Rony From davea at ieee.org Fri Aug 20 06:34:27 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 20 Aug 2010 06:34:27 -0400 Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? In-Reply-To: References: Message-ID: <4C6E5A33.3020801@ieee.org> m_ahlenius wrote: > Hi, > > I am relatively new to doing serious work in python. I am using it to > access a large number of log files. Some of the logs get corrupted > and I need to detect that when processing them. This code seems to > work for quite a few of the logs (all same structure) It also > correctly identifies some corrupt logs but then it identifies others > as being corrupt when they are not. > > example error msg from below code: > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > Exception: CRC check\ > failed 0x8967e931 != 0x4e5f1036L > > When I manually examine the supposed corrupt log file and use > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " on it, it opens > just fine. > > Is there anything wrong with how I am using this module? (extra code > removed for clarity) > > if tarfile.is_tarfile( file ): > try: > xf = tarfile.open( file, "r:gz" ) > for locFile in xf: > logfile = xf.extractfile( locFile ) > validFileFlag = True > # iterate through each log file, grab the first and > the last lines > lines = iter( logfile ) > firstLine = lines.next() > for nextLine in lines: > .... > continue > > logfile.close() > ... > xf.close() > except Exception, e: > validFileFlag = False > msg = "\nCould not open the log file: " + repr(file) + " > Exception: " + str(e) + "\n" > else: > validFileFlag = False > lTime = extractFileNameTime( file ) > msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive > \n" > print msg > > I haven't used tarfile, but this feels like a problem with the Win/Unix line endings. I'm going to assume you're running on Windows, which could trigger the problem I'm going to describe. You use 'file' to hold something, but don't show us what. In fact, it's a lousy name, since it's already a Python builtin. But if it's holding fileobj, that you've separately opened, then you need to change that open to use mode 'rb' The problem, if I've guessed right, is that occasionally you'll accidentally encounter a 0d0a sequence in the middle of the (binary) compressed data. If you're on Windows, and use the default 'r' mode, it'll be changed into a 0a byte. Thus corrupting the checksum, and eventually the contents. DaveA From ldo at geek-central.gen.new_zealand Fri Aug 20 07:11:06 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 20 Aug 2010 23:11:06 +1200 Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: In message <8d1b76b7-1ba3-49c5-97cf-dc38370502ae at y11g2000yqm.googlegroups.com>, Rony wrote: > The manager of the development has been fired, main reason (what they > told me) is that they have big big troubles in keeping deadlines ! For > there last product, for which they estimated 3 man years of > development they had 9 months extra effort, and the product was > delivered a year to late. From ahleniusm at gmail.com Fri Aug 20 07:57:36 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 04:57:36 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: Message-ID: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> On Aug 20, 5:34?am, Dave Angel wrote: > m_ahlenius wrote: > > Hi, > > > I am relatively new to doing serious work in python. ?I am using it to > > access a large number of log files. ?Some of the logs get corrupted > > and I need to detect that when processing them. ?This code seems to > > work for quite a few of the logs (all same structure) ?It also > > correctly identifies some corrupt logs but then it identifies others > > as being corrupt when they are not. > > > example error msg from below code: > > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > > Exception: CRC check\ > > ?failed 0x8967e931 != 0x4e5f1036L > > > When I manually examine the supposed corrupt log file and use > > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " ?on it, it opens > > just fine. > > > Is there anything wrong with how I am using this module? ?(extra code > > removed for clarity) > > > ?if tarfile.is_tarfile( file ): > > ? ? ? ? try: > > ? ? ? ? ? ? xf = tarfile.open( file, "r:gz" ) > > ? ? ? ? ? ? for locFile in xf: > > ? ? ? ? ? ? ? ? logfile = xf.extractfile( locFile ) > > ? ? ? ? ? ? ? ? validFileFlag = True > > ? ? ? ? ? ? ? ? # iterate through each log file, grab the first and > > the last lines > > ? ? ? ? ? ? ? ? lines = iter( logfile ) > > ? ? ? ? ? ? ? ? firstLine = lines.next() > > ? ? ? ? ? ? ? ? for nextLine in lines: > > ? ? ? ? ? ? ? ? ? ? .... > > ? ? ? ? ? ? ? ? ? ? ? ? continue > > > ? ? ? ? ? ? ? ? logfile.close() > > ? ? ? ? ? ? ? ? ?... > > ? ? ? ? ? ? xf.close() > > ? ? ? ? except Exception, e: > > ? ? ? ? ? ? validFileFlag = False > > ? ? ? ? ? ? msg = "\nCould not open the log file: " + repr(file) + " > > Exception: " + str(e) + "\n" > > ?else: > > ? ? ? ? validFileFlag = False > > ? ? ? ? lTime = extractFileNameTime( file ) > > ? ? ? ? msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive > > \n" > > ? ? ? ? print msg > > I haven't used tarfile, but this feels like a problem with the Win/Unix > line endings. ?I'm going to assume you're running on Windows, which > could trigger the problem I'm going to describe. > > You use 'file' to hold something, but don't show us what. ?In fact, it's > a lousy name, since it's already a Python builtin. ?But if it's holding ? > fileobj, that you've separately opened, then you need to change that > open to use mode 'rb' > > The problem, if I've guessed right, is that occasionally you'll > accidentally encounter a 0d0a sequence in the middle of the (binary) > compressed data. ?If you're on Windows, and use the default 'r' mode, > it'll be changed into a 0a byte. ?Thus corrupting the checksum, and > eventually the contents. > > DaveA Hi, thanks for the comments - I'll change the variable name. I am running this on linux so don't think its a Windows issue. So if that's the case is the 0d0a still an issue? 'mark From rami.chowdhury at gmail.com Fri Aug 20 07:58:50 2010 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 20 Aug 2010 17:58:50 +0600 Subject: OpenCV_Problem In-Reply-To: References: <201008151914.34334.rami.chowdhury@gmail.com> Message-ID: On Thu, Aug 19, 2010 at 13:47, arihant nahata wrote: > I m new to python and openCV. i installed openCV and python and copied the necessary folder. and even appended the sys.path. but then too the same error. > > from opencv import cv > > File "C:\Python26\lib\site-packages\opencv\__init__.py", line 74, in > > > from cv import * > File "C:\Python26\lib\site-packages\opencv\cv.py", line 25, in > > _cv = swig_import_helper() > File "C:\Python26\lib\site-packages\opencv\cv.py", line 21, in > swig_import_helper > _mod = imp.load_module('_cv', fp, pathname, description) > ImportError: DLL load failed: The specified module could not be found. > > can you help me with this?? [next message] > This is what i have, > > >>> print sys.path > > ['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', > 'C:\\Python27\ > \lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', > 'C:\\Python27 > ', 'C:\\Python27\\lib\\site-packages', > 'C:\\OpenCV2.0\\Python2.6\\Lib\\site-pack > ages'] [next message] >> There is no file named _cv.dll file in the directory that you mentioned > what to do now.??? Well, we've established that the '_cv' module really isn't present. Which makes me wonder if the OpenCV installation went correctly, or if you've added the right paths. However, as I'm not an OpenCV expert, I don't know where to look next. If no one on the Python mailing list can help, you could also try the OpenCV mailing list: http://tech.groups.yahoo.com/group/OpenCV/ HTH, Rami -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From rami.chowdhury at merton.oxon.org Fri Aug 20 08:07:30 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Fri, 20 Aug 2010 18:07:30 +0600 Subject: A question to experienced Pythoneers In-Reply-To: References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 15:25, geremy condra wrote: > On Fri, Aug 20, 2010 at 1:16 AM, Rony wrote: >> Here's the story : >> I've been hired by a company as a consultant to reorganise there >> development department. [snip] >> One of my plans is to introduce Python as development tool. >> They mostly develop back-office software, and at the moment they do it >> all in C with MFC. >> Another new requirement they have, is that the new product should run >> on Win & Mac. [snip] > 2) Use the tools at hand. If your developers don't know Python, you > could wind up wasting a lot of talent turning a top-notch C developer > into a bottom-tier Python developer, assuming you don't lose them > altogether. > > 3) Don't rewrite critical code in a new language unless you have > somebody who really knows what the hell they're doing. All you've done > is turn programming's usual first-order ignorance into a much harder > second-order problem. +1 to both of these, personally. If the developers are used to C and MFC, but you need to make the product run on the Mac as well, have you considered C / C++ GUI frameworks like GTK, WxWidgets, or Qt? Porting your GUI to those might be a better use of time than porting the software to Python... -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From roy at panix.com Fri Aug 20 08:44:42 2010 From: roy at panix.com (Roy Smith) Date: Fri, 20 Aug 2010 08:44:42 -0400 Subject: 79 chars or more? References: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> Message-ID: In article <4c6dfb31$0$11111$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > Of course source code is written in a monospaced typeface, which is a > little wider and consequently fewer characters per page. There was a fling a while ago with typesetting code in proportional spaced type. I think some of the "Effective C++" series from Addison-Wesley did that. Yuck. From malcolm.mclean5 at btinternet.com Fri Aug 20 08:53:43 2010 From: malcolm.mclean5 at btinternet.com (Malcolm McLean) Date: Fri, 20 Aug 2010 05:53:43 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> Message-ID: <03cfab6b-0d69-458b-8d89-fb1a705c5836@y11g2000yqm.googlegroups.com> On Aug 19, 2:14?pm, spinoza1111 wrote: > All the rest [how to implement heaps] is > detail for the little techies to normally, get wrong. > That's a fundamental feature of structured programming. If we maintain the interface malloc(), realloc(), and free(), then we could have a fairly simple or a fairly complicated scheme, and the user doesn't care or need to know. The problem is that a lot of techniques we can use to speed up memory management, such as allocating from a stack, can't be used with this interface. Designing good interfaces is hard. From neilc at norwich.edu Fri Aug 20 09:10:54 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 20 Aug 2010 13:10:54 GMT Subject: 79 chars or more? References: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> Message-ID: <8d7d6uFpvvU1@mid.individual.net> On 2010-08-20, Roy Smith wrote: > In article <4c6dfb31$0$11111$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: > >> Of course source code is written in a monospaced typeface, which is a >> little wider and consequently fewer characters per page. > > There was a fling a while ago with typesetting code in > proportional spaced type. I think some of the "Effective C++" > series from Addison-Wesley did that. Yuck. It's probably influenced by The C++ Programming Language. Stroustrup likes it. -- Neil Cerutti From ahleniusm at gmail.com Fri Aug 20 09:23:57 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 06:23:57 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: On Aug 20, 6:57?am, m_ahlenius wrote: > On Aug 20, 5:34?am, Dave Angel wrote: > > > > > > > m_ahlenius wrote: > > > Hi, > > > > I am relatively new to doing serious work in python. ?I am using it to > > > access a large number of log files. ?Some of the logs get corrupted > > > and I need to detect that when processing them. ?This code seems to > > > work for quite a few of the logs (all same structure) ?It also > > > correctly identifies some corrupt logs but then it identifies others > > > as being corrupt when they are not. > > > > example error msg from below code: > > > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > > > Exception: CRC check\ > > > ?failed 0x8967e931 != 0x4e5f1036L > > > > When I manually examine the supposed corrupt log file and use > > > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " ?on it, it opens > > > just fine. > > > > Is there anything wrong with how I am using this module? ?(extra code > > > removed for clarity) > > > > ?if tarfile.is_tarfile( file ): > > > ? ? ? ? try: > > > ? ? ? ? ? ? xf = tarfile.open( file, "r:gz" ) > > > ? ? ? ? ? ? for locFile in xf: > > > ? ? ? ? ? ? ? ? logfile = xf.extractfile( locFile ) > > > ? ? ? ? ? ? ? ? validFileFlag = True > > > ? ? ? ? ? ? ? ? # iterate through each log file, grab the first and > > > the last lines > > > ? ? ? ? ? ? ? ? lines = iter( logfile ) > > > ? ? ? ? ? ? ? ? firstLine = lines.next() > > > ? ? ? ? ? ? ? ? for nextLine in lines: > > > ? ? ? ? ? ? ? ? ? ? .... > > > ? ? ? ? ? ? ? ? ? ? ? ? continue > > > > ? ? ? ? ? ? ? ? logfile.close() > > > ? ? ? ? ? ? ? ? ?... > > > ? ? ? ? ? ? xf.close() > > > ? ? ? ? except Exception, e: > > > ? ? ? ? ? ? validFileFlag = False > > > ? ? ? ? ? ? msg = "\nCould not open the log file: " + repr(file) + " > > > Exception: " + str(e) + "\n" > > > ?else: > > > ? ? ? ? validFileFlag = False > > > ? ? ? ? lTime = extractFileNameTime( file ) > > > ? ? ? ? msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive > > > \n" > > > ? ? ? ? print msg > > > I haven't used tarfile, but this feels like a problem with the Win/Unix > > line endings. ?I'm going to assume you're running on Windows, which > > could trigger the problem I'm going to describe. > > > You use 'file' to hold something, but don't show us what. ?In fact, it's > > a lousy name, since it's already a Python builtin. ?But if it's holding ? > > fileobj, that you've separately opened, then you need to change that > > open to use mode 'rb' > > > The problem, if I've guessed right, is that occasionally you'll > > accidentally encounter a 0d0a sequence in the middle of the (binary) > > compressed data. ?If you're on Windows, and use the default 'r' mode, > > it'll be changed into a 0a byte. ?Thus corrupting the checksum, and > > eventually the contents. > > > DaveA > > Hi, > > thanks for the comments - I'll change the variable name. > > I am running this on linux so don't think its a Windows issue. ?So if > that's the case > is the 0d0a still an issue? > > 'mark Oh and what's stored currently in The file var us just the unopened pathname to the Target file I want to open From nt_mahmood at yahoo.com Fri Aug 20 09:43:20 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Fri, 20 Aug 2010 06:43:20 -0700 (PDT) Subject: Get authentication error while using 'smtplib' Message-ID: <13714.16636.qm@web50005.mail.re2.yahoo.com> I have this script to send an email via SMTP: import smtplib smtpserver = 'smtp.server.com' AUTHREQUIRED = 1# if you need to use SMTP AUTH set to 1 smtpuser = "username"# for SMTP AUTH, set SMTP username here smtppass = "password"# for SMTP AUTH, set SMTP password here RECIPIENTS ='recipient at server.com' SENDER = 'sender at server.com' mssg = open('filename.txt', 'r').read() session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: ?? session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) After running the script I get this error: ? Traceback (most recent call last): ? File "my_mail.py", line 14, in ??? session.login(smtpuser, smtppass) ? File "/usr/lib/python2.6/smtplib.py", line 589, in login ??? raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, '5.7.0 Error: authentication failed: authentication failure') However there is no problem with my user/pass because I can login to my mail account. Thanks for any idea.? // Naderan *Mahmood;? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sschwarzer at sschwarzer.net Fri Aug 20 09:55:51 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 20 Aug 2010 15:55:51 +0200 Subject: A question to experienced Pythoneers In-Reply-To: References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: <4C6E8967.40408@sschwarzer.net> Hi Lawrence, On 2010-08-20 13:11, Lawrence D'Oliveiro wrote: > In message > <8d1b76b7-1ba3-49c5-97cf-dc38370502ae at y11g2000yqm.googlegroups.com>, Rony > wrote: > >> The manager of the development has been fired, main reason (what they >> told me) is that they have big big troubles in keeping deadlines ! For >> there last product, for which they estimated 3 man years of >> development they had 9 months extra effort, and the product was >> delivered a year to late. > > I can't get the page; all I get is an error message: """ Not Found The requested message, i4ku71$fdg$1 at lust.ihug.co.nz, could not be found. """ Can you please give a part of the message to search for or even better, an URL that works? :-) Thanks, Stefan From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 20 09:56:17 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Aug 2010 15:56:17 +0200 Subject: 79 chars or more? In-Reply-To: <4C6A9C72.4040708@sschwarzer.net> References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> Message-ID: <4c6e8980$0$692$426a74cc@news.free.fr> Stefan Schwarzer a ?crit : > Hi Neil, > > On 2010-08-17 14:42, Neil Cerutti wrote: (snip) >> Looking through my code, the split-up lines almost always include >> string literals or elimination of meaningless temporary >> variables, e.g.: >> >> self.expiration_date = translate_date(find(response, >> 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') > > I'd probably reformat this to > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', '%m%d%Y') > > or even > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y') make this : self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y' ) I just HATE closing parens on the same line when the args don't fit on one single line. Significant indentation only solves one single issue when it comes to coding conventions war !-) From neilc at norwich.edu Fri Aug 20 10:00:49 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 20 Aug 2010 14:00:49 GMT Subject: 79 chars or more? References: <4C69F585.5050504@gmail.com> <4C69FB05.7070307@gmail.com> <8cved7Fr7qU3@mid.individual.net> <4C6A9C72.4040708@sschwarzer.net> <4c6e8980$0$692$426a74cc@news.free.fr> Message-ID: <8d7g4gFa0nU1@mid.individual.net> On 2010-08-20, Bruno Desthuilliers wrote: > make this : > > self.expiration_date = translate_date( > find(response, 'MPNExpirationDate').text, > '%Y-%m-%d', > '%m%d%Y' > ) > > I just HATE closing parens on the same line when the args don't > fit on one single line. It's been interesting to see my code scrutinized like this. Thanks all. As a result of the discussion, I changed translate_date to trans_date_from_to to make the order of arguments clear. find is just a small wrapper around Element.find calls, inserting the namespace. -- Neil Cerutti From davea at ieee.org Fri Aug 20 10:10:13 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 20 Aug 2010 10:10:13 -0400 Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? In-Reply-To: References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: <4C6E8CC5.6060308@ieee.org> m_ahlenius wrote: > On Aug 20, 6:57 am, m_ahlenius wrote: > >> On Aug 20, 5:34 am, Dave Angel wrote: >> >> >> >> >> >> >>> m_ahlenius wrote: >>> >>>> Hi, >>>> >>>> I am relatively new to doing serious work in python. I am using it to >>>> access a large number of log files. Some of the logs get corrupted >>>> and I need to detect that when processing them. This code seems to >>>> work for quite a few of the logs (all same structure) It also >>>> correctly identifies some corrupt logs but then it identifies others >>>> as being corrupt when they are not. >>>> >>>> example error msg from below code: >>>> >>>> Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' >>>> Exception: CRC check\ >>>> failed 0x8967e931 !=x4e5f1036L >>>> >>>> When I manually examine the supposed corrupt log file and use >>>> "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " on it, it opens >>>> just fine. >>>> >>>> Is there anything wrong with how I am using this module? (extra code >>>> removed for clarity) >>>> >>>> if tarfile.is_tarfile( file ): >>>> try: >>>> xf =arfile.open( file, "r:gz" ) >>>> for locFile in xf: >>>> logfile =f.extractfile( locFile ) >>>> validFileFlag =rue >>>> # iterate through each log file, grab the first and >>>> the last lines >>>> lines =ter( logfile ) >>>> firstLine =ines.next() >>>> for nextLine in lines: >>>> .... >>>> continue >>>> >>>> logfile.close() >>>> ... >>>> xf.close() >>>> except Exception, e: >>>> validFileFlag =alse >>>> msg =\nCould not open the log file: " + repr(file) + " >>>> Exception: " + str(e) + "\n" >>>> else: >>>> validFileFlag =alse >>>> lTime =xtractFileNameTime( file ) >>>> msg =>>>>>>> Warning " + file + " is NOT a valid tar archive >>>> \n" >>>> print msg >>>> >>> I haven't used tarfile, but this feels like a problem with the Win/Unix >>> line endings. I'm going to assume you're running on Windows, which >>> could trigger the problem I'm going to describe. >>> >>> You use 'file' to hold something, but don't show us what. In fact, it's >>> a lousy name, since it's already a Python builtin. But if it's holding >>> fileobj, that you've separately opened, then you need to change that >>> open to use mode 'rb' >>> >>> The problem, if I've guessed right, is that occasionally you'll >>> accidentally encounter a 0d0a sequence in the middle of the (binary) >>> compressed data. If you're on Windows, and use the default 'r' mode, >>> it'll be changed into a 0a byte. Thus corrupting the checksum, and >>> eventually the contents. >>> >>> DaveA >>> >> Hi, >> >> thanks for the comments - I'll change the variable name. >> >> I am running this on linux so don't think its a Windows issue. So if >> that's the case >> is the 0d0a still an issue? >> >> 'mark >> > > Oh and what's stored currently in > The file var us just the unopened pathname to the > Target file I want to open > > > No, on Linux, there should be no such problem. And I have to assume that if you pass the filename as a string, the library would use 'rb' anyway. It's just if you pass a fileobj, AND are on Windows. Sorry I wasted your time, but nobody else had answered, and I hoped it might help. DaveA From sschwarzer at sschwarzer.net Fri Aug 20 10:10:16 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 20 Aug 2010 16:10:16 +0200 Subject: A question to experienced Pythoneers In-Reply-To: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: <4C6E8CC8.2090603@sschwarzer.net> Hi Rony, On 2010-08-20 10:16, Rony wrote: > Here's the story : > I've been hired by a company as a consultant to reorganise there > development department. > The actual situation is : > The manager of the development has been fired, main reason (what they > told me) is that they have big big troubles in keeping deadlines ! For > there last product, for which they estimated 3 man years of > development they had 9 months extra effort, and the product was > delivered a year to late. I guess the most important issue will be to find out what was wrong with the development process and fix the problems, i. e. don't repeat them. Keep in mind that "what was wrong" can mean any number of reasons. Until you haven't dealt with this, thinking about changing the programming language in my opinion makes little sense. > I basicaly have 'carte blanche' :) Um, yes ... with the corresponding responsibilities and risks. :-) > So, my strategie would be : > - Use Python and wxpython for the GUI > - Develop critical routines in Pyrex or in C and make PYD's from it > which will be imported by the main Python programm. > - Distribute with py2exe on Win & py2app for Mac. You plan to change a process (and people) used to developing with C to developing with Python and the associated tools. For a developer experienced with both C and Python, using the latter usually will result in faster development. On the other hand, switching to a tool you (i. e. an individual developer) never used before adds some risk (-> uncertainty in effort estimation). If the project you're dealing with now is based on the project you mentioned above, you better not start from scratch in a different language. Very likely the existing code will have subtle though important fixes for subtle problems which were encountered during development. If you start from scratch you risk losing these fixes and having to re-discover the problems and fixes which can take a lot of time. Even if you have all programmers of the old team available, it's risky because they might have forgotten the parts of the code or they may no longer be around when you're about to implement the functionality of these critical parts of the code. If you haven't already, I recommend to read these books: Steve McConnell Rapid Development http://www.amazon.com/x/dp/0072850604/ Tom DeMarco, Timothy Lister Waltzing With Bears: Managing Risk on Software Projects http://www.amazon.com/x/dp/0932633609/ Stefan From __peter__ at web.de Fri Aug 20 10:25:42 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Aug 2010 16:25:42 +0200 Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: m_ahlenius wrote: > On Aug 20, 6:57 am, m_ahlenius wrote: >> On Aug 20, 5:34 am, Dave Angel wrote: >> >> >> >> >> >> > m_ahlenius wrote: >> > > Hi, >> >> > > I am relatively new to doing serious work in python. I am using it >> > > to access a large number of log files. Some of the logs get >> > > corrupted and I need to detect that when processing them. This code >> > > seems to work for quite a few of the logs (all same structure) It >> > > also correctly identifies some corrupt logs but then it identifies >> > > others as being corrupt when they are not. >> >> > > example error msg from below code: >> >> > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' >> > > Exception: CRC check\ >> > > failed 0x8967e931 != 0x4e5f1036L >> >> > > When I manually examine the supposed corrupt log file and use >> > > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " on it, it opens >> > > just fine. >> >> > > Is there anything wrong with how I am using this module? (extra code >> > > removed for clarity) >> >> > > if tarfile.is_tarfile( file ): >> > > try: >> > > xf = tarfile.open( file, "r:gz" ) >> > > for locFile in xf: >> > > logfile = xf.extractfile( locFile ) >> > > validFileFlag = True >> > > # iterate through each log file, grab the first and >> > > the last lines >> > > lines = iter( logfile ) >> > > firstLine = lines.next() >> > > for nextLine in lines: >> > > .... >> > > continue >> >> > > logfile.close() >> > > ... >> > > xf.close() >> > > except Exception, e: >> > > validFileFlag = False >> > > msg = "\nCould not open the log file: " + repr(file) + " >> > > Exception: " + str(e) + "\n" >> > > else: >> > > validFileFlag = False >> > > lTime = extractFileNameTime( file ) >> > > msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive >> > > \n" >> > > print msg >> >> > I haven't used tarfile, but this feels like a problem with the Win/Unix >> > line endings. I'm going to assume you're running on Windows, which >> > could trigger the problem I'm going to describe. >> >> > You use 'file' to hold something, but don't show us what. In fact, >> > it's a lousy name, since it's already a Python builtin. But if it's >> > holding fileobj, that you've separately opened, then you need to change >> > that open to use mode 'rb' >> >> > The problem, if I've guessed right, is that occasionally you'll >> > accidentally encounter a 0d0a sequence in the middle of the (binary) >> > compressed data. If you're on Windows, and use the default 'r' mode, >> > it'll be changed into a 0a byte. Thus corrupting the checksum, and >> > eventually the contents. >> >> > DaveA >> >> Hi, >> >> thanks for the comments - I'll change the variable name. >> >> I am running this on linux so don't think its a Windows issue. So if >> that's the case >> is the 0d0a still an issue? >> >> 'mark > > Oh and what's stored currently in > The file var us just the unopened pathname to the > Target file I want to open Random questions: What python version are you using? If you have other python versions around, do they exhibit the same problem? If you extract and compress your data using the external tool, does the resulting file make problems in Python, too? If so, can you reduce data size and put a small demo online for others to experiment with? Peter From vicente.soler at gmail.com Fri Aug 20 10:26:49 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 07:26:49 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> Message-ID: <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> On Aug 20, 9:36?am, Tim Golden wrote: > > I currently do not have subversion access in my PC. I could try to > > install a free copy of it. But it you could ptovide an installer, it > > certainly would do things easier. Please let me know if it is > > possible. > > Vicente, can you just confirm that you received the installer I > sent offlist? I'll try to put winsys on PyPI with installers; > just haven't got round to it yes :) > > TJG Tim, I just downloaded it, and am going to install it right away. From kara at kara-moon.com Fri Aug 20 10:31:54 2010 From: kara at kara-moon.com (Rony) Date: Fri, 20 Aug 2010 07:31:54 -0700 (PDT) Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> <4C6E8CC8.2090603@sschwarzer.net> Message-ID: <8d6f1093-c585-4374-a843-2e452aebafa5@i13g2000yqd.googlegroups.com> It looks like I forgot to specify that the product is a totaly new product build from scratch, not an upgrade from an existing product. Interesting answers ! Rony From vicente.soler at gmail.com Fri Aug 20 10:45:22 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 07:45:22 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> Message-ID: <3d972531-6b5b-470f-a446-5c897731fc8b@z10g2000yqb.googlegroups.com> On Aug 20, 9:36?am, Tim Golden wrote: > > I currently do not have subversion access in my PC. I could try to > > install a free copy of it. But it you could ptovide an installer, it > > certainly would do things easier. Please let me know if it is > > possible. > > Vicente, can you just confirm that you received the installer I > sent offlist? I'll try to put winsys on PyPI with installers; > just haven't got round to it yes :) > > TJG Tim, I just downloaded it, and am going to install it right away. From vicente.soler at gmail.com Fri Aug 20 10:49:04 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 07:49:04 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> Message-ID: <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> On Aug 20, 4:26?pm, vsoler wrote: > On Aug 20, 9:36?am, Tim Golden wrote: > > > > I currently do not have subversion access in my PC. I could try to > > > install a free copy of it. But it you could ptovide an installer, it > > > certainly would do things easier. Please let me know if it is > > > possible. > > > Vicente, can you just confirm that you received the installer I > > sent offlist? I'll try to put winsys on PyPI with installers; > > just haven't got round to it yes :) > > > TJG > > Tim, > > I just downloaded it, and am going to install it right away. Tim, It works!!! or at least, should I say, it runs!!! wonderful. Now, would it be possible to have a hint/suggestion as to some lines that I should include in my script? I find this exercice very interesting. Thank you for your help. Vicente Soler From a.j.romanista at gmail.com Fri Aug 20 11:02:30 2010 From: a.j.romanista at gmail.com (ata.jaf) Date: Fri, 20 Aug 2010 08:02:30 -0700 (PDT) Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> <4c6cefc6$0$11111$c3e8da3@news.astraweb.com> Message-ID: <31e9a229-9422-42d4-ab51-14cd4aaf62af@z10g2000yqb.googlegroups.com> On Aug 19, 11:48?am, Steven D'Aprano wrote: > On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote: > > On Aug 17, 11:55?pm, Thomas Jollans wrote: > >> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > > >> > I am developing a little program in Mac with wxPython. But I have > >> > problems with the characters that are not in ASCII. Like some special > >> > characters in French or Turkish. So I am looking for a way to solve > >> > this. Like an encoding standard that supports all languages. Or some > >> > other way. > > >> Anything that supports all of Unicode will do. Like UTF-8. If your text > >> is mostly Latin, then just go for UTF-8, if you use other alphabets > >> extensively, you might want to consider UTF-16, which might the use a > >> little less space. > > > OK, I used UTF-8. > > I write a line of strings in the source code > > Do you have a source code encoding line at the start of your script? > > http://www.python.org/dev/peps/pep-0263/ > > > and I want my program to > > show that as an output on GUI. And this line of strings includes a > > character like "?". But I see that in GUI this character is replaced > > with another strange characters. I mean it doesn't work. And when I try > > to use UTF-16, I get an syntax error that declares "UTF-16 stream does > > not start with BOM". > > What GUI are you using? > > Please COPY AND PASTE (do not retype) the EXACT error message you get, > including the entire traceback. > > -- > Steven Yes I have a source code encoding line. Here it is: # -*- coding: utf_16 -*- I am using WxPython. And the error that I get about using utf-16 is:\ Traceback (most recent call last): File "", line 1, in File "z.py", line 2 SyntaxError: UTF-16 stream does not start with BOM From mail at timgolden.me.uk Fri Aug 20 11:10:51 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Aug 2010 16:10:51 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: <4C6E9AFB.1070508@timgolden.me.uk> On 20/08/2010 15:49, vsoler wrote: > On Aug 20, 4:26 pm, vsoler wrote: >> On Aug 20, 9:36 am, Tim Golden wrote: >> >>>> I currently do not have subversion access in my PC. I could try to >>>> install a free copy of it. But it you could ptovide an installer, it >>>> certainly would do things easier. Please let me know if it is >>>> possible. >> >>> Vicente, can you just confirm that you received the installer I >>> sent offlist? I'll try to put winsys on PyPI with installers; >>> just haven't got round to it yes :) >> >>> TJG >> >> Tim, >> >> I just downloaded it, and am going to install it right away. > > Tim, > > It works!!! or at least, should I say, it runs!!! wonderful. > > Now, would it be possible to have a hint/suggestion as to some lines > that I should include in my script? Depends what, exactly, you want your script to do :) The simplest way to get an ad-hoc look at what permissions are applied to a file is: import os, sys from winsys import fs # # Just using sys.executable as a file I know will exist; # obviously you put your own file name in there... # fs.file (sys.executable).security ().dump () To get that in the more compact but more esoteric MS SDDL format: import os, sys from winsys import fs print (fs.file (sys.executable).security ()) To decode the permission bit-strings to vaguely meaningful names: import os, sys from winsys import fs dacl = fs.file (sys.executable).security ().dacl for permission in dacl: print (d.trustee, " (Inherited )" if d.inherited else "") for name in fs.FILE_ACCESS.names_from_value (d.access): print (" ", name) TJG From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 20 11:16:14 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Aug 2010 17:16:14 +0200 Subject: A question to experienced Pythoneers In-Reply-To: <8d6f1093-c585-4374-a843-2e452aebafa5@i13g2000yqd.googlegroups.com> References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> <4C6E8CC8.2090603@sschwarzer.net> <8d6f1093-c585-4374-a843-2e452aebafa5@i13g2000yqd.googlegroups.com> Message-ID: <4c6e9c3c$0$411$426a74cc@news.free.fr> Rony a ?crit : > It looks like I forgot to specify that the product is a totaly new > product build from scratch, not an upgrade from an existing product. Still the advice to first find out what went wrong with the previous project is a very sensible one. Technical problems do exist, but from experience they rarely are the main source of failure. From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 20 11:23:23 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Aug 2010 17:23:23 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c6e9de9$0$23142$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: > >> Recursion can be quite a trick to get your mind round at first > > Really? Do people actually find the *concept* of recursion to be tricky? > I onced worked in a shop (Win32 desktop / accouting applications mainly) where I was the only guy that could actually understand recursion. FWIW, I also was the only guy around that understood "hairy" (lol) concepts like callback functions, FSM, polymorphism, hashtables, linked lists, ADTs, algorithm complexity etc... Needless to say, I didn't last long !-) From enleverLesX_XXmcX at XmclavXeauX.com.invalid Fri Aug 20 11:34:56 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Fri, 20 Aug 2010 17:34:56 +0200 Subject: Iterative vs. Recursive coding References: <4c6e9de9$0$23142$426a74cc@news.free.fr> Message-ID: <4c6ea0a9$0$5403$ba4acef3@reader.news.orange.fr> Salut ! C'est cela, la solitude du programmeur g?nial... @-salutations -- Michel Claveau From aahz at pythoncraft.com Fri Aug 20 11:41:00 2010 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2010 08:41:00 -0700 Subject: urllib "quote" problem References: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> Message-ID: In article <4c5eef7f$0$1609$742ec2ed at news.sonic.net>, John Nagle wrote: > > This looks like code that will do the wrong thing in >Python 2.6 for characters in the range 128-255. Those are >illegal in type "str", but this code is constructing such >values with "chr". WDYM "illegal"? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 20 11:45:09 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Aug 2010 17:45:09 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6ea0a9$0$5403$ba4acef3@reader.news.orange.fr> References: <4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6ea0a9$0$5403$ba4acef3@reader.news.orange.fr> Message-ID: <4c6ea303$0$23154$426a34cc@news.free.fr> Michel Claveau - MVP a ?crit : > Salut ! > > C'est cela, la solitude du programmeur g?nial... > > @-salutations Moi aussi je t'aime, Michel !-) From aahz at pythoncraft.com Fri Aug 20 11:45:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2010 08:45:44 -0700 Subject: requirements in writing an email/rss/usenet client? References: Message-ID: In article , George Oliver wrote: > >I'd like to know what to consider when writing an email/rss/usenet >client. Apologies for such a broad question, but I've never attempted >a project of this scope and I'm currently feeling out the >requirements. About the only advice I can give you to such a broad question is the aphorism "Be strict about what you send; be generous about what you receive". IOW, follow the standards very very carefully in sending messages but be very very lenient with what you accept (just make sure you don't crash). Overall, you probably will get discouraged eventually, so I suggest that you try to have as much fun as possible along the way. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From aahz at pythoncraft.com Fri Aug 20 11:53:34 2010 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2010 08:53:34 -0700 Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> Message-ID: In article <8d1b76b7-1ba3-49c5-97cf-dc38370502ae at y11g2000yqm.googlegroups.com>, Rony wrote: > >The manager of the development has been fired, main reason (what they >told me) is that they have big big troubles in keeping deadlines ! For >there last product, for which they estimated 3 man years of >development they had 9 months extra effort, and the product was >delivered a year to late. Keep in mind that the real problem may have been that upper management forced a completely unrealistic deadline. They may also have had difficulty translating "development effort" into Real World Timing [tm]. (For example, when I tell my boss that something will take three days of development effort, I also make clear that between support and production issues that I need to help with, not to mention meetings, mentoring other people on my team, etc -- those three days will almost inevitably expand into six business days BEST CASE.) Try to have some quiet, off-campus discussions with developers to gather information. NOTE VERY CAREFULLY: if you promise to keep a conversation private, KEEP THE PROMISE. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From vicente.soler at gmail.com Fri Aug 20 12:00:56 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 09:00:56 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: <1f6b049b-6bdc-4305-9389-5142dbd44e4e@s9g2000yqd.googlegroups.com> On Aug 20, 5:10?pm, Tim Golden wrote: > On 20/08/2010 15:49, vsoler wrote: > > > > > On Aug 20, 4:26 pm, vsoler ?wrote: > >> On Aug 20, 9:36 am, Tim Golden ?wrote: > > >>>> I currently do not have subversion access in my PC. I could try to > >>>> install a free copy of it. But it you could ptovide an installer, it > >>>> certainly would do things easier. Please let me know if it is > >>>> possible. > > >>> Vicente, can you just confirm that you received the installer I > >>> sent offlist? I'll try to put winsys on PyPI with installers; > >>> just haven't got round to it yes :) > > >>> TJG > > >> Tim, > > >> I just downloaded it, and am going to install it right away. > > > Tim, > > > It works!!! or at least, should I say, it runs!!! wonderful. > > > Now, would it be possible to have a hint/suggestion as to some lines > > that I should include in my script? > > Depends what, exactly, you want your script to do :) > > The simplest way to get an ad-hoc look at what permissions are applied to > a file is: > > > import os, sys > from winsys import fs > > # > # Just using sys.executable as a file I know will exist; > # obviously you put your own file name in there... > # > fs.file (sys.executable).security ().dump () > > > > To get that in the more compact but more esoteric MS SDDL format: > > > import os, sys > from winsys import fs > > print (fs.file (sys.executable).security ()) > > > > To decode the permission bit-strings to vaguely meaningful > names: > > > import os, sys > from winsys import fs > > dacl = fs.file (sys.executable).security ().dacl > for permission in dacl: > ? ?print (d.trustee, " (Inherited )" if d.inherited else "") > ? ?for name in fs.FILE_ACCESS.names_from_value (d.access): > ? ? ?print (" ?", name) > > > > TJG Tim, in your last piece of code, the definition of "d" is missing. missed anything when copying? Vicente Soler From rami.chowdhury at merton.oxon.org Fri Aug 20 12:07:21 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Fri, 20 Aug 2010 22:07:21 +0600 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: <31e9a229-9422-42d4-ab51-14cd4aaf62af@z10g2000yqb.googlegroups.com> References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> <4c6cefc6$0$11111$c3e8da3@news.astraweb.com> <31e9a229-9422-42d4-ab51-14cd4aaf62af@z10g2000yqb.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 21:02, ata.jaf wrote: > On Aug 19, 11:48?am, Steven D'Aprano T... at cybersource.com.au> wrote: >> On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote: >> > On Aug 17, 11:55?pm, Thomas Jollans wrote: >> >> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: >> >> >> > I am developing a little program in Mac with wxPython. But I have >> >> > problems with the characters that are not in ASCII. Like some special >> >> > characters in French or Turkish. So I am looking for a way to solve >> >> > this. Like an encoding standard that supports all languages. Or some >> >> > other way. >> >> >> Anything that supports all of Unicode will do. Like UTF-8. If your text >> >> is mostly Latin, then just go for UTF-8, if you use other alphabets >> >> extensively, you might want to consider UTF-16, which might the use a >> >> little less space. >> >> > OK, I used UTF-8. >> > I write a line of strings in the source code >> >> Do you have a source code encoding line at the start of your script? >> >> http://www.python.org/dev/peps/pep-0263/ >> > > Yes I have a source code encoding line. > Here it is: > > # -*- coding: utf_16 -*- > > I am using WxPython. > > And the error that I get about using utf-16 is:\ > > Traceback (most recent call last): > ?File "", line 1, in > ?File "z.py", line 2 > SyntaxError: UTF-16 stream does not start with BOM Which encoding are you saving your script in? Very few of the text editors I've used save to UTF-16 by default. -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From vicente.soler at gmail.com Fri Aug 20 12:10:23 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 09:10:23 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: On Aug 20, 5:10?pm, Tim Golden wrote: > On 20/08/2010 15:49, vsoler wrote: > > > > > On Aug 20, 4:26 pm, vsoler ?wrote: > >> On Aug 20, 9:36 am, Tim Golden ?wrote: > > >>>> I currently do not have subversion access in my PC. I could try to > >>>> install a free copy of it. But it you could ptovide an installer, it > >>>> certainly would do things easier. Please let me know if it is > >>>> possible. > > >>> Vicente, can you just confirm that you received the installer I > >>> sent offlist? I'll try to put winsys on PyPI with installers; > >>> just haven't got round to it yes :) > > >>> TJG > > >> Tim, > > >> I just downloaded it, and am going to install it right away. > > > Tim, > > > It works!!! or at least, should I say, it runs!!! wonderful. > > > Now, would it be possible to have a hint/suggestion as to some lines > > that I should include in my script? > > Depends what, exactly, you want your script to do :) > > The simplest way to get an ad-hoc look at what permissions are applied to > a file is: > > > import os, sys > from winsys import fs > > # > # Just using sys.executable as a file I know will exist; > # obviously you put your own file name in there... > # > fs.file (sys.executable).security ().dump () > > > > To get that in the more compact but more esoteric MS SDDL format: > > > import os, sys > from winsys import fs > > print (fs.file (sys.executable).security ()) > > > > To decode the permission bit-strings to vaguely meaningful > names: > > > import os, sys > from winsys import fs > > dacl = fs.file (sys.executable).security ().dacl > for permission in dacl: > ? ?print (d.trustee, " (Inherited )" if d.inherited else "") > ? ?for name in fs.FILE_ACCESS.names_from_value (d.access): > ? ? ?print (" ?", name) > > > > TJG it seems as though the definition of "d" is missing in your last piece of code From ahleniusm at gmail.com Fri Aug 20 12:27:52 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 09:27:52 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: On Aug 20, 9:10?am, Dave Angel wrote: > m_ahlenius wrote: > > On Aug 20, 6:57 am, m_ahlenius wrote: > > >> On Aug 20, 5:34 am, Dave Angel wrote: > > >>> m_ahlenius wrote: > > >>>> Hi, > > >>>> I am relatively new to doing serious work in python. ?I am using it to > >>>> access a large number of log files. ?Some of the logs get corrupted > >>>> and I need to detect that when processing them. ?This code seems to > >>>> work for quite a few of the logs (all same structure) ?It also > >>>> correctly identifies some corrupt logs but then it identifies others > >>>> as being corrupt when they are not. > > >>>> example error msg from below code: > > >>>> Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > >>>> Exception: CRC check\ > >>>> ?failed 0x8967e931 !=x4e5f1036L > > >>>> When I manually examine the supposed corrupt log file and use > >>>> "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " ?on it, it opens > >>>> just fine. > > >>>> Is there anything wrong with how I am using this module? ?(extra code > >>>> removed for clarity) > > >>>> ?if tarfile.is_tarfile( file ): > >>>> ? ? ? ? try: > >>>> ? ? ? ? ? ? xf =arfile.open( file, "r:gz" ) > >>>> ? ? ? ? ? ? for locFile in xf: > >>>> ? ? ? ? ? ? ? ? logfile =f.extractfile( locFile ) > >>>> ? ? ? ? ? ? ? ? validFileFlag =rue > >>>> ? ? ? ? ? ? ? ? # iterate through each log file, grab the first and > >>>> the last lines > >>>> ? ? ? ? ? ? ? ? lines =ter( logfile ) > >>>> ? ? ? ? ? ? ? ? firstLine =ines.next() > >>>> ? ? ? ? ? ? ? ? for nextLine in lines: > >>>> ? ? ? ? ? ? ? ? ? ? .... > >>>> ? ? ? ? ? ? ? ? ? ? ? ? continue > > >>>> ? ? ? ? ? ? ? ? logfile.close() > >>>> ? ? ? ? ? ? ? ? ?... > >>>> ? ? ? ? ? ? xf.close() > >>>> ? ? ? ? except Exception, e: > >>>> ? ? ? ? ? ? validFileFlag =alse > >>>> ? ? ? ? ? ? msg =\nCould not open the log file: " + repr(file) + " > >>>> Exception: " + str(e) + "\n" > >>>> ?else: > >>>> ? ? ? ? validFileFlag =alse > >>>> ? ? ? ? lTime =xtractFileNameTime( file ) > >>>> ? ? ? ? msg =>>>>>>> Warning " + file + " is NOT a valid tar archive > >>>> \n" > >>>> ? ? ? ? print msg > > >>> I haven't used tarfile, but this feels like a problem with the Win/Unix > >>> line endings. ?I'm going to assume you're running on Windows, which > >>> could trigger the problem I'm going to describe. > > >>> You use 'file' to hold something, but don't show us what. ?In fact, it's > >>> a lousy name, since it's already a Python builtin. ?But if it's holding ? > >>> fileobj, that you've separately opened, then you need to change that > >>> open to use mode 'rb' > > >>> The problem, if I've guessed right, is that occasionally you'll > >>> accidentally encounter a 0d0a sequence in the middle of the (binary) > >>> compressed data. ?If you're on Windows, and use the default 'r' mode, > >>> it'll be changed into a 0a byte. ?Thus corrupting the checksum, and > >>> eventually the contents. > > >>> DaveA > > >> Hi, > > >> thanks for the comments - I'll change the variable name. > > >> I am running this on linux so don't think its a Windows issue. ?So if > >> that's the case > >> is the 0d0a still an issue? > > >> 'mark > > > Oh and what's stored currently in > > The file var us just the unopened pathname to the > > Target file I want to open > > No, on Linux, there should be no such problem. ?And I have to assume > that if you pass the filename as a string, the library would use 'rb' > anyway. ?It's just if you pass a fileobj, ?AND are on Windows. > > Sorry I wasted your time, but nobody else had answered, and I hoped it > might help. > > DaveA Hi Dave thanks for responding - you were not wasting my time but helping me to be aware of other potential issues. Appreciate it much. Its just weird that it works for most files and even finds corrupt ones, but some of the ones it marks as corrupt seem to be OK. thanks 'mark From nagle at animats.com Fri Aug 20 12:34:58 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 09:34:58 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6e3313$0$16599$426a74cc@news.free.fr> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> Message-ID: <4c6eaead$0$1638$742ec2ed@news.sonic.net> On 8/20/2010 12:47 AM, News123 wrote: > On 08/20/2010 02:26 AM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be tricky? > Is this a sincere surprise or are you just boasting? >> >> If I remember correctly, my puzzlement about recursion lasted about 15 >> seconds. I remember thinking "How does the function foo know that there >> is a function foo when foo doesn't fully exist yet?", but once I accepted >> the fact that it just does it all just seemed obvious. Getting recursion >> *right* is sometimes tricky, but the idea itself isn't. If you think about what the implementation has to do, it's quite complicated. Which objects are copied, and which are merely referenced? Is the recursion going to result in control being inside the same object instance twice? Is the recursion a closure? Is tail recursion possible, and does your language implement it? Python does not do tail recursion, so using recursion where iteration could do the job is generally a bad idea. Scheme, on the other hand, always does tail recursion where possible. Python does have generators, and I recently wrote a recursive generator for a production application. I needed to descend a specialized directory tree structure (the one used by the US Securities and Exchange Commission to store filings) and retrieve the last N days of filings. So I have a recursive generator that returns directory after directory, descending into the directories for years and quarters as necessary. The calling function stops calling the generator when it has found the information it needs, which happens before the generator runs out. That's a real-life use case for such a construct, and led to much shorter code than a non-recursive implementation. John Nagle From ahleniusm at gmail.com Fri Aug 20 12:44:29 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 09:44:29 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> Message-ID: <19aa141c-1ae9-47ed-bf4b-9af0b0de0396@u26g2000yqu.googlegroups.com> On Aug 20, 9:25?am, Peter Otten <__pete... at web.de> wrote: > m_ahlenius wrote: > > On Aug 20, 6:57 am, m_ahlenius wrote: > >> On Aug 20, 5:34 am, Dave Angel wrote: > > >> > m_ahlenius wrote: > >> > > Hi, > > >> > > I am relatively new to doing serious work in python. ?I am using it > >> > > to access a large number of log files. ?Some of the logs get > >> > > corrupted and I need to detect that when processing them. ?This code > >> > > seems to work for quite a few of the logs (all same structure) ?It > >> > > also correctly identifies some corrupt logs but then it identifies > >> > > others as being corrupt when they are not. > > >> > > example error msg from below code: > > >> > > Could not open the log file: '/disk/7-29-04-02-01.console.log.tar.gz' > >> > > Exception: CRC check\ > >> > > failed 0x8967e931 != 0x4e5f1036L > > >> > > When I manually examine the supposed corrupt log file and use > >> > > "tar -xzvof /disk/7-29-04-02-01.console.log.tar.gz " ?on it, it opens > >> > > just fine. > > >> > > Is there anything wrong with how I am using this module? ?(extra code > >> > > removed for clarity) > > >> > > if tarfile.is_tarfile( file ): > >> > > try: > >> > > xf = tarfile.open( file, "r:gz" ) > >> > > for locFile in xf: > >> > > logfile = xf.extractfile( locFile ) > >> > > validFileFlag = True > >> > > # iterate through each log file, grab the first and > >> > > the last lines > >> > > lines = iter( logfile ) > >> > > firstLine = lines.next() > >> > > for nextLine in lines: > >> > > .... > >> > > continue > > >> > > logfile.close() > >> > > ... > >> > > xf.close() > >> > > except Exception, e: > >> > > validFileFlag = False > >> > > msg = "\nCould not open the log file: " + repr(file) + " > >> > > Exception: " + str(e) + "\n" > >> > > else: > >> > > validFileFlag = False > >> > > lTime = extractFileNameTime( file ) > >> > > msg = ">>>>>>> Warning " + file + " is NOT a valid tar archive > >> > > \n" > >> > > print msg > > >> > I haven't used tarfile, but this feels like a problem with the Win/Unix > >> > line endings. ?I'm going to assume you're running on Windows, which > >> > could trigger the problem I'm going to describe. > > >> > You use 'file' to hold something, but don't show us what. ?In fact, > >> > it's a lousy name, since it's already a Python builtin. ?But if it's > >> > holding fileobj, that you've separately opened, then you need to change > >> > that open to use mode 'rb' > > >> > The problem, if I've guessed right, is that occasionally you'll > >> > accidentally encounter a 0d0a sequence in the middle of the (binary) > >> > compressed data. ?If you're on Windows, and use the default 'r' mode, > >> > it'll be changed into a 0a byte. ?Thus corrupting the checksum, and > >> > eventually the contents. > > >> > DaveA > > >> Hi, > > >> thanks for the comments - I'll change the variable name. > > >> I am running this on linux so don't think its a Windows issue. ?So if > >> that's the case > >> is the 0d0a still an issue? > > >> 'mark > > > Oh and what's stored currently in > > The file var us just the unopened pathname to the > > Target file I want to open > > Random questions: > > What python version are you using? > If you have other python versions around, do they exhibit the same problem? > If you extract and compress your data using the external tool, does the > resulting file make problems in Python, too? > If so, can you reduce data size and put a small demo online for others to > experiment with? > > Peter Hi, I am using Python 2.6.5. Unfortunately I don't have other versions installed so its hard to test with a different version. As for the log compression, its a bit hard to test. Right now I may process 100+ of these logs per night, and will get maybe 5 which are reported as corrupt (typically a bad CRC) and 2 which it reported as a bad tar archive. This morning I checked each of the 7 reported problem files by manually opening them with "tar -xzvof" and they were all indeed corrupt. Sign. Unfortunately due to the nature of our business, I can't post the data files online, I hope you can understand. But I really appreciate your suggestions. The thing that gets me is that it seems to work just fine for most files, but then not others. Labeling normal files as corrupt hurts us as we then skip getting any log data from those files. appreciate all your help. 'mark From neilc at norwich.edu Fri Aug 20 13:09:43 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 20 Aug 2010 17:09:43 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> Message-ID: <8d7r6nFe1nU1@mid.individual.net> On 2010-08-20, John Nagle wrote: > Python does not do tail recursion, so using recursion where > iteration could do the job is generally a bad idea. Scheme, on > the other hand, always does tail recursion where possible. A tail-recursive function is usually easy to convert to a loop-style iteration. However, Scheme does tail-call optimization, I believe, which is slightly more general. -- Neil Cerutti From thomas at jollybox.de Fri Aug 20 13:41:44 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 20 Aug 2010 19:41:44 +0200 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: <201008201941.45601.thomas@jollybox.de> On Friday 20 August 2010, it occurred to Nobody to exclaim: > Unix lacks the "Append Data" permission for files, and the "Create Files", > "Create Folders" and "Delete Subfolders and Files" correspond to having > write permission on a directory. How does append differ from write? If you have appending permissions, but not writing ones, is it impossible to seek? Or is there a more complex "block" that bites you when you seek to before the old end of file and try writing there? Thank you for the insights, "Nobody". Makes me wonder whether SELinux makes changes in this area, and if so, how far-reaching they are. > On Unix, you can read permissions (and attributes if the filesystem has > them) for any file which you can "reach" (i.e. have "x" permission on all > ancestor directories). You can only change permissions (and some > attributes) if you own the file, and only root can change ownership (and > change some attributes). > > 2. Permissions can be inherited from the "parent object" (which isn't > necessarily the parent folder). If you change a permission on the parent > object, it automatically affects any file or folder which inherits the > permission. > > 3. The owner can be either a user or a group. What about both? > 4. On Windows, a file cannot be "given away" either by its owner or an > administrator. You can grant the "Take Ownership" permission, but > the recipient still has to explicitly change the ownership. Really? So the operating system actually places restrictions on what the administrator can do? Or is there a fine distinction here between administrator-accounts in general and the NT "Administrator" account that at least some versions of Windows (xp home edition springs to mind) appear to try to hide as best they can ? Well, this is probably just my UNIX conditioning, expecting a single all-powerful super-user, shining through here -- but it does seam strange to have a super- user that is not omnipotent. From mail at timgolden.me.uk Fri Aug 20 13:42:08 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Aug 2010 18:42:08 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: <4C6EBE70.2040308@timgolden.me.uk> On 20/08/2010 5:10 PM, vsoler wrote: > On Aug 20, 5:10 pm, Tim Golden wrote: >> To decode the permission bit-strings to vaguely meaningful >> names: >> >> >> import os, sys >> from winsys import fs >> >> dacl = fs.file (sys.executable).security ().dacl >> for permission in dacl: >> print (d.trustee, " (Inherited )" if d.inherited else "") >> for name in fs.FILE_ACCESS.names_from_value (d.access): >> print (" ", name) >> >> >> >> TJG > > it seems as though the definition of "d" is missing in your last piece > of code Whoops, changed tack mid-thingy. Try: dacl = ... for d in dacl: # .. as before From __peter__ at web.de Fri Aug 20 13:55:54 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Aug 2010 19:55:54 +0200 Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> <19aa141c-1ae9-47ed-bf4b-9af0b0de0396@u26g2000yqu.googlegroups.com> Message-ID: m_ahlenius wrote: > I am using Python 2.6.5. > > Unfortunately I don't have other versions installed so its hard to > test with a different version. > > As for the log compression, its a bit hard to test. Right now I may > process 100+ of these logs per night, and will get maybe 5 which are > reported as corrupt (typically a bad CRC) and 2 which it reported as a > bad tar archive. This morning I checked each of the 7 reported > problem files by manually opening them with "tar -xzvof" and they were > all indeed corrupt. Sign. So many corrupted files? I'd say you have to address the problem with your infrastructure first. > Unfortunately due to the nature of our business, I can't post the data > files online, I hope you can understand. But I really appreciate your > suggestions. > > The thing that gets me is that it seems to work just fine for most > files, but then not others. Labeling normal files as corrupt hurts us > as we then skip getting any log data from those files. > > appreciate all your help. I've written an autocorruption script, import sys import subprocess import tarfile def process(source, dest, data): for pos in range(len(data)): for bit in range(8): new_data = data[:pos] + chr(ord(data[pos]) ^ (1< <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> Message-ID: <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> On Aug 20, 1:23?am, Martin Braun wrote: > I find this thread extremely interesting, but what surprised me that > everyone seems to agree that mathematics is 1-based, but we Pythoneers > should stick to zero-based. I disagree. To make sure I'm not going > crazy, I took the top five books lying on my desk, which were the DSP > book by Oppenheim/Schafer, two books by Stephen M. Kay (Spectral > Estimation and Estimation Theory) and the Channel Coding book by Lin & > Costello. This is isn't pure mathematics (as in proving the Goldbach > conjecture), but nevertheless, this is serious mathematics and, > surprise, they most exclusively use zero-based notation. > You probably don't have those books in grabbing distance, so here's some > examples for zero-based stuff: That's interesting, but I think zero-based indexing is rare in the literature of mathematics, applied math, science and engineering. All the literature I've ever seen that uses vectors and matrices is one- based, and that includes text books and technical papers. It all boils down to personal preference, but I just find it strange that we would not try to make programming as consistent as possible with notational conventions in the literature. If I try to implement some algorithm I find in a technical book or paper, why should I have to mentally offset every index by one? That's very error prone, and I have more important things to think about. Then again, I don't do that very often, so maybe it's not a big deal. The zero-based indexing just seemed wrong to me when I first saw it. I'm used to it by now, but it still doesn't seem quite right to me. It's almost right -- but it's off by one. I still have a habit of taking the "1" element when I really want the "0" element. Most programmers probably never use vectors and matrices, so they don't care about the inconsistency with standard mathematical notation. And yes, I understand that zero-based indexing can be slightly more efficient. That's why I think it's appropriate for low-level languages such as C. However, I think one-based indexing is more appropriate for high-level languages. From znarus at telia.com Fri Aug 20 14:09:36 2010 From: znarus at telia.com (M B) Date: Fri, 20 Aug 2010 20:09:36 +0200 Subject: scope of variable Message-ID: <1282327776.2942.3.camel@pex-desktop> Hi, I try to learn python. I don't understand this: (running in idle) >>> dept=0 >>> def mud(): print dept >>> mud() 0 >>> def mud(): dept+=1 print dept >>> mud() Traceback (most recent call last): File "", line 1, in mud() File "", line 2, in mud dept+=1 UnboundLocalError: local variable 'dept' referenced before assignment >>> Regards MB From debatem1 at gmail.com Fri Aug 20 14:19:46 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 20 Aug 2010 11:19:46 -0700 Subject: Python "why" questions In-Reply-To: <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 11:01 AM, Russ P. wrote: > On Aug 20, 1:23?am, Martin Braun wrote: > >> I find this thread extremely interesting, but what surprised me that >> everyone seems to agree that mathematics is 1-based, but we Pythoneers >> should stick to zero-based. I disagree. To make sure I'm not going >> crazy, I took the top five books lying on my desk, which were the DSP >> book by Oppenheim/Schafer, two books by Stephen M. Kay (Spectral >> Estimation and Estimation Theory) and the Channel Coding book by Lin & >> Costello. This is isn't pure mathematics (as in proving the Goldbach >> conjecture), but nevertheless, this is serious mathematics and, >> surprise, they most exclusively use zero-based notation. >> You probably don't have those books in grabbing distance, so here's some >> examples for zero-based stuff: > > That's interesting, but I think zero-based indexing is rare in the > literature of mathematics, applied math, science and engineering. All > the literature I've ever seen that uses vectors and matrices is one- > based, and that includes text books and technical papers. Not sure what you read, but for me (mostly number theory, numerical analysis, and abstract algebra) zero-based indexing is quite common. > It all boils down to personal preference, but I just find it strange > that we would not try to make programming as consistent as possible > with notational conventions in the literature. If I try to implement > some algorithm I find in a technical book or paper, why should I have > to mentally offset every index by one? That's very error prone, and I > have more important things to think about. Then again, I don't do that > very often, so maybe it's not a big deal. Ever read code by a mathematician? It's usually (obviously not always) a nightmare. I'm glad we break with convention, particularly when that convention is things like one-letter variables and 'reuse' of notation. Geremy Condra From clp2 at rebertia.com Fri Aug 20 14:25:05 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 20 Aug 2010 11:25:05 -0700 Subject: scope of variable In-Reply-To: <1282327776.2942.3.camel@pex-desktop> References: <1282327776.2942.3.camel@pex-desktop> Message-ID: On Fri, Aug 20, 2010 at 11:09 AM, M B wrote: > Hi, > I try to learn python. > I don't understand this: >>>> dept=0 >>>> def mud(): > ? ? ? ?dept+=1 > ? ? ? ?print dept > >>>> mud() > Traceback (most recent call last): > ?File "", line 1, in > ? ?mud() > ?File "", line 2, in mud > ? ?dept+=1 > UnboundLocalError: local variable 'dept' referenced before assignment http://www.mail-archive.com/python-list at python.org/msg75263.html Cheers, Chris -- Google is your friend http://blog.rebertia.com From kara at kara-moon.com Fri Aug 20 14:33:19 2010 From: kara at kara-moon.com (Rony) Date: Fri, 20 Aug 2010 11:33:19 -0700 (PDT) Subject: scope of variable References: <1282327776.2942.3.camel@pex-desktop> Message-ID: <3ad95d6c-9011-4c07-8a93-38efbdaa5eca@c10g2000yqi.googlegroups.com> On Aug 20, 8:25?pm, Chris Rebert wrote: > On Fri, Aug 20, 2010 at 11:09 AM, M B wrote: > > Hi, > > I try to learn python. > > I don't understand this: > > >>>> dept=0 > > >>>> def mud(): > > ? ? ? ?dept+=1 > > ? ? ? ?print dept > > >>>> mud() > > Traceback (most recent call last): > > ?File "", line 1, in > > ? ?mud() > > ?File "", line 2, in mud > > ? ?dept+=1 > > UnboundLocalError: local variable 'dept' referenced before assignment Just put a global dept at the start of your function and it will work Rony From martin at address-in-sig.invalid Fri Aug 20 14:34:16 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Fri, 20 Aug 2010 18:34:16 +0000 (UTC) Subject: A question to experienced Pythoneers References: <8d1b76b7-1ba3-49c5-97cf-dc38370502ae@y11g2000yqm.googlegroups.com> <4C6E8CC8.2090603@sschwarzer.net> <8d6f1093-c585-4374-a843-2e452aebafa5@i13g2000yqd.googlegroups.com> <4c6e9c3c$0$411$426a74cc@news.free.fr> Message-ID: On Fri, 20 Aug 2010 17:16:14 +0200, Bruno Desthuilliers wrote: > Rony a ?crit : >> It looks like I forgot to specify that the product is a totaly new >> product build from scratch, not an upgrade from an existing product. > > > Still the advice to first find out what went wrong with the previous > project is a very sensible one. Technical problems do exist, but from > experience they rarely are the main source of failure. > And be sure to look into the estimation and costing methods the company is using. IOW are you sure whether design/build/test phases are overrunning a sensible estimate or if the initial costing and estimation is underestimating the project size? -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From nagle at animats.com Fri Aug 20 14:50:39 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 11:50:39 -0700 Subject: urllib "quote" problem In-Reply-To: References: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> Message-ID: <4c6ece79$0$1583$742ec2ed@news.sonic.net> On 8/20/2010 8:41 AM, Aahz wrote: > In article<4c5eef7f$0$1609$742ec2ed at news.sonic.net>, > John Nagle wrote: >> >> This looks like code that will do the wrong thing in >> Python 2.6 for characters in the range 128-255. Those are >> illegal in type "str", but this code is constructing such >> values with "chr". > > WDYM "illegal"? Type "str" in Python 2.6 is ASCII, 0..127. John Nagle From nagle at animats.com Fri Aug 20 14:54:36 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 11:54:36 -0700 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> <4c6cefc6$0$11111$c3e8da3@news.astraweb.com> <31e9a229-9422-42d4-ab51-14cd4aaf62af@z10g2000yqb.googlegroups.com> Message-ID: <4c6ecf67$0$1639$742ec2ed@news.sonic.net> On 8/20/2010 9:07 AM, Rami Chowdhury wrote: > On Fri, Aug 20, 2010 at 21:02, ata.jaf wrote: >> On Aug 19, 11:48 am, Steven D'Aprano> T... at cybersource.com.au> wrote: >>> On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote: >>>> On Aug 17, 11:55 pm, Thomas Jollans wrote: >> Yes I have a source code encoding line. >> Here it is: >> >> # -*- coding: utf_16 -*- Try "utf_8". >> >> I am using WxPython. >> >> And the error that I get about using utf-16 is:\ >> >> Traceback (most recent call last): >> File "", line 1, in >> File "z.py", line 2 >> SyntaxError: UTF-16 stream does not start with BOM > > Which encoding are you saving your script in? Very few of the text > editors I've used save to UTF-16 by default. Most editors that will do Unicode save files as "utf-8". Try that. John Nagle From thomas at jollybox.de Fri Aug 20 15:04:55 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 20 Aug 2010 21:04:55 +0200 Subject: Looking for an appropriate encoding standard that supports all languages In-Reply-To: <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: <201008202104.55683.thomas@jollybox.de> On Thursday 19 August 2010, it occurred to ata.jaf to exclaim: > On Aug 17, 11:55 pm, Thomas Jollans wrote: > > On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > > > I am developing a little program in Mac with wxPython. > > > But I have problems with the characters that are not in ASCII. Like > > > some special characters in French or Turkish. > > > So I am looking for a way to solve this. Like an encoding standard > > > that supports all languages. Or some other way. > > > > Anything that supports all of Unicode will do. Like UTF-8. If your text > > is mostly Latin, then just go for UTF-8, if you use other alphabets > > extensively, you might want to consider UTF-16, which might the use a > > little less space. > > OK, I used UTF-8. > I write a line of strings in the source code and I want my program to > show that as an output on GUI. And this line of strings includes a > character like "?". But I see that in GUI this character is replaced > with another strange characters. I mean it doesn't work. > And when I try to use UTF-16, I get an syntax error that declares > "UTF-16 stream does not start with BOM". I get the feeling you're not actually using the encoding you say you're using, or not telling every program involved what you're doing. 1. Save the file in the correct encoding. Either tell your text editor to use a specific encoding (UTF-8 would be a good choice), or find out what encoding your text editor is using and use that encoding during the rest of the process. 2. Tell Python which encoding you're using. The coding: line will do the trick, *provided* you don't lie, and the encoding your specify in the file is actually the encoding you're using to store the file on disk. 3. Instruct your GUI library to do the right thing. If you use unicode strings (either by using Python 3 or by using the u"K?se" syntax in Python 2), that should be enough, otherwise, if you're using byte strings, which you shouldn't be doing in this case, you might have to tell the library what you're doing, or use the customary encoding. (For GTK+, this is UTF-8. For other libraries, it might be Latin-1, or system-dependent) From robert.kern at gmail.com Fri Aug 20 15:09:58 2010 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 20 Aug 2010 14:09:58 -0500 Subject: urllib "quote" problem In-Reply-To: <4c6ece79$0$1583$742ec2ed@news.sonic.net> References: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> <4c6ece79$0$1583$742ec2ed@news.sonic.net> Message-ID: On 8/20/10 1:50 PM, John Nagle wrote: > On 8/20/2010 8:41 AM, Aahz wrote: >> In article<4c5eef7f$0$1609$742ec2ed at news.sonic.net>, >> John Nagle wrote: >>> >>> This looks like code that will do the wrong thing in >>> Python 2.6 for characters in the range 128-255. Those are >>> illegal in type "str", but this code is constructing such >>> values with "chr". >> >> WDYM "illegal"? > > Type "str" in Python 2.6 is ASCII, 0..127. In Python 2.6, type "str" is comprised of bytes 0..255, not ASCII characters. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From jkrukoff at ltgc.com Fri Aug 20 15:10:13 2010 From: jkrukoff at ltgc.com (John Krukoff) Date: Fri, 20 Aug 2010 13:10:13 -0600 Subject: [ANN]VTD-XML 2.9 In-Reply-To: <61aedbd9-1fa4-4f37-926e-f57512948a9d@q21g2000prm.googlegroups.com> References: <61aedbd9-1fa4-4f37-926e-f57512948a9d@q21g2000prm.googlegroups.com> Message-ID: <1282331413.3695.1.camel@localhost> On Thu, 2010-08-19 at 17:40 -0700, dontcare wrote: > VTD-XML 2.9, the next generation XML Processing API for SOA and Cloud > computing, has been released. Please visit https://sourceforge.net/projects/vtd-xml/files/ > to download the latest version. > > * Strict Conformance > # VTD-XML now fully conforms to XML namespace 1.0 spec > * Performance Improvement > # Significantly improved parsing performance for small XML files > * Expand Core VTD-XML API > # Adds getPrefixString(), and toNormalizedString2() > * Cutting/Splitting > # Adds getSiblingElementFragment() > * A number of bug fixes and code enhancement including: > # Fixes a bug for reading very large XML documents on some > platforms > # Fixes a bug in parsing processing instruction > # Fixes a bug in outputAndReparse() So, correct me if I'm wrong, but it doesn't look like this project even has a python version. So, why is it on the python-announce list? -- John Krukoff Land Title Guarantee Company jkrukoff at ltgc.com From python at mrabarnett.plus.com Fri Aug 20 15:13:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 20 Aug 2010 20:13:52 +0100 Subject: urllib "quote" problem In-Reply-To: <4c6ece79$0$1583$742ec2ed@news.sonic.net> References: <4c5eef7f$0$1609$742ec2ed@news.sonic.net> <4c6ece79$0$1583$742ec2ed@news.sonic.net> Message-ID: <4C6ED3F0.9030001@mrabarnett.plus.com> John Nagle wrote: > On 8/20/2010 8:41 AM, Aahz wrote: >> In article<4c5eef7f$0$1609$742ec2ed at news.sonic.net>, >> John Nagle wrote: >>> >>> This looks like code that will do the wrong thing in >>> Python 2.6 for characters in the range 128-255. Those are >>> illegal in type "str", but this code is constructing such >>> values with "chr". >> >> WDYM "illegal"? > > Type "str" in Python 2.6 is ASCII, 0..127. > Actually 'str' in Python 2.6 is bytestring, or ASCII + other characters, by which I mean that the other characters aren't affected by .lower, etc. From burton at userful.com Fri Aug 20 15:19:08 2010 From: burton at userful.com (Burton Samograd) Date: Fri, 20 Aug 2010 13:19:08 -0600 Subject: scope of variable References: <1282327776.2942.3.camel@pex-desktop> Message-ID: M B writes: > Hi, >>>> dept=0 >>>> def mud(): > print dept > > >>>> mud() > 0 >>>> def mud(): > dept+=1 > print dept You should add a global statement or else python thinks a variable used is a local: >>> def mud(): global dept dept+=1 print dept -- Burton Samograd From russ.paielli at gmail.com Fri Aug 20 15:31:36 2010 From: russ.paielli at gmail.com (Russ P.) Date: Fri, 20 Aug 2010 12:31:36 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> Message-ID: <6ec14625-0f5e-4f43-b889-150e8add8b1e@a36g2000yqc.googlegroups.com> On Aug 20, 11:19?am, geremy condra wrote: > Not sure what you read, but for me (mostly number theory, numerical > analysis, and abstract algebra) zero-based indexing is quite common. My background is in aerospace control engineering. I am certainly not familiar with the literature in pure mathematics, but I assume that the math textbooks I used on college used standard mathematical notation. If one-based indexing is becoming more common in the literature, I'll bet that is only because it is so widely used in computer programming -- not because the writers decided independently that it is a better notation. But that's just a guess on my part. From tom.browder at gmail.com Fri Aug 20 15:32:54 2010 From: tom.browder at gmail.com (Tom Browder) Date: Fri, 20 Aug 2010 14:32:54 -0500 Subject: How to Customize the New 2.7 ArgumentParser Library Class (module argparse)? Message-ID: I have converted from OptionParser to ArgumentParser (new in version 2.7) to great advantage, and I think it's a great improvement! But now I want to customize the help formatting just a bit. The documentation is sketchy here, but I started by subclassing ArgumentParser and attempted to redefine format_usage, but after looking at the detailed instructions with pydoc I see "the API of the formatter objects is still considered an implementation detail." I take that to mean I should abandon such efforts at the moment. So, using the defined class as is, and following instructions in the online docs, I have been able to get my output to look like this: ==============> $ test_argparser.py -h usage: test_argparser.py [options] A program to manipulate user programs. optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -s, --show Show a list of user post-processing programs. Version 2010-08-20.01 <============== To beautify things I would like to change two strings which are auto-generated by the standard parser: 1. change "usage:" to "Usage:" # capitalize 'usage' 2. change "optional arguments:" to "Optional arguments:" # capitalize 'Optional' Does anyone know how to do it without modifying source code? Thanks, -Tom Thomas M. Browder, Jr. Niceville, Florida USA From thomas at jollybox.de Fri Aug 20 15:36:31 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 20 Aug 2010 21:36:31 +0200 Subject: How to convert bytearray into integer? In-Reply-To: <38b3c3b4-5a06-4fe1-9e5f-7194142a3606@f20g2000pro.googlegroups.com> References: <38b3c3b4-5a06-4fe1-9e5f-7194142a3606@f20g2000pro.googlegroups.com> Message-ID: <201008202136.31591.thomas@jollybox.de> On Tuesday 17 August 2010, it occurred to Jacky to exclaim: > On Aug 17, 3:38 am, Thomas Jollans wrote: > > On Monday 16 August 2010, it occurred to Jacky to exclaim: > > > it's hard to image why socket object provides the interface: > > > socket.recv_from(buf[, num_bytes[, flags]]) but forget the more > > > generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]]) > > > > Well, that's what pointer arithmetic (in C) or slices (in Python) are > > for! There's an argument to be made for sticking close to the > > traditional (originally C) interface here - it's familiar. > > Hi Thomas, - I'm not quite follow you. It will be great if you could > show me some code no this part... When I originally wrote that, I didn't check the Python docs, I just had a quick look at the manual page. This is the signature of the BSD-socket recv function: (recv(2)) ssize_t recv(int sockfd, void *buf, size_t len, int flags); so, to receive data into a buffer, you pass it the buffer pointer. len = recv(sock, buf, full_len, 0); To receive more data into another buffer, you pass it a pointer further on: len = recv(sock, buf+len, full_len-len, 0); /* or, this might be clearer, but it's 100% the same: */ len = recv(sock, & buf[len], full_len-len, 0); Now, in Python. I assume you were referring to socket.recv_into: socket.recv_into(buffer[, nbytes[, flags]]) It's hard to imagine why this method exists at all. I think the recv method is perfectly adequate: buf = bytearray() buf[:] = sock.recv(full_len) # then: lngth = len(buf) buf[lngth:] = sock.recv(full_len - lngth) But still, nothing's stopping us from using recv_into: # create a buffer large enough. Oh this is so C... buf = bytearray([0]) * full_len lngth = sock.recv_into(buf, length_of_first_bit) # okay, now let's fill the rest ! sock.recv_into(memoryview(buf)[lngth:]) In C, you can point your pointers where ever you want. In Python, you can point your memoryview at buffers in any way you like, but there tend to be better ways of doing things. Cheers, Thomas From znarus at telia.com Fri Aug 20 15:56:52 2010 From: znarus at telia.com (M B) Date: Fri, 20 Aug 2010 21:56:52 +0200 Subject: scope of variable In-Reply-To: References: <1282327776.2942.3.camel@pex-desktop> Message-ID: <1282334212.1887.6.camel@pex-desktop> fre 2010-08-20 klockan 13:19 -0600 skrev Burton Samograd: > M B writes: > > > Hi, > >>>> dept=0 > >>>> def mud(): > > print dept > > > > > >>>> mud() > > 0 > >>>> def mud(): > > dept+=1 > > print dept > > You should add a global statement or else python thinks a variable used > is a local: > > >>> def mud(): > global dept > dept+=1 > print dept > > -- > Burton Samograd > Ok. Thanks for the answers. :) I was a bit puzzled of the fact that I could read but not assign to a global variable. From debatem1 at gmail.com Fri Aug 20 16:07:38 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 20 Aug 2010 13:07:38 -0700 Subject: Python "why" questions In-Reply-To: <6ec14625-0f5e-4f43-b889-150e8add8b1e@a36g2000yqc.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <6ec14625-0f5e-4f43-b889-150e8add8b1e@a36g2000yqc.googlegroups.com> Message-ID: On Fri, Aug 20, 2010 at 12:31 PM, Russ P. wrote: > On Aug 20, 11:19?am, geremy condra wrote: > >> Not sure what you read, but for me (mostly number theory, numerical >> analysis, and abstract algebra) zero-based indexing is quite common. > > My background is in aerospace control engineering. I am certainly not > familiar with the literature in pure mathematics, but I assume that > the math textbooks I used on college used standard mathematical > notation. > > If one-based indexing is becoming more common in the literature, I'll > bet that is only because it is so widely used in computer programming > -- not because the writers decided independently that it is a better > notation. But that's just a guess on my part. I can't speak for the motivation for selecting that notation, but I'm not sure it matters anyway- if the rationale for a switch is to become consistent with mathematical notation and the 0-based indexing is becoming a common notation in that field then we achieve consistency by standing still. Geremy Condra From john at castleamber.com Fri Aug 20 16:17:22 2010 From: john at castleamber.com (John Bokma) Date: Fri, 20 Aug 2010 15:17:22 -0500 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> Message-ID: <8739u9ninh.fsf@castleamber.com> John Nagle writes: > Python does not do tail recursion, so using recursion > where iteration could do the job is generally a bad idea. Scheme, on > the other hand, always does tail recursion where possible. I think you mean tail recursion optimization / elimination. Python does tail recursion: >>> def x(n): ... if n == 10: return ... print n ... x(n + 1) ... >>> x(1) 1 2 3 4 5 6 7 8 9 -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From __peter__ at web.de Fri Aug 20 16:19:42 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Aug 2010 22:19:42 +0200 Subject: How to Customize the New 2.7 ArgumentParser Library Class (module argparse)? References: Message-ID: Tom Browder wrote: > I have converted from OptionParser to ArgumentParser (new in version > 2.7) to great advantage, and I think it's a great improvement! But > now I want to customize the help formatting just a bit. > > The documentation is sketchy here, but I started by subclassing > ArgumentParser and attempted to redefine format_usage, but after > looking at the detailed instructions with pydoc I see "the API of the > formatter objects is still considered an implementation detail." > > I take that to mean I should abandon such efforts at the moment. > > So, using the defined class as is, and following instructions in the > online docs, I have been able to get my output to look like this: > > ==============> > $ test_argparser.py -h > usage: test_argparser.py [options] > > A program to manipulate user programs. > > optional arguments: > -h, --help Show this help message and exit. > -v, --version Show program's version number and exit. > -s, --show Show a list of user post-processing programs. > > Version 2010-08-20.01 > <============== > > To beautify things I would like to change two strings which are > auto-generated by the standard parser: > > 1. change "usage:" > > to "Usage:" # capitalize 'usage' > > 2. change "optional arguments:" > > to "Optional arguments:" # capitalize 'Optional' > > Does anyone know how to do it without modifying source code? You can use internationalization via http://docs.python.org/library/gettext.html or take a shortcut: $ cat tmp.py lookup = { "usage: ": "Usage: ", "optional arguments": "Optional arguments"} def gettext(s): return lookup.get(s, s) import argparse argparse._ = gettext if __name__ == "__main__": p = argparse.ArgumentParser() p.parse_args() $ python tmp.py -h Usage: tmp.py [-h] Optional arguments: -h, --help show this help message and exit Peter From hughaguilar96 at yahoo.com Fri Aug 20 18:51:44 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Fri, 20 Aug 2010 15:51:44 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> On Aug 18, 6:23?pm, Standish P wrote: > On Aug 17, 6:38?pm, John Passaniti wrote: > > > You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > > lists are constructed with pair of pointers called a "cons cell". > > That is the most primitive component that makes up a list. ?Forth has > > no such thing; in Forth, the dictionary (which is traditionally, but > > not necessarily a list) is a data structure that links to the previous > > word with a pointer. ? > > Would you show me a picture, ascii art or whatever for Forth ? I know > what lisp lists look like so I dont need that for comparison. Forth > must have a convention and a standard or preferred practice for its > dicts. However, let me tell you that in postscript the dictionaries > can be nested inside other dictionaries and any such hiearchical > structure is a nested associative list, which is what linked list, > nested dictionaries, nested tables are. You can see an example of lists in my novice package (in the list.4th file): http://www.forth.org/novice.html Also in there is symtab, which is a data structure intended to be used for symbol tables (dictionaries). Almost nobody uses linked lists for the dictionary anymore (the FIG compilers of the 1970s did, but they are obsolete). I must say, I've read through this entire thread and I didn't understand *anything* that *anybody* was saying (especially the OP). I really recommend that people spend a lot more time writing code, and a lot less time with all of this pseudo-intellectual nonsense. This whole thread (and most of what I see on C.L.F. these days) reminds me of the "dialectic method" of the early Middle Ages --- a lot of talk and no substance. Write some programs! Are we not programmers? From vicente.soler at gmail.com Fri Aug 20 18:54:47 2010 From: vicente.soler at gmail.com (vsoler) Date: Fri, 20 Aug 2010 15:54:47 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> Message-ID: <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> On Aug 20, 7:42?pm, Tim Golden wrote: > On 20/08/2010 5:10 PM, vsoler wrote: > > > > > On Aug 20, 5:10 pm, Tim Golden ?wrote: > >> To decode the permission bit-strings to vaguely meaningful > >> names: > > >> > >> import os, sys > >> from winsys import fs > > >> dacl = fs.file (sys.executable).security ().dacl > >> for permission in dacl: > >> ? ? print (d.trustee, " (Inherited )" if d.inherited else "") > >> ? ? for name in fs.FILE_ACCESS.names_from_value (d.access): > >> ? ? ? print (" ?", name) > > >> > > >> TJG > > > it seems as though the definition of "d" is missing in your last piece > > of code > > Whoops, changed tack mid-thingy. Try: > > dacl = ... > for d in dacl: > ? ?# .. as before Tim, I'am testing your library. I am mainly interested in knowing the access attributes of directories in the local(C:\) or shared unit(W:\) of my system. Using your script with 'c:\\' I get an error message saying... 'file exists but it is a directory' and I cannot go any further. Of course, the problem is that I am using "fs.file" when I should be using something different. Reading the doc I have found that I should be using os.walk(...), which works, but then I cannot use fs.file Could you please give me a hint as to what metghod I should be using? Thank you Vicente Soler From hughaguilar96 at yahoo.com Fri Aug 20 19:04:44 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Fri, 20 Aug 2010 16:04:44 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <9e58b256-b381-43a4-91b4-42d94eeafbf2@v41g2000yqv.googlegroups.com> <0684ca4f-2032-4b25-ac29-d8d26fa268f6@x24g2000pro.googlegroups.com> <72f4ab16-edaf-43de-9d33-2b1bffb2d91e@l20g2000yqm.googlegroups.com> Message-ID: <56ef1e79-7a94-45a7-b854-43b48ed96af8@m1g2000yqo.googlegroups.com> On Aug 18, 6:13?pm, Standish P wrote: > > Mostly it had a "snowball's chance" because it was never picked up by > > the CS gurus who, AFAIK, never really took a serious look at it. > > Its quite possible that the criticism is unfair, but dont you think > that in part some responsibility must be borne by your organization in > not doing a good job of education ? > ... > She is quite humble. Take a look at this page, > > http://www.forth.com/resources/evolution/index.html That is actually pretty humorous; she managed to describe herself as a "leading expert" twice in a single short paragraph. LOL See! I do have a sense of humor! http://groups.google.com/group/comp.lang.forth/browse_thread/thread/4c4dba9135bcf03e/8086ee13095bf78c From ben+python at benfinney.id.au Fri Aug 20 19:17:11 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 21 Aug 2010 09:17:11 +1000 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> Message-ID: <8762z4swlk.fsf@benfinney.id.au> Steven D'Aprano writes: > On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: > > > Recursion can be quite a trick to get your mind round at first > > Really? Do people actually find the *concept* of recursion to be > tricky? Evidently so. It's folk wisdom that some adults find recursion an easy concept, and those people will find programming significantly easier; and the majority of people have a great deal of difficulty with recursion and so find programming correspondingly difficult. There is evidence that the phenomenon is at least significant and measurable . There is all manner of speculation as to what might cause this divide in capability, but precious little scientific research has been done on the differences between such people AFAICT. -- \ ?Two possibilities exist: Either we are alone in the Universe | `\ or we are not. Both are equally terrifying.? ?Arthur C. Clarke, | _o__) 1999 | Ben Finney From mailtome200420032002 at gmail.com Fri Aug 20 19:21:15 2010 From: mailtome200420032002 at gmail.com (aj) Date: Fri, 20 Aug 2010 16:21:15 -0700 (PDT) Subject: make install DESTDIR Message-ID: I am trying to install python with make install DESTDIR=/home/blah ./python -E ./setup.py install \ --prefix=/ \ --install-scripts=//bin \ --install-platlib=//lib/python2.6/lib-dynload \ --root=//home/blah running install running build running build_ext INFO: Can't locate Tcl/Tk libs and/or headers Failed to find the necessary bits to build these modules: _tkinter bsddb185 dl imageop sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. running build_scripts running install_lib creating /lib/python2.6 error: could not create '/lib/python2.6': Permission denied make: *** [sharedinstall] Error 1 From raoulbia at gmail.com Fri Aug 20 19:22:44 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 20 Aug 2010 16:22:44 -0700 (PDT) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: Hi Martin Thanks for your post. This basic but fundamental computation is a great example when trying to understand the concept of recursion for the first time. Also thanks to John for the stackoverflow link where i found a very good summarised definition completing some of the posts left here. For future readers of this post who want to learn to programm (just like myself) let me re-state the basics i have learned now: - a procedure is said to be recursive when it contains a statement that calls itself - there must be a condition where the recursion has to stop otherwise the routine will continue to call itself infinitely. This is called the Base Case - every time the procedure calls itself the memory gradually fills up with the copies until the whole thing winds down again as the "return" statements start being executed. - the above point means that a recursive approach is expensive on resources so in the practical world it should be avoided. (Thanks John for giving me a real life example where recursion is recommended) For the purposes of learning programming i think it's a must to understand Recursion so thanks all for your help! Ok so now i hope you all agree that my code is also correct :) def r_countSubStringMatch(target,key): counter=0 if len(key) References: Message-ID: <201008210139.47901.thomas@jollybox.de> On Saturday 21 August 2010, it occurred to aj to exclaim: > I am trying to install python with make install DESTDIR=/home/blah > > --prefix=/ ... > creating /lib/python2.6 > error: could not create '/lib/python2.6': Permission denied > make: *** [sharedinstall] Error 1 Obviously, the flags you specified didn't have the effect you intended. --prefix=$HOME should do the trick. From raoulbia at gmail.com Fri Aug 20 19:42:26 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 20 Aug 2010 16:42:26 -0700 (PDT) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: On Aug 19, 11:00?pm, Martin Gregorie wrote: > By way of a hint, here are two versions of the classic example of > recursion: calculating factorials. Recursion can be quite a trick to get > your mind round at first, so compare the two and follow through their > operation step by step... Hi Martin Thanks for your post. This basic but fundamental computation (calculating factorials) is a great example when trying to understand the concept of recursion for the first time. Also thanks to John for the stackoverflow link where i found a very good summarised definition completing some of the posts left here. For future readers of this post who want to learn to programm (just like myself) let me re-state the basics i have learned now: - a procedure is said to be recursive when it contains a statement that calls itself - there must be a condition where the recursion has to stop otherwise the routine will continue to call itself infinitely. This is called the Base Case - every time the procedure calls itself the memory gradually fills up with the copies until the whole thing winds down again as the "return" statements start being executed. - the above point means that a recursive approach is expensive on resources so in the practical world it should be avoided. (Thanks John for giving me a real life example where recursion is recommended) For the purposes of learning programming i think it's a must to understand Recursion so thanks all for your help! Ok so now i hope you all agree that my code is also correct :) def r_countSubStringMatch(target,key): counter=0 if len(key) References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <201008210159.46825.thomas@jollybox.de> On Saturday 21 August 2010, it occurred to Baba to exclaim: > - every time the procedure calls itself the memory gradually fills up > with the copies until the whole thing winds down again > as the "return" statements start being executed. > - the above point means that a recursive approach is expensive on > resources so in the practical world it should be avoided. > (Thanks John for giving me a real life example where recursion is > recommended) This is only partly true. In most programming languages "typical" today, this is true: each recursion is a normal function call which allocates space on the stack. Thus, the maximum recursion depth is severely limited. However, in most functional programming languages, recursion is recognized as a highly expressive, powerful, and idiomatic tool that can often be optimized. Languages like haskell or scheme compile tail-end recursive functions in a manner that is just as efficient as a loop would have been. In general, if you could rewrite a recursive scheme function to use a loop, then a decent scheme compiler will be able to "do it for you" behind the scenes. From greg.ewing at canterbury.ac.nz Fri Aug 20 20:17:09 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 12:17:09 +1200 Subject: Python "why" questions In-Reply-To: References: <4c5db0ae$0$1641$742ec2ed@news.sonic.net> <8crg0eFfbkU1@mid.individual.net> Message-ID: <8d8jnkFoitU1@mid.individual.net> Lawrence D'Oliveiro wrote: > That is not some kind of ordinal numbering of the terms, that is the power > of the variable involved. It's both. Convention is to make the power and the index of the coefficent the same, because it would be pointlessly confusing to do anything else. -- Greg From martin at address-in-sig.invalid Fri Aug 20 20:24:18 2010 From: martin at address-in-sig.invalid (Martin Gregorie) Date: Sat, 21 Aug 2010 00:24:18 +0000 (UTC) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: On Fri, 20 Aug 2010 16:22:44 -0700, Baba wrote: > For the purposes of learning programming i think it's a must to > understand Recursion so thanks all for your help! > That depends on the language and/or hardware. COBOL wouldn't understand recursion if hit on the head with a recursion brick and early computer hardware (those without a stack) made it VERY hard work. If you don't follow this, look at the CODASYL language specification for COBOL or the hardware design of ICL 1900 or IBM System/360 mainframes (which are still the heart of the financial world) and work out how to implement a recursive function for any of them. Its not easy but it can be done. > Ok so now i hope you all agree that my code is also correct :) > Yes: it runs and does what I'd expect. A good result. A basic skill for a programmer is to understand the specification for a piece of code and write test cases. This is a set of inputs (both expected/sensible and totally out of order) and the expected outputs from each set of inputs. Then you write the code and run it against the test cases to show that it does what the specification requires. Never bullshit yourself or anybody else about this conformance to spec: either you screwed up or, hopefully less often, the designer wrote an ambiguous or plain wrong requirement. Either way, the problem must be resolved and the code be made to do what is wanted. while (results don't match the spec): Rince, wash, repeat. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From greg.ewing at canterbury.ac.nz Fri Aug 20 20:26:19 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 12:26:19 +1200 Subject: Python "why" questions In-Reply-To: References: <8crequF9tpU1@mid.individual.net> Message-ID: <8d8k8vFs2qU1@mid.individual.net> Martin Gregorie wrote: > On Mon, 16 Aug 2010 12:33:51 +1200, Gregory Ewing wrote: > > >>Ian Kelly wrote: >> >>>On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie >>> wrote: >> >>>> real sample[-500:750]; >> >>>Ugh, no. The ability to change the minimum index is evil. >> >>Not always; it can have its uses, particularly when you're using the >>array as a mapping rather than a collection. >> > > Say you have intensity data captured from an X-ray goniometer from 160 > degrees to 30 degrees at 0.01 degree resolution. Which is most evil of > the following? > > 1) real intensity[16000:3000] > for i from lwb intensity to upb intensity > plot(i/100, intensity[i]); > > 2) double angle[13000]; > double intensity[13000]; > for (int i = 0; i < 13000; i++) > plot(angle[i], intensity[i]); > > 3) struct > { > double angle; > double intensity > } measurement; > measurement m[13000]; > for (int i = 0; i < 13000; i++) > plot(m[i].angle, m[i].intensity); > > 4) double intensity[13000]; > for (int i = 0; i < 13000; i++) > plot((16000 - i)/100, intensity[i]) > > To my mind (1) is much clearer to read and far less error-prone to write, > while zero-based indexing forces you to use code like (2), (3) or (4), > all of which obscure rather than clarify what the program is doing. This might be true if the only thing you ever do with your indices is use them to iterate over the array. However, if you need to do any arithmetic with them, you may find yourself thinking again. Also, in Python you wouldn't write iteration loops that way in the first place. You would write things such as for x, y in zip(angle, intensity): plot(x, y) which avoids dealing with indexes altogether. The only time you really need to use indexes in Python is when you want to do arithmetic with them, or take slices, both of which turn out to be less confusing most of the time with 0-based indexing. -- Greg From greg.ewing at canterbury.ac.nz Fri Aug 20 20:27:52 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 12:27:52 +1200 Subject: Python "why" questions In-Reply-To: References: <8crequF9tpU1@mid.individual.net> Message-ID: <8d8kbmFs2qU2@mid.individual.net> Robert Kern wrote: > On 8/16/10 9:29 PM, Roy Smith wrote: > >> In article, >> Lawrence D'Oliveiro wrote: >> >>> In message, Roy Smith wrote: >>> >>>> 5) real intensity[160.0 : 30.0 : 0.01] >>> >>> How many elements in that array? >>> >> c) neither of the above. More specifically, 13,001 (if I counted >> correctly). > > 13000, actually. Floating point is a bitch. Or 12999.9999999 if you're unlucky. Floating point is a *real* bitch! -- Greg From greg.ewing at canterbury.ac.nz Fri Aug 20 20:29:53 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 12:29:53 +1200 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <20100807085428.48664a76.darcy@druid.net> <79C2FAB5-FCAE-4A5E-9483-0B8691FC4772@gmail.com> <7f3c505c-4002-427e-a969-6d735307e0f6@z10g2000yqb.googlegroups.com> <4C5EF1DF.3090007@mrabarnett.plus.com> Message-ID: <8d8kffFs2qU3@mid.individual.net> J.B. Brown wrote: > Then users of my class (mainly my research lab coworkers) could > specify whichever behavior they wanted. > > In terms of providing readable code and removing beginning programmer > confusion, But having some arrays indexed from 0 and others from 1 can be a recipe for confusion in its own right. -- Greg From mailtome200420032002 at gmail.com Fri Aug 20 21:12:16 2010 From: mailtome200420032002 at gmail.com (aj) Date: Fri, 20 Aug 2010 18:12:16 -0700 (PDT) Subject: make install DESTDIR References: Message-ID: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> On Aug 20, 4:39?pm, Thomas Jollans wrote: > On Saturday 21 August 2010, it occurred to aj to exclaim: > > > I am trying to install python with make install DESTDIR=/home/blah > > > ? ? ? ? ? ? ? ? --prefix=/ > > ... > > > creating /lib/python2.6 > > error: could not create '/lib/python2.6': Permission denied > > make: *** [sharedinstall] Error 1 > > Obviously, the flags you specified didn't have the effect you intended. > > ? --prefix=$HOME > > should do the trick. The whole point of DESTDIR is that it should be prepended to all installed paths, but the binaries should not contain any references to it.DESTDIR is commonly used by packagers, for example, to allow installation without superuser privileges. From greg.ewing at canterbury.ac.nz Fri Aug 20 21:22:35 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 13:22:35 +1200 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> Message-ID: <8d8nicFc1dU1@mid.individual.net> Martin Braun wrote: > Another thing worth mentioning (I guess here is a good a place as any > other) is the fact that programming and mathematics are still pretty > different things, despite how much we programmers would like to think > ourselves as some kind of mathematician. Although when it comes to indexing, mathematics and programming have remarkably similar issues. I've seen mathematics texts that made a poor choice of index base and ended up with formulas confusingly littered with plus and minus ones, or where I've had to scratch my head a few times and look back to find out whether a particular index was meant to start from 0 or 1. Also it doesn't help that the sigma notation lends itself more to closed than half-open intervals, which can lead to a Hobson's choice between i-1 in the formulas and n-1 in the summation range. -- Greg From greg.ewing at canterbury.ac.nz Fri Aug 20 21:29:59 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 13:29:59 +1200 Subject: Python "why" questions In-Reply-To: <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> Message-ID: <8d8o08Fe34U1@mid.individual.net> Russ P. wrote: > It all boils down to personal preference, but I just find it strange > that we would not try to make programming as consistent as possible > with notational conventions in the literature. It doesn't matter how much mathematical convention you quote, your assertion that 1-based indexing is better won't convince me, because it flies in the face of my own personal experience. > The zero-based indexing just seemed wrong to me when I first saw it. > I'm used to it by now, but it still doesn't seem quite right to me. > It's almost right -- but it's off by one. I still have a habit of > taking the "1" element when I really want the "0" element. That may be because you haven't fully adopted 0-based indexing into your thinking. You're trying to think in terms of 1-based indexes and convert to 0-based when you code. If you think in 0-based indexes in the first place, many things become simpler. -- Greg From greg.ewing at canterbury.ac.nz Fri Aug 20 21:41:10 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 21 Aug 2010 13:41:10 +1200 Subject: Pop return from stack? In-Reply-To: References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> Message-ID: <8d8ol4FgdpU1@mid.individual.net> bvdp wrote: > The whole problem I was having is that I was trying to tie a small > application (an helper to the main application) to use a bit of the > existing code as a pseudo-library. This is precisely the reason that it's a bad idea to directly terminate the program from somewhere deep inside the code. It makes it hard to re-use the code in another context. It's much better to raise an exception containing an appropriate error message, catch it at the top level of the application and print the message and exit there. Then you can easily re-use any of the code in a context where it's not appropriate to have it exit out from under you. -- Greg From me+list/python at ixokai.io Fri Aug 20 22:13:52 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Fri, 20 Aug 2010 19:13:52 -0700 Subject: Simple Python Sandbox In-Reply-To: <20100816140142.GB22789@localhost> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4C67586C.3020107@ixokai.io> <20100816140142.GB22789@localhost> Message-ID: <4C6F3660.4000901@ixokai.io> On 8/16/10 7:01 AM, Roland Koebler wrote: > On Sat, Aug 14, 2010 at 08:01:00PM -0700, Stephen Hansen wrote: >>> As you can see, black listing isn't the best approach here. >> >> But I have a two pronged strategy: the black list is only half of the >> equation. One, I'm blacklisting all the meta functions out of builtins. > But blacklists are *never* secure. Sorry, but you should fully understand > this before even thinking about more detailed security. And whitelists are never secure, either. There is no such thing as perfectly secure, no. But that is not a goal that I've set for this at all. There's more secure, less secure, more likely to provide a vector for attack, less likely to provide a vector for attack. Every security precaution does end up having a cost: every one weakens the resulting environment or makes something someone wants to do legitimately more hard. Security is always a trade off. The goal is "secure enough" -- and what 'enough' is is going to vary a lot depending on different people's needs. If I were in a situation where I'm executing arbitrary code gathered off of the 'net, that'd be a very different demand and I'd be a lot more keen on finding a perfect sand box (and thus would simply not use Python). That isn't the case here; my relatively untrusted users are uniquely and specifically identifyable and trackable, their interface to the system is logged and actions recorded. There's no money involved in this system, nor possibility that someone could use it to get higher tier access on the parent machine: if someone gets through the sandbox, it'll be a nuisance, hurt some people's enjoyment, harm a community, but really-- it should be able to be fixed pretty rapidly, and then that person utterly locked out. I just want a sandbox that is good enough that it'd be really hard for someone to do that. That's all. Minimize how many times I have to go fix up something. :) > Why are you blacklisting the "known-bad" functions instead of whitelising > the allowed ones?? Because that would annoy some of the other users, who think the status quo isn't really all that bad and that I'm paranoid :) Me, I'm going to go farther on my own installation and kill import entirely, and do a sort of require() which returns a special proxied version of an imported module only if its on a pre-allowed white-list, and even then each individual member of said module will have to be white-listed specifically, too. But in general, I just want a better sandbox that starts things off without getting in anyone's way to do totally legitimate sorts of things. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From ahleniusm at gmail.com Fri Aug 20 23:07:00 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Fri, 20 Aug 2010 20:07:00 -0700 (PDT) Subject: Problem with tarfile module to open *.tar.gz files - unreliable ? References: <87b27da2-5045-4266-90f2-a2ef137f1676@w30g2000yqw.googlegroups.com> <19aa141c-1ae9-47ed-bf4b-9af0b0de0396@u26g2000yqu.googlegroups.com> Message-ID: <5bf10ba0-cb79-46e4-8cef-a8579e905d58@x42g2000yqx.googlegroups.com> On Aug 20, 12:55?pm, Peter Otten <__pete... at web.de> wrote: > m_ahlenius wrote: > > I am using Python 2.6.5. > > > Unfortunately I don't have other versions installed so its hard to > > test with a different version. > > > As for the log compression, its a bit hard to test. ?Right now I may > > process 100+ of these logs per night, and will get maybe 5 which are > > reported as corrupt (typically a bad CRC) and 2 which it reported as a > > bad tar archive. ?This morning I checked each of the 7 reported > > problem files by manually opening them with "tar -xzvof" and they were > > all indeed corrupt. Sign. > > So many corrupted files? I'd say you have to address the problem with your > infrastructure first. > > > Unfortunately due to the nature of our business, I can't post the data > > files online, I hope you can understand. ?But I really appreciate your > > suggestions. > > > The thing that gets me is that it seems to work just fine for most > > files, but then not others. ?Labeling normal files as corrupt hurts us > > as we then skip getting any log data from those files. > > > appreciate all your help. > > I've written an autocorruption script, > > import sys > import subprocess > import tarfile > > def process(source, dest, data): > ? ? for pos in range(len(data)): > ? ? ? ? for bit in range(8): > ? ? ? ? ? ? new_data = data[:pos] + chr(ord(data[pos]) ^ (1< data[pos+1:] > ? ? ? ? ? ? assert len(data) == len(new_data) > ? ? ? ? ? ? out = open(dest, "w") > ? ? ? ? ? ? out.write(new_data) > ? ? ? ? ? ? out.close() > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? t = tarfile.open(dest) > ? ? ? ? ? ? ? ? for f in t: > ? ? ? ? ? ? ? ? ? ? t.extractfile(f) > ? ? ? ? ? ? except Exception, e: > ? ? ? ? ? ? ? ? if 0 == subprocess.call(["tar", "-xf", dest]): > ? ? ? ? ? ? ? ? ? ? return pos, bit > > if __name__ == "__main__": > ? ? source, dest = sys.argv[1:] > ? ? data = open(source).read() > ? ? print process(source, dest, data) > > and I can indeed construct an archive that is rejected by tarfile, but not > by tar. My working hypothesis is that the python library is a bit stricter > in what it accepts... > > Peter Thanks - that's cool. A friend of mine was suggesting that he's seen similar behaviour when he uses Perl on these types of files when the OS (Unix) has not finished writing them. We have an rsync process which sync's our servers for these files and then come down somewhat randomly. So its conceivable I think that this process could be trying to open a file as its being written. I know it sounds like a stretch but my guess is that its a possibility. I could verify that with the timestamps of the errors in my log and the mod time on the original file. 'mark From john.passaniti at gmail.com Fri Aug 20 23:10:19 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Fri, 20 Aug 2010 20:10:19 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: On Aug 20, 6:51?pm, Hugh Aguilar wrote: > You can see an example of lists in my novice package (in the list.4th > file):http://www.forth.org/novice.html > Also in there is symtab, which is a data structure intended to be used > for symbol tables (dictionaries). Almost nobody uses linked lists for > the dictionary anymore (the FIG compilers of the 1970s did, but they > are obsolete). Thanks for pointing this out, Hugh. After reading the code in your novice package and symtab, I am confused: With code of that caliber and the obvious stunning intellect behind it, why hasn't everyone adapted your awesome symtab for symbol tables instead? Any why hasn't there been an effort to translate symtab into other languages so users outside of Forth can also experience the sheer speed and hyper- efficient use of memory and CPU? Let me say I find it refreshing that a great programmer like yourself doesn't bother with stupid fads like testing algorithms against large data sets and measuring performance relative to competitive algorithms. That's all academic nonsense. The only test and measurement anyone needs are the comments at the top of symtab where you state your algorithm is better. You clearly wouldn't have written that if it wasn't true. > Write some programs! Are we not programmers? Amen! All this academic talk is useless. Who cares about things like the big-O notation for program complexity. Can't people just *look* at code and see how complex it is?! And take things like the years of wasted effort computer scientists have put into taking data structures (like hashes and various kinds of trees) and extending them along various problem domains and requirements. Real programmers don't waste their time with learning that junk. What good did any of that ever do anyone?! Thanks Hugh for a refreshing stance on what it means to be a programmer. From ldo at geek-central.gen.new_zealand Fri Aug 20 23:19:22 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 21 Aug 2010 15:19:22 +1200 Subject: 79 chars or more? References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> Message-ID: In message , Jean-Michel Pichavant wrote: > Saying that, if one intend to distribute its code, he should stick to 80 > chars per line. Why? From rowlett at pcnetinc.com Sat Aug 21 00:07:50 2010 From: rowlett at pcnetinc.com (Richard Owlett) Date: Fri, 20 Aug 2010 23:07:50 -0500 Subject: OI VEY, I AGREE -was once [Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?] In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: John Passaniti wrote: > On Aug 20, 6:51 pm, Hugh Aguilar wrote: >> You can see an example of lists in my novice package (in the list.4th >> file):http://www.forth.org/novice.html >> Also in there is symtab, which is a data structure intended to be used >> for symbol tables (dictionaries). Almost nobody uses linked lists for >> the dictionary anymore (the FIG compilers of the 1970s did, but they >> are obsolete). > > Thanks for pointing this out, Hugh. After reading the code in your > novice package and symtab, I am confused: With code of that caliber > and the obvious stunning intellect behind it, why hasn't everyone > adapted your awesome symtab for symbol tables instead? Any why hasn't > there been an effort to translate symtab into other languages so users > outside of Forth can also experience the sheer speed and hyper- > efficient use of memory and CPU? Let me say I find it refreshing that > a great programmer like yourself doesn't bother with stupid fads like > testing algorithms against large data sets and measuring performance > relative to competitive algorithms. That's all academic nonsense. > The only test and measurement anyone needs are the comments at the top > of symtab where you state your algorithm is better. You clearly > wouldn't have written that if it wasn't true. > >> Write some programs! Are we not programmers? > > Amen! All this academic talk is useless. Who cares about things like > the big-O notation for program complexity. Can't people just *look* > at code and see how complex it is?! And take things like the years of > wasted effort computer scientists have put into taking data structures > (like hashes and various kinds of trees) and extending them along > various problem domains and requirements. Real programmers don't > waste their time with learning that junk. What good did any of that > ever do anyone?! > > Thanks Hugh for a refreshing stance on what it means to be a > programmer. > Never thought I I'd agree wholeheartedly with very verbose John. Hugh, you are complete idiot! (and other less complementary ...) From stndshp at gmail.com Sat Aug 21 01:36:18 2010 From: stndshp at gmail.com (Standish P) Date: Fri, 20 Aug 2010 22:36:18 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> Message-ID: <00b9244e-7339-45b0-b38b-9c9854286345@l6g2000yqb.googlegroups.com> On Aug 18, 8:05?pm, Elizabeth D Rather wrote: > On 8/18/10 2:23 PM, Standish P wrote: > > > On Aug 17, 6:38 pm, John Passaniti ?wrote: > > >> You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > >> lists are constructed with pair of pointers called a "cons cell". > >> That is the most primitive component that makes up a list. ?Forth has > >> no such thing; in Forth, the dictionary (which is traditionally, but > >> not necessarily a list) is a data structure that links to the previous > >> word with a pointer. > > > Would you show me a picture, ascii art or whatever for Forth ? I know > > what lisp lists look like so I dont need that for comparison. Forth > > must have a convention and a standard or preferred practice for its > > dicts. However, let me tell you that in postscript the dictionaries > > can be nested inside other dictionaries and any such hiearchical > > structure is a nested associative list, which is what linked list, > > nested dictionaries, nested tables are. > > You indicated that you have a copy of Forth Application Techniques. > Sections 8.1 and 8.2 cover this topic, with some drawings. Can someone send me a scan copy of sec 8.1 to 8.2 within the exemption in the copyright law for my personal study and evaluation of the book only. I have only looked at the book cover on forth site and its table of contents on amazon. why elase would I ask where it is if I had a copy and would go directly to index assuming it has a good indexing. Alternative, a link to an open source of explanation would be requested. From stndshp at gmail.com Sat Aug 21 01:42:18 2010 From: stndshp at gmail.com (Standish P) Date: Fri, 20 Aug 2010 22:42:18 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: On Aug 20, 3:51?pm, Hugh Aguilar wrote: > On Aug 18, 6:23?pm, Standish P wrote: > > > > > > > On Aug 17, 6:38?pm, John Passaniti wrote: > > > > You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > > > lists are constructed with pair of pointers called a "cons cell". > > > That is the most primitive component that makes up a list. ?Forth has > > > no such thing; in Forth, the dictionary (which is traditionally, but > > > not necessarily a list) is a data structure that links to the previous > > > word with a pointer. ? > > > Would you show me a picture, ascii art or whatever for Forth ? I know > > what lisp lists look like so I dont need that for comparison. Forth > > must have a convention and a standard or preferred practice for its > > dicts. However, let me tell you that in postscript the dictionaries > > can be nested inside other dictionaries and any such hiearchical > > structure is a nested associative list, which is what linked list, > > nested dictionaries, nested tables are. > > You can see an example of lists in my novice package (in the list.4th > file):http://www.forth.org/novice.html > Also in there is symtab, which is a data structure intended to be used > for symbol tables (dictionaries). Almost nobody uses linked lists for > the dictionary anymore (the FIG compilers of the 1970s did, but they > are obsolete). > > I must say, I've read through this entire thread and I didn't > understand *anything* that *anybody* was saying (especially the OP). You didnt understand anything because no one explained anything coherently. Admittedly, I am asking a question that would be thought provoking to those who claim to be "experts" but these experts are actually very stingy and mean business people, most certainly worse than Bill Gates, only it did not occur to them his ideas and at the right time. > I really recommend that people spend a lot more time writing code, and a > lot less time with all of this pseudo-intellectual nonsense. You have to have a concept to write code. > This > whole thread (and most of what I see on C.L.F. these days) reminds me > of the "dialectic method" of the early Middle Ages --- a lot of talk > and no substance. > > Write some programs! Are we not programmers?- Hide quoted text - > > - Show quoted text - From mail at timgolden.me.uk Sat Aug 21 02:10:53 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 21 Aug 2010 07:10:53 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: <4C6F6DED.6080202@timgolden.me.uk> On 20/08/2010 11:54 PM, vsoler wrote: > I'am testing your library. I am mainly interested in knowing the > access attributes of directories in the local(C:\) or shared unit(W:\) > of my system. > > Using your script with 'c:\\' I get an error message saying... 'file > exists but it is a directory' and I cannot go any further. > > Of course, the problem is that I am using "fs.file" when I should be > using something different. Either use fs.dir (if you know it's a directory) or fs.entry (if it could be a file or a directory; the code will dispatch to the right one). If you only want the directories immediately some directory, you could do this: from winsys import fs, security root = fs.file (sys.executable).path # or fs.dir ("w:/") etc. for d in root.dirs (ignore_access_errors=True): print (d, "=>", d.security ()) # or whatever If you want to walk the tree of directories looking at permissions, then: import os, sys from winsys import fs root = fs.file (sys.executable).path for dirpath, _, _ in root.walk (): print (dirpath, "=>", dirpath.security ()) > Reading the doc I have found that I should be using os.walk(...), > which works, but then I cannot use fs.file In fact, even if you did for some reason use os.walk, you can easily wrap the returned filenames using fs.entry: import os, sys from winsys import fs root = os.path.dirname (sys.executable) for dirpath, filenames, dirnames in os.walk (root): print (dirpath, "=>", fs.entry (dirpath).security ()) TKG From nagle at animats.com Sat Aug 21 02:37:12 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 23:37:12 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: <8739u9ninh.fsf@castleamber.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> Message-ID: <4c6f7413$0$1631$742ec2ed@news.sonic.net> On 8/20/2010 1:17 PM, John Bokma wrote: > John Nagle writes: > >> Python does not do tail recursion, so using recursion >> where iteration could do the job is generally a bad idea. Scheme, on >> the other hand, always does tail recursion where possible. > > I think you mean tail recursion optimization / elimination. > Python does tail recursion: Not very well. def cnt(n) : if n > 0 : cnt(n-1) This will work for up to cnt(998), but at cnt(999), CPython reports "RuntimeError: maximum recursion depth exceeded." Yes, you can increase the recursion depth, but that case shouldn't be compiled to recursion at all. John Nagle From nagle at animats.com Sat Aug 21 02:40:53 2010 From: nagle at animats.com (John Nagle) Date: Fri, 20 Aug 2010 23:40:53 -0700 Subject: scope of variable In-Reply-To: References: <1282327776.2942.3.camel@pex-desktop> Message-ID: <4c6f74ef$0$1631$742ec2ed@news.sonic.net> On 8/20/2010 12:56 PM, M B wrote: > fre 2010-08-20 klockan 13:19 -0600 skrev Burton Samograd: >> M B writes: >> >>> Hi, >>>>>> dept=0 >>>>>> def mud(): >>> print dept >>> >>> >>>>>> mud() >>> 0 >>>>>> def mud(): >>> dept+=1 >>> print dept >> >> You should add a global statement or else python thinks a variable used >> is a local: >> >>>>> def mud(): >> global dept >> dept+=1 >> print dept >> >> -- >> Burton Samograd >> > Ok. Thanks for the answers. :) I was a bit puzzled of > the fact that I could read but not assign to a global variable. If you assign before a read, you create a local variable. If you read only, you get a global access. If you do a read before an assignment, you get an error message. John Nagle From wuwei23 at gmail.com Sat Aug 21 02:40:59 2010 From: wuwei23 at gmail.com (alex23) Date: Fri, 20 Aug 2010 23:40:59 -0700 (PDT) Subject: expression in an if statement References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> <4c6e1a93$0$1658$742ec2ed@news.sonic.net> Message-ID: <95be46b5-cfa8-49df-9b77-28e62f766168@h40g2000pro.googlegroups.com> John Nagle wrote: > I was talking to the Facebook guys doing the compiler for PHP, and they > said that it was a huge win for them that PHP doesn't allow dynamically > replacing a function. I'm not sure if I call all that effort for a 50% speed increase a win. PyPy is seeing speed increases of up to 15 times that of CPython 2.6.2 without reducing the flexibility of the language at all. From erather at forth.com Sat Aug 21 03:39:58 2010 From: erather at forth.com (Elizabeth D Rather) Date: Fri, 20 Aug 2010 21:39:58 -1000 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: On 8/20/10 7:42 PM, Standish P wrote: ... >Admittedly, I am asking a question that would be thought > provoking to those who claim to be "experts" but these experts are > actually very stingy and mean business people, most certainly worse > than Bill Gates, only it did not occur to them his ideas and at the > right time. The problem as I see it is that you're asking complex questions in a forum that, at best, supports simple answers. The information you're looking for exists, on the net, free. There are free pdfs of manuals on Forth available with program downloads from FORTH, Inc., MPE, Gforth, and other sources, as well as some inexpensive books. But you have to be willing to make the investment to download and read them, because the answers to your questions are not simple one-liners that you can get from newsgroups, and the folks in newsgroups are not prepared to host computer science seminars -- many of us are working programmers, engineers, and project managers who have limited time to spend here. If you're willing to invest your time enough to investigate some of these sources, and still have questions, we'll be happy to try to help. Cheers, Elizabeth -- ================================================== Elizabeth D. Rather (US & Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com "Forth-based products and Services for real-time applications since 1973." ================================================== From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 04:30:53 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 08:30:53 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> Message-ID: <4c6f8ebc$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 09:47:30 +0200, News123 wrote: > On 08/20/2010 02:26 AM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be >> tricky? > Is this a sincere surprise or are you just boasting? Why would it be boasting? I didn't say that at the age of seven I independently invented a COBOL compiler that supported recursion. *That* would be boasting. (It would also be a lie -- at the age of seven, I don't think I even knew about the existence of computers.) Boasting about understanding the idea of recursion is kind of like boasting about the putting my hands in the correct glove nine times out of ten. [...] > The fact, that you didn't have the issue doens't mean it's easy for > others. Apparently not. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 04:31:25 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 08:31:25 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e9de9$0$23142$426a74cc@news.free.fr> Message-ID: <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: > Steven D'Aprano a ?crit : >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> >> Really? Do people actually find the *concept* of recursion to be >> tricky? >> >> > I onced worked in a shop (Win32 desktop / accouting applications mainly) > where I was the only guy that could actually understand recursion. FWIW, > I also was the only guy around that understood "hairy" (lol) concepts > like callback functions, FSM, FSM? Flying Spaghetti Monster? > polymorphism, hashtables, linked lists, > ADTs, algorithm complexity etc... Was there anything they *did* understand, or did they just bang on the keyboard at random until the code compiled? *wink* > Needless to say, I didn't last long !-) And rightly so :) -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 04:33:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 08:33:26 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> Message-ID: <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: > Most programmers probably never use vectors and matrices, so they don't > care about the inconsistency with standard mathematical notation. Perhaps you should ask the numpy programmers what they think about that. Vectors and matrices are just arrays, and the suggestion that most programmers don't use arrays (or array-like objects like lists) is ludicrous. > And yes, I understand that zero-based indexing can be slightly more > efficient. That's why I think it's appropriate for low-level languages > such as C. However, I think one-based indexing is more appropriate for > high-level languages. Only if your aim is to reduce the learning curve for newbies and non- programmers, at the expense of making it easier for them to produce buggy code. That's a defensible choice. I'm a great fan of Apple's Hypercard from the late 80s and early 90s, and it used one-based indexing, as well as English-like syntax like: put char 2 of the third word of it into the last field You don't need to know a thing about the language to guess what that does, and you'd probably be right. It would have been inappropriate for Hypercard to use zero-based indexing, because it was aimed at giving non- programmers a shallow learning curve and syntax that looks like natural language. There is room in the world for programming languages aimed at non- programmers (although HC is an extreme case), but not all languages should prefer the intuition of non-programmers over other values. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 04:54:19 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 08:54:19 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c6f943a$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 09:21:25 +0200, Kai Borgolte wrote: > Sorry about my previous posting with wrong references, this one should > be better. > > Steven D'Aprano wrote: > >>A simple example: Using zero-based indexing, suppose you want to indent >>the string "spam" so it starts at column 4. How many spaces to you >>prepend? As AK pointed out, I totally messed up the example by talking about column 4 then giving an example of column 5. Sigh. 0123456789 spam > No, you won't want to indent a string so it starts at column 4. You > simply want to indent the string by four spaces. Like in PEP 8: > > /Use 4 spaces per indentation level./ I don't see what PEP 8 has to do with anything here. Code is not the only thing that needs indenting, and 4 was just a mere example chosen at random. I might be pretty-printing a table of numbers, I might be drawing a text-based maze, I could be writing a function to left-fill strings with some arbitrary character, e.g left-fill with asterisks: 01234567 ****spam Besides, PEP 8 is merely a coding standard, not a law of nature. Some people might choose other coding standards, such as two-space indents, eight-spaces, or even (gasp! horror!) tabs. > And of course your text editor will number the columns beginning with > one, so the string starts at column 5. Ah, text editors. I'm glad you mention that... My text editor of choice is kwrite, which suits me fine, but it has one obnoxious, painful design choice. It indexes characters from one, so when I have the cursor at the left-hand margin and haven't typed anything, it says I'm at position 1. Consequently, if I want to know how many characters are in a line (and you'd be amazed how frequently I need to do this!), I can't just glance at the cursor position, I have to remember to subtract one from whatever the cursor position says. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 05:03:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2010 09:03:42 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4c6f966e$0$28653$c3e8da3@news.astraweb.com> On Fri, 20 Aug 2010 16:42:26 -0700, Baba wrote: > For future readers of this post who want to learn to programm (just like > myself) let me re-state the basics i have learned now: I would disagree in part with nearly all of these. > - a procedure is said to be recursive when it contains a statement that > calls itself Not necessarily. A function can be indirectly recursive -- function f can call function g which calls function h which calls function f. This is still recursion, even though f doesn't contain a statement which calls itself. > - there must be a condition where the recursion has to stop otherwise > the routine will continue to call itself infinitely. > This is called the Base Case I agree with this, although I've never heard the name "Base Case" before. > - every time the procedure calls itself the memory gradually fills up > with the copies until the whole thing winds down again > as the "return" statements start being executed. That's so vague as to be almost meaningless. I think what you are talking about is one specific part of memory, the calling stack, which fills up with arguments needed to call the function, and then empties as the recursive calls return. However, there is an import class of recursive calls where a sufficiently smart compiler can avoid this cost, essentially turning recursion into iteration automatically, speeding up recursion drastically. > - the above point means that a recursive approach is expensive on > resources so in the practical world it should be avoided. True-ish for the first part of the sentence, absolutely false for the second. Recursion can be slower and more memory consuming than iteration under some circumstances, although this depends on the specific way that recursion is used, not the mere fact that recursion happens. A single recursive call is no more expensive than any other function call. Also, as mentioned, some compilers can optimize tail-call recursion to make it as fast and efficient as iteration. (However, Python doesn't do this.) In the real world, avoiding recursion also has costs. Your function may be bigger, more complicated, need more memory, possibly manage its own stack. None of these things happen for free. Whether a specific recursive function is better than a specific iterative function depends on the details of what that function does and what arguments you call it with. If your recursive function is likely to use only a few recursive calls, there is no need to complicate matters by re-writing it iteratively. There's no need to avoid recursion just because it is recursive. Also, recursion together with memoisation can be extremely fast and efficient, at some cost of memory. For example, the typical recursive version of factorisation: def fact(n): if n <= 1: return 1 return n*fact(n-1) can be made much, much faster by giving it a simple cache: def fact(n): try: cache = fact.cache except AttributeError: cache = fact.cache = {} try: return cache[n] except KeyError: pass if n <= 1: result = 1 else: result = n*fact(n-1) # Don't let the cache grow indefinitely large. if len(cache) >= 100: cache.popitem() # Discard some arbitrary item. cache[n] = result return result -- Steven From ldo at geek-central.gen.new_zealand Sat Aug 21 05:27:56 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 21 Aug 2010 21:27:56 +1200 Subject: String substitution VS proper mysql escaping References: <4C6BA2C4.4000309@gmail.com> Message-ID: In message , ????? wrote: > I would expect that: > > ("nikos") is a single element tuple. Then how would you do a simple parenthesized expression? From ldo at geek-central.gen.new_zealand Sat Aug 21 05:30:42 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 21 Aug 2010 21:30:42 +1200 Subject: Python Developer - HFT Trading firm - Chicago, IL References: Message-ID: In message , Rich Moss wrote: > Python developer needed for math/trading applications and research at > leading HFT firm. Wasn?t HFT an exacerbating factor in just about every major stockmarket downturn since, oh, 1987? From ldo at geek-central.gen.new_zealand Sat Aug 21 05:32:04 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 21 Aug 2010 21:32:04 +1200 Subject: Open a command pipe for reading References: Message-ID: In message , Rodrick Brown wrote: > Sent from my iPhone 4. Glad to hear you achieved it without losing the signal. :) From raoulbia at gmail.com Sat Aug 21 05:35:18 2010 From: raoulbia at gmail.com (Baba) Date: Sat, 21 Aug 2010 02:35:18 -0700 (PDT) Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> Message-ID: <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> On Aug 21, 7:37?am, John Nagle wrote: > On 8/20/2010 1:17 PM, John Bokma wrote: > > > I think you mean tail recursion optimization / elimination. > > Python does tail recursion: > > ? ? Not very well. > > ? ? ?def cnt(n) : > ? ? ? ? ?if n > 0 : > ? ? ? ? ? ? ?cnt(n-1) > Hi John I'm intrigued by this example. Is there something missing in the code? When i run it i get: I suppose it is meant to print a sequence of numbers from n down to zero? re tail recursion, on wiki i found: "With tail recursion, there is no need to remember the place we are calling from?instead, we can leave the stack alone, and the newly called function will return its result directly to the original caller. Converting a call to a branch or jump in such a case is called a tail call optimization. " not sure i understand that... is this bit of theory applicable to your cnt function above? tnx Baba From dak at gnu.org Sat Aug 21 06:36:43 2010 From: dak at gnu.org (David Kastrup) Date: Sat, 21 Aug 2010 12:36:43 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: <87aaogtfpg.fsf@lola.goethe.zz> John Passaniti writes: > Amen! All this academic talk is useless. Who cares about things like > the big-O notation for program complexity. Can't people just *look* > at code and see how complex it is?! And take things like the years of > wasted effort computer scientists have put into taking data structures > (like hashes and various kinds of trees) and extending them along > various problem domains and requirements. Real programmers don't > waste their time with learning that junk. What good did any of that > ever do anyone?! It is my experience that in particular graduated (and in particular Phd) computer scientists don't waste their time _applying_ that junk. They have learnt to analyze it, they could tell you how bad their own algorithms are (if they actually bothered applying their knowledge), but it does not occur to them to replace them by better ones. Or even factor their solutions in a way that the algorithms and data structures are actually isolated. I think there must be some programmer gene. It is not enough to be able to recognize O(n^k) or worse (though it helps having a more exact rather than a fuzzy notion of them _if_ you have that gene). You have to fear it. It has to hurt. You need to feel compassion with the CPU. It's not enough to sit there in your easychair, occasionally sucking on your pipeline and listen to its story about a hard realtime youth and its strained connection to its motherboard. When it stops, you have to see its benchmarks and feel their pain in your own backplane. -- David Kastrup From python.list at tim.thechases.com Sat Aug 21 06:54:02 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 21 Aug 2010 05:54:02 -0500 Subject: Iterative vs. Recursive coding In-Reply-To: <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> Message-ID: <4C6FB04A.7090102@tim.thechases.com> On 08/21/10 04:35, Baba wrote: > On Aug 21, 7:37 am, John Nagle wrote: >> On 8/20/2010 1:17 PM, John Bokma wrote: >>> I think you mean tail recursion optimization / elimination. >>> Python does tail recursion: >> >> Not very well. >> >> def cnt(n) : >> if n> 0 : >> cnt(n-1) > > I'm intrigued by this example. Is there something missing in the code? > When i run it i get: > I suppose it is meant to print a sequence of numbers from n down to > zero? Sounds like you merely executed: >>> cnt which just asks what "cnt" is (in this case, it is as Python reports: a function named "cnt" at some given address), instead of actually *running* the function: >>> cnt(42) (function-calling is performed by the parens). > re tail recursion, on wiki i found: > "With tail recursion, there is no need to remember the place we are > calling from?instead, we can leave the stack alone, and the newly > called function will return its result directly to the original > caller. Converting a call to a branch or jump in such a case is called > a tail call optimization. " > > not sure i understand that... > is this bit of theory applicable to your cnt function above? The recursive call (calling cnt(...) again) is the last instruction in the function before it would otherwise exit. A tail-recursion-aware compiler/interpreter would optimize that away. Instead of keeping track of a new stack-frame for each call (growing in stack-memory usage with each call), it would recognize that it could just reuse the current/top stack-frame to prevent stack blowouts. JohnN's observation was that Python doesn't recognize tail-recursion, and thus blows the top of the default stack-size at 999 recursive calls (a number adjustable with parameters to Python). If Python recognized tail-recursion and optimized for it, you could use any number you had the time to wait for. -tkc From python.list at tim.thechases.com Sat Aug 21 06:59:59 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 21 Aug 2010 05:59:59 -0500 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4C6FB1AF.2050709@tim.thechases.com> On 08/21/10 03:31, Steven D'Aprano wrote: > On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: >> I also was the only guy around that understood "hairy" (lol) concepts >> like callback functions, FSM, > > FSM? Flying Spaghetti Monster? I'm guessing "Finite State Machines". But in a way, "Flying Spaghetti Monster" is also a bit "hairy" and hard to understand... > Was there anything they *did* understand, or did they just bang on the > keyboard at random until the code compiled? *wink* Accompanied by coping and pasting example code from Google results, random twiddling of the code or posting questions on newsgroups until the code compiles...a surprisingly popular technique. :-( -tkc From thomas at jollybox.de Sat Aug 21 07:02:55 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sat, 21 Aug 2010 13:02:55 +0200 Subject: make install DESTDIR In-Reply-To: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> Message-ID: <201008211302.56158.thomas@jollybox.de> On Saturday 21 August 2010, it occurred to aj to exclaim: > On Aug 20, 4:39 pm, Thomas Jollans wrote: > > On Saturday 21 August 2010, it occurred to aj to exclaim: > > > I am trying to install python with make install DESTDIR=/home/blah > > > > > > --prefix=/ > > > > ... > > > > > creating /lib/python2.6 > > > error: could not create '/lib/python2.6': Permission denied > > > make: *** [sharedinstall] Error 1 > > > > Obviously, the flags you specified didn't have the effect you intended. > > > > --prefix=$HOME > > > > should do the trick. > > The whole point of DESTDIR is that it should be prepended to all > installed paths, but the binaries should not contain any references to > it.DESTDIR is commonly used by packagers, for example, to allow > installation without superuser privileges. Sorry, that feature slipped my mind. So, are you running $ make install DESTDIR=/home/foo/bar or are you trying to directly run setup.py? I just tried and use make worked for me. (though I was in a Python 3.2 dev source tree, not 2.6 -- maybe this was a bug that has been fixed?) From davea at dejaviewphoto.com Sat Aug 21 07:07:16 2010 From: davea at dejaviewphoto.com (Dave Angel) Date: Sat, 21 Aug 2010 07:07:16 -0400 Subject: Iterative vs. Recursive coding In-Reply-To: <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <2790452c-6fec-4087-af0d-0a373f93272e@h19g2000yqb.googlegroups.com> Message-ID: <4C6FB364.6020008@dejaviewphoto.com> Baba wrote: > On Aug 21, 7:37 am, John Nagle wrote: > >> On 8/20/2010 1:17 PM, John Bokma wrote: >> >>> I think you mean tail recursion optimization / elimination. >>> Python does tail recursion: >>> >> Not very well. >> >> def cnt(n) : >> if n > 0 : >> cnt(n-1) >> > > Hi John > > I'm intrigued by this example. Is there something missing in the code? > When i run it i get: > I suppose it is meant to print a sequence of numbers from n down to > zero? > > re tail recursion, on wiki i found: > "With tail recursion, there is no need to remember the place we are > calling from?instead, we can leave the stack alone, and the newly > called function will return its result directly to the original > caller. Converting a call to a branch or jump in such a case is called > a tail call optimization. " > > not sure i understand that... > is this bit of theory applicable to your cnt function above? > > tnx > Baba > > Juding from your output, you didn't call the function, you just named it. To call it you needed to use parentheses, type something like cnt(5) The function is a do-nothing function. It makes no calculations, returns no result. Just illustrating recursion in the simplest way. Tail call optimization would work fine on that function. CPython doesn't do such optimization, however. If it did, it would convert the call at the end to a decrement and a jump. The net effect would be something like: def cnt(n) : while True: if n > 0: n = n-1 continue break Clearly that could be optimized as well. Maybe a great optimizer could turn it into: def cnt(n): pass DaveA From blog at rivadpm.com Sat Aug 21 07:29:59 2010 From: blog at rivadpm.com (Alex McDonald) Date: Sat, 21 Aug 2010 04:29:59 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: On 21 Aug, 06:42, Standish P wrote: > On Aug 20, 3:51?pm, Hugh Aguilar wrote: > > > > > On Aug 18, 6:23?pm, Standish P wrote: > > > > On Aug 17, 6:38?pm, John Passaniti wrote: > > > > > You asked if Forth "borrowed" lists from Lisp. ?It did not. ?In Lisp, > > > > lists are constructed with pair of pointers called a "cons cell". > > > > That is the most primitive component that makes up a list. ?Forth has > > > > no such thing; in Forth, the dictionary (which is traditionally, but > > > > not necessarily a list) is a data structure that links to the previous > > > > word with a pointer. ? > > > > Would you show me a picture, ascii art or whatever for Forth ? I know > > > what lisp lists look like so I dont need that for comparison. Forth > > > must have a convention and a standard or preferred practice for its > > > dicts. However, let me tell you that in postscript the dictionaries > > > can be nested inside other dictionaries and any such hiearchical > > > structure is a nested associative list, which is what linked list, > > > nested dictionaries, nested tables are. > > > You can see an example of lists in my novice package (in the list.4th > > file):http://www.forth.org/novice.html > > Also in there is symtab, which is a data structure intended to be used > > for symbol tables (dictionaries). Almost nobody uses linked lists for > > the dictionary anymore (the FIG compilers of the 1970s did, but they > > are obsolete). > > > I must say, I've read through this entire thread and I didn't > > understand *anything* that *anybody* was saying (especially the OP). > > You didnt understand anything because no one explained anything > coherently. It indicates that you're asking a question that *you don't understand*. I'm continually amazed that people come to Usenet, wikis, websites and other fora and ask questions that even the most basic of research (and a bit of care with terminology aka "using the right words") would show to be confused. A quick scan of the available literature on garbage collection and stacks, starting with the fundamentals, would surely show you what you need to know. > Admittedly, I am asking a question that would be thought > provoking to those who claim to be "experts" but these experts are > actually very stingy and mean business people, most certainly worse > than Bill Gates, only it did not occur to them his ideas and at the > right time. > What surprises may is that anyone bothered to answer, as your question was neither "thought provoking" nor in need of attention from an expert. Their generosity in the face of so much stupidity stands out as remarkable. From martin at v.loewis.de Sat Aug 21 07:43:48 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 21 Aug 2010 13:43:48 +0200 Subject: make install DESTDIR In-Reply-To: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> Message-ID: <4C6FBBF4.40704@v.loewis.de> > The whole point of DESTDIR is that it should be prepended to all > installed paths, but the binaries should not contain any references to > it.DESTDIR is commonly used by packagers, for example, to allow > installation without superuser privileges. So what is the point of your messages? Do you want to report a problem? Are you asking for help? Do you want to vent frustration? Regards, Martin From vicente.soler at gmail.com Sat Aug 21 07:51:57 2010 From: vicente.soler at gmail.com (vsoler) Date: Sat, 21 Aug 2010 04:51:57 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: On Aug 21, 8:10?am, Tim Golden wrote: > On 20/08/2010 11:54 PM, vsoler wrote: > > > I'am testing your library. I am mainly interested in knowing the > > access attributes of directories in the local(C:\) or shared unit(W:\) > > of my system. > > > Using your script with 'c:\\' I get an error message saying... 'file > > exists but it is a directory' and I cannot go any further. > > > Of course, the problem is that I am using "fs.file" when I should be > > using something different. > > Either use fs.dir (if you know it's a directory) or fs.entry (if it > could be a file or a directory; the code will dispatch to the right one). > > If you only want the directories immediately some directory, > you could do this: > > > from winsys import fs, security > > root = fs.file (sys.executable).path ?# or fs.dir ("w:/") etc. > for d in root.dirs (ignore_access_errors=True): > ? ?print (d, "=>", d.security ()) # or whatever > > > > If you want to walk the tree of directories looking at permissions, then: > > > import os, sys > from winsys import fs > > root = fs.file (sys.executable).path > for dirpath, _, _ in root.walk (): > ? ?print (dirpath, "=>", dirpath.security ()) > > > > > Reading the doc I have found that I should be using os.walk(...), > > which works, but then I cannot use fs.file > > In fact, even if you did for some reason use os.walk, you can > easily wrap the returned filenames using fs.entry: > > > import os, sys > from winsys import fs > > root = os.path.dirname (sys.executable) > for dirpath, filenames, dirnames in os.walk (root): > ? ?print (dirpath, "=>", fs.entry (dirpath).security ()) > > > > TKG Tim, I appreciate the time and effort that you are putting in this post. Personally, I am impressed of the power of python, your winsys library, and overall, how easy it is to customize the scripting of one's day to day needs. I have started testing your first script from winsys import fs, security root = fs.dir ("c:/") for d in root.dirs (ignore_access_errors=True): print (d, "=>", d.security ()) Howwvwer, I am getting an error: >>> ================================ RESTART ================================ >>> c:\$recycle.bin\ => O:BAD:PAI(A;;FA;;;BA)(A;OICIIO;GA;;;BA)(A;;FA;;;SY) (A;OICIIO;GA;;;SY)(A;;0x1201ad;;;BU) c:\aeat\ => O:BAD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) (A;OICIIOID;SDGXGWGR;;;AU) c:\archivos de programa\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) (A;;FA;;;SY)(A;;FA;;;BA) c:\documents and settings\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) (A;;FA;;;SY)(A;;FA;;;BA) c:\hp\ => O:SYD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) (A;OICIIOID;SDGXGWGR;;;AU) Traceback (most recent call last): File "C:/Users/Vicente/Documents/VS/Python/test6.py", line 5, in print(d, "=>",d.security()) File "C:\Python31\lib\site-packages\winsys\fs.py", line 1044, in security return security.security (self, options=options) File "C:\Python31\lib\site-packages\winsys\security.py", line 585, in security return Security.from_object (str (obj), obj_type, options=options) File "C:\Python31\lib\site-packages\winsys\security.py", line 475, in from_object sd = wrapped (win32security.GetNamedSecurityInfo, obj, object_type, options) File "C:\Python31\lib\site-packages\winsys\exc.py", line 55, in _wrapped raise exception (errno, errctx, errmsg) winsys.security.x_security: (5, 'GetNamedSecurityInfo', 'Acceso denegado.') >>> I am using a system in the Spanish language. As you can see in the last line, 'Acceso denegado' or 'Access denied' even though the flag "ignore_access_errors" is set to True. I am using python 3.1 on Windows 7. What do you think is the origin of this problem? Vicente Soler From vicente.soler at gmail.com Sat Aug 21 08:01:33 2010 From: vicente.soler at gmail.com (vsoler) Date: Sat, 21 Aug 2010 05:01:33 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: On Aug 21, 8:10?am, Tim Golden wrote: > On 20/08/2010 11:54 PM, vsoler wrote: > > > I'am testing your library. I am mainly interested in knowing the > > access attributes of directories in the local(C:\) or shared unit(W:\) > > of my system. > > > Using your script with 'c:\\' I get an error message saying... 'file > > exists but it is a directory' and I cannot go any further. > > > Of course, the problem is that I am using "fs.file" when I should be > > using something different. > > Either use fs.dir (if you know it's a directory) or fs.entry (if it > could be a file or a directory; the code will dispatch to the right one). > > If you only want the directories immediately some directory, > you could do this: > > > from winsys import fs, security > > root = fs.file (sys.executable).path ?# or fs.dir ("w:/") etc. > for d in root.dirs (ignore_access_errors=True): > ? ?print (d, "=>", d.security ()) # or whatever > > > > If you want to walk the tree of directories looking at permissions, then: > > > import os, sys > from winsys import fs > > root = fs.file (sys.executable).path > for dirpath, _, _ in root.walk (): > ? ?print (dirpath, "=>", dirpath.security ()) > > > > > Reading the doc I have found that I should be using os.walk(...), > > which works, but then I cannot use fs.file > > In fact, even if you did for some reason use os.walk, you can > easily wrap the returned filenames using fs.entry: > > > import os, sys > from winsys import fs > > root = os.path.dirname (sys.executable) > for dirpath, filenames, dirnames in os.walk (root): > ? ?print (dirpath, "=>", fs.entry (dirpath).security ()) > > > > TKG Tim, I appreciate the time and effort that you are putting in this post. Personally, I am impressed of the power of python, your winsys library, and overall, how easy it is to customize the scripting of one's day to day needs. I have started testing your first script from winsys import fs, security root = fs.dir ("c:/") for d in root.dirs (ignore_access_errors=True): print (d, "=>", d.security ()) Howwvwer, I am getting an error: >>> ================================ RESTART ================================ >>> c:\$recycle.bin\ => O:BAD:PAI(A;;FA;;;BA)(A;OICIIO;GA;;;BA)(A;;FA;;;SY) (A;OICIIO;GA;;;SY)(A;;0x1201ad;;;BU) c:\aeat\ => O:BAD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) (A;OICIIOID;SDGXGWGR;;;AU) c:\archivos de programa\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) (A;;FA;;;SY)(A;;FA;;;BA) c:\documents and settings\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) (A;;FA;;;SY)(A;;FA;;;BA) c:\hp\ => O:SYD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) (A;OICIIOID;SDGXGWGR;;;AU) Traceback (most recent call last): File "C:/Users/Vicente/Documents/VS/Python/test6.py", line 5, in print(d, "=>",d.security()) File "C:\Python31\lib\site-packages\winsys\fs.py", line 1044, in security return security.security (self, options=options) File "C:\Python31\lib\site-packages\winsys\security.py", line 585, in security return Security.from_object (str (obj), obj_type, options=options) File "C:\Python31\lib\site-packages\winsys\security.py", line 475, in from_object sd = wrapped (win32security.GetNamedSecurityInfo, obj, object_type, options) File "C:\Python31\lib\site-packages\winsys\exc.py", line 55, in _wrapped raise exception (errno, errctx, errmsg) winsys.security.x_security: (5, 'GetNamedSecurityInfo', 'Acceso denegado.') >>> I am using a system in the Spanish language. As you can see in the last line, 'Acceso denegado' or 'Access denied' even though the flag "ignore_access_errors" is set to True. I am using python 3.1 on Windows 7. What do you think is the origin of this problem? Vicente Soler From hobson42 at gmaiil.com Sat Aug 21 08:03:56 2010 From: hobson42 at gmaiil.com (Ian) Date: Sat, 21 Aug 2010 13:03:56 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: <8762z4swlk.fsf@benfinney.id.au> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <8762z4swlk.fsf@benfinney.id.au> Message-ID: <4C6FC0AC.1030208@gmaiil.com> On 21/08/2010 00:17, Ben Finney wrote: > Steven D'Aprano writes: > >> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >> >>> Recursion can be quite a trick to get your mind round at first >> Really? Do people actually find the *concept* of recursion to be >> tricky? > Evidently so. It's folk wisdom that some adults find recursion an easy > concept, and those people will find programming significantly easier; > and the majority of people have a great deal of difficulty with > recursion and so find programming correspondingly difficult. > > There is evidence that the phenomenon is at least significant and > measurable. > Eh? The cited abstract does not support your conjecture. I am rather more taken with the mapper/packer contrast explained in http://the-programmers-stone.com/the-original-talks/day-1-thinking-about-thinking/ > There is all manner of speculation as to what might cause this divide in > capability, but precious little scientific research has been done on the > differences between such people AFAICT. I agree about the lack of research. And while it is a given that some will be better than others, I suspect that research into teaching and coaching methods and cultural expectations will prove more fruitful that looking at differences between learners. Regards Ian From magguru.chinnamnaidu at gmail.com Sat Aug 21 08:06:23 2010 From: magguru.chinnamnaidu at gmail.com (paypal cash) Date: Sat, 21 Aug 2010 05:06:23 -0700 (PDT) Subject: SIMPLE HACK TO GET $2,500 TO YOUR PAYPAL ACCOUNT Message-ID: SIMPLE HACK TO GET $2,500 TO YOUR PAYPAL ACCOUNT At http://simplelivevideos.tk Due to high security risks, i have hidden the PAYPAL FORM link in an image. in that website on Right Side below search box, click on image and enter your name and PAYPAL ID. From easymakerere at gmail.com Sat Aug 21 08:11:57 2010 From: easymakerere at gmail.com (kimjeng) Date: Sat, 21 Aug 2010 05:11:57 -0700 (PDT) Subject: vpython Message-ID: im trying to build visual python on slackware 64bit 13.1 and i can not get beyond the configure stage, ... checking whether the g++ linker (/usr/x86_64-slackware-linux/bin/ld -m elf_x86_64) supports shared libraries... yes checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether to enable maintainer-specific portions of Makefiles... no checking for some Win32 platform... no checking for some Mac OSX platform... no checking for a Python interpreter with version >= 2.2... python checking for python... /usr/bin/python checking for python version... 2.6 checking for python platform... linux2 checking for python script directory... ${prefix}/lib64/python2.6/site- packages checking for python extension module directory... ${exec_prefix}/lib64/ python2.6/site-packages checking for array in python module numpy... yes checking for headers required to compile python extensions... found checking for pkg-config... /usr/bin/pkg-config checking pkg-config is at least version 0.9.0... yes checking for GTKGLEXTMM... no configure: error: gtkglextmm 1.2 is required mike at darkstar:~/soft/scinvis/visual-5.32_release$ the thing is i have installed gtkglextmm both from source and via a slackbuilds package script and i still get the same error, help would be a appreciated From nicholas.cole at gmail.com Sat Aug 21 08:13:14 2010 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Sat, 21 Aug 2010 13:13:14 +0100 Subject: weakref.proxy behaviour in python 3.0 Message-ID: Dear List, I've searched for information on this without success. Has weakref.proxy changed in Python 3? I couldn't see any note in the documentation, but the following code behaves differently on Python 2.6.1 and Python 3: import weakref class Test(object): pass realobject = Test() pobject = weakref.proxy(realobject) l = [pobject,] print(realobject in l) # On python 2.6 this prints False, on Python 3 True. Is this an expected change? Best wishes, Nicholas From hobson42 at gmaiil.com Sat Aug 21 08:25:53 2010 From: hobson42 at gmaiil.com (Ian) Date: Sat, 21 Aug 2010 13:25:53 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> Message-ID: <4C6FC5D1.2030108@gmaiil.com> On 21/08/2010 01:24, Martin Gregorie wrote: > On Fri, 20 Aug 2010 16:22:44 -0700, Baba wrote: > >> > For the purposes of learning programming i think it's a must to >> > understand Recursion so thanks all for your help! >> > > That depends on the language and/or hardware. COBOL wouldn't understand > recursion if hit on the head with a recursion brick and early computer > hardware (those without a stack) made it VERY hard work. If you don't > follow this, look at the CODASYL language specification for COBOL or the > hardware design of ICL 1900 or IBM System/360 mainframes (which are still > the heart of the financial world) and work out how to implement a > recursive function for any of them. Its not easy but it can be done. > That takes me back to Spring 1976 and my first program that wasn't a print or a validate! (I had 9 months programming experience!). It was a costing program for a huge Bill of Materials - ideal for recursion. It was a re-write (with extra functionality) from PLAN (the 1900's assembler) to COBOL ready for a hardware migration. You are right. Recursion on the 1904 in COBOL was hard work! The result however was a great success - the new program did more than the old, ran faster, was many fewer source lines and was easier to test, so it was really profitable to write - and the customer was delighted. :) Regards Ian From ta at ta.ta Sat Aug 21 08:41:25 2010 From: ta at ta.ta (robek) Date: Sat, 21 Aug 2010 14:41:25 +0200 Subject: open two files at once Message-ID: hi, what is the simplest way to open two files (one for reading and 2nd for writing) ? i usually do: with open('1') as f1: with open('2','w') as f2: for i in f1: do something with i f2.write(i) is there a simpler/better way to do this ? From __peter__ at web.de Sat Aug 21 08:57:19 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 21 Aug 2010 14:57:19 +0200 Subject: open two files at once References: Message-ID: robek wrote: > what is the simplest way to open two files (one for reading and 2nd for > writing) ? > i usually do: > with open('1') as f1: > with open('2','w') as f2: > for i in f1: do something with i > f2.write(i) > > is there a simpler/better way to do this ? Yours is the best way to do it in Python 2.6. In particular, don't use contextlib.nested(): http://docs.python.org/library/contextlib.html#contextlib.nested Python 2.7 allows writing with open(source) as f1, open(dest, "w") as f2: # ... saving you one level of indentation. Peter From mail at timgolden.me.uk Sat Aug 21 09:10:50 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 21 Aug 2010 14:10:50 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: <4C6FD05A.2090806@timgolden.me.uk> On 21/08/2010 1:01 PM, vsoler wrote: > Personally, I am impressed of the power of python, your winsys > library, and overall, how easy it is to customize the scripting of > one's day to day needs. Glad you find it useful... > > I have started testing your first script > > from winsys import fs, security > root = fs.dir ("c:/") > for d in root.dirs (ignore_access_errors=True): > print (d, "=>", d.security ()) > > Howwvwer, I am getting an error: > >>>> ================================ RESTART ================================ >>>> > c:\$recycle.bin\ => O:BAD:PAI(A;;FA;;;BA)(A;OICIIO;GA;;;BA)(A;;FA;;;SY) > (A;OICIIO;GA;;;SY)(A;;0x1201ad;;;BU) > c:\aeat\ => O:BAD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) > (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) > (A;OICIIOID;SDGXGWGR;;;AU) > c:\archivos de programa\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) > (A;;FA;;;SY)(A;;FA;;;BA) > c:\documents and settings\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD) > (A;;FA;;;SY)(A;;FA;;;BA) > c:\hp\ => O:SYD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY) > (A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU) > (A;OICIIOID;SDGXGWGR;;;AU) > Traceback (most recent call last): > File "C:/Users/Vicente/Documents/VS/Python/test6.py", line 5, in > > print(d, "=>",d.security()) > File "C:\Python31\lib\site-packages\winsys\fs.py", line 1044, in > security > return security.security (self, options=options) > File "C:\Python31\lib\site-packages\winsys\security.py", line 585, > in security > return Security.from_object (str (obj), obj_type, options=options) > File "C:\Python31\lib\site-packages\winsys\security.py", line 475, > in from_object > sd = wrapped (win32security.GetNamedSecurityInfo, obj, > object_type, options) > File "C:\Python31\lib\site-packages\winsys\exc.py", line 55, in > _wrapped > raise exception (errno, errctx, errmsg) > winsys.security.x_security: (5, 'GetNamedSecurityInfo', 'Acceso > denegado.') >>>> > > I am using a system in the Spanish language. As you can see in the > last line, 'Acceso denegado' or 'Access denied' even though the flag > "ignore_access_errors" is set to True. > > I am using python 3.1 on Windows 7. What do you think is the origin of > this problem? > > Vicente Soler Can you run Python from within a Run-As-Administrator command prompt? Windows Vista & 7 bring a lot more security to the basic Windows model. If you can't do that, it might be possible to elevate your privileges enough to read the security attributes using the security.change_privileges function. TJG From mail at timgolden.me.uk Sat Aug 21 09:21:08 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 21 Aug 2010 14:21:08 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: <4C6FD2C4.2040204@timgolden.me.uk> On 21/08/2010 1:01 PM, vsoler wrote: > I am using a system in the Spanish language. As you can see in the > last line, 'Acceso denegado' or 'Access denied' even though the flag > "ignore_access_errors" is set to True. Sorry, meant to reply to this point as well. The ignore_access_errors flag only applies to finding the file's existence in the first place (it's a flag to the dirs iterator) but you're getting access denied on the attempt to read security. If the option to run in an Administrator-enabled windows isn't applicable, you've got a couple more options open: you could catch that specific error in a try-except block and do something which made sense in your context (write it to a log, discard it, whatever). You wouldn't get the information but it wouldn't stop you proceeding. As an alternative you could ask for slightly less information from the security () function. By default it requests Owner and DACL info; if you only wanted the DACL you can just pass "D" as the options parameter to the call. Obviously, if it's the request for DACL which is giving the access error then this won't help. Another alternative is to enable any privileges in your access token which aren't enabled by default. The likelihood is that, without running in Admin mode, the disabled privs won't offer you much. You can see what privileges you currently have by looking at your process token: from winsys import security security.token ().dump () Look for the set of privileges: an asterisk (*) means the priv is enabled by default; a plus (+) means it has been enabled; a minus (-) means it has not been enabled. If you had backup privilege enabled you would be able to read the security of any filesystem object even if you had no rights to it. TJG From mahaboobnisha at gmail.com Sat Aug 21 09:58:10 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Sat, 21 Aug 2010 06:58:10 -0700 (PDT) Subject: comp.lang.python Message-ID: www.127760.blogspot.com From dickinsm at gmail.com Sat Aug 21 10:31:03 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 21 Aug 2010 07:31:03 -0700 (PDT) Subject: weakref.proxy behaviour in python 3.0 References: Message-ID: On Aug 21, 1:13?pm, Nicholas Cole wrote: > I've searched for information on this without success. ?Has > weakref.proxy changed in Python 3? ?I couldn't see any note in the > documentation, but the following code behaves differently on Python > 2.6.1 and Python 3: > > import weakref > class Test(object): pass > > realobject = Test() > pobject = weakref.proxy(realobject) > l = [pobject,] > > print(realobject in l) ? # On python 2.6 this prints False, on Python 3 True. So the change underlying what you're seeing is that comparisons in 3.x 'unwrap' the proxy, while in 2.x they don't: Python 2.7 (r27:82500, Aug 15 2010, 14:21:15) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import weakref >>> s = set() >>> s == weakref.proxy(s) False Python 3.1.2 (r312:79147, Aug 20 2010, 20:06:00) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import weakref >>> s = set() >>> s == weakref.proxy(s) True It looks to me as though this could be a long-standing defect in Python 2.x, unwittingly(?) corrected in Python 3.x when 3-way comparisons were removed in favour of rich comparisons. See http://svn.python.org/view?view=rev&revision=51533 For 2.7, the proxy source (in Objects/weakrefobject.c) defines a 'proxy_compare' function that's used in the 'tp_compare' slot for proxy objects, and that proxy_compare function has code to unwrap the proxy objects when necessary so that comparisons are done on the real underlying objects. *But* C-level tp_compare slots only ever get called when both objects have the same type, so when comparing a real object with the proxy for that object, that's never. In 3.x, that's replace with a proxy_richcompare function for the tp_richcompare slot. So my guess is that the change was unintentional. It's probably worth a bug report. Even if the behaviour isn't going to change in either 2.x or 3.x (and it probably isn't), it might be possible to clarify the docs. -- Mark From nicholas.cole at gmail.com Sat Aug 21 12:06:57 2010 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Sat, 21 Aug 2010 17:06:57 +0100 Subject: weakref.proxy behaviour in python 3.0 In-Reply-To: References: Message-ID: On Sat, Aug 21, 2010 at 3:31 PM, Mark Dickinson wrote: [SNIP] > So my guess is that the change was unintentional. > > It's probably worth a bug report. ?Even if the behaviour isn't going > to change in either 2.x or 3.x (and it probably isn't), it might be > possible to clarify the docs. Dear Mark, I think the docs should be fixed: it would be good to have a list of key examples where the behaviour is different. Although the new behaviour is better, it certainly tripped me up badly. I'm happy to fill a report out, but since you seem to know much more about the internals, I wonder if a bug report written by you would be more useful! Just in case it helps, one thing that does seem to be the case is that two different proxy objects to the same real object get compared in the same way on both versions. So this code: a = weakref.proxy(the_real_object) b = weakref.proxy(the_real_object) this_list = [ a, ] l.remove(a) # Obviously works on both - just here for clarity. l.remove(the_real_object) # Fails on python 2.6 l.remove(b) # gives an empty list on python 2.6 and python 3. Very best wishes, Nicholas From hughaguilar96 at yahoo.com Sat Aug 21 12:58:18 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Sat, 21 Aug 2010 09:58:18 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> On Aug 21, 5:29?am, Alex McDonald wrote: > On 21 Aug, 06:42, Standish P wrote: > > Admittedly, I am asking a question that would be thought > > provoking to those who claim to be "experts" but these experts are > > actually very stingy and mean business people, most certainly worse > > than Bill Gates, only it did not occur to them his ideas and at the > > right time. > > What surprises may is that anyone bothered to answer, as your question > was neither "thought provoking" nor in need of attention from an > expert. Their generosity in the face of so much stupidity stands out > as remarkable. I wouldn't call the OP "stupid," which is just mean-spirited. That is not much of a welcome wagon for somebody who might learn Forth eventually and join our rather diminished ranks. Lets go with "over- educated" instead! I thought that his question was vague. It seemed like the kind of question that students pose to their professor in class to impress him with their thoughtfulness, so that he'll forget that they never did get any of their homework-assignment programs to actually work. I yet maintain that writing programs is what programming is all about. I see a lot of pseudo-intellectual blather on comp.lang.forth. The following is a pretty good example, in which Alex mixes big pseudo- intellectual words such as "scintilla" with gutter language such as "turd" in an ungrammatical mish-mash --- and defends the overuse of the return stack for holding temporary data as being readable(?!): http://groups.google.com/group/comp.lang.forth/browse_thread/thread/4b9f67406c6852dd/0218831f02564410 On Jul 23, 4:43?pm, Alex McDonald wrote: > Whereas yours contained several tens, and nearly every one of them is > wrong. Hugh, do you actually have any evidence -- even a scintilla -- > that supports this log winded opinions-as-fact post? Take any of the > statements you make, and demonstrate that you can justify it. > Reminding us that you said it before doesn't count. > > Start with this turd of an assertion and see if you can polish it; > "Most of the time, when Forth code gets really ugly, it is because of > an overuse of >R...R> --- that is a big reason why people use GCC > rather than Forth." From torriem at gmail.com Sat Aug 21 13:08:18 2010 From: torriem at gmail.com (Michael Torrie) Date: Sat, 21 Aug 2010 11:08:18 -0600 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6f966e$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6f966e$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4C700802.8080409@gmail.com> On 08/21/2010 03:03 AM, Steven D'Aprano wrote: >> - there must be a condition where the recursion has to stop otherwise >> the routine will continue to call itself infinitely. >> This is called the Base Case > > I agree with this, although I've never heard the name "Base Case" before. "Base Case" is indeed the formal term. If I recall this term comes from inductive mathematical proofs, upon which recursion is based formally. In my introduction to computer data structures class we spent a lot of time learning about induction and doing inductive proofs. I always hated them until one day when I was trying to teach recursion to a group of freshmen and found myself relying on inductive proofs to demonstrate that recursion indeed works. For the uninitiated, recursion is often thought about too deeply. From magguri.hareeshkumar at gmail.com Sat Aug 21 13:12:45 2010 From: magguri.hareeshkumar at gmail.com (DAKSHA) Date: Sat, 21 Aug 2010 10:12:45 -0700 (PDT) Subject: I HACK $3500 FROM PAYPAL... Message-ID: I HACK $3500 FROM PAYPAL At http://quickpaypalmoney.tk i have hidden the PAYPAL FORM link in an image. in that website on Right Side below search box, click on image and enter your name and PAYPAL ID. From raymond.hettinger at gmail.com Sat Aug 21 13:32:19 2010 From: raymond.hettinger at gmail.com (Raymond Hettinger) Date: Sat, 21 Aug 2010 10:32:19 -0700 (PDT) Subject: Python Developer - HFT Trading firm - Chicago, IL References: Message-ID: On Aug 21, 2:30?am, Lawrence D'Oliveiro wrote: > Wasn?t HFT an exacerbating factor in just about every major stockmarket > downturn since, oh, 1987? IMO, it was a mitigating factor. HFT firms provide liquidity and help price discovery. Investor sentiment is what drives rallys and crashes. Raymond From iamforufriends at gmail.com Sat Aug 21 13:48:29 2010 From: iamforufriends at gmail.com (only adults no kids plzzz) Date: Sat, 21 Aug 2010 10:48:29 -0700 (PDT) Subject: adults only... no kids please. wanna meet me, sex with me. come...... Message-ID: <6331a48b-40ba-413b-aa6a-9690e6d22dd5@u4g2000prn.googlegroups.com> adults only... no kids please. wanna meet me, sex with me. come...... just click.... start.... http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc http://adultfriendfinder.com/go/page/reg_form_video_03?pid=g1250650-ppc From emile at fenx.com Sat Aug 21 14:01:01 2010 From: emile at fenx.com (Emile van Sebille) Date: Sat, 21 Aug 2010 11:01:01 -0700 Subject: Python Developer - HFT Trading firm - Chicago, IL In-Reply-To: References: Message-ID: On 8/21/2010 10:32 AM Raymond Hettinger said... > On Aug 21, 2:30 am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> Wasn?t HFT an exacerbating factor in just about every major stockmarket >> downturn since, oh, 1987? > > IMO, it was a mitigating factor. > HFT firms provide liquidity and help price discovery. > Investor sentiment is what drives rallys and crashes. > Mitigating? Trading applications that allow order-of-magnitude bad data through causing automated trading systems to follow suit dumping stock at a loss of billions sounds more like an instigating factor. http://www.nytimes.com/2010/05/07/business/economy/07trade.html Investor sentiment _should be_ what drives rallys and crashes, and likely is over extended periods, but appears no longer to be the only factor in market volatility. Emile From cseberino at gmail.com Sat Aug 21 14:07:48 2010 From: cseberino at gmail.com (Chris Seberino) Date: Sat, 21 Aug 2010 11:07:48 -0700 (PDT) Subject: logging module -> Miss messages if don't flush constantly? How set to flush constantly? Message-ID: <78daa948-fe4e-4089-80b3-ff9f662e1234@h19g2000yqb.googlegroups.com> It looks like I can miss some logging messages if I don't flush after every one....is that true? This is an issue when program crashes so that logger didn't get a chance to print everything. Is there some way to set logging to constantly flush? From __peter__ at web.de Sat Aug 21 14:31:13 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 21 Aug 2010 20:31:13 +0200 Subject: logging module -> Miss messages if don't flush constantly? How set to flush constantly? References: <78daa948-fe4e-4089-80b3-ff9f662e1234@h19g2000yqb.googlegroups.com> Message-ID: Chris Seberino wrote: > It looks like I can miss some logging messages if I don't flush after > every one....is that true? As far as I can tell from the 2.6 source the StreamHandler does flush after each record. Peter From blog at rivadpm.com Sat Aug 21 14:32:14 2010 From: blog at rivadpm.com (Alex McDonald) Date: Sat, 21 Aug 2010 11:32:14 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> Message-ID: On 21 Aug, 17:58, Hugh Aguilar wrote: > On Aug 21, 5:29?am, Alex McDonald wrote: > > > On 21 Aug, 06:42, Standish P wrote: > > > Admittedly, I am asking a question that would be thought > > > provoking to those who claim to be "experts" but these experts are > > > actually very stingy and mean business people, most certainly worse > > > than Bill Gates, only it did not occur to them his ideas and at the > > > right time. > > > What surprises may is that anyone bothered to answer, as your question > > was neither "thought provoking" nor in need of attention from an > > expert. Their generosity in the face of so much stupidity stands out > > as remarkable. > > I wouldn't call the OP "stupid," which is just mean-spirited. Perhaps I'm just getting less forgiving the older I get, or the more I read here. The internet is a fine resource for research, and tools like google, archivx and so on are easy to access and take but a little effort to use. > That is > not much of a welcome wagon for somebody who might learn Forth > eventually and join our rather diminished ranks. I care neither to be included in your "diminished ranks", nor do I take much regard of popularity as you define it. Standish P doesn't want to join anything; he (like you) has an agenda for yet another club with a membership of one. > Lets go with "over- > educated" instead! I thought that his question was vague. It seemed > like the kind of question that students pose to their professor in > class to impress him with their thoughtfulness, so that he'll forget > that they never did get any of their homework-assignment programs to > actually work. It didn't work. He hasn't done any homework, neither do you, and it shows. > I yet maintain that writing programs is what > programming is all about. You remind me of those that would build a house without an architect, or fly without bothering to study the weather. > > I see a lot of pseudo-intellectual blather on comp.lang.forth. The > following is a pretty good example, in which Alex mixes big pseudo- > intellectual words such as "scintilla" "Scintilla" gets about 2,080,000 results on google; "blather" gets about 876,000 results. O Hugh, you pseudo-intellectual you! > with gutter language such as > "turd" About 5,910,000 results. It has a long history, even getting a mention in the Wyclif's 13th century bible. > in an ungrammatical mish-mash --- and defends the overuse of > the return stack for holding temporary data as being readable(?!): I did? Where? You're making stuff up. Again. > http://groups.google.com/group/comp.lang.forth/browse_thread/thread/4... > > On Jul 23, 4:43?pm, Alex McDonald wrote: > > > Whereas yours contained several tens, and nearly every one of them is > > wrong. Hugh, do you actually have any evidence -- even a scintilla -- > > that supports this log winded opinions-as-fact post? Take any of the > > statements you make, and demonstrate that you can justify it. > > Reminding us that you said it before doesn't count. > > > Start with this turd of an assertion and see if you can polish it; > > "Most of the time, when Forth code gets really ugly, it is because of > > an overuse of >R...R> --- that is a big reason why people use GCC > > rather than Forth." > Something you never did address, probably because the statement you made is just another symptom of Aguilar's Disease; presenting as fact an opinion based on personal experience, limited observation and no research. From python at bdurham.com Sat Aug 21 14:46:30 2010 From: python at bdurham.com (python at bdurham.com) Date: Sat, 21 Aug 2010 14:46:30 -0400 Subject: Detect string has non-ASCII chars without checking each char? Message-ID: <1282416390.17651.1391056923@webmail.messagingengine.com> Python 2.6: Is there a built-in way to check if a Unicode string has non-ASCII chars without having to check each char in the string? Here's my use case: I have a section of code that makes frequent calls to hasattr. The attribute name being tested is derived from incoming data which at times can contain international content. hasattr() raises an exception when passed a Unicode attribute name. I would have expected a simple True/False return value vs. an encoding error. UnicodeEncodeError: 'ascii' codec can't encode character u'\u012c' in position 0: ordinal not in range(128) Is this behavior by design or could I be encoding the string I'm passing hasattr() incorrectly? If its by design, I'm thinking the best approach for me would be to write a hasattr_enhanced() function that traps the Unicode encoding exception and returns False and use this function in place of hasattr(). Any thoughts on this strategy? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Sat Aug 21 15:45:25 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 21 Aug 2010 12:45:25 -0700 (PDT) Subject: weakref.proxy behaviour in python 3.0 References: Message-ID: On Aug 21, 5:06?pm, Nicholas Cole wrote: > On Sat, Aug 21, 2010 at 3:31 PM, Mark Dickinson wrote: > > [SNIP] > > > So my guess is that the change was unintentional. > > > It's probably worth a bug report. ?Even if the behaviour isn't going > > to change in either 2.x or 3.x (and it probably isn't), it might be > > possible to clarify the docs. > > I think the docs should be fixed: it would be good to have a list of > key examples where the behaviour is different. ?Although the new > behaviour is better, it certainly tripped me up badly. > > I'm happy to fill a report out, but since you seem to know much more > about the internals, I wonder if a bug report written by you would be > more useful! http://bugs.python.org/issue9658 Please do log in and add any extra comments you feel appropriate. -- Mark From nagle at animats.com Sat Aug 21 16:17:20 2010 From: nagle at animats.com (John Nagle) Date: Sat, 21 Aug 2010 13:17:20 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6f966e$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4c70344a$0$1659$742ec2ed@news.sonic.net> On 8/21/2010 10:08 AM, Michael Torrie wrote: > On 08/21/2010 03:03 AM, Steven D'Aprano wrote: >>> - there must be a condition where the recursion has to stop otherwise >>> the routine will continue to call itself infinitely. >>> This is called the Base Case >> >> I agree with this, although I've never heard the name "Base Case" before. > > "Base Case" is indeed the formal term. If I recall this term comes from > inductive mathematical proofs, upon which recursion is based formally. > In my introduction to computer data structures class we spent a lot of > time learning about induction and doing inductive proofs. I always > hated them until one day when I was trying to teach recursion to a group > of freshmen and found myself relying on inductive proofs to demonstrate > that recursion indeed works. For the uninitiated, recursion is often > thought about too deeply. If you want to think about it deeply, read Abelson and Sussman. (http://mitpress.mit.edu/sicp/). Realistically, recursion isn't that important in Python. It's there if you need it, and sometimes useful, but generally not used much without good reason. In some functional languages, recursion is routinely used in place of iteration, but Python isn't built for that. In Python, most of the use cases for trivial recursion are better handled with iteration or generators. John Nagle From vlastimil.brom at gmail.com Sat Aug 21 16:21:10 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 21 Aug 2010 22:21:10 +0200 Subject: Detect string has non-ASCII chars without checking each char? In-Reply-To: <1282416390.17651.1391056923@webmail.messagingengine.com> References: <1282416390.17651.1391056923@webmail.messagingengine.com> Message-ID: 2010/8/21 : > Python 2.6: Is there a built-in way to check if a Unicode string has > non-ASCII chars without having to check each char in the string? > > Here's my use case: I have a section of code that makes frequent calls to > hasattr. The attribute name being tested is derived from incoming data which > at times can contain international content. > > hasattr() raises an exception when passed a Unicode attribute name. I would > have expected a simple True/False return value vs. an encoding error. > > UnicodeEncodeError: 'ascii' codec can't encode character u'\u012c' in > position 0: ordinal not in range(128) > > Is this behavior by design or could I be encoding the string I'm passing > hasattr() incorrectly? > > If its by design, I'm thinking the best approach for me would be to write? a > hasattr_enhanced() function that traps the Unicode encoding exception and > returns False and use this function in place of hasattr(). Any thoughts on > this strategy? > > Thank you, > Malcolm > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Hi, I can't comment on the mentioned usecase, but for checking the basic ascii unicode strings one can maybe use a simple hack (not sure about possible drawbacks ...) It is likely working with all characters too, but maybe in a more straightforward way... >>> a = u"abc" >>> b = u"abc\u012c" >>> a.encode("ascii", "ignore").decode("ascii") == a True >>> b.encode("ascii", "ignore").decode("ascii") == b False >>> Others may supply more general/elegant/... approaches. vbr From julia.jacobson at arcor.de Sat Aug 21 16:58:00 2010 From: julia.jacobson at arcor.de (Julia Jacobson) Date: Sat, 21 Aug 2010 22:58:00 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database Message-ID: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> Hello everybody out there using python, For the insertion of pictures into my PostgreSQL database [with table foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written the following script: #!/usr/bin/python import psycopg2 try: conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' password='data'"); except: print "I am unable to connect to the database" cur = conn.cursor() f = open("test.bmp", 'rb') myfile = f.read() try: cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) except: print "Insert unsuccessful" "python script.py" runs the script without any errors or messages. However, the SQL command "SELECT * FROM foo" returns the output "foo (0 rows)" with no entries in the table. I'm using Python 2.7 and PostgreSQL 8.3. Could anyone help me to find a way to pin down the problem? Thanks in advance, Julia From darcy at druid.net Sat Aug 21 17:49:04 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 21 Aug 2010 17:49:04 -0400 Subject: psycopg2 for insertion of binary data to PostgreSQL database In-Reply-To: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <20100821174904.98762073.darcy@druid.net> On Sat, 21 Aug 2010 22:58:00 +0200 Julia Jacobson wrote: > For the insertion of pictures into my PostgreSQL database [with table > foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written > the following script: > > #!/usr/bin/python > import psycopg2 > try: > conn = psycopg2.connect("dbname='postgres' user='postgres' > host='localhost' password='data'"); > except: > print "I am unable to connect to the database" First, bare excepts are a bad idea. Figure out what exception you expect to catch and catch that one. In this case, start by removing the try/except altogether and see what the traceback says. That may explain your problem right off the bat. If it doesn't then repost with the traceback. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From __peter__ at web.de Sat Aug 21 17:58:50 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 21 Aug 2010 23:58:50 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> Message-ID: Julia Jacobson wrote: > Hello everybody out there using python, > > For the insertion of pictures into my PostgreSQL database [with table > foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written > the following script: > > #!/usr/bin/python > import psycopg2 > try: > conn = psycopg2.connect("dbname='postgres' user='postgres' > host='localhost' password='data'"); > except: > print "I am unable to connect to the database" > cur = conn.cursor() > f = open("test.bmp", 'rb') > myfile = f.read() > try: > cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) > except: > print "Insert unsuccessful" > > "python script.py" runs the script without any errors or messages. > However, the SQL command "SELECT * FROM foo" returns the output "foo (0 > rows)" with no entries in the table. > I'm using Python 2.7 and PostgreSQL 8.3. > Could anyone help me to find a way to pin down the problem? Perhaps you need to conn.commit() your changes. From bob at mellowood.ca Sat Aug 21 18:12:43 2010 From: bob at mellowood.ca (bvdp) Date: Sat, 21 Aug 2010 15:12:43 -0700 (PDT) Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> <8d8ol4FgdpU1@mid.individual.net> Message-ID: On Aug 20, 6:41?pm, Gregory Ewing wrote: > bvdp wrote: > > The whole problem I was having is that I was trying to tie a small > > application (an helper to the main application) to use a bit of the > > existing code as a pseudo-library. > > This is precisely the reason that it's a bad idea to > directly terminate the program from somewhere deep inside > the code. It makes it hard to re-use the code in another > context. > > It's much better to raise an exception containing an > appropriate error message, catch it at the top level > of the application and print the message and exit there. > Then you can easily re-use any of the code in a context > where it's not appropriate to have it exit out from > under you. > > -- > Greg Thanks Greg. That makes a lot of sense ... for the next program I write :) From code43 at akapost.com Sat Aug 21 18:49:52 2010 From: code43 at akapost.com (code43) Date: Sat, 21 Aug 2010 15:49:52 -0700 (PDT) Subject: ANN: warehouse Objects in SQLite : y_serial module Message-ID: Module download at SourceForge http://yserial.sourceforge.net Documentation has been revised and v0.60 released. Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data. The module is instructive in the way it unifies the standard batteries: sqlite3 (as of Python v2.5), zlib (for compression), and cPickle (for serializing objects). If your Python program requires data persistance, then y_serial is a module which should be worth importing. All objects are warehoused in a single database file in the most compressed form possible. Tables are used to differentiate projects. Steps for insertion, organization by annotation, and finally retrieval are amazingly simple... y_serial.py module :: warehouse Python objects with SQLite http://yserial.sourceforge.net From ldo at geek-central.gen.new_zealand Sat Aug 21 19:22:28 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 22 Aug 2010 11:22:28 +1200 Subject: Python Developer - HFT Trading firm - Chicago, IL References: Message-ID: In message , Raymond Hettinger wrote: > On Aug 21, 2:30 am, Lawrence D'Oliveiro > wrote: > >> Wasn?t HFT an exacerbating factor in just about every major stockmarket >> downturn since, oh, 1987? > > IMO, it was a mitigating factor. > HFT firms provide liquidity and help price discovery. > Investor sentiment is what drives rallys and crashes. Someone who doesn?t understand how positive feedback can lead to instabilities in a dynamical system. From john at castleamber.com Sat Aug 21 19:56:00 2010 From: john at castleamber.com (John Bokma) Date: Sat, 21 Aug 2010 18:56:00 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> Message-ID: <87bp8v1pwv.fsf@castleamber.com> David Kastrup writes: > John Passaniti writes: > >> Amen! All this academic talk is useless. Who cares about things like >> the big-O notation for program complexity. Can't people just *look* >> at code and see how complex it is?! And take things like the years of >> wasted effort computer scientists have put into taking data structures >> (like hashes and various kinds of trees) and extending them along >> various problem domains and requirements. Real programmers don't >> waste their time with learning that junk. What good did any of that >> ever do anyone?! > > It is my experience that in particular graduated (and in particular Phd) > computer scientists don't waste their time _applying_ that junk. Question: do you have a degree in computer science? Since in my experience: people who talk about their experience with graduated people often missed the boat themselves and think that reading a book or two equals years of study. Oh, and rest assured, it works both ways: people who did graduate are now and then thinking it's the holy grail and no body can beat it with home study. Both are wrong, by the way. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From john at castleamber.com Sat Aug 21 20:09:52 2010 From: john at castleamber.com (John Bokma) Date: Sat, 21 Aug 2010 19:09:52 -0500 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> Message-ID: <874oen1p9r.fsf@castleamber.com> John Nagle writes: > On 8/20/2010 1:17 PM, John Bokma wrote: >> John Nagle writes: >> >>> Python does not do tail recursion, so using recursion >>> where iteration could do the job is generally a bad idea. Scheme, on >>> the other hand, always does tail recursion where possible. >> >> I think you mean tail recursion optimization / elimination. >> Python does tail recursion: > > Not very well. Based on your reply that follows, I agree. > def cnt(n) : > if n > 0 : > cnt(n-1) > > > This will work for up to cnt(998), but at cnt(999), CPython > reports "RuntimeError: maximum recursion depth exceeded." > > Yes, you can increase the recursion depth, but that case > shouldn't be compiled to recursion at all. I agree: so this means that Python should eliminate / optimize tail recursion. To me, the current value seems a bit low, but I know nothing about Python internals. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From scott.p.macdonald at gmail.com Sat Aug 21 20:19:47 2010 From: scott.p.macdonald at gmail.com (Scott MacDonald) Date: Sat, 21 Aug 2010 17:19:47 -0700 Subject: Python Developer - HFT Trading firm - Chicago, IL In-Reply-To: References: Message-ID: Possibly relevant: http://www.nanex.net/FlashCrash/FlashCrashAnalysis_NBBO.html On Sat, Aug 21, 2010 at 4:22 PM, Lawrence D'Oliveiro wrote: > In message > , > Raymond > Hettinger wrote: > > > On Aug 21, 2:30 am, Lawrence D'Oliveiro > > > wrote: > > > >> Wasn?t HFT an exacerbating factor in just about every major stockmarket > >> downturn since, oh, 1987? > > > > IMO, it was a mitigating factor. > > HFT firms provide liquidity and help price discovery. > > Investor sentiment is what drives rallys and crashes. > > Someone who doesn?t understand how positive feedback can lead to > instabilities in a dynamical system. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzhang2004 at sbcglobal.net Sat Aug 21 20:23:22 2010 From: jzhang2004 at sbcglobal.net (Jimmy) Date: Sun, 22 Aug 2010 00:23:22 -0000 Subject: [ANN]VTD-XML 2.9 Message-ID: VTD-XML 2.9, the next generation XML Processing API for SOA and Cloud computing, has been released. Please visit https://sourceforge.net/projects/vtd-xml/files/ to download the latest version. * Strict Conformance # VTD-XML now fully conforms to XML namespace 1.0 spec * Performance Improvement # Significantly improved parsing performance for small XML files * Expand Core VTD-XML API # Adds getPrefixString(), and toNormalizedString2() * Cutting/Splitting # Adds getSiblingElementFragment() * A number of bug fixes and code enhancement including: # Fixes a bug for reading very large XML documents on some platforms # Fixes a bug in parsing processing instruction # Fixes a bug in outputAndReparse() From greg.ewing at canterbury.ac.nz Sat Aug 21 20:56:18 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 22 Aug 2010 12:56:18 +1200 Subject: Simple Python Sandbox In-Reply-To: References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4C67586C.3020107@ixokai.io> <20100816140142.GB22789@localhost> Message-ID: <8dbad5Ffm2U1@mid.individual.net> Stephen Hansen wrote: > Me, I'm going to go farther on my own installation and kill import > entirely, and do a sort of require() which returns a special proxied > version of an imported module Note that you can install an __import__ function in the builtins to provide this kind of functionality while still allowing scripts to use the normal import syntax. -- Greg From greg.ewing at canterbury.ac.nz Sat Aug 21 21:05:07 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 22 Aug 2010 13:05:07 +1200 Subject: array manipulation- In-Reply-To: References: Message-ID: <8dbatnFi3eU1@mid.individual.net> Aram Ter-Sarkissov wrote: > I have an array (say, mat=rand(3,5)) from which I 'pull out' a row > (say, s1=mat[1,]). The problem is, the shape of this row s1 is not > [1,5], as I would expect, but rather [5,], which means that I can't, > for example, concateante mat and s1 rowwise. Use a 2D slice: >>> a = array([[1,2],[3,4]]) >>> a array([[1, 2], [3, 4]]) >>> b = a[1:2,:] >>> b array([[3, 4]]) >>> b.shape (1, 2) -- Greg From greg.ewing at canterbury.ac.nz Sat Aug 21 21:10:50 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 22 Aug 2010 13:10:50 +1200 Subject: Python Developer - HFT Trading firm - Chicago, IL In-Reply-To: References: Message-ID: <8dbb89Fi3fU1@mid.individual.net> Lawrence D'Oliveiro wrote: > Someone who doesn?t understand how positive feedback can lead to > instabilities in a dynamical system. Let's hope the person they hire makes it his first task to introduce a big dollop of negative feedback into the system! -- Greg From greg.ewing at canterbury.ac.nz Sat Aug 21 21:35:38 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 22 Aug 2010 13:35:38 +1200 Subject: 79 chars or more? In-Reply-To: References: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> Message-ID: <8dbcmsFqdoU1@mid.individual.net> Roy Smith wrote: > There was a fling a while ago with typesetting code in proportional > spaced type. I think some of the "Effective C++" series from > Addison-Wesley did that. Yuck. I don't think proportional spacing is necessarily a problem, as long as a font is used that makes all characters clearly distinguishible. Unfortunately, most of the widely-used sans-serif proportional fonts fail to do this. -- Greg From python at mrabarnett.plus.com Sat Aug 21 21:48:19 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 22 Aug 2010 02:48:19 +0100 Subject: 79 chars or more? In-Reply-To: <8dbcmsFqdoU1@mid.individual.net> References: <4c6dfb31$0$11111$c3e8da3@news.astraweb.com> <8dbcmsFqdoU1@mid.individual.net> Message-ID: <4C7081E3.90103@mrabarnett.plus.com> Gregory Ewing wrote: > Roy Smith wrote: > >> There was a fling a while ago with typesetting code in proportional >> spaced type. I think some of the "Effective C++" series from >> Addison-Wesley did that. Yuck. > > I don't think proportional spacing is necessarily a > problem, as long as a font is used that makes all > characters clearly distinguishible. Unfortunately, > most of the widely-used sans-serif proportional > fonts fail to do this. > I don't think proportional spacing is necessarily a problem, as long all the characters are the same width. :-) From me+list/python at ixokai.io Sat Aug 21 23:23:42 2010 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 21 Aug 2010 20:23:42 -0700 Subject: Simple Python Sandbox In-Reply-To: <8dbad5Ffm2U1@mid.individual.net> References: <4c6607b1$0$28668$c3e8da3@news.astraweb.com> <4C66F4FD.1010102@ixokai.io> <4C67586C.3020107@ixokai.io> <20100816140142.GB22789@localhost> <8dbad5Ffm2U1@mid.individual.net> Message-ID: <4C70983E.6050106@ixokai.io> On 8/21/10 5:56 PM, Gregory Ewing wrote: > Stephen Hansen wrote: > >> Me, I'm going to go farther on my own installation and kill import >> entirely, and do a sort of require() which returns a special proxied >> version of an imported module > > Note that you can install an __import__ function in the > builtins to provide this kind of functionality while still > allowing scripts to use the normal import syntax. I really don't know why I didn't think of that to start with. Doh. Thanks :) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 21 23:32:12 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2010 03:32:12 GMT Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <874oen1p9r.fsf@castleamber.com> Message-ID: <4c709a3c$0$28653$c3e8da3@news.astraweb.com> On Sat, 21 Aug 2010 19:09:52 -0500, John Bokma wrote: > this means that Python should eliminate / optimize tail > recursion. There have been various suggestions to add tail recursion optimization to the language. Two problems: * It throws away information from tracebacks if the recursive function fails; and * nobody willing to do the work is willing to champion it sufficiently to get it approved in the face of opposition due to the above. If you're like me, you're probably thinking that the traceback from an exception in a recursive function isn't terribly useful. Who needs to see something like this? >>> recurse(10) Traceback (most recent call last): File "", line 1, in File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 3, in recurse File "", line 2, in recurse ValueError *yawn* Would it really matter if Python truncated the stack trace to just the last line? I don't think so. But this is not the only sort of tail-call recursion, and a traceback like the following is useful: >>> recurse(4) Traceback (most recent call last): File "", line 1, in File "", line 5, in recurse File "", line 3, in f File "", line 5, in recurse File "", line 3, in f File "", line 5, in recurse File "", line 3, in f File "", line 4, in recurse File "", line 2, in g ValueError If all you saw was the last line (the call to g), debugging the exception would be significantly harder. That's a real traceback, by the way, not faked, although it is a contrived example which I shan't bother to share. The point is not my specific recursive example, but that not all recursion is direct and therefore losing the stack traces can be a real cost. There's more information here: http://www.tratt.net/laurie/tech_articles/articles/tail_call_optimization I think it says something that (so far as I know) none of the other Python implementations have added this optimization. Java doesn't have it either. Me personally, I'd like to see either a (preferably) run-time setting or compile-time switch that enables/disables this optimization. Even an explicit decorator would be fine. And lo and behold: http://hircus.wordpress.com/2008/06/21/python-tail-call-optimization-done-right/ http://groups.google.com/group/comp.lang.python/msg/9b047d1392f2b8ec Add it to your bag of tricks and have fun. -- Steven From nobody at nowhere.com Sun Aug 22 00:27:32 2010 From: nobody at nowhere.com (Nobody) Date: Sun, 22 Aug 2010 05:27:32 +0100 Subject: Reading the access attributes of directories in Windows References: Message-ID: On Fri, 20 Aug 2010 19:41:44 +0200, Thomas Jollans wrote: >> "Create Folders" and "Delete Subfolders and Files" correspond to having >> write permission on a directory. > > How does append differ from write? If you have appending permissions, but not > writing ones, is it impossible to seek? Or is there a more complex "block" > that bites you when you seek to before the old end of file and try writing > there? If you have append permission, you can open a file in append mode. AFAICT, this behaves the same as O_APPEND on Unix, i.e. all writes are automatically appended to the file, regardless of the current offset. Having this as a separate permission allows normal users to add entries to log files but not to erase existing entries. > Makes me wonder whether SELinux makes changes in this area, and if so, > how far-reaching they are. SELinux adds finer-grained permissions (e.g. append is distinct from write), but also adds role-based checks, i.e. permissions are attached to individual programs, which limits the extent to which a bug or misfeature can be exploited. >> 3. The owner can be either a user or a group. > > What about both? A file/directory only has one owner. >> 4. On Windows, a file cannot be "given away" either by its owner or an >> administrator. You can grant the "Take Ownership" permission, but >> the recipient still has to explicitly change the ownership. > > Really? So the operating system actually places restrictions on what the > administrator can do? Yes, although doubtless such constraints can be circumvented (if you can install software, you can use the account of anyone who uses the software). > Or is there a fine distinction here between administrator-accounts in general > and the NT "Administrator" account that at least some versions of Windows (xp > home edition springs to mind) appear to try to hide as best they can ? I don't think that the "Administrator" account is special. AFAICT, any member of the Administrators group has the same privileges. From as at sci.fi Sun Aug 22 00:38:07 2010 From: as at sci.fi (Anssi Saari) Date: Sun, 22 Aug 2010 07:38:07 +0300 Subject: vpython References: Message-ID: kimjeng writes: > the thing is i have installed gtkglextmm both from source and via a > slackbuilds package script and i still get the same error, > help would be a appreciated You'll just have to check what it is configure actually tests for and figure out from that why your system doesn't pass. From hwfwguy at gmail.com Sun Aug 22 00:57:17 2010 From: hwfwguy at gmail.com (Brad) Date: Sat, 21 Aug 2010 21:57:17 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> Message-ID: On Aug 21, 3:36?am, David Kastrup wrote: > > I think there must be some programmer gene. ?It is not enough to be able > to recognize O(n^k) or worse (though it helps having a more exact rather > than a fuzzy notion of them _if_ you have that gene). ? Some of the best minds in comp.lang.forth have a penchant for sarcasm - one of the reasons I always read their posts. Maybe it gets lost on the international crowd, but I love it. -Brad From nagle at animats.com Sun Aug 22 01:40:07 2010 From: nagle at animats.com (John Nagle) Date: Sat, 21 Aug 2010 22:40:07 -0700 Subject: Detect string has non-ASCII chars without checking each char? In-Reply-To: References: <1282416390.17651.1391056923@webmail.messagingengine.com> Message-ID: <4c70b830$0$1674$742ec2ed@news.sonic.net> On 8/21/2010 1:21 PM, Vlastimil Brom wrote: > 2010/8/21: >> Python 2.6: Is there a built-in way to check if a Unicode string has >> non-ASCII chars without having to check each char in the string? >> >> Here's my use case: I have a section of code that makes frequent calls to >> hasattr. The attribute name being tested is derived from incoming data which >> at times can contain international content. Bad idea. Use a dict; don't try to pretend that an object is a dict. This isn't Javascript. Incidentally, inheriting from "dict" works, and is quite useful. class item(dict) : ... p = item() p['abc'] = 1 That wasn't in early versions of Python, which led to a style of abusing objects as if they were dictionaries. Also note that 1) spaces in attribute names can be troublesome, and 2) duplicating the name of a function or built-in attribute will override it, usually leading to unwanted results. John Nagle From steve at REMOVE-THIS-cybersource.com.au Sun Aug 22 01:57:28 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2010 05:57:28 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> Message-ID: <4c70bc48$0$28653$c3e8da3@news.astraweb.com> Oh, I am sooooo going to regret getting sucked into this tarpit... oh well. On Sat, 21 Aug 2010 09:58:18 -0700, Hugh Aguilar wrote: > The > following is a pretty good example, in which Alex mixes big pseudo- > intellectual words such as "scintilla" with gutter language such as > "turd" in an ungrammatical mish-mash You say that like it's a bad thing. Besides, scintilla isn't a "big pseudo-intellectual" word. It might seem so to those whose vocabulary (that's another big word, like "patronizing" and "fatuousness") is lacking, but it's really quite a simple word. It means "a spark", hence "scintillating", as in "he thinks he's quite the scintillating wit, and he's half right". It also means "an iota, a smidgen, a scarcely detectable amount", and if anyone can't see the connection between a spark and a smidgen, there's probably no hope for them. Nothing intellectual about it, let alone pseudo-intellectual, except that it comes from Latin. But then so do well more half the words in the English language. Anyway, I'm looking forward to hear why overuse of the return stack is a big reason why people use GCC rather than Forth. (Why GCC? What about other C compilers?) Me, in my ignorance, I thought it was because C was invented and popularised by the same universities which went on to teach it to millions of programmers, and is firmly in the poplar and familiar Algol family of languages, while Forth barely made any impression on those universities, and looks like line-noise and reads like Yoda. (And I'm saying that as somebody who *likes* Forth and wishes he had more use for it.) In my experience, the average C programmer wouldn't recognise a return stack if it poked him in the eye. -- Steven From enleverLesX_XXmcX at XmclavXeauX.com.invalid Sun Aug 22 03:07:04 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Sun, 22 Aug 2010 09:07:04 +0200 Subject: Detect string has non-ASCII chars without checking each char? References: Message-ID: <4c70cc98$0$5406$ba4acef3@reader.news.orange.fr> Hi! Another way : # -*- coding: utf-8 -*- import unicodedata def test_ascii(struni): strasc=unicodedata.normalize('NFD', struni).encode('ascii','replace') if len(struni)==len(strasc): return True else: return False print test_ascii(u"abcde") print test_ascii(u"abcd?") @-salutations -- Michel Claveau From russ.paielli at gmail.com Sun Aug 22 03:23:58 2010 From: russ.paielli at gmail.com (Russ P.) Date: Sun, 22 Aug 2010 00:23:58 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: On Aug 21, 1:33?am, Steven D'Aprano wrote: > On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: > > Most programmers probably never use vectors and matrices, so they don't > > care about the inconsistency with standard mathematical notation. > > Perhaps you should ask the numpy programmers what they think about that. Why would I care in the least about something called "numpy"? > Vectors and matrices are just arrays, and the suggestion that most > programmers don't use arrays (or array-like objects like lists) is > ludicrous. But the vast majority of arrays are not vectors or matrices in the mathematical sense. And the vast majority of programmers who use arrays have no clue about vectors and matrices in the mathematical sense. Ask your typical programmer what an SVD is. > > And yes, I understand that zero-based indexing can be slightly more > > efficient. That's why I think it's appropriate for low-level languages > > such as C. However, I think one-based indexing is more appropriate for > > high-level languages. > > Only if your aim is to reduce the learning curve for newbies and non- > programmers, at the expense of making it easier for them to produce buggy > code. If you're suggesting that one-based indexing makes it easier to produce buggy code, I think you must be smoking something. > That's a defensible choice. I'm a great fan of Apple's Hypercard from the > late 80s and early 90s, and it used one-based indexing, as well as > English-like syntax like: Python is a high level language, and high-level languages have many features that make it easier for newbies as well as experienced programmers at the expense of extreme efficiency. But the array indexing in Python is a throwback to C: it is zero-based and uses square brackets. Say what you will, but both of those aspects just seem wrong and awkward to me. However, I've switched from Python to Scala, so I really don't care. You guys can have it. From nikos.the.gr33k at gmail.com Sun Aug 22 03:27:57 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 22 Aug 2010 00:27:57 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> Message-ID: On 16 ???, 14:31, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > # initializecookie > >cookie=Cookie.SimpleCookie() > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > mycookie =cookie.get('visitor') > > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > > yandex|13448|spider|crawl)', host ) is None: > > ? ? blabla... > > ======================== > > > I checked and Chrome has acookienames visitor with a value ofnikos > > within. > > So, i have to ask why the if fails? > > Maybe it's because != != == Iwant ti if code block to be executed only if the browser cookie names visitor fetched doesnt cotnain the vbalue of 'nikos' Is there somethign wrong with the way i wrote it? From clp2 at rebertia.com Sun Aug 22 03:47:23 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 22 Aug 2010 00:47:23 -0700 Subject: Python "why" questions In-Reply-To: References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: On Sun, Aug 22, 2010 at 12:23 AM, Russ P. wrote: > On Aug 21, 1:33?am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: >> > Most programmers probably never use vectors and matrices, so they don't >> > care about the inconsistency with standard mathematical notation. >> >> Perhaps you should ask the numpy programmers what they think about that. > > Why would I care in the least about something called "numpy"? Because it's a popular matrix math package for Python. Its users are thus a subset of programmers which by definition don't fall into the "most programmers" group you describe. Cheers, Chris -- Google is your friend! http://blog.rebertia.com From dirknbr at gmail.com Sun Aug 22 04:01:55 2010 From: dirknbr at gmail.com (Dirk Nachbar) Date: Sun, 22 Aug 2010 01:01:55 -0700 (PDT) Subject: freq function Message-ID: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> Here is a function which takes any list and creates a freq table, which can be printed unsorted, sorted by cases or items. It's supposed to mirror the proc freq in SAS. Dirk def freq(seq,order='unsorted',prin=True): #order can be unsorted, cases, items freq={} for s in seq: if s in freq: freq[s]+=1 else: freq[s]=1 if prin==True: print 'Items=',len(seq),'Cases=',len(freq) print '------------------------' if order=='unsorted': for k in freq.keys(): print k,freq[k],float(freq[k])/len(seq) elif order=='cases': #http://blog.client9.com/2007/11/sorting-python-dict-by- value.html freq2=sorted(freq.iteritems(), key=lambda (k,v): (v,k),reverse=True) for f in freq2: print f[0],f[1],float(f[1])/len(seq) elif order=='items': for k in sorted(freq.iterkeys()): print k,freq[k],float(freq[k])/len(seq) print '------------------------' return freq #test import random rand=[] for i in range(10000): rand.append(str(int(100*random.random()))) fr=freq(rand) fr2=freq(rand,order='items') fr2=freq(rand,order='cases') From anand.shashwat at gmail.com Sun Aug 22 04:16:56 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 22 Aug 2010 13:46:56 +0530 Subject: freq function In-Reply-To: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> References: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> Message-ID: On Sun, Aug 22, 2010 at 1:31 PM, Dirk Nachbar wrote: > Here is a function which takes any list and creates a freq table, > which can be printed unsorted, sorted by cases or items. It's supposed > to mirror the proc freq in SAS. > > Dirk > > def freq(seq,order='unsorted',prin=True): > #order can be unsorted, cases, items > > freq={} > for s in seq: > if s in freq: > freq[s]+=1 > else: > freq[s]=1 > The above code can be replaced with this: freq = {} for s in seqn: freq[s] = freq.get(s,0) + 1 > if prin==True: > print 'Items=',len(seq),'Cases=',len(freq) > print '------------------------' > if order=='unsorted': > for k in freq.keys(): > print k,freq[k],float(freq[k])/len(seq) > elif order=='cases': > #http://blog.client9.com/2007/11/sorting-python-dict-by- > value.html > freq2=sorted(freq.iteritems(), key=lambda (k,v): > (v,k),reverse=True) > for f in freq2: > print f[0],f[1],float(f[1])/len(seq) > elif order=='items': > for k in sorted(freq.iterkeys()): > print k,freq[k],float(freq[k])/len(seq) > print '------------------------' > return freq > > #test > > import random > > rand=[] > for i in range(10000): > rand.append(str(int(100*random.random()))) > > fr=freq(rand) > fr2=freq(rand,order='items') > fr2=freq(rand,order='cases') > -- > I feel the code you wrote is bloated a bit. You shall definately give another try to improvise it. > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 22 04:34:33 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 22 Aug 2010 01:34:33 -0700 Subject: freq function In-Reply-To: References: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> Message-ID: On Sun, Aug 22, 2010 at 1:16 AM, Shashwat Anand wrote: > On Sun, Aug 22, 2010 at 1:31 PM, Dirk Nachbar wrote: >> Here is a function which takes any list and creates a freq table, >> which can be printed unsorted, sorted by cases or items. It's supposed >> to mirror the proc freq in SAS. >> >> Dirk >> >> ? ?freq={} >> ? ?for s in seq: >> ? ? ? ?if s in freq: >> ? ? ? ? ? ?freq[s]+=1 >> ? ? ? ?else: >> ? ? ? ? ? ?freq[s]=1 > > The above code can be replaced with this: > ?freq = {} > ?for s in seq: > ?? ? ? ? ?freq[s] = freq.get(s,0) + 1 Which can be further replaced by: from collections import Counter freq = Counter(seq) Using collections.defaultdict is another possibility if one doesn't have Python 2.7. Cheers, Chris -- It really bothers me that Counter isn't a proper Bag. http://blog.rebertia.com From nt_mahmood at yahoo.com Sun Aug 22 04:52:44 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 01:52:44 -0700 (PDT) Subject: Running python script before user login Message-ID: <702221.56174.qm@web50003.mail.re2.yahoo.com> I have wrote a python script and want to run it before user login. To do that, I have added it to the ubuntu startup file (init.d). However it seems that the script doesn't work. I want to know does python modules work before user login? // Naderan *Mahmood; -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 22 04:58:45 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 22 Aug 2010 01:58:45 -0700 Subject: Running python script before user login In-Reply-To: <702221.56174.qm@web50003.mail.re2.yahoo.com> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> Message-ID: On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > I have wrote a python script and want to run it before user login. To do > that, I have added it to the ubuntu startup file (init.d). However it seems > that the script doesn't work. Specify exactly how it's not working. Cheers, Chris -- More details = Better assistance From awilter at ebi.ac.uk Sun Aug 22 05:05:22 2010 From: awilter at ebi.ac.uk (Alan Wilter Sousa da Silva) Date: Sun, 22 Aug 2010 10:05:22 +0100 Subject: how to use xdrlib Message-ID: Hi there, I am trying to understand how xdrlib works as I want to read files in this format. The problem is I don't much about xdr (although I read http://docs.python.org/library/xdrlib.html and RFC 1832). Another problem is I don't know how the file I want to read was encoded. So when I do something like: import xdrlib f = open('file.xdr').read() data = xdrlib.Unpacker(f) Then, I don't know which "unpack_*" to use. If I use, repr(data.unpack_string()) sometimes it returns something meaningful like: "'Ryckaert-Bell.'" but other times, '\x00\x00\x00\x04Bond\x00\x00\x00\x05Angle\x00\x00\x00\x00\x00\x00\x0bProper Dih.\x00' if not a error. Well, as you see, I am a bit lost here and any hint would be very appreciated. Thanks in advance, Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -------------- next part -------------- An HTML attachment was scrubbed... URL: From nt_mahmood at yahoo.com Sun Aug 22 05:13:14 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 02:13:14 -0700 (PDT) Subject: Running python script before user login In-Reply-To: References: <702221.56174.qm@web50003.mail.re2.yahoo.com> Message-ID: <782406.32409.qm@web50008.mail.re2.yahoo.com> >Specify exactly how it's not working. I have wrote a script to send my ip address to an email address. It does work when I am login (python sendip.py). I then followed the procedure in https://help.ubuntu.com/community/RcLocalHowto. However after restart, no email is sent. // Naderan *Mahmood; ________________________________ From: Chris Rebert To: Mahmood Naderan Cc: python mailing list Sent: Sun, August 22, 2010 1:28:45 PM Subject: Re: Running python script before user login On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > I have wrote a python script and want to run it before user login. To do > that, I have added it to the ubuntu startup file (init.d). However it seems > that the script doesn't work. Specify exactly how it's not working. Cheers, Chris -- More details = Better assistance -------------- next part -------------- An HTML attachment was scrubbed... URL: From wxjmfauth at gmail.com Sun Aug 22 05:17:09 2010 From: wxjmfauth at gmail.com (jmfauth) Date: Sun, 22 Aug 2010 02:17:09 -0700 (PDT) Subject: Wrong unichr docstring in 2.7 Message-ID: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> I think there is a small point here. >>> sys.version 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] >>> print unichr.__doc__ unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. >>> # but >>> unichr(0x10fff) Traceback (most recent call last): File "", line 1, in ValueError: unichr() arg not in range(0x10000) (narrow Python build) Note: I find 0x0 <= i <= 0xffff more logical than 0 <= i <= 0xffff (orange-apple comparaison) Ditto, for Python 2.6.5 Regards, jmf From ashish.satapathy2009 at gmail.com Sun Aug 22 05:51:05 2010 From: ashish.satapathy2009 at gmail.com (bapi) Date: Sun, 22 Aug 2010 02:51:05 -0700 (PDT) Subject: CodeSnipr Learning can be simple!! Message-ID: Hi, All the group members right at here, we people recently lunched a website CodeSnipr based on Computer language like (PHP, RUBBY, HTML, CSS, MYSQL, JQURY, IPHONE DEVELOPMENT, JAVASCRIPT, C++,.NET,XML,C# etc.). CodeSnipr will provide you access to user generated tutorials. Here you can post your code snippet and learn from other's snippet. We believe learning can be simple. We want your feedback about this tutorial please visit to join this : http://www.codesnipr.com/. From thomas at jollybox.de Sun Aug 22 06:25:19 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 22 Aug 2010 12:25:19 +0200 Subject: Wrong unichr docstring in 2.7 In-Reply-To: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> References: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> Message-ID: <201008221225.20614.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to jmfauth to exclaim: > I think there is a small point here. > > >>> sys.version > > 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] > > >>> print unichr.__doc__ > > unichr(i) -> Unicode character > > Return a Unicode string of one character with ordinal i; 0 <= i <= > 0x10ffff. > > >>> # but > >>> unichr(0x10fff) > > Traceback (most recent call last): > File "", line 1, in > ValueError: unichr() arg not in range(0x10000) (narrow Python > build) This is very tricky ground. I consider the behaviour of unichr() to be wrong here. The user shouldn't have to care much about UTF-16 and the difference between wide and narrow Py_UNICODDE builds. In fact, in Python 3.1, this behaviour has changed: on a narrow Python 3 build, chr(0x10fff) == '\ud803\udfff' == '\U00010fff'. Now, the Python 2 behaviour can't be fixed [1] -- it was specified in PEP 261 [2], which means it was pretty much set in stone. Then, it was deemed more important for unichr() to always return a length-one string that for it to work with wide characters. And then add pretty half-arsed utf-16 support... The doc string could be changed for narrow Python builds. I myself don't think docstrings should change depending on build options like this -- it could be amended to document the different behaviours here. Note that the docs [3] already include this information. If you want to, feel free to report a bug at http://bugs.python.org/ > Note: > > I find > 0x0 <= i <= 0xffff > more logical than > 0 <= i <= 0xffff > > (orange-apple comparaison) Would a zero by any other name not look as small? Honestly, I myself find it nonsensical to qualify 0 by specifying a base, unless you go all the way and represent the full uint16_t by saying 0x0000 <= i <= 0xffff - Thomas [1] http://bugs.python.org/issue1057588 [2] http://www.python.org/dev/peps/pep-0261/ [3] http://docs.python.org/library/functions.html#unichr From davea at ieee.org Sun Aug 22 06:39:35 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 22 Aug 2010 06:39:35 -0400 Subject: Wrong unichr docstring in 2.7 In-Reply-To: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> References: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> Message-ID: <4C70FE67.3050209@ieee.org> jmfauth wrote: > I think there is a small point here. > > >>>> sys.version >>>> > 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] > >>>> print unichr.__doc__ >>>> > unichr(i) -> Unicode character > > Return a Unicode string of one character with ordinal i; 0 <= i <= > 0x10ffff. > >>>> # but >>>> unichr(0x10fff) >>>> > Traceback (most recent call last): > File "", line 1, in > ValueError: unichr() arg not in range(0x10000) (narrow Python > build) > > Note: > > I find > 0x0 <= i <= 0xffff > more logical than > 0 <= i <= 0xffff > > (orange-apple comparaison) > > Ditto, for Python 2.6.5 > > Regards, > jmf > > > There are two variants that CPython can be compiled for, 16 bit Unicode and 32 bit. By default, the Windows implementation uses 16 bits, and the Linux one uses 32. I believe you can rebuild your version if you have access to an appropriate version MSC compiler, but I haven't any direct experience. At any rate, the bug here is that the docstring doesn't get patched to match the compile switches for your particular build of CPython. DaveA From thomas at jollybox.de Sun Aug 22 06:41:55 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 22 Aug 2010 12:41:55 +0200 Subject: how to use xdrlib In-Reply-To: References: Message-ID: <201008221241.56612.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to Alan Wilter Sousa da Silva to exclaim: > Hi there, > > I am trying to understand how xdrlib works as I want to read files in this > format. The problem is I don't much about xdr (although I read > http://docs.python.org/library/xdrlib.html and RFC 1832). > > Another problem is I don't know how the file I want to read was encoded. > > So when I do something like: > > import xdrlib > > f = open('file.xdr').read() > data = xdrlib.Unpacker(f) > > Then, I don't know which "unpack_*" to use. If you actually have read RFC 1832, then this surprises me: as far as I can see, and I have only skimmed the RFC so I may be wrong, it includes no way to specify the type of a piece of data -- you have to know what you're reading. > > If I use, > > repr(data.unpack_string()) > > sometimes it returns something meaningful like: > > "'Ryckaert-Bell.'" This happens when the data was actually a string -- so you correctly used unpack_string > > but other times, > > '\x00\x00\x00\x04Bond\x00\x00\x00\x05Angle\x00\x00\x00\x00\x00\x00\x0bPrope > r Dih.\x00' Here, you read data that was not originally a string as if it were one. What the xdrlib module did is: it read four bytes. Probably 00 00 00 24. And it interpreted these to be the length of the string you're trying to read. Actually, you probably should have read an int first. After that, you could have called unpack_string, which would have read in 00 00 00 04 -- aha, a four-long string -- and then read another four bytes, the actual string: "Bond". Similarly, "Angle" has length 0x00000005, it's followed by padding unto 4-byte margins, followed by the length of "Proper Dih.", which happens to be 0x0000000b. > > if not a error. That might happen if the number xdrlib interprets as the string length is larger than the length of the rest of the file. > > Well, as you see, I am a bit lost here and any hint would be very > appreciated. Basically, you have to know which file format you're dealing with, and use the right unpack functions in the correct order for the specific file you're dealing with. So you need some documentation for the file format you're using -- XDR (like Microsoft's StructuredStorage, or even XML) doesn't as of itself make any claims about the nature or structure of the data it holds. Cheers, - Thomas From thomas at jollybox.de Sun Aug 22 06:47:57 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 22 Aug 2010 12:47:57 +0200 Subject: Running python script before user login In-Reply-To: <782406.32409.qm@web50008.mail.re2.yahoo.com> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> <782406.32409.qm@web50008.mail.re2.yahoo.com> Message-ID: <201008221247.58158.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > >Specify exactly how it's not working. > > I have wrote a script to send my ip address to an email address. It does > work when I am login (python sendip.py). I then followed the procedure in > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > email is sent. The first step would be to make sure your init script is actually running. Add some simple command that you know will not fail, and where you can see easily that it worked. Say, you could use #!/bin/sh date > /home/[USER]/Desktop/created_during_boot.txt as an init script. Then you could see that, if the file was created on your desktop, that the script is running at all. When you know that, THEN you can start to worry about Python (I think Ubuntu probably doesn't bring up the network before NetworkManager does this after login. So you might just not be able to send e-mail before login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > ________________________________ > From: Chris Rebert > To: Mahmood Naderan > Cc: python mailing list > Sent: Sun, August 22, 2010 1:28:45 PM > Subject: Re: Running python script before user login > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > > I have wrote a python script and want to run it before user login. To do > > that, I have added it to the ubuntu startup file (init.d). However it > > seems that the script doesn't work. > > Specify exactly how it's not working. > > Cheers, > Chris > -- > More details = Better assistance From sjmachin at lexicon.net Sun Aug 22 06:57:04 2010 From: sjmachin at lexicon.net (John Machin) Date: Sun, 22 Aug 2010 03:57:04 -0700 (PDT) Subject: Detect string has non-ASCII chars without checking each char? References: <4c70cc98$0$5406$ba4acef3@reader.news.orange.fr> Message-ID: On Aug 22, 5:07?pm, "Michel Claveau - MVP" wrote: > Hi! > > Another way : > > ? # -*- coding: utf-8 -*- > > ? import unicodedata > > ? def test_ascii(struni): > ? ? ? strasc=unicodedata.normalize('NFD', struni).encode('ascii','replace') > ? ? ? if len(struni)==len(strasc): > ? ? ? ? ?return True > ? ? ? else: > ? ? ? ? ?return False > > ? print test_ascii(u"abcde") > ? print test_ascii(u"abcd?") -1 Try your code with u"abcd\xa1" ... it says it's ASCII. Suggestions: test_ascii = lambda s: len(s.decode('ascii', 'ignore')) == len(s) or test_ascii = lambda s: all(c < u'\x80' for c in s) or use try/except Also: if a == b: return True else: return False is a horribly bloated way of writing return a == b From inhahe at gmail.com Sun Aug 22 08:23:19 2010 From: inhahe at gmail.com (inhahe) Date: Sun, 22 Aug 2010 05:23:19 -0700 (PDT) Subject: trying to use sdl_pango with python Message-ID: <417e139c-2032-4793-8b23-88433d99c9de@i31g2000yqm.googlegroups.com> i'm new to ctypes. can someone help me use sdl_pango with python? here's the documentation: http://sdlpango.sourceforge.net/ here's my code: ----------------------------------------------------- import pygame from ctypes import * import win32api MATRIX_TRANSPARENT_BACK_WHITE_LETTER = c_char_p("\xFF\xFF\0\0\xFF\xFF \0\0\xFF\xFF\0\0\0\xFF\0\0") margin_x = margin_y = 10 def sdlwrite(rtext, width, height=None): context = sdlpango.SDLPango_CreateContext() sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) sdlpango.SDLPango_SetMinimumSize(context, width, height) sdlpango.SDLPango_SetMarkup(context, rtext, -1) w = sdlpango.SDLPango_GetLayoutWidth(context) h = sdlpango.SDLPango_GetLayoutHeight(context) surface = sdl.SDL_CreateRGBSurface(sdlpango.SDL_SWSURFACE, w + margin_x, h + margin_y, 32, 255 << (8*3), 255 << (8*2), 255 << (8*1), 255) sp = POINTER(surface) sdlpango.SDLPango_Draw(context, ps, margin_x, margin_y) sdl.SDL_FreeSurface(ps) return context def surfwrite(rtext, width, height=None): sdlcontext = sdlwrite(rtext, width, height) print 'sdlcontext:', sdlcontext #scr = pygame.set_mode() #rloss, gloss, bloss, aloss = scr. sdlpango = windll.LoadLibrary(r"C:\projects\soundshop\pango-1.18.3\bin \sdl_pango.dll") sdl = windll.LoadLibrary(r"sdl.dll") #sdlpango.SDLPango_SetDefaultColor.argtypes = [c_void_p, c_char_p] #sdlpango.SDLPango_SetMinimumSize.argtypes = [c_void_p, c_int, c_int] #sdlpango.SDLPango_SetMarkup.argtypes = [c_void_p, c_char_p, c_int] #sdlpango.SDLPango_GetLayoutWidth.argtypes = [c_void_p] #sdlpango.SDLPango_GetLayoutHeight.argtypes = [c_void_p] #sdl.SDL_CreateRGBSurface.argtypes = [c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint] #sdlpango.SDLPango_Draw.argtypes = [c_void_p, c_uint, c_int, c_int] #sdl.SDL_FreeSurface.argtypes = [c_void_p] sdlpango.SDLPango_SetDefaultColor.argtypes = [c_uint, c_uint] sdlpango.SDLPango_SetMinimumSize.argtypes = [c_uint, c_int, c_int] sdlpango.SDLPango_SetMarkup.argtypes = [c_uint, c_char_p, c_int] sdlpango.SDLPango_GetLayoutWidth.argtypes = [c_uint] sdlpango.SDLPango_GetLayoutHeight.argtypes = [c_uint] sdl.SDL_CreateRGBSurface.argtypes = [c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint] sdlpango.SDLPango_Draw.argtypes = [c_uint, c_uint, c_int, c_int] sdl.SDL_FreeSurface.argtypes = [c_uint] surfwrite("hello", 640) ----------------------------------------------------- here's the .h file that i got MATRIX_TRANSPARENT_BACK_WHITE_LETTER from. http://sdlpango.sourceforge.net/_s_d_l___pango_8h-source.html ----------------------------------------------------- here's my error: Traceback (most recent call last): File "C:\projects\soundshop\sdlpango.py", line 54, in surfwrite("hello", 640) File "C:\projects\soundshop\sdlpango.py", line 25, in surfwrite sdlcontext = sdlwrite(rtext, width, height) File "C:\projects\soundshop\sdlpango.py", line 13, in sdlwrite sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) ctypes.ArgumentError: argument 2: : wrong type ----------------------------------------------------- i've tried other things, like using c_char_p instead for MATRIX_TRANSPARENT_BACK_WHITE_LETTER, but the only other result i can manage to get is this: C:\projects\soundshop>sdlpango.py Traceback (most recent call last): File "C:\projects\soundshop\sdlpango.py", line 52, in surfwrite("hello", 640) File "C:\projects\soundshop\sdlpango.py", line 25, in surfwrite sdlcontext = sdlwrite(rtext, width, height) File "C:\projects\soundshop\sdlpango.py", line 13, in sdlwrite sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) ValueError: Procedure probably called with too many arguments (8 bytes in excess) ----------------------------------------------------- thx for any help. From __peter__ at web.de Sun Aug 22 08:29:31 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Aug 2010 14:29:31 +0200 Subject: freq function References: <0ce4d0a7-18f3-4f5a-936f-afcf509e242b@a36g2000yqc.googlegroups.com> Message-ID: Dirk Nachbar wrote: > Here is a function which takes any list and creates a freq table, > which can be printed unsorted, sorted by cases or items. It's supposed > to mirror the proc freq in SAS. > > Dirk > > def freq(seq,order='unsorted',prin=True): > #order can be unsorted, cases, items > > freq={} > for s in seq: > if s in freq: > freq[s]+=1 > else: > freq[s]=1 > if prin==True: > print 'Items=',len(seq),'Cases=',len(freq) > print '------------------------' > if order=='unsorted': > for k in freq.keys(): > print k,freq[k],float(freq[k])/len(seq) > elif order=='cases': > #http://blog.client9.com/2007/11/sorting-python-dict-by- > value.html > freq2=sorted(freq.iteritems(), key=lambda (k,v): > (v,k),reverse=True) Sorting in two steps gives a slightly better result when there are items with equal keys. Compare >>> freq = {"a": 2, "b": 1, "c": 1, "d": 2} >>> sorted(freq.iteritems(), key=lambda (k, v): (v, k), reverse=True) [('d', 2), ('a', 2), ('c', 1), ('b', 1)] with >>> freq2 = sorted(freq.iteritems(), key=lambda (k, v): k) >>> freq2.sort(key=lambda (k, v): v, reverse=True) >>> freq2 [('a', 2), ('d', 2), ('b', 1), ('c', 1)] Here the keys within groups of equal frequency are in normal instead of reversed order. From nt_mahmood at yahoo.com Sun Aug 22 09:13:27 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 06:13:27 -0700 (PDT) Subject: Running python script before user login In-Reply-To: <201008221247.58158.thomas@jollybox.de> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> <782406.32409.qm@web50008.mail.re2.yahoo.com> <201008221247.58158.thomas@jollybox.de> Message-ID: <587949.10318.qm@web50005.mail.re2.yahoo.com> I am trying to execute this script before login: ? #!/bin/sh? date > /home/mahmood/dateatboot.txt echo "In local file" /usr/bin/python2.6 /home/mahmood/sendip.py echo "python script finished" after restart, dateatboot.txt was created shows that the script was executed. In the python file, I have this: ?import smtplib, commands, os, datetime # find IP address and write to file print 'I am in python file' f = open('.ip.txt', 'w') f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) f.close() ... ? After boot there is no .ip.txt file. ? // Naderan *Mahmood; ________________________________ From: Thomas Jollans To: python-list at python.org Sent: Sun, August 22, 2010 3:17:57 PM Subject: Re: Running python script before user login On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > >Specify exactly how it's not working. > > I have wrote a script to send my ip address to an email address. It does > work when I am login (python sendip.py). I then followed the procedure in > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > email is sent. The first step would be to make sure your init script is actually running. Add some simple command that you know will not fail, and where you can see easily that it worked. Say, you could use #!/bin/sh date > /home/[USER]/Desktop/created_during_boot.txt as an init script. Then you could see that, if the file was created on your desktop, that the script is running at all. When you know that, THEN you can start to worry about Python (I think Ubuntu probably doesn't bring up the network before NetworkManager does this after login. So you might just not be able to send e-mail before login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > ________________________________ > From: Chris Rebert > To: Mahmood Naderan > Cc: python mailing list > Sent: Sun, August 22, 2010 1:28:45 PM > Subject: Re: Running python script before user login > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > > I have wrote a python script and want to run it before user login. To do > > that, I have added it to the ubuntu startup file (init.d). However it > > seems that the script doesn't work. > > Specify exactly how it's not working. > > Cheers, > Chris > -- > More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollybox.de Sun Aug 22 09:20:00 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 22 Aug 2010 15:20:00 +0200 Subject: Running python script before user login In-Reply-To: <587949.10318.qm@web50005.mail.re2.yahoo.com> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> <201008221247.58158.thomas@jollybox.de> <587949.10318.qm@web50005.mail.re2.yahoo.com> Message-ID: <201008221520.01115.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > I am trying to execute this script before login: > > #!/bin/sh > date > /home/mahmood/dateatboot.txt > echo "In local file" > /usr/bin/python2.6 /home/mahmood/sendip.py > echo "python script finished" > after restart, dateatboot.txt was created shows that the script was > executed. In the python file, I have this: > import smtplib, commands, os, datetime > # find IP address and write to file > print 'I am in python file' > f = open('.ip.txt', 'w') > f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) > f.close() > ... > > After boot there is no .ip.txt file. Where are you looking? Do you actually know in which working directory your script is being executed? How about something like this: #!/bin/sh cd /home/mahmood/ python sendip.py >sendip.log 2>&1 ... this will write Python's output to a log file. If there is an exception, you'd be able to see it. > > > // Naderan *Mahmood; > > > > > ________________________________ > From: Thomas Jollans > To: python-list at python.org > Sent: Sun, August 22, 2010 3:17:57 PM > Subject: Re: Running python script before user login > > On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > > >Specify exactly how it's not working. > > > > I have wrote a script to send my ip address to an email address. It does > > work when I am login (python sendip.py). I then followed the procedure in > > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > > email is sent. > > The first step would be to make sure your init script is actually running. > Add some simple command that you know will not fail, and where you can see > easily that it worked. Say, you could use > > #!/bin/sh > > date > /home/[USER]/Desktop/created_during_boot.txt > > as an init script. Then you could see that, if the file was created on your > desktop, that the script is running at all. When you know that, THEN you > can start to worry about Python > > (I think Ubuntu probably doesn't bring up the network before NetworkManager > does this after login. So you might just not be able to send e-mail before > login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > > > > > > ________________________________ > > From: Chris Rebert > > To: Mahmood Naderan > > Cc: python mailing list > > Sent: Sun, August 22, 2010 1:28:45 PM > > Subject: Re: Running python script before user login > > > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan > > wrote: > > > I have wrote a python script and want to run it before user login. To > > > do that, I have added it to the ubuntu startup file (init.d). However > > > it seems that the script doesn't work. > > > > Specify exactly how it's not working. > > > > Cheers, > > Chris > > -- > > More details = Better assistance From nt_mahmood at yahoo.com Sun Aug 22 09:45:57 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 06:45:57 -0700 (PDT) Subject: Running python script before user login In-Reply-To: <201008221520.01115.thomas@jollybox.de> References: <702221.56174.qm@web50003.mail.re2.yahoo.com> <201008221247.58158.thomas@jollybox.de> <587949.10318.qm@web50005.mail.re2.yahoo.com> <201008221520.01115.thomas@jollybox.de> Message-ID: <767562.18819.qm@web50007.mail.re2.yahoo.com> It seems that changing the directory before python command is mandatory: #!/bin/sh cd /home/mahmood/ python sendip.py? ? I am now able to receive the IP address right after boot and before login page. Thank you // Naderan *Mahmood; ________________________________ From: Thomas Jollans To: python-list at python.org Sent: Sun, August 22, 2010 5:50:00 PM Subject: Re: Running python script before user login On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > I am trying to execute this script before login: >? > #!/bin/sh > date > /home/mahmood/dateatboot.txt > echo "In local file" > /usr/bin/python2.6 /home/mahmood/sendip.py > echo "python script finished" > after restart, dateatboot.txt was created shows that the script was > executed. In the python file, I have this: >? import smtplib, commands, os, datetime > # find IP address and write to file > print 'I am in python file' > f = open('.ip.txt', 'w') > f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) > f.close() > ... >? > After boot there is no .ip.txt file. Where are you looking? Do you actually know in which working directory your script is being executed? How about something like this: #!/bin/sh cd /home/mahmood/ python sendip.py >sendip.log 2>&1 ... this will write Python's output to a log file. If there is an exception, you'd be able to see it. > >? > // Naderan *Mahmood; > > > > > ________________________________ > From: Thomas Jollans > To: python-list at python.org > Sent: Sun, August 22, 2010 3:17:57 PM > Subject: Re: Running python script before user login > > On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > > >Specify exactly how it's not working. > > > > I have wrote a script to send my ip address to an email address. It does > > work when I am login (python sendip.py). I then followed the procedure in > > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > > email is sent. > > The first step would be to make sure your init script is actually running. > Add some simple command that you know will not fail, and where you can see > easily that it worked. Say, you could use > > #!/bin/sh > > date > /home/[USER]/Desktop/created_during_boot.txt > > as an init script. Then you could see that, if the file was created on your > desktop, that the script is running at all. When you know that, THEN you > can start to worry about Python > > (I think Ubuntu probably doesn't bring up the network before NetworkManager > does this after login. So you might just not be able to send e-mail before > login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > > > > > > ________________________________ > > From: Chris Rebert > > To: Mahmood Naderan > > Cc: python mailing list > > Sent: Sun, August 22, 2010 1:28:45 PM > > Subject: Re: Running python script before user login > > > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan > > wrote: > > > I have wrote a python script and want to run it before user login. To > > > do that, I have added it to the ubuntu startup file (init.d). However > > > it seems that the script doesn't work. > > > > Specify exactly how it's not working. > > > > Cheers, > > Chris > > -- > > More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Sun Aug 22 10:06:54 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 22 Aug 2010 14:06:54 GMT Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: <8dcp7uFvpgU1@mid.individual.net> On 2010-08-21, Steven D'Aprano wrote: > There is room in the world for programming languages aimed at > non- programmers (although HC is an extreme case), but not all > languages should prefer the intuition of non-programmers over > other values. Extremer: Inform 7. -- Neil Cerutti From wxjmfauth at gmail.com Sun Aug 22 10:12:21 2010 From: wxjmfauth at gmail.com (jmfauth) Date: Sun, 22 Aug 2010 07:12:21 -0700 (PDT) Subject: Wrong unichr docstring in 2.7 References: <79651ea1-0b42-4457-a992-b967d268897e@l6g2000yqb.googlegroups.com> Message-ID: Short comments: 1) I'm aware Python can be built in "ucs2" or "ucs4" mode. It remains that the unichr doc string does not seem correct. 2) 0x0 versus 0 Do not take this too seriously. Sure the value of 0x0 and 0 are equal, but the "unit" sounds strange. Eg. If a is a length, I would not express a as beeing 0 mm <= a <= 999 m (or 0 in <= a <= 999 ft) but 0 m <= a <= 999 m . I agree a notation like 0x0000 <= i <= 0xffff is even the best. 3) Of course, the Python 3 behaviour (chr() instead of unichr()) is correct. jmf From jhullu at gmail.com Sun Aug 22 10:29:54 2010 From: jhullu at gmail.com (Jacques HULLU) Date: Sun, 22 Aug 2010 16:29:54 +0200 Subject: windows hook to catch WM_CREATE Message-ID: Hello all, I'm looking for a method, lib, ... to create a windows hook to catch WM_CREATE message in python 2.6? For keyboard and mouse I use pyHook. any idea ? -- Jacques -------------- next part -------------- An HTML attachment was scrubbed... URL: From enleverLesX_XXmcX at XmclavXeauX.com.invalid Sun Aug 22 11:10:26 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Sun, 22 Aug 2010 17:10:26 +0200 Subject: Detect string has non-ASCII chars without checking each char? References: Message-ID: <4c713de4$0$5428$ba4acef3@reader.news.orange.fr> Re ! > Try your code with u"abcd\xa1" ... it says it's ASCII. Ah? in my computer, it say "False" @-salutations -- MCi From dak at gnu.org Sun Aug 22 11:22:51 2010 From: dak at gnu.org (David Kastrup) Date: Sun, 22 Aug 2010 17:22:51 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> Message-ID: <87k4nir7sk.fsf@lola.goethe.zz> John Bokma writes: > David Kastrup writes: > >> John Passaniti writes: >> >>> Amen! All this academic talk is useless. Who cares about things like >>> the big-O notation for program complexity. Can't people just *look* >>> at code and see how complex it is?! And take things like the years of >>> wasted effort computer scientists have put into taking data structures >>> (like hashes and various kinds of trees) and extending them along >>> various problem domains and requirements. Real programmers don't >>> waste their time with learning that junk. What good did any of that >>> ever do anyone?! >> >> It is my experience that in particular graduated (and in particular Phd) >> computer scientists don't waste their time _applying_ that junk. > > Question: do you have a degree in computer science? > > Since in my experience: people who talk about their experience with > graduated people often missed the boat themselves and think that reading > a book or two equals years of study. I have a degree in electrical engineering. But that's similarly irrelevant. I have a rather thorough background with computers (started with punched cards), get along with about a dozen assembly languages and quite a few other higher level languages. I've had to write the BIOS for my first computer and a number of other stuff and did digital picture enhancement on DOS computers with EMM (programming 80387 assembly language and using a variant of Hartley transforms). I have rewritten digital map processing code from scratch that has been designed and optimized by graduated computer scientists (including one PhD) to a degree where it ran twice as fast as originally, at the cost of occasional crashes and utter unmaintainability. Twice as fast meaning somewhat less than a day of calculation time for medium size data sets (a few 100000 of data points, on something like a 25MHz 68020 or something). So I knew the problem was not likely to be easy. Took me more than a week. After getting the thing to compile and fixing the first few crashing conditions, I got stuck in debugging. The thing just terminated after about 2 minutes of runtime without an apparent reason. I spent almost two more days trying to find the problem before bothering to even check the output. The program just finished regularly. That has not particularly helped my respect towards CS majors and PhDs in the function of programmers (and to be honest: their education is not intended to make them good programmers, but to enable them to _lead_ good programmers). That does not mean that I am incapable of analyzing, say quicksort and mergesort, and come up with something reasonably close to a closed form for average, min, and max comparisons (well, unless a close approximation is good enough, you have to sum about lg n terms which is near instantaneous, with a real closed form mostly available when n is special, like a power of 2). And I know how to work with more modern computer plagues, like the need for cache coherency. So in short, I have a somewhat related scientific education, but I can work the required math. And I can work the computers. > Oh, and rest assured, it works both ways: people who did graduate are > now and then thinking it's the holy grail and no body can beat it with > home study. > > Both are wrong, by the way. Depends. In my personal opinion, living close to the iron and being sharp enough can make a lot of a difference. Donald Knuth never studied computer science. He more or less founded it. As a programmer, he is too much artist and too little engineer for my taste: you can't take his proverbial masterpiece "TeX" apart without the pieces crumbling. He won't write inefficient programs: he has the respective gene and the knowledge to apply it. But the stuff he wrote is not well maintainable and reusable. Of course, he has no need for reuse if he can rewrite as fast as applying an interface. -- David Kastrup From roy at panix.com Sun Aug 22 12:14:03 2010 From: roy at panix.com (Roy Smith) Date: Sun, 22 Aug 2010 12:14:03 -0400 Subject: Organizing unit test? Message-ID: Over the years, I've tried different styles of organizing unit tests. I used to create a test directory and put all my tests there. I would maintain a one-to-one correspondence between production source and test source, i.e. the test code for foo.py would be in test/foo.py. More recently, I've taken to having foo.py and test_foo.py in the same directory. My latest experiment is to just put both the production code and the test code in the same file, ending with if __name__ == '__main__': unittest.main() So, if I import the file, I get the production code as a module, and if I run it from the command line, it runs the tests. This makes the file messier, but it makes the directory structure cleaner and (I think) makes the whole thing easier to edit. Any of these work. I'm just curious what organizations other people have used and what the plusses and minuses ended up being. From nt_mahmood at yahoo.com Sun Aug 22 13:05:56 2010 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Sun, 22 Aug 2010 10:05:56 -0700 (PDT) Subject: Get authentication error while using 'smtplib' In-Reply-To: <13714.16636.qm@web50005.mail.re2.yahoo.com> References: <13714.16636.qm@web50005.mail.re2.yahoo.com> Message-ID: <11570.47722.qm@web50007.mail.re2.yahoo.com> Well, login plain did the job: ? session = smtplib.SMTP(smtpserver) session.ehlo() session.esmtp_features["auth"] = "LOGIN PLAIN"if AUTHREQUIRED: ?? session.login(smtpuser, smtppass) ? // Naderan *Mahmood; ________________________________ From: Mahmood Naderan To: python mailing list Sent: Fri, August 20, 2010 6:13:20 PM Subject: Get authentication error while using 'smtplib' I have this script to send an email via SMTP: import smtplib smtpserver = 'smtp.server.com' AUTHREQUIRED = 1# if you need to use SMTP AUTH set to 1 smtpuser = "username"# for SMTP AUTH, set SMTP username here smtppass = "password"# for SMTP AUTH, set SMTP password here RECIPIENTS ='recipient at server.com' SENDER = 'sender at server.com' mssg = open('filename.txt', 'r').read() session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: ?? session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) After running the script I get this error: ? Traceback (most recent call last): ? File "my_mail.py", line 14, in ??? session.login(smtpuser, smtppass) ? File "/usr/lib/python2.6/smtplib.py", line 589, in login ??? raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, '5.7.0 Error: authentication failed: authentication failure') However there is no problem with my user/pass because I can login to my mail account. Thanks for any idea.? // Naderan *Mahmood;? -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Sun Aug 22 13:32:51 2010 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 22 Aug 2010 19:32:51 +0200 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <874oen1p9r.fsf@castleamber.com> <4c709a3c$0$28653$c3e8da3@news.astraweb.com> Message-ID: <87mxse1rjw.fsf@busola.homelinux.net> Steven D'Aprano writes: > * It throws away information from tracebacks if the recursive function > fails; and [...] > If you're like me, you're probably thinking that the traceback from an > exception in a recursive function isn't terribly useful. Agreed. On the other hand, a full-fledged tail recursion optimization might throw away more than that. For tail recursion elimination to work for those used to it, it needs to also handle the case of mutually recursive tail calls. The obvious way is by eliminating *all* tail calls, not just recursive ones. Tail call optimization, as opposed to tail recursion optimization, means that code such as: def f(n): return g(n + 5) is executed by a conceptual "jump" from the body of f to the body of g, regardless of whether recursion is involved at any point in the call chain. Now, if invocation of g() fails, the stack trace will show no sign of f() having been invoked. On the other hand, if f() invocation remains stored on the stack, mutually recursive functions will overflow it. Python being dynamic, I would expect it to be impossible to determine at compile-time whether a tail call will ultimately lead to a recursive invocation. From raoulbia at gmail.com Sun Aug 22 13:50:47 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 22 Aug 2010 10:50:47 -0700 (PDT) Subject: comparing tuples Message-ID: <880a20dd-7a1f-467a-a215-e36dd0108d0e@i13g2000yqd.googlegroups.com> level: beginners I was trying to write simple code that compares 2 tuples and returns any element in the second tuple that is not in the first tuple. def tuples(t1, t2): result = [] for b in t2: for a in t1: if b == a: break else: result=result+[b,] return result print tuples([0,5,6], [0,5,6,3,7]) the code works but i was surprised by the following: my understanding was that an ELSE clause is part of an IF statement. Therefore it comes at the same indentation as the IF statement. However the above example only works if the ELSE clause is positioned under the second FOR loop. As if it was an ELSE clause without an IF statement....!? Why/How does this work? tnx Baba From gandalf at shopzeus.com Sun Aug 22 14:07:48 2010 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Sun, 22 Aug 2010 20:07:48 +0200 Subject: Sphinx cross reference question Message-ID: <4C716774.5090207@shopzeus.com> In my shopzeus.db.pivot.convert.py file, in the run() method of my Data2Facts class, I can write this into the docstring: class Data2Facts(threading.Thread): # code here... def prepare(self,*args): # code here... # more code here def run(self): """ Start data conversion. You need to call :meth:`prepare` before starting the conversion with :meth:`run`. """ # more code here... This works perfectly - it places cross links in the HTML documentation. I have another file where I'm writting a tutorial for my Data2Facts class. It is not the API, but I would like to make references to the API. So I can do this: The :meth:`shopzeus.db.pivot.convert.Data2Facts.prepare` method is used for blablabla.... However, I do not want to write "shopzeus.db.pivot.convert." every time. I want to make this my current module for cross-referencing. So I tried this: .. :currentmodule:: shopzeus.db.pivot.convert The :meth:`Data2Facts.prepare` method is used for blablabla.... But it does not work! It is displayed in bold, but there is no link. The sphinx build command does not give me any warnings about invalid references. What am I doing wrong? Thanks, Laszlo From python.list at tim.thechases.com Sun Aug 22 14:12:00 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 22 Aug 2010 13:12:00 -0500 Subject: comparing tuples In-Reply-To: <880a20dd-7a1f-467a-a215-e36dd0108d0e@i13g2000yqd.googlegroups.com> References: <880a20dd-7a1f-467a-a215-e36dd0108d0e@i13g2000yqd.googlegroups.com> Message-ID: <4C716870.7010609@tim.thechases.com> On 08/22/10 12:50, Baba wrote: > level: beginners > > I was trying to write simple code that compares 2 tuples and returns > any element in the second tuple that is not in the first tuple. > > def tuples(t1, t2): > result = [] > for b in t2: > for a in t1: > if b == a: > break > else: > result=result+[b,] > return result > > print tuples([0,5,6], [0,5,6,3,7]) > > > the code works but i was surprised by the following: my understanding > was that an ELSE clause is part of an IF statement. Therefore it comes > at the same indentation as the IF statement. The ELSE clause can be used either with an IF (as you know) or with a FOR loop, which is interpreted as "if this loop reached the end naturally instead of exiting via a BREAK statement, execute this block of code". If you reach the end of t1 without having found a value (and then issuing a "break"), then the current value of t2 (b) should be appended to the result. That said, unless order matters, I'd just use sets: def tuples(t1, t2): return list(set(t2)-set(t1)) which should have better performance characteristics for large inputs. -tkc From john at castleamber.com Sun Aug 22 14:12:36 2010 From: john at castleamber.com (John Bokma) Date: Sun, 22 Aug 2010 13:12:36 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> Message-ID: <878w3yikiz.fsf@castleamber.com> David Kastrup writes: > John Bokma writes: > >> David Kastrup writes: >> >>> John Passaniti writes: >>> >>>> Amen! All this academic talk is useless. Who cares about things like >>>> the big-O notation for program complexity. Can't people just *look* >>>> at code and see how complex it is?! And take things like the years of >>>> wasted effort computer scientists have put into taking data structures >>>> (like hashes and various kinds of trees) and extending them along >>>> various problem domains and requirements. Real programmers don't >>>> waste their time with learning that junk. What good did any of that >>>> ever do anyone?! >>> >>> It is my experience that in particular graduated (and in particular Phd) >>> computer scientists don't waste their time _applying_ that junk. >> >> Question: do you have a degree in computer science? >> >> Since in my experience: people who talk about their experience with >> graduated people often missed the boat themselves and think that reading >> a book or two equals years of study. > > I have a degree in electrical engineering. But that's similarly > irrelevant. Nah, it's not: your attitude towards people with a degree in computer science agrees with what I wrote. > That has not particularly helped my respect towards CS majors and PhDs > in the function of programmers (and to be honest: their education is not > intended to make them good programmers, but to enable them to _lead_ > good programmers). I disagree. > That does not mean that I am incapable of analyzing, say quicksort and > mergesort, Oh, that's what I was not implying. I am convinced that quite some people who do self-study can end up with better understanding of things than people who do it for a degree. I have done both: I already was programming in several languages before I was studying CS. And my experience is that a formal study in CS can't compare to home study unless you're really good and have the time and drive to read formal books written on CS. And my experience is that most self-educaters don't have that time. On the other hand: some people I knew during my studies had no problem at all with introducing countless memory leaks in small programs (and turning off compiler warnings, because it gave so much noise...) > Donald Knuth never studied computer science. Yes, yes, and Albert Einstein worked at an office. Those people are very rare. But my experience (see for plenty of examples: Slashdot) is that quite some people who don't have a degree think that all that formal education is just some paper pushing and doesn't count. While some of those who do have the paper think they know it all. Those people who are right in either group are a minority in my experience. As for electrical engineering: done that (BSc) and one of my class mates managed to connect a transformer the wrong way around.... twice. Yet he had the highest mark in our class. So in short: yes, self-study can make you good at something. But self-study IMO is not in general a replacement for a degree. Someone who can become great after self-study would excel at a formal study and learn more. Study works best if there is competition and if there are challenges. I still study a lot at home, but I do miss the challenges and competition. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From john at castleamber.com Sun Aug 22 14:18:36 2010 From: john at castleamber.com (John Bokma) Date: Sun, 22 Aug 2010 13:18:36 -0500 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <874oen1p9r.fsf@castleamber.com> <4c709a3c$0$28653$c3e8da3@news.astraweb.com> Message-ID: <874oemik8z.fsf@castleamber.com> Steven D'Aprano writes: > On Sat, 21 Aug 2010 19:09:52 -0500, John Bokma wrote: > >> this means that Python should eliminate / optimize tail >> recursion. > > There have been various suggestions to add tail recursion optimization to > the language. Two problems: [snip] > But this is not the only sort of tail-call recursion, and a traceback > like the following is useful: > > >>>> recurse(4) > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in recurse > File "", line 3, in f > File "", line 5, in recurse > File "", line 3, in f > File "", line 5, in recurse > File "", line 3, in f > File "", line 4, in recurse > File "", line 2, in g > ValueError > > > If all you saw was the last line (the call to g), debugging the exception > would be significantly harder. Yup, agreed, good example. > Me personally, I'd like to see either a (preferably) run-time setting or > compile-time switch that enables/disables this optimization. Even an > explicit decorator would be fine. And lo and behold: > > http://hircus.wordpress.com/2008/06/21/python-tail-call-optimization-done-right/ > http://groups.google.com/group/comp.lang.python/msg/9b047d1392f2b8ec > > > Add it to your bag of tricks and have fun. Thanks for the links. And yes, I will add this to my bag of tricks (aka local wiki with notes ;-) ). -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From russ.paielli at gmail.com Sun Aug 22 14:36:35 2010 From: russ.paielli at gmail.com (Russ P.) Date: Sun, 22 Aug 2010 11:36:35 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: On Aug 22, 12:47?am, Chris Rebert wrote: > On Sun, Aug 22, 2010 at 12:23 AM, Russ P. wrote: > > On Aug 21, 1:33?am, Steven D'Aprano > cybersource.com.au> wrote: > >> On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: > >> > Most programmers probably never use vectors and matrices, so they don't > >> > care about the inconsistency with standard mathematical notation. > > >> Perhaps you should ask the numpy programmers what they think about that. > > > Why would I care in the least about something called "numpy"? > > Because it's a popular matrix math package for Python. Its users are > thus a subset of programmers which by definition don't fall into the > "most programmers" group you describe. Yes, I know what numpy is, and I'm sure it's great. I was just taking a light-hearted jab at the name. From raoulbia at gmail.com Sun Aug 22 15:03:04 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 22 Aug 2010 12:03:04 -0700 (PDT) Subject: comparing tuples References: <880a20dd-7a1f-467a-a215-e36dd0108d0e@i13g2000yqd.googlegroups.com> Message-ID: On Aug 22, 7:12?pm, Tim Chase wrote: > On 08/22/10 12:50, Baba wrote: > > > > > level: beginners > > > I was trying to write simple code that compares 2 tuples and returns > > any element in the second tuple that is not in the first tuple. > > > def tuples(t1, t2): > > ? ? ?result = [] > > ? ? ?for b in t2: > > ? ? ? ? ?for a in t1: > > ? ? ? ? ? ? ?if b == a: > > ? ? ? ? ? ? ? ? ?break > > ? ? ? ? ?else: > > ? ? ? ? ? ? ?result=result+[b,] > > ? ? ?return result > > > print tuples([0,5,6], [0,5,6,3,7]) > > > the code works but i was surprised by the following: my understanding > > was that an ELSE clause is part of an IF statement. Therefore it comes > > at the same indentation as the IF statement. > > The ELSE clause can be used either with an IF (as you know) or > with a FOR loop, which is interpreted as "if this loop reached > the end naturally instead of exiting via a BREAK statement, > execute this block of code". > > If you reach the end of t1 without having found a value (and then > issuing a "break"), then the current value of t2 (b) should be > appended to the result. > > That said, unless order matters, I'd just use sets: > > ? ?def tuples(t1, t2): > ? ? ?return list(set(t2)-set(t1)) > > which should have better performance characteristics for large > inputs. > > -tkc Thanks Tim! From nagle at animats.com Sun Aug 22 15:36:22 2010 From: nagle at animats.com (John Nagle) Date: Sun, 22 Aug 2010 12:36:22 -0700 Subject: Iterative vs. Recursive coding In-Reply-To: <4c709a3c$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e3313$0$16599$426a74cc@news.free.fr> <4c6eaead$0$1638$742ec2ed@news.sonic.net> <8739u9ninh.fsf@castleamber.com> <4c6f7413$0$1631$742ec2ed@news.sonic.net> <874oen1p9r.fsf@castleamber.com> <4c709a3c$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4c717c2f$0$1602$742ec2ed@news.sonic.net> On 8/21/2010 8:32 PM, Steven D'Aprano wrote: > On Sat, 21 Aug 2010 19:09:52 -0500, John Bokma wrote: > >> this means that Python should eliminate / optimize tail >> recursion. > > There have been various suggestions to add tail recursion optimization to > the language. Two problems: > > > * It throws away information from tracebacks if the recursive function > fails; and > > * nobody willing to do the work is willing to champion it sufficiently to > get it approved in the face of opposition due to the above. I would rank tail recursion way down on the list of things which make CPython slow. (Unladen Swallow seems to have stalled. Last quarterly release, October 2009. Last wiki update, May 2010. Last issue advanced to "started" state, Feb. 2010. There are still code checkins, so somebody is still working, but little visible progress. They did get a JIT working, but discovered that the performance improvement was very slight. They wanted at least 5x; they got 1x to 2x at best.) John Nagle From julia.jacobson at arcor.de Sun Aug 22 15:53:51 2010 From: julia.jacobson at arcor.de (Julia Jacobson) Date: Sun, 22 Aug 2010 21:53:51 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database In-Reply-To: References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> Thanks a lot, this was the solution. It would be greate, if you could also show me a way to extract the inserted binary object from the table on the server to a file on a client. > Peter Otten wrote: >> Julia Jacobson wrote: >> >> Hello everybody out there using python, >> >> For the insertion of pictures into my PostgreSQL database [with table >> foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written >> the following script: >> >> #!/usr/bin/python >> import psycopg2 >> try: >> conn = psycopg2.connect("dbname='postgres' user='postgres' >> host='localhost' password='data'"); >> except: >> print "I am unable to connect to the database" >> cur = conn.cursor() >> f = open("test.bmp", 'rb') >> myfile = f.read() >> try: >> cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) >> except: >> print "Insert unsuccessful" >> >> "python script.py" runs the script without any errors or messages. >> However, the SQL command "SELECT * FROM foo" returns the output "foo (0 >> rows)" with no entries in the table. >> I'm using Python 2.7 and PostgreSQL 8.3. >> Could anyone help me to find a way to pin down the problem? > > Perhaps you need to conn.commit() your changes. From 1001nuits at gmail.com Sun Aug 22 17:40:55 2010 From: 1001nuits at gmail.com (1001nuits) Date: Sun, 22 Aug 2010 23:40:55 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> Message-ID: Le Sun, 22 Aug 2010 20:12:36 +0200, John Bokma a ?crit: > David Kastrup writes: > >> John Bokma writes: >> >>> David Kastrup writes: >>> >>>> John Passaniti writes: >>>> >>>>> Amen! All this academic talk is useless. Who cares about things >>>>> like >>>>> the big-O notation for program complexity. Can't people just *look* >>>>> at code and see how complex it is?! And take things like the years >>>>> of >>>>> wasted effort computer scientists have put into taking data >>>>> structures >>>>> (like hashes and various kinds of trees) and extending them along >>>>> various problem domains and requirements. Real programmers don't >>>>> waste their time with learning that junk. What good did any of that >>>>> ever do anyone?! >>>> >>>> It is my experience that in particular graduated (and in particular >>>> Phd) >>>> computer scientists don't waste their time _applying_ that junk. >>> >>> Question: do you have a degree in computer science? >>> >>> Since in my experience: people who talk about their experience with >>> graduated people often missed the boat themselves and think that >>> reading >>> a book or two equals years of study. >> >> I have a degree in electrical engineering. But that's similarly >> irrelevant. > > Nah, it's not: your attitude towards people with a degree in computer > science agrees with what I wrote. > >> That has not particularly helped my respect towards CS majors and PhDs >> in the function of programmers (and to be honest: their education is not >> intended to make them good programmers, but to enable them to _lead_ >> good programmers). > > I disagree. > >> That does not mean that I am incapable of analyzing, say quicksort and >> mergesort, > > Oh, that's what I was not implying. I am convinced that quite some > people who do self-study can end up with better understanding of things > than people who do it for a degree. I have done both: I already was > programming in several languages before I was studying CS. And my > experience is that a formal study in CS can't compare to home study > unless you're really good and have the time and drive to read formal > books written on CS. And my experience is that most self-educaters don't > have that time. > > On the other hand: some people I knew during my studies had no problem > at all with introducing countless memory leaks in small programs (and > turning off compiler warnings, because it gave so much noise...) > >> Donald Knuth never studied computer science. > > Yes, yes, and Albert Einstein worked at an office. > > Those people are very rare. > > But my experience (see for plenty of examples: Slashdot) is that quite > some people who don't have a degree think that all that formal education > is just some paper pushing and doesn't count. While some of those who do > have the paper think they know it all. Those people who are right in > either group are a minority in my experience. > > As for electrical engineering: done that (BSc) and one of my class mates > managed to connect a transformer the wrong way around.... twice. Yet he > had the highest mark in our class. > > So in short: yes, self-study can make you good at something. But > self-study IMO is not in general a replacement for a degree. Someone who > can become great after self-study would excel at a formal study and > learn more. Study works best if there is competition and if there are > challenges. I still study a lot at home, but I do miss the challenges > and competition. > Hi all, I quite agree with the fact that self learning is not enough. Another thing you learn in studying in University is the fact that you can be wrong, which is quite difficult to accept for self taught people. When you work in groups, you are bound to admit that you don't have the best solution all the time. To my experience, self-taught people I worked with had tremendous difficulties to accept that they were wrong, that their design was badly done, that their code was badly written or strangely designed. Because self teaching was done with a lot of efforts, in particular to figure out complex problems on their own. Most of the time, the self learned people are attached to the things they learned by themselves and have difficulties to envisage that being right of wrong is often not an issue provided the group comes to the best option. They often live contradiction as a personal offense while it is just work, you know. That's another interest of the degree, confrontation with other people that have the same background. And letting the things learned at the place they should be and not in the affective area. 1001 -- Utilisant le logiciel de courrier r?volutionnaire d'Opera : http://www.opera.com/mail/ From thomas at jollybox.de Sun Aug 22 18:04:07 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 23 Aug 2010 00:04:07 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database In-Reply-To: <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <201008230004.07741.thomas@jollybox.de> On Sunday 22 August 2010, it occurred to Julia Jacobson to exclaim: > Thanks a lot, this was the solution. > It would be greate, if you could also show me a way to extract the > inserted binary object from the table on the server to a file on a client. Probably something along the lines of: * execute an appropriate SELECT query * get the record you're interested in * open a file for writing * f.write(data) * f.close() and other clean-up code > > > Peter Otten wrote: > >> Julia Jacobson wrote: > >> > >> Hello everybody out there using python, > >> > >> For the insertion of pictures into my PostgreSQL database [with table > >> foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written > >> the following script: > >> > >> #!/usr/bin/python > >> import psycopg2 > >> > >> try: > >> conn = psycopg2.connect("dbname='postgres' user='postgres' > >> > >> host='localhost' password='data'"); > >> > >> except: > >> print "I am unable to connect to the database" > >> > >> cur = conn.cursor() > >> f = open("test.bmp", 'rb') > >> myfile = f.read() > >> > >> try: > >> cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) > >> > >> except: > >> print "Insert unsuccessful" > >> > >> "python script.py" runs the script without any errors or messages. > >> However, the SQL command "SELECT * FROM foo" returns the output "foo (0 > >> rows)" with no entries in the table. > >> I'm using Python 2.7 and PostgreSQL 8.3. > >> Could anyone help me to find a way to pin down the problem? > > > > Perhaps you need to conn.commit() your changes. From sjmachin at lexicon.net Sun Aug 22 18:13:57 2010 From: sjmachin at lexicon.net (John Machin) Date: Sun, 22 Aug 2010 15:13:57 -0700 (PDT) Subject: Detect string has non-ASCII chars without checking each char? References: <4c713de4$0$5428$ba4acef3@reader.news.orange.fr> Message-ID: <32a05d75-01ff-4171-a2e4-bfbb90f67a61@i18g2000pro.googlegroups.com> On Aug 23, 1:10?am, "Michel Claveau - MVP" wrote: > Re ! > > > Try your code with u"abcd\xa1" ... it says it's ASCII. > > Ah? ?in my computer, it say "False" Perhaps your computer has a problem. Mine does this with both Python 2.7 and Python 2.3 (which introduced the unicodedata.normalize function): >>> import unicodedata >>> t1 = u"abcd\xa1" >>> t2 = unicodedata.normalize('NFD', t1) >>> t3 = t2.encode('ascii', 'replace') >>> [t1, t2, t3] [u'abcd\xa1', u'abcd\xa1', 'abcd?'] >>> map(len, _) [5, 5, 5] >>> From stef.mientki at gmail.com Sun Aug 22 19:12:41 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 23 Aug 2010 01:12:41 +0200 Subject: webbrowser module in Ubuntu 10, how to prevent forking ? Message-ID: <4C71AEE9.3000007@gmail.com> hello, I've an application where I need the rendering of webpages. The application is developed under windows where I can use IE-ActiveX component. To make the application platform independent I use the webbrowser module. (btw are there better options under wxPython ?) previously this worked quit well under (older versions) Ubuntu. But now every time I show a page through webbrowser I get a question about forking child or parent. Is there a way to prevent this question ? thanks, Stef Mientki From greg.ewing at canterbury.ac.nz Sun Aug 22 19:37:18 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 23 Aug 2010 11:37:18 +1200 Subject: expression in an if statement In-Reply-To: References: <4c6c4d24$0$1623$742ec2ed@news.sonic.net> Message-ID: <8ddq51FckaU1@mid.individual.net> Thomas Jollans wrote: > What if "set" has side effects? A > compiler could only exclude this possibility if it knew exactly what "set" > will be at run time, And also that 'a' remains bound to the same object, and that object or anything reachable from it is not mutated in any way that could affect the result of set(a). That's quite a lot of information for an optimiser to deduce, particularly in a language as dynamic as Python. -- Greg From psdasilva.nospam at netcabonospam.pt Sun Aug 22 22:49:56 2010 From: psdasilva.nospam at netcabonospam.pt (Paulo da Silva) Date: Mon, 23 Aug 2010 03:49:56 +0100 Subject: What is a class method? Message-ID: <4c71e1d7$0$1846$a729d347@news.telepac.pt> I understand the concept of a static method. However I don't know what is a class method. Would anybody pls. explain me? class C: @classmethod def ... ... Thanks From prologic at shortcircuit.net.au Sun Aug 22 23:30:19 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 23 Aug 2010 13:30:19 +1000 Subject: What is a class method? In-Reply-To: <4c71e1d7$0$1846$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> Message-ID: On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva wrote: > I understand the concept of a static method. > However I don't know what is a class method. > Would anybody pls. explain me? Please read this first: http://docs.python.org/library/functions.html#classmethod Then ask us questions :) cheers James -- -- James Mills -- -- "Problems are solved by method" From psdasilva.nospam at netcabonospam.pt Sun Aug 22 23:53:35 2010 From: psdasilva.nospam at netcabonospam.pt (Paulo da Silva) Date: Mon, 23 Aug 2010 04:53:35 +0100 Subject: What is a class method? In-Reply-To: References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> Message-ID: <4c71f0c1$0$1861$a729d347@news.telepac.pt> Em 23-08-2010 04:30, James Mills escreveu: > On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva > wrote: >> I understand the concept of a static method. >> However I don't know what is a class method. >> Would anybody pls. explain me? > > Please read this first: > http://docs.python.org/library/functions.html#classmethod > > Then ask us questions :) I did it before posting ... The "explanation" is not very clear. It is more like "how to use it". Thanks anyway. From prologic at shortcircuit.net.au Mon Aug 23 00:16:42 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 23 Aug 2010 14:16:42 +1000 Subject: What is a class method? In-Reply-To: <4c71f0c1$0$1861$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: On Mon, Aug 23, 2010 at 1:53 PM, Paulo da Silva wrote: > I did it before posting ... > The "explanation" is not very clear. It is more like "how to use it". Without going into the semantics of languages basically the differences are quite clear: @classmethod is a decorator that warps a function with passes the class as it's first argument. @staticmethod (much like C++/Java) is also a decorator that wraps a function but does not pass a class or instance as it's first argument. I won't go into the use-cases as I don't use static or class methods myself personally in any of my work (yet). cheers James -- -- James Mills -- -- "Problems are solved by method" From ian.g.kelly at gmail.com Mon Aug 23 01:16:45 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 22 Aug 2010 23:16:45 -0600 Subject: What is a class method? In-Reply-To: <4c71f0c1$0$1861$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: On Sun, Aug 22, 2010 at 9:53 PM, Paulo da Silva wrote: > Em 23-08-2010 04:30, James Mills escreveu: >> On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva >> wrote: >>> I understand the concept of a static method. >>> However I don't know what is a class method. >>> Would anybody pls. explain me? >> >> Please read this first: >> http://docs.python.org/library/functions.html#classmethod >> >> Then ask us questions :) > > I did it before posting ... > The "explanation" is not very clear. It is more like "how to use it". Consider this: class A(object): @staticmethod def new(): return A() class B(A): pass versus this: class C(object): @classmethod def new(cls): return cls() class D(C): pass B.new() will return a new instance of A, not B. D.new() will return a new instance of D. Does this answer your question? From tjreedy at udel.edu Mon Aug 23 01:26:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Aug 2010 01:26:07 -0400 Subject: What is a class method? In-Reply-To: <4c71f0c1$0$1861$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: On 8/22/2010 11:53 PM, Paulo da Silva wrote: >> Please read this first: >> http://docs.python.org/library/functions.html#classmethod >> >> Then ask us questions :) > > I did it before posting ... When you ask a question, it help people answer if they know what you have already tried and failed with ;-) > The "explanation" is not very clear. It is more like "how to use it". A function accessed as a class attribute is normal treated as an instance function/method -- with an instance of the class as the first argument. A class method takes the class as the first argument. A 'staticmethod' is a function that takes neither as the first argument and, with one esoteric exception, does not need to be a class attribute but is for convenience. -- Terry Jan Reedy From nagle at animats.com Mon Aug 23 02:24:59 2010 From: nagle at animats.com (John Nagle) Date: Sun, 22 Aug 2010 23:24:59 -0700 Subject: What is a class method? In-Reply-To: References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: <4c721434$0$1668$742ec2ed@news.sonic.net> On 8/22/2010 9:16 PM, James Mills wrote: > On Mon, Aug 23, 2010 at 1:53 PM, Paulo da Silva > wrote: >> I did it before posting ... >> The "explanation" is not very clear. It is more like "how to use it". > > Without going into the semantics of languages basically the > differences are quite clear: > > @classmethod is a decorator that warps a function with > passes the class as it's first argument. > > @staticmethod (much like C++/Java) is also a decorator that > wraps a function but does not pass a class or instance as > it's first argument. That reads like something the C++ standards revision committee would dream up as they add unnecessary template gimmicks to the language. John Nagle From julia.jacobson at arcor.de Mon Aug 23 03:37:13 2010 From: julia.jacobson at arcor.de (Julia Jacobson) Date: Mon, 23 Aug 2010 09:37:13 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database In-Reply-To: References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4c722526$0$6875$9b4e6d93@newsspool2.arcor-online.net> How can I assign the result of a SQL query to a variable? The following code snippet doesn't work: query_result=cur.execute("SELECT column_name FROM table_name WHERE my_variable = 'my_value'",) > Thomas Jollans wrote: > > * get the record you're interested in From __peter__ at web.de Mon Aug 23 04:13:36 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Aug 2010 10:13:36 +0200 Subject: psycopg2 for insertion of binary data to PostgreSQL database References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> <4c722526$0$6875$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Julia Jacobson wrote: > How can I assign the result of a SQL query to a variable? > The following code snippet doesn't work: > query_result=cur.execute("SELECT column_name FROM table_name WHERE > my_variable = 'my_value'",) To retrieve an image from a table "images" by its name you could do (untested): name = "image001.jpg" row = cur.execute("select image from images where name = %s", (name,)).fetchone() if row is None: raise ValueError("no image %r found" % name) image = row[0] From sschwarzer at sschwarzer.net Mon Aug 23 04:15:56 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 23 Aug 2010 10:15:56 +0200 Subject: Open a command pipe for reading In-Reply-To: References: Message-ID: <4C722E3C.5010206@sschwarzer.net> Hi Rodrick, On 2010-08-17 18:40, Rodrick Brown wrote: > I have a fairly large file 1-2GB in size that I need to > process line by line but I first need to convert the file > to text using a 3rd party tool that prints the records > also line by line. > > I've tried using Popen to do this with no luck. I'm trying > to simulate > > /bin/foo myfile.dat Is foo the 3rd-party conversion tool you've mentioned? It would be good to have a bit more context, e. g. an actual snippet from your code. > And as the records are being printed do some calculations. > > pipe = Popen(exttool,shell=True,stdout=PIPE).stdout > > for data in pipe.readlines(): > print data, > > This operation blocks forever I'm guessing it's trying to > process the entire file at once. If you use `readlines` on a file object it reads the whole file at once and returns a list of the lines (including line end characters, by the way). What you probably want is for line in pipe: print line, which reads and prints the file contents line by line. Stefan From ldo at geek-central.gen.new_zealand Mon Aug 23 04:34:48 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 23 Aug 2010 20:34:48 +1200 Subject: Python Developer - HFT Trading firm - Chicago, IL References: <8dbb89Fi3fU1@mid.individual.net> Message-ID: In message <8dbb89Fi3fU1 at mid.individual.net>, Gregory Ewing wrote: > Lawrence D'Oliveiro wrote: > >> Someone who doesn?t understand how positive feedback can lead to >> instabilities in a dynamical system. > > Let's hope the person they hire makes it his first task > to introduce a big dollop of negative feedback into the > system! Actually the normal way to prevent instabilities is to add damping to leak the energy away. In an economic system, that?s generally called ?Government regulation?. From graemeglass at gmail.com Mon Aug 23 04:42:23 2010 From: graemeglass at gmail.com (Graeme Glass) Date: Mon, 23 Aug 2010 01:42:23 -0700 (PDT) Subject: psycopg2 for insertion of binary data to PostgreSQL database References: <4c703dd5$0$7655$9b4e6d93@newsspool1.arcor-online.net> <4c71804d$0$6880$9b4e6d93@newsspool2.arcor-online.net> <4c722526$0$6875$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Aug 23, 9:37?am, Julia Jacobson wrote: > How can I assign the result of a SQL query to a variable? > The following code snippet doesn't work: > query_result=cur.execute("SELECT column_name FROM table_name WHERE > my_variable = 'my_value'",) > > ?> Thomas Jollans wrote: > > > > > * get the record you're interested in You need to go and fetch the data now. query_result.fetchone() Take a look at the docs here, on how to fetch one vs many rows (fetchmany) http://initd.org/psycopg/docs/cursor.html#cursor.fetchone hth, Graeme From pDOTpagel at wzw.tum.de Mon Aug 23 05:03:35 2010 From: pDOTpagel at wzw.tum.de (Philipp Pagel) Date: Mon, 23 Aug 2010 09:03:35 +0000 (UTC) Subject: Creating a PYD file References: Message-ID: Rony wrote: > Is a PYD file created from Pyrex faster in execution then a PYD file > created from python source ? What do you mean? An African or European swallow? Of course it depends on your choice of algorithm, programmer ability.familarity with the respective langugage, ... cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://webclu.bio.wzw.tum.de/~pagel/ From easymakerere at gmail.com Mon Aug 23 05:08:50 2010 From: easymakerere at gmail.com (kimjeng) Date: Mon, 23 Aug 2010 02:08:50 -0700 (PDT) Subject: vpython References: Message-ID: On Aug 22, 7:38?am, Anssi Saari wrote: > kimjeng writes: > > the thing is i have installed gtkglextmm both from source and via a > > slackbuilds package script and i still get the same error, > > help would be a appreciated > > You'll just have to check what it is configure actually tests for and > figure out from that why your system doesn't pass. thanks here's something i noticed ... Package gtkglextmm-1.2 was not found in the pkg-config search path. Perhaps you should add the directory containing `gtkglextmm-1.2.pc' to the PKG_CONFIG_PATH environment variable No package 'gtkglextmm-1.2' found ... the configure script is looking for gtkglextmm-1.2.pc , a file that does not exist, what i do have is gtkglext-1.0.pc , im wondering why i have the 1.0. version while i built the 1.2. source , plus the 'mm' in the name is missing from the name of my .pc files thanks From jhullu at gmail.com Mon Aug 23 06:15:46 2010 From: jhullu at gmail.com (jacquesh) Date: Mon, 23 Aug 2010 03:15:46 -0700 (PDT) Subject: Global Hook for Window Creation and Destruction Message-ID: hello, I'm looking for a sample using a Global Hook for Window Creation and Destruction in python 2.6 in win32 env... I've found some samples in c# or delphi but nothing in python. I'll try to catch any WM_CREATE events, like pyHook do to catch event from keyboard and mouse... any idea ? thx From oss.elmar at googlemail.com Mon Aug 23 06:24:50 2010 From: oss.elmar at googlemail.com (Elmar Hinz) Date: Mon, 23 Aug 2010 12:24:50 +0200 Subject: Gentoo, Cygwin: Import Error time, cStringIO, Permission denied Message-ID: Hello all, I freshly subscribed to this list, because I search a solution for a very special problem. Is this the appropriate list? Context ====== I try if it is possible to bootstrap Gentoo Prefix, upon the Cygwin compatibility layer on Windows. Gentoo Prefix is not a virtual machine but a bundle of Gentoo programs compiled into a nonstandard directory on a host OS. IT is similar to Cygwin itself, but compiled from sources. I try to compile Prefix into Cygwin on Windows. This involves compiling python. The gentoo management tool "emerge" is done in python. However I am not a Python programmer myself, so I have some difficulties to understand what is going on. Problem ====== After compiling pyhton I run into errors when I start to use it in form of emerge. It says something like this in the logger module: Import Error sys, os, types, time, string, cStringIO, traceback. Permission denied. I researched the web. One discssion told to try it on the pyhton shell. I did the same. Only "time" and "cStringIO" are not imported. Looking into the compiled sources i find cStringIO.dll and time.dll. Both have the permissions 755. Hence permission to run them should be given. Is it a path problem? Are environment variables wrong? I would expect in that case python would complain "Modules not found" instead of "Permission denied". I am at the end of my wits now. Al From stefan_ml at behnel.de Mon Aug 23 06:34:45 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 23 Aug 2010 12:34:45 +0200 Subject: Creating a PYD file In-Reply-To: <201008192047.10460.thomas@jollybox.de> References: <201008192047.10460.thomas@jollybox.de> Message-ID: Thomas Jollans, 19.08.2010 20:47: > On Thursday 19 August 2010, it occurred to Rony to exclaim: >> Is a PYD file created from Pyrex faster in execution then a PYD file >> created from python source ? > > How do you plan to create an extension module (*.so, *.pyd on Windows) from > Python source then? You can try to compile it using Cython. Stefan From oss.elmar at googlemail.com Mon Aug 23 06:41:48 2010 From: oss.elmar at googlemail.com (Elmar Hinz) Date: Mon, 23 Aug 2010 12:41:48 +0200 Subject: Gentoo, Cygwin: Import Error time, cStringIO, Permission denied In-Reply-To: References: Message-ID: > Problem > ====== > > After compiling pyhton I run into errors when I start to use it in > form of emerge. It says something like this in the logger module: > > Import Error sys, os, types, time, string, cStringIO, traceback. > Permission denied. > > I researched the web. One discssion told to try it on the pyhton > shell. I did the same. Only "time" and "cStringIO" are not imported. > > Looking into the compiled sources i find cStringIO.dll and time.dll. > Both have the permissions 755. Hence permission to run them should be > given. > I tried something different. I tried to run emerge with Cygwins precompiled python. In this case I get a related but different error: fatal error - unable to map \\?\F:\cygwin\lib\pyhton2.6\lib-dynload\time.dll to same address as parent: 0x330000 != 0x3A0000 What does this mean? Is there a naming conflict between pythons time.dll and a time.dll of the windows system? Al From mail at johnohagan.com Mon Aug 23 06:47:56 2010 From: mail at johnohagan.com (John O'Hagan) Date: Mon, 23 Aug 2010 10:47:56 +0000 Subject: Helper classes design question Message-ID: <201008231047.57128.mail@johnohagan.com> I want to know the best way to organise a bunch of functions designed to operate on instances of a given class without cluttering the class itself with a bunch of unrelated methods. What I've done is make what I think are called helper classes, each of which are initialized with an instance of the main class and has methods which are all of the same type (insofar as they return a boolean, or modify the object in place, or whatever). I'm not sure if I'm on the right track here design-wise. Maybe this could be better done with inheritance (not my forte), but my first thought is that no, the helper classes (if that's what they are) are not actually a type of the main class, but are auxiliary to it. Here's what I've done: I have a class MySequence which is initialized with a number sequence (in a list), which has a bunch of methods which deal with various (musical) properties of the sequence. Toy example: class MySequence(object): """MySequence, a representation musical sequences as numbers. Its methods return various characteristics of the sequence.""" def __init__(self, sequence): self.pitches = sequence[:] def pcset(self): """Example method: The pitch class set derived from the sequence""" return sorted(list(set([ i % 12 for i in self.pitches]))) A generator function spits out MySequence objects, and I want to filter them (i.e. reject those which do not meet certain criteria) and then be able to modify them in various ways. For that I have two classes; toy examples: class SeqTest(object): """SeqTest, initialized with a MySequence object. Its methods return the boolean result of tests against the Sequence object.""" def __init__(self, myseq_obj): self.seq = myseq_obj def degrees(self, degrees): """Example method: Test for certain members, passed as list""" return all(i in self.seq.pcset() for i in degrees) class SeqMod(object): """A SeqMod object's methods modify in place the MySequence object with which it is initialized """ def __init__(self, myseq_obj): self.seq = myseq_obj def rotate(self, num): """Example method: Rotate pitches by n steps""" self.seq.pitches = self.seq.pitches[-num:] + self.seq.pitches[:-num] And here is a toy version of how I'm using them with the generator: def seq_factory(generator_func, test_opts, mod_opts): """Yields Sequence objects, filtered and modified. Opts are dictionaries.""" for sequence in generator_func: seq = MySequence(sequence) tester = SeqTest(seq) if any (not getattr(tester, opt)(value) for opt, value in test_opts.items()): continue modifier = SeqMod(seq) for opt, value in mod_opts.items(): getattr(modifier, opt)(value) yield seq Used, say, like this: generator_func = (range(n, n+5) for n in range(5)) test_opts = {'degrees': [5,7]} mod_opts = {'rotate': 3} for i in seq_factory(generator_func, test_opts, mod_opts): print i.pitches Which yields: [5, 6, 7, 3, 4] [6, 7, 8, 4, 5] It actually works well, so there's no real problem apart from wanting to know if this is a good way to do what I want. Thanks for any wise words, John From stefan_ml at behnel.de Mon Aug 23 07:02:01 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 23 Aug 2010 13:02:01 +0200 Subject: Creating a PYD file In-Reply-To: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> References: <7dfcb1a8-f296-4fc3-b212-4d25ec56e1c3@l14g2000yql.googlegroups.com> Message-ID: Rony, 19.08.2010 21:41: > The question actually is, is a PYD file created from C faster then a > PYD file from Pyrex ? Most likely, yes. However, when comparing to Cython instead of Pyrex, the answer really depends on your code. Cython cannot be faster than the equivalent C code, simply because it generates C code. However, if the Python call overhead matters (e.g. in thin wrappers around simple C functions), Cython easily wins because it uses various tweaks that you simply wouldn't write in your own C code. If the overhead can be ignored, hand tuned C code wins often but not always, with the obvious drawback of being much harder to write and much longer in lines of code. Generally speaking, if you can avoid it, don't write the extension in C. You'll have your Cython code hand optimised long before your C code is even close to running. And in the long run, the maintenance cost will always be the dominating factor anyway. Stefan From __peter__ at web.de Mon Aug 23 07:33:07 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Aug 2010 13:33:07 +0200 Subject: Helper classes design question References: Message-ID: John O'Hagan wrote: > I want to know the best way to organise a bunch of functions designed to > operate on instances of a given class without cluttering the class itself > with a bunch of unrelated methods. > > What I've done is make what I think are called helper classes, each of > which are initialized with an instance of the main class and has methods > which are all of the same type (insofar as they return a boolean, or > modify the object in place, or whatever). > > I'm not sure if I'm on the right track here design-wise. Maybe this could > be better done with inheritance (not my forte), but my first thought is > that no, the helper classes (if that's what they are) are not actually a > type of the main class, but are auxiliary to it. > > Here's what I've done: > > I have a class MySequence which is initialized with a number sequence (in > a list), which has a bunch of methods which deal with various (musical) > properties of the sequence. Toy example: > > class MySequence(object): > """MySequence, a representation musical sequences as numbers. > Its methods return various characteristics of the sequence.""" > def __init__(self, sequence): > self.pitches = sequence[:] > def pcset(self): > """Example method: The pitch class set > derived from the sequence""" > return sorted(list(set([ i % 12 for i in self.pitches]))) > > A generator function spits out MySequence objects, and I want to filter > them (i.e. reject those which do not meet certain criteria) and then be > able to modify them in various ways. For that I have two classes; toy > examples: > > class SeqTest(object): > """SeqTest, initialized with a MySequence object. Its methods > return the boolean result of tests against the Sequence object.""" > def __init__(self, myseq_obj): > self.seq = myseq_obj > def degrees(self, degrees): > """Example method: Test for certain members, passed as list""" > return all(i in self.seq.pcset() for i in degrees) > > class SeqMod(object): > """A SeqMod object's methods modify in place > the MySequence object with which it is initialized """ > def __init__(self, myseq_obj): > self.seq = myseq_obj > def rotate(self, num): > """Example method: Rotate pitches by n steps""" > self.seq.pitches = self.seq.pitches[-num:] + > self.seq.pitches[:-num] > > > And here is a toy version of how I'm using them with the generator: > > def seq_factory(generator_func, test_opts, mod_opts): > """Yields Sequence objects, filtered and modified. > Opts are dictionaries.""" > for sequence in generator_func: > seq = MySequence(sequence) > tester = SeqTest(seq) > if any (not getattr(tester, opt)(value) > for opt, value in test_opts.items()): > continue > modifier = SeqMod(seq) > for opt, value in mod_opts.items(): > getattr(modifier, opt)(value) > yield seq > > > Used, say, like this: > > generator_func = (range(n, n+5) for n in range(5)) > test_opts = {'degrees': [5,7]} > mod_opts = {'rotate': 3} > > for i in seq_factory(generator_func, test_opts, mod_opts): > print i.pitches > > Which yields: > > [5, 6, 7, 3, 4] > [6, 7, 8, 4, 5] > > It actually works well, so there's no real problem apart from wanting to > know if this is a good way to do what I want. > > Thanks for any wise words, As far as I can see the SeqMod and SeqTest classes don't keep any state apart from the sequence instance. Therefore functions instead of methods would do as well: from functools import partial class MySequence(object): def __init__(self, sequence): self.pitches = sequence[:] def pcset(self): return sorted(list(set([ i % 12 for i in self.pitches]))) def degrees(seq, degrees): return all(i in seq.pcset() for i in degrees) def rotate(seq, num): seq.pitches = seq.pitches[-num:] + seq.pitches[:-num] def seq_factory(sequences, tests, modifications): for seq in sequences: if all(test(seq) for test in tests): for modify in modifications: modify(seq) yield seq sequences = (MySequence(range(n, n+5)) for n in range(5)) tests = [ partial(degrees, degrees=[5,7]), # ... ] modifications = [ partial(rotate, num=3), # ... ] for i in seq_factory(sequences, tests, modifications): print i.pitches When you see that your module becomes too messy move the testing and modifying functions into separate modules that are part of the same package. Peter From oss.elmar at googlemail.com Mon Aug 23 07:37:44 2010 From: oss.elmar at googlemail.com (Elmar Hinz) Date: Mon, 23 Aug 2010 13:37:44 +0200 Subject: SOLVED: Gentoo, Cygwin: Import Error time, cStringIO, Permission denied Message-ID: I seem to talk to myself. So for the archives: This is no python thingy. It is a windows/cygwin one. The second error message brings good search results in the web. Search for: "cygwin, dll to same address as parent, rebaseall" Al From madhusoodan.shanbhag at gmail.com Mon Aug 23 07:50:01 2010 From: madhusoodan.shanbhag at gmail.com (Madhusoodan) Date: Mon, 23 Aug 2010 04:50:01 -0700 (PDT) Subject: DDE Module for Python 3.1.2 Message-ID: Hi Members, I am learning python 3.1.2 on windows XP. I wanted to do experiments on importing real time data from QuoteCenter with DDE. After searching relevant module, I found dde module only for Python 2.6, but not for 3.1.2. Kindly guide me if there is any other way I can communicate with DDE server for requesting data with Python 3.X. Thanks and Regards madhusoodan From parvini_navid at yahoo.com Mon Aug 23 08:00:02 2010 From: parvini_navid at yahoo.com (Navid Parvini) Date: Mon, 23 Aug 2010 05:00:02 -0700 (PDT) Subject: import a module in a destructor of a class Message-ID: <157673.25880.qm@web51006.mail.re2.yahoo.com> Dear All, I have a python module named "book.py" I want to import it in a destructor of a class. class Excel: ? ??? def __init__( self, ... ): ??????????? . . . ??? def __del__( self ): ????????? import book but I got error. Would you please help me? Can I import a module in a destructor? Thank you in advance. Regards, Navid -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Aug 23 08:02:01 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 23 Aug 2010 14:02:01 +0200 Subject: DDE Module for Python 3.1.2 In-Reply-To: References: Message-ID: Madhusoodan, 23.08.2010 13:50: > I am learning python 3.1.2 on windows XP. I wanted to do experiments > on importing real time data from QuoteCenter with DDE. What's DDE here? > After searching > relevant module, I found dde module only for Python 2.6, but not for > 3.1.2. Could you provide a link to the module, so that we know what module you are actually talking about? Also, if the project that provides the module has a mailing list, you might want to ask there. Stefan From mail at timgolden.me.uk Mon Aug 23 08:12:02 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 23 Aug 2010 13:12:02 +0100 Subject: DDE Module for Python 3.1.2 In-Reply-To: References: Message-ID: <4C726592.7010406@timgolden.me.uk> On 23/08/2010 13:02, Stefan Behnel wrote: > Madhusoodan, 23.08.2010 13:50: >> I am learning python 3.1.2 on windows XP. I wanted to do experiments >> on importing real time data from QuoteCenter with DDE. > > What's DDE here? It'll be Microsoft's Dynamic Data Exchange : http://msdn.microsoft.com/en-us/library/ms648711%28VS.85%29.aspx Didn't know anyone was still using it explicitly. > > >> After searching >> relevant module, I found dde module only for Python 2.6, but not for >> 3.1.2. > > Could you provide a link to the module, so that we know what module you > are actually talking about? I expect that'll be the dde module in the pywin32 packages: http://pywin32.cvs.sourceforge.net/viewvc/pywin32/pywin32/win32/Demos/dde/ I haven't run any tests against it, but it imports ok on my 3.1.2 instance (albeit after importing win32ui) TJG From clp2 at rebertia.com Mon Aug 23 08:33:58 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 23 Aug 2010 05:33:58 -0700 Subject: import a module in a destructor of a class In-Reply-To: <157673.25880.qm@web51006.mail.re2.yahoo.com> References: <157673.25880.qm@web51006.mail.re2.yahoo.com> Message-ID: On Mon, Aug 23, 2010 at 5:00 AM, Navid Parvini wrote: > Dear All, > > I have a python module named "book.py" I want to import it in a destructor of a class. > > class Excel: > > ??? def __init__( self, ... ): > ??????????? . . . > > ??? def __del__( self ): > ????????? import book > > but I got error. And the exact error message and exception traceback were...? Cheers, Chris -- Vagueness makes questions harder to answer. http://blog.rebertia.com From __peter__ at web.de Mon Aug 23 08:41:57 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Aug 2010 14:41:57 +0200 Subject: import a module in a destructor of a class References: <157673.25880.qm@web51006.mail.re2.yahoo.com> Message-ID: Navid Parvini wrote: > I have a python module named "book.py" I want to import it in a destructor > of a class. Why would you do that? > class Excel: > > def __init__( self, ... ): > . . . > > def __del__( self ): > import book > > but I got error. Would you please help me? Can I import a module in a > destructor? > > Thank you in advance. You may be able to avoid the ImportError by moving the instance from the global scope into a function, e. g. instead of e = Excel() # work with e do def main(): e = Excel() # work with e main() but the more appropriate answer is likely: Don't use __del__() at all. Peter From chris at simplistix.co.uk Mon Aug 23 09:10:29 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 23 Aug 2010 14:10:29 +0100 Subject: Sphinx cross reference question In-Reply-To: <4C716774.5090207@shopzeus.com> References: <4C716774.5090207@shopzeus.com> Message-ID: <4C727345.8010500@simplistix.co.uk> Laszlo Nagy wrote: > > In my shopzeus.db.pivot.convert.py file, in the run() method of my > Data2Facts class, I can write this into the docstring: ...you may have more joy asking about this on the Sphinx list: http://groups.google.com/group/sphinx-dev cheers, Chris From chris at simplistix.co.uk Mon Aug 23 09:16:14 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 23 Aug 2010 14:16:14 +0100 Subject: nested subparsers with argparse Message-ID: <4C72749E.1000706@simplistix.co.uk> Hi All, I'm looking to build a script that has command line options as follows: ./myscript.py command subcommand [options] I can do up to the command [options] bit with add_subparsers in argparse, but how do I then add a second level of subparsers? cheers, Chris From a.j.romanista at gmail.com Mon Aug 23 09:34:26 2010 From: a.j.romanista at gmail.com (Ata Jafari) Date: Mon, 23 Aug 2010 06:34:26 -0700 (PDT) Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: On Aug 20, 10:04?pm, Thomas Jollans wrote: > On Thursday 19 August 2010, it occurred to ata.jaf to exclaim: > > > > > On Aug 17, 11:55 pm, Thomas Jollans wrote: > > > On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim: > > > > I am developing a little program in Mac with wxPython. > > > > But I have problems with the characters that are not in ASCII. Like > > > > some special characters in French or Turkish. > > > > So I am looking for a way to solve this. Like an encoding standard > > > > that supports all languages. Or some other way. > > > > Anything that supports all of Unicode will do. Like UTF-8. If your text > > > is mostly Latin, then just go for UTF-8, if you use other alphabets > > > extensively, you might want to consider UTF-16, which might the use a > > > little less space. > > > OK, I used UTF-8. > > I write a line of strings in the source code and I want my program to > > show that as an output on GUI. And this line of strings includes a > > character like "?". But I see that in GUI this character is replaced > > with another strange characters. I mean it doesn't work. > > And when I try to use UTF-16, I get an syntax error that declares > > "UTF-16 stream does not start with BOM". > > I get the feeling you're not actually using the encoding you say you're using, > or not telling every program involved what you're doing. > > 1. Save the file in the correct encoding. Either tell your text editor to use > a specific encoding (UTF-8 would be a good choice), or find out what encoding > your text editor is using and use that encoding during the rest of the > process. > > 2. Tell Python which encoding you're using. The coding: line will do the > trick, *provided* you don't lie, and the encoding your specify in the file is > actually the encoding you're using to store the file on disk. > > 3. Instruct your GUI library to do the right thing. If you use unicode strings > (either by using Python 3 or by using the u"K?se" syntax in Python 2), that > should be enough, otherwise, if you're using byte strings, which you shouldn't > be doing in this case, you might have to tell the library what you're doing, > or use the customary encoding. (For GTK+, this is UTF-8. For other libraries, > it might be Latin-1, or system-dependent) Finally I did it. I was doing some stupid mistakes. Thanks alot. Ata From fmanley at gmail.com Mon Aug 23 09:45:04 2010 From: fmanley at gmail.com (Frederick Manley) Date: Mon, 23 Aug 2010 09:45:04 -0400 Subject: IDLE will not startup after upgrading Python on Mac OS X Message-ID: I have snow leopard and a brand new mac book pro. After running python from x11, I saw that I had python 2.5.1 installed on this laptop, so went to python.org to download Python 2.7, as I was "strongly encouraged" to do on the website. The problem is that Mac doesn't come with a text editor for writing programs. TextEdit won't allow you to save files with the ".py" extension. So IDLE is really my only choice. The only problem is, whenever I start it up (I've tried starting it from the Terminal and double clicking the icon) I get the following message: "Idle's subprocess cannot make connection. Either Idle can't start a subprocess or a personal firewall is blocking the connection." Searching various programming forums came up with similar problems users have had in windows, but I couldn't find any information on how to fix this problem on a mac with OSX. Please help. Thanks, Fred -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Mon Aug 23 09:55:31 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 23 Aug 2010 06:55:31 -0700 (PDT) Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: On Aug 21, 8:10?am, Tim Golden wrote: > On 20/08/2010 11:54 PM, vsoler wrote: > > > I'am testing your library. I am mainly interested in knowing the > > access attributes of directories in the local(C:\) or shared unit(W:\) > > of my system. > > > Using your script with 'c:\\' I get an error message saying... 'file > > exists but it is a directory' and I cannot go any further. > > > Of course, the problem is that I am using "fs.file" when I should be > > using something different. > > Either use fs.dir (if you know it's a directory) or fs.entry (if it > could be a file or a directory; the code will dispatch to the right one). > > If you only want the directories immediately some directory, > you could do this: > > > from winsys import fs, security > > root = fs.file (sys.executable).path ?# or fs.dir ("w:/") etc. > for d in root.dirs (ignore_access_errors=True): > ? ?print (d, "=>", d.security ()) # or whatever > > > > If you want to walk the tree of directories looking at permissions, then: > > > import os, sys > from winsys import fs > > root = fs.file (sys.executable).path > for dirpath, _, _ in root.walk (): > ? ?print (dirpath, "=>", dirpath.security ()) > > > > > Reading the doc I have found that I should be using os.walk(...), > > which works, but then I cannot use fs.file > > In fact, even if you did for some reason use os.walk, you can > easily wrap the returned filenames using fs.entry: > > > import os, sys > from winsys import fs > > root = os.path.dirname (sys.executable) > for dirpath, filenames, dirnames in os.walk (root): > ? ?print (dirpath, "=>", fs.entry (dirpath).security ()) > > > > TKG Tim, One of your scripts still does not work on my system: ==> If you want to walk the tree of directories looking at permissions, then: import os, sys from winsys import fs root = fs.file (sys.executable).path for dirpath, _, _ in root.walk (): print (dirpath, "=>", dirpath.security ()) However, I get the following error: Traceback (most recent call last): File "C:/Local/test4.py", line 5, in root = fs.file (r'W:\FRIB\ELPR\$DATA\DPT-FINANZAS').path File "C:\Program Files\Python31\lib\site-packages\winsys\fs.py", line 1775, in file raise x_fs (None, "file", "%s exists but is a directory" % filepath) winsys.fs.x_fs: (None, 'file', 'W:\\FRIB\\ELPR\\$DATA\\DPT-FINANZAS exists but is a directory') That is, I am interested in looking for directories, but the problem is that the path is a directory. I'm sure there must be some way to get around this problem. Thank you Vicente Soler From dsdale24 at gmail.com Mon Aug 23 09:58:16 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Mon, 23 Aug 2010 06:58:16 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X Message-ID: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> The following script runs without problems on Ubuntu and Windows 7. h5py is a package wrapping the hdf5 library (http://code.google.com/p/ h5py/): from multiprocessing import Pool import h5py def update(i): print i def f(i): "hello foo" return i*i if __name__ == '__main__': pool = Pool() for i in range(10): pool.apply_async(f, [i], callback=update) pool.close() pool.join() On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to comment out the as-yet unused h5py import, otherwise I get a traceback: Exception in thread Thread-1: Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/threading.py", line 532, in __bootstrap_inner self.run() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/threading.py", line 484, in run self.__target(*self.__args, **self.__kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/multiprocessing/pool.py", line 226, in _handle_tasks put(task) PicklingError: Can't pickle : attribute lookup __builtin__.function failed I've searched that pickle error and found some references to pickling a lambda, but I don't think that is the issue. There are no lambdas in the h5py module, and the script runs fine on windows and linux. I need access to both multiprocessing and h5py objects in the same module, so I can register a callback that saves the results to an hdf5 file. Are there any suggestions as to what could be the problem, or suggestions on how I can track it down? Thanks, Darren From mahaboobnisha at gmail.com Mon Aug 23 09:59:01 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Mon, 23 Aug 2010 06:59:01 -0700 (PDT) Subject: comp.lang.python Message-ID: <190fadcc-250d-454a-a0a5-62dd98829e24@u31g2000pru.googlegroups.com> www.127760.blogspot.com From benjamin.kaplan at case.edu Mon Aug 23 10:05:36 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 23 Aug 2010 10:05:36 -0400 Subject: IDLE will not startup after upgrading Python on Mac OS X In-Reply-To: References: Message-ID: On Mon, Aug 23, 2010 at 9:45 AM, Frederick Manley wrote: > I have snow leopard and a brand new mac book pro. ?After running python from > x11, I saw that I had python 2.5.1 installed on this laptop, That should be 2.6.1 if you're on Snow Leopard. Also, why were you running Python from an xterm? Just use Terminal.app. > so went to > python.org to download Python 2.7, as I was "strongly encouraged" to do on > the website. > The problem is that Mac doesn't come with a text editor for writing > programs. ?TextEdit won't allow you to save files with the ".py" extension. Yes it will. You just have to turn it to plain text mode first. It's in the format menu. Then, just add the .py extension to the file name when you go to save it. You'll get an annoying little "do you want to use .py or .txt" message box. > ?So IDLE is really my only choice. Vim and emacs are both installed on the machine. Or you can install MacVim. Or whatever GUI version of Emacs there is. Or you can install TextMate if you don't want to learn those. Or you can install XCode or Eclipse+PyDev if you want an IDE. Or Eric or Komodo Edit. Or any of a dozen others. >The only problem is, whenever I start it > up (I've tried starting it from the Terminal and double clicking the icon) I > get the following message: > "Idle's subprocess cannot make connection. ?Either Idle can't start a > subprocess or a personal firewall is blocking the connection." > Searching various programming forums came up with similar problems users > have had in windows, but I couldn't find any information on how to fix this > problem on a mac with OSX. ?Please help. >From the title, this may be relevant, but I'm not sure because I'm having trouble accessing the bug tracker right now. http://bugs.python.org/issue9227 Also, this one: http://bugs.python.org/issue9620 > Thanks, > Fred > -- > http://mail.python.org/mailman/listinfo/python-list > > From mail at timgolden.me.uk Mon Aug 23 10:07:03 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 23 Aug 2010 15:07:03 +0100 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: <4C728087.3080500@timgolden.me.uk> On 23/08/2010 14:55, vsoler wrote: > On Aug 21, 8:10 am, Tim Golden wrote: >> On 20/08/2010 11:54 PM, vsoler wrote: >> >>> I'am testing your library. I am mainly interested in knowing the >>> access attributes of directories in the local(C:\) or shared unit(W:\) >>> of my system. >> >>> Using your script with 'c:\\' I get an error message saying... 'file >>> exists but it is a directory' and I cannot go any further. >> >>> Of course, the problem is that I am using "fs.file" when I should be >>> using something different. >> >> Either use fs.dir (if you know it's a directory) or fs.entry (if it >> could be a file or a directory; the code will dispatch to the right one). >> >> If you only want the directories immediately some directory, >> you could do this: >> >> >> from winsys import fs, security >> >> root = fs.file (sys.executable).path # or fs.dir ("w:/") etc. >> for d in root.dirs (ignore_access_errors=True): >> print (d, "=>", d.security ()) # or whatever >> >> >> >> If you want to walk the tree of directories looking at permissions, then: >> >> >> import os, sys >> from winsys import fs >> >> root = fs.file (sys.executable).path >> for dirpath, _, _ in root.walk (): >> print (dirpath, "=>", dirpath.security ()) >> >> >> >>> Reading the doc I have found that I should be using os.walk(...), >>> which works, but then I cannot use fs.file >> >> In fact, even if you did for some reason use os.walk, you can >> easily wrap the returned filenames using fs.entry: >> >> >> import os, sys >> from winsys import fs >> >> root = os.path.dirname (sys.executable) >> for dirpath, filenames, dirnames in os.walk (root): >> print (dirpath, "=>", fs.entry (dirpath).security ()) >> >> >> >> TKG > > Tim, > > One of your scripts still does not work on my system: > > > ==> If you want to walk the tree of directories looking at > permissions, then: > > > import os, sys > from winsys import fs > > root = fs.file (sys.executable).path > for dirpath, _, _ in root.walk (): > print (dirpath, "=>", dirpath.security ()) > > > However, I get the following error: > > Traceback (most recent call last): > File "C:/Local/test4.py", line 5, in > root = fs.file (r'W:\FRIB\ELPR\$DATA\DPT-FINANZAS').path > File "C:\Program Files\Python31\lib\site-packages\winsys\fs.py", > line 1775, in file > raise x_fs (None, "file", "%s exists but is a directory" % > filepath) > winsys.fs.x_fs: (None, 'file', 'W:\\FRIB\\ELPR\\$DATA\\DPT-FINANZAS > exists but is a directory') > > That is, I am interested in looking for directories, but the problem > is that the path is a directory. > > I'm sure there must be some way to get around this problem. Replace fs.file by fs.entry: the latter detects automatically whether it's looking at a file or at a directory. I used fs.file in my example because I *know&* what sys.executable must be a file (python.exe). In your case, either use fs.dir if you know it's a directory or fs.entry if it could be either. (Obviously fs.entry must do some work to determine which it is, so you can optimise slightly by specifying fs.dir / fs.file) TJG From chris at simplistix.co.uk Mon Aug 23 10:19:30 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 23 Aug 2010 15:19:30 +0100 Subject: nested subparsers with argparse In-Reply-To: <4C72749E.1000706@simplistix.co.uk> References: <4C72749E.1000706@simplistix.co.uk> Message-ID: <4C728372.4020504@simplistix.co.uk> Chris Withers wrote: > Hi All, > > I'm looking to build a script that has command line options as follows: > > ./myscript.py command subcommand [options] > > I can do up to the command [options] bit with add_subparsers in > argparse, but how do I then add a second level of subparsers? Answering my own question, here's what worked for me: """ from argparse import ArgumentParser from mock import Mock m = Mock() parser = ArgumentParser() subparsers = parser.add_subparsers() agroup = subparsers.add_parser('a') command = subparsers.add_parser('b') command.set_defaults(func=m.b) subparsers = agroup.add_subparsers() command = subparsers.add_parser('aa') command.set_defaults(func=m.a.a) command = subparsers.add_parser('ab') command.set_defaults(func=m.a.b) options = parser.parse_args() options.func(options) print m.method_calls """ If there's anything I could have done better, please let me know! Chris From __peter__ at web.de Mon Aug 23 10:21:44 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Aug 2010 16:21:44 +0200 Subject: nested subparsers with argparse References: Message-ID: Chris Withers wrote: > I'm looking to build a script that has command line options as follows: > > ./myscript.py command subcommand [options] > > I can do up to the command [options] bit with add_subparsers in > argparse, but how do I then add a second level of subparsers? It looks like subparsers behave like the toplevel parsers -- you can invoke add_subparsers() on them, too. From burton at userful.com Mon Aug 23 11:09:24 2010 From: burton at userful.com (Burton Samograd) Date: Mon, 23 Aug 2010 09:09:24 -0600 Subject: vpython References: Message-ID: kimjeng writes: > On Aug 22, 7:38?am, Anssi Saari wrote: >> kimjeng writes: >> > the thing is i have installed gtkglextmm both from source and via a >> > slackbuilds package script and i still get the same error, >> > help would be a appreciated >> >> You'll just have to check what it is configure actually tests for and >> figure out from that why your system doesn't pass. > > thanks > here's something i noticed > > ... > Package gtkglextmm-1.2 was not found in the pkg-config search path. > Perhaps you should add the directory containing `gtkglextmm-1.2.pc' > to the PKG_CONFIG_PATH environment variable > No package 'gtkglextmm-1.2' found > ... > > the configure script is looking for gtkglextmm-1.2.pc , a file that > does not exist, what i do have is gtkglext-1.0.pc , im wondering why > i have the 1.0. version while i built the 1.2. source , plus the 'mm' > in the name is missing from the name of my .pc files > thanks The mm in the name is for a C++ binding for the library. Make sure you install both gtkglext and gtkglextmm packages. -- Burton From joncle at googlemail.com Mon Aug 23 11:35:11 2010 From: joncle at googlemail.com (Jon Clements) Date: Mon, 23 Aug 2010 08:35:11 -0700 (PDT) Subject: Using String Methods In Jump Tables References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: On 20 Aug, 01:51, Tim Daneliuk wrote: > On 8/19/2010 7:23 PM, Steven D'Aprano wrote: > > > On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: > > >> Problem: > > >> ? Given tuples in the form (key, string), use 'key' to determine what > >> ? string method to apply to the string: > > >>>> table = {'l': str.lower, 'u': str.upper} > >>>> table['u']('hello world') > > 'HELLO WORLD' > > Aha! ?That's just what I was looking for. > > > > > [...] > >> As I said, I know I could do this as a set of cascading ifs or even as > >> an eval, but I'm loathe to use such approaches. I like jump tables as a > >> structural construct because they are easy to understand and maintain. I > >> also realize that what I'm asking may be violating some deeply held > >> notion of OO purity, but, well, now I'm just curious if there is a way > >> to do this > > > This is Python, not some "pure" OO language. We have functional > > programming constructs, procedural constructs, and probably other > > programming models as well. Screw the deeply held notion of OO purity :) > > Yeah, I've never been much impressed with the OO purists. ?One of > the best speeches on the subject I ever saw was by David Korn (of > ksh fame) who did a presentation at USENIX one year called "Objecting > To Objects". ?He documented an attempt to write a compiler using > purely OO constructs and the many rings of hell that ensued. ? > > > > > But seriously, Python's object model includes bound and unbound methods > > precisely so you can do this sort of thing, and the above table-based > > approach is very common and recommended as an alternative to case/switch > > statements. It's a very common Pythonic idiom, so never fear that people > > will stone you for using it. > > +1 > > > > > The only thing that is a bit unusual is that you call it a jump table. In > > my experience, "Jump Table" is used for low-level languages where the > > table values are memory addresses. > > Yeah ... those old assembler memories never quite fade do they. > I dunno what you might call this. ?A Function Dispatch Table > perhaps? > > Thanks to both you and Chris for setting me straight :) > > -- > ------------------------------------------------------------------------ > Tim Daneliuk > tun... at tundraware.com Another more generic option would be to use methodcaller from the operator module. Just my 2p, Jon. From tundra at tundraware.com Mon Aug 23 11:57:08 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 23 Aug 2010 10:57:08 -0500 Subject: Using String Methods In Jump Tables In-Reply-To: References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: On 8/23/2010 10:35 AM, Jon Clements wrote: > On 20 Aug, 01:51, Tim Daneliuk wrote: >> On 8/19/2010 7:23 PM, Steven D'Aprano wrote: >> >>> On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: >> >>>> Problem: >> >>>> Given tuples in the form (key, string), use 'key' to determine what >>>> string method to apply to the string: >> >>>>>> table = {'l': str.lower, 'u': str.upper} >>>>>> table['u']('hello world') >>> 'HELLO WORLD' >> >> Aha! That's just what I was looking for. >> >> >> >>> [...] >>>> As I said, I know I could do this as a set of cascading ifs or even as >>>> an eval, but I'm loathe to use such approaches. I like jump tables as a >>>> structural construct because they are easy to understand and maintain. I >>>> also realize that what I'm asking may be violating some deeply held >>>> notion of OO purity, but, well, now I'm just curious if there is a way >>>> to do this >> >>> This is Python, not some "pure" OO language. We have functional >>> programming constructs, procedural constructs, and probably other >>> programming models as well. Screw the deeply held notion of OO purity :) >> >> Yeah, I've never been much impressed with the OO purists. One of >> the best speeches on the subject I ever saw was by David Korn (of >> ksh fame) who did a presentation at USENIX one year called "Objecting >> To Objects". He documented an attempt to write a compiler using >> purely OO constructs and the many rings of hell that ensued. >> >> >> >>> But seriously, Python's object model includes bound and unbound methods >>> precisely so you can do this sort of thing, and the above table-based >>> approach is very common and recommended as an alternative to case/switch >>> statements. It's a very common Pythonic idiom, so never fear that people >>> will stone you for using it. >> >> +1 >> >> >> >>> The only thing that is a bit unusual is that you call it a jump table. In >>> my experience, "Jump Table" is used for low-level languages where the >>> table values are memory addresses. >> >> Yeah ... those old assembler memories never quite fade do they. >> I dunno what you might call this. A Function Dispatch Table >> perhaps? >> >> Thanks to both you and Chris for setting me straight :) >> >> -- >> ------------------------------------------------------------------------ >> Tim Daneliuk >> tun... at tundraware.com > > Another more generic option would be to use methodcaller from the > operator module. > > Just my 2p, > > Jon. Could you say a bit more about just why you prefer this approach? Clearly, it *is* more generic, but in looking it over, it seems that methodcaller is less readable and intuitive ... at least to my eyes ... -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From psdasilva.nospam at netcabonospam.pt Mon Aug 23 12:07:48 2010 From: psdasilva.nospam at netcabonospam.pt (Paulo da Silva) Date: Mon, 23 Aug 2010 17:07:48 +0100 Subject: What is a class method? In-Reply-To: References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: <4c729cd7$0$18263$a729d347@news.telepac.pt> Em 23-08-2010 06:16, Ian Kelly escreveu: > On Sun, Aug 22, 2010 at 9:53 PM, Paulo da Silva > wrote: >> Em 23-08-2010 04:30, James Mills escreveu: >>> On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva >>> wrote: >>>> I understand the concept of a static method. >>>> However I don't know what is a class method. >>>> Would anybody pls. explain me? >>> >>> Please read this first: >>> http://docs.python.org/library/functions.html#classmethod >>> >>> Then ask us questions :) >> >> I did it before posting ... >> The "explanation" is not very clear. It is more like "how to use it". > > Consider this: > > class A(object): > @staticmethod > def new(): > return A() > > class B(A): > pass > > versus this: > > class C(object): > @classmethod > def new(cls): > return cls() > > class D(C): > pass > > B.new() will return a new instance of A, not B. D.new() will return a > new instance of D. > > Does this answer your question? Yes. Thank you very much. From denisg640 at gmail.com Mon Aug 23 12:31:11 2010 From: denisg640 at gmail.com (Denis Gomes) Date: Mon, 23 Aug 2010 12:31:11 -0400 Subject: What is a class method? In-Reply-To: <4c721434$0$1668$742ec2ed@news.sonic.net> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> <4c721434$0$1668$742ec2ed@news.sonic.net> Message-ID: John, I agree with you and I also think the definition given on the official python site is somewhat confusing, at least for an engineer like myself. But I'll take a stab at explaning it using what I know thus far. I think to understand what a class method is you have to first understand what a class variable is. Take this code snippet for example. class foo(object): x=10 def __init__(self): self.x=20 In this example if you create an instance of foo and call it f. You can access the instance attribute x by using f.x or you can access the class variable using the notation foo.x. These two will give you two different results. Now lets do something a bit more interesting. Say you have the following snippet. class foo(object): x=0 def __init__(self): self.x=10 foo.x+=1 >>>f=foo() >>>g=goo() >>>f.x 10 >>>g.x 10 >>>foo.x 2 What happened here is that the class variable foo.x is used to keep a count of the total number of instances created. So we see that a class variable can be looked at as what "connects" the two instances in a way, so that data can be shared between instances of the same class. This defintion may very well only apply to this case, but I think the mechanics is fundamentally the same. Keeping this in mind, lets make the jump to class methods. When an instance of a class is created, the methods are just functions that "work on" the attributes (the variables). Similarly, a class method is a method that works on a class variable. For example, class foo(object): x=10 def __init__(self): self.x=20 @classmethod def change(self): self.x=15 >>>f=foo() >>>f.x 20 >>>foo.x 10 >>>f.change() >>>f.x 20 >>>foo.x 15 So this is my explanation for what a classmethod is. Hope it helps. Good luck. Denis On Mon, Aug 23, 2010 at 2:24 AM, John Nagle wrote: > On 8/22/2010 9:16 PM, James Mills wrote: > >> On Mon, Aug 23, 2010 at 1:53 PM, Paulo da Silva >> >> wrote: >> >>> I did it before posting ... >>> >>> The "explanation" is not very clear. It is more like "how to use it". >>> >> >> Without going into the semantics of languages basically the >> differences are quite clear: >> >> @classmethod is a decorator that warps a function with >> passes the class as it's first argument. >> >> @staticmethod (much like C++/Java) is also a decorator that >> wraps a function but does not pass a class or instance as >> it's first argument. >> > > That reads like something the C++ standards revision committee > would dream up as they add unnecessary template gimmicks to the > language. > > John Nagle > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Aug 23 13:10:00 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Aug 2010 13:10:00 -0400 Subject: IDLE will not startup after upgrading Python on Mac OS X In-Reply-To: References: Message-ID: On 8/23/2010 10:05 AM, Benjamin Kaplan wrote: >> From the title, this may be relevant, but I'm not sure because I'm > having trouble accessing the bug tracker right now. > http://bugs.python.org/issue9227 > > Also, this one: > http://bugs.python.org/issue9620 Tracker is still down (site maintainers have been informed). I believe one of those may have helpful info when it is back up. -- Terry Jan Reedy From thomas at jollybox.de Mon Aug 23 13:22:46 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 23 Aug 2010 19:22:46 +0200 Subject: Helper classes design question In-Reply-To: <201008231047.57128.mail@johnohagan.com> References: <201008231047.57128.mail@johnohagan.com> Message-ID: <201008231922.46898.thomas@jollybox.de> On Monday 23 August 2010, it occurred to John O'Hagan to exclaim: > I want to know the best way to organise a bunch of functions designed to > operate on instances of a given class without cluttering the class itself > with a bunch of unrelated methods. > > What I've done is make what I think are called helper classes, each of > which are initialized with an instance of the main class and has methods > which are all of the same type (insofar as they return a boolean, or > modify the object in place, or whatever). > > I'm not sure if I'm on the right track here design-wise. Maybe this could > be better done with inheritance (not my forte), but my first thought is > that no, the helper classes (if that's what they are) are not actually a > type of the main class, but are auxiliary to it. You could try using mixins. I don't know how well this fits with the problem at hand, but what you'd do is this: Instead of thinking of the bits you're writing as helper classes, think of them as more or less isolated pieces of the functionality you'd like the final object to have. You can implement these independently, operating on self instead of on self.seq or something like that. Have a look at the abc module (abstract base classes) for a nifty way to prevent instantiation of these classes. If the functionality you're implementing only makes sense for a sequence, or for a sequence with certain characteristics, you can define an ABC that represents/specifies those characteristics and inherit from that. Or maybe not. Then, you have a bunch of largely independent classes providing isolated pieces of functionality, which you can then combine into one class by inheriting from ALL of them, and implementing the missing methods, like a constructor. Let's draw a graph: MySuperDuperCoolSequenceThing / / \ \ Filtered Rotated Tap \ \ / / \ | AbstractSequence KitchenSink \ / object I hope you understood at least a bit of my ramblings. Cheers, Thomas From Sang-Ho.Yun at jpl.nasa.gov Mon Aug 23 13:37:03 2010 From: Sang-Ho.Yun at jpl.nasa.gov (Sang-Ho Yun) Date: Mon, 23 Aug 2010 10:37:03 -0700 Subject: Save/load like matlab? Message-ID: I wonder if there is a way to save and load all python variables just like matlab does, so I can build a code step by step by loading previous states. I am handling a python processing code for very large files and multiple processing steps. Each time I find a bug, I have to run the whole thing again, which is time consuming. Thank you, Sang-Ho From leon at dcs.shef.ac.uk Mon Aug 23 13:38:02 2010 From: leon at dcs.shef.ac.uk (Leon Derczynski) Date: Mon, 23 Aug 2010 10:38:02 -0700 (PDT) Subject: Discarding STDERR generated during subprocess.popen Message-ID: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> Hi, I would like to run an external program, and discard anything written to stderr during its execution, capturing only stdout. My code currently looks like: def blaheta_tag(filename): blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/' process = subprocess.Popen([blaheta_dir + 'exec/funcTag', blaheta_dir + 'data/', filename], cwd=blaheta_dir, stdout=subprocess.PIPE) process.wait() return process.communicate()[0] This returns stdout, and stderr ends up printing to the console. How can I disregard anything sent to stderr such that it doesn't appear on the console? Thanks From tjreedy at udel.edu Mon Aug 23 13:41:02 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Aug 2010 13:41:02 -0400 Subject: Using String Methods In Jump Tables In-Reply-To: References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: On 8/23/2010 11:57 AM, Tim Daneliuk wrote: > On 8/23/2010 10:35 AM, Jon Clements wrote: >> Another more generic option would be to use methodcaller from the >> operator module. > Could you say a bit more about just why you prefer this approach? > Clearly, it *is* more generic, but in looking it over, it seems that > methodcaller is less readable and intuitive ... at least to my eyes ... He did not say 'preferable', only more generic, as you agree, and the generic solution, buried away in operator, is a good thing to know about. The OP wanted to convert (methodname, string) pairs to a call of methodname on strings. Since there is only one class, str, involved, mapping methodname to str.methodname works. If, for instance, the OP instead had to map (methodname, bytes_or_string) to a call, a not unreasonable generalization, str.methodname does not work (with bytes) but methodcaller(methodname) will, with bytes or string. >>> methodcaller('upper')(b'abc') b'ABC' >>> methodcaller('upper')('abc') 'ABC' -- Terry Jan Reedy From mailtome200420032002 at gmail.com Mon Aug 23 13:43:56 2010 From: mailtome200420032002 at gmail.com (aj) Date: Mon, 23 Aug 2010 10:43:56 -0700 (PDT) Subject: make install DESTDIR References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> Message-ID: <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> Thanks for reply Thomas. I am running make install DESTDIR=/home/foo/ bar. Martin- Asking for help :) On Aug 21, 4:43?am, "Martin v. Loewis" wrote: > > The whole point of DESTDIR is that it should be prepended to all > > installed paths, but the binaries should not contain any references to > > it.DESTDIR is commonly used by packagers, for example, to allow > > installation without superuser privileges. > > So what is the point of your messages? Do you want to report a problem? > Are you asking for help? Do you want to vent frustration? > > Regards, > Martin From thomas at jollybox.de Mon Aug 23 13:53:40 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 23 Aug 2010 19:53:40 +0200 Subject: Discarding STDERR generated during subprocess.popen In-Reply-To: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> References: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> Message-ID: <201008231953.41180.thomas@jollybox.de> On Monday 23 August 2010, it occurred to Leon Derczynski to exclaim: > Hi, > > I would like to run an external program, and discard anything written > to stderr during its execution, capturing only stdout. My code > currently looks like: > > def blaheta_tag(filename): > blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/' > process = subprocess.Popen([blaheta_dir + 'exec/funcTag', > blaheta_dir + 'data/', filename], cwd=blaheta_dir, > stdout=subprocess.PIPE) > process.wait() > return process.communicate()[0] > > This returns stdout, and stderr ends up printing to the console. How > can I disregard anything sent to stderr such that it doesn't appear on > the console? Read it into a pipe as well, and then ignore. Or, if you're targeting only UNIX-like systems, open /dev/null for writing and redirect the output there. From dan.kluev at gmail.com Mon Aug 23 14:16:43 2010 From: dan.kluev at gmail.com (Daniel Kluev) Date: Tue, 24 Aug 2010 05:16:43 +1100 Subject: Discarding STDERR generated during subprocess.popen In-Reply-To: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> References: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> Message-ID: On Tue, Aug 24, 2010 at 4:38 AM, Leon Derczynski wrote: > Hi, > > I would like to run an external program, and discard anything written > to stderr during its execution, capturing only stdout. My code > currently looks like: > > def blaheta_tag(filename): > blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/' > process = subprocess.Popen([blaheta_dir + 'exec/funcTag', > blaheta_dir + 'data/', filename], cwd=blaheta_dir, > stdout=subprocess.PIPE) > process.wait() > return process.communicate()[0] > > This returns stdout, and stderr ends up printing to the console. How > can I disregard anything sent to stderr such that it doesn't appear on > the console? > Just add `stderr=subprocess.PIPE` keyword in the Popen call. -- With best regards, Daniel Kluev -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.koda at gmail.com Mon Aug 23 14:22:21 2010 From: python.koda at gmail.com (Alban Nona) Date: Mon, 23 Aug 2010 14:22:21 -0400 Subject: Replace multiple lines in a txt file. Message-ID: Hi everybody, I would like to know if its possible to modify a list of entry that is define into a list and replace it by another list ? I try this piece of code, but Im pretty sure I messed something: http://pastebin.com/HfdkGeB3 Any help appreciated, Thank you :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From empwanted at cox.net Mon Aug 23 14:45:58 2010 From: empwanted at cox.net (empwanted at cox.net) Date: Mon, 23 Aug 2010 11:45:58 -0700 Subject: Start up company is looking for an experianced Django web developer . Message-ID: <20100823144558.AUPWA.560488.imail@fed1rmwml40> Hi Everyone, Our company is looking for an experienced full time Django programmer to work with our development team on a contract basis. We are a start up that is developing a large web application with extensive database interfaces. We are based in the US so living in the US is a plus. The existing application is partially completed using Django, Centos 5, Postgresql 8.4, SVN, and Jquery. This contract position could lead to a full time position with our new company. If you?ve got expert skills in Django, HTML, Jquery, CSS and overall web development and design, we?d like to hear from you. If you are interested please send your resume or work experience to empwanted at cox.net Please include your expected hourly or weekly rate. Accepted applicants will be required to sign a non-disclosure agreement. From emile at fenx.com Mon Aug 23 15:13:15 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 23 Aug 2010 12:13:15 -0700 Subject: Replace multiple lines in a txt file. In-Reply-To: References: Message-ID: On 8/23/2010 11:22 AM Alban Nona said... > Hi everybody, > > I would like to know if its possible to modify a list of entry that is > define into a list and replace it by another list ? > I try this piece of code, but Im pretty sure I messed something: > > http://pastebin.com/HfdkGeB3 > > The code you posted references variables not defined within the snippet, so it's hard to guess what may be wrong. Emile From jyoung79 at kc.rr.com Mon Aug 23 15:15:44 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Mon, 23 Aug 2010 19:15:44 +0000 Subject: Working with PDFs? Message-ID: <20100823191544.DVI43.197922.root@cdptpa-web24-z02> > writes: >> - Pull out text from each PDF page (to search for specific words) >> - Combine separate pdf documents into one document >> - Add bookmarks (with destination settings) > PDF Shuffler is a Python app which does PDF merging and splitting very > well. I don't think it does anything else, though, but maybe that's > where your code comes in? Thank you Anssi, MRAB, Terry and Geremy for your replies. I've been researching the apps you have recommended. Just curious if anyone has used pyPdf? While testing this, it seems to work pretty well for combining pdf files (seems to keep the annotation notes nicely also) and pulling out the text contents. I'm not sure I'm going to be able to find anything that can add bookmarks though. If you have used pyPdf, would you mind sharing your thoughts about it? Thanks. Jay From emile at fenx.com Mon Aug 23 15:18:00 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 23 Aug 2010 12:18:00 -0700 Subject: Replace multiple lines in a txt file. In-Reply-To: References: Message-ID: On 8/23/2010 12:13 PM Emile van Sebille said... > On 8/23/2010 11:22 AM Alban Nona said... >> Hi everybody, >> >> I would like to know if its possible to modify a list of entry that is >> define into a list and replace it by another list ? >> I try this piece of code, but Im pretty sure I messed something: >> >> http://pastebin.com/HfdkGeB3 >> >> > > The code you posted references variables not defined within the snippet, > so it's hard to guess what may be wrong. > > Emile > One thing stands out -- fopen = open(_path).read() for passe in _passeFettel: fopen.write(re.sub(passe, _fileFettel) fopen contains the data read from _path and certainly has no write method. Emile From fetchinson at googlemail.com Mon Aug 23 15:44:00 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 23 Aug 2010 21:44:00 +0200 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: > I wonder if there is a way to save and load all python variables just like > matlab does, so I can build a code step by step by loading previous states. > > I am handling a python processing code for very large files and multiple > processing steps. Each time I find a bug, I have to run the whole thing > again, which is time consuming. Perhaps pickle is the thing you are looking for? http://docs.python.org/library/pickle.html HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From stef.mientki at gmail.com Mon Aug 23 15:54:37 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 23 Aug 2010 21:54:37 +0200 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: <4C72D1FD.1020009@gmail.com> On 23-08-2010 21:44, Daniel Fetchinson wrote: >> I wonder if there is a way to save and load all python variables just like >> matlab does, so I can build a code step by step by loading previous states. >> >> I am handling a python processing code for very large files and multiple >> processing steps. Each time I find a bug, I have to run the whole thing >> again, which is time consuming. > Perhaps pickle is the thing you are looking for? > > http://docs.python.org/library/pickle.html or even cpickle which is lot faster cheers, Stef > HTH, > Daniel > > From debatem1 at gmail.com Mon Aug 23 15:58:43 2010 From: debatem1 at gmail.com (geremy condra) Date: Mon, 23 Aug 2010 12:58:43 -0700 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On Mon, Aug 23, 2010 at 10:37 AM, Sang-Ho Yun wrote: > I wonder if there is a way to save and load all python variables just like > matlab does, so I can build a code step by step by loading previous states. > > I am handling a python processing code for very large files and multiple > processing steps. Each time I find a bug, I have to run the whole thing > again, which is time consuming. > > Thank you, > Sang-Ho You may also be interested in Sage if you're trying to do Matlab-like things in Python. http://www.sagemath.org/ Geremy Condra From joncle at googlemail.com Mon Aug 23 16:08:25 2010 From: joncle at googlemail.com (Jon Clements) Date: Mon, 23 Aug 2010 13:08:25 -0700 (PDT) Subject: Using String Methods In Jump Tables References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: <5c99a604-f64c-49db-88f6-762175aa8532@5g2000yqz.googlegroups.com> On 23 Aug, 16:57, Tim Daneliuk wrote: > On 8/23/2010 10:35 AM, Jon Clements wrote: > > > > > On 20 Aug, 01:51, Tim Daneliuk wrote: > >> On 8/19/2010 7:23 PM, Steven D'Aprano wrote: > > >>> On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: > > >>>> Problem: > > >>>> ? Given tuples in the form (key, string), use 'key' to determine what > >>>> ? string method to apply to the string: > > >>>>>> table = {'l': str.lower, 'u': str.upper} > >>>>>> table['u']('hello world') > >>> 'HELLO WORLD' > > >> Aha! ?That's just what I was looking for. > > >>> [...] > >>>> As I said, I know I could do this as a set of cascading ifs or even as > >>>> an eval, but I'm loathe to use such approaches. I like jump tables as a > >>>> structural construct because they are easy to understand and maintain. I > >>>> also realize that what I'm asking may be violating some deeply held > >>>> notion of OO purity, but, well, now I'm just curious if there is a way > >>>> to do this > > >>> This is Python, not some "pure" OO language. We have functional > >>> programming constructs, procedural constructs, and probably other > >>> programming models as well. Screw the deeply held notion of OO purity :) > > >> Yeah, I've never been much impressed with the OO purists. ?One of > >> the best speeches on the subject I ever saw was by David Korn (of > >> ksh fame) who did a presentation at USENIX one year called "Objecting > >> To Objects". ?He documented an attempt to write a compiler using > >> purely OO constructs and the many rings of hell that ensued. ? > > >>> But seriously, Python's object model includes bound and unbound methods > >>> precisely so you can do this sort of thing, and the above table-based > >>> approach is very common and recommended as an alternative to case/switch > >>> statements. It's a very common Pythonic idiom, so never fear that people > >>> will stone you for using it. > > >> +1 > > >>> The only thing that is a bit unusual is that you call it a jump table. In > >>> my experience, "Jump Table" is used for low-level languages where the > >>> table values are memory addresses. > > >> Yeah ... those old assembler memories never quite fade do they. > >> I dunno what you might call this. ?A Function Dispatch Table > >> perhaps? > > >> Thanks to both you and Chris for setting me straight :) > > >> -- > >> ------------------------------------------------------------------------ > >> Tim Daneliuk > >> tun... at tundraware.com > > > Another more generic option would be to use methodcaller from the > > operator module. > > > Just my 2p, > > > Jon. > > Could you say a bit more about just why you prefer this approach? > Clearly, it *is* more generic, but in looking it over, it seems that > methodcaller is less readable and intuitive ... at least to my eyes ... In addition to Terry's informative response... Using methodcaller allows you to 'preserve' Python's duck-typing as well as any over-ridden methods in subclasses. In your example, this is probably overkill as you're only dealing with one class: but Terry did provide a nice example of when it could fail. Another (convoluted) example: class mystr(str): def lower(self): return self.upper() >>> s = mystr('abc') >>> s.lower() 'ABC' >>> lower = methodcaller('lower') >>> lower(s) 'ABC' >>> str.lower(s) 'abc' ^^^ Most likely incorrect It also adds a further bit of flexibility (which can be emulated with functools.partial admittedly): split_tab = methodcaller('split', '\t') split_comma = methodcaller('split', ',') ... etc ... Cheers, Jon. From robert.kern at gmail.com Mon Aug 23 16:18:08 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 23 Aug 2010 15:18:08 -0500 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On 8/23/10 12:37 PM, Sang-Ho Yun wrote: > I wonder if there is a way to save and load all python variables just like > matlab does, so I can build a code step by step by loading previous states. > > I am handling a python processing code for very large files and multiple > processing steps. Each time I find a bug, I have to run the whole thing > again, which is time consuming. Test each piece of code in isolation from the rest rather than relying on a complete run to test everything in one go. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nad at acm.org Mon Aug 23 16:20:17 2010 From: nad at acm.org (Ned Deily) Date: Mon, 23 Aug 2010 13:20:17 -0700 Subject: IDLE will not startup after upgrading Python on Mac OS X References: Message-ID: In article , Benjamin Kaplan wrote: > On Mon, Aug 23, 2010 at 9:45 AM, Frederick Manley wrote: > > so went to > > python.org to download Python 2.7, as I was "strongly encouraged" to do on > > the website. [...] > >The only problem is, whenever I start it > > up (I've tried starting it from the Terminal and double clicking the icon) I > > get the following message: > > "Idle's subprocess cannot make connection. ?Either Idle can't start a > > subprocess or a personal firewall is blocking the connection." > > Searching various programming forums came up with similar problems users > > have had in windows, but I couldn't find any information on how to fix this > > problem on a mac with OSX. ?Please help. > >From the title, this may be relevant, but I'm not sure because I'm > having trouble accessing the bug tracker right now. > http://bugs.python.org/issue9227 Yes, you are undoubtedly running into Issue9227. This is a known problem with IDLE and Tkinter on OS X 10.6 when using the python.org 2.7 installer "for OS X 10.5 and later". Until a replacement installer is made available, the simplest workaround is to just re-install 2.7 using the 32-bit OS X installer "for OS X 10.3 and later" (available here http://www.python.org/download/releases/2.7/). -- Ned Deily, nad at acm.org From f1crazed at gmail.com Mon Aug 23 16:43:58 2010 From: f1crazed at gmail.com (f1crazed) Date: Mon, 23 Aug 2010 13:43:58 -0700 (PDT) Subject: Installing pymssql Message-ID: <7e155e4e-ca2e-41c0-b838-0dfba5acc93f@h40g2000pro.googlegroups.com> Hello, I am new to the python world. I'm trying the install the pymssql package and have been unsuccessful. I am running Win7 x64. Here is the output I get when I try to build the pymssql package: running build running build_ext cythoning _mssql.pyx to _mssql.c building '_mssql' extension creating build creating build\temp.win-amd64-2.6 creating build\temp.win-amd64-2.6\Release C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN \amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Iwin32\free tds\include -IC:\Python26\include -IC:\Python26\PC /Tc_mssql.c /Fobuild \temp.win-amd64-2.6\Release\_mssql.obj -DMSDBLIB _mssql.c _mssql.c(643) : warning C4244: 'function' : conversion from 'Py_ssize_t' to 'long', possible loss of data _mssql.c(663) : warning C4244: 'function' : conversion from 'Py_ssize_t' to 'long', possible loss of data _mssql.c(685) : warning C4244: 'function' : conversion from 'Py_ssize_t' to 'long', possible loss of data _mssql.c(712) : warning C4244: 'function' : conversion from 'Py_ssize_t' to 'long', possible loss of data _mssql.c(6192) : warning C4244: '=' : conversion from 'Py_ssize_t' to 'int', possible loss of data _mssql.c(9967) : warning C4267: '=' : conversion from 'size_t' to 'int', possible loss of data c:\pythonmods\pymssql-1.9.908\_mssql.c(4652) : warning C4700: uninitialized local variable '__pyx_v_dbcol' used creating build\lib.win-amd64-2.6 C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN \amd64\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:win32\fre etds\lib /LIBPATH:C:\Python26\libs /LIBPATH:C:\Python26\PCbuild\amd64 msvcrt.lib kernel32.lib user32.lib gdi32.lib winsp ool.lib ws2_32.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libTDS. lib dblib.lib /EXPORT:init_mssql build\temp.win-amd64-2.6\Release \_mssql.obj /OUT:build\lib.win-amd64-2.6\_mssql.pyd /IM PLIB:build\temp.win-amd64-2.6\Release\_mssql.lib /MANIFESTFILE:build \temp.win-amd64-2.6\Release\_mssql.pyd.manifest _mssql.obj : warning LNK4197: export 'init_mssql' specified multiple times; using first specification Creating library build\temp.win-amd64-2.6\Release\_mssql.lib and object build\temp.win-amd64-2.6\Release\_mssql.exp _mssql.obj : error LNK2019: unresolved external symbol dbsqlexec referenced in function __pyx_f_6_mssql_db_sqlexec _mssql.obj : error LNK2019: unresolved external symbol dbadata referenced in function __pyx_f_6_mssql_get_data _mssql.obj : error LNK2019: unresolved external symbol dbdata referenced in function __pyx_f_6_mssql_get_data _mssql.obj : error LNK2019: unresolved external symbol dbalttype referenced in function __pyx_f_6_mssql_get_type _mssql.obj : error LNK2019: unresolved external symbol dbcoltype referenced in function __pyx_f_6_mssql_get_type _mssql.obj : error LNK2019: unresolved external symbol dbadlen referenced in function __pyx_f_6_mssql_get_length _mssql.obj : error LNK2019: unresolved external symbol dbdatlen referenced in function __pyx_f_6_mssql_get_length _mssql.obj : error LNK2019: unresolved external symbol dbcancel referenced in function __pyx_f_6_mssql_db_cancel _mssql.obj : error LNK2019: unresolved external symbol dbtds referenced in function __pyx_pf_6_mssql_15MSSQLConnection_1 1tds_version___get__ _mssql.obj : error LNK2019: unresolved external symbol dbclose referenced in function __pyx_pf_6_mssql_15MSSQLConnection _close _mssql.obj : error LNK2019: unresolved external symbol dbuse referenced in function __pyx_pf_6_mssql_15MSSQLConnection_s elect_db _mssql.obj : error LNK2019: unresolved external symbol dbgetmaxprocs referenced in function __pyx_pf_6_mssql_get_max_con nections _mssql.obj : error LNK2019: unresolved external symbol dbcount referenced in function __pyx_f_6_mssql_15MSSQLConnection_ execute_scalar _mssql.obj : error LNK2019: unresolved external symbol dbnextrow referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_execute_scalar _mssql.obj : error LNK2019: unresolved external symbol dbsettime referenced in function __pyx_pf_6_mssql_15MSSQLConnecti on_13query_timeout___set__ _mssql.obj : error LNK2019: unresolved external symbol dbcmd referenced in function __pyx_pf_6_mssql_15MSSQLConnection__ _init__ _mssql.obj : error LNK2019: unresolved external symbol dbloginfree referenced in function __pyx_pf_6_mssql_15MSSQLConnec tion___init__ _mssql.obj : error LNK2019: unresolved external symbol tdsdbopen referenced in function __pyx_pf_6_mssql_15MSSQLConnecti on___init__ _mssql.obj : error LNK2019: unresolved external symbol dbsetlogintime referenced in function __pyx_pf_6_mssql_15MSSQLCon nection___init__ _mssql.obj : error LNK2019: unresolved external symbol dbsetlname referenced in function __pyx_pf_6_mssql_15MSSQLConnect ion___init__ _mssql.obj : error LNK2019: unresolved external symbol dblogin referenced in function __pyx_pf_6_mssql_15MSSQLConnection ___init__ _mssql.obj : error LNK2019: unresolved external symbol dbdatecrack referenced in function __pyx_f_6_mssql_15MSSQLConnect ion_convert_db_value _mssql.obj : error LNK2019: unresolved external symbol dbconvert referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_convert_db_value _mssql.obj : error LNK2019: unresolved external symbol dbresults referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_execute_non_query _mssql.obj : error LNK2019: unresolved external symbol dbrpcinit referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure___init__ _mssql.obj : error LNK2019: unresolved external symbol dbrpcparam referenced in function __pyx_pf_6_mssql_20MSSQLStoredP rocedure_bind _mssql.obj : error LNK2019: unresolved external symbol dbretstatus referenced in function __pyx_pf_6_mssql_20MSSQLStored Procedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbretdata referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbretlen referenced in function __pyx_pf_6_mssql_20MSSQLStoredPro cedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbretname referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbrettype referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbnumrets referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbsqlok referenced in function __pyx_pf_6_mssql_20MSSQLStoredProc edure_execute _mssql.obj : error LNK2019: unresolved external symbol dbrpcsend referenced in function __pyx_pf_6_mssql_20MSSQLStoredPr ocedure_execute _mssql.obj : error LNK2019: unresolved external symbol dbsetmaxprocs referenced in function __pyx_pf_6_mssql_set_max_con nections _mssql.obj : error LNK2019: unresolved external symbol dbmsghandle referenced in function __pyx_f_6_mssql_init_mssql _mssql.obj : error LNK2019: unresolved external symbol dberrhandle referenced in function __pyx_f_6_mssql_init_mssql _mssql.obj : error LNK2019: unresolved external symbol dbinit referenced in function __pyx_f_6_mssql_init_mssql _mssql.obj : error LNK2019: unresolved external symbol dbcolname referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_get_result _mssql.obj : error LNK2019: unresolved external symbol dbnumcols referenced in function __pyx_f_6_mssql_15MSSQLConnectio n_get_result build\lib.win-amd64-2.6\_mssql.pyd : fatal error LNK1120: 40 unresolved externals error: command '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC \BIN\amd64\link.exe"' failed with exit status 1120 I know this might be a bit much to chew on but I have been trying to figure this out for a while know and I cannot figure this one out. Thanks in advance for the help! -JD From almar.klein at gmail.com Mon Aug 23 16:47:54 2010 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 23 Aug 2010 22:47:54 +0200 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On 23 August 2010 19:37, Sang-Ho Yun wrote: > I wonder if there is a way to save and load all python variables just like > matlab does, so I can build a code step by step by loading previous states. > > I am handling a python processing code for very large files and multiple > processing steps. Each time I find a bug, I have to run the whole thing > again, which is time consuming. > > Thank you, > Sang-Ho > > -- > http://mail.python.org/mailman/listinfo/python-list > A year ago or so I designed a simple file format that could do that and is also human readable (binary data is compressed and then base64 encoded). I use it extensively to store experiment data for my research and also for configuration files for two open source projects that I own: http://code.google.com/p/ssdf/ Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Mon Aug 23 17:22:17 2010 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 23 Aug 2010 23:22:17 +0200 Subject: Using String Methods In Jump Tables References: Message-ID: <87fwy510ty.fsf@busola.homelinux.net> Tim Daneliuk writes: > You can get away with this because all string objects appear to point to common > method objects. That is,: id("a".lower) == id("b".lower) A side note: your use of `id' has misled you. id(X)==id(Y) is not a perfect substitue for the X is Y. :) "a".lower and "b".lower obviously cannot be the same object, because in that case, how could they behave differently when called? >>> "a".lower() 'a' >>> "b".lower() # this should also return 'a' if "b".lower is the # same object 'b' Yet, id("a".lower) == id("b".lower) evaluates as True. What happens is, when the expression id("a".lower) == id("b.lower") is evaluated, each of the bound method objects created with subexpressions "a".lower" and "b".lower is referenced and thrown away as soon as "id" is called (i.e. pretty much immediately), so the two never exist at the same time. By the time "b".lower needs to be created, "a".lower is freshly deceased, and the memory it used to occupy is ready for use, and waiting at the top of the freelist. If CPython happened to use a different allocation/garbage collection strategy and failed to reuse the same memory address immediately, your code would just (happen to) work. From martin at v.loewis.de Mon Aug 23 17:23:09 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 23 Aug 2010 23:23:09 +0200 Subject: make install DESTDIR In-Reply-To: <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> Message-ID: <4C72E6BD.1020204@v.loewis.de> > Martin- Asking for help :) Ok. Please try the patch below. If this works, please make a bug report. Regards, Martin Index: Lib/distutils/util.py =================================================================== --- Lib/distutils/util.py (Revision 84197) +++ Lib/distutils/util.py (Arbeitskopie) @@ -220,7 +220,7 @@ if not os.path.isabs(pathname): return os.path.join(new_root, pathname) else: - return os.path.join(new_root, pathname[1:]) + return os.path.join(new_root, pathname.lstrip('/')) elif os.name == 'nt': (drive, path) = os.path.splitdrive(pathname) From robert.kern at gmail.com Mon Aug 23 17:33:54 2010 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 23 Aug 2010 16:33:54 -0500 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On 8/23/10 3:18 PM, Robert Kern wrote: > On 8/23/10 12:37 PM, Sang-Ho Yun wrote: >> I wonder if there is a way to save and load all python variables just like >> matlab does, so I can build a code step by step by loading previous states. >> >> I am handling a python processing code for very large files and multiple >> processing steps. Each time I find a bug, I have to run the whole thing >> again, which is time consuming. > > Test each piece of code in isolation from the rest rather than relying on a > complete run to test everything in one go. Having said that, you will want to take a look into using joblib to structure your larger runs: http://pypi.python.org/pypi/joblib -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ben+python at benfinney.id.au Mon Aug 23 17:38:53 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 24 Aug 2010 07:38:53 +1000 Subject: Looking for an appropriate encoding standard that supports all languages References: <1c0012ed-c94b-4143-8cd8-43e15a37ed15@q22g2000yqm.googlegroups.com> <90e26f24-4348-4192-a879-ee72e7b8403d@l20g2000yqm.googlegroups.com> Message-ID: <87zkwdovpu.fsf@benfinney.id.au> Ata Jafari writes: > Finally I did it. > I was doing some stupid mistakes. > Thanks alot. For the benefit of future readers of this thread, could you please describe what the errors were and how you discovered them? Also what the eventual solution was. -- \ ?When I get new information, I change my position. What, sir, | `\ do you do with new information?? ?John Maynard Keynes | _o__) | Ben Finney From ben+python at benfinney.id.au Mon Aug 23 17:56:42 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 24 Aug 2010 07:56:42 +1000 Subject: Start up company is looking for an experianced Django web developer . References: Message-ID: <87vd71ouw5.fsf@benfinney.id.au> writes: > Our company is looking for an experienced full time Django programmer [?] Please don't use the Python forum for this. Instead, post it to the Python Jobs Board . > Accepted applicants will be required to sign a non-disclosure agreement. I would strongly recommend that IT workers not sign such agreements. Instead, both parties can rely on existing law (which already heavily favours the employer), and don't sign away more of your rights just to get a job. -- \ ?I am amazed, O Wall, that you have not collapsed and fallen, | `\ since you must bear the tedious stupidities of so many | _o__) scrawlers.? ?anonymous graffiti, Pompeii, 79 CE | Ben Finney From thomas at jollybox.de Mon Aug 23 17:57:06 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 23 Aug 2010 23:57:06 +0200 Subject: Installing pymssql In-Reply-To: <7e155e4e-ca2e-41c0-b838-0dfba5acc93f@h40g2000pro.googlegroups.com> References: <7e155e4e-ca2e-41c0-b838-0dfba5acc93f@h40g2000pro.googlegroups.com> Message-ID: <201008232357.07258.thomas@jollybox.de> On Monday 23 August 2010, it occurred to f1crazed to exclaim: > Hello, > > I am new to the python world. I'm trying the install the pymssql > package and have been unsuccessful. I am running Win7 x64. Here is > the output I get when I try to build the pymssql package: > > [snip: missing symbols 64 bit blah] This appears to be a known bug: http://code.google.com/p/pymssql/issues/detail?id=11 There is a comment by the reporter: " This is likely because the 'freetds.zip' included in the source distribution only has 32-bit libraries (lib/libTDS.lib). " Assuming this analysis is correct, maybe you can find (or, more likely, create) a 64-bit build of libTDS and use that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Mon Aug 23 18:15:26 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 23 Aug 2010 15:15:26 -0700 (PDT) Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation Message-ID: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> I started learning python with ver 2.6. Then I switched to 3.1 after uninstalling the previous version. Now I find that many of the code snippets that I would need are written for py 2.6. Sometimes the automatic converter 2to3 doesn't help, because it is not able to complete its objective and request manual "tuning" from the user. This is to tell you that I would like to have both versions running on my PC. I am using Windows 7 at home, and Windows Vista in the office. Right now, the two versions are installed on the PC I have at home. If I go to the directory C:\python26 or C:\python31 and I type "python", the correct version of python is launched. I need the pywin32 extensions in either case. I was about to feel happy that everything worked when I found that I cannot change the file associations. If I want to work with py 3.1, I want that a double click on a *.py file launches python 3.1, and not 2.6. On the other hand, when I pan to work with py 2.6 I want that a double click on a*.py file launches python 3.1. I keep source files (*.py) for either version in different directories. I tried to change file associations, first manually, in a CMD window. But the system was responding "access denied" even when I used an Administrator account (I was using FTYPE python.file="C: \Python26\python.exe" "%1" %*). So I directed my efforts towards the Control Panel. But here I got lost. I am not able to find the python file associations (I can find others, but not python's). Perhaps I am focussing my efforts in the wrong direction, but I am not aware of any alternative one. Perhaps you can help me. Thank you Vicente Soler From martin at v.loewis.de Mon Aug 23 18:55:30 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 24 Aug 2010 00:55:30 +0200 Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation In-Reply-To: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> Message-ID: <4C72FC62.1050908@v.loewis.de> > I tried to change file associations, first manually, in a CMD window. > But the system was responding "access denied" even when I used an > Administrator account (I was using FTYPE python.file="C: > \Python26\python.exe" "%1" %*). That works, in principle. Put that command into py26.bat, then, in Explorer, Run As Administrator. Make sure to double-escape the percent signs. Alternatively, you can also write a program that writes to HKEY_CURRENT_USER; that would take precedence over HKEY_LOCAL_MACHINE. Regards, Martin From vicente.soler at gmail.com Mon Aug 23 19:08:17 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 23 Aug 2010 16:08:17 -0700 (PDT) Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> <4C72FC62.1050908@v.loewis.de> Message-ID: <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> On 24 ago, 00:55, "Martin v. Loewis" wrote: > > I tried to change file associations, first manually, in a CMD window. > > But the system was responding "access denied" even when I used an > > Administrator account (I was using FTYPE python.file="C: > > \Python26\python.exe" "%1" %*). > > That works, in principle. Put that command into py26.bat, then, in > Explorer, Run As Administrator. Make sure to double-escape the percent > signs. > > Alternatively, you can also write a program that writes to > HKEY_CURRENT_USER; that would take precedence over HKEY_LOCAL_MACHINE. > > Regards, > Martin When I am logged-in in a session as an administrator, the BAT file on the Desktop, and I double-click on it, it does not work. However, if instead of double-clicking on the BAT file, I enter the Explorer and I run the BAT file as administrator, then something seems to start working. Excellent! When you say to double-escape the percent signs, do you mean that in my BAT file I should write... FTYPE python.file="C:\Python26\python.exe" "%%1" %%* and the inverted commas around %%*, are they not necessary? Vicente Soler From martin at v.loewis.de Mon Aug 23 19:33:21 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 24 Aug 2010 01:33:21 +0200 Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation In-Reply-To: <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> <4C72FC62.1050908@v.loewis.de> <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> Message-ID: <4C730541.7040507@v.loewis.de> > When I am logged-in in a session as an administrator, the BAT file on > the Desktop, and I double-click on it, it does not work. This is not what I meant. Instead, right-click on the BAT file, and select "run as administrator". > When you say to double-escape the percent signs, do you mean that in > my BAT file I should write... > > FTYPE python.file="C:\Python26\python.exe" "%%1" %%* > > and the inverted commas around %%*, are they not necessary? No, I don't think so. Regards, Martin From vicente.soler at gmail.com Mon Aug 23 19:41:13 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 23 Aug 2010 16:41:13 -0700 (PDT) Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> <4C72FC62.1050908@v.loewis.de> <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> <4C730541.7040507@v.loewis.de> Message-ID: <3d85d8f5-8ce0-470f-b6ec-c86c452a335b@a36g2000yqc.googlegroups.com> On Aug 24, 1:33?am, "Martin v. Loewis" wrote: > > When I am logged-in in a session as an administrator, the BAT file on > > the Desktop, and I double-click on it, it does not work. > > This is not what I meant. Instead, right-click on the BAT file, > and select "run as administrator". > > > When you say to double-escape the percent signs, do you mean that in > > my BAT file I should write... > > > ? ? FTYPE python.file="C:\Python26\python.exe" "%%1" %%* > > > and the inverted commas around %%*, are they not necessary? > > No, I don't think so. > > Regards, > Martin Martin (or anybody else), The problem with FTYPE is solved. However, after having switched to py 3.1 with the help of the BAT script (which only changes FTYPE) I have another problem. (Just for reference, here is my batch file) @ECHO OFF ECHO ************************************************ ECHO Cambia a Python 3.1 ECHO ************************************************ ECHO * ECHO FTYPES: ECHO * ECHO .py=Python.File ECHO .pyc=Python.CompiledFile ECHO .pyo=Python.CompiledFile ECHO .pys=pysFile ECHO .pyw=Python.NoConFile ECHO * ECHO ************************************************ ECHO * FTYPE python.file="C:\Python31\python.exe" "%%1" %%* FTYPE python.compiledfile="C:\Python31\python.exe" "%%1" %%* FTYPE python.NoConFile="C:\Python31\pythonw.exe" "%%1" %%* ECHO * Pause @ECHO ON The problem is that, if I am on top of a .py file, and, with the mouse, I click on the right button, then I click on "Edit with IDLE", I get the 2.6 system, not the 3.1 one (which was supposed to be the correct one after the change). My question is: are there any other changes that I should do in order to fully switch from one version to another? Thank you in advance. Vicente Soler From hughaguilar96 at yahoo.com Mon Aug 23 20:00:55 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Mon, 23 Aug 2010 17:00:55 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> Message-ID: <80befec3-be41-4166-8487-9a147131c7b9@s9g2000yqd.googlegroups.com> On Aug 21, 12:32?pm, Alex McDonald wrote: > "Scintilla" gets about 2,080,000 results on google; "blather" gets > about 876,000 results. O Hugh, you pseudo-intellectual you! > > > with gutter language such as > > "turd" > > About 5,910,000 results. It has a long history, even getting a mention > in the Wyclif's 13th century bible. You looked up "blather" and "turd" on google *AND* you are not a pseudo-intellectual??? That is funny! I don't consider myself to be a pseudo-intellectual. I don't have any education however, so a pseudo-intellectual is the only kind of intellectual that I could be. From python at mrabarnett.plus.com Mon Aug 23 20:16:56 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 24 Aug 2010 01:16:56 +0100 Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation In-Reply-To: <4C730541.7040507@v.loewis.de> References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com> <4C72FC62.1050908@v.loewis.de> <8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com> <4C730541.7040507@v.loewis.de> Message-ID: <4C730F78.9050502@mrabarnett.plus.com> Martin v. Loewis wrote: >> When I am logged-in in a session as an administrator, the BAT file on >> the Desktop, and I double-click on it, it does not work. > > This is not what I meant. Instead, right-click on the BAT file, > and select "run as administrator". > >> When you say to double-escape the percent signs, do you mean that in >> my BAT file I should write... >> >> FTYPE python.file="C:\Python26\python.exe" "%%1" %%* >> >> and the inverted commas around %%*, are they not necessary? > > No, I don't think so. > %1 is the placeholder for parameter 1, which you do want quoted. %* is the placeholder for all the remaining parameters, which you don't want quoted as single string. From hughaguilar96 at yahoo.com Mon Aug 23 20:26:46 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Mon, 23 Aug 2010 17:26:46 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> Message-ID: <009e2df0-6299-442d-aedf-e0e2e704d6c1@g17g2000yqe.googlegroups.com> On Aug 22, 3:40?pm, 1001nuits <1001nu... at gmail.com> wrote: > Another thing you learn in studying in University is the fact that you can ? > be wrong, which is quite difficult to accept for self taught people. Yet another thing you learn in studying in University, is the art of apple polishing! LOL If a person has graduated from college, it is not clear what if anything he has learned of a technical nature --- but it can be assumed that he has learned to be a head-bobber (someone who habitually bobs his head up and down in agreement when the boss is speaking) and has learned to readily admit to being wrong when pressured (when the boss looks at him without smiling for more than two seconds). These are the traits that bosses want in an employee --- that prove the employee to be "trainable." BTW, has anybody actually looked at my software? http://www.forth.org/novice.html All this pseudo-intellectual nonsense (including this post) is getting boring. Why don't we try discussing software for a while? I wrote that slide-rule program as a showcase of Forth. I've been thinking of porting it over to another language, possibly C. Maybe one of you C experts could write the C program though, as a comparison --- to show how much better C is than Forth. You can demonstrate that my code was badly written and strangely designed --- with a concrete example, rather than just a lot hand-waving and chest-thumping. From bblais at bryant.edu Mon Aug 23 21:18:01 2010 From: bblais at bryant.edu (Brian Blais) Date: Mon, 23 Aug 2010 21:18:01 -0400 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On Aug 23, 2010, at 16:47 , Almar Klein wrote: > A year ago or so I designed a simple file format that could do that > and is also human readable (binary data is compressed and then > base64 encoded). I use it extensively to store experiment data for > my research and also for configuration files for two open source > projects that I own: > http://code.google.com/p/ssdf/ > this is fantastic! what a great format! I've been looking for something like this for quite some time. thanks! bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais http://bblais.blogspot.com/ From mailtome200420032002 at gmail.com Mon Aug 23 21:26:05 2010 From: mailtome200420032002 at gmail.com (aj) Date: Mon, 23 Aug 2010 18:26:05 -0700 (PDT) Subject: make install DESTDIR References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> <4C72E6BD.1020204@v.loewis.de> Message-ID: On Aug 23, 2:23?pm, "Martin v. Loewis" wrote: > > Martin- Asking for help :) > > Ok. Please try the patch below. > > If this works, please make a bug report. > > Regards, > Martin > > Index: Lib/distutils/util.py > =================================================================== > --- Lib/distutils/util.py ? ? ? (Revision 84197) > +++ Lib/distutils/util.py ? ? ? (Arbeitskopie) > @@ -220,7 +220,7 @@ > ? ? ? ? ?if not os.path.isabs(pathname): > ? ? ? ? ? ? ?return os.path.join(new_root, pathname) > ? ? ? ? ?else: > - ? ? ? ? ? ?return os.path.join(new_root, pathname[1:]) > + ? ? ? ? ? ?return os.path.join(new_root, pathname.lstrip('/')) > > ? ? ?elif os.name == 'nt': > ? ? ? ? ?(drive, path) = os.path.splitdrive(pathname) Thanks Martin. That seems to work. I will file a bug report. Also, can you describe what the problem was? From nanothermite911fbibustards at gmail.com Mon Aug 23 22:30:52 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Mon, 23 Aug 2010 19:30:52 -0700 (PDT) Subject: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From nanothermite911fbibustards at gmail.com Mon Aug 23 22:39:05 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Mon, 23 Aug 2010 19:39:05 -0700 (PDT) Subject: Iran's self-defense options 'limitless' - against the YANQUI and KHAZAR Bustards - Brilliant ANALYSIS References: Message-ID: Iran's self-defense options 'limitless' - against the YANQUI and KHAZAR Bustards - Brilliant ANALYSIS Iran's self-defense options 'limitless' Tue Aug 24, 2010 12:9AM President Mahmoud AhmadinejadIran's President Mahmoud Ahmadinejad says no military action is expected to be taken against the Islamic Republic since enemies are aware of Iran's reaction. "Iran is not concerned by a prospective military attack by any country, although it is always prepared to defend itself," Ahmadinejad said in an interview with Qatar's al-Sharq and the Peninsula newspapers on Monday. "Enemies know well that Iran is an invincible fortress and I do not believe the US masters of the Zionists will allow the regime [in Tel Aviv] to take any measures against Iran," noted the Iranian chief executive. Asked about Iran's options in the case it is attacked, Ahmadinejad said, "Iran has limitless options which extends to all parts of the world." Commenting on the Israeli threats against Iran's sovereignty over the county's nuclear enrichment program, the Iranian president pointed out that "Israel is too weak to stage a military strike against Iran, but if it attacks, it will receive a devastating response, which will make it regret its aggression." He also dismissed the idea that Arab countries' soil would be used to launch attacks on Iran, saying that the "leaders of these countries are more prudent than that.? Ahmadinejad further downplayed US military might in its current wars in the Middle East region and rejected the speculations that an imminent war against Iran was the cause of the US troops' withdrawal from Iraq. GHN/MGH ============ BRILLIANT ANALYSIS http://www.tehrantimes.com/index_View.asp?code=225469 View Rate : 1531 # News Code : TTime- 225469 Print Date : Tuesday, August 24, 2010 ?Iran will stand beside any country threatened in region? Ahmadinejad: Israel lacks courage to attack Iran TEHRAN ? Iranian President Mahmoud Ahmadinejad says that Iran will stand beside any country in the region that is threatened. ?Iran will stand on the side of any country in the region which comes under pressure or is threatened,? Ahmadinejad said in an interview with Arabic satellite television network Al Jazeera aired on Sunday. He also said he doesn?t think the threats by the United States and Israel to attack Iran are ?serious?. ?Israel does not have the courage to do it? I do not think the threat is serious.? Ahmadinejad also stated that Israel is ?too weak? to attack the Islamic Republic. The Iranian president said that any military adventure by the Zionist regime targeting Iran would receive a ?crushing? response that would make Israel regret the decision. He went on to say that Persian Gulf states are ?too smart? to allow the U.S. to use bases on their territory for a strike on Iran. ?We regard the Persian Gulf countries as brothers and friends. They are smarter than that.? In the interview, the president also said he does not fear an attack by the U.S. because it could not even defeat a small army in Iraq. ?There are no logical reasons for the United States to carry out such an act,? President Ahmadinejad told Al Jazeera. ?Do you believe an army that has been defeated by a small army in Iraq can enter into a war with a large and well trained army like the Iranian army?? he asked, referring to the insurgents in Iraq. Iran will only ?look to the views of wise people? in the U.S. and not to those whose minds are obsessed with ?hatred and animosity?, the president said when asked about former U.S. ambassador to the UN John Bolton?s remarks, which had apparently encouraged Israel to attack the Bushehr plant before its start-up. Washington has no real motive to attack Iran and would not benefit from hostilities, he added. ?The friendship of Iran is much better than its hostility,? he said. He went on to say that Iran is working to produce nuclear fuel independently ?because receiving it from an outside source is conditioned on diplomatic criteria.? To prevent Iran from using the Bushehr reactor to produce plutonium, inspectors from the International Atomic Energy Agency and Russia, which built the power plant, are making sure Iran returns the fuel rods it receives after they are spent. ?There is a difference between those who produce and those who buy. We must make sure our nuclear power plant continues to operate. We do not trust the West, despite our good relations with Russia,? Ahmadinejad said. ?We need 20 power plants like the one in Bushehr,? he added. From wuwei23 at gmail.com Mon Aug 23 22:46:51 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 23 Aug 2010 19:46:51 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: "Russ P." wrote: > However, I've switched from Python to > Scala, so I really don't care. Really? Your endless whining in this thread would seem to indicate otherwise. From nobody at nowhere.com Mon Aug 23 22:53:40 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 24 Aug 2010 03:53:40 +0100 Subject: Discarding STDERR generated during subprocess.popen References: <18e2178f-e042-4d84-9706-c6fde44199b4@t20g2000yqa.googlegroups.com> Message-ID: On Mon, 23 Aug 2010 10:38:02 -0700, Leon Derczynski wrote: > I would like to run an external program, and discard anything written > to stderr during its execution, capturing only stdout. My code > currently looks like: > > def blaheta_tag(filename): > blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/' > process = subprocess.Popen([blaheta_dir + 'exec/funcTag', > blaheta_dir + 'data/', filename], cwd=blaheta_dir, > stdout=subprocess.PIPE) > process.wait() > return process.communicate()[0] > > This returns stdout, and stderr ends up printing to the console. How > can I disregard anything sent to stderr such that it doesn't appear on > the console? Either: 1. Add "stderr=subprocess.PIPE" to the Popen() call. The communicate() method will read both stdout and stderr, and you just ignore stderr. 2. Redirect stderr to the null device: nul_f = open(os.devnull, 'w') process = subprocess.Popen(..., stderr = nul_f) nul_f.close() return process.communicate()[0] [os.devnull will be "/dev/null" on Unix, "nul" on Windows.] BTW: you shouldn't call process.wait() here. The communicate() method will call the wait() method when it receives EOF. If you call wait(), and the process tries to write more than a buffer's worth of output (the exact figure is platform-specific), your script will deadlock. The child process will block waiting for the script to consume its output, while the script will block waiting for the child process to terminate. From smallpox911 at gmail.com Mon Aug 23 23:02:02 2010 From: smallpox911 at gmail.com (small Pox) Date: Mon, 23 Aug 2010 20:02:02 -0700 (PDT) Subject: YANQUI cry babies concerned that Iran has achieved parity in DRONES and against the massive AIRCRAFT carriers which are like SITTING DUCKS. A nation needs AIRCRAFT carriers to venture out for IMPERIALISTIC assaults but cant go out on speed boats. References: Message-ID: <7211b12b-86fe-4a27-8b4b-674dec101fef@v41g2000yqv.googlegroups.com> YANQUI cry babies concerned that Iran has achieved parity in DRONES and against the massive AIRCRAFT carriers which are like SITTING DUCKS. A nation needs AIRCRAFT carriers to venture out for IMPERIALISTIC assaults but cant go out on speed boats. Yet the NUMEROUS fast boats can sink the AIRCRAFT carrier and make it a SAILING COFFIN. http://www.google.com/hostednews/afp/article/ALeqM5gYlBmnQz28otk-w_hvx1pZ5C= bl0w US concerned about Iran's assault boats, drone (AFP) =96 5 hours ago WASHINGTON =97 The United States voiced concern Monday over Iran's unveiling of new assault boats and an aerial drone, but said Iran's arms buildup will backfire as its neighbors gang up against it. Iran began mass-producing two high-speed variants of missile-launching assault boats on Monday, a day after Iranian President Mahmoud Ahmadinejad revealed a home-built bomber drone. "This is... something that is of concern to us and... concern to Iran's neighbors," State Department spokesman Philip Crowley told reporters. He said that while every country had the right to provide for its self- defense, the United States takes into account "systems that can potentially... threaten particular countries or peace and stability in the region." Faced with "the growth of Iran's capabilities over a number of years, we've stepped up our military cooperation with other countries in the region," Crowley said. "This is one of the reasons why... we believe that if Iran continues on the path that it's on... (it) might find itself less secure because you'll have countries in the region that join together to offset Iran's growing capabilities." He added that the United States is still open to "constructive dialogue" with Iran to answer questions it and the world community have about its nuclear program, which Washington fears is aimed at building a bomb. "But in the meantime, we will work with other countries to try to do everything that we can to maintain peace and stability in the region," Crowley said. Copyright =A9 2010 AFP. All rights reserved From russ.paielli at gmail.com Tue Aug 24 00:06:09 2010 From: russ.paielli at gmail.com (Russ P.) Date: Mon, 23 Aug 2010 21:06:09 -0700 (PDT) Subject: Python "why" questions References: <4c5d4810$0$1426$426a74cc@news.free.fr> <46211060-3d46-4518-8ec0-08c9707338a2@l14g2000yql.googlegroups.com> <4c6d7241$0$11111$c3e8da3@news.astraweb.com> <4c6d826e$0$11111$c3e8da3@news.astraweb.com> <27a9eac6-bebb-44df-adf2-6a5c4b5e67a6@v41g2000yqv.googlegroups.com> <4c6f8f56$0$28653$c3e8da3@news.astraweb.com> Message-ID: <2938d973-9011-46d7-bcdb-bbd2827ee42d@v35g2000prn.googlegroups.com> On Aug 23, 7:46?pm, alex23 wrote: > "Russ P." wrote: > > However, I've switched from Python to > > Scala, so I really don't care. > > Really? Your endless whining in this thread would seem to indicate > otherwise. Yes, I guess I care some, but not much. I still use Python for some things, and I still have lots of "legacy" Python code that I still use. I just like to "whine" about zero-based indexing (but Scala is no different in that regard). It's my number one gripe. (My number zero gripe is semicolons after each statement -- but both Python and Scala got that one right, thank goodness.) From pahitezu at gmail.com Tue Aug 24 01:40:04 2010 From: pahitezu at gmail.com (pahi sharma) Date: Mon, 23 Aug 2010 22:40:04 -0700 (PDT) Subject: help in code Message-ID: I am new to python .I have a corpus which is written in Bengali and i want to read that file using python code.Can anyone help me in this matter. Thank You From martin at v.loewis.de Tue Aug 24 01:52:01 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 24 Aug 2010 07:52:01 +0200 Subject: make install DESTDIR In-Reply-To: References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> <4C72E6BD.1020204@v.loewis.de> Message-ID: <4C735E01.3050709@v.loewis.de> > Thanks Martin. That seems to work. I will file a bug report. Also, can > you describe what the problem was? If you have / as the prefix, you get two leading slashes, e.g. for //lib/python2.x. Any other prefix would have given you only a single slash: e.g. if it had been /usr, then you end up with /usr/lib/python2.x. Now, the code strips the first character to make it a relative path name (so that join can be used), which fails to work correctly if there are two leading slashes. HTH, Martin From steve-REMOVE-THIS at cybersource.com.au Tue Aug 24 03:15:08 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2010 07:15:08 GMT Subject: help in code References: Message-ID: <4c73717c$0$28639$c3e8da3@news.astraweb.com> On Mon, 23 Aug 2010 22:40:04 -0700, pahi sharma wrote: > I am new to python .I have a corpus which is written in Bengali and i > want to read that file using python code.Can anyone help me in this > matter. In Python 3, I believe this should work: f = open("filename", encoding="which-encoding-you-use") text = f.read() f.close() In Python 2, you probably need to do this: f = open("filename") bytes = f.read() text = bytes.decode('which-encoding-you-use') f.close() Hope this helps. -- Steven From steve-REMOVE-THIS at cybersource.com.au Tue Aug 24 03:23:31 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2010 07:23:31 GMT Subject: Helper classes design question References: <201008231047.57128.mail@johnohagan.com> Message-ID: <4c737373$0$28639$c3e8da3@news.astraweb.com> On Mon, 23 Aug 2010 19:22:46 +0200, Thomas Jollans wrote: > On Monday 23 August 2010, it occurred to John O'Hagan to exclaim: [...] >> I'm not sure if I'm on the right track here design-wise. Maybe this >> could be better done with inheritance (not my forte), but my first >> thought is that no, the helper classes (if that's what they are) are >> not actually a type of the main class, but are auxiliary to it. > > You could try using mixins. Without taking a position for or against mixins, I think it is only fair to point out that not everyone considers them a good design choice: Mixins considered harmful part 1 by Michele Simionato http://www.artima.com/weblogs/viewpost.jsp?thread=246341 And parts 2, 3, and 4: http://www.artima.com/weblogs/viewpost.jsp?thread=246483 http://www.artima.com/weblogs/viewpost.jsp?thread=254367 http://www.artima.com/weblogs/viewpost.jsp?thread=254507 -- Steven From kai.diefenbach at iqpp.de Tue Aug 24 03:54:37 2010 From: kai.diefenbach at iqpp.de (Kai Diefenbach) Date: Tue, 24 Aug 2010 09:54:37 +0200 Subject: ANN: LFC 1.0 Message-ID: Hi guys, today we released LFC 1.0. This is the first final release of LFC. LFC is a CMS based on Python, Django and jQuery. You can find the installer here: http://pypi.python.org/pypi/django-lfc/1.0. The installation is described here: http://packages.python.org/django-lfc/introduction/installation.html and should last just a few minutes. Its main features are: - Commenting - Cut/Copy?n Paste - Easy upload of images and files - Flexible Databases - Multilingual content - Pluggable - Role based per-object permissions - RSS Feeds - Search - Tagging - Time based publishing - Variable Templates - Variable Portlets - Variable Workflows - WYSIWYG-Editor You can find more information on following places: - Official Homepage: http://www.lfcproject.com/ - Documentation: http://packages.python.org/django-lfc - Download: http://pypi.python.org/pypi/django-lfc - Source Code: http://bitbucket.org/diefenbach/django-lfc - Google Group: http://groups.google.com/group/django-lfc - Twitter: http://twitter.com/lfcproject - IRC: irc://irc.freenode.net/django-lfc Any suggestions are highly appreciated. Thanks Kai From bill at supposedly.org Tue Aug 24 04:34:01 2010 From: bill at supposedly.org (Bill Green) Date: Tue, 24 Aug 2010 08:34:01 +0000 (UTC) Subject: curses KEY_* constants Message-ID: Hello, According to the documentation for the curses module, there are a number of constants defined for various special keys (such as KEY_DOWN, KEY_UP, KEY_BACKSPACE, etc.). However, these do not exist on my system (NetBSD 5). Looking at _cursesmodule.c, the code that sets up the KEY_ variables is #defined out on NetBSD (in initcurses() at line 2860 for Python 2.7). Does anyone know why this is so? Thanks. From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 24 04:40:14 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 24 Aug 2010 10:40:14 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4c73856e$0$8111$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: > >> Steven D'Aprano a ?crit : >>> On Thu, 19 Aug 2010 22:00:16 +0000, Martin Gregorie wrote: >>> >>>> Recursion can be quite a trick to get your mind round at first >>> Really? Do people actually find the *concept* of recursion to be >>> tricky? >>> >>> >> I onced worked in a shop (Win32 desktop / accouting applications mainly) >> where I was the only guy that could actually understand recursion. FWIW, >> I also was the only guy around that understood "hairy" (lol) concepts >> like callback functions, FSM, > > FSM? Flying Spaghetti Monster? Lol. Now this would at least be a pretty good description of the kind of code base these guys were used to !-) > >> polymorphism, hashtables, linked lists, >> ADTs, algorithm complexity etc... > > > Was there anything they *did* understand, Hmmm.... good question - but I didn't last long enough to find out. > or did they just bang on the > keyboard at random until the code compiled? *wink* Kind of, yes. From durumdara at gmail.com Tue Aug 24 05:21:00 2010 From: durumdara at gmail.com (durumdara) Date: Tue, 24 Aug 2010 02:21:00 -0700 (PDT) Subject: ftplib limitations? Message-ID: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> Hi! See this code: ---------------- import os, sys, ftplib from ftplib import FTP ftp = FTP() ftp.connect('ftp.anything.hu', 2121) ftp.login('?', '?') print ftp.getwelcome() ftp.set_pasv(False) ls = ftp.nlst() for s in ls: print "\nFilename:", '"%s"' % s, fsize = ftp.size(s) print "Size:", fsize print "..download:", d = {} d['buffer'] = [] d['size'] = 0 d['lastpercentp10'] = 0 def CallBack(Data): d['size'] = d['size'] + len(Data) d['buffer'].append(Data) percent = (d['size'] / float(fsize)) * 100 percentp10 = int(percent/10) if percentp10 > d['lastpercentp10']: d['lastpercentp10'] = percentp10 print str(percentp10 * 10) + "%", ftp.retrbinary("retr " + s, CallBack) print "" print "..downloaded, joining" dbuffer = "".join(d['buffer']) adir = os.path.abspath("b:\\_BACKUP_") newfilename = os.path.join(adir, s) print "..saving into", newfilename f = open(newfilename, "wb") f.write(dbuffer) f.close() print "..saved" print "..delete from the server" ftp.delete(s) print "..deleted" #sys.exit() print "\nFinished" ---------------- This code is login into a site, download and delete all files. I experienced some problem. The server is Windows and FileZilla, the client is Win7 and Python2.6. When I got a file with size 1 303 318 662 byte, python is halt on "retrbinary" line everytime. It down all of the file (100%) but the next line never reached. Some error I got, but this was in yesterday, I don't remember the text of the error. I want to ask that have Py2.6 some ftp limitations? I remembered that Zip have 2 GB limitation, the bigger size of the archive making infinite loop. May ftplib also have this, and this cause the problem... Or I need to add a "NOOP" command in Callback? Thanks for your help: dd From jeanmichel at sequans.com Tue Aug 24 05:29:21 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 24 Aug 2010 11:29:21 +0200 Subject: 79 chars or more? In-Reply-To: References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> Message-ID: <4C7390F1.8070401@sequans.com> Lawrence D'Oliveiro wrote: > In message > , Jean-Michel Pichavant > wrote: > > >> Saying that, if one intend to distribute its code, he should stick to 80 >> chars per line. >> > > Why? > Because some(many ?) people cannot deal with more than 80 chars, otherwise this rule would be pointless. JM From bill at supposedly.org Tue Aug 24 05:43:46 2010 From: bill at supposedly.org (Bill Green) Date: Tue, 24 Aug 2010 09:43:46 +0000 (UTC) Subject: curses KEY_* constants References: Message-ID: I perhaps should have mentioned I linked the Python curses module against ncurses rather than BSD curses. Perhaps NetBSD's curses doesn't support this feature, and that's why it's not included there. In any case, I removed the relevant #defines in _cursesmodule.c and got a Python that includes all the KEY_ constants in the curses module, but these constants (for the arrow keys at least) seem not to match the actual keycodes. From mark.leander at topicbranch.net Tue Aug 24 05:46:48 2010 From: mark.leander at topicbranch.net (Mark Leander) Date: Tue, 24 Aug 2010 09:46:48 +0000 (UTC) Subject: Save/load like matlab? References: Message-ID: Almar Klein gmail.com> writes: > A year ago or so I designed a simple file format that could do that and is also > human readable (binary data is compressed and then base64 encoded). I use it > extensively to store experiment data for my research and also for configuration > files for two open source projects that I own:http://code.google.com/p/ssdf/ That looks quite nice! Thank you for sharing! I see that at least in some case you use the generally unsafe eval() for parsing. For instance the following will consume CPU and memory for quite a while: >>> ssdf.loads(u'a = [0xffffffffffffffff**0xffffffffffffffff]') Regards Mark http://blog.topicbranch.net/2010/08/ssdf-simple-structured-data-format.html From bill at supposedly.org Tue Aug 24 06:01:16 2010 From: bill at supposedly.org (Bill Green) Date: Tue, 24 Aug 2010 10:01:16 +0000 (UTC) Subject: curses KEY_* constants References: Message-ID: On 2010-08-24, Bill Green wrote: > ... but these > constants (for the arrow keys at least) seem not to match the actual > keycodes. After looking at the documentation again I've realized I needed to enable keypad mode on the window for curses to catch the escape codes, and now everything's working. It seems to me that _cursesmodule.c should check at compile time to see if the platform is NetBSD AND ncurses isn't being used. Regards, Bill From ldo at geek-central.gen.new_zealand Tue Aug 24 06:13:26 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 24 Aug 2010 22:13:26 +1200 Subject: 79 chars or more? References: <4c6a0736$0$28672$c3e8da3@news.astraweb.com> <4C6A0C3F.9060900@gmail.com> <5838e8c3-84c1-4c64-95eb-37da16fd4db6@v8g2000yqe.googlegroups.com> Message-ID: In message , Jean-Michel Pichavant wrote: > Lawrence D'Oliveiro wrote: > >> In message >> , Jean-Michel >> Pichavant wrote: >> >>> Saying that, if one intend to distribute its code, he should stick to 80 >>> chars per line. >>> >> >> Why? >> > Because some(many ?) people cannot deal with more than 80 chars, > otherwise this rule would be pointless. So you assume the rule cannot be pointless? From ldo at geek-central.gen.new_zealand Tue Aug 24 06:16:40 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 24 Aug 2010 22:16:40 +1200 Subject: Reading the access attributes of directories in Windows References: <4C6D7E2A.9010703@timgolden.me.uk> Message-ID: In message , Nobody wrote: > 1. There are far more permission types than just "rwx". One thing Windows lacks is the ability to replace files that are currently open by another process. This is why Windows software updates require so many reboots. On Unix/Linux, you can replace the files, then restart the affected processes, instead of having to take them down for the entire duration of the update. This minimizes downtime. From ldo at geek-central.gen.new_zealand Tue Aug 24 06:21:29 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 24 Aug 2010 22:21:29 +1200 Subject: requirements in writing an email/rss/usenet client? References: Message-ID: In message , George Oliver wrote: > I currently use Thunderbird + Muttator, which is a nice setup; but, it > has some clunky parts, and I thought it might be simpler in the end to > start fresh than try to engage with what seems to be the massive-ness > of Thunderbird (of course, I may be disabused of this notion at some > point ;) ). I would advise you to use Thunderbird or some such MUA as a starting point. Why reinvent the wheel? From ldo at geek-central.gen.new_zealand Tue Aug 24 06:23:35 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 24 Aug 2010 22:23:35 +1200 Subject: Contains/equals References: Message-ID: In message , Alex Hall wrote: > def __eq__(self, obj): > if self.a==obj.a and self.b==obj.b: return True > return False Is there a ?Useless Use Of ...? award category for these ?if then return True; else return False? constructs? From eacheaby at gmail.com Tue Aug 24 06:28:17 2010 From: eacheaby at gmail.com (=?GB2312?B?t+fW0L6ist0=?=) Date: Tue, 24 Aug 2010 03:28:17 -0700 (PDT) Subject: sex-girl Message-ID: sex-girl http://bailong.0fees.net/ From almar.klein at gmail.com Tue Aug 24 07:13:03 2010 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 24 Aug 2010 13:13:03 +0200 Subject: Save/load like matlab? In-Reply-To: References: Message-ID: On 24 August 2010 11:46, Mark Leander wrote: > Almar Klein gmail.com> writes: > > A year ago or so I designed a simple file format that could do that and > is also > > human readable (binary data is compressed and then base64 encoded). I use > it > > extensively to store experiment data for my research and also for > configuration > > files for two open source projects that I own: > http://code.google.com/p/ssdf/ > > That looks quite nice! Thank you for sharing! > > I see that at least in some case you use the generally unsafe eval() for > parsing. > For instance the following will consume CPU and memory for quite a while: > > >>> ssdf.loads(u'a = [0xffffffffffffffff**0xffffffffffffffff]') > > I added an issue for this, will take a look at it. Thanks! Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Tue Aug 24 07:27:47 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 24 Aug 2010 13:27:47 +0200 Subject: What is a class method? In-Reply-To: <4c71f0c1$0$1861$a729d347@news.telepac.pt> References: <4c71e1d7$0$1846$a729d347@news.telepac.pt> <4c71f0c1$0$1861$a729d347@news.telepac.pt> Message-ID: <4C73ACB3.7090108@sequans.com> Paulo da Silva wrote: > Em 23-08-2010 04:30, James Mills escreveu: > >> On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva >> wrote: >> >>> I understand the concept of a static method. >>> However I don't know what is a class method. >>> Would anybody pls. explain me? >>> >> Please read this first: >> http://docs.python.org/library/functions.html#classmethod >> >> Then ask us questions :) >> > > I did it before posting ... > The "explanation" is not very clear. It is more like "how to use it". > > Thanks anyway. > A very naive approach: Instance methodes modify/use the instance. They requires a reference to the instance as first parameter (self) class Foo: def foo(self): print self.instanceAttribute Class methodes modify/use the class. They require a class as parameter (cls) class Foo: occurrences = 0 @classmethod def foo(cls): print "Number of %s occurrences : %s" % (cls.__name__, cls.occurrences) Static methods neither use a class nor an instance, thus require no parameter. In that case, the class acts like a namespace (<~>container): class Foo: @staticmethod def sayHello(): print "Hello" Foo.sayHello() Cheers, JM From jeanmichel at sequans.com Tue Aug 24 07:37:52 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 24 Aug 2010 13:37:52 +0200 Subject: Helper classes design question In-Reply-To: <201008231047.57128.mail@johnohagan.com> References: <201008231047.57128.mail@johnohagan.com> Message-ID: <4C73AF10.5010703@sequans.com> John O'Hagan wrote: > I want to know the best way to organise a bunch of functions designed to > operate on instances of a given class without cluttering the class itself with > a bunch of unrelated methods. > > What I've done is make what I think are called helper classes, each of which > are initialized with an instance of the main class and has methods which are > all of the same type (insofar as they return a boolean, or modify the object > in place, or whatever). > > I'm not sure if I'm on the right track here design-wise. Maybe this could be > better done with inheritance (not my forte), but my first thought is that no, > the helper classes (if that's what they are) are not actually a type of the > main class, but are auxiliary to it. > I've seen the following pattern in someone else code which was working pretty well: It was using composition instead of inheritance. When a method is not found in the 'main class', then it searches within all the registered helpers and automatically call the helper method if it exists. It was pretty much clever but has some drawbacks: - you have to handle collisions between helpers methods name - reading the code may become difficult because you're successfully calling methods that do not belong the the instance class. JM From mahaboobnisha at gmail.com Tue Aug 24 08:21:10 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Tue, 24 Aug 2010 05:21:10 -0700 (PDT) Subject: comp.lang.python Message-ID: <7413e35a-ca4c-4838-98c6-d97fc9c7832d@x18g2000pro.googlegroups.com> www.127760.blogspot.com From blog at rivadpm.com Tue Aug 24 08:59:19 2010 From: blog at rivadpm.com (Alex McDonald) Date: Tue, 24 Aug 2010 05:59:19 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> <80befec3-be41-4166-8487-9a147131c7b9@s9g2000yqd.googlegroups.com> Message-ID: <12c3d3b0-e433-4748-8b5f-5087e4f72a7a@l6g2000yqb.googlegroups.com> On 24 Aug, 01:00, Hugh Aguilar wrote: > On Aug 21, 12:32?pm, Alex McDonald wrote: > > > "Scintilla" gets about 2,080,000 results on google; "blather" gets > > about 876,000 results. O Hugh, you pseudo-intellectual you! > > > > with gutter language such as > > > "turd" > > > About 5,910,000 results. It has a long history, even getting a mention > > in the Wyclif's 13th century bible. > > You looked up "blather" and "turd" on google *AND* you are not a > pseudo-intellectual??? That is funny! > > I don't consider myself to be a pseudo-intellectual. I don't have any > education however, so a pseudo-intellectual is the only kind of > intellectual that I could be. I don't have any formal CS education, nor a degree in anything else. But that doesn't make me an anti-intellectual by instinct (the instinct would be jealousy, I guess), nor does it stop me from learning. Or using Google, something I'm sure you do too. We have a great degree of admiration and fondness for intellectuals in Europe; the French in particular hold them in very high regard. Perhaps disdain of learning and further education is peculiar to a certain section of American society, as the label "intellectual" (often, "liberal intellectual") appears to be used as a derogatory term. I have no idea what a pseudo-intellectual might be, but it's evident you mean it in much the same way. From tundra at tundraware.com Tue Aug 24 09:06:04 2010 From: tundra at tundraware.com (Tim Daneliuk) Date: Tue, 24 Aug 2010 08:06:04 -0500 Subject: Using String Methods In Jump Tables In-Reply-To: <87fwy510ty.fsf@busola.homelinux.net> References: <87fwy510ty.fsf@busola.homelinux.net> Message-ID: On 8/23/2010 4:22 PM, Hrvoje Niksic wrote: > Tim Daneliuk writes: > >> You can get away with this because all string objects appear to point to common >> method objects. That is,: id("a".lower) == id("b".lower) > > A side note: your use of `id' has misled you. id(X)==id(Y) is not a > perfect substitue for the X is Y. :) > > "a".lower and "b".lower obviously cannot be the same object, because in > that case, how could they behave differently when called? > >>>> "a".lower() > 'a' >>>> "b".lower() # this should also return 'a' if "b".lower is the > # same object > 'b' > > Yet, id("a".lower) == id("b".lower) evaluates as True. > > What happens is, when the expression id("a".lower) == id("b.lower") is > evaluated, each of the bound method objects created with subexpressions > "a".lower" and "b".lower is referenced and thrown away as soon as "id" > is called (i.e. pretty much immediately), so the two never exist at the > same time. By the time "b".lower needs to be created, "a".lower is > freshly deceased, and the memory it used to occupy is ready for use, and > waiting at the top of the freelist. > > If CPython happened to use a different allocation/garbage collection > strategy and failed to reuse the same memory address immediately, your > code would just (happen to) work. Thanks for the clarification. -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From hniksic at xemacs.org Tue Aug 24 09:16:12 2010 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 24 Aug 2010 15:16:12 +0200 Subject: Contains/equals References: Message-ID: <87d3t8w3qb.fsf@busola.homelinux.net> Lawrence D'Oliveiro writes: > In message , Alex Hall > wrote: > >> def __eq__(self, obj): >> if self.a==obj.a and self.b==obj.b: return True >> return False > > Is there a ?Useless Use Of ...? award category for these ?if then > return True; else return False? constructs? Well, remember that self.a == obj.a can return something other than bool, and the and operator will evaluate to either False or the last value. Maybe he doesn't want to propagate the non-bools out of his __eq__. :) what's-next-"useless-use-of-"useless-use-of...""-ly y'rs From funthyme at gmail.com Tue Aug 24 09:49:08 2010 From: funthyme at gmail.com (John Pinner) Date: Tue, 24 Aug 2010 06:49:08 -0700 (PDT) Subject: Using String Methods In Jump Tables References: Message-ID: <98f1a235-3ee8-44ee-b886-3fc8ec7e46cf@5g2000yqz.googlegroups.com> On Aug 20, 12:27?am, Tim Daneliuk wrote: > Problem: > > ? Given tuples in the form (key, string), use 'key' to determine > ? what string method to apply to the string: > > ? ? key ? ? ? ? ? operation > ? ? ----------------------- > > ? ? ?l ? ? ? ? ? ?lower() > ? ? ?u ? ? ? ? ? ?upper() > ? ? ?t ? ? ? ? ? ?title() > ? ? ?... > > Commentary: > > ? ?Easy, right? ?Well ... except that I would really, really like > ? ?to avoid cascading ifs or eval based solutions. ?I'd like to implement > ? ?this as a jump table dictionary: > > ? ? ?jt = { 'l' : lower_function reference, > ? ? ? ? ? ? 'u' : upper_function reference, > ? ? ? ? ? ? ?... > ? ? ? ? ? } > > ? ?So I could then do this: > > ? ? ?string = jt[key](string) > > But There's A Problem: > > ? ?I tried to do this: > > ? ? ?jt = {'l', "".lower, > ? ? ? ? ? ?'u', "".upper, > ? ? ? ? ? ?... > ? ? ? ? ? } > > ? ?You can get away with this because all string objects appear to point to common > ? ?method objects. ?That is,: id("a".lower) == id("b".lower) > > ? ?HOWEVER, you cannot then do this: > > ? ? ?string = jt[key](string) > > ? ?Why? ?Because the methods of a string, while common to all strings > ? ?*do not accept an arg*. ?They are implemented to "know" about the > ? ?string instance they "belong to" (that contains them). > > (Forgive me here, I am probably not using some of the OO arcana properly...) > > I realize that the string module has many of the same functions that > are found as methods on strings. ?But it doesn't have all of them - > the .title() method is notably absent. ?If this were not the case, > I could happily do things like 'l' : string.lower ?and my approach > would work fine. ? > > Even if I could use the string module, I'd still be curious though: > > ? ?How do you get a reference to a method found in one object instance, but > ? ?actually apply it to another instance of the same class? ?I'm guessing this may > ? ?involve fiddling with some of the internal __ variables, but I'm not > ? ?quite sure where to go next. > > As I said, I know I could do this as a set of cascading ifs or even as an > eval, but I'm loathe to use such approaches. I like jump tables as a > structural construct because they are easy to understand and maintain. I > also realize that what I'm asking may be violating some deeply held notion > of OO purity, but, well, now I'm just curious if there is a way to do this I think the solution to what you are asking for is to use getattr(), eg: >>> ops={'u':'upper','l':'lower'} >>> s='hello world' >>> getattr( s, ops['u'] )() 'HELLO WORLD' >>> For info on getattr() see: http://docs.python.org/library/functions.html#getattr or http://effbot.org/zone/python-getattr.htm Best wishes, John -- From sschwarzer at sschwarzer.net Tue Aug 24 10:29:12 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 24 Aug 2010 16:29:12 +0200 Subject: ftplib limitations? In-Reply-To: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> Message-ID: <4C73D738.9030501@sschwarzer.net> Hi durumdara, On 2010-08-24 11:21, durumdara wrote: > def CallBack(Data): > d['size'] = d['size'] + len(Data) > d['buffer'].append(Data) > percent = (d['size'] / float(fsize)) * 100 > percentp10 = int(percent/10) > if percentp10 > d['lastpercentp10']: > d['lastpercentp10'] = percentp10 > print str(percentp10 * 10) + "%", > > ftp.retrbinary("retr " + s, CallBack) > print "" > print "..downloaded, joining" > dbuffer = "".join(d['buffer']) > [...] > This code is login into a site, download and delete all files. > > I experienced some problem. > The server is Windows and FileZilla, the client is Win7 and Python2.6. > When I got a file with size 1 303 318 662 byte, python is halt on > "retrbinary" line everytime. So if I understand correctly, the script works well on smaller files but not on the large one? > It down all of the file (100%) but the next line never reached. _Which_ line is never reached? The `print` statement after the `retrbinary` call? > Some error I got, but this was in yesterday, I don't remember the text > of the error. Can't you reproduce the error by executing the script once more? Can you copy the file to another server and see if the problem shows up there, too? I can imagine the error message (a full traceback if possible) would help to say a bit more about the cause of the problem and maybe what to do about it. Stefan From aahz at pythoncraft.com Tue Aug 24 10:54:45 2010 From: aahz at pythoncraft.com (Aahz) Date: 24 Aug 2010 07:54:45 -0700 Subject: iter References: Message-ID: In article , Terry Reedy wrote: > >Changing a list while iterating through it is possible, sometimes >useful, but error prone, especially with insert or delete. Changing a >dict while iterating through it is prohibited since the iteration order >depends on the exact internal structure. That in turn depends on the >history of additions and deletions. Although I agree in general with your warning, you are factually incorrect about dicts: >>> d = {1:2, 3:4} >>> i = iter(d) >>> i.next() 1 >>> d[1] = 'foo' >>> d {1: 'foo', 3: 4} Essentially, the prohibition is against changing the *keys* of lists and dicts (where list keys are the indexes). So what you can't do is add or delete dict keys and changing the position or order of list elements is a Bad Idea. But changing dict or list values is fine as long as you're careful that's *all* you're doing. Python newcomers are best off simply avoiding any list/dict mutation during iteration. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From ian at ianhobson.co.uk Tue Aug 24 11:25:30 2010 From: ian at ianhobson.co.uk (Ian Hobson) Date: Tue, 24 Aug 2010 16:25:30 +0100 Subject: adodbapi help needed Message-ID: <4C73E46A.7050207@ianhobson.co.uk> Hi all, I am just starting to learn Python and I have a setup problem - I think. Python 3.1. I have a small test script that is not working as expected. Start script----------- # coding=utf8 import adodbapi connectString = ( "DRIVER={MySQL ODBC 5.1 Driver} ;" "SERVER=127.0.0.1;" "PORT=3306;" "DATABASE=moschatel;" "USER=Moschatel;" "PASSWORD=badger43time;" "OPTION=3;" ) # MySQL ODBC 5.1 Driver - version 5.01.06.00 is installed db = adodbapi.connect(connectString) ------------end script -------------- I get an error message that reads D:\websites\moschatel\sop\Printing>test.py Traceback (most recent call last): File "D:\websites\moschatel\sop\Printing\test.py", line 13, in db = adodbapi.connect(connectString) AttributeError: 'module' object has no attribute 'connect' Now, adodbapi is installed into D:\websites\moschatel\sop\Printing\adodbapi and contains file adodbapi.py, and line 279 reads def connect(connection_string, timeout=30): I expected that to be called. What have I missed? Regards Ian From aahz at pythoncraft.com Tue Aug 24 11:37:59 2010 From: aahz at pythoncraft.com (Aahz) Date: 24 Aug 2010 08:37:59 -0700 Subject: Python parsing XML file problem with SAX References: Message-ID: In article , Stefan Behnel wrote: >Christian Heimes, 10.08.2010 01:39: >> Am 10.08.2010 01:20, schrieb Aahz: >>> The docs say, "Parses an XML section into an element tree incrementally". >>> Sure sounds like it retains the entire parsed tree in RAM. Not good. >>> Again, how do you parse an XML file larger than your available memory >>> using something other than SAX? >> >> The document at >> http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ explains it >> one way. >> >> The iterparser approach is ingenious but it doesn't work for every XML >> format. Let's say you have a 10 GB XML file with one million >> tags. An iterparser doesn't load the entire document. Instead it >> iterates over the file and yields (for example) one million ElementTrees >> for each tag and its children. You can get the nice API of >> ElementTree with the memory efficiency of a SAX parser if you obey >> "Listing 4". > >In the very common case that you are interested in all children of the root >element, it's even enough to intercept on the specific tag name (lxml.etree >has an option for that, but an 'if' block will do just fine in ET) and just >".clear()" the child element at the end of the loop body. That results in >very fast and simple code, but will leave the tags in the tree while only >removing their content and attributes. Usually works well enough for >several ten thousand elements, especially when using cElementTree. Thanks to both of you! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From sumit.jha50 at gmail.com Tue Aug 24 11:49:44 2010 From: sumit.jha50 at gmail.com (sumit) Date: Tue, 24 Aug 2010 08:49:44 -0700 (PDT) Subject: easy n perfect earning Message-ID: hey guys try dis link n make account...click on view adds...click on every add n leave it 4 60sec n once cmpleted click on my account n u vl c tat u got $40.. http://www.fineptc.com/index.php?ref=sumit4u2010 ...must try...i hav experienced and its safe From nanothermite911fbibustards at gmail.com Tue Aug 24 12:11:06 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 09:11:06 -0700 (PDT) Subject: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: <1ececad8-7f6b-412f-9eba-61ac82e7ae4f@j8g2000yqd.googlegroups.com> CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From nanothermite911fbibustards at gmail.com Tue Aug 24 12:17:57 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 09:17:57 -0700 (PDT) Subject: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: CENSORSHIP by GOOGLE NSA BUSTARDS deleted my earlier post dated Mon, Aug 23, 2010 at 7:33 PM from google groups. but its archived in the mailing lists linked to the various newsgroups. CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From dak at gnu.org Tue Aug 24 12:24:17 2010 From: dak at gnu.org (David Kastrup) Date: Tue, 24 Aug 2010 18:24:17 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> Message-ID: <87bp8sou6m.fsf@lola.goethe.zz> John Bokma writes: > On the other hand: some people I knew during my studies had no problem > at all with introducing countless memory leaks in small programs (and > turning off compiler warnings, because it gave so much noise...) [...] > As for electrical engineering: done that (BSc) and one of my class > mates managed to connect a transformer the wrong way > around.... twice. Yet he had the highest mark in our class. Anybody worth his salt in his profession has a trail of broken things in his history. The faster it thinned out, the better he learned. The only reliable way never to break a thing is not to touch it in the first place. But that will not help you if it decides to break on its own. -- David Kastrup From tim.arnold at sas.com Tue Aug 24 12:32:31 2010 From: tim.arnold at sas.com (Tim Arnold) Date: Tue, 24 Aug 2010 12:32:31 -0400 Subject: Working with PDFs? References: Message-ID: wrote in message news:mailman.2465.1282591017.1673.python-list at python.org... >> writes: > >>> - Pull out text from each PDF page (to search for specific words) >>> - Combine separate pdf documents into one document >>> - Add bookmarks (with destination settings) > >> PDF Shuffler is a Python app which does PDF merging and splitting very >> well. I don't think it does anything else, though, but maybe that's >> where your code comes in? > > Thank you Anssi, MRAB, Terry and Geremy for your replies. I've been > researching the apps you have recommended. Just curious if anyone has > used pyPdf? While testing this, it seems to work pretty well for > combining pdf files (seems to keep the annotation notes nicely also) > and pulling out the text contents. I'm not sure I'm going to be able > to find anything that can add bookmarks though. If you have used pyPdf, > would you mind sharing your thoughts about it? > > Thanks. > > Jay Hi Jay, I use pyPdf and I seem to remember I had to patch it so it didn't crash when a PDF dictionary contained duplicate keys. (the part that holds the document properties I think). Anyway, I use the package to get info from that document properties dictionary, page count and etc for displaying a build report to users of a customized LaTeX system. So I'm using LaTeX to generate the PDFs and pyPDF to glean data about the pdfs after the builds. I'd like to be able to do more with it, like find out whether any fonts in the doc are not embedded for example. --Tim Arnold From richie8105 at gmail.com Tue Aug 24 12:33:11 2010 From: richie8105 at gmail.com (richie05 bal) Date: Tue, 24 Aug 2010 09:33:11 -0700 (PDT) Subject: seach for pattern based on string Message-ID: <6054e266-4730-411e-9a27-9b501e6086cd@j8g2000yqd.googlegroups.com> i am starting to learn python and I am stuck with query I want to generate with python File looks something like this TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, publishingCompanyId 7} TRACE: AddNewBookD {bookId 21, noofBooks 6577, authorId 42, publishingCompanyId 8} I want to first search for AddNewBookD if found store bookId, noofBooks, authorId and publishingCompanyId I know how to search for only AddNewBookD or find the pattern bookId 20, noofBooks 6576, authorId 41, publishingCompanyId 7 but I don't know how search one based on another. From emile at fenx.com Tue Aug 24 13:08:28 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 24 Aug 2010 10:08:28 -0700 Subject: adodbapi help needed In-Reply-To: <4C73E46A.7050207@ianhobson.co.uk> References: <4C73E46A.7050207@ianhobson.co.uk> Message-ID: On 8/24/2010 8:25 AM Ian Hobson said... > Hi all, > > I am just starting to learn Python and I have a setup problem - I think. > Python 3.1. > > > def connect(connection_string, timeout=30): > > I expected that to be called. > > What have I missed? > The current revision includes the caveat: This module source should run correctly in CPython versions 2.3 and later, or IronPython version 2.6 and later, or, after running through 2to3.py, CPython 3.0 or later. Does that help? Emile From dani.valverde at gmail.com Tue Aug 24 13:15:11 2010 From: dani.valverde at gmail.com (Dani Valverde) Date: Tue, 24 Aug 2010 19:15:11 +0200 Subject: Declare self.cursor Message-ID: <4C73FE1F.5000206@gmail.com> Hello! I am working on a GUI to connect to a MySQL database using MySQLdb (code in attached file). I define the cursor in lines 55-66 in the OnLogin function within the LoginDlg class. /db= MySQLdb.connect(host='localhost', user=Username , passwd=pwd, db='Ornithobase') self.cursor = db.cursor()/ When I try to use the cursor on another part of the code (EditUser class, line 176) /sql = 'select substring_index(CURRENT_USER(),"@",1)' login.cursor.execute(sql)/ I get this error: /AttributeError: 'LoginDlg' object has no attribute 'cursor'/ You can check the code for details, I think is better. Cheers! Dani -- Daniel Valverde Saub? c/Joan Maragall 37 4 2 17002 Girona Spain Tel?fon m?bil: +34651987662 e-mail: dani.valverde at gmail.com http://www.acrocephalus.net http://natupics.blogspot.com Si no ?s del tot necessari, no imprimeixis aquest missatge. Si ho fas utilitza paper 100% reciclat i blanquejat sense clor. D'aquesta manera ajudar?s a estalviar aigua, energia i recursos forestals. GR?CIES! Do not print this message unless it is absolutely necessary. If you must print it, please use 100% recycled paper whitened without chlorine. By doing so, you will save water, energy and forest resources. THANK YOU! -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: OrnithobaseGUI.txt URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: dani_valverde.vcf Type: text/x-vcard Size: 296 bytes Desc: not available URL: From mwilson at the-wire.com Tue Aug 24 13:39:23 2010 From: mwilson at the-wire.com (Mel) Date: Tue, 24 Aug 2010 13:39:23 -0400 Subject: Declare self.cursor References: Message-ID: Dani Valverde wrote: > Hello! > I am working on a GUI to connect to a MySQL database using MySQLdb (code > in attached file). I define the cursor in lines 55-66 in the OnLogin > function within the LoginDlg class. > > /db= MySQLdb.connect(host='localhost', user=Username , passwd=pwd, > db='Ornithobase') > self.cursor = db.cursor()/ > > When I try to use the cursor on another part of the code (EditUser > class, line 176) > > /sql = 'select substring_index(CURRENT_USER(),"@",1)' > login.cursor.execute(sql)/ > > I get this error: > > /AttributeError: 'LoginDlg' object has no attribute 'cursor'/ > > You can check the code for details, I think is better. Did you actually click the loginBtn? Mel. From astan.chee at al.com.au Tue Aug 24 15:18:52 2010 From: astan.chee at al.com.au (Astan Chee) Date: Wed, 25 Aug 2010 05:18:52 +1000 Subject: equivalent of source in python? Message-ID: <4C741B1C.3080405@al.com.au> Hi, I'm trying to convert my tcsh script to python and am stuck at one part, particularly the part of the script that looks like this: #!/bin/tcsh setenv LSFLOG /var/tmp/lsf_log source /etc/setup unalias cp umask 0 env >> ${AFLOG} What is the equivalent of doing this in python2.5? Thanks again From mailtome200420032002 at gmail.com Tue Aug 24 15:21:31 2010 From: mailtome200420032002 at gmail.com (aj) Date: Tue, 24 Aug 2010 12:21:31 -0700 (PDT) Subject: make install DESTDIR References: <2d4110de-160d-415d-bdc3-60ca32f96158@q21g2000prm.googlegroups.com> <4C6FBBF4.40704@v.loewis.de> <719b45e3-0724-41cb-b3ad-ecde307629b0@a4g2000prm.googlegroups.com> <4C72E6BD.1020204@v.loewis.de> <4C735E01.3050709@v.loewis.de> Message-ID: On Aug 23, 10:52?pm, "Martin v. Loewis" wrote: > > Thanks Martin. That seems to work. I will file a bug report. Also, can > > you describe what the problem was? > > If you have / as the prefix, you get two leading slashes, e.g. for > //lib/python2.x. Any other prefix would have given you only a single > slash: e.g. if it had been /usr, then you end up with /usr/lib/python2.x. > > Now, the code strips the first character to make it a relative path name > (so that join can be used), which fails to work correctly if there are > two leading slashes. > > HTH, > Martin Thanks a lot for the help Martin. I have created http://bugs.python.org/issue9674 From dsdale24 at gmail.com Tue Aug 24 15:31:00 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Tue, 24 Aug 2010 12:31:00 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> Message-ID: <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> On Aug 23, 9:58?am, Darren Dale wrote: > The following script runs without problems on Ubuntu and Windows 7. > h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > h5py/): > > from multiprocessing import Pool > import h5py > > def update(i): > ? ? print i > > def f(i): > ? ? "hello foo" > ? ? return i*i > > if __name__ == '__main__': > ? ? pool = Pool() > ? ? for i in range(10): > ? ? ? ? pool.apply_async(f, [i], callback=update) > ? ? pool.close() > ? ? pool.join() > > On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > comment out the as-yet unused h5py import, otherwise I get a > traceback: > > Exception in thread Thread-1: > Traceback (most recent call last): > ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > lib/python2.6/threading.py", line 532, in __bootstrap_inner > ? ? self.run() > ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > lib/python2.6/threading.py", line 484, in run > ? ? self.__target(*self.__args, **self.__kwargs) > ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > lib/python2.6/multiprocessing/pool.py", line 226, in _handle_tasks > ? ? put(task) > PicklingError: Can't pickle : attribute lookup > __builtin__.function failed This is a really critical bug for me, but I'm not sure how to proceed. Can I file a bug report on the python bugtracker if the only code I can come up with to illustrate the problem requires a lame import of a third party module? From barry at python.org Tue Aug 24 15:31:46 2010 From: barry at python.org (Barry Warsaw) Date: Tue, 24 Aug 2010 15:31:46 -0400 Subject: Released: Python 2.6.6 Message-ID: <20100824153146.69874f04@heresy> Hello fellow Pythoneers and Pythonistas, I'm very happy to announce the release of Python 2.6.6. A truly impressive number of bugs have been fixed since Python 2.6.5. Source code and Windows installers for Python 2.6.6 are now available here: http://www.python.org/download/releases/2.6.6/ The full details of everything that's changed is available in the NEWS file: http://www.python.org/download/releases/2.6.6/NEWS.txt Python 2.6.6 marks the end of regular maintenance releases for the Python 2.6 series. From now until October 2013, only security related, source-only releases of Python 2.6 will be made available. After that date, Python 2.6 will no longer be supported, even for security bugs. My deepest appreciation go out to everyone who has helped contribute fixes great and small, and much testing and bug tracker gardening for Python 2.6.6. Enjoy, -Barry (on behalf of the Python development community) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: not available URL: From smallpox911 at gmail.com Tue Aug 24 15:36:28 2010 From: smallpox911 at gmail.com (small Pox) Date: Tue, 24 Aug 2010 12:36:28 -0700 (PDT) Subject: CRIMINAL YanQui MARINES BUSTARDS Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: CENSORSHIP by GOOGLE NSA BUSTARDS deleted my earlier post dated Mon, Aug 23, 2010 at 7:33 PM from google groups. but its archived in the mailing lists linked to the various newsgroups. CRIMINAL YanQui MARINES BUSTARDS Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From smallpox911 at gmail.com Tue Aug 24 15:38:00 2010 From: smallpox911 at gmail.com (small Pox) Date: Tue, 24 Aug 2010 12:38:00 -0700 (PDT) Subject: CRIMINAL YanQui MARINES BUSTARDS Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Message-ID: <156f547e-c730-4e16-9790-0c0636ddf12d@f42g2000yqn.googlegroups.com> CENSORSHIP by GOOGLE NSA BUSTARDS deleted my earlier post dated Mon, Aug 23, 2010 at 7:33 PM from google groups. but its archived in the mailing lists linked to the various newsgroups. CRIMINAL YanQui MARINES BUSTARDS Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA From steve.ferg.bitbucket at gmail.com Tue Aug 24 16:00:24 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Tue, 24 Aug 2010 13:00:24 -0700 (PDT) Subject: Help please! strange Tkinter behavior has me totally baffled. Message-ID: <6270b512-8b73-434d-83c3-ec5c60100eb1@w17g2000vbn.googlegroups.com> I have a short Python script that uses Tkinter to display an image. Here is the script =================================================================== import sys, os from Tkinter import * root = Tk() # A: create a global variable named "root" def showPicture(imageFilename): # global root #C: make root global root = Tk() # B: create a local variable named "root" imageFrame = Frame(root) imageFrame.pack() imageObject = PhotoImage(file=imageFilename) label = Label(imageFrame,image=imageObject) label.pack() root.mainloop() showPicture("python_and_check_logo.gif") =================================================================== The strange thing is that it crashes with this traceback... =================================================================== Traceback (most recent call last): File "easygui_test3.py", line 19, in showPicture("python_and_check_logo.gif") File "easygui_test3.py", line 14, in showPicture label = Label(imageFrame,image=imageObject) File "L:\FergLabstatPublic\Python26\lib\lib-tk\Tkinter.py", line 2474, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "L:\FergLabstatPublic\Python26\lib\lib-tk\Tkinter.py", line 1940, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "pyimage1" doesn't exist =================================================================== If I comment out either line A or line B, the script works fine. What I don't understand is why creating a global "root" variable and a local "root" variable causes the script to crash. Even more puzzling... if I uncomment line C, so that "root" in line B refers to a global "root" variable, the script still crashes. I'm totally baffled. Does anybody know what is going on here? -- Steve Ferg (I'm running Python 2.6 under Windows, but I get the same behavior under Solaris.) From news1234 at free.fr Tue Aug 24 16:01:19 2010 From: news1234 at free.fr (News123) Date: Tue, 24 Aug 2010 22:01:19 +0200 Subject: equivalent of source in python? In-Reply-To: References: Message-ID: <4c742513$0$9846$426a74cc@news.free.fr> On 08/24/2010 09:18 PM, Astan Chee wrote: > Hi, > I'm trying to convert my tcsh script to python and am stuck at one part, > particularly the part of the script that looks like this: > > #!/bin/tcsh > setenv LSFLOG /var/tmp/lsf_log > source /etc/setup > unalias cp > umask 0 > env >> ${AFLOG} > > What is the equivalent of doing this in python2.5? > Thanks again the equivalent would be exec(), but I'm not sure, that it is a good idea to try to make a word by word translation of a shell script into python. you could do exec( open("/etc/setup").read() ) but of course you had to translate /etc/setup to python. From steve.ferg.bitbucket at gmail.com Tue Aug 24 16:06:06 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Tue, 24 Aug 2010 13:06:06 -0700 (PDT) Subject: Questions, newbies, and community (was: python terminology on classes) References: <8e60e2db-205d-4b8b-9c19-1d46e2318cb8@h20g2000vbs.googlegroups.com> <87tyna2dc7.fsf_-_@benfinney.id.au> Message-ID: I stand corrected. I didn't know the background. Thanks for supplying the larger picture. :-) From sschwarzer at sschwarzer.net Tue Aug 24 16:12:06 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 24 Aug 2010 22:12:06 +0200 Subject: equivalent of source in python? In-Reply-To: References: Message-ID: <4C742796.8020904@sschwarzer.net> Hi Astan, On 2010-08-24 21:18, Astan Chee wrote: > I'm trying to convert my tcsh script to python and am stuck at one part, > particularly the part of the script that looks like this: > > #!/bin/tcsh > setenv LSFLOG /var/tmp/lsf_log > source /etc/setup > unalias cp > umask 0 > env >> ${AFLOG} > > What is the equivalent of doing this in python2.5? I guess it doesn't make sense to "translate" this to Python line by line. For example, you can't "source" shell code into a Python program. The above commands don't look as if they were the purpose of the program, but rather mostly some preparation/setup before solving the actual problem. Maybe it's more helpful to tell us what you want to achieve in the end and we might be able to make suggestions on that. How long is the shell script and what's your Python code so far? Stefan From clp2 at rebertia.com Tue Aug 24 16:28:42 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 24 Aug 2010 13:28:42 -0700 Subject: equivalent of source in python? In-Reply-To: <4C741B1C.3080405@al.com.au> References: <4C741B1C.3080405@al.com.au> Message-ID: On Tue, Aug 24, 2010 at 12:18 PM, Astan Chee wrote: > Hi, > I'm trying to convert my tcsh script to python and am stuck at one part, > particularly the part of the script that looks like this: > > #!/bin/tcsh > setenv LSFLOG /var/tmp/lsf_log > source /etc/setup > unalias cp > umask 0 > env >> ${AFLOG} > > What is the equivalent of doing this in python2.5? I agree with Stefan, but anyway, here's an approximate untested literal translation: import os import subprocess os.environ['LSFLOG'] = '/var/tmp/lsf_log' subprocess.check_call(['tcsh', '/etc/setup']) os.umask(0) out = open(os.environ['AFLOG'], 'a') subprocess.check_call(['env'], stdout=out) out.close() Cheers, Chris -- http://blog.rebertia.com From emile at fenx.com Tue Aug 24 16:32:26 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 24 Aug 2010 13:32:26 -0700 Subject: equivalent of source in python? In-Reply-To: <4C741B1C.3080405@al.com.au> References: <4C741B1C.3080405@al.com.au> Message-ID: On 8/24/2010 12:18 PM Astan Chee said... > Hi, > I'm trying to convert my tcsh script to python and am stuck at one part, > particularly the part of the script that looks like this: > > #!/bin/tcsh > setenv LSFLOG /var/tmp/lsf_log > source /etc/setup > unalias cp > umask 0 > env >> ${AFLOG} > > What is the equivalent of doing this in python2.5? > Thanks again source == import * Although that's generally considered non-pythonic. Emile From thomas at jollybox.de Tue Aug 24 16:32:29 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 24 Aug 2010 22:32:29 +0200 Subject: problem with simple multiprocessing script on OS X In-Reply-To: <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: <201008242232.29481.thomas@jollybox.de> On Tuesday 24 August 2010, it occurred to Darren Dale to exclaim: > On Aug 23, 9:58 am, Darren Dale wrote: > > The following script runs without problems on Ubuntu and Windows 7. > > h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > > h5py/): > > > > from multiprocessing import Pool > > import h5py > > > > def update(i): > > print i > > > > def f(i): > > "hello foo" > > return i*i > > > > if __name__ == '__main__': > > pool = Pool() > > for i in range(10): > > pool.apply_async(f, [i], callback=update) > > pool.close() > > pool.join() > > > > On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > > comment out the as-yet unused h5py import, otherwise I get a > > traceback: What on earth is h5py doing there? If what you're telling us is actually happening, and the code works 1:1 on Linux and Windows, but fails on OSX, and you're using the same versions of h5py and Python, then the h5py initialization code is not only enticing multiprocessing to try to pickle something other than usual, but it is also doing that due to some platform- dependent witchcraft, and I doubt there's very much separating the OSX versions from the Linux versions of anything involved. > This is a really critical bug for me, but I'm not sure how to proceed. > Can I file a bug report on the python bugtracker if the only code I > can come up with to illustrate the problem requires a lame import of a > third party module? I doubt this is an issue with Python. File a bug on the h5py tracker and see what they say. The people there might at least have some vague inkling of what may be going on. From thomas at jollybox.de Tue Aug 24 16:36:00 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 24 Aug 2010 22:36:00 +0200 Subject: equivalent of source in python? In-Reply-To: <4c742513$0$9846$426a74cc@news.free.fr> References: <4c742513$0$9846$426a74cc@news.free.fr> Message-ID: <201008242236.01193.thomas@jollybox.de> On Tuesday 24 August 2010, it occurred to News123 to exclaim: > On 08/24/2010 09:18 PM, Astan Chee wrote: > > Hi, > > I'm trying to convert my tcsh script to python and am stuck at one part, > > particularly the part of the script that looks like this: > > > > #!/bin/tcsh > > setenv LSFLOG /var/tmp/lsf_log > > source /etc/setup > > unalias cp > > umask 0 > > env >> ${AFLOG} > > > > What is the equivalent of doing this in python2.5? > > Thanks again > > the equivalent would be exec(), but I'm not sure, that it is a good idea > to try to make a > word by word translation of a shell script into python. > > > you could do > exec( open("/etc/setup").read() ) Rather use execfile here. Though you'd probably rather want to write a Python module and use it as such (you know, import). > > but of course you had to translate /etc/setup > > to python. From hobson42 at gmaiil.com Tue Aug 24 16:38:55 2010 From: hobson42 at gmaiil.com (Ian) Date: Tue, 24 Aug 2010 21:38:55 +0100 Subject: adodbapi help needed In-Reply-To: References: <4C73E46A.7050207@ianhobson.co.uk> Message-ID: <4C742DDF.7000608@gmaiil.com> On 24/08/2010 18:08, Emile van Sebille wrote: > On 8/24/2010 8:25 AM Ian Hobson said... >> Hi all, >> >> I am just starting to learn Python and I have a setup problem - I think. >> Python 3.1. >> > > > >> >> def connect(connection_string, timeout=30): >> >> I expected that to be called. >> >> What have I missed? >> > > > > The current revision includes the caveat: > > This module source should run correctly in CPython versions 2.3 and > later, or IronPython version 2.6 and later, or, after running through > 2to3.py, CPython 3.0 or later. > > Does that help? > > Emile > Thanks for the response Emile, I have also removed all my Python installations and started again - with same result. After installing Python3.1 and pywin32-214.win32-py3.1.exe (which includes adodbapi) I was getting System does not exist. I have run 2to3.py on adodbapi and I still get this trackback. D:\websites\moschatel\sop\Printing>test.py Traceback (most recent call last): File "D:\websites\moschatel\sop\Printing\test.py", line 16, in import adodbapi File "C:\Python31\lib\site-packages\adodbapi\__init__.py", line 1, in from .adodbapi import * File "C:\Python31\lib\site-packages\adodbapi\adodbapi.py", line 57, in from System import Activator, Type, DBNull, DateTime, Array, Byte ImportError: No module named System I suspect that is movement, not progress. :) Regards Ian From raymond.hettinger at gmail.com Tue Aug 24 16:40:11 2010 From: raymond.hettinger at gmail.com (Raymond Hettinger) Date: Tue, 24 Aug 2010 13:40:11 -0700 Subject: [Python-Dev] Released: Python 2.6.6 In-Reply-To: <20100824153146.69874f04@heresy> References: <20100824153146.69874f04@heresy> Message-ID: On Aug 24, 2010, at 12:31 PM, Barry Warsaw wrote: > Hello fellow Pythoneers and Pythonistas, > > I'm very happy to announce the release of Python 2.6.6. Thanks Barry :-) Raymond From ahleniusm at gmail.com Tue Aug 24 16:45:12 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Tue, 24 Aug 2010 13:45:12 -0700 (PDT) Subject: problem with strptime and time zone Message-ID: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> Hi, perhaps I missed this posted already somewhere. I am got a program which reads time stings from some devices which are providing the time zones. I have to take this into account when doing some epoch time calculations. When I run the following code with the time zone string set to 'GMT' it works ok. This works: myStrA = 'Sun Aug 22 19:03:06 GMT' gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') print "gTimeA = ",gTimeA --- But when its set to 'PDT' it fails. Any ideas? whereas this fails: myStrA = 'Sun Aug 22 19:03:06 PDT' gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') print "gTimeA = ",gTimeA ValueError: time data 'Sun Aug 22 19:03:06 PDT' does not match format '%a %b %d %H:%M:%S %Z' thank you, From astan.chee at al.com.au Tue Aug 24 16:50:32 2010 From: astan.chee at al.com.au (Astan Chee) Date: Wed, 25 Aug 2010 06:50:32 +1000 Subject: equivalent of source in python? In-Reply-To: References: <4C741B1C.3080405@al.com.au> Message-ID: <4C743098.5010304@al.com.au> Thanks for all the help. I think Chris's answer is the one I can use. I know its probably better to convert the /etc/setup file into python but it'll do for now. Also, the entire tsch script is just setting up env vars and such; various mvs and cps. Not really executing anything. Thanks again for the help. Chris Rebert wrote: > On Tue, Aug 24, 2010 at 12:18 PM, Astan Chee wrote: > >> Hi, >> I'm trying to convert my tcsh script to python and am stuck at one part, >> particularly the part of the script that looks like this: >> >> #!/bin/tcsh >> setenv LSFLOG /var/tmp/lsf_log >> source /etc/setup >> unalias cp >> umask 0 >> env >> ${AFLOG} >> >> What is the equivalent of doing this in python2.5? >> > > I agree with Stefan, but anyway, here's an approximate untested > literal translation: > > import os > import subprocess > > os.environ['LSFLOG'] = '/var/tmp/lsf_log' > subprocess.check_call(['tcsh', '/etc/setup']) > os.umask(0) > out = open(os.environ['AFLOG'], 'a') > subprocess.check_call(['env'], stdout=out) > out.close() > > Cheers, > Chris > -- > http://blog.rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 24 16:56:55 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 24 Aug 2010 22:56:55 +0200 Subject: Help please! strange Tkinter behavior has me totally baffled. References: <6270b512-8b73-434d-83c3-ec5c60100eb1@w17g2000vbn.googlegroups.com> Message-ID: Steve Ferg wrote: > I have a short Python script that uses Tkinter to display an image. > Here is the script > > =================================================================== > import sys, os > from Tkinter import * > root = Tk() # A: create a global variable named "root" > > def showPicture(imageFilename): > # global root #C: make root global > root = Tk() # B: create a local variable named "root" > > imageFrame = Frame(root) > imageFrame.pack() > > imageObject = PhotoImage(file=imageFilename) > > label = Label(imageFrame,image=imageObject) > label.pack() > > root.mainloop() > > showPicture("python_and_check_logo.gif") > =================================================================== > > The strange thing is that it crashes with this traceback... > > =================================================================== > > Traceback (most recent call last): > File "easygui_test3.py", line 19, in > showPicture("python_and_check_logo.gif") > File "easygui_test3.py", line 14, in showPicture > label = Label(imageFrame,image=imageObject) > File "L:\FergLabstatPublic\Python26\lib\lib-tk\Tkinter.py", line > 2474, in __init__ > Widget.__init__(self, master, 'label', cnf, kw) > File "L:\FergLabstatPublic\Python26\lib\lib-tk\Tkinter.py", line > 1940, in __init__ > (widgetName, self._w) + extra + self._options(cnf)) > _tkinter.TclError: image "pyimage1" doesn't exist > > =================================================================== > > If I comment out either line A or line B, the script works fine. > > What I don't understand is why creating a global "root" variable and a > local "root" variable causes the script to crash. > > Even more puzzling... if I uncomment line C, so that "root" in line B > refers to a global "root" variable, the script still crashes. > > I'm totally baffled. Does anybody know what is going on here? > > -- Steve Ferg > (I'm running Python 2.6 under Windows, but I get the same behavior > under Solaris.) Tkinter.Tk() creates a new Tcl interpreter. Are you sure you want that? The standard way to create an additional window is Tkinter.Toplevel(). The PhotoImage is created in the default (first) interpreter and then looked up in the Label's (second) interpreter. At least that's what I would infer from class Image: """Base class for images.""" _last_id = 0 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): self.name = None if not master: master = _default_root if not master: raise RuntimeError, 'Too early to create image' self.tk = master.tk in the Tkinter source which also makes it plausible that you can avoid the problem by specifying an explicit master def showPicture(imageFilename): root = Tk() # ... imageObject = PhotoImage(file=imageFilename, master=root) # ... Peter From nanothermite911fbibustards at gmail.com Tue Aug 24 17:01:14 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 14:01:14 -0700 (PDT) Subject: YANQUI cry babies concerned that Iran has achieved parity in DRONES and against the massive AIRCRAFT carriers which are like SITTING DUCKS. A nation needs AIRCRAFT carriers to venture out for IMPERIALISTIC assaults but cant go out on speed boats. References: <156f547e-c730-4e16-9790-0c0636ddf12d@f42g2000yqn.googlegroups.com> Message-ID: <5383f461-3549-4674-b490-e2183fcf4be9@v8g2000yqe.googlegroups.com> This was censored by google or removed by some KhazarJew/YanQui hacker. I am reposting from python list : YANQUI cry babies concerned that Iran has achieved parity in DRONES and against the massive AIRCRAFT carriers which are like SITTING DUCKS. A nation needs AIRCRAFT carriers to venture out for IMPERIALISTIC assaults but cant go out on speed boats. Yet the NUMEROUS fast boats can sink the AIRCRAFT carrier and make it a SAILING COFFIN. http://www.google.com/hostednews/afp/article/ALeqM5gYlBmnQz28otk-w_hvx1pZ5C= bl0w US concerned about Iran's assault boats, drone (AFP) =96 5 hours ago WASHINGTON =97 The United States voiced concern Monday over Iran's unveiling of new assault boats and an aerial drone, but said Iran's arms buildup will backfire as its neighbors gang up against it. Iran began mass-producing two high-speed variants of missile- launching assault boats on Monday, a day after Iranian President Mahmoud Ahmadinejad revealed a home-built bomber drone. "This is... something that is of concern to us and... concern to Iran's neighbors," State Department spokesman Philip Crowley told reporters. He said that while every country had the right to provide for its self- defense, the United States takes into account "systems that can potentially... threaten particular countries or peace and stability in the region." Faced with "the growth of Iran's capabilities over a number of years, we've stepped up our military cooperation with other countries in the region," Crowley said. "This is one of the reasons why... we believe that if Iran continues on the path that it's on... (it) might find itself less secure because you'll have countries in the region that join together to offset Iran's growing capabilities." He added that the United States is still open to "constructive dialogue" with Iran to answer questions it and the world community have about its nuclear program, which Washington fears is aimed at building a bomb. "But in the meantime, we will work with other countries to try to do everything that we can to maintain peace and stability in the region," Crowley said. Copyright =A9 2010 AFP. All rights reserved -- http://mail.python.org/mailman/listinfo/python-list > Asked by a Mexican reporter at the time of his arrest whether he > killed Lauterbach, Laurean replied, "I loved her." > > Laurean's lawyer said his client would appeal the decision. > > ///////////////////////////////////////////////////////////////// > > The MARINE BASTARD will probably claim INSANITY ........ > > ////////////////////// > The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE > is UNACCEPTABLE. > > ===== > > http://www.youtube.com/watch?v=lX18zUp6WPY > > http://www.youtube.com/watch?v=XQapkVCx1HI > > http://www.youtube.com/watch?v=tXJ-k-iOg0M > > Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? > Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did > you release the 5 dancing Israelis compromising the whole 911 > investigation ? If the Dubai Police can catch Mossad Murderers and put > the videos and Iranian Police can why cant you put the Pentagon > Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and > puting on INTERNATIONAL MEDIA a day after catching him without > TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did > you have to LIE about Dr Afiya Siddiqui and torture that Innocent > little mother of 3 and smashing the skull of her one child ? > > http://www.youtube.com/watch?v=DhMcii8smxkhttp://www.youtube.com/watch?v=0SZ2lxDJmdg > > There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian > courts. > > FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but > only because he was a white. They got away with MURDER of thousands of > Non-whites in all parts of the world. > > Daily 911 news :http://911blogger.com > > http://www.youtube.com/watch?v=tRfhUezbKLw > > http://www.youtube.com/watch?v=x7kGZ3XPEm4 > > http://www.youtube.com/watch?v=lX18zUp6WPY > > Conclusion : FBI bustards are RACIST and INcompetent. They could > neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they > cover them up - whichever was their actual goal or task. > > SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across > tbe board, esp the whites/jew on the top. > > FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and > UNPATRIOTIC Act > FBI bustards failed to prevent ROMAN POLANSKY from absconding to > europe and rapes. > FBI bustards failed to prevent OKLAHOMA From alex at moreati.org.uk Tue Aug 24 17:05:50 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 24 Aug 2010 14:05:50 -0700 (PDT) Subject: seach for pattern based on string References: <6054e266-4730-411e-9a27-9b501e6086cd@j8g2000yqd.googlegroups.com> Message-ID: On Aug 24, 5:33?pm, richie05 bal wrote: > i am starting to learn python and I am stuck with query I want to > generate with python > File looks something like this > TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, > publishingCompanyId 7} > TRACE: AddNewBookD {bookId 21, noofBooks 6577, authorId 42, > publishingCompanyId 8} > > I want to first search for AddNewBookD > if found > ? ?store bookId, noofBooks, authorId and publishingCompanyId > > I know how to search for only AddNewBookD or find the pattern bookId > 20, noofBooks 6576, authorId 41, publishingCompanyId 7 but I don't > know how search one based on another. Using a regular expression I would perform a match against each line. If the match fails, it will return None. If the match succeeds it returns a match object with which you can extract the values >>> import re >>> pattern = re.compile(r'TRACE: AddNewBookD \{bookId (\d+), noofBooks (\d+), authorId (\d+), publishingCompanyId (\d+)\}\s*') >>> s = '''TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, publishingCompanyId 7} ''' >>> pattern.match(s) <_sre.SRE_Match object at 0xa362f40> # If the match failed this would be None >>> m = pattern.match(s) >>> m.groups() ('20', '6576', '41', '7') >>> So your code to store the result would be inside an if m: block HTH, Alex From rowlett at pcnetinc.com Tue Aug 24 17:12:32 2010 From: rowlett at pcnetinc.com (Richard Owlett) Date: Tue, 24 Aug 2010 16:12:32 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <87bp8sou6m.fsf@lola.goethe.zz> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <87bp8sou6m.fsf@lola.goethe.zz> Message-ID: David Kastrup wrote: > John Bokma writes: > >> On the other hand: some people I knew during my studies had no problem >> at all with introducing countless memory leaks in small programs (and >> turning off compiler warnings, because it gave so much noise...) > > [...] > >> As for electrical engineering: done that (BSc) and one of my class >> mates managed to connect a transformer the wrong way >> around.... twice. Yet he had the highest mark in our class. > > Anybody worth his salt in his profession has a trail of broken things in > his history. The faster it thinned out, the better he learned. The > only reliable way never to break a thing is not to touch it in the first > place. But that will not help you if it decides to break on its own. > *LOL* !!! I remember the day a very senior field service engineer for a multi-national minicomputer mfg plugged 16k (or was it 32k) of core (back when a core was visible to naked eye ;) the wrong way into a backplane. After the smoke cleared ... snicker snicker. I also remember writing a failure report because someone installed a grounding strap 100 degrees out of orientation on a piece of multi kV switchgear.(don't recall nominal capacity, buck backup generator was rated for 1.5 MW continuous ;) P.S. failure was demonstrated as manufacturer's senior sales rep was demonstrating how easy it was to do maintenance on the system. There were times I had fun writing up inspection reports. From alex at moreati.org.uk Tue Aug 24 17:16:01 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 24 Aug 2010 14:16:01 -0700 (PDT) Subject: problem with strptime and time zone References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> Message-ID: <45faa241-620e-42c7-b524-949936f63610@f6g2000yqa.googlegroups.com> On Aug 24, 9:45?pm, m_ahlenius wrote: > > whereas this fails: > myStrA = 'Sun Aug 22 19:03:06 PDT' > gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') > print "gTimeA = ",gTimeA > > ValueError: time data 'Sun Aug 22 19:03:06 PDT' does not match format > '%a %b %d %H:%M:%S %Z' Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform- specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones). http://docs.python.org/library/time.html Dateutil has it's own timezone database, so should work reliably http://labix.org/python-dateutil From emile at fenx.com Tue Aug 24 17:17:22 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 24 Aug 2010 14:17:22 -0700 Subject: adodbapi help needed In-Reply-To: <4C742DDF.7000608@gmaiil.com> References: <4C73E46A.7050207@ianhobson.co.uk> <4C742DDF.7000608@gmaiil.com> Message-ID: On 8/24/2010 1:38 PM Ian said... > On 24/08/2010 18:08, Emile van Sebille wrote: >> On 8/24/2010 8:25 AM Ian Hobson said... >>> Hi all, >>> >>> I am just starting to learn Python and I have a setup problem - I think. >>> Python 3.1. >>> >> >> >> >>> >>> def connect(connection_string, timeout=30): >>> >>> I expected that to be called. >>> >>> What have I missed? >>> >> >> >> >> The current revision includes the caveat: >> >> This module source should run correctly in CPython versions 2.3 and >> later, or IronPython version 2.6 and later, or, after running through >> 2to3.py, CPython 3.0 or later. >> >> Does that help? >> >> Emile >> > Thanks for the response Emile, > > I have also removed all my Python installations and started again - with > same result. > After installing Python3.1 and pywin32-214.win32-py3.1.exe (which > includes adodbapi) > I was getting System does not exist. > > I have run 2to3.py on adodbapi and I still get this trackback. > > D:\websites\moschatel\sop\Printing>test.py > Traceback (most recent call last): > File "D:\websites\moschatel\sop\Printing\test.py", line 16, in > import adodbapi > File "C:\Python31\lib\site-packages\adodbapi\__init__.py", line 1, in > > > from .adodbapi import * > File "C:\Python31\lib\site-packages\adodbapi\adodbapi.py", line 57, in > > > from System import Activator, Type, DBNull, DateTime, Array, Byte > ImportError: No module named System > > I suspect that is movement, not progress. :) > In a windows environment 3.x and 2.x live side-by-side without issues. I haven't made the jump yet to using 3.x for production, but as the warning says "... should run correctly ..." I'd try next with activestate's 2.x version which should come with all the right bits and pieces, and particularly as you're just starting out using 2.x shouldn't matter much. HTH, Emile From clp2 at rebertia.com Tue Aug 24 17:23:31 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 24 Aug 2010 14:23:31 -0700 Subject: problem with strptime and time zone In-Reply-To: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> Message-ID: On Tue, Aug 24, 2010 at 1:45 PM, m_ahlenius wrote: > Hi, > > perhaps I missed this posted already somewhere. > > I am got a program which reads time stings from some devices which > are ?providing the time zones. ?I have to take this into account when > doing some epoch time calculations. > > When I run the following code with the time zone string set to 'GMT' > it works ok. > > This works: > > myStrA = 'Sun Aug 22 19:03:06 GMT' > > gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') > > print "gTimeA = ",gTimeA > > --- > > whereas this fails: > myStrA = 'Sun Aug 22 19:03:06 PDT' > gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') > print "gTimeA = ",gTimeA > > > ValueError: time data 'Sun Aug 22 19:03:06 PDT' does not match format > '%a %b %d %H:%M:%S %Z' > > But when its set to 'PDT' it fails. > > Any ideas? Read The Fine Manual. Quoth http://docs.python.org/library/time.html#time.strptime : """ time.strptime(string[, format]) [...] Support for the %Z directive is based on the values contained in time.tzname and whether time.daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones). """ Cheers, Chris -- http://blog.rebertia.com From benjamin.kaplan at case.edu Tue Aug 24 17:29:16 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 24 Aug 2010 17:29:16 -0400 Subject: problem with simple multiprocessing script on OS X In-Reply-To: <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: On Tue, Aug 24, 2010 at 3:31 PM, Darren Dale wrote: > On Aug 23, 9:58?am, Darren Dale wrote: >> The following script runs without problems on Ubuntu and Windows 7. >> h5py is a package wrapping the hdf5 library (http://code.google.com/p/ >> h5py/): >> >> from multiprocessing import Pool >> import h5py >> >> def update(i): >> ? ? print i >> >> def f(i): >> ? ? "hello foo" >> ? ? return i*i >> >> if __name__ == '__main__': >> ? ? pool = Pool() >> ? ? for i in range(10): >> ? ? ? ? pool.apply_async(f, [i], callback=update) >> ? ? pool.close() >> ? ? pool.join() >> >> On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to >> comment out the as-yet unused h5py import, otherwise I get a >> traceback: >> >> Exception in thread Thread-1: >> Traceback (most recent call last): >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ >> lib/python2.6/threading.py", line 532, in __bootstrap_inner >> ? ? self.run() >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ >> lib/python2.6/threading.py", line 484, in run >> ? ? self.__target(*self.__args, **self.__kwargs) >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ >> lib/python2.6/multiprocessing/pool.py", line 226, in _handle_tasks >> ? ? put(task) >> PicklingError: Can't pickle : attribute lookup >> __builtin__.function failed > > > This is a really critical bug for me, but I'm not sure how to proceed. > Can I file a bug report on the python bugtracker if the only code I > can come up with to illustrate the problem requires a lame import of a > third party module? > -- It's working fine for me, OS X 10.6.4, Python 2.6 and h5py from Macports. From nanothermite911fbibustards at gmail.com Tue Aug 24 17:46:43 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 14:46:43 -0700 (PDT) Subject: Iran's self-defense options 'limitless' - against the YANQUI and KHAZAR Bustards - Brilliant ANALYSIS References: <156f547e-c730-4e16-9790-0c0636ddf12d@f42g2000yqn.googlegroups.com> <5383f461-3549-4674-b490-e2183fcf4be9@v8g2000yqe.googlegroups.com> Message-ID: <896d73ff-13c0-4235-87df-51572c291305@j8g2000yqd.googlegroups.com> Iran's self-defense options 'limitless' - against the YANQUI and KHAZAR Bustards - Brilliant ANALYSIS Iran's self-defense options 'limitless' Tue Aug 24, 2010 12:9AM President Mahmoud AhmadinejadIran's President Mahmoud Ahmadinejad says no military action is expected to be taken against the Islamic Republic since enemies are aware of Iran's reaction. "Iran is not concerned by a prospective military attack by any country, although it is always prepared to defend itself," Ahmadinejad said in an interview with Qatar's al-Sharq and the Peninsula newspapers on Monday. "Enemies know well that Iran is an invincible fortress and I do not believe the US masters of the Zionists will allow the regime [in Tel Aviv] to take any measures against Iran," noted the Iranian chief executive. Asked about Iran's options in the case it is attacked, Ahmadinejad said, "Iran has limitless options which extends to all parts of the world." Commenting on the Israeli threats against Iran's sovereignty over the county's nuclear enrichment program, the Iranian president pointed out that "Israel is too weak to stage a military strike against Iran, but if it attacks, it will receive a devastating response, which will make it regret its aggression." He also dismissed the idea that Arab countries' soil would be used to launch attacks on Iran, saying that the "leaders of these countries are more prudent than that.? Ahmadinejad further downplayed US military might in its current wars in the Middle East region and rejected the speculations that an imminent war against Iran was the cause of the US troops' withdrawal from Iraq. GHN/MGH ============ BRILLIANT ANALYSIS http://www.tehrantimes.com/index_View.asp?code=225469 View Rate : 1531 # News Code : TTime- 225469 Print Date : Tuesday, August 24, 2010 ?Iran will stand beside any country threatened in region? Ahmadinejad: Israel lacks courage to attack Iran TEHRAN ? Iranian President Mahmoud Ahmadinejad says that Iran will stand beside any country in the region that is threatened. ?Iran will stand on the side of any country in the region which comes under pressure or is threatened,? Ahmadinejad said in an interview with Arabic satellite television network Al Jazeera aired on Sunday. He also said he doesn?t think the threats by the United States and Israel to attack Iran are ?serious?. ?Israel does not have the courage to do it? I do not think the threat is serious.? Ahmadinejad also stated that Israel is ?too weak? to attack the Islamic Republic. The Iranian president said that any military adventure by the Zionist regime targeting Iran would receive a ?crushing? response that would make Israel regret the decision. He went on to say that Persian Gulf states are ?too smart? to allow the U.S. to use bases on their territory for a strike on Iran. ?We regard the Persian Gulf countries as brothers and friends. They are smarter than that.? In the interview, the president also said he does not fear an attack by the U.S. because it could not even defeat a small army in Iraq. ?There are no logical reasons for the United States to carry out such an act,? President Ahmadinejad told Al Jazeera. ?Do you believe an army that has been defeated by a small army in Iraq can enter into a war with a large and well trained army like the Iranian army?? he asked, referring to the insurgents in Iraq. Iran will only ?look to the views of wise people? in the U.S. and not to those whose minds are obsessed with ?hatred and animosity?, the president said when asked about former U.S. ambassador to the UN John Bolton?s remarks, which had apparently encouraged Israel to attack the Bushehr plant before its start-up. Washington has no real motive to attack Iran and would not benefit from hostilities, he added. ?The friendship of Iran is much better than its hostility,? he said. He went on to say that Iran is working to produce nuclear fuel independently ?because receiving it from an outside source is conditioned on diplomatic criteria.? To prevent Iran from using the Bushehr reactor to produce plutonium, inspectors from the International Atomic Energy Agency and Russia, which built the power plant, are making sure Iran returns the fuel rods it receives after they are spent. ?There is a difference between those who produce and those who buy. We must make sure our nuclear power plant continues to operate. We do not trust the West, despite our good relations with Russia,? Ahmadinejad said. ?We need 20 power plants like the one in Bushehr,? he added. -- http://mail.python.org/mailman/listinfo/python-list From hughaguilar96 at yahoo.com Tue Aug 24 17:48:09 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 14:48:09 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> Message-ID: <91927894-a2b3-46df-801e-577f0e68e8be@l20g2000yqm.googlegroups.com> On Aug 21, 12:18?pm, ehr... at dk3uz.ampr.org (Edmund H. Ramm) wrote: > In <2d59bfaa-2aa5-4396-bd03-22200df8c... at x21g2000yqa.googlegroups.com> Hugh Aguilar writes: > > > [...] > > I really recommend that people spend a lot more time writing code, > > and a lot less time with all of this pseudo-intellectual nonsense. > > [...] > > ? ?I energetically second that! > -- > ? ? ? e-mail: dk3uz AT arrl DOT net ?| ?AMPRNET: dk... at db0hht.ampr.org > ? ? ? If replying to a Usenet article, please use above e-mail address. > ? ? ? ? ? ? ? ?Linux/m68k, the best U**x ever to hit an Atari! What open-source code have you posted publicly? BTW, why did you request that your post not be archived, and be removed in a few days? That doesn't seem very energetic. Also, now that I've responded to it, it will be archived forever. It is so rare that anybody agrees with me, I wanted to make a permanent record. :-) From nanothermite911fbibustards at gmail.com Tue Aug 24 17:48:48 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 14:48:48 -0700 (PDT) Subject: CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM References: <156f547e-c730-4e16-9790-0c0636ddf12d@f42g2000yqn.googlegroups.com> <5383f461-3549-4674-b490-e2183fcf4be9@v8g2000yqe.googlegroups.com> <896d73ff-13c0-4235-87df-51572c291305@j8g2000yqd.googlegroups.com> Message-ID: <5c56cb90-b5ef-4584-83e1-e932db968f56@x21g2000yqa.googlegroups.com> CRIMINAL MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list From john at castleamber.com Tue Aug 24 17:50:23 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 16:50:23 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <87bp8sou6m.fsf@lola.goethe.zz> Message-ID: <87pqx77k9s.fsf@castleamber.com> David Kastrup writes: > John Bokma writes: > >> On the other hand: some people I knew during my studies had no problem >> at all with introducing countless memory leaks in small programs (and >> turning off compiler warnings, because it gave so much noise...) > > [...] > >> As for electrical engineering: done that (BSc) and one of my class >> mates managed to connect a transformer the wrong way >> around.... twice. Yet he had the highest mark in our class. > > Anybody worth his salt in his profession has a trail of broken things in > his history. Sure. The long version is: he blew up his work when he connected the transformer wrong. He borrowed someone else's board and blew that one up as well. > The faster it thinned out, the better he learned. He he he, his internships went along similar lines. Maybe he loved to blow up things. > The only reliable way never to break a thing is not to touch it in the > first place. But that will not help you if it decides to break on its > own. I don't think transfomers connect themselfs in the wrong way ;-). I agree with that accidents do happen, but some people just manage to make accidents happen way above average. And in that case they might start to think if it's a good idea them touching things. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From hughaguilar96 at yahoo.com Tue Aug 24 18:05:20 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 15:05:20 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> Message-ID: <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> On Aug 22, 11:12?am, John Bokma wrote: > And my > experience is that a formal study in CS can't compare to home study > unless you're really good and have the time and drive to read formal > books written on CS. And my experience is that most self-educaters don't > have that time. I've read a lot of graduate-level CS books. I think most self-educated programmers have read more of these books than have 4-year degree students who were not required to in order to get their Bachelors degree and who were too busy during college to read anything that wasn't required. > On the other hand: some people I knew during my studies had no problem > at all with introducing countless memory leaks in small programs (and > turning off compiler warnings, because it gave so much noise...) I do this all the time. My slide-rule program, for example, has beau- coup memory leaks. When I have time to mess with the program I clean up these memory leaks, but it is not a big deal. The program just runs, generates the gcode and PostScript, and then it is done. I don't really worry about memory leaks except with programs that are run continuously and have a user-interface, because they can eventually run out of memory. The real problem here is that C, Forth and C++ lack automatic garbage collection. If I have a program in which I have to worry about memory leaks (as described above), I would be better off to ignore C, Forth and C++ and just use a language that supports garbage collection. Why should I waste my time carefully freeing up heap space? I will very likely not find everything but yet have a few memory leaks anyway. From rowlett at pcnetinc.com Tue Aug 24 18:17:13 2010 From: rowlett at pcnetinc.com (Richard Owlett) Date: Tue, 24 Aug 2010 17:17:13 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> Message-ID: Hugh Aguilar wrote: > [SNIP ;] > > The real problem here is that C, Forth and C++ lack automatic garbage > collection. If I have a program in which I have to worry about memory > leaks (as described above), I would be better off to ignore C, Forth > and C++ and just use a language that supports garbage collection. Why > should I waste my time carefully freeing up heap space? I will very > likely not find everything but yet have a few memory leaks anyway. IOW Hugh has surpassed GIGO to achieve AGG - *A*utomatic*G*arbage*G*eneration ;) From hughaguilar96 at yahoo.com Tue Aug 24 18:25:25 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 15:25:25 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <87bp8sou6m.fsf@lola.goethe.zz> Message-ID: <5a3360f9-3eaf-4694-963a-8f67b813eb17@t2g2000yqe.googlegroups.com> On Aug 24, 9:24?am, David Kastrup wrote: > Anybody worth his salt in his profession has a trail of broken things in > his history. When I was employed as a Forth programmer, I worked for two brothers. The younger one told me a funny story about when he was 13 or 14 years old. He bought a radio at a garage sale. The radio worked perfectly, except that it had no case. He was mighty proud of his radio and was admiring it, but he noticed that the tubes were dusty. That wouldn't do! Such a wonderful radio ought to look as good as it sounds! So he removed the tubes and cleaned them all off with a soft cloth. At this time it occurred to him that maybe he should have kept track of which sockets the tubes had come out of. He put the tubes back in so that they looked correct, but he couldn't be sure. Fortunately, his older brother who was in high school knew *everything* about electronics, or at least, that is what he claimed. So the boy gets his big brother and asks him. The brother says: "There is one way to know for sure if the tubes are in correctly or not --- plug the radio in." He plugs in the radio; it makes a crackling noise and begins to smoke. The boy desperately yanks the cord, but it is too late; his wonderful radio is toast. The older brother says: "Now you know!" From cs_bittin at msn.com Tue Aug 24 18:31:51 2010 From: cs_bittin at msn.com (Martin Jernberg) Date: Wed, 25 Aug 2010 00:31:51 +0200 Subject: [Python-Dev] Released: Python 2.6.6 In-Reply-To: References: <20100824153146.69874f04@heresy>, Message-ID: yay new python release :) > From: raymond.hettinger at gmail.com > Date: Tue, 24 Aug 2010 13:40:11 -0700 > To: barry at python.org > CC: python-announce-list at python.org; python-list at python.org; python-dev at python.org > Subject: Re: [Python-Dev] Released: Python 2.6.6 > > > On Aug 24, 2010, at 12:31 PM, Barry Warsaw wrote: > > > Hello fellow Pythoneers and Pythonistas, > > > > I'm very happy to announce the release of Python 2.6.6. > > Thanks Barry :-) > > > Raymond > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: http://mail.python.org/mailman/options/python-dev/cs_bittin%40msn.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Tue Aug 24 19:04:55 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 25 Aug 2010 11:04:55 +1200 Subject: Reading the access attributes of directories in Windows References: Message-ID: In message , Nobody wrote: > Having this as a separate permission allows normal users to add entries to > log files but not to erase existing entries. Unix/Linux systems can do this already. From nanothermite911fbibustards at gmail.com Tue Aug 24 19:37:32 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Tue, 24 Aug 2010 16:37:32 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach Message-ID: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list From john at castleamber.com Tue Aug 24 19:53:26 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 18:53:26 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> Message-ID: <871v9n36vd.fsf@castleamber.com> Hugh Aguilar writes: > On Aug 22, 11:12?am, John Bokma wrote: > >> And my >> experience is that a formal study in CS can't compare to home study >> unless you're really good and have the time and drive to read formal >> books written on CS. And my experience is that most self-educaters don't >> have that time. > > I've read a lot of graduate-level CS books. I think most self-educated > programmers have read more of these books than have 4-year degree > students who were not required to in order to get their Bachelors > degree and who were too busy during college to read anything that > wasn't required. I doubt it. But this all comes back to what I earlier wrote: those with a CS degree think they are better than people without, and people without think they can achieve the same or better by just buying a few books and reading them. On top of that, most of the people I knew in my final year were very fanatic regarding CS: it was a hobby to them. During coffeebreaks we talked about approximation algorithms for TSPs for example. Not always, but it happened. I read plenty of books during my studies that were not on the list, as did other students I knew. If I recall correctly, you don't have a CS degree. I do, and I can tell you that your /guess/ (since that is all it is) is wrong. For most exams I've done one had not only to have read the entire book (often in a very short time), but also the hand-outs. And for quite some courses additional material was given during the course itself, so not attending all classes could result in a lower score. Reading additional books and papers helped. Sometimes reading a book by a different author could be a real eye opener (and the students I had contact with did exactly this). On top of that, often in class excercises were done, and with some courses I had to hand in home work (yikes). Also, most books are easy to read compared to CS papers. In my final two years I did several courses which solely consisted of reading a CS paper and giving a presentation on the subject in front of your classmates (and sometimes other interested people). Reading and understanding such a paper is one (and quite an effort). Teaching it in front of a (small) class within a few days is not easy, to say the least. We also had to attend several talks by guest speakers. I went to more than the required number, including a guest talk by Linus. When there was a break-through in proving Fermat's last theorem there was a talk, which I attended, like several other class mates. I am sure there are students who are there just to get a degree and to make money. But my class mates didn't fall into that category, or I have missed something. So yes, I am convinced that there are plenty of self-educated people who can code circles around me or plenty of other people with a CS degree. But IMO those people are very hard to find. Most people overestimate their skills, with or without a degree; I am sure I do. And it wouldn't surprise me if self-educated people do this more so. >> On the other hand: some people I knew during my studies had no problem >> at all with introducing countless memory leaks in small programs (and >> turning off compiler warnings, because it gave so much noise...) > > I do this all the time. My slide-rule program, for example, has beau- > coup memory leaks. When I have time to mess with the program I clean > up these memory leaks, but it is not a big deal. The program just > runs, generates the gcode and PostScript, and then it is done. I don't > really worry about memory leaks except with programs that are run > continuously and have a user-interface, because they can eventually > run out of memory. Oh boy, I think you just made my point for me... > The real problem here is that C, Forth and C++ lack automatic garbage > collection. If I have a program in which I have to worry about memory > leaks (as described above), I would be better off to ignore C, Forth > and C++ and just use a language that supports garbage collection. Several languages that support garbage collection still are able to leak memory when circular datastructures are used (for example). Also, allocating memory and never giving it back (by keeping a reference to it) can also be memory leaking. And the wrong form of optimization can result in a program using more memory than necessary. On top of that, you have to understand when the gc releases memory, and things like memory fragmentation. In short: you still have to use your head (on some occasions even more). > Why should I waste my time carefully freeing up heap space? I will > very likely not find everything but yet have a few memory leaks > anyway. Why should you waste time with carefully checking for other issues? In my experience, once you become sloppy with one aspect it's very easy to become sloppy with others as well. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From hughaguilar96 at yahoo.com Tue Aug 24 20:00:14 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 17:00:14 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> Message-ID: <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> On Aug 24, 4:17?pm, Richard Owlett wrote: > Hugh Aguilar wrote: > > [SNIP ;] > > > The real problem here is that C, Forth and C++ lack automatic garbage > > collection. If I have a program in which I have to worry about memory > > leaks (as described above), I would be better off to ignore C, Forth > > and C++ and just use a language that supports garbage collection. Why > > should I waste my time carefully freeing up heap space? I will very > > likely not find everything but yet have a few memory leaks anyway. > > IOW Hugh has surpassed GIGO to achieve AGG - > *A*utomatic*G*arbage*G*eneration ;) The C programmers reading this are likely wondering why I'm being attacked. The reason is that Elizabeth Rather has made it clear to everybody that this is what she wants: http://groups.google.com/group/comp.lang.forth/browse_thread/thread/c37b473ec4da66f1 Every Forth programmer who aspires to get a job at Forth Inc. is obliged to attack me. Attacking my software that I posted on the FIG site is preferred, but personal attacks work too. It is a loyalty test. From rowlett at pcnetinc.com Tue Aug 24 20:05:38 2010 From: rowlett at pcnetinc.com (Richard Owlett) Date: Tue, 24 Aug 2010 19:05:38 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> Message-ID: Hugh Aguilar wrote: > On Aug 24, 4:17 pm, Richard Owlett wrote: >> Hugh Aguilar wrote: >>> [SNIP ;] >> >>> The real problem here is that C, Forth and C++ lack automatic garbage >>> collection. If I have a program in which I have to worry about memory >>> leaks (as described above), I would be better off to ignore C, Forth >>> and C++ and just use a language that supports garbage collection. Why >>> should I waste my time carefully freeing up heap space? I will very >>> likely not find everything but yet have a few memory leaks anyway. >> >> IOW Hugh has surpassed GIGO to achieve AGG - >> *A*utomatic*G*arbage*G*eneration ;) > > The C programmers reading this are likely wondering why I'm being > attacked. The reason is that Elizabeth Rather has made it clear to > everybody that this is what she wants: > http://groups.google.com/group/comp.lang.forth/browse_thread/thread/c37b473ec4da66f1 > > Every Forth programmer who aspires to get a job at Forth Inc. is > obliged to attack me. Attacking my software that I posted on the FIG > site is preferred, but personal attacks work too. It is a loyalty > test. *SNICKER SNICKER LOL* I am not now, nor have been a professional programmer. I still recognize you. P.S. - ever read "The Emperor's New Clothes" From no.email at nospam.invalid Tue Aug 24 20:16:20 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 24 Aug 2010 17:16:20 -0700 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> Message-ID: <7xhbijo8bv.fsf@ruckus.brouhaha.com> Hugh Aguilar writes: > I've read a lot of graduate-level CS books. Reading CS books doesn't make you a computer scientist any more than listening to violin records makes you a violinist. Write out answers to all the exercises in those books, and get your answers to the more difficult ones checked by a professor, and you'll be getting somewhere. That's the point someone else was making about self-study: without someone checking your answers at first, it's easy to not learn to recogize your own mistakes. Anyway, as someone else once said, studying a subject like CS isn't done by reading. It's done by writing out answers to problem after problem. Unless you've been doing that, you haven't been studying. From john at castleamber.com Tue Aug 24 20:39:48 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 19:39:48 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> Message-ID: <87tymj1q5n.fsf@castleamber.com> Paul Rubin writes: > Hugh Aguilar writes: >> I've read a lot of graduate-level CS books. > > Reading CS books doesn't make you a computer scientist any more than > listening to violin records makes you a violinist. Write out answers to > all the exercises in those books, and get your answers to the more > difficult ones checked by a professor, and you'll be getting somewhere. > That's the point someone else was making about self-study: without > someone checking your answers at first, it's easy to not learn to > recogize your own mistakes. > > Anyway, as someone else once said, studying a subject like CS isn't done > by reading. It's done by writing out answers to problem after problem. > Unless you've been doing that, you haven't been studying. Yup. I would like to add the following three: 1) being able to teach to peers what you've read. As explained in a post I made: during several courses I took you got a paper from your teacher and had to teach in front of the class the next week. Those papers are quite hard to grasp on the first reading even if you know quite a bit of the topic. Understanding it enough to teach in front of a class and being able to handle the question round, in which the teacher participates, is quite a killer. 2) being able to program on paper / understand programs on paper. On several exams I had to write small programs on paper. The solutions had to compile (i.e. missing a ; for languages that required so was counted against you, or using optional ;). One exam was about OOP and several OO languages were taught, and hence on paper one had to provide solutions in C++, Objective-C, Object Pascal, Smalltalk, Eiffel, etc. No compiler(s) handy. And of course questions like: what's wrong with this piece of code and how should it be written. 3) being able to write papers and a thesis (or two) No explanation needed, quite some people have no problem reading the required books, passing the exams, but need quite some time to do this (and some give up on it). -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From hughaguilar96 at yahoo.com Tue Aug 24 21:05:18 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 18:05:18 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> Message-ID: <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> On Aug 24, 5:16?pm, Paul Rubin wrote: > Anyway, as someone else once said, studying a subject like CS isn't done > by reading. ?It's done by writing out answers to problem after problem. > Unless you've been doing that, you haven't been studying. What about using what I learned to write programs that work? Does that count for anything? If I don't have a professor to pat me on the back, will my programs stop working? That sounds more like magic than technology. From hughaguilar96 at yahoo.com Tue Aug 24 21:47:14 2010 From: hughaguilar96 at yahoo.com (Hugh Aguilar) Date: Tue, 24 Aug 2010 18:47:14 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> <4c70bc48$0$28653$c3e8da3@news.astraweb.com> Message-ID: On Aug 21, 10:57?pm, Steven D'Aprano wrote: > Anyway, I'm looking forward to hear why overuse of the return stack is a > big reason why people use GCC rather than Forth. (Why GCC? What about > other C compilers?) Me, in my ignorance, I thought it was because C was > invented and popularised by the same universities which went on to teach > it to millions of programmers, and is firmly in the poplar and familiar > Algol family of languages, while Forth barely made any impression on > those universities, and looks like line-noise and reads like Yoda. (And > I'm saying that as somebody who *likes* Forth and wishes he had more use > for it.) In my experience, the average C programmer wouldn't recognise a > return stack if it poked him in the eye. "The Empire Strikes Back" was a popular movie. I read an article ("The puppet like, I do not") criticizing the movie though. At one point, Luke asked why something was true that Yoda had told him, and Yoda replied: "There is no why!" The general idea is that the sudent (Luke) was supposed to blindly accept what the professor (Yoda) tells him. If he asks "why?," he gets yelled at. This is also the attitude that I find among college graduates. They just believe what their professors told them in college, and there is no why. This is essentially the argument being made above --- that C is taught in college and Forth is not, therefore C is good and Forth is bad --- THERE IS NO WHY! People who promote "idiomatic" programming are essentially trying to be Yoda. They want to criticize people even when those people's programs work. They are just faking up their own expertise --- many of them have never actually written a program that works themselves. The reason why I like programming is because there is an inherent anti- bullshit mechanism in programming. Your program either works or it doesn't. If your program doesn't work, then it doesn't matter if it is idiomatic, if you have a college degree, etc., etc.. That is the way I see it, anyway. This perspective doesn't hold for much on comp.lang.forth where we have people endlessly spouting blather *about* programming, without actually doing any programming themselves. This is why I don't take c.l.f. very seriously; people attack me all of the time and I don't really care --- I know that my programs work, which is what matters in the real world. (Pardon my use of the word "bullshit" above; there is no better term available.) From ahleniusm at gmail.com Tue Aug 24 22:07:52 2010 From: ahleniusm at gmail.com (m_ahlenius) Date: Tue, 24 Aug 2010 19:07:52 -0700 (PDT) Subject: problem with strptime and time zone References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> <45faa241-620e-42c7-b524-949936f63610@f6g2000yqa.googlegroups.com> Message-ID: On Aug 24, 4:16?pm, Alex Willmer wrote: > On Aug 24, 9:45?pm, m_ahlenius wrote: > > > > > whereas this fails: > > myStrA = 'Sun Aug 22 19:03:06 PDT' > > gTimeA = strptime( myStrA, '%a %b %d %H:%M:%S %Z') > > print "gTimeA = ",gTimeA > > > ValueError: time data 'Sun Aug 22 19:03:06 PDT' does not match format > > '%a %b %d %H:%M:%S %Z' > > Support for the %Z directive is based on the values contained in > tzname and whether daylight is true. Because of this, it is platform- > specific except for recognizing UTC and GMT which are always known > (and are considered to be non-daylight savings timezones). > > http://docs.python.org/library/time.html > > Dateutil has it's own timezone database, so should work reliablyhttp://labix.org/python-dateutil Thanks much, I missed the directive settings. From john at castleamber.com Tue Aug 24 22:17:10 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 21:17:10 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> Message-ID: <87pqx71lnd.fsf@castleamber.com> Hugh Aguilar writes: > On Aug 24, 5:16?pm, Paul Rubin wrote: >> Anyway, as someone else once said, studying a subject like CS isn't done >> by reading. ?It's done by writing out answers to problem after problem. >> Unless you've been doing that, you haven't been studying. > > What about using what I learned to write programs that work? Does that > count for anything? Of course it does; but who's going to verify your program? > If I don't have a professor to pat me on the back, will my programs > stop working? That sounds more like magic than technology. I am sure you know what Paul means. As for patting on the back: you must make a hell of an effort to get that. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From john at castleamber.com Tue Aug 24 22:35:39 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 21:35:39 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> <4c70bc48$0$28653$c3e8da3@news.astraweb.com> Message-ID: <87lj7v1ksk.fsf@castleamber.com> Hugh Aguilar writes: > This is also the attitude that I find among college graduates. They > just believe what their professors told them in college, and there is > no why. Which college is that? It doesn't agree with my experiences. In CS quite a lot has to be proven with a formal proof, exactly the opposite from what you claim. And after some time students want to see the proof and certainly don't accept "there is no why!" unless it's a trivial thing. Maybe it's because your anecdote is an interpretation from a distance, not based on the actual experience? > This is essentially the argument being made above --- that C > is taught in college and Forth is not, therefore C is good and Forth > is bad --- THERE IS NO WHY! At an university which languages you see depend a lot on what your teachers use themselves. A language is just a verhicle to get you from a to b. What a good study should teach you is how to drive the verhicle without accidents and not that a red one is the best. From top of my head I've seen 20+ languages during my study at the University of Utrecht. Forth wasn't one of them, but I already knew about Forth before I went to the UU. On top of that I had written an extremely minimalistic Forth in Z80 assembly years before I went to the UU (based on the work of someone else). > People who promote "idiomatic" programming are essentially trying to > be Yoda. They want to criticize people even when those people's > programs work. "Works" doesn't mean that a program is good or what. There is a lot to say about a program that works, even one that works flawless. I do it all the time about my own programs. It's good to be critical about your own work. And if you're a teacher, it's good to provide positive feedback. > They are just faking up their own expertise --- Like you, you mean? You consider yourself quite the expert on how people educate and what they learn when educated in a formal environment. Without (if I recall correctly) only second hand information and guessing. > many of them have never actually written a program that works > themselves. Quite some part of CS can be done without writing a single line of code. > The reason why I like programming is because there is an inherent anti- > bullshit mechanism in programming. Your program either works or it > doesn't. Now can you provide a formal proof that it works, or do you just consider running the program a few times sufficient proof that "it works"? > If your program doesn't work, then it doesn't matter if it is > idiomatic, if you have a college degree, etc., etc.. That is the way I > see it, anyway. Well, you see it wrong. A program that doesn't work and is idiomatic is easier to make work and to verify by others that it works. A program that's the result of trial-and-error (that's what quite some people end up doing who are self-taught) is a pain in the ass (pardon my French) to maintain or to extend. > This perspective doesn't hold for much on > comp.lang.forth where we have people endlessly spouting blather > *about* programming, and you are different how? Also note that your post is crossposted to several other groups. > without actually doing any programming themselves. This is why I don't > take c.l.f. very seriously; people attack me all of the time and I > don't really care heh, hence all the replies you write, and mentioning it in this post. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From john at castleamber.com Tue Aug 24 22:38:57 2010 From: john at castleamber.com (John Bokma) Date: Tue, 24 Aug 2010 21:38:57 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <60de5b2d-9c27-425c-92d6-881e818d2b5e@s9g2000yqd.googlegroups.com> <4c70bc48$0$28653$c3e8da3@news.astraweb.com> <87lj7v1ksk.fsf@castleamber.com> Message-ID: <87hbij1kn2.fsf@castleamber.com> John Bokma writes: > At an university which languages you see depend a lot on what your > teachers use themselves. A language is just a verhicle to get you from a > to b. Addendum: or to illustrate a concept (e.g. functional programming, oop) [..] > Like you, you mean? You consider yourself quite the expert on how people > educate and what they learn when educated in a formal > environment. Without (if I recall correctly) only second hand ^^^^^^^ Should've written "With", of course. > information and guessing. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From ghoetker at illinois.edu Tue Aug 24 22:49:42 2010 From: ghoetker at illinois.edu (ghoetker) Date: Tue, 24 Aug 2010 19:49:42 -0700 (PDT) Subject: Passing data between objects and calling all objects of a class in turn Message-ID: I'm a fairly new Python coder, learning along with my son (actually, hopefully a bit ahead of him...). We're stuck on something. As part of solving a backwards induction problem (purely as a learning experience, we are geeks), we are going to create N objects, each of the class "interview". We will first create the N_th interview, which will calculate, based on data we pass to it, its expected payoff value. We will then create interview N-1, which needs to know the expected payoff of interview N in order to determine a decision and then calculate its own expected payoff. We then create interview N-2, which needs to know the expected payoff of interview N-1, etc., until we reach interview 1. 1. How can we best (that is, most Pythonically) let interview N-1 know the expected value of interview N and so on. One way would be to define a variable "payoff_of_continuing" which gets set to the expected value of interview N and is passed to interview N-1 when is created. Interview N-1 then resets "payoff_of_continuing", which is passed to interview N-2 when it is created, etc. Is there a more Pythonic approach? 2. When we want to output the results of the analysis, how do we most Pythonically get each interview object in turn to report its identity, the result of its decision and its expected payoff (e.g., For interview 3, stop if you interview a good candidate. This interview's expected value is 2.5). I know how to do the reporting part (print....), it's the "getting each interview object in turn to..." part that I'm unsure about. We could have each interview report as it is created, but I'm wondering if the splitting it into "Create all the objects" and "Report the results from all the objects" is sensible. For one thing, it would allow compiling the results into a table, etc. I really appreciate any input. I'm a competent procedural programmer (albeit not primarily in Python), but a dabbler in object oriented programming (we've already done this problem procedurally, but want to try it again as OOP). Thank you!! From python at mrabarnett.plus.com Tue Aug 24 23:18:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 25 Aug 2010 04:18:52 +0100 Subject: Passing data between objects and calling all objects of a class in turn In-Reply-To: References: Message-ID: <4C748B9C.8040000@mrabarnett.plus.com> On 25/08/2010 03:49, ghoetker wrote: > I'm a fairly new Python coder, learning along with my son (actually, > hopefully a bit ahead of him...). We're stuck on something. > > As part of solving a backwards induction problem (purely as a learning > experience, we are geeks), we are going to create N objects, each of > the class "interview". We will first create the N_th interview, which > will calculate, based on data we pass to it, its expected payoff > value. We will then create interview N-1, which needs to know the > expected payoff of interview N in order to determine a decision and > then calculate its own expected payoff. We then create interview N-2, > which needs to know the expected payoff of interview N-1, etc., until > we reach interview 1. > > 1. How can we best (that is, most Pythonically) let interview N-1 > know the expected value of interview N and so on. One way would be to > define a variable "payoff_of_continuing" which gets set to the > expected value of interview N and is passed to interview N-1 when is > created. Interview N-1 then resets "payoff_of_continuing", which is > passed to interview N-2 when it is created, etc. Is there a more > Pythonic approach? > I hope you don't mean that "payoff_of_continuing" is a global variable which is set by the instance when it's created. The Pythonic way would be to create the instance and then ask it what it's payoff is so that you then know what to pass in when you create the next instance. > 2. When we want to output the results of the analysis, how do we most > Pythonically get each interview object in turn to report its identity, > the result of its decision and its expected payoff (e.g., For > interview 3, stop if you interview a good candidate. This interview's > expected value is 2.5). I know how to do the reporting part > (print....), it's the "getting each interview object in turn to..." > part that I'm unsure about. We could have each interview report as it > is created, but I'm wondering if the splitting it into "Create all the > objects" and "Report the results from all the objects" is sensible. > For one thing, it would allow compiling the results into a table, etc. > Put the objects into a list when you create them and then iterate through them, asking each to print its report. > I really appreciate any input. I'm a competent procedural programmer > (albeit not primarily in Python), but a dabbler in object oriented > programming (we've already done this problem procedurally, but want to > try it again as OOP). Thank you!! From magawake at gmail.com Tue Aug 24 23:19:50 2010 From: magawake at gmail.com (Mag Gam) Date: Tue, 24 Aug 2010 23:19:50 -0400 Subject: pypy Message-ID: Just curious if anyone had the chance to build pypy on a 64bit environment and to see if it really makes a huge difference in performance. Would like to hear some thoughts (or alternatives). From madhusoodan.shanbhag at gmail.com Tue Aug 24 23:39:31 2010 From: madhusoodan.shanbhag at gmail.com (Madhusoodan) Date: Tue, 24 Aug 2010 20:39:31 -0700 (PDT) Subject: DDE Module for Python 3.1.2 References: Message-ID: Respected Stefan and Tim, Thanks very much for help. I found DDE tutorial for 2.6 but was wondering why I can't do it in 3.X. Thanks Stefan for pywin32. I was not knowing this tool. Thanks again to both of you. Regards madhusoodan On Aug 23, 5:12?pm, Tim Golden wrote: > On 23/08/2010 13:02, Stefan Behnel wrote: > > > Madhusoodan, 23.08.2010 13:50: > >> I am learning python 3.1.2 on windows XP. I wanted to do experiments > >> on importing real time data from QuoteCenter with DDE. > > > What's DDE here? > > It'll be Microsoft's Dynamic Data Exchange : > > ? ?http://msdn.microsoft.com/en-us/library/ms648711%28VS.85%29.aspx > > Didn't know anyone was still using it explicitly. > > > > >> After searching > >> relevant module, I found dde module only for Python 2.6, but not for > >> 3.1.2. > > > Could you provide a link to the module, so that we know what module you > > are actually talking about? > > I expect that'll be the dde module in the pywin32 packages: > > http://pywin32.cvs.sourceforge.net/viewvc/pywin32/pywin32/win32/Demos... > > I haven't run any tests against it, but it imports ok on > my 3.1.2 instance (albeit after importing win32ui) > > TJG From ritchy_gato at hotmail.com Wed Aug 25 01:21:34 2010 From: ritchy_gato at hotmail.com (Ritchy lelis) Date: Tue, 24 Aug 2010 22:21:34 -0700 (PDT) Subject: How to implement a pipeline...??? Please help References: <5242b005-31b6-4a9c-afd9-6fbb82e28db7@l14g2000yql.googlegroups.com> <08ce00ca-f58e-4ff4-a95e-54f7a4d5071f@w30g2000yqw.googlegroups.com> Message-ID: On 11 Ago, 01:01, Ritchy lelis wrote: > On 7 Ago, 07:30, Dennis Lee Bieber wrote: > > > > > > > On Fri, 6 Aug 2010 16:47:58 -0700 (PDT), Ritchy lelis > > declaimed the following in > > gmane.comp.python.general: > > > > Guys i'm asking if it's possible for a generic function for a > > >pipeline, all the suggestions ideas are welcome. > > > ? ? ? ? I've not done metaclasses, so don't know if a metaclass would be of > > use... Since it appears one would have to have something that generates > > functions on the fly based upon inputs... > > > ? ? ? ? I look at details on what you are trying to create and see a > > series-parallel circuit architecture with clocked stages and delay lines > > for the summing of the outputs. That is, when the clock ticks, every > > stage in the unit does its processing and provides and output... On the > > next tick, those outputs become inputs to the subsequent stage and the > > process repeats > > > > Also if you have a specific solution for my problem I will be grateful > > > for it here. > > > ? ? ? ? I'm still blinking at the thought of doing analog to digital > > conversion in Python! I sure wouldn't hold out much hope of real-time > > signal processing. There is a reason ADC and DAC are done in hardware, > > even if the intermediate processing is with general purpose processors. > > > ? ? ? ? I'm also not sure I understand the > > > np.linspace(1,1, Inc)... > > > ? ? ? ? Looking up documentation implies you are trying to create a vector > > of "inc" length, evenly populated by values between 1 and 1... which > > means a vector of all 1s... Might it not be faster to just > > > ? ? ? ? v = [1] * inc > > > and pass v to some numpy method for conversion from Python list to numpy > > vector? > > > (the -1 to 1 at least makes sense) > > > ? ? ? ? Me? I'd probably create a class in which the __init__() takes a > > value specifying the number of stages. It would than create suitable > > lists to track values, some sort of counter (c), a Semaphore (s) > > [initialized at 0 -- ie, already acquired/block], ?a thread for EACH > > stage, and an Event (e) object > > > ? ? ? ? Each stage thread, initialized with its position in thepipeline. > > The threads perform an e.wait() call. They also, after the wait is > > released, perform an e.clear() call. As their processing, they each grab > > from thepipeline"input" list the current value for their position. > > After processing they update their position in the "output" list(s), > > they decrement the counter c (maybe put a lock around access to c). The > > thread that decrements c to 0 is responsible for "releasing" the > > semaphore. > > > ? ? ? ? The main code of the class instance is responsible for a loop that > > does: set up the "input" list based on current value of stage outputs, > > initialize c to the count of stages (minus 1?), e.set() to signal all > > stage threads to process the current conditions, s.acquire() to block > > until the last processed thread (by c hitting 0) does s.release(). It > > then collects the output lists, does whatever shifting is needed to > > prepare for the next cycle... > > > ? ? ? ? Actually, that "loop" may not be a loop so much as a method off the > > class like > > > ? ? ? ? digitalOutput = adcInstance.step(analogInput) > > > which is, itself, in a loop. > > > That is, something like... > > > myADC = ADC(stages=10) > > while True: > > ? ? ? ? voltage = getNextAnalogInput() > > ? ? ? ? digital = myADC.step(voltage) > > ? ? ? ? outputDigitalValue() > > > ? ? ? ? Obviously I've not taken the time to actually lay out all the > > instance lists needed for inputs and outputs, nor the code of threads > > (while one can create the first "stages-1" threads with a loop, the > > final stage needs a discrete creation) > > > ? ? ? ? When one finds that the threading solution is really slow (though > > understandable in terms of the hardware circuit -- one thread per stage > > makes the stages easy to code), THEN one might try to figure out how to > > implement an iterative version... I suspect using numpy would be the > > third optimization -- removing iteration by using parallel vector > > operations. > > -- > > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ > > Hi > > First of all i would like to thank you for your time and help. > > I appreciate your suggestions and they seems very good to me... The > only problem it's that i'm newbie at python programming, but still > interested to learn more and more... > > I already got a solution through harsh but it worked. at least I got > the wave form i wanted. > > Next i'm going to let you'll my solution here. It's rudimentary but it > work's. > > Seems very perceptible that's why i will not explain it right now but > if in case of doubt I will: > > PipelineFunction: > > from flash1b5 import flash1b5 > from flash1b5 import * > from flash2b import flash2b > from flash2b import * > import matplotlib.pyplot as plt > import numpy as np > from pylab import * > > if __name__ == "__main__": > > ? ? Inc = raw_input("Valor do Incrimento = ") > > ? ? Vref = np.linspace(1,1, Inc) > ? ? Vi = np.linspace(-1,1, Inc) > # ? ?x = np.linspace(-1,1, Inc) > # ? ?Vi = 1*sin(2*pi*(x-1/4)) > ? ? Cs = np.linspace(3e-12, 3e-12, Inc) > ? ? Cf = np.linspace(3e-12, 3e-12, Inc) > > ? ? f1 = flash1b5(Vi, Vref, Cs, Cf) > > ? ? Vin1 = f1[0] > ? ? Vt1 = f1[1] > ? ? Vd1 = f1[2]*256 > > ? ? f2 = flash1b5(Vt1, Vref, Cs, Cf) > > ? ? Vin2 = f2[0] > ? ? Vt2 = f2[1] > ? ? Vd2 = f2[2]*128 > > ? ? f3 = flash1b5(Vt2, Vref, Cs, Cf) > > ? ? Vin3 = f3[0] > ? ? Vt3 = f3[1] > ? ? Vd3 = f3[2]*64 > > ? ? f4 = flash1b5(Vt3, Vref, Cs, Cf) > > ? ? Vin4 = f4[0] > ? ? Vt4 = f4[1] > ? ? Vd4 = f4[2]*32 > > ? ? f5 = flash1b5(Vt4, Vref, Cs, Cf) > > ? ? Vin5 = f5[0] > ? ? Vt5 = f5[1] > ? ? Vd5 = f5[2]*16 > > ? ? f6 = flash1b5(Vt5, Vref, Cs, Cf) > > ? ? Vin6 = f6[0] > ? ? Vt6 = f6[1] > ? ? Vd6 = f6[2]*8 > > ? ? f7 = flash1b5(Vt6, Vref, Cs, Cf) > > ? ? Vin7 = f7[0] > ? ? Vt7 = f7[1] > ? ? Vd7 = f7[2]*4 > > ? ? f8 = flash1b5(Vt7, Vref, Cs, Cf) > > ? ? Vin8 = f8[0] > ? ? Vt8 = f8[1] > ? ? Vd8 = f8[2]*2 > > ? ? f2b = flash2b(Vt8, Vref) > > ? ? Vin2b = f2b[0] > ? ? Vd2b = f2b[1]*1 > > ? ? Vd = Vd1+Vd2+Vd3+Vd4+Vd5+Vd6+Vd7+Vd8+Vd2b > > ## ? ?print 'Vin = ',Vin > ## ? ?print 'Vt = ',Vt > ## ? ?print 'Vd = ',Vd > ## > # ? ?fig1 = figure(1,figsize=(8,5)) > # ? ?ax1 = fig1.add_subplot(211, autoscale_on=False, xlim=(-1,1), > ylim=(-1,1)) > # ? ?ax1.plot(Vin1, Vt4, lw=2, color='blue') > # ? ?grid (True); title('FLASH 1.5 BIT',fontsize = > 16);ylabel('Vout_Residuo') > ## > ## ? ?ax1.annotate('00', xy=(-0.5, 0.5)) > ## ? ?ax1.annotate('01', xy=(0.0, 0.5)) > ## ? ?ax1.annotate('11', xy=(0.5, 0.5)) > # > ## ? ?hold(True) > # > ? ? fig2 = figure(1,figsize=(8,5)) > ? ? ax2 = fig2.add_subplot(111, autoscale_on=True) > ? ? ax2.plot(Vin1, Vd, lw=2, color='red') > ? ? grid (True); xlabel('Vin');ylabel('Vout_Digital') > # > ## ? ?ax2.annotate('00 --> 0', xy=(-0.5, 0.1)) > ## ? ?ax2.annotate('01 --> 1', xy=(0.0, 1.1)) > ## ? ?ax2.annotate('11 --> 2', xy=(0.5, 2.1)) > ## > # > ? ? plt.show() > -------------------------------------------------------------------------- > > About the answer i got for my last post: > > ?1 - > ? ? v = [1] * inc > > > > > and pass v to some numpy method for conversion from Python list to numpy > > vector? > > Yes i agree with you, but at the time i made it i found that function > (Linspace) that could do what i was loking for and i didn't worry > about search for a better solution. but even if wanted to, i'm new at > the programming language and i don't know how to convert a list to a > vector in numpy. but still open for tips/tricks that could help me. > > 2 - > > > ? ? ? ? Me? I'd probably create a class in which the __init__() takes a > > value specifying the number of stages. It would than create suitable > > lists to track values, some sort of counter (c), a Semaphore (s) > > [initialized at 0 -- ie, already acquired/block], ?a thread for EACH > > stage, and an Event (e) object > > ? ? ? ? Each stage thread, initialized with its position in thepipeline. > > The threads perform an e.wait() call. They also, after the wait is > > released, perform an e.clear() call. As their processing, they each grab > > from thepipeline"input" list the current value for their position. > > After processing they update their position in the "output" list(s), > > they decrement the counter c (maybe put a lock around access to c). The > > thread that decrements c to 0 is responsible for "releasing" the > > semaphore > > I did understand your algorithm/idea and that's what i want to > implement here (you couldn't be more right). but i don't now how to > implement the funcs e.wait() call and e.clear() call. they already > exists? i have to create them? > > if I may, i would like to ask more help on this one please. I hope not > to be bothering you :( hi friend Dennis Lee Bieber I have watching your code sujestion and now i can understand more of what you have there.. I have made some chances into it, for my better understanding of your point of view and adapted for it to fits my needs... i would like to show you them but i need to now if you still interested in the challenge it self and also in helping me with your extraordinary tips. Can i count on your help? I hope so gratefully. I'll be waiting for a message so we can proceed. Cheers. From sschwarzer at sschwarzer.net Wed Aug 25 02:07:47 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 25 Aug 2010 08:07:47 +0200 Subject: ftplib limitations? In-Reply-To: <4C73D738.9030501@sschwarzer.net> References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> Message-ID: <4C74B333.5020206@sschwarzer.net> Hi durumdara, On 2010-08-24 16:29, Stefan Schwarzer wrote: >> I experienced some problem. >> The server is Windows and FileZilla, the client is Win7 and Python2.6. >> When I got a file with size 1 303 318 662 byte, python is halt on >> "retrbinary" line everytime. > > So if I understand correctly, the script works well on > smaller files but not on the large one? I just did an experiment in the interpreter which corresponds to this script: import ftplib of = open("large_file", "wb") def callback(data): of.write(data) ftp = ftplib.FTP("localhost", userid, passwd) ftp.retrbinary("RETR large_file", callback) of.close() ftp.close() The file is 2 GB in size and is fully transferred, without blocking or an error message. The status message from the server is '226-File successfully transferred\n226 31.760 seconds (measured here), 64.48 Mbytes per second', so this looks ok, too. I think your problem is related to the FTP server or its configuration. Have you been able to reproduce the problem? Stefan From pdwjfndjbdgfyg at gmail.com Wed Aug 25 02:30:13 2010 From: pdwjfndjbdgfyg at gmail.com (097) Date: Tue, 24 Aug 2010 23:30:13 -0700 (PDT) Subject: GAMES Message-ID: <823cf601-f0da-4621-9099-963f42963693@q21g2000prm.googlegroups.com> games GAME 1 http://freeonlingamesplay.blogspot.com/2010/08/game-1.html GAME 2 http://freeonlingamesplay.blogspot.com/2010/08/game-2.html GAME 3 http://freeonlingamesplay.blogspot.com/2010/08/game-3.html GAME 4 http://freeonlingamesplay.blogspot.com/2010/08/game-4.html GAME 5 http://freeonlingamesplay.blogspot.com/2010/08/game-5.html GAME 6 http://freeonlingamesplay.blogspot.com/2010/08/game-6.html GAME 7 http://freeonlingamesplay.blogspot.com/2010/08/game-7.html GAME 8 http://freeonlingamesplay.blogspot.com/2010/08/game-8.html GAME 9 http://freeonlingamesplay.blogspot.com/2010/08/game-9.html GAME 10 http://freeonlingamesplay.blogspot.com/2010/08/game-10.html From durumdara at gmail.com Wed Aug 25 03:43:01 2010 From: durumdara at gmail.com (durumdara) Date: Wed, 25 Aug 2010 00:43:01 -0700 (PDT) Subject: ftplib limitations? References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> Message-ID: Hi! > > So if I understand correctly, the script works well on > smaller files but not on the large one? Yes. 500-800 MB is ok. > 1 GB is not ok. > > > It down all of the file (100%) but the next line never reached. > > _Which_ line is never reached? The `print` statement after > the `retrbinary` call? Yes, the print. > > > Some error I got, but this was in yesterday, I don't remember the text > > of the error. > > Can't you reproduce the error by executing the script once > more? Can you copy the file to another server and see if the > problem shows up there, too? I got everytime, but I don't have another server to test it. > > I can imagine the error message (a full traceback if > possible) would help to say a bit more about the cause of > the problem and maybe what to do about it. This was: Filename: "Repositories 20100824_101805 (Teljes).zip" Size: 1530296127 ..download: 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% Traceback (most recent call last): File "C:\D\LocalBackup\ftpdown.py", line 31, in ftp.retrbinary("retr " + s, CallBack) File "C:\Python26\lib\ftplib.py", line 401, in retrbinary return self.voidresp() File "C:\Python26\lib\ftplib.py", line 223, in voidresp resp = self.getresp() File "C:\Python26\lib\ftplib.py", line 209, in getresp resp = self.getmultiline() File "C:\Python26\lib\ftplib.py", line 195, in getmultiline line = self.getline() File "C:\Python26\lib\ftplib.py", line 182, in getline line = self.file.readline() File "C:\Python26\lib\socket.py", line 406, in readline data = self._sock.recv(self._rbufsize) socket.error: [Errno 10054] A l?tez? kapcsolatot a t?voli ?llom?s k?nyszer?tette n bez?rta So this message is meaning that the remote station forced close the existing connection. Now I'm trying with saving the file into temporary file, not hold in memory. Thanks: dd From ldo at geek-central.gen.new_zealand Wed Aug 25 03:48:26 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 25 Aug 2010 19:48:26 +1200 Subject: problem with strptime and time zone References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> <45faa241-620e-42c7-b524-949936f63610@f6g2000yqa.googlegroups.com> Message-ID: In message <45faa241-620e-42c7-b524-949936f63610 at f6g2000yqa.googlegroups.com>, Alex Willmer wrote: > Dateutil has it's own timezone database ... I hate code which doesn?t just use /usr/share/zoneinfo. How many places do you need to patch every time somebody changes their daylight-saving rules? From metolone+gmane at gmail.com Wed Aug 25 03:57:44 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 25 Aug 2010 00:57:44 -0700 Subject: Proper set-up for a co-existant python 2.6 & 3.1 installation References: <4f8bb076-8b6d-4ec1-b43c-6ed192a5e5ec@z10g2000yqb.googlegroups.com><4C72FC62.1050908@v.loewis.de><8c4e970a-dbe8-4495-bc74-3daf50221b6a@f42g2000yqn.googlegroups.com><4C730541.7040507@v.loewis.de> <3d85d8f5-8ce0-470f-b6ec-c86c452a335b@a36g2000yqc.googlegroups.com> Message-ID: > "vsoler" wrote in message > news:3d85d8f5-8ce0-470f-b6ec-c86c452a335b at a36g2000yqc.googlegroups.com... > On Aug 24, 1:33 am, "Martin v. Loewis" wrote: > > > When I am logged-in in a session as an administrator, the BAT file on > > > the Desktop, and I double-click on it, it does not work. > > > > This is not what I meant. Instead, right-click on the BAT file, > > and select "run as administrator". > > > > > When you say to double-escape the percent signs, do you mean that in > > > my BAT file I should write... > > > > > FTYPE python.file="C:\Python26\python.exe" "%%1" %%* > > > > > and the inverted commas around %%*, are they not necessary? > > > > No, I don't think so. > > > > Regards, > > Martin > > Martin (or anybody else), > > The problem with FTYPE is solved. > > However, after having switched to py 3.1 with the help of the BAT > script (which only changes FTYPE) I have another problem. > > (Just for reference, here is my batch file) > > @ECHO OFF > ECHO ************************************************ > ECHO Cambia a Python 3.1 > ECHO ************************************************ > ECHO * > ECHO FTYPES: > ECHO * > ECHO .py=Python.File > ECHO .pyc=Python.CompiledFile > ECHO .pyo=Python.CompiledFile > ECHO .pys=pysFile > ECHO .pyw=Python.NoConFile > ECHO * > ECHO ************************************************ > ECHO * > FTYPE python.file="C:\Python31\python.exe" "%%1" %%* > FTYPE python.compiledfile="C:\Python31\python.exe" "%%1" %%* > FTYPE python.NoConFile="C:\Python31\pythonw.exe" "%%1" %%* > ECHO * > Pause > @ECHO ON > > The problem is that, if I am on top of a .py file, and, with the > mouse, I click on the right button, then I click on "Edit with IDLE", > I get the 2.6 system, not the 3.1 one (which was supposed to be the > correct one after the change). > > My question is: are there any other changes that I should do in order > to fully switch from one version to another? Yes, and they are relatively easy to edit with a .reg file instead of a batch file. Below is just an example for type "Python.File" that adds "Open with Python3", "Edit with IDLE3", and "Open with Pythonwin3" commands to the right-click context menu of a .py file. The first 3 entries are the original Python26 entries. The last three were copied from them and modified to create the alternative context menus. You could also create two .reg files that toggle the original three entries between Python 2.6 and Python 3.1 if you want. -----------------------START------------------------ Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE\command] @="\"C:\\Python26\\pythonw.exe\" \"C:\\Python26\\Lib\\idlelib\\idle.pyw\" -n -e \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\Edit with Pythonwin\command] @="C:\\Python26\\Lib\\site-packages\\Pythonwin\\Pythonwin.exe /edit \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\open\command] @="\"C:\\Python26\\python.exe\" \"%1\" %*" [HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE3\command] @="\"C:\\Python31\\pythonw.exe\" \"C:\\Python31\\Lib\\idlelib\\idle.pyw\" -n -e \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\Edit with Pythonwin3\command] @="C:\\Python31\\Lib\\site-packages\\Pythonwin\\Pythonwin.exe /edit \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\Open with Python3\command] @="\"C:\\Python31\\python.exe\" \"%1\" %*" -------------------END--------------------------- -Mark From bartc at freeuk.com Wed Aug 25 04:22:41 2010 From: bartc at freeuk.com (BartC) Date: Wed, 25 Aug 2010 09:22:41 +0100 Subject: Iterative vs. Recursive coding In-Reply-To: <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com><4c6dcbc5$0$11111$c3e8da3@news.astraweb.com><4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> Message-ID: "Steven D'Aprano" wrote in message news:4c6f8edd$0$28653$c3e8da3 at news.astraweb.com... > On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: >> I onced worked in a shop (Win32 desktop / accouting applications mainly) >> where I was the only guy that could actually understand recursion. FWIW, >> I also was the only guy around that understood "hairy" (lol) concepts >> like callback functions, FSM, polymorphism, hashtables, linked lists, >> ADTs, algorithm complexity etc... > > > Was there anything they *did* understand, or did they just bang on the > keyboard at random until the code compiled? *wink* You underestimate how much programming (of applications) can be done without needing any of this stuff. >> Needless to say, I didn't last long !-) > > And rightly so :) I guess they wanted code that could be maintained by anybody. -- Bartc --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From durumdara at gmail.com Wed Aug 25 05:18:03 2010 From: durumdara at gmail.com (durumdara) Date: Wed, 25 Aug 2010 02:18:03 -0700 (PDT) Subject: ftplib limitations? References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74B333.5020206@sschwarzer.net> Message-ID: <8b5971fe-8561-4801-8605-5b9c1e186c84@f42g2000yqn.googlegroups.com> Hi! On aug. 25, 08:07, Stefan Schwarzer wrote: > > The file is 2 GB in size and is fully transferred, without > blocking or an error message. The status message from the > server is '226-File successfully transferred\n226 31.760 > seconds (measured here), 64.48 Mbytes per second', so this > looks ok, too. > > I think your problem is related to the FTP server or its > configuration. > > Have you been able to reproduce the problem? Yes. I tried with saving the file, but I also got this error. but: Total COmmander CAN download the file, and ncftpget also can download it without problem... Hmmmmm... :-( Thanks: dd From sschwarzer at sschwarzer.net Wed Aug 25 05:44:36 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 25 Aug 2010 11:44:36 +0200 Subject: ftplib limitations? In-Reply-To: References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> Message-ID: <4C74E604.6090208@sschwarzer.net> Hi durumdara, On 2010-08-25 09:43, durumdara wrote: >> I can imagine the error message (a full traceback if >> possible) would help to say a bit more about the cause of >> the problem and maybe what to do about it. > > This was: > > Filename: "Repositories 20100824_101805 (Teljes).zip" Size: 1530296127 > ..download: 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% > Traceback (most recent call last): > File "C:\D\LocalBackup\ftpdown.py", line 31, in > ftp.retrbinary("retr " + s, CallBack) > File "C:\Python26\lib\ftplib.py", line 401, in retrbinary > return self.voidresp() > File "C:\Python26\lib\ftplib.py", line 223, in voidresp > resp = self.getresp() > File "C:\Python26\lib\ftplib.py", line 209, in getresp > resp = self.getmultiline() > File "C:\Python26\lib\ftplib.py", line 195, in getmultiline > line = self.getline() > File "C:\Python26\lib\ftplib.py", line 182, in getline > line = self.file.readline() > File "C:\Python26\lib\socket.py", line 406, in readline > data = self._sock.recv(self._rbufsize) > socket.error: [Errno 10054] A l?tez? kapcsolatot a t?voli ?llom?s > k?nyszer?tette > n bez?rta > > So this message is meaning that the remote station forced close the > existing connection. The file transfer protocol uses two connections for data transfers, a control connection to send commands and responses, and a data connection for the data payload itself. Now it may be that the data connection, after having started the transfer, works as it should, but the control connection times out because the duration of the transfer is too long. A hint at this is that the traceback above contains `getline` and `readline` calls which strongly suggest that this socket was involved in some text transfer (presumably for a status message). Most FTP servers are configured for a timeout of 5 or 10 minutes. If you find that the file transfers don't fail reproducably for a certain size limit, it's probably not the size of the file that causes the problem but some timing issue (see above). What to do about it? One approach is to try to get the timeout value increased. Of course that depends on the relation between you and the party running the server. Another approach is to catch the exception and ignore it. To make sure you only ignore timeout messages, you may want to check the status code at the start of the error message and re-raise the exception if it's not the status expected for a timeout. Something along the lines of: try: # transer involving `retrbinary` except socket.error, exc: if str(exc).startswith("[Errno 10054] "): pass else: raise Note, however, that this is a rather brittle way to handle the problem, as the status code or format of the error message may depend on the platform your program runs on, library versions, etc. In any case you should close and re-open the FTP connection after you got the error from the server. > Now I'm trying with saving the file into temporary file, not hold in > memory. If my theory holds, that shouldn't make a difference. But maybe my theory is wrong. :) Could you do me a favor and try your download with ftputil [1]? The code should be something like: import ftputil host = ftputil.FTPHost(server, userid, passwd) for name in host.listdir(host.curdir): host.download(name, name, 'b') host.close() There's neither a need nor - at the moment - a possibility to specify a callback if you just want the download. (I'm working on the callback support though!) For finding the error, it's of course better to just use the download command for the file that troubles you. I'm the maintainer of ftputil and if you get the same or similar error here, I may find a workaround for ftputil. As it happens, someone reported a similar problem (_if_ it's the same problem in your case) just a few days ago. [2] [1] http://ftputil.sschwarzer.net [2] http://www.mail-archive.com/ftputil at codespeak.net/msg00141.html Stefan From fetchinson at googlemail.com Wed Aug 25 06:00:04 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 25 Aug 2010 12:00:04 +0200 Subject: pypy In-Reply-To: References: Message-ID: > Just curious if anyone had the chance to build pypy on a 64bit > environment and to see if it really makes a huge difference in > performance. Would like to hear some thoughts (or alternatives). I'd recommend asking about this on the pypy mailing list or looking at their documentation first; see http://codespeak.net/pypy/dist/pypy/doc/ HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From dak at gnu.org Wed Aug 25 06:04:08 2010 From: dak at gnu.org (David Kastrup) Date: Wed, 25 Aug 2010 12:04:08 +0200 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> Message-ID: <87eidnnh47.fsf@lola.goethe.zz> Hugh Aguilar writes: > On Aug 24, 5:16?pm, Paul Rubin wrote: >> Anyway, as someone else once said, studying a subject like CS isn't done >> by reading. ?It's done by writing out answers to problem after problem. >> Unless you've been doing that, you haven't been studying. > > What about using what I learned to write programs that work? Does that > count for anything? No. Having put together a cupboard that holds some books without falling apart does not make you a carpenter, much less an architect. -- David Kastrup From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 25 06:35:27 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 25 Aug 2010 12:35:27 +0200 Subject: Using String Methods In Jump Tables In-Reply-To: References: <4c6dcb1d$0$11111$c3e8da3@news.astraweb.com> Message-ID: <4c74f1e9$0$21917$426a74cc@news.free.fr> Tim Daneliuk a ?crit : > On 8/19/2010 7:23 PM, Steven D'Aprano wrote: >> On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote: >> >>> Problem: >>> >>> Given tuples in the form (key, string), use 'key' to determine what >>> string method to apply to the string: >>>>> table = {'l': str.lower, 'u': str.upper} >>>>> table['u']('hello world') >> 'HELLO WORLD' >> > (snip) > > Yeah ... those old assembler memories never quite fade do they. > I dunno what you might call this. A Function Dispatch Table > perhaps? I usually refers to this idiom as "dict-based dispatch". And FWIW, it's in fact (part of...) polymorphic dispatch implemention in Python's object model: >>> str.__dict__['lower'] >>> d = dict(l="lower", u="upper") >>> s = "aHa" >>> for k, v in d.items(): ... print "%s : %s" % (k, s.__class__.__dict__[v](s)) From alex at moreati.org.uk Wed Aug 25 06:36:38 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Wed, 25 Aug 2010 03:36:38 -0700 (PDT) Subject: problem with strptime and time zone References: <45f83a40-5e39-4871-bc6c-37fa07abba92@t20g2000yqa.googlegroups.com> <45faa241-620e-42c7-b524-949936f63610@f6g2000yqa.googlegroups.com> Message-ID: <611bf2ee-3715-4816-94ca-8a63b5ae8154@s9g2000yqd.googlegroups.com> On Aug 25, 8:48?am, Lawrence D'Oliveiro wrote: > In message > <45faa241-620e-42c7-b524-949936f63... at f6g2000yqa.googlegroups.com>, Alex > > Willmer wrote: > > Dateutil has it's own timezone database ... > > I hate code which doesn?t just use /usr/share/zoneinfo. How many places do > you need to patch every time somebody changes their daylight-saving rules? >From reading http://labix.org/python-dateutil can read timezone information from several platforms, including /usr/share/zoneinfo. I don't know whether one chooses the source explicitly, or if it is detected with fall back to the internal database. From mail at johnohagan.com Wed Aug 25 07:00:23 2010 From: mail at johnohagan.com (John O'Hagan) Date: Wed, 25 Aug 2010 11:00:23 +0000 Subject: Helper classes design question In-Reply-To: <4C73AF10.5010703@sequans.com> References: <201008231047.57128.mail@johnohagan.com> <4C73AF10.5010703@sequans.com> Message-ID: <201008251100.23743.mail@johnohagan.com> On Tue, 24 Aug 2010, Jean-Michel Pichavant wrote: > John O'Hagan wrote: > > I want to know the best way to organise a bunch of functions designed to > > operate on instances of a given class without cluttering the class itself > > with a bunch of unrelated methods. > > > > What I've done is make what I think are called helper classes, each of > > which are initialized with an instance of the main class and has methods > > which are all of the same type (insofar as they return a boolean, or > > modify the object in place, or whatever). > > > > I'm not sure if I'm on the right track here design-wise. Maybe this could > > be better done with inheritance (not my forte), but my first thought is > > that no, the helper classes (if that's what they are) are not actually a > > type of the main class, but are auxiliary to it. I wasn't subscribed when I posted this question so the quoting and threading is messed up (sorry), but thanks for the differing approaches; in the end I have taken Peter Otten's advice and simply put the functions in separate modules according to type (instead of in classes as methods), then imported them. This has all the advantages of using a class, in that I can add new functions in just one place and call them as required without knowing what they are, e.g.: options = {dictionary of option names and values} #derived from optparse for sequence in sequences: for option, value in options.items(): {imported namespace}[option](sequence, value) but it seems simpler and cleaner. John From blog at rivadpm.com Wed Aug 25 07:05:58 2010 From: blog at rivadpm.com (Alex McDonald) Date: Wed, 25 Aug 2010 04:05:58 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> Message-ID: <0b04a316-a147-4179-a11f-de7a935385ea@q16g2000prf.googlegroups.com> On 25 Aug, 01:00, Hugh Aguilar wrote: > On Aug 24, 4:17?pm, Richard Owlett wrote: > > > Hugh Aguilar wrote: > > > [SNIP ;] > > > > The real problem here is that C, Forth and C++ lack automatic garbage > > > collection. If I have a program in which I have to worry about memory > > > leaks (as described above), I would be better off to ignore C, Forth > > > and C++ and just use a language that supports garbage collection. Why > > > should I waste my time carefully freeing up heap space? I will very > > > likely not find everything but yet have a few memory leaks anyway. > > > IOW Hugh has surpassed GIGO to achieve AGG - > > *A*utomatic*G*arbage*G*eneration ;) > > The C programmers reading this are likely wondering why I'm being > attacked. The reason is that Elizabeth Rather has made it clear to > everybody that this is what she wants:http://groups.google.com/group/comp.lang.forth/browse_thread/thread/c... > > Every Forth programmer who aspires to get a job at Forth Inc. is > obliged to attack me. Attacking my software that I posted on the FIG > site is preferred, but personal attacks work too. It is a loyalty > test. Complete bollox. A pox on your persecution fantasies. This isn't about Elizabeth Rather or Forth Inc. It's about your massive ego and blind ignorance. Your example of writing code with memory leaks *and not caring because it's a waste of your time* makes me think that you've never been a programmer of any sort. Ever. In a commercial environment, your slide rule code would be rejected during unit testing, and you'd be fired and your code sent to the bit bucket. This isn't about CS BS; this is about making sure that banks accounts square, that planes fly, that nuclear reactors stay sub-critical; that applications can run 24 by 7, 365 days a year without requiring any human attention. So who designs and writes compilers for fail-safe systems? Who designs and writes operating systems that will run for years, non-stop? Where do they get the assurance that what they're writing is correct -- and provably so? From people that do research, hard math, have degrees, and design algorithms and develop all those other abstract ideas you seem so keen to reject as high-falutin' nonsense. I'd rather poke myself in the eye than run any of the crap you've written. From sschwarzer at sschwarzer.net Wed Aug 25 07:41:27 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 25 Aug 2010 13:41:27 +0200 Subject: ftplib limitations? In-Reply-To: <8b5971fe-8561-4801-8605-5b9c1e186c84@f42g2000yqn.googlegroups.com> References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74B333.5020206@sschwarzer.net> <8b5971fe-8561-4801-8605-5b9c1e186c84@f42g2000yqn.googlegroups.com> Message-ID: <4C750167.7040000@sschwarzer.net> Hi durumdara, On 2010-08-25 11:18, durumdara wrote: > On aug. 25, 08:07, Stefan Schwarzer wrote: >> >> The file is 2 GB in size and is fully transferred, without >> blocking or an error message. The status message from the >> server is '226-File successfully transferred\n226 31.760 >> seconds (measured here), 64.48 Mbytes per second', so this >> looks ok, too. >> >> I think your problem is related to the FTP server or its >> configuration. >> >> Have you been able to reproduce the problem? > > Yes. I tried with saving the file, but I also got this error. > but: Total COmmander CAN download the file, and ncftpget also can > download it without problem... I suppose they do the same as in my former suggestion: "catching" the error and ignoring it. ;-) After all, if I understood you correctly, you get the complete file contents, so with ftplib the download succeeds as well (in a way). You might want to do something like (untested): import os import socket import ftputil def my_download(host, filename): """Some intelligent docstring.""" # Need timestamp to check if we actually have a new # file after the attempted download try: old_mtime = os.path.getmtime(filename) except OSError: old_mtime = 0.0 try: host.download(filename, filename, 'b') except socket.error: is_rewritten = (os.path.getmtime(filename) != old_mtime) # If you're sure that suffices as a test is_complete = (host.path.getsize(filename) == os.path.getsize(filename)) if is_rewritten and is_complete: # Transfer presumably successful, ignore error pass else: # Something else went wrong raise def main(): host = ftputil.FTPHost(...) my_download(host, "large_file") host.close() If you don't want to use an external library, you can use `ftplib.FTP`'s `retrbinary` and check the file size with `ftplib.FTP.size`. This size command requires support for the SIZE command on the server, whereas ftputil parses the remote directory listing to extract the size and so doesn't depend on SIZE support. Stefan From magguru.chinnamnaidu at gmail.com Wed Aug 25 07:42:40 2010 From: magguru.chinnamnaidu at gmail.com (paypal cash) Date: Wed, 25 Aug 2010 04:42:40 -0700 (PDT) Subject: Simple hack to get *$5000* to your Paypal account Message-ID: <1e8ff0e9-212e-44c3-97c8-6d165cf593ac@x20g2000pro.googlegroups.com> Simple hack to get* $5000 * to your Paypal account At http://moneyforwarding.co.cc i have hidden the Paypal Form link in an image. in that website on Right Side below search box, click on image and enter your name and Paypal ID. From anton at mips.complang.tuwien.ac.at Wed Aug 25 08:26:20 2010 From: anton at mips.complang.tuwien.ac.at (Anton Ertl) Date: Wed, 25 Aug 2010 12:26:20 GMT Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> <0b04a316-a147-4179-a11f-de7a935385ea@q16g2000prf.googlegroups.com> Message-ID: <2010Aug25.142620@mips.complang.tuwien.ac.at> Alex McDonald writes: > Your example of writing code with >memory leaks *and not caring because it's a waste of your time* makes >me think that you've never been a programmer of any sort. Ever. Well, I find his approach towards memory leaks as described in <779b992b-7199-4126-bf3a-7ec40ea801a6 at j18g2000yqd.googlegroups.com> quite sensible, use something like that myself, and recommend it to others. Followups set to c.l.f (adjust as appropriate). - anton -- M. Anton Ertl http://www.complang.tuwien.ac.at/anton/home.html comp.lang.forth FAQs: http://www.complang.tuwien.ac.at/forth/faq/toc.html New standard: http://www.forth200x.org/forth200x.html EuroForth 2010: http://www.euroforth.org/ef10/ From darwin at nowhere.com Wed Aug 25 08:33:21 2010 From: darwin at nowhere.com (Paul Hemans) Date: Wed, 25 Aug 2010 22:33:21 +1000 Subject: Newbie: Win32 COM problem Message-ID: Simple class to wrap the xlwt module for COM access pyXLS.py: from xlwt import Workbook class WrapXLS: _reg_clsid_ = "{c94df6f0-b001-11df-8d63-00e09103a9a0}" _reg_desc_ = "XLwt wrapper" _reg_progid_ = "PyXLS.Write" _public_methods_ = ['createBook','createSheet','writeSheetCell','saveBook'] # _public_attrs_ = ['book'] def __init__(self): self.book = None def createBook(self): self.book = Workbook() def createSheet(self,sheetName): self.book.add_sheet(sheetName) def writeSheetCell(self, sheet, row, col, value, style=""): sheet = self.book.get_sheet(sheet) sheet.write(row,col,value,style) def saveBook(self,fileName): self.book.save(fileName) if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(WrapXLS) It registers ok with --debug. Code executing within Foxpro (no comments pls): oPyXLS = CREATEOBJECT("PyXLS.Write") oPyXLS.createBook() oPyXLS.createSheet("Sheet 1") -- Error here Output in Python Trace Collector (PythonWin): ... in _GetIDsOfNames_ with '(u'createsheet',)' and '1033' in _Invoke_ with 1001 1033 3 (u'Sheet 1',) Traceback (most recent call last): File "C:\Python26\lib\site-packages\win32com\server\dispatcher.py", line 47, in _Invoke_ return self.policy._Invoke_(dispid, lcid, wFlags, args) File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 277, in _Invoke_ return self._invoke_(dispid, lcid, wFlags, args) File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 282, in _invoke_ return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 585, in _invokeex_ return func(*args) File "C:\development\PyXLS\pyXLS.py", line 13, in createSheet def createBook(self): AttributeError: WrapXLS instance has no attribute '_book' pythoncom error: Python error invoking COM method. Can anyone help? From samufuentes at gmail.com Wed Aug 25 09:03:51 2010 From: samufuentes at gmail.com (Samu) Date: Wed, 25 Aug 2010 06:03:51 -0700 (PDT) Subject: staticmethod behaviour Message-ID: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Hi, I run today into some problems with my code and I realized that there is something in the behaviours of the @staticmethod that I don't really understand. I don't know if it is an error or not, actually, only that it was, definitely, unexpected. I wrote a small demo of what happens. The code: http://dpaste.com/hold/233795/ The answer I get: User created with static: id, rights, rights2 1 ['read', 'write'] ['write2'] ['write3'] User created with User() None [] ['write2'] ['write3'] I was expecting either all arrays from the second to be [] or to be a copy of the first one. If someone can provide an explanation, I would be thankful :) Regards, Samu From samufuentes at gmail.com Wed Aug 25 09:18:37 2010 From: samufuentes at gmail.com (Samu) Date: Wed, 25 Aug 2010 06:18:37 -0700 (PDT) Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: <7492d4d2-8b35-4fc3-a9a1-fe894eba50b1@g17g2000yqe.googlegroups.com> On Aug 25, 3:03?pm, Samu wrote: > Hi, > > I run today into some problems with my code and I realized that there > is something in the behaviours of the @staticmethod that I don't > really understand. I don't know if it is an error or not, actually, > only that it was, definitely, unexpected. > > I wrote a small demo of what happens. > > The code:http://dpaste.com/hold/233795/ > > The answer I get: > User created with static: id, rights, rights2 > 1 ['read', 'write'] ['write2'] ['write3'] > User created with User() > None [] ['write2'] ['write3'] > > I was expecting either all arrays from the second to be [] or to be a > copy of the first one. > > If someone can provide an explanation, I would be thankful :) > > Regards, > Samu In addition, if I don't define the function as static, but either as a method of the object or a function outside of the class, something like this: def cr_user(): user = User(1, ['read'], rights3=[]) user.rights.append('write') user.rights2.append('write2') user.rights3.append('write3') return user I get instead: User created with static: id, rights, rights2 1 ['read', 'write'] ['write2'] ['write3'] User created with User() None [] ['write2'] [] There is some (maybe deep) concept that I don't get it seems, because that output puzzles me... From __peter__ at web.de Wed Aug 25 09:26:10 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Aug 2010 15:26:10 +0200 Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: Samu wrote: > Hi, > > I run today into some problems with my code and I realized that there > is something in the behaviours of the @staticmethod that I don't > really understand. I don't know if it is an error or not, actually, > only that it was, definitely, unexpected. > > I wrote a small demo of what happens. > The code: > class User: > def __init__(self, id=None, rights=[], rights2=[], rights3=[]): > self.id = id > self.rights = rights > self.rights2 = rights2 > self.rights3 = rights3 > @staticmethod > def cr_user(): > user = User(1, ['read'], rights3=[]) > user.rights.append('write') > user.rights2.append('write2') > user.rights3.append('write3') > return user > > print "User created with static: id, rights, rights2" > a = User.cr_user() > print a.id, a.rights, a.rights2, a.rights3 > print "User created with User()" > b = User() > print b.id, b.rights, b.rights2, a.rights3 > The answer I get: > User created with static: id, rights, rights2 > 1 ['read', 'write'] ['write2'] ['write3'] > User created with User() > None [] ['write2'] ['write3'] > > I was expecting either all arrays from the second to be [] or to be a > copy of the first one. > > If someone can provide an explanation, I would be thankful :) The problem is not the staticmethod, it's the mutable default values for __init__(). See http://effbot.org/zone/default-values.htm Peter From dsdale24 at gmail.com Wed Aug 25 09:49:29 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Wed, 25 Aug 2010 06:49:29 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: <23146f03-2502-427d-b55d-aec06f732fbf@x21g2000yqa.googlegroups.com> On Aug 24, 5:29?pm, Benjamin Kaplan wrote: > On Tue, Aug 24, 2010 at 3:31 PM, Darren Dale wrote: > > On Aug 23, 9:58?am, Darren Dale wrote: > >> The following script runs without problems on Ubuntu and Windows 7. > >> h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > >> h5py/): > > >> from multiprocessing import Pool > >> import h5py > > >> def update(i): > >> ? ? print i > > >> def f(i): > >> ? ? "hello foo" > >> ? ? return i*i > > >> if __name__ == '__main__': > >> ? ? pool = Pool() > >> ? ? for i in range(10): > >> ? ? ? ? pool.apply_async(f, [i], callback=update) > >> ? ? pool.close() > >> ? ? pool.join() > > >> On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > >> comment out the as-yet unused h5py import, otherwise I get a > >> traceback: > > >> Exception in thread Thread-1: > >> Traceback (most recent call last): > >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > >> lib/python2.6/threading.py", line 532, in __bootstrap_inner > >> ? ? self.run() > >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > >> lib/python2.6/threading.py", line 484, in run > >> ? ? self.__target(*self.__args, **self.__kwargs) > >> ? File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ > >> lib/python2.6/multiprocessing/pool.py", line 226, in _handle_tasks > >> ? ? put(task) > >> PicklingError: Can't pickle : attribute lookup > >> __builtin__.function failed > > > This is a really critical bug for me, but I'm not sure how to proceed. > > Can I file a bug report on the python bugtracker if the only code I > > can come up with to illustrate the problem requires a lame import of a > > third party module? > > -- > > It's working fine for me, OS X 10.6.4, Python 2.6 and h5py from Macports. Really? With the h5py import uncommented? I just uninstalled and reinstalled my entire macports python26/py26-numpy/hdf5-18/py26-h5py stack, and I still see the same error. From steve.ferg.bitbucket at gmail.com Wed Aug 25 09:56:22 2010 From: steve.ferg.bitbucket at gmail.com (Steve Ferg) Date: Wed, 25 Aug 2010 06:56:22 -0700 (PDT) Subject: Help please! strange Tkinter behavior has me totally baffled. References: <6270b512-8b73-434d-83c3-ec5c60100eb1@w17g2000vbn.googlegroups.com> Message-ID: Thanks mucho! That was it! -- Steve Ferg From dsdale24 at gmail.com Wed Aug 25 09:58:35 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Wed, 25 Aug 2010 06:58:35 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: <1cbf9e1f-67c5-4519-880b-7c65c9504777@s9g2000yqd.googlegroups.com> On Aug 24, 4:32?pm, Thomas Jollans wrote: > On Tuesday 24 August 2010, it occurred to Darren Dale to exclaim: > > > > > > > On Aug 23, 9:58 am, Darren Dale wrote: > > > The following script runs without problems on Ubuntu and Windows 7. > > > h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > > > h5py/): > > > > from multiprocessing import Pool > > > import h5py > > > > def update(i): > > > ? ? print i > > > > def f(i): > > > ? ? "hello foo" > > > ? ? return i*i > > > > if __name__ == '__main__': > > > ? ? pool = Pool() > > > ? ? for i in range(10): > > > ? ? ? ? pool.apply_async(f, [i], callback=update) > > > ? ? pool.close() > > > ? ? pool.join() > > > > On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > > > comment out the as-yet unused h5py import, otherwise I get a > > > traceback: > > What on earth is h5py doing there? ?If what you're telling us is actually > happening, and the code works 1:1 on Linux and Windows, but fails on OSX, and > you're using the same versions of h5py and Python, then the h5py > initialization code is not only enticing multiprocessing to try to pickle > something other than usual, but it is also doing that due to some platform- > dependent witchcraft, and I doubt there's very much separating the OSX > versions from the Linux versions of anything involved. I can't find anything in the source to suggest that h5py is doing any platform-specific magic. Do you have an idea of how it would be possible for initialization code to cause multiprocessing to try to pickle something it normally would not? > > This is a really critical bug for me, but I'm not sure how to proceed. > > Can I file a bug report on the python bugtracker if the only code I > > can come up with to illustrate the problem requires a lame import of a > > third party module? > > I doubt this is an issue with Python. File a bug on the h5py tracker and see > what they say. The people there might at least have some vague inkling of what > may be going on. Thanks for the suggestion. I was in touch with the h5py maintainer before my original post. We don't have any leads. From samufuentes at gmail.com Wed Aug 25 09:58:46 2010 From: samufuentes at gmail.com (Samu) Date: Wed, 25 Aug 2010 06:58:46 -0700 (PDT) Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: On Aug 25, 3:26?pm, Peter Otten <__pete... at web.de> wrote: > Samu wrote: > > Hi, > > > I run today into some problems with my code and I realized that there > > is something in the behaviours of the @staticmethod that I don't > > really understand. I don't know if it is an error or not, actually, > > only that it was, definitely, unexpected. > > > I wrote a small demo of what happens. > > The code: > > class User: > > ?def __init__(self, id=None, rights=[], rights2=[], rights3=[]): > > ? self.id = id > > ? self.rights = rights > > ? self.rights2 = rights2 > > ? self.rights3 = rights3 > > ?@staticmethod > > ?def cr_user(): > > ? user = User(1, ['read'], rights3=[]) > > ? user.rights.append('write') > > ? user.rights2.append('write2') > > ? user.rights3.append('write3') > > ? return user > > > print "User created with static: id, rights, rights2" > > a = User.cr_user() > > print a.id, a.rights, a.rights2, a.rights3 > > print "User created with User()" > > b = User() > > print b.id, b.rights, b.rights2, a.rights3 > > The answer I get: > > User created with static: id, rights, rights2 > > 1 ['read', 'write'] ['write2'] ['write3'] > > User created with User() > > None [] ['write2'] ['write3'] > > > I was expecting either all arrays from the second to be [] or to be a > > copy of the first one. > > > If someone can provide an explanation, I would be thankful :) > > The problem is not the staticmethod, it's the mutable default values for > __init__(). See > > http://effbot.org/zone/default-values.htm > > Peter Ahh, thank you very much for the link. Now I understand. I remember having read that before, but it is not until you face the problem that the concept sticks. But why does it have a different behaviour the staticmethod with the "rights3" case then? From carlos.grohmann at gmail.com Wed Aug 25 09:59:36 2010 From: carlos.grohmann at gmail.com (Carlos Grohmann) Date: Wed, 25 Aug 2010 06:59:36 -0700 (PDT) Subject: speed of numpy.power()? Message-ID: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Hi all, I'd like to hear from you on the benefits of using numpy.power(x,y) over (x*x*x*x..) I looks to me that numpy.power takes more time to run. cheers Carlos From nanothermite911fbibustards at gmail.com Wed Aug 25 10:12:22 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 07:12:22 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards Message-ID: <9c3b672d-b636-4f12-9918-4837784fce42@x42g2000yqx.googlegroups.com> CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list From breamoreboy at yahoo.co.uk Wed Aug 25 10:20:50 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 25 Aug 2010 15:20:50 +0100 Subject: speed of numpy.power()? In-Reply-To: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: On 25/08/2010 14:59, Carlos Grohmann wrote: > Hi all, > > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > > I looks to me that numpy.power takes more time to run. > > cheers > > Carlos > Measure it yourself using the timeit module. Cheers. Mark Lawrence. From nanothermite911fbibustards at gmail.com Wed Aug 25 10:22:22 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 07:22:22 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards Message-ID: <059e2fea-bf6d-4f55-b9e9-7338ea1fbe97@f6g2000yqa.googlegroups.com> CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list From ajeet.yadav.77 at gmail.com Wed Aug 25 10:25:38 2010 From: ajeet.yadav.77 at gmail.com (Ajeet Yadav) Date: Wed, 25 Aug 2010 19:55:38 +0530 Subject: Python2.4 on ARM-Linux "import time module fails" Message-ID: Hi, I cross-compiled Python2.4 for ARM (Linux 2.6.30) in order to run autotest-client-xxx on my ARM target. When I run autotest on ARM target I get "ImportError: No module named time" Which package I need to install to add support for time module. # bin/autotest samples/filesystem Traceback (most recent call last): File "bin/autotest", line 6, in ? import common File "/dtv/usb/sda1/autotest-client-0.12.0-dirty/bin/common.py", line 8, in ? root_module_name="autotest_lib.client") File "/dtv/usb/sda1/autotest-client-0.12.0-dirty/setup_modules.py", line 139, in setup _monkeypatch_logging_handle_error() File "/dtv/usb/sda1/autotest-client-0.12.0-dirty/setup_modules.py", line 103, in _monkeypatch_logging_handle_error import logging File "/dtv/usb/sda1/Python-2.4/Lib/logging/__init__.py", line 29, in ? import sys, os, types, time, string, cStringIO ImportError: No module named time With Regards Ajeet Yadav -------------- next part -------------- An HTML attachment was scrubbed... URL: From stndshp at gmail.com Wed Aug 25 10:31:03 2010 From: stndshp at gmail.com (Standish P) Date: Wed, 25 Aug 2010 07:31:03 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards References: <9c3b672d-b636-4f12-9918-4837784fce42@x42g2000yqx.googlegroups.com> Message-ID: On Aug 25, 7:12?am, nanothermite911fbibustards wrote: > CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria > Lauterbach and KILL THEM > > Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist > Bustard who > > The girl was a German like the one Roman Polansky raped, Semantha > Geimer > > http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ > > Look at his face, what criminal race is he ? What goes around comes > around !!! > > Former Marine convicted in North Carolina of killing female colleague > By the CNN Wire Staff > August 23, 2010 8:33 p.m. EDT > > For more on this story, read the coverage from CNN affiliate WRAL. > > (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North > Carolina on Monday of first degree murder in the 2007 death of Lance > Cpl. Maria Lauterbach, who was eight months pregnant when she died. > > An autopsy showed that Lauterbach, 20, died of blunt force trauma to > the head. Police unearthed her charred body from beneath a barbecue > pit in Laurean's backyard in January 2008. She had disappeared the > month before. > > Laurean, who was dressed in black slacks and wore a white shirt and > black tie, did not show any emotion as the judge read his sentence of > life in prison without parole. He either said or mouthed something to > someone in the audience of the courtroom before he was led out in > handcuffs, video showed. > > Laurean and Lauterbach were stationed together at Camp Lejeune, North > Carolina. > > North Carolina prosecutors alleged Laurean killed Lauterbach on > December 14 and used her ATM card 10 days later before fleeing to > Mexico.Laurean was arrested there in April 2008. He holds dual > citizenship in the United States and Mexico. > > Before her death, Lauterbach told the Marines that Laurean had raped > her. Laurean denied it, and disappeared just a few weeks before a > scheduled rape hearing at Camp LeJeune. > > The DNA of Lauterbach's unborn child did not match that of Laurean, > according to law enforcement personnel. > > Authorities found Lauterbach's body after Laurean's wife, Christina, > produced a note her husband had written claiming the 20-year-old > woman > slit her own throat during an argument, according to officials. > > Although a gaping 4-inch wound was found on the left side of > Lauterbach's neck, autopsy results indicated that the wound itself > would not have been fatal and may have occurred after death. > > Asked by a Mexican reporter at the time of his arrest whether he > killed Lauterbach, Laurean replied, "I loved her." > > Laurean's lawyer said his client would appeal the decision. > > ///////////////////////////////////////////////////////////////// > > The MARINE BASTARD will probably claim INSANITY ........ > > ////////////////////// > The FAT per DIEM FBI bustards use our TAX PAYER MONEY and > INCOMPETENCE > is UNACCEPTABLE. > > ===== > > http://www.youtube.com/watch?v=lX18zUp6WPY > > http://www.youtube.com/watch?v=XQapkVCx1HI > > http://www.youtube.com/watch?v=tXJ-k-iOg0M > > Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX > Mailer ? > Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did > you release the 5 dancing Israelis compromising the whole 911 > investigation ? If the Dubai Police can catch Mossad Murderers and > put > the videos and Iranian Police can why cant you put the Pentagon > Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and > puting on INTERNATIONAL MEDIA a day after catching him without > TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did > you have to LIE about Dr Afiya Siddiqui and torture that Innocent > little mother of 3 and smashing the skull of her one child ? > > http://www.youtube.com/watch?v=DhMcii8smxkhttp://www.youtube.com/watch?v=0SZ2lxDJmdg > > There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian > courts. > > FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but > only because he was a white. They got away with MURDER of thousands > of > Non-whites in all parts of the world. > > Daily 911 news :http://911blogger.com > > http://www.youtube.com/watch?v=tRfhUezbKLw > > http://www.youtube.com/watch?v=x7kGZ3XPEm4 > > http://www.youtube.com/watch?v=lX18zUp6WPY > > Conclusion : FBI bustards are RACIST and INcompetent. They could > neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they > cover them up - whichever was their actual goal or task. > > SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across > tbe board, esp the whites/jew on the top. > > FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST > and > UNPATRIOTIC Act > FBI bustards failed to prevent ROMAN POLANSKY from absconding to > europe and rapes. > FBI bustards failed to prevent OKLAHOMA > > --http://mail.python.org/mailman/listinfo/python-list ... so you want to render this in TeX ... ? From __peter__ at web.de Wed Aug 25 10:32:02 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Aug 2010 16:32:02 +0200 Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: Samu wrote: > the concept sticks. But why does it have a different behaviour the > staticmethod with the "rights3" case then? Moving from staticmethod to standalone function doesn't affect the output. You have inadvertently changed something else. Peter From hniksic at xemacs.org Wed Aug 25 10:41:27 2010 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 25 Aug 2010 16:41:27 +0200 Subject: speed of numpy.power()? References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: <874oei69go.fsf@busola.homelinux.net> Carlos Grohmann writes: > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > > I looks to me that numpy.power takes more time to run. You can use math.pow, which is no slower than repeated multiplication, even for small exponents. Obviously, after the exponent has grown large enough, numpy.power becomes faster than repeated exponentiation (it's already faster at 100). Like math.pow, it supports negative and non-integer exponents. Unlike math.pow, numpy.power also supports all kinds of interesting objects as bases for exponentiation. From nick_keighley_nospam at hotmail.com Wed Aug 25 10:43:36 2010 From: nick_keighley_nospam at hotmail.com (Nick Keighley) Date: Wed, 25 Aug 2010 07:43:36 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <3b3e2bbb-db52-4a6d-a38e-2e853c4c049f@t20g2000yqa.googlegroups.com> <860dc63c-bc00-4960-956e-ba0cfa0b4e22@s9g2000yqd.googlegroups.com> <518b97c6-78ad-4ce9-9967-c7f72ea74109@5g2000yqz.googlegroups.com> <4c6d356f.608280081@text.giganews.com> Message-ID: <2e241131-17f7-4cf0-9e0e-f2ec4e11f714@v41g2000yqv.googlegroups.com> On 19 Aug, 16:25, c... at tiac.net (Richard Harter) wrote: > On Wed, 18 Aug 2010 01:39:09 -0700 (PDT), Nick Keighley > wrote: > >On 17 Aug, 18:34, Standish P wrote: > >> How are these heaps being implemented ? Is there some illustrative > >> code or a book showing how to implement these heaps in C for example ? > > >any book of algorithms I'd have thought my library is currently inaccessible. Normally I'd have picked up Sedgewick and seen what he had to say on the subject. And possibly Knuth (though that requires taking more of a deep breath). Presumably Plauger's library book includes an implementation of malloc()/free() so that might be a place to start. > >http://en.wikipedia.org/wiki/Dynamic_memory_allocation > >http://www.flounder.com/inside_storage_allocation.htm > > >I've no idea how good either of these is serves me right for not checking :-( > The wikipedia page is worthless. ? odd really, you'd think basic computer science wasn't that hard... I found even wikipedia's description of a stack confusing and heavily biased towards implementation > The flounder page has > substantial meat, but the layout and organization is a mess. ?A > quick google search didn't turn up much that was general - most > articles are about implementations in specific environments. From samufuentes at gmail.com Wed Aug 25 11:17:03 2010 From: samufuentes at gmail.com (Samu) Date: Wed, 25 Aug 2010 08:17:03 -0700 (PDT) Subject: staticmethod behaviour References: <4d1dc04e-e297-496a-a47d-c86f25a9bbd5@v8g2000yqe.googlegroups.com> Message-ID: <9ac9f8a0-4127-4138-9452-bc0431a3c579@x42g2000yqx.googlegroups.com> On Aug 25, 4:32?pm, Peter Otten <__pete... at web.de> wrote: > Samu wrote: > > the concept sticks. But why does it have a different behaviour the > > staticmethod with the "rights3" case then? > > Moving from staticmethod to standalone function doesn't affect the output. > You have inadvertently changed something else. > > Peter Absolutely right. Thank you very much for your time and answers, Peter :) It helped me a lot! From exarkun at twistedmatrix.com Wed Aug 25 11:24:13 2010 From: exarkun at twistedmatrix.com (Jean-Paul Calderone) Date: Wed, 25 Aug 2010 08:24:13 -0700 (PDT) Subject: How to see intermediate fail results from unittest as tests are running? References: Message-ID: <68309158-cc5d-4857-952a-d89cb767cb35@q22g2000yqm.googlegroups.com> On Aug 18, 9:20?pm, Margie Roginski wrote: > Hi, > > I am using unittest in a fairly basic way, where I have a single file > that simply defines a class that inherits from unittest.TestCase and > then within that class I have a bunch of methods that start with > "test". ?Within that file, at the bottom I have: > > if __name__ == "__main__": > ? ? unittest.main() > > This works fine and it runs all of the testxx() methods in my file. > As it runs it prints if the tests passed or failed, but if they fail, > it does not print the details of the assert that made them fail. ?It > collects this info up and prints it all at the end. > > Ok - my question: Is there any way to get unittest to print the > details of the assert that made a test fail, as the tests are > running? ?IE, after a test fails, I would like to see why, rather than > waiting until all the tests are done. > > I've searched the doc and even looked at the code, and it seems the > answer is no, but I'm just wondering if I'm missing something. > > Thanks! > > Margie trial (Twisted's test runner) has a `--rterrors` option which causes it to display errors as soon as they happen. Jean-Paul From cournape at gmail.com Wed Aug 25 11:40:10 2010 From: cournape at gmail.com (David Cournapeau) Date: Thu, 26 Aug 2010 00:40:10 +0900 Subject: speed of numpy.power()? In-Reply-To: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: On Wed, Aug 25, 2010 at 10:59 PM, Carlos Grohmann wrote: > Hi all, > > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) Without more context, I would say None if x*x*x*x*... works and you are not already using numpy. The point of numpy is mostly to work on numpy arrays, and to support types of data not "natively" supported by python (single, extended precision). If x is a python object such as int or float, numpy will also be much slower. Using numpy would make sense if for example you are already using numpy everywhere else, for consistency reason, David From carlos.grohmann at gmail.com Wed Aug 25 11:59:19 2010 From: carlos.grohmann at gmail.com (Carlos Grohmann) Date: Wed, 25 Aug 2010 08:59:19 -0700 (PDT) Subject: speed of numpy.power()? References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: <5cd0c88f-5be7-443a-885e-6fc6deaaf3f0@x42g2000yqx.googlegroups.com> On 25 ago, 12:40, David Cournapeau wrote: > On Wed, Aug 25, 2010 at 10:59 PM, Carlos Grohmann > Thanks David and Hrvoje. That was the feedback I was looking for. I am using numpy in my app but in some cases I will use math.pow(), as some tests with timeit showed that numpy.power was slower for (x*x*x*x*x). best Carlos From dsdale24 at gmail.com Wed Aug 25 12:24:01 2010 From: dsdale24 at gmail.com (Darren Dale) Date: Wed, 25 Aug 2010 09:24:01 -0700 (PDT) Subject: problem with simple multiprocessing script on OS X References: <5fcea7ea-13ad-41af-8a68-9d418f9cdf93@i31g2000yqm.googlegroups.com> <45015919-6de0-4ed3-b4fe-62824e16cd43@t11g2000vbc.googlegroups.com> Message-ID: On Aug 24, 4:32?pm, Thomas Jollans wrote: > On Tuesday 24 August 2010, it occurred to Darren Dale to exclaim: > > > > > > > On Aug 23, 9:58 am, Darren Dale wrote: > > > The following script runs without problems on Ubuntu and Windows 7. > > > h5py is a package wrapping the hdf5 library (http://code.google.com/p/ > > > h5py/): > > > > from multiprocessing import Pool > > > import h5py > > > > def update(i): > > > ? ? print i > > > > def f(i): > > > ? ? "hello foo" > > > ? ? return i*i > > > > if __name__ == '__main__': > > > ? ? pool = Pool() > > > ? ? for i in range(10): > > > ? ? ? ? pool.apply_async(f, [i], callback=update) > > > ? ? pool.close() > > > ? ? pool.join() > > > > On OS X 10.6 (tested using python-2.6.5 from MacPorts), I have to > > > comment out the as-yet unused h5py import, otherwise I get a > > > traceback: > > What on earth is h5py doing there? ?If what you're telling us is actually > happening, and the code works 1:1 on Linux and Windows, but fails on OSX, and > you're using the same versions of h5py and Python, then the h5py > initialization code is not only enticing multiprocessing to try to pickle > something other than usual, but it is also doing that due to some platform- > dependent witchcraft, and I doubt there's very much separating the OSX > versions from the Linux versions of anything involved. Your analysis was spot on. About a year ago, I contributed a patch to h5py which checks to see if h5py is being imported into an active IPython session. If so, then a custom tab completer is loaded to make it easier to navigate hdf5 files. In the development version of IPython, a function that used to return None if there was no instance of an IPython interactive shell now creates and returns a new instance. This was the cause of the error I was reporting. If one were to install ipython from the master branch at github or from http://ipython.scipy.org/dist/testing/ipython-dev-nightly.tgz, then the following script will reproduce the problem. I'm not sure why this causes an error, but I'll discuss it with the IPython devs. Thank you Thomas and Benjamin for helping me understand the problem. Darren from multiprocessing import Pool import IPython.core.ipapi as ip ip.get() def update(i): print i def f(i): return i*i if __name__ == '__main__': pool = Pool() for i in range(10): pool.apply_async(f, [i], callback=update) pool.close() pool.join() From robert.kern at gmail.com Wed Aug 25 12:44:06 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 25 Aug 2010 11:44:06 -0500 Subject: speed of numpy.power()? In-Reply-To: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: On 8/25/10 8:59 AM, Carlos Grohmann wrote: > Hi all, > > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > > I looks to me that numpy.power takes more time to run. You will want to ask numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists The advantage that numpy.power(x,y) has over (x*x*x...) is that y can be floating point. We do not attempt to do strength reduction in the integer case. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ppearson at nowhere.invalid Wed Aug 25 13:39:46 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 25 Aug 2010 17:39:46 GMT Subject: speed of numpy.power()? References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> Message-ID: <8dl2r2F5h4U1@mid.individual.net> On Wed, 25 Aug 2010 06:59:36 -0700 (PDT), Carlos Grohmann wrote: > > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > Using the "dis" package under Python 2.5, I see that computing x_to_the_16 = x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x uses 15 multiplies. I hope that numpy.power does it with 4. -- To email me, substitute nowhere->spamcop, invalid->net. From zapwireDASHgroups at yahoo.com Wed Aug 25 14:36:07 2010 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 25 Aug 2010 11:36:07 -0700 Subject: Can PySerial's write method be called by multiple threads? Message-ID: I have a multi-threaded application where several of the threads need to write to a serial port that's being handled by pySerial. If pySerial thread-safe in the sense that pySerial.write behaves atomically? I.e., if thread 1 executes, serport.write("Hello, world!") and thread 2 executes serport.write("All your bases are belong to us!"), is it guaranteed that the output over the serial port won't "mix" the two together (e.g., "Hello All your bases are belong to us!, world!") ? I looked at the source code, and the write method eventually boils down to calling an the OS's "write" function, which presumably ends up being a call to a C function. Given the global interpreter lock -- and particularly how C functions can't be interrupted by the Python interpreter at all -- it sure seems as though everything is copacetic here? If not I can just add a queue and have everything go through it, but of course I'd like to avoid the extra code and CPU cycles if it isn't at all necessary. Thank you, ---Joel Koltner From thomas at jollybox.de Wed Aug 25 14:54:36 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 25 Aug 2010 20:54:36 +0200 Subject: Can PySerial's write method be called by multiple threads? In-Reply-To: References: Message-ID: <201008252054.37377.thomas@jollybox.de> On Wednesday 25 August 2010, it occurred to Joel Koltner to exclaim: > I have a multi-threaded application where several of the threads need to > write to a serial port that's being handled by pySerial. If pySerial > thread-safe in the sense that pySerial.write behaves atomically? I.e., if > thread 1 executes, serport.write("Hello, world!") and thread 2 executes > serport.write("All your bases are belong to us!"), is it guaranteed that > the output over the serial port won't "mix" the two together (e.g., "Hello > All your bases are belong to us!, world!") ? > > I looked at the source code, and the write method eventually boils down to > calling an the OS's "write" function, which presumably ends up being a call > to a C function. Given the global interpreter lock -- and particularly > how C functions can't be interrupted by the Python interpreter at all -- > it sure seems as though everything is copacetic here? I expect that it gives away the GIL to call the resident write() function, to allow other threads to run while it's sitting there, blocking. I haven't looked at the code, so maybe it doesn't hand over the GIL, but if it doesn't, I'd consider that a bug rather than a feature: the GIL shouldn't be abused as some kind of local mutex, and only gets in the way anyway. Speaking of the GIL, you shouldn't rely on it being there. Ever. It's a necessary evil, or it appears to be necessary. but nobody likes it and if somebody finds a good way to kick it out then that will happen. (That happens to be an explicit exception from the language moratorium, so it's not just my own personal wishful thinking) > > If not I can just add a queue and have everything go through it, but of > course I'd like to avoid the extra code and CPU cycles if it isn't at all > necessary. From python at mrabarnett.plus.com Wed Aug 25 15:02:21 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 25 Aug 2010 20:02:21 +0100 Subject: Can PySerial's write method be called by multiple threads? In-Reply-To: References: Message-ID: <4C7568BD.3040400@mrabarnett.plus.com> On 25/08/2010 19:36, Joel Koltner wrote: > I have a multi-threaded application where several of the threads need to > write to a serial port that's being handled by pySerial. If pySerial > thread-safe in the sense that pySerial.write behaves atomically? I.e., > if thread 1 executes, serport.write("Hello, world!") and thread 2 > executes serport.write("All your bases are belong to us!"), is it > guaranteed that the output over the serial port won't "mix" the two > together (e.g., "Hello All your bases are belong to us!, world!") ? > > I looked at the source code, and the write method eventually boils down > to calling an the OS's "write" function, which presumably ends up being > a call to a C function. Given the global interpreter lock -- and > particularly how C functions can't be interrupted by the Python > interpreter at all -- it sure seems as though everything is copacetic here? > Don't assume that just because it calls a C function the GIL won't be released. I/O calls which can take a relatively long time to complete often release the GIL. > If not I can just add a queue and have everything go through it, but of > course I'd like to avoid the extra code and CPU cycles if it isn't at > all necessary. > Unless I know that something is definitely thread-safe, that would be the way I would go. From zapwireDASHgroups at yahoo.com Wed Aug 25 15:02:27 2010 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 25 Aug 2010 12:02:27 -0700 Subject: Can PySerial's write method be called by multiple threads? References: Message-ID: <8Nddo.61739$MG3.56239@en-nntp-16.dc1.easynews.com> "Thomas Jollans" wrote in message news:mailman.36.1282762569.29448.python-list at python.org... > I expect that it gives away the GIL to call the resident write() function, > to > allow other threads to run while it's sitting there, blocking. I haven't > looked at the code, so maybe it doesn't hand over the GIL, but if it > doesn't, > I'd consider that a bug rather than a feature: the GIL shouldn't be abused > as > some kind of local mutex, and only gets in the way anyway. Ah, I expect you're correct. I'm still largely a Python newbie, and only know enough about things like the GIL to get myself into trouble. > Speaking of the GIL, you shouldn't rely on it being there. Ever. It's a > necessary evil, or it appears to be necessary. but nobody likes it and if > somebody finds a good way to kick it out then that will happen. OK, but presumably I can't know whether or not someone who wrote a library like pySerial relied on it or not. Although I suppose this is really a documentation bug -- pySerial's documentation doesn't talk about multi-threaded access directly, although their "minicom" example does demonstrate it in action. Thanks for the help, ---Joel From jedmeltzer at gmail.com Wed Aug 25 15:46:25 2010 From: jedmeltzer at gmail.com (Jed) Date: Wed, 25 Aug 2010 12:46:25 -0700 (PDT) Subject: split string into multi-character "letters" Message-ID: Hi, I'm seeking help with a fairly simple string processing task. I've simplified what I'm actually doing into a hypothetical equivalent. Suppose I want to take a word in Spanish, and divide it into individual letters. The problem is that there are a few 2-character combinations that are considered single letters in Spanish - for example 'ch', 'll', 'rr'. Suppose I have: alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include the whole alphabet but I shortened it here theword = 'churro' I would like to split the string 'churro' into a list containing: 'ch','u','rr','o' So at each letter I want to look ahead and see if it can be combined with the next letter to make a single 'letter' of the Spanish alphabet. I think this could be done with a regular expression passing the list called "alphabet" to re.match() for example, but I'm not sure how to use the contents of a whole list as a search string in a regular expression, or if it's even possible. My real application is a bit more complex than the Spanish alphabet so I'm looking for a fairly general solution. Thanks, Jed From nagle at animats.com Wed Aug 25 15:54:00 2010 From: nagle at animats.com (John Nagle) Date: Wed, 25 Aug 2010 12:54:00 -0700 Subject: Declare self.cursor In-Reply-To: References: Message-ID: <4c7574e6$0$1655$742ec2ed@news.sonic.net> On 8/24/2010 10:15 AM, Dani Valverde wrote: > Hello! > I am working on a GUI to connect to a MySQL database using MySQLdb (code > in attached file). I define the cursor in lines 55-66 in the OnLogin > function within the LoginDlg class. > > /db= MySQLdb.connect(host='localhost', user=Username , passwd=pwd, > db='Ornithobase') > self.cursor = db.cursor()/ > > When I try to use the cursor on another part of the code (EditUser > class, line 176) > > /sql = 'select substring_index(CURRENT_USER(),"@",1)' > login.cursor.execute(sql)/ > > I get this error: > > /AttributeError: 'LoginDlg' object has no attribute 'cursor'/ > > You can check the code for details, I think is better. > Cheers! > > Dani > self.cursor = db.cursor() ... self.Destroy() # probably clears the object Also, it's generally better to hold on to the database handle and get a cursor from it as a local variable when needed. You need the database handle for "db.commit()", at least. Getting a cursor is fast. (Actually, in MySQL, there is only one cursor.) I realize it's a desktop application, but still: db= MySQLdb.connect(host='localhost', user='root' , passwd='acrsci00', db='Ornithobase') From john.passaniti at gmail.com Wed Aug 25 15:56:06 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Wed, 25 Aug 2010 12:56:06 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> Message-ID: <81e52218-b72c-4b7c-aed6-82e040803064@s9g2000yqd.googlegroups.com> On Aug 24, 8:00?pm, Hugh Aguilar wrote: > The C programmers reading this are likely wondering why I'm being > attacked. The reason is that Elizabeth Rather has made it clear to > everybody that this is what she wants: [http://tinyurl.com/2bjwp7q] Hello to those outside of comp.lang.forth, where Hugh usually leaves his slime trail. I seriously doubt many people will bother to read the message thread Hugh references, but if you do, you'll get to delight in the same nonsense Hugh has brought to comp.lang.forth. Here's the compressed version: 1. Hugh references code ("symtab") that he wrote (in Factor) to manage symbol tables. 2. I (and others) did some basic analysis and found it to be a poor algorithm-- both in terms of memory use and performance-- especially compared to the usual solutions (hash tables, splay trees, etc.). 3. I stated that symtab sucked for the intended application. 4. Hugh didn't like that I called his baby ugly and decided to expose his bigotry. 5. Elizabeth Rather said she didn't appreciate Hugh's bigotry in the newsgroup. Yep, that's it. What Hugh is banking on is that you won't read the message thread, and that you'll blindly accept that Elizabeth is some terrible ogre with a vendetta against Hugh. The humor here is that Hugh himself provides a URL that disproves that! So yes, if you care, do read the message thread. It won't take long for you to get a clear impression of Hugh's character. From nagle at animats.com Wed Aug 25 16:01:01 2010 From: nagle at animats.com (John Nagle) Date: Wed, 25 Aug 2010 13:01:01 -0700 Subject: Can PySerial's write method be called by multiple threads? In-Reply-To: References: Message-ID: <4c75768a$0$1608$742ec2ed@news.sonic.net> On 8/25/2010 11:36 AM, Joel Koltner wrote: > I have a multi-threaded application where several of the threads need to > write to a serial port that's being handled by pySerial. If pySerial > thread-safe in the sense that pySerial.write behaves atomically? I.e., > if thread 1 executes, serport.write("Hello, world!") and thread 2 > executes serport.write("All your bases are belong to us!"), is it > guaranteed that the output over the serial port won't "mix" the two > together (e.g., "Hello All your bases are belong to us!, world!") ? You're not guaranteed that one Python "write" maps to one OS-level "write". Individual "print" statements in Python are not atomic. You don't need a queue, though; just use your own "write" function with a lock. import threading lok = threading.Lock() def atomicwrite(fd, data) : with lok : fd.write(data) John Nagle From jpiitula at ling.helsinki.fi Wed Aug 25 16:05:39 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 25 Aug 2010 23:05:39 +0300 Subject: split string into multi-character "letters" References: Message-ID: Jed writes: > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would > include the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' All non-overlapping matches, each as long as can be, and '.' catches single characters by default: >>> import re >>> re.findall('ch|ll|rr|.', 'churro') ['ch', 'u', 'rr', 'o'] From vlastimil.brom at gmail.com Wed Aug 25 16:08:19 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Wed, 25 Aug 2010 22:08:19 +0200 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: 2010/8/25 Jed : > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. ?The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. ?I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. ?My real application > is a bit more complex than the Spanish alphabet so I'm looking for a > fairly general solution. > Thanks, > Jed > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I am not sure, whether it can be generalised enough for your needs, but you can try something like >>> re.findall(r"rr|ll|ch|[a-z]", "asdasdallasdrrcvb") ['a', 's', 'd', 'a', 's', 'd', 'a', 'll', 'a', 's', 'd', 'rr', 'c', 'v', 'b'] of course, the pattern should be adjusted precisely in order not to loose characters... hth, vbr From python at mrabarnett.plus.com Wed Aug 25 16:10:11 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 25 Aug 2010 21:10:11 +0100 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: <4C7578A3.2080603@mrabarnett.plus.com> On 25/08/2010 20:46, Jed wrote: > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. My real application > is a bit more complex than the Spanish alphabet so I'm looking for a > fairly general solution. You can build a regex with: >>> '|'.join(alphabet) 'a|b|c|ch|d|u|r|rr|o' You want to try to match, say, 'ch' before 'c', so you want the longest first: >>> '|'.join(sorted(alphabet, key=len, reverse=True)) 'ch|rr|a|b|c|d|u|r|o' If you were going to match the Spanish alphabet then I would recommend that you do it in Unicode. Well, any text that's not pure ASCII should be done in Unicode! From thomas at jollybox.de Wed Aug 25 16:16:52 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Wed, 25 Aug 2010 22:16:52 +0200 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: <201008252216.53347.thomas@jollybox.de> On Wednesday 25 August 2010, it occurred to Jed to exclaim: > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. My real application > is a bit more complex than the Spanish alphabet so I'm looking for a > fairly general solution. A very simple solution that might be general enough: >>> def tokensplit(string, bits): ... while string: ... for b in bits: ... if string.startswith(b): ... yield b ... string = string[len(b):] ... break ... else: ... raise ValueError("string not composed of the right bits.") ... >>> >>> alphabet = ['a','b','c','ch','d','u','r','rr','o'] >>> # move longer letters to the front >>> alphabet.sort(key=len, reverse=True) >>> >>> list(tokensplit("churro", alphabet)) ['ch', 'u', 'rr', 'o'] >>> From python.list at tim.thechases.com Wed Aug 25 16:17:54 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 25 Aug 2010 15:17:54 -0500 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: <4C757A72.7020404@tim.thechases.com> On 08/25/10 14:46, Jed wrote: > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. My first attempt at the problem: >>> import re >>> special = ['ch', 'rr', 'll'] >>> r = re.compile(r'(?:%s)|[a-z]' % ('|'.join(re.escape(c) for c in special)), re.I) >>> r.findall('churro') ['ch', 'u', 'rr', 'o'] >>> [r.findall(word) for word in 'churro lorenzo caballo'.split()] [['ch', 'u', 'rr', 'o'], ['l', 'o', 'r', 'e', 'n', 'z', 'o'], ['c', 'a', 'b', 'a', 'll', 'o']] This joins escaped versions of all your special characters. Due to the sequential nature used by Python's re module to handle "|" or-branching, the paired versions get tested (and found) before proceeding to the single-letters. -tkc From zapwireDASHgroups at yahoo.com Wed Aug 25 16:24:52 2010 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 25 Aug 2010 13:24:52 -0700 Subject: Can PySerial's write method be called by multiple threads? References: <4c75768a$0$1608$742ec2ed@news.sonic.net> Message-ID: Hi John, "John Nagle" wrote in message news:4c75768a$0$1608$742ec2ed at news.sonic.net... > You don't need a queue, though; just use your own "write" function > with a lock. Hmm... that would certainly work. I suppose it's even more efficient than a queue in that the first thing the queue is going to do is to acquire a lock; thanks for the idea! > def atomicwrite(fd, data) : > with lok : > fd.write(data) Cool, I didn't know that threading.Lock() supported "with!" -- Just the other day I was contemplating how one might go about duplicating the pattern in C++ where you do something like this: { Lock lok; // Constructor acquires lock, will be held until destructor called (i.e., while lok remains in scope) DoSomething(); } // Lock released ...clearly "with" does the job here. ---Joel From alex.kapps at web.de Wed Aug 25 16:26:53 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Wed, 25 Aug 2010 22:26:53 +0200 Subject: split string into multi-character "letters" In-Reply-To: References: Message-ID: <4C757C8D.3040208@web.de> Jed wrote: > Hi, I'm seeking help with a fairly simple string processing task. > I've simplified what I'm actually doing into a hypothetical > equivalent. > Suppose I want to take a word in Spanish, and divide it into > individual letters. The problem is that there are a few 2-character > combinations that are considered single letters in Spanish - for > example 'ch', 'll', 'rr'. > Suppose I have: > > alphabet = ['a','b','c','ch','d','u','r','rr','o'] #this would include > the whole alphabet but I shortened it here > theword = 'churro' > > I would like to split the string 'churro' into a list containing: > > 'ch','u','rr','o' > > So at each letter I want to look ahead and see if it can be combined > with the next letter to make a single 'letter' of the Spanish > alphabet. I think this could be done with a regular expression > passing the list called "alphabet" to re.match() for example, but I'm > not sure how to use the contents of a whole list as a search string in > a regular expression, or if it's even possible. My real application > is a bit more complex than the Spanish alphabet so I'm looking for a > fairly general solution. > Thanks, > Jed I don't know the Spanish alphabet, and you didn't say in what way your real application is more complex, but maybe something like this could be a starter: In [13]: import re In [14]: theword = 'churro' In [15]: two_chars=["ch", "rr"] In [16]: re.findall('|'.join(two_chars)+"|[a-z]", theword) Out[16]: ['ch', 'u', 'rr', 'o'] From john.passaniti at gmail.com Wed Aug 25 16:44:46 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Wed, 25 Aug 2010 13:44:46 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> Message-ID: <471f4b3f-5a95-432b-8d4b-4d18d0855f6c@h19g2000yqb.googlegroups.com> On Aug 24, 9:05?pm, Hugh Aguilar wrote: > What about using what I learned to write programs that work? > Does that count for anything? It obviously counts, but it's not the only thing that matters. Where I'm employed, I am currently managing a set of code that "works" but the quality of that code is poor. The previous programmer suffered from a bad case of cut-and-paste programming mixed with a unsophisticated use of the language. The result is that this code that "works" is a maintenance nightmare, has poor performance, wastes memory, and is very brittle. The high level of coupling between code means that when you change virtually anything, it invariably breaks something else. And then you have the issue of the programmer thinking the code "works" but it doesn't actually meet the needs of the customer. The same code I'm talking about has a feature where you can pass message over the network and have the value you pass configure a parameter. It "works" fine, but it's not what the customer wants. The customer wants to be able to bump the value up and down, not set it to an absolute value. So does the code "work"? Depends on the definition of "work." In my experience, there are a class of software developers who care only that their code "works" (or more likely, *appears* to work) and think that is the gold standard. It's an attitude that easy for hobbyists to take, but not one that serious professionals can afford to have. A hobbyist can freely spend hours hacking away and having a grand time writing code. Professionals are paid for their efforts, and that means that *someone* is spending both time and money on the effort. A professional who cares only about slamming out code that "works" is invariably merely moving the cost of maintaining and extending the code to someone else. It becomes a hidden cost, but why do they care... it isn't here and now, and probably won't be their problem. > If I don't have a professor to pat me on the back, will my > programs stop working? What a low bar you set for yourself. Does efficiency, clarity, maintainability, extensibility, and elegance not matter to you? From joshuamaurice at gmail.com Wed Aug 25 17:01:49 2010 From: joshuamaurice at gmail.com (Joshua Maurice) Date: Wed, 25 Aug 2010 14:01:49 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> <471f4b3f-5a95-432b-8d4b-4d18d0855f6c@h19g2000yqb.googlegroups.com> Message-ID: <1bc3a400-1631-454b-bdd6-54a58e172fd4@f20g2000pro.googlegroups.com> On Aug 25, 1:44?pm, John Passaniti wrote: > On Aug 24, 9:05?pm, Hugh Aguilar wrote: > > > What about using what I learned to write programs that work? > > Does that count for anything? > > It obviously counts, but it's not the only thing that matters. ?Where > I'm employed, I am currently managing a set of code that "works" but > the quality of that code is poor. ?The previous programmer suffered > from a bad case of cut-and-paste programming mixed with a > unsophisticated use of the language. ?The result is that this code > that "works" is a maintenance nightmare, has poor performance, wastes > memory, and is very brittle. ?The high level of coupling between code > means that when you change virtually anything, it invariably breaks > something else. > > And then you have the issue of the programmer thinking the code > "works" but it doesn't actually meet the needs of the customer. ?The > same code I'm talking about has a feature where you can pass message > over the network and have the value you pass configure a parameter. > It "works" fine, but it's not what the customer wants. ?The customer > wants to be able to bump the value up and down, not set it to an > absolute value. ?So does the code "work"? ?Depends on the definition > of "work." > > In my experience, there are a class of software developers who care > only that their code "works" (or more likely, *appears* to work) and > think that is the gold standard. ?It's an attitude that easy for > hobbyists to take, but not one that serious professionals can afford > to have. ?A hobbyist can freely spend hours hacking away and having a > grand time writing code. ?Professionals are paid for their efforts, > and that means that *someone* is spending both time and money on the > effort. ?A professional who cares only about slamming out code that > "works" is invariably merely moving the cost of maintaining and > extending the code to someone else. ?It becomes a hidden cost, but why > do they care... it isn't here and now, and probably won't be their > problem. I agree. Sadly, with managers, especially non-technical managers, it's hard to make this case when the weasel guy says "See! It's working.". From davea at ieee.org Wed Aug 25 17:05:27 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 25 Aug 2010 17:05:27 -0400 Subject: speed of numpy.power()? In-Reply-To: <8dl2r2F5h4U1@mid.individual.net> References: <4222a7dd-03ea-4466-a96c-1fd445d7e3d0@t2g2000yqe.googlegroups.com> <8dl2r2F5h4U1@mid.individual.net> Message-ID: <4C758597.2040507@ieee.org> Peter Pearson wrote: > On Wed, 25 Aug 2010 06:59:36 -0700 (PDT), Carlos Grohmann wrote: > > > >> I'd like to hear from you on the benefits of using numpy.power(x,y) >> over (x*x*x*x..) >> >> > > Using the "dis" package under Python 2.5, I see that > computing x_to_the_16 = x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x uses > 15 multiplies. I hope that numpy.power does it with 4. > > Right. Square/multiply algorithm takes something like 2*(log2(y)) multiplies worst case. That should not only be faster, but quite likely more accurate, at least for non-integer x values and large enough integer y. DaveA From rosswilliamson.spt at gmail.com Wed Aug 25 17:18:15 2010 From: rosswilliamson.spt at gmail.com (Ross Williamson) Date: Wed, 25 Aug 2010 16:18:15 -0500 Subject: Overload print Message-ID: Hi All Is there anyway in a class to overload the print function? >> class foo_class(): >> pass >> cc = foo_class() >> print cc Gives: <__main__.foo_class instance at ....> Can I do something like: >> class foo_class(): >> def __print__(self): >> print "hello" >> cc = foo_class() >> print cc Gives: hello I'm looking at finding nice way to print variables in a class just by asking to print it Cheers Ross -- Ross Williamson University of Chicago Department of Astronomy & Astrophysics 773-834-9785 (office) 312-504-3051 (Cell) From john at castleamber.com Wed Aug 25 17:19:33 2010 From: john at castleamber.com (John Bokma) Date: Wed, 25 Aug 2010 16:19:33 -0500 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <00f109a1-379a-4bf0-a6c0-b0d6310e6693@f42g2000yqn.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> <81e52218-b72c-4b7c-aed6-82e040803064@s9g2000yqd.googlegroups.com> Message-ID: <87pqx6z8yi.fsf@castleamber.com> John Passaniti writes: > On Aug 24, 8:00?pm, Hugh Aguilar wrote: >> The C programmers reading this are likely wondering why I'm being >> attacked. The reason is that Elizabeth Rather has made it clear to >> everybody that this is what she wants: [http://tinyurl.com/2bjwp7q] > > Hello to those outside of comp.lang.forth, where Hugh usually leaves > his slime trail. I seriously doubt many people will bother to read > the message thread Hugh references, but if you do, you'll get to > delight in the same nonsense Hugh has brought to comp.lang.forth. > Here's the compressed version: I did :-). I have somewhat followed Forth from a far, far distance since the 80's (including hardware), and did read several messages in the thread, also since it was not clear what Hugh was referring to. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From zondo42 at gmail.com Wed Aug 25 17:23:41 2010 From: zondo42 at gmail.com (Glenn Hutchings) Date: Wed, 25 Aug 2010 14:23:41 -0700 (PDT) Subject: Overload print References: mailman.44.1282771124.29448.python-list@python.org Message-ID: <3aa21cb0-1787-47f9-b674-d79c3632b92d@q22g2000yqm.googlegroups.com> On 25 Aug, 22:18, Ross Williamson wrote: > Is there anyway in a class to overload the print function? > > >> class foo_class(): > >> ? ? ?pass > >> cc = foo_class() > >> print cc > > Gives: > > <__main__.foo_class instance at ....> > > Can I do something like: > > >> class foo_class(): > >> ? ? def __print__(self): > >> ? ? ? ? ? print "hello" > >> cc = foo_class() > >> print cc > > Gives: > > hello Yes. Just define the __str__ method, like this: class foo_class(): def __str__(self): return "hello" From chris at rebertia.com Wed Aug 25 17:32:25 2010 From: chris at rebertia.com (Chris Rebert) Date: Wed, 25 Aug 2010 14:32:25 -0700 Subject: Overload print In-Reply-To: References: Message-ID: On Wed, Aug 25, 2010 at 2:18 PM, Ross Williamson wrote: > Hi All > > Is there anyway in a class to overload the print function? > >>> class foo_class(): >>> ? ? ?pass > >>> cc = foo_class() >>> print cc > > Gives: > > <__main__.foo_class instance at ....> > > Can I do something like: > >>> class foo_class(): >>> ? ? def __print__(self): >>> ? ? ? ? ? print "hello" > >>> cc = foo_class() >>> print cc > > Gives: > > hello > > I'm looking at finding nice way to print variables in a class just by > asking to print it You want to overload the __str__() method: http://docs.python.org/reference/datamodel.html#object.__str__ Cheers, Chris -- http://blog.rebertia.com From darcy at druid.net Wed Aug 25 17:39:58 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 25 Aug 2010 17:39:58 -0400 Subject: Overload print In-Reply-To: References: Message-ID: <20100825173958.c3c5f63f.darcy@druid.net> On Wed, 25 Aug 2010 16:18:15 -0500 Ross Williamson wrote: > Hi All > > Is there anyway in a class to overload the print function? Your terminology threw me off for a moment. You don't want to override print. You want to override the default representation of an object. > > >> class foo_class(): > >> pass > > >> cc = foo_class() > >> print cc > > Gives: > > <__main__.foo_class instance at ....> That's the default representation. > Can I do something like: > > >> class foo_class(): > >> def __print__(self): > >> print "hello" Close. Check this. >>> class foo_class(): ... def __repr__(self): ... return "hello" ... >>> x = foo_class() >>> x hello -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From alex.kapps at web.de Wed Aug 25 17:42:42 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Wed, 25 Aug 2010 23:42:42 +0200 Subject: Overload print In-Reply-To: References: Message-ID: <4C758E52.3090107@web.de> Ross Williamson wrote: > Hi All > > Is there anyway in a class to overload the print function? In Python <= 2.x "print" is a statement and thus can't be "overloaded". That's exactly the reason, why Python 3 has turned "print" into a function. >>> class foo_class(): >>> def __print__(self): >>> print "hello" > >>> cc = foo_class() >>> print cc > > Gives: > > hello Hmm, on what Python version are you? To my knowledge there is no __print__ special method. Did you mean __str__ or __repr__ ? > I'm looking at finding nice way to print variables in a class just by > asking to print it In Python3 you *can* overload print(), but still, you better define __str__() on your class to return a string, representing what ever you want: In [11]: class Foo(object): ....: def __str__(self): ....: return "foo" ....: ....: In [12]: f = Foo() In [13]: print f foo From ckaynor at zindagigames.com Wed Aug 25 17:43:51 2010 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 25 Aug 2010 14:43:51 -0700 Subject: Overload print In-Reply-To: <3aa21cb0-1787-47f9-b674-d79c3632b92d@q22g2000yqm.googlegroups.com> References: <3aa21cb0-1787-47f9-b674-d79c3632b92d@q22g2000yqm.googlegroups.com> Message-ID: On Wed, Aug 25, 2010 at 2:23 PM, Glenn Hutchings wrote: > On 25 Aug, 22:18, Ross Williamson > wrote: > > Is there anyway in a class to overload the print function? > > > > >> class foo_class(): > > >> pass > > >> cc = foo_class() > > >> print cc > > > > Gives: > > > > <__main__.foo_class instance at ....> > > > > Can I do something like: > > > > >> class foo_class(): > > >> def __print__(self): > > >> print "hello" > > >> cc = foo_class() > > >> print cc > > > > Gives: > > > > hello > > Yes. Just define the __str__ method, like this: > > class foo_class(): > def __str__(self): > return "hello" > -- > http://mail.python.org/mailman/listinfo/python-list > I'd recommend looking at both the __str__ and __repr__ functions at http://docs.python.org/reference/datamodel.html. Depending on your specific use case, its possible __repr__ may be perfered for you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rda.selin at gmail.com Wed Aug 25 17:57:33 2010 From: rda.selin at gmail.com (becky_s) Date: Wed, 25 Aug 2010 14:57:33 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) Message-ID: All, I?m having a problem with the matplotlib.pyplot.contourf function. I have a 1-D array of latitudes (mesolat), a 1-D array of longitudes (mesolon), and a 1-D array of rainfall values (rain) at those corresponding lat, lon points. After importing the necessary libraries, and reading in these 1-D arrays, I do the following commands: p = Basemap(projection='lcc',llcrnrlon=-108.173,llcrnrlat=26.809999, urcrnrlon=-81.944664,urcrnrlat=45.730892, lon_0=-97.00, lat_0=37.00, resolution='i') px,py = p(mesolon, mesolat) prplvls = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] crain = p.contourf(px,py,rain,prplvls) At this point the contourf function returns an error saying ?Input z must be a 2D array.? However, based on the documentation (http:// matplotlib.sourceforge.net/api/ pyplot_api.html#matplotlib.pyplot.contourf) I thought that as long as px, py, and rain are the same dimensions, everything should be fine. Apparently that is not the case? If 1D arrays are not allowed in contourf, then how can I change my data into a 2D array? Thanks in advance for the help. From rda.selin at gmail.com Wed Aug 25 18:17:43 2010 From: rda.selin at gmail.com (becky_s) Date: Wed, 25 Aug 2010 15:17:43 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) References: Message-ID: <2a415d82-c631-42ad-a96d-917d0b3ee17f@d8g2000yqf.googlegroups.com> On Aug 25, 4:57?pm, becky_s wrote: > All, > > I?m having a problem with the matplotlib.pyplot.contourf function. ?I > have a 1-D array of latitudes (mesolat), a 1-D array of longitudes > (mesolon), and a 1-D array of rainfall values (rain) at those > corresponding lat, lon points. ?After importing the necessary > libraries, and reading in these 1-D arrays, I do the following > commands: > > p = Basemap(projection='lcc',llcrnrlon=-108.173,llcrnrlat=26.809999, > ? ? ? ? ? ? urcrnrlon=-81.944664,urcrnrlat=45.730892, > ? ? ? ? ? ? lon_0=-97.00, lat_0=37.00, resolution='i') > > px,py = p(mesolon, mesolat) > > prplvls = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] > > crain = p.contourf(px,py,rain,prplvls) > > At this point the contourf function returns an error saying ?Input z > must be a 2D array.? ?However, based on the documentation (http:// > matplotlib.sourceforge.net/api/ > pyplot_api.html#matplotlib.pyplot.contourf) I thought that as long as > px, py, and rain are the same dimensions, everything should be fine. > Apparently that is not the case? ?If 1D arrays are not allowed in > contourf, then how can I change my data into a 2D array? > > Thanks in advance for the help. I neglected to mention that these are masked arrays, due to some missing data. I tried using numpy.griddata: mesolati = np.linspace(33.8,37.0,150) mesoloni = np.linspace(-94.5,-102.9,150) raini = griddata(mesolon,mesolat,rain,mesoloni,mesolati) but the raini array returned was entirely masked (no values). Thanks again, Becky From john.passaniti at gmail.com Wed Aug 25 19:01:07 2010 From: john.passaniti at gmail.com (John Passaniti) Date: Wed, 25 Aug 2010 16:01:07 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> <471f4b3f-5a95-432b-8d4b-4d18d0855f6c@h19g2000yqb.googlegroups.com> <1bc3a400-1631-454b-bdd6-54a58e172fd4@f20g2000pro.googlegroups.com> Message-ID: <22c66313-bf7c-4999-9d3e-02d9695fdc38@x21g2000yqa.googlegroups.com> On Aug 25, 5:01?pm, Joshua Maurice wrote: > I agree. Sadly, with managers, especially non-technical > managers, it's hard to make this case when the weasel > guy says "See! It's working.". Actually, it's not that hard. The key to communicating the true cost of software development to non-technical managers (and even some technical ones!) is to express the cost in terms of a metaphor they can understand. Non-technical managers may not understand the technology or details of software development, but they can probably understand money. So finding a metaphor along those lines can help them to understand. http://c2.com/cgi/wiki?WardExplainsDebtMetaphor I've found that explaining the need to improve design and code quality in terms of a debt metaphor usually helps non-technical managers have a very real, very concrete understanding of the problem. For example, telling a non-technical manager that a piece of code is poorly written and needs to be refactored may not resonate with them. To them, the code "works" and isn't that the only thing that matters? But put in terms of a debt metaphor, it becomes easier for them to see the problem. From nanothermite911fbibustards at gmail.com Wed Aug 25 19:44:12 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 16:44:12 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria - Re: GERMAN GIRLS HOT SEX VIDEOS. - I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post References: <968e144b-b230-4b60-ae2a-f3c1dc2f8573@v6g2000prd.googlegroups.com> Message-ID: <78f2b6a1-8c0f-42c0-9461-9c7e5d7d7003@q1g2000yqg.googlegroups.com> I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post ///////////////////////////////////////////////////////////////////////////////////// CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxk http://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news : http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA -- http://mail.python.org/mailman/listinfo/python-list I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post On Aug 14, 6:07?am, Hot Hot wrote: > GERMAN GIRLS ?HOT SEX VIDEOS Athttp://simpletoget.co.cc > > Due to high sex content, i have hidden the videos in an image.in that > website on Right side ?below search box click on image and watch > videos in all angles. From joshuamaurice at gmail.com Wed Aug 25 20:06:38 2010 From: joshuamaurice at gmail.com (Joshua Maurice) Date: Wed, 25 Aug 2010 17:06:38 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <7xhbijo8bv.fsf@ruckus.brouhaha.com> <02aef2f4-68f2-45a9-80c1-b95389065df3@a36g2000yqc.googlegroups.com> <471f4b3f-5a95-432b-8d4b-4d18d0855f6c@h19g2000yqb.googlegroups.com> <1bc3a400-1631-454b-bdd6-54a58e172fd4@f20g2000pro.googlegroups.com> <22c66313-bf7c-4999-9d3e-02d9695fdc38@x21g2000yqa.googlegroups.com> Message-ID: <59dafb50-0c98-4bdc-915e-fc99501d3399@u31g2000pru.googlegroups.com> On Aug 25, 4:01?pm, John Passaniti wrote: > On Aug 25, 5:01?pm, Joshua Maurice wrote: > > > I agree. Sadly, with managers, especially non-technical > > managers, it's hard to make this case when the weasel > > guy says "See! It's working.". > > Actually, it's not that hard. ?The key to communicating the true cost > of software development to non-technical managers (and even some > technical ones!) is to express the cost in terms of a metaphor they > can understand. ?Non-technical managers may not understand the > technology or details of software development, but they can probably > understand money. ?So finding a metaphor along those lines can help > them to understand. > > http://c2.com/cgi/wiki?WardExplainsDebtMetaphor > > I've found that explaining the need to improve design and code quality > in terms of a debt metaphor usually helps non-technical managers have > a very real, very concrete understanding of the problem. ?For example, > telling a non-technical manager that a piece of code is poorly written > and needs to be refactored may not resonate with them. ?To them, the > code "works" and isn't that the only thing that matters? ?But put in > terms of a debt metaphor, it becomes easier for them to see the > problem. But then it becomes a game of "How bad is this code exactly?" and "How much technical debt have we accrued?". At least in my company's culture, it is quite hard. From tjreedy at udel.edu Wed Aug 25 20:15:31 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Aug 2010 20:15:31 -0400 Subject: split string into multi-character "letters" In-Reply-To: <4C757A72.7020404@tim.thechases.com> References: <4C757A72.7020404@tim.thechases.com> Message-ID: > On 08/25/10 14:46, Jed wrote: >> I would like to split the string 'churro' into a list containing: >> >> 'ch','u','rr','o' Dirt simple, straightforward, easily generalized solution: def sp_split(s): n,i,ret = len(s), 0, [] while i < n: s2 = s[i:i+2] if s2 in ('ch', 'll', 'rr'): ret.append(s2) i += 2 else: ret.append(s[i]) i += 1 return ret print(sp_split('churro')) #'ch', 'u', 'rr', 'o'] -- Terry Jan Reedy From skippy.hammond at gmail.com Wed Aug 25 21:08:11 2010 From: skippy.hammond at gmail.com (Mark Hammond) Date: Thu, 26 Aug 2010 11:08:11 +1000 Subject: Newbie: Win32 COM problem In-Reply-To: References: Message-ID: <4C75BE7B.1030305@gmail.com> On 25/08/2010 10:33 PM, Paul Hemans wrote: > File "C:\development\PyXLS\pyXLS.py", line 13, in createSheet > def createBook(self): > AttributeError: WrapXLS instance has no attribute '_book' > pythoncom error: Python error invoking COM method. > > Can anyone help? That line seems an unlikely source of the error. Note that as win32com uses an in-process model by default, your problem may be that you changed your implementation but didn't restart the hosting process - and therefore are still using an earlier implementation. HTH, Mark From darwin at nowhere.com Wed Aug 25 22:17:40 2010 From: darwin at nowhere.com (Paul Hemans) Date: Thu, 26 Aug 2010 12:17:40 +1000 Subject: Newbie: Win32 COM problem References: Message-ID: Yes, that was it. I just needed to restart the host process. Thanks "Mark Hammond" wrote in message news:mailman.51.1282784920.29448.python-list at python.org... > On 25/08/2010 10:33 PM, Paul Hemans wrote: >> File "C:\development\PyXLS\pyXLS.py", line 13, in createSheet >> def createBook(self): >> AttributeError: WrapXLS instance has no attribute '_book' >> pythoncom error: Python error invoking COM method. >> >> Can anyone help? > > That line seems an unlikely source of the error. Note that as win32com > uses an in-process model by default, your problem may be that you changed > your implementation but didn't restart the hosting process - and therefore > are still using an earlier implementation. > > HTH, > > Mark From nanothermite911fbibustards at gmail.com Wed Aug 25 23:11:14 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 20:11:14 -0700 (PDT) Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - Re: GERMAN GIRLS HOT SEX VIDEOS. - I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post References: <968e144b-b230-4b60-ae2a-f3c1dc2f8573@v6g2000prd.googlegroups.com> Message-ID: I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post ///////////////////////////////////////////////////////////////////////////?////////// CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist Bustard who The girl was a German like the one Roman Polansky raped, Semantha Geimer http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ Look at his face, what criminal race is he ? What goes around comes around !!! Former Marine convicted in North Carolina of killing female colleague By the CNN Wire Staff August 23, 2010 8:33 p.m. EDT For more on this story, read the coverage from CNN affiliate WRAL. (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North Carolina on Monday of first degree murder in the 2007 death of Lance Cpl. Maria Lauterbach, who was eight months pregnant when she died. An autopsy showed that Lauterbach, 20, died of blunt force trauma to the head. Police unearthed her charred body from beneath a barbecue pit in Laurean's backyard in January 2008. She had disappeared the month before. Laurean, who was dressed in black slacks and wore a white shirt and black tie, did not show any emotion as the judge read his sentence of life in prison without parole. He either said or mouthed something to someone in the audience of the courtroom before he was led out in handcuffs, video showed. Laurean and Lauterbach were stationed together at Camp Lejeune, North Carolina. North Carolina prosecutors alleged Laurean killed Lauterbach on December 14 and used her ATM card 10 days later before fleeing to Mexico.Laurean was arrested there in April 2008. He holds dual citizenship in the United States and Mexico. Before her death, Lauterbach told the Marines that Laurean had raped her. Laurean denied it, and disappeared just a few weeks before a scheduled rape hearing at Camp LeJeune. The DNA of Lauterbach's unborn child did not match that of Laurean, according to law enforcement personnel. Authorities found Lauterbach's body after Laurean's wife, Christina, produced a note her husband had written claiming the 20-year-old woman slit her own throat during an argument, according to officials. Although a gaping 4-inch wound was found on the left side of Lauterbach's neck, autopsy results indicated that the wound itself would not have been fatal and may have occurred after death. Asked by a Mexican reporter at the time of his arrest whether he killed Lauterbach, Laurean replied, "I loved her." Laurean's lawyer said his client would appeal the decision. ///////////////////////////////////////////////////////////////// The MARINE BASTARD will probably claim INSANITY ........ ////////////////////// The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE is UNACCEPTABLE. ===== http://www.youtube.com/watch?v=lX18zUp6WPY http://www.youtube.com/watch?v=XQapkVCx1HI http://www.youtube.com/watch?v=tXJ-k-iOg0M Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ? Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did you release the 5 dancing Israelis compromising the whole 911 investigation ? If the Dubai Police can catch Mossad Murderers and put the videos and Iranian Police can why cant you put the Pentagon Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and puting on INTERNATIONAL MEDIA a day after catching him without TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did you have to LIE about Dr Afiya Siddiqui and torture that Innocent little mother of 3 and smashing the skull of her one child ? http://www.youtube.com/watch?v=DhMcii8smxkhttp://www.youtube.com/watch?v=0SZ2lxDJmdg There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian courts. FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but only because he was a white. They got away with MURDER of thousands of Non-whites in all parts of the world. Daily 911 news :http://911blogger.com http://www.youtube.com/watch?v=tRfhUezbKLw http://www.youtube.com/watch?v=x7kGZ3XPEm4 http://www.youtube.com/watch?v=lX18zUp6WPY Conclusion : FBI bustards are RACIST and INcompetent. They could neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they cover them up - whichever was their actual goal or task. SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across tbe board, esp the whites/jew on the top. FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and UNPATRIOTIC Act FBI bustards failed to prevent ROMAN POLANSKY from absconding to europe and rapes. FBI bustards failed to prevent OKLAHOMA --http://mail.python.org/mailman/listinfo/python-list I dont think the JEW COMPANY GOOGLE will delete your post, but it will delete my post On Aug 14, 6:07 am, Hot Hot wrote: > GERMAN GIRLS HOT SEX VIDEOS Athttp://simpletoget.co.cc > Due to high sex content, i have hidden the videos in an image.in that > website on Right side below search box click on image and watch > videos in all angles.- Hide quoted text - From nanothermite911fbibustards at gmail.com Thu Aug 26 00:22:31 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Wed, 25 Aug 2010 21:22:31 -0700 (PDT) Subject: OBAMA created by the CIA - Proofs by Wayne Madsen, the Investigative Journalist - Obama's StepMother Ruth Niedesand and two StepBrothers are JEW References: <0f2ba00f-2589-44fb-acb6-ea8b693677b7@d8g2000yqf.googlegroups.com> <87aaoaxtyu.fsf@kuiper.lan.informatimago.com> <4c75e310$0$7111$607ed4bc@cv.net> Message-ID: <01c5fea9-264f-48ff-b076-5d3b459fd6c5@t20g2000yqa.googlegroups.com> OBAMA created by the CIA - Proofs by Wayne Madsen, the Investigative Journalist - Obama's StepMother Ruth Niedesand and two StepBrothers are JEW OBAMA family are CIA agents or employees http://www.presstv.ir/detail/140093.html http://www.voltairenet.org/article166741.html Special Report The Story of Obama: All in The Company (Part I) by Wayne Madsen* Investigative journalist Wayne Madsen has discovered CIA files that document the agency?s connections to institutions and individuals figuring prominently in the lives of Barack Obama and his mother, father, grandmother, and stepfather. The first part of his report highlights the connections between Barack Obama, Sr. and the CIA- sponsored operations in Kenya to counter rising Soviet and Chinese influence among student circles and, beyond, to create conditions obstructing the emergence of independent African leaders. -------------------------------------------------------------------------------- 20 August 2010 From Washington D.C. (USA) Themes AfriCom: Control of Africa Biographies Barack Obama In 1983-84, Barack Obama worked as Editor at Business Internation Corporation, a Business International Corporation, a known CIA front company. President Obama?s own work in 1983 for Business International Corporation, a CIA front that conducted seminars with the world?s most powerful leaders and used journalists as agents abroad, dovetails with CIA espionage activities conducted by his mother, Stanley Ann Dunham in 1960s post-coup Indonesia on behalf of a number of CIA front operations, including the East-West Center at the University of Hawaii, the U.S. Agency for International Development (USAID), and the Ford Foundation. Dunham met and married Lolo Soetoro, Obama?s stepfather, at the East-West Center in 1965. Soetoro was recalled to Indonesia in 1965 to serve as a senior army officer and assist General Suharto and the CIA in the bloody overthrow of President Sukarno. Barack Obama, Sr., who met Dunham in 1959 in a Russian language class at the University of Hawaii, had been part of what was described as an airlift of 280 East African students to the United States to attend various colleges ? merely ?aided? by a grant from the Joseph P. Kennedy Foundation, according to a September 12, 1960, Reuters report from London. The airlift was a CIA operation to train and indoctrinate future agents of influence in Africa, which was becoming a battleground between the United States and the Soviet Union and China for influence among newly-independent and soon-to-be independent countries on the continent. The airlift was condemned by the deputy leader of the opposition Kenyan African Democratic Union (KADU) as favoring certain tribes ? the majority Kikuyus and minority Luos ? over other tribes to favor the Kenyan African National Union (KANU), whose leader was Tom Mboya, the Kenyan nationalist and labor leader who selected Obama, Sr. for a scholarship at the University of Hawaii. Obama, Sr., who was already married with an infant son and pregnant wife in Kenya, married Dunham on Maui on February 2, 1961 and was also the university?s first African student. Dunham was three month?s pregnant with Barack Obama, Jr. at the time of her marriage to Obama, Sr. KADU deputy leader Masinda Muliro, according to Reuters, said KADU would send a delegation to the United States to investigate Kenyan students who received ?gifts? from the Americans and ?ensure that further gifts to Kenyan students are administered by people genuinely interested in Kenya?s development.?? The CIA allegedly recruited Tom M?Boya in a heavily funded "selective liberation" programme to isolate Kenya?s founding President Jomo Kenyatta, whom the American spy agency labelled as "unsafe." Mboya received a $100,000 grant for the airlift from the Kennedy Foundation after he turned down the same offer from the U.S. State Department, obviously concerned that direct U.S. assistance would look suspicious to pro-Communist Kenyan politicians who suspected Mboya of having CIA ties. The Airlift Africa project was underwritten by the Kennedy Foundation and the African-American Students Foundation. Obama, Sr. was not on the first airlift but a subsequent one. The airlift, organized by Mboya in 1959, included students from Kenya, Uganda, Tanganyika, Zanzibar, Northern Rhodesia, Southern Rhodesia, and Nyasaland. Reuters also reported that Muliro charged that Africans were ?disturbed and embittered? by the airlift of the selected students. Muliro ?stated that ?preferences were shown to two major tribes [Kikuyu and Luo] and many U.S.-bound students had failed preliminary and common entrance examinations, while some of those left behind held first-class certificates.? CIA-airlifted to Hawaii, Barack Obama Sr., with leis, stands with Stanley Dunham, President Obama?s grandfather, on his right. Obama, Sr. was a friend of Mboya and a fellow Luo. After Mboya was assassinated in 1969, Obama, Sr. testified at the trial of his alleged assassin. Obama, Sr. claimed he was the target of a hit-and-run assassination attempt after his testimony. Obama, Sr., who left Hawaii for Harvard in 1962, divorced Dunham in 1964. Obama, Sr. married a fellow Harvard student, Ruth Niedesand, a Jewish-American woman, who moved with him to Kenya and had two sons. They were later divorced. Obama, Sr. worked for the Kenyan Finance and Transport ministries as well as an oil firm. Obama, Sr. died in a 1982 car crash and his funeral was attended by leading Kenyan politicians, including future Foreign Minister Robert Ouko, who was murdered in 1990. CIA files indicate that Mboya was an important agent-of-influence for the CIA, not only in Kenya but in all of Africa. A formerly Secret CIA Current Intelligence Weekly Summary, dated November 19, 1959, states that Mboya served as a check on extremists at the second All-African People?s Conference (AAPC) in Tunis. The report states that ?serious friction developed between Ghana?s Prime Minister Kwame Nkrumah and Kenyan nationalist Tom Mboya who cooperated effectively last December to check extremists at the AAPC?s first meeting in Accra.? The term ?cooperated effectively? appears to indicate that Mboya was cooperating with the CIA, which filed the report from field operatives in Accra and Tunis. While ?cooperating? with the CIA in Accra and Tunis, Mboya selected the father of the president of the United States to receive a scholarship and be airlifted to the University of Hawaii where he met and married President Obama?s mother. An earlier CIA Current Intelligence Weekly Summary, secret, and dated April 3, 1958, states that Mboya ?still appears to be the most promising of the African leaders.? Another CIA weekly summary, secret and dated December 18, 1958, calls Mboya the Kenyan nationalist an ?able and dynamic young chairman? of the People?s Convention party who was viewed as an opponent of ?extremists? like Nkrumah, supported by ?Sino-Soviet representatives.? In a formerly Secret CIA report on the All-Africa Peoples Conference in 1961, dated November 1, 1961, Mboya?s conservatism, along with that of Taleb Slim of Tunisia, are contrasted to the leftist policies of Nkrumah and others. Pro-communists who were elected to the AAPC?s steering committee at the March 1961 Cairo conference, attended by Mboya, are identified in the report as Abdoulaye Diallo, AAPC Secretary General, of Senegal; Ahmed Bourmendjel of Algeria; Mario de Andrade of Angola; Ntau Mokhele of Basutoland; Kingue Abel of Cameroun; Antoine Kiwewa of Congo (Leopoldville); Kojo Botsio of Ghana; Ismail Toure of Guinea; T. O. Dosomu Johnson of Liberia; Modibo Diallo of Mali; Mahjoub Ben Seddik of Morocco; Djibo Bakari of Niger; Tunji Otegbeya of Nigeria; Kanyama Chiume of Nyasaland; Ali Abdullahi of Somalia; Tennyson Makiwane of South Africa, and Mohamed Fouad Galal of the United Arab Republic. The only attendees in Cairo who were given a clean bill of health by the CIA were Mboya, who appears to have been a snitch for the agency, and Joshua Nkomo of Southern Rhodesia, B. Munanka of Tanganyika, Abdel Magid Shaker of Tunisia, and John Kakonge of Uganda. Nkrumah would eventually be overthrown in a 1966 CIA-backed coup while he was on a state visit to China and North Vietnam. The CIA overthrow of Nkrumah followed by one year the agency?s overthrow of Sukarno, another coup that was connected to President Obama?s family on his mother?s side. There are suspicions that Mboya was assassinated in 1969 by Chinese agents working with anti-Mboya factions in the government of Kenyan President Jomo Kenyatta in order to eliminate a pro-U.S. leading political leader in Africa. Upon Mboya?s death, every embassy in Nairobi flew its flag at half-mast except for one, the embassy of the People?s Republic of China. Jomo Kenyatta, first President of Kenya. Mboya?s influence in the Kenyatta government would continue long after his death and while Obama, Sr. was still alive. In 1975, after the assassination of KANU politician Josiah Kariuki, a socialist who helped start KANU, along with Mboya and Obama, Sr., Kenyatta dismissed three rebellious cabinet ministers who ?all had personal ties to either Kariuki or Tom Mboya.? This information is contained in CIA Staff Notes on the Middle East, Africa, and South Asia, formerly Top Secret Umbra, Handle via COMINT Channels, dated June 24, 1975. The intelligence in the report, based on its classification, indicate the information was derived from National Security Agency intercepts in Kenya. No one was ever charged in the assassination of Kariuki. The intecepts of Mboya?s and Kariuki?s associates are an indication that the NSA and CIA also maintain intercepts on Barack Obama, Sr., who, as a non-U.S. person, would have been lawfully subject at the time to intercepts carried out by NSA and Britain?s Government Communications Headquarters (GCHQ). (To be continued) == Article concerning Barack Obama?s own meddling in Kenya?s domestic affairs: "Behind the 2009 Nobel Peace Prize", by Thierry Meyssan, Voltaire Network, 19 October 2009. From python.koda at gmail.com Thu Aug 26 00:29:28 2010 From: python.koda at gmail.com (Alban Nona) Date: Thu, 26 Aug 2010 00:29:28 -0400 Subject: Path / Listing and os.walk problem. Message-ID: Hi So here is my problem: I have my render files that are into a directory like this: c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0001.exr c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0002.exr c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0003.exr .... c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0001.exr c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0002.exr c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0003.exr True is, there is like 1000 Files is the directory (C:\log\renderfiles\) What Iam looking to is to extract the first part of the filenames as a list, but I dont want the script to extract it 1000times, I mean I dont need it to extract HPO7_SEQ004_031_VDM_AMB 150 times, because there is 150 Frames. (not sure if its clear tought) so far, I would like the list to look lik: ["HPO7_SEQ004_031_VDM_DIF", "HPO7_SEQ004_031_VDM_AMB", etc...] I start to think about that, to try to use a for (path, dirs, files) in os.walk(path): list.append(files) but this kind of thing will just append the whole 1000 files, thing that I dont want, and more complicated I dont want the thing after "AMB" or "DIF" in the name files to follow. (thing I can delete using a split, if I read well ?) I trying to search on internet for answer, but seems I find nothing about it. Someone can help me with that please, show me the way or something ? Thank you ! :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Aug 26 03:54:13 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Aug 2010 09:54:13 +0200 Subject: Path / Listing and os.walk problem. References: Message-ID: Alban Nona wrote: > Hi > > So here is my problem: > > I have my render files that are into a directory like this: > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0001.exr > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0002.exr > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0003.exr > .... > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0001.exr > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0002.exr > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0003.exr > > True is, there is like 1000 Files is the directory (C:\log\renderfiles\) > > What Iam looking to is to extract the first part of the filenames as a > list, but I dont want the script to extract it 1000times, I mean I dont > need it to extract HPO7_SEQ004_031_VDM_AMB 150 times, because there is 150 > Frames. (not sure if its clear tought) > > so far, I would like the list to look lik: > > ["HPO7_SEQ004_031_VDM_DIF", "HPO7_SEQ004_031_VDM_AMB", etc...] > > > I start to think about that, to try to use a > > for (path, dirs, files) in os.walk(path): > list.append(files) > > > but this kind of thing will just append the whole 1000 files, thing that I > dont want, and more complicated I dont want the thing after "AMB" or "DIF" > in the name files to follow. > (thing I can delete using a split, if I read well ?) > > > I trying to search on internet for answer, but seems I find nothing about > it. > Someone can help me with that please, show me the way or something ? You can use glob. Assuming the files are all in one directory: import os import glob folder = r"C:\log\renderfiles" # find files that end with "_V001.0001.exr" pattern = os.path.join(folder, "*_V001.0001.exr") files = glob.glob(pattern) # remove the directory names = [os.path.basename(f) for f in files] # remove everything after and including the last occurence of "_" names = [n.rpartition("_")[0] for n in names] print "\n".join(sorted(names)) Peter From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 26 04:19:25 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 26 Aug 2010 10:19:25 +0200 Subject: Iterative vs. Recursive coding In-Reply-To: References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com><4c6dcbc5$0$11111$c3e8da3@news.astraweb.com><4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> Message-ID: <4c762382$0$20848$426a34cc@news.free.fr> BartC a ?crit : > "Steven D'Aprano" wrote in > message news:4c6f8edd$0$28653$c3e8da3 at news.astraweb.com... >> On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: > >>> I onced worked in a shop (Win32 desktop / accouting applications mainly) >>> where I was the only guy that could actually understand recursion. FWIW, >>> I also was the only guy around that understood "hairy" (lol) concepts >>> like callback functions, FSM, polymorphism, hashtables, linked lists, >>> ADTs, algorithm complexity etc... >> >> >> Was there anything they *did* understand, or did they just bang on the >> keyboard at random until the code compiled? *wink* > > You underestimate how much programming (of applications) can be done > without needing any of this stuff. From personal experience : almost nothing worth being maintained. I'm talking about complex domain-specific applications here - not shell scripts or todo-lists. >>> Needless to say, I didn't last long !-) >> >> And rightly so :) > > I guess they wanted code that could be maintained by anybody. The code base was an unmaintainable, undecip?erable mess loaded with global state (litteraly *hundreds* of global variables), duplication, dead code, and enough WTF to supply thedailywtf.com for years - to make a long story short, the perfect BigBallOfMudd. FWIW, the company didn't last long neither - they just kept on introducing ten new bugs each time they "fixed" one. From navkirats at gmail.com Thu Aug 26 04:35:16 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 26 Aug 2010 14:05:16 +0530 Subject: Webcam support Message-ID: <2E90C179-B58D-44E6-9779-FA072BF220C5@gmail.com> Hi Guys, I am programming a web centric app in python for customer, which needs to click a snap of the customer and forward the pic to the server via POST. I am not very familiar with how I can achieve this. Any direction would be much appreciated. Regards, Nav From sathish at solitontech.com Thu Aug 26 05:59:47 2010 From: sathish at solitontech.com (Sathish S) Date: Thu, 26 Aug 2010 15:29:47 +0530 Subject: Python Editor or IDE ActiveX control Message-ID: Hi Ppl, Is there any python IDE or editor that has an ActiveX control which could be embed in other Windows applications. I'm basically looking to write a application that can show the indentations of python, change the color of keywords etc on a application, which will save this python script and run it from command prompt. Thanks, Sathish -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Thu Aug 26 06:34:30 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 26 Aug 2010 03:34:30 -0700 Subject: Webcam support In-Reply-To: <2E90C179-B58D-44E6-9779-FA072BF220C5@gmail.com> References: <2E90C179-B58D-44E6-9779-FA072BF220C5@gmail.com> Message-ID: On Thu, Aug 26, 2010 at 1:35 AM, Navkirat Singh wrote: > Hi Guys, > > I am programming a web centric app in python for customer, which needs to click a snap of the customer and forward the pic to the server via POST. I am not very familiar with how I can achieve this. Any direction would be much appreciated. I think Flash (*shudder*) has some sort of webcam API. Cheers, Chris -- http://blog.rebertia.com From richie8105 at gmail.com Thu Aug 26 07:02:35 2010 From: richie8105 at gmail.com (richie05 bal) Date: Thu, 26 Aug 2010 04:02:35 -0700 (PDT) Subject: seach for pattern based on string References: <6054e266-4730-411e-9a27-9b501e6086cd@j8g2000yqd.googlegroups.com> Message-ID: <673b629a-9072-44a8-aa8a-970ac4c84711@l20g2000yqm.googlegroups.com> On Aug 24, 11:05?pm, Alex Willmer wrote: > On Aug 24, 5:33?pm, richie05 bal wrote: > > > i am starting to learn python and I am stuck with query I want to > > generate with python > > File looks something like this > > TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, > > publishingCompanyId 7} > > TRACE: AddNewBookD {bookId 21, noofBooks 6577, authorId 42, > > publishingCompanyId 8} > > > I want to first search for AddNewBookD > > if found > > ? ?store bookId, noofBooks, authorId and publishingCompanyId > > > I know how to search for only AddNewBookD or find the pattern bookId > > 20, noofBooks 6576, authorId 41, publishingCompanyId 7 but I don't > > know how search one based on another. > > Using a regular expression I would perform a match against each line. > If the match fails, it will return None. If the match succeeds it > returns a match object with which you can extract the values > > >>> import re > >>> pattern = re.compile(r'TRACE: AddNewBookD \{bookId (\d+), noofBooks (\d+), authorId (\d+), publishingCompanyId (\d+)\}\s*') > >>> s = '''TRACE: AddNewBookD {bookId 20, noofBooks 6576, authorId 41, publishingCompanyId 7} ''' > >>> pattern.match(s) > > <_sre.SRE_Match object at 0xa362f40> # If the match failed this would > be None>>> m = pattern.match(s) > >>> m.groups() > > ('20', '6576', '41', '7') > > > > So your code to store the result would be inside an if m: block > > HTH, Alex thanks Alex. exactly what i was looking for. From stephan0h at yahoo.de Thu Aug 26 07:16:51 2010 From: stephan0h at yahoo.de (steph) Date: Thu, 26 Aug 2010 04:16:51 -0700 (PDT) Subject: pil and reportlab: image compression Message-ID: <0e89301b-2cb3-42fe-ba24-4018b5343c4d@v41g2000yqv.googlegroups.com> Hi group, I've written a small application that puts images into a pdf document. It works ok, but my problem is that the pdf-files become quite huge, bigger than the original jpegs. The problem seems to arise because I use PIL to resize the pictures - and the images seem to get uncompressed in the process. Unfortunately I have not found a way to compress them again before rendering them to the pdf. Any clues? Thanks, Stephan From jeeva235 at hotmail.com Thu Aug 26 07:36:19 2010 From: jeeva235 at hotmail.com (superman) Date: Thu, 26 Aug 2010 04:36:19 -0700 (PDT) Subject: HOW TO MAKE $2000 IN YOUR WEEKEND NO INVESTMENT Message-ID: HOW TO MAKE $2000 IN YOUR WEEKEND NO INVESTMENT Great way to earn $$$ from online. Earn $100 everyday from online part time jobs. Last week i have earned $800 from this money making network. It is a free money making network Lot of people earn more than $2000 p/m from this network. Just join this network and start working today & Get paid to your bank account http://alturl.com/z9cz7 EARN AWESOME EARNINGS FROM ONLINE From chris at simplistix.co.uk Thu Aug 26 08:51:15 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 26 Aug 2010 13:51:15 +0100 Subject: bug? pkgutil.walk_packages returns packages that result in an ImportError Message-ID: <4C766343.1080908@simplistix.co.uk> Hi All, From the docs of pkgutils.walk_packages: """ 'onerror' is a function which gets called with one argument (the name of the package which was being imported) if any exception occurs while trying to import a package. If no onerror function is supplied, ImportErrors are caught and ignored, while all other exceptions are propagated, terminating the search. """ My expectation of this is that if onerrors is left as None, names yielded will be importable. However, because the yield is before the import check, you can get packages returned that are not importable. This feels at odds with the docs above and I think is a bug. If the yield were dropped to befoer the import check, we wouldn't have this problem. what do others think? cheers, Chris From rda.selin at gmail.com Thu Aug 26 08:58:14 2010 From: rda.selin at gmail.com (becky_s) Date: Thu, 26 Aug 2010 05:58:14 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) References: Message-ID: <2aa0205a-bb19-4265-a0ac-cd87445b7e0e@i13g2000yqd.googlegroups.com> On Aug 26, 1:52?am, Dennis Lee Bieber wrote: > On Wed, 25 Aug 2010 14:57:33 -0700 (PDT), becky_s > declaimed the following in gmane.comp.python.general: > > > > > px,py = p(mesolon, mesolat) > > ? ? ? ? For my elucidation, what does that ? ? ?p(x,y) ?actually do? Especially > as you appear to expect the result to be split into separate x and y > afterwards? I can't find it defined in either matplotlib nor numpy. p was declared as a basemap object in the previous statement, which sets up a map projection. Calling p(mesolon, mesolat) converts those lons, lats to units in that map projection and stores them in px,py. (See http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html for more info on basemap.) > > > pyplot_api.html#matplotlib.pyplot.contourf) I thought that as long as > > px, py, and rain are the same dimensions, everything should be fine. > > ? ? ? ? And are they? You don't demonstrate that you've checked for that I did a simple print px.shape, rain.shape, etc. to check. They are all size (135,). > > > Apparently that is not the case? ?If 1D arrays are not allowed in > > contourf, then how can I change my data into a 2D array? > > ? ? ? ? Also note (jumping to your follow up) that contourf is described as > having a potential problem with masked arrays (whatever those are) for > "Z" My problem isn't with the masked arrays as much as it is with rain being a 1D array. IDL can handle contouring 1D arrays with missing variables lickety-split, so I was really hoping Python could as well. Also, numpy.ma is the masked array library. See http://docs.scipy.org/doc/numpy/reference/routines.ma.html. From rda.selin at gmail.com Thu Aug 26 08:58:14 2010 From: rda.selin at gmail.com (becky_s) Date: Thu, 26 Aug 2010 05:58:14 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) References: Message-ID: <2aa0205a-bb19-4265-a0ac-cd87445b7e0e@i13g2000yqd.googlegroups.com> On Aug 26, 1:52?am, Dennis Lee Bieber wrote: > On Wed, 25 Aug 2010 14:57:33 -0700 (PDT), becky_s > declaimed the following in gmane.comp.python.general: > > > > > px,py = p(mesolon, mesolat) > > ? ? ? ? For my elucidation, what does that ? ? ?p(x,y) ?actually do? Especially > as you appear to expect the result to be split into separate x and y > afterwards? I can't find it defined in either matplotlib nor numpy. p was declared as a basemap object in the previous statement, which sets up a map projection. Calling p(mesolon, mesolat) converts those lons, lats to units in that map projection and stores them in px,py. (See http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html for more info on basemap.) > > > pyplot_api.html#matplotlib.pyplot.contourf) I thought that as long as > > px, py, and rain are the same dimensions, everything should be fine. > > ? ? ? ? And are they? You don't demonstrate that you've checked for that I did a simple print px.shape, rain.shape, etc. to check. They are all size (135,). > > > Apparently that is not the case? ?If 1D arrays are not allowed in > > contourf, then how can I change my data into a 2D array? > > ? ? ? ? Also note (jumping to your follow up) that contourf is described as > having a potential problem with masked arrays (whatever those are) for > "Z" My problem isn't with the masked arrays as much as it is with rain being a 1D array. IDL can handle contouring 1D arrays with missing variables lickety-split, so I was really hoping Python could as well. Also, numpy.ma is the masked array library. See http://docs.scipy.org/doc/numpy/reference/routines.ma.html. From __peter__ at web.de Thu Aug 26 09:29:33 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Aug 2010 15:29:33 +0200 Subject: bug? pkgutil.walk_packages returns packages that result in an ImportError References: Message-ID: Chris Withers wrote: > From the docs of pkgutils.walk_packages: > """ > 'onerror' is a function which gets called with one argument (the > name of the package which was being imported) if any exception > occurs while trying to import a package. If no onerror function is > supplied, ImportErrors are caught and ignored, while all other > exceptions are propagated, terminating the search. > """ > > My expectation of this is that if onerrors is left as None, names > yielded will be importable. I would infer no such promise, especially as the generator also yields modules, and no attempt at all is made to import those. > However, because the yield is before the import check, you can get > packages returned that are not importable. > > This feels at odds with the docs above and I think is a bug. > > If the yield were dropped to befoer the import check, we wouldn't have > this problem. > > what do others think? I've never worked with that function; I'd like to hear more about your usecase. Peter From john at castleamber.com Thu Aug 26 10:32:47 2010 From: john at castleamber.com (John Bokma) Date: Thu, 26 Aug 2010 09:32:47 -0500 Subject: Iterative vs. Recursive coding References: <71e72427-7604-4286-b119-08ba669e9240@f42g2000yqn.googlegroups.com> <4c6dcbc5$0$11111$c3e8da3@news.astraweb.com> <4c6e9de9$0$23142$426a74cc@news.free.fr> <4c6f8edd$0$28653$c3e8da3@news.astraweb.com> <4c762382$0$20848$426a34cc@news.free.fr> Message-ID: <87zkw9bg1c.fsf@castleamber.com> Bruno Desthuilliers writes: > BartC a ?crit : >> "Steven D'Aprano" wrote in >> message news:4c6f8edd$0$28653$c3e8da3 at news.astraweb.com... >>> On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote: >> >>>> I onced worked in a shop (Win32 desktop / accouting applications mainly) >>>> where I was the only guy that could actually understand recursion. FWIW, >>>> I also was the only guy around that understood "hairy" (lol) concepts >>>> like callback functions, FSM, polymorphism, hashtables, linked lists, >>>> ADTs, algorithm complexity etc... >>> >>> >>> Was there anything they *did* understand, or did they just bang on the >>> keyboard at random until the code compiled? *wink* >> >> You underestimate how much programming (of applications) can be done >> without needing any of this stuff. > > From personal experience : almost nothing worth being maintained. I'm > talking about complex domain-specific applications here - not shell > scripts or todo-lists. I doubt anyone who codes like that keeps a todo-list. >>>> Needless to say, I didn't last long !-) >>> >>> And rightly so :) >> >> I guess they wanted code that could be maintained by anybody. > > The code base was an unmaintainable, undecip?erable mess loaded with > global state (litteraly *hundreds* of global variables), duplication, > dead code, and enough WTF to supply thedailywtf.com for years - to > make a long story short, the perfect BigBallOfMudd. FWIW, the company > didn't last long neither - they just kept on introducing ten new bugs > each time they "fixed" one. and they forgot to sell that as new features, I guess :-D. -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From python.koda at gmail.com Thu Aug 26 10:35:27 2010 From: python.koda at gmail.com (Alban Nona) Date: Thu, 26 Aug 2010 10:35:27 -0400 Subject: Path / Listing and os.walk problem. In-Reply-To: References: Message-ID: Hey ! Thank you guys ! It help me a lot ! @Dennis (Gomes): Thanks ! I tried it it worked well but list me the whole files :P (and finally crashed python...lol) I looked at the Peter method and, Im really dumb to didnt tough about defining a pattern like *_v001.0001.exr * like this, it sort me only one frame...which is perfect and less memory consuming I guess. And glob use seems to be perfect for what I want to do ! so thank you to point me in this direction :p I tried also the Peter code, and it give me a good listing of my element like I wanted: HPO7_SEQ004_031_VDMRoom_ALB HPO7_SEQ004_031_VDMRoom_AMB HPO7_SEQ004_031_VDMRoom_BTY HPO7_SEQ004_031_VDMRoom_Cutouts_ALB HPO7_SEQ004_031_VDMRoom_Cutouts_AMB HPO7_SEQ004_031_VDMRoom_Cutouts_DET .... HPO7_SEQ004_031_VDMRoom_DET HPO7_SEQ004_031_VDMRoom_DIF HPO7_SEQ004_031_VDMRoom_DPF HPO7_SEQ004_031_VDMRoom_Decals_ALB .... HPO7_SEQ004_031_VDM_ALB HPO7_SEQ004_031_VDM_AMB HPO7_SEQ004_031_VDM_BTY HPO7_SEQ004_031_VDM_DIF HPO7_SEQ004_031_VDM_DPF HPO7_SEQ004_031_VDM_Fresnel_mat Unfortunatly, a new problem come to me, I looking to get that kind of list: HPO7_SEQ004_031_VDMRoom HPO7_SEQ004_031_VDMRoom HPO7_SEQ004_031_VDMRoom HPO7_SEQ004_031_VDMRoom_Cutouts HPO7_SEQ004_031_VDMRoom_Cutouts HPO7_SEQ004_031_VDMRoom_Cutouts .... Right now, Im looking the documentation to find a way to do it, Im thinking about string methods, I also though: " hey, I just have to delete the 4 last characters, but na ! itll not work because sometime I have something like "_Fresnel_mat'' which is of course more than 4 chars...) Maybe the best would be to declare something like "in the string, look at the last "_" and delete it + whatever there is after" but I didnt find how to do it, I mean I tried splitext which is, not appropriate. Do I have to declare a list of element like: elementList: ["_ALB", "AMB", "_Beauty", etc...] and to search that pattern in the files name to remove it after ? it seems not bad as solution, but I pretty sure there is a better way to do it. right ? anyway, thank very much guys ! :) and have a good day ! 2010/8/26 Peter Otten <__peter__ at web.de> > Alban Nona wrote: > > > Hi > > > > So here is my problem: > > > > I have my render files that are into a directory like this: > > > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0001.exr > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0002.exr > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0003.exr > > .... > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0001.exr > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0002.exr > > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0003.exr > > > > True is, there is like 1000 Files is the directory (C:\log\renderfiles\) > > > > What Iam looking to is to extract the first part of the filenames as a > > list, but I dont want the script to extract it 1000times, I mean I dont > > need it to extract HPO7_SEQ004_031_VDM_AMB 150 times, because there is > 150 > > Frames. (not sure if its clear tought) > > > > so far, I would like the list to look lik: > > > > ["HPO7_SEQ004_031_VDM_DIF", "HPO7_SEQ004_031_VDM_AMB", etc...] > > > > > > I start to think about that, to try to use a > > > > for (path, dirs, files) in os.walk(path): > > list.append(files) > > > > > > but this kind of thing will just append the whole 1000 files, thing that > I > > dont want, and more complicated I dont want the thing after "AMB" or > "DIF" > > in the name files to follow. > > (thing I can delete using a split, if I read well ?) > > > > > > I trying to search on internet for answer, but seems I find nothing about > > it. > > Someone can help me with that please, show me the way or something ? > > You can use glob. Assuming the files are all in one directory: > > import os > import glob > > folder = r"C:\log\renderfiles" > > # find files that end with "_V001.0001.exr" > pattern = os.path.join(folder, "*_V001.0001.exr") > files = glob.glob(pattern) > > # remove the directory > names = [os.path.basename(f) for f in files] > > # remove everything after and including the last occurence of "_" > names = [n.rpartition("_")[0] for n in names] > > print "\n".join(sorted(names)) > > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nanothermite911fbibustards at gmail.com Thu Aug 26 11:56:12 2010 From: nanothermite911fbibustards at gmail.com (nanothermite911fbibustards) Date: Thu, 26 Aug 2010 08:56:12 -0700 (PDT) Subject: JEW BUSTARDS , MOSSAD BUSTARDS , CIA Bustards did 911 and bustards are afraid of truth, GOOGLE BUSTARDS do censorship and but not in CHINA to subvert it ... Re: GERMAN GIRLS HOT SEX VIDEOS. References: <968e144b-b230-4b60-ae2a-f3c1dc2f8573@v6g2000prd.googlegroups.com> Message-ID: On Aug 26, 1:31?am, nanothermite911fbibustards wrote: > On Aug 14, 6:07?am, Hot Hot wrote: > > > GERMAN GIRLS ?HOT SEX VIDEOS Athttp://simpletoget.co.cc > > > Due to high sex content, i have hidden the videos in an image.in that > > website on Right side ?below search box click on image and watch > > videos in all angles. > > I dont think the JEW COMPANY GOOGLE will delete your post, but it will > delete my post > ///////////////////////////////////////////////////////////////////////////??////////// > > CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria > Lauterbach and KILL THEM > > Is he a Jew or a white Anglo Saxon race ? or a Southern Baptist > Bustard who > > The girl was a German like the one Roman Polansky raped, Semantha > Geimer > > http://www.cnn.com/2010/CRIME/08/23/north.carolina.marine.murder/ > > Look at his face, what criminal race is he ? What goes around comes > around !!! > > Former Marine convicted in North Carolina of killing female colleague > By the CNN Wire Staff > August 23, 2010 8:33 p.m. EDT > > For more on this story, read the coverage from CNN affiliate WRAL. > > (CNN) -- Former U.S. Marine Cesar Laurean was convicted in North > Carolina on Monday of first degree murder in the 2007 death of Lance > Cpl. Maria Lauterbach, who was eight months pregnant when she died. > > An autopsy showed that Lauterbach, 20, died of blunt force trauma to > the head. Police unearthed her charred body from beneath a barbecue > pit in Laurean's backyard in January 2008. She had disappeared the > month before. > > Laurean, who was dressed in black slacks and wore a white shirt and > black tie, did not show any emotion as the judge read his sentence of > life in prison without parole. He either said or mouthed something to > someone in the audience of the courtroom before he was led out in > handcuffs, video showed. > > Laurean and Lauterbach were stationed together at Camp Lejeune, North > Carolina. > > North Carolina prosecutors alleged Laurean killed Lauterbach on > December 14 and used her ATM card 10 days later before fleeing to > Mexico.Laurean was arrested there in April 2008. He holds dual > citizenship in the United States and Mexico. > > Before her death, Lauterbach told the Marines that Laurean had raped > her. Laurean denied it, and disappeared just a few weeks before a > scheduled rape hearing at Camp LeJeune. > > The DNA of Lauterbach's unborn child did not match that of Laurean, > according to law enforcement personnel. > > Authorities found Lauterbach's body after Laurean's wife, Christina, > produced a note her husband had written claiming the 20-year-old > woman > slit her own throat during an argument, according to officials. > > Although a gaping 4-inch wound was found on the left side of > Lauterbach's neck, autopsy results indicated that the wound itself > would not have been fatal and may have occurred after death. > > Asked by a Mexican reporter at the time of his arrest whether he > killed Lauterbach, Laurean replied, "I loved her." > > Laurean's lawyer said his client would appeal the decision. > > ///////////////////////////////////////////////////////////////// > > The MARINE BASTARD will probably claim INSANITY ........ > > ////////////////////// > The FAT per DIEM FBI bustards use our TAX PAYER MONEY and > INCOMPETENCE > is UNACCEPTABLE. > > ===== > > http://www.youtube.com/watch?v=lX18zUp6WPY > > http://www.youtube.com/watch?v=XQapkVCx1HI > > http://www.youtube.com/watch?v=tXJ-k-iOg0M > > Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX > Mailer ? > Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did > you release the 5 dancing Israelis compromising the whole 911 > investigation ? If the Dubai Police can catch Mossad Murderers and > put > the videos and Iranian Police can why cant you put the Pentagon > Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and > puting on INTERNATIONAL MEDIA a day after catching him without > TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did > you have to LIE about Dr Afiya Siddiqui and torture that Innocent > little mother of 3 and smashing the skull of her one child ? > > http://www.youtube.com/watch?v=DhMcii8smxkhttp://www.youtube.com/watc... > > There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian > courts. > > FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but > only because he was a white. They got away with MURDER of thousands > of > Non-whites in all parts of the world. > > Daily 911 news :http://911blogger.com > > http://www.youtube.com/watch?v=tRfhUezbKLw > > http://www.youtube.com/watch?v=x7kGZ3XPEm4 > > http://www.youtube.com/watch?v=lX18zUp6WPY > > Conclusion : FBI bustards are RACIST and INcompetent. They could > neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they > cover them up - whichever was their actual goal or task. > > SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across > tbe board, esp the whites/jew on the top. > > FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST > and > UNPATRIOTIC Act > FBI bustards failed to prevent ROMAN POLANSKY from absconding to > europe and rapes. > FBI bustards failed to prevent OKLAHOMA > > --http://mail.python.org/mailman/listinfo/python-list > > I dont think the JEW COMPANY GOOGLE will delete your post, but it will > delete my post > > On Aug 14, 6:07 am, Hot Hot wrote: > > > > > GERMAN GIRLS ?HOT SEX VIDEOS Athttp://simpletoget.co.cc > > Due to high sex content, i have hidden the videos in an image.in that > > website on Right side ?below search box click on image and watch > > videos in all angles.- Hide quoted text -- Hide quoted text - > > - Show quoted text - From garabik-news-2005-05 at kassiopeia.juls.savba.sk Thu Aug 26 12:19:38 2010 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Thu, 26 Aug 2010 16:19:38 +0000 (UTC) Subject: Webcam support References: Message-ID: Navkirat Singh wrote: > Hi Guys, > > I am programming a web centric app in python for customer, which needs > to click a snap of the customer and forward the pic to the server via > POST. I am not very familiar with how I can achieve this. Any > direction would be much appreciated. > For something very similar, I used fswebcam, the crucial code looked like this: def capture_frame(filename, brightness=50): os.system('fswebcam -S 1 -r %s -s brightness=%i%% --font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf --jpeg 60 --save %s' % (RESOLUTION, brightness, filename)) -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread From navkirats at gmail.com Thu Aug 26 13:22:16 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 26 Aug 2010 22:52:16 +0530 Subject: Writing byte stream as jpeg format to disk Message-ID: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> Hey guys, I am programming a webserver, I receive a jpeg file with the POST method.The file (.jpeg) is encoded in bytes, I parse the bytes by decoding them to a string. I wanted to know how i could write the file (now a string) as a jpeg image on disk. When I try to encode the same string to a bytes and write them in binary format to disk, the file is not recognized as jpeg. I would be grateful if someone could help me with this. Regards, Nav From navkirats at gmail.com Thu Aug 26 13:23:50 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 26 Aug 2010 22:53:50 +0530 Subject: Webcam support In-Reply-To: References: Message-ID: <1B995359-7C7C-47E7-8360-9A629A9BFB7D@gmail.com> On 26-Aug-2010, at 9:49 PM, garabik-news-2005-05 at kassiopeia.juls.savba.sk wrote: > Navkirat Singh wrote: >> Hi Guys, >> >> I am programming a web centric app in python for customer, which needs >> to click a snap of the customer and forward the pic to the server via >> POST. I am not very familiar with how I can achieve this. Any >> direction would be much appreciated. >> > > For something very similar, I used fswebcam, the crucial code looked > like this: > > def capture_frame(filename, brightness=50): > os.system('fswebcam -S 1 -r %s -s brightness=%i%% > --font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf > --jpeg 60 --save %s' % (RESOLUTION, brightness, filename)) > > > -- > ----------------------------------------------------------- > | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | > | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | > ----------------------------------------------------------- > Antivirus alert: file .signature infected by signature virus. > Hi! I'm a signature virus! Copy me into your signature file to help me spread > -- > http://mail.python.org/mailman/listinfo/python-list Thanks guys, I stumbled upon jpegcam (javascript and flash library) which does this. It works awesome !! :) Regards From john at castleamber.com Thu Aug 26 13:31:07 2010 From: john at castleamber.com (John Bokma) Date: Thu, 26 Aug 2010 12:31:07 -0500 Subject: Writing byte stream as jpeg format to disk References: Message-ID: <874oeh2sdg.fsf@castleamber.com> Navkirat Singh writes: > Hey guys, > > I am programming a webserver, I receive a jpeg file with the POST > method.The file (.jpeg) is encoded in bytes, I parse the bytes by > decoding them to a string. Why? -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From navkirats at gmail.com Thu Aug 26 14:25:46 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Thu, 26 Aug 2010 23:55:46 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <874oeh2sdg.fsf@castleamber.com> References: <874oeh2sdg.fsf@castleamber.com> Message-ID: On 26-Aug-2010, at 11:01 PM, John Bokma wrote: > Navkirat Singh writes: > >> Hey guys, >> >> I am programming a webserver, I receive a jpeg file with the POST >> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >> decoding them to a string. > > Why? > > -- > John Bokma j3b > > Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma > Freelance Perl & Python Development: http://castleamber.com/ > -- > http://mail.python.org/mailman/listinfo/python-list why? I am not quite sure what you have not understood. From invalid at invalid.invalid Thu Aug 26 14:35:37 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 26 Aug 2010 18:35:37 +0000 (UTC) Subject: Writing byte stream as jpeg format to disk References: <874oeh2sdg.fsf@castleamber.com> Message-ID: On 2010-08-26, Navkirat Singh wrote: > > On 26-Aug-2010, at 11:01 PM, John Bokma wrote: > >> Navkirat Singh writes: >> >>> Hey guys, >>> >>> I am programming a webserver, I receive a jpeg file with the POST >>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>> decoding them to a string. >> >> Why? > > why? I am not quite sure what you have not understood. You're starting with JPEG data. If you want to write it to a file, then write it to a file. Whatever process you're describing as "I parse the bytes by decoding them to a string" is not needed and is apparently converting the JPEG data into something that's not JPEG data. -- Grant Edwards grant.b.edwards Yow! PARDON me, am I at speaking ENGLISH? gmail.com From sschwarzer at sschwarzer.net Thu Aug 26 14:37:44 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 26 Aug 2010 20:37:44 +0200 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: Message-ID: <4C76B478.1090700@sschwarzer.net> Hi Navkirat, On 2010-08-26 19:22, Navkirat Singh wrote: > I am programming a webserver, I receive a jpeg file with > the POST method.The file (.jpeg) is encoded in bytes, I > parse the bytes by decoding them to a string. I wanted to > know how i could write the file (now a string) as a jpeg > image on disk. When I try to encode the same string to a > bytes and write them in binary format to disk, the file is > not recognized as jpeg. I would be grateful if someone > could help me with this. I guess you mean you "see" a byte string in your server and want to write that to disk. Assuming the string you got is the correct image data in the first place, you can, in Python 2.x, write the string data to disk like this: fobj = open("some_image.jpg", "wb") fobj.write(byte_string) fobj.close() Note that you should use "wb" as mode to write as binary. Otherwise you'll get automatic line ending conversion (at least on Windows) which will give the result you describe. If my answer doesn't help, you probably need to describe in more detail what you're doing, including showing some real code. Stefan From python.koda at gmail.com Thu Aug 26 14:41:49 2010 From: python.koda at gmail.com (Alban Nona) Date: Thu, 26 Aug 2010 14:41:49 -0400 Subject: Path / Listing and os.walk problem. In-Reply-To: References: Message-ID: So I found a way to do it, maybe some people could be interested: listNames = [] for n in names: listNames.append('_'.join(n.split('_')[:-1])) #It will cut the last part of the file name convention listNames = list(set(listNames)) #we Delete duplicates from the list, like this we only have what we are interested in for e in listNames: #Juste to check. print e :) 2010/8/26 Alban Nona > Hey ! Thank you guys ! > It help me a lot ! > > @Dennis (Gomes): Thanks ! I tried it it worked well but list me the whole > files :P (and finally crashed python...lol) > > I looked at the Peter method and, Im really dumb to didnt tough about > defining a pattern like *_v001.0001.exr * like this, it sort me only one > frame...which is perfect and less memory consuming I guess. > > And glob use seems to be perfect for what I want to do ! so thank you to > point me in this direction :p > > I tried also the Peter code, and it give me a good listing of my element > like I wanted: > > HPO7_SEQ004_031_VDMRoom_ALB > HPO7_SEQ004_031_VDMRoom_AMB > HPO7_SEQ004_031_VDMRoom_BTY > HPO7_SEQ004_031_VDMRoom_Cutouts_ALB > HPO7_SEQ004_031_VDMRoom_Cutouts_AMB > HPO7_SEQ004_031_VDMRoom_Cutouts_DET > .... > HPO7_SEQ004_031_VDMRoom_DET > HPO7_SEQ004_031_VDMRoom_DIF > HPO7_SEQ004_031_VDMRoom_DPF > HPO7_SEQ004_031_VDMRoom_Decals_ALB > .... > HPO7_SEQ004_031_VDM_ALB > > HPO7_SEQ004_031_VDM_AMB > HPO7_SEQ004_031_VDM_BTY > > HPO7_SEQ004_031_VDM_DIF > HPO7_SEQ004_031_VDM_DPF > HPO7_SEQ004_031_VDM_Fresnel_mat > > > Unfortunatly, a new problem come to me, I looking to get that kind of > list: > > HPO7_SEQ004_031_VDMRoom > HPO7_SEQ004_031_VDMRoom > HPO7_SEQ004_031_VDMRoom > HPO7_SEQ004_031_VDMRoom_Cutouts > HPO7_SEQ004_031_VDMRoom_Cutouts > HPO7_SEQ004_031_VDMRoom_Cutouts > .... > > Right now, Im looking the documentation to find a way to do it, Im thinking > about string methods, I also though: " hey, I just have to delete the 4 last > characters, but na ! itll not work because sometime I have something like > "_Fresnel_mat'' which is of course more than 4 chars...) > > Maybe the best would be to declare something like "in the string, look at > the last "_" and delete it + whatever there is after" > but I didnt find how to do it, I mean I tried splitext which is, not > appropriate. > > Do I have to declare a list of element like: > elementList: ["_ALB", "AMB", "_Beauty", etc...] > and to search that pattern in the files name to remove it after ? it seems > not bad as solution, but I pretty sure there is a better way to do it. > > right ? > > anyway, thank very much guys ! :) > and have a good day ! > > > 2010/8/26 Peter Otten <__peter__ at web.de> > > Alban Nona wrote: >> >> > Hi >> > >> > So here is my problem: >> > >> > I have my render files that are into a directory like this: >> > >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0001.exr >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0002.exr >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_DIF_V001.0003.exr >> > .... >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0001.exr >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0002.exr >> > c:\log\renderfiles\HPO7_SEQ004_031_VDM_AMB_V001.0003.exr >> > >> > True is, there is like 1000 Files is the directory (C:\log\renderfiles\) >> > >> > What Iam looking to is to extract the first part of the filenames as a >> > list, but I dont want the script to extract it 1000times, I mean I dont >> > need it to extract HPO7_SEQ004_031_VDM_AMB 150 times, because there is >> 150 >> > Frames. (not sure if its clear tought) >> > >> > so far, I would like the list to look lik: >> > >> > ["HPO7_SEQ004_031_VDM_DIF", "HPO7_SEQ004_031_VDM_AMB", etc...] >> > >> > >> > I start to think about that, to try to use a >> > >> > for (path, dirs, files) in os.walk(path): >> > list.append(files) >> > >> > >> > but this kind of thing will just append the whole 1000 files, thing that >> I >> > dont want, and more complicated I dont want the thing after "AMB" or >> "DIF" >> > in the name files to follow. >> > (thing I can delete using a split, if I read well ?) >> > >> > >> > I trying to search on internet for answer, but seems I find nothing >> about >> > it. >> > Someone can help me with that please, show me the way or something ? >> >> You can use glob. Assuming the files are all in one directory: >> >> import os >> import glob >> >> folder = r"C:\log\renderfiles" >> >> # find files that end with "_V001.0001.exr" >> pattern = os.path.join(folder, "*_V001.0001.exr") >> files = glob.glob(pattern) >> >> # remove the directory >> names = [os.path.basename(f) for f in files] >> >> # remove everything after and including the last occurence of "_" >> names = [n.rpartition("_")[0] for n in names] >> >> print "\n".join(sorted(names)) >> >> Peter >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From navkirats at gmail.com Thu Aug 26 14:57:19 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 00:27:19 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76B478.1090700@sschwarzer.net> References: <4C76B478.1090700@sschwarzer.net> Message-ID: I am sorry, maybe I was not elaborate in what I was having trouble with. I am using a jpegcam library, which on my web page captures a webcam image and sends it to the server via the POST method. On the Server side (python 3), I receive this image as a part of header content in bytes (I know thats not how it should be done, but the author has some reason for it), so I first convert the headers to a string so I can separate them. From the separated headers I fish out the content of the image file (which is a string). This is where I get stuck, how am I supposed to convert it back to an image, so I can save as a jpeg on disk. Regards, Nav On 27-Aug-2010, at 12:07 AM, Stefan Schwarzer wrote: > Hi Navkirat, > > On 2010-08-26 19:22, Navkirat Singh wrote: >> I am programming a webserver, I receive a jpeg file with >> the POST method.The file (.jpeg) is encoded in bytes, I >> parse the bytes by decoding them to a string. I wanted to >> know how i could write the file (now a string) as a jpeg >> image on disk. When I try to encode the same string to a >> bytes and write them in binary format to disk, the file is >> not recognized as jpeg. I would be grateful if someone >> could help me with this. > > I guess you mean you "see" a byte string in your server and > want to write that to disk. Assuming the string you got is > the correct image data in the first place, you can, in > Python 2.x, write the string data to disk like this: > > fobj = open("some_image.jpg", "wb") > fobj.write(byte_string) > fobj.close() > > Note that you should use "wb" as mode to write as binary. > Otherwise you'll get automatic line ending conversion (at > least on Windows) which will give the result you describe. > > If my answer doesn't help, you probably need to describe in > more detail what you're doing, including showing some real > code. > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list From python at mrabarnett.plus.com Thu Aug 26 15:15:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 26 Aug 2010 20:15:25 +0100 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <4C76B478.1090700@sschwarzer.net> Message-ID: <4C76BD4D.8060303@mrabarnett.plus.com> On 26/08/2010 19:57, Navkirat Singh wrote: > I am sorry, maybe I was not elaborate in what I was having trouble > with. I am using a jpegcam library, which on my web page captures a > webcam image and sends it to the server via the POST method. On the > Server side (python 3), I receive this image as a part of header > content in bytes (I know thats not how it should be done, but the > author has some reason for it), so I first convert the headers to a > string so I can separate them. From the separated headers I fish out > the content of the image file (which is a string). This is where I > get stuck, how am I supposed to convert it back to an image, so I can > save as a jpeg on disk. > [snip] What does that string look like? Try printing out repr(image[ : 100]). If it looks like plain bytes, then write it to file. If it looks like a series of hex digits, then decode to bytes before writing. From johnroth1 at gmail.com Thu Aug 26 15:29:25 2010 From: johnroth1 at gmail.com (John Roth) Date: Thu, 26 Aug 2010 12:29:25 -0700 (PDT) Subject: Overload print References: Message-ID: <7e793b96-1f42-43d7-91d8-3aac1e6d7188@a4g2000prm.googlegroups.com> On Aug 25, 3:42?pm, Alexander Kapps wrote: > Ross Williamson wrote: > > Hi All > > > Is there anyway in a class to overload the print function? > > In Python <= 2.x "print" is a statement and thus can't be > "overloaded". That's exactly the reason, why Python 3 has turned > "print" into a function. > > >>> class foo_class(): > >>> ? ? def __print__(self): > >>> ? ? ? ? ? print "hello" > > >>> cc = foo_class() > >>> print cc > > > Gives: > > > hello > > Hmm, on what Python version are you? To my knowledge there is no > __print__ special method. Did you mean __str__ or __repr__ ? > > > I'm looking at finding nice way to print variables in a class just by > > asking to print it > > In Python3 you *can* overload print(), but still, you better define > __str__() on your class to return a string, representing what ever > you want: > > In [11]: class Foo(object): > ? ? ....: ? ? def __str__(self): > ? ? ....: ? ? ? ? return "foo" > ? ? ....: > ? ? ....: > > In [12]: f = Foo() > > In [13]: print f > foo Maybe what the OP really wants is the format() method on a string? That gives a very rich set of override options, at the expense of not using the print statement/method, including the ability to define your own formatting language for a class. John Roth From stillyet+nntp at googlemail.com Thu Aug 26 15:31:17 2010 From: stillyet+nntp at googlemail.com (Simon Brooke) Date: 26 Aug 2010 19:31:17 GMT Subject: CRIMINAL YanQui MARINES Cesar Laurean Regularly RAPE GIRLS Maria Lauterbach and KILL THEM - CIA/Mossad/Jew did 911 - Wikileaks for ever CRIMES of YANQUI Bustards References: <9c3b672d-b636-4f12-9918-4837784fce42@x42g2000yqx.googlegroups.com> Message-ID: <8dnto5F4poU2@mid.individual.net> On Wed, 25 Aug 2010 07:31:03 -0700, Standish P wrote: > ... so you want to render this in TeX ... ? It was very thoughtful of you to repost the whole spammer text for the benefit of those of us who have the spammer killfiled, and consequently would not otherwise have been able to read it. -- ;; Semper in faecibus sumus, sole profundam variat From robert.kern at gmail.com Thu Aug 26 15:40:30 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 14:40:30 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <874oeh2sdg.fsf@castleamber.com> Message-ID: On 8/26/10 1:25 PM, Navkirat Singh wrote: > > On 26-Aug-2010, at 11:01 PM, John Bokma wrote: > >> Navkirat Singh writes: >> >>> Hey guys, >>> >>> I am programming a webserver, I receive a jpeg file with the POST >>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>> decoding them to a string. >> >> Why? >> >> -- >> John Bokma j3b >> >> Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma >> Freelance Perl& Python Development: http://castleamber.com/ >> -- >> http://mail.python.org/mailman/listinfo/python-list > > why? I am not quite sure what you have not understood. Why decode the bytes to (presumably) unicode strings just to encode them back to bytes again? JPEG is not composed of unicode characters; you need to leave them as bytes. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From navkirats at gmail.com Thu Aug 26 15:47:18 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 01:17:18 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <874oeh2sdg.fsf@castleamber.com> Message-ID: On 27-Aug-2010, at 1:10 AM, Robert Kern wrote: > On 8/26/10 1:25 PM, Navkirat Singh wrote: >> >> On 26-Aug-2010, at 11:01 PM, John Bokma wrote: >> >>> Navkirat Singh writes: >>> >>>> Hey guys, >>>> >>>> I am programming a webserver, I receive a jpeg file with the POST >>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>> decoding them to a string. >>> >>> Why? >>> >>> -- >>> John Bokma j3b >>> >>> Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma >>> Freelance Perl& Python Development: http://castleamber.com/ >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> why? I am not quite sure what you have not understood. > > Why decode the bytes to (presumably) unicode strings just to encode them back to bytes again? JPEG is not composed of unicode characters; you need to leave them as bytes. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list The image bytes are a part of a HTTP header content ( not the message body ). To separate the header content from the image I have to first convert the bytes to string to perform parsing. The resultant string then needs to be converted back to the image. Hence, my problem. From navkirats at gmail.com Thu Aug 26 15:54:43 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 01:24:43 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76BD4D.8060303@mrabarnett.plus.com> References: <4C76B478.1090700@sschwarzer.net> <4C76BD4D.8060303@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 12:45 AM, MRAB wrote: > On 26/08/2010 19:57, Navkirat Singh wrote: >> I am sorry, maybe I was not elaborate in what I was having trouble >> with. I am using a jpegcam library, which on my web page captures a >> webcam image and sends it to the server via the POST method. On the >> Server side (python 3), I receive this image as a part of header >> content in bytes (I know thats not how it should be done, but the >> author has some reason for it), so I first convert the headers to a >> string so I can separate them. From the separated headers I fish out >> the content of the image file (which is a string). This is where I >> get stuck, how am I supposed to convert it back to an image, so I can >> save as a jpeg on disk. >> > [snip] > What does that string look like? Try printing out repr(image[ : 100]). > If it looks like plain bytes, then write it to file. If it looks like a > series of hex digits, then decode to bytes before writing. > -- > http://mail.python.org/mailman/listinfo/python-list Thanks MRAB, your suggestions have always been very helpful to me. I shall let you know on what I see. Regards, Nav From davea at ieee.org Thu Aug 26 16:02:36 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 26 Aug 2010 16:02:36 -0400 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> Message-ID: <4C76C85C.7030505@ieee.org> Navkirat Singh wrote: > Hey guys, > > I am programming a webserver, I receive a jpeg file with the POST method.The file (.jpeg) is encoded in bytes, I parse the bytes by decoding them to a string. I wanted to know how i could write the file (now a string) as a jpeg image on disk. When I try to encode the same string to a bytes and write them in binary format to disk, the file is not recognized as jpeg. I would be grateful if someone could help me with this. > > > Regards, > Nav > If by "decoding them to a string" you mean converting to Unicode, then you've already trashed the data. That's only valid if the bytes had been encoded from valid Unicode characters, and then only if you use the corresponding decoding technique. If you mean some other decoding, then the question is meaningless without telling us just what the decoding is, preferably with some code. It also might be useful to know what version of Python you're using, when you post the code. DaveA From navkirats at gmail.com Thu Aug 26 16:14:40 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 01:44:40 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76C85C.7030505@ieee.org> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> Message-ID: <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: > Navkirat Singh wrote: >> Hey guys, >> >> I am programming a webserver, I receive a jpeg file with the POST method.The file (.jpeg) is encoded in bytes, I parse the bytes by decoding them to a string. I wanted to know how i could write the file (now a string) as a jpeg image on disk. When I try to encode the same string to a bytes and write them in binary format to disk, the file is not recognized as jpeg. I would be grateful if someone could help me with this. >> >> >> Regards, >> Nav > If by "decoding them to a string" you mean converting to Unicode, then you've already trashed the data. That's only valid if the bytes had been encoded from valid Unicode characters, and then only if you use the corresponding decoding technique. > > If you mean some other decoding, then the question is meaningless without telling us just what the decoding is, preferably with some code. > > It also might be useful to know what version of Python you're using, when you post the code. > > DaveA > Dave, I am using Python3 and I receive a byte stream with a jpeg attached sent by the web browser over a socket, which looks like this: b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f From the above, I need to: a) Split the header content from the image content, which comes after the keep-alive\r\n\r\n part b) Then write the image content to file for further use as a jpeg. Nav -------------- next part -------------- An HTML attachment was scrubbed... URL: From navkirats at gmail.com Thu Aug 26 16:19:25 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 01:49:25 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76C85C.7030505@ieee.org> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> Message-ID: <279000F8-D9C6-464C-912D-A49BC3AC4D3F@gmail.com> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: > Navkirat Singh wrote: >> Hey guys, >> >> I am programming a webserver, I receive a jpeg file with the POST method.The file (.jpeg) is encoded in bytes, I parse the bytes by decoding them to a string. I wanted to know how i could write the file (now a string) as a jpeg image on disk. When I try to encode the same string to a bytes and write them in binary format to disk, the file is not recognized as jpeg. I would be grateful if someone could help me with this. >> >> >> Regards, >> Nav > If by "decoding them to a string" you mean converting to Unicode, then you've already trashed the data. That's only valid if the bytes had been encoded from valid Unicode characters, and then only if you use the corresponding decoding technique. > > If you mean some other decoding, then the question is meaningless without telling us just what the decoding is, preferably with some code. > > It also might be useful to know what version of Python you're using, when you post the code. > > DaveA > Also, my apologies for lack of knowledge of character encodings. You have pointed out correctly about unicode encoding. I was under the impression that a unicode will preserve the integrity of the message which has been encoded. From rda.selin at gmail.com Thu Aug 26 16:24:56 2010 From: rda.selin at gmail.com (becky_s) Date: Thu, 26 Aug 2010 13:24:56 -0700 (PDT) Subject: matplotlib pyplot contourf with 1-D array (vector) References: Message-ID: I was able to figure this out on my own. First, to eliminate the masked arrays, I used a combination of the where and compress functions to remove any missing data from my 1-D arrays. Then, I used the griddata function as described above. This did the trick. From python at mrabarnett.plus.com Thu Aug 26 16:27:21 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 26 Aug 2010 21:27:21 +0100 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> Message-ID: <4C76CE29.8080507@mrabarnett.plus.com> On 26/08/2010 21:14, Navkirat Singh wrote: > > On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: > >> Navkirat Singh wrote: >>> Hey guys, >>> >>> I am programming a webserver, I receive a jpeg file with the POST >>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>> decoding them to a string. I wanted to know how i could write the >>> file (now a string) as a jpeg image on disk. When I try to encode the >>> same string to a bytes and write them in binary format to disk, the >>> file is not recognized as jpeg. I would be grateful if someone could >>> help me with this. >>> >>> >>> Regards, >>> Nav >> If by "decoding them to a string" you mean converting to Unicode, then >> you've already trashed the data. That's only valid if the bytes had >> been encoded from valid Unicode characters, and then only if you use >> the corresponding decoding technique. >> >> If you mean some other decoding, then the question is meaningless >> without telling us just what the decoding is, preferably with some code. >> >> It also might be useful to know what version of Python you're using, >> when you post the code. >> >> DaveA >> > > Dave, > > I am using Python3 and I receive a byte stream with a jpeg attached sent > by the web browser over a socket, which looks like this: > > b': image/jpeg\r\nAccept: text/*\r\nReferer: > http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: > gzip, deflate\r\nContent-Length: 91783\r\nConnection: > keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f > > From the above, I need to: > > a) Split the header content from the image content, which comes after > the keep-alive\r\n\r\n part > > b) Then write the image content to file for further use as a jpeg. > Try: image = header.split(b'keep-alive\r\n\r\n', 1)[-1] open(image_path, 'wb').write(image) From davea at ieee.org Thu Aug 26 16:32:59 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 26 Aug 2010 16:32:59 -0400 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> Message-ID: <4C76CF7B.3070809@ieee.org> Navkirat Singh wrote: > O > > I am using Python3 and I receive a byte stream with a jpeg attached sent by the web browser over a socket, which looks like this: > > b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f > > From the above, I need to: > > a) Split the header content from the image content, which comes after the keep-alive\r\n\r\n part > > b) Then write the image content to file for further use as a jpeg. > > Nav > An arbitrary string of bytes is not necessarily valid utf-8, so I'm not sure why you haven't been getting errors during that "decode." In any case, such a conversion is not reversible. I would parse that as bytes, perhaps by searching for 'keep-alive'. Then split the byte stream into the two parts, and only convert the first part to Unicode (Python 3 string). For safety, you could check to make sure the search pattern only appears once, and potentially decode it multiple times. It'll only make sense once. DaveA From hwfwguy at gmail.com Thu Aug 26 16:44:32 2010 From: hwfwguy at gmail.com (Brad) Date: Thu, 26 Aug 2010 13:44:32 -0700 (PDT) Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> <0b04a316-a147-4179-a11f-de7a935385ea@q16g2000prf.googlegroups.com> Message-ID: On Aug 25, 4:05?am, Alex McDonald wrote: > Your example of writing code with > memory leaks *and not caring because it's a waste of your time* makes > me think that you've never been a programmer of any sort. "Windows applications are immune from memory leaks since programmers can count on regular crashes to automatically release previously allocated RAM." From navkirats at gmail.com Thu Aug 26 16:47:05 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:17:05 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76CE29.8080507@mrabarnett.plus.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 1:57 AM, MRAB wrote: > On 26/08/2010 21:14, Navkirat Singh wrote: >> >> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >> >>> Navkirat Singh wrote: >>>> Hey guys, >>>> >>>> I am programming a webserver, I receive a jpeg file with the POST >>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>> decoding them to a string. I wanted to know how i could write the >>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>> same string to a bytes and write them in binary format to disk, the >>>> file is not recognized as jpeg. I would be grateful if someone could >>>> help me with this. >>>> >>>> >>>> Regards, >>>> Nav >>> If by "decoding them to a string" you mean converting to Unicode, then >>> you've already trashed the data. That's only valid if the bytes had >>> been encoded from valid Unicode characters, and then only if you use >>> the corresponding decoding technique. >>> >>> If you mean some other decoding, then the question is meaningless >>> without telling us just what the decoding is, preferably with some code. >>> >>> It also might be useful to know what version of Python you're using, >>> when you post the code. >>> >>> DaveA >>> >> >> Dave, >> >> I am using Python3 and I receive a byte stream with a jpeg attached sent >> by the web browser over a socket, which looks like this: >> >> b': image/jpeg\r\nAccept: text/*\r\nReferer: >> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >> >> From the above, I need to: >> >> a) Split the header content from the image content, which comes after >> the keep-alive\r\n\r\n part >> >> b) Then write the image content to file for further use as a jpeg. >> > Try: > > image = header.split(b'keep-alive\r\n\r\n', 1)[-1] > open(image_path, 'wb').write(image) > -- > http://mail.python.org/mailman/listinfo/python-list I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes From navkirats at gmail.com Thu Aug 26 16:48:57 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:18:57 +0530 Subject: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? In-Reply-To: References: <5fa7b287-0199-4349-ae0d-c34c8461cdcd@5g2000yqz.googlegroups.com> <18b0b074-0bea-4046-a6aa-993b8cf424c5@v41g2000yqv.googlegroups.com> <2d59bfaa-2aa5-4396-bd03-22200df8c36d@x21g2000yqa.googlegroups.com> <87aaogtfpg.fsf@lola.goethe.zz> <87bp8v1pwv.fsf@castleamber.com> <87k4nir7sk.fsf@lola.goethe.zz> <878w3yikiz.fsf@castleamber.com> <779b992b-7199-4126-bf3a-7ec40ea801a6@j18g2000yqd.googlegroups.com> <4c8ac052-a16a-4e88-8b85-a7de6e138a11@l20g2000yqm.googlegroups.com> <0b04a316-a147-4179-a11f-de7a935385ea@q16g2000prf.googlegroups.com> Message-ID: <111315E9-1191-48A3-A56C-C37131F0A23A@gmail.com> On 27-Aug-2010, at 2:14 AM, Brad wrote: > On Aug 25, 4:05 am, Alex McDonald wrote: >> Your example of writing code with >> memory leaks *and not caring because it's a waste of your time* makes >> me think that you've never been a programmer of any sort. > > "Windows applications are immune from memory leaks since programmers > can count on regular crashes to automatically release previously > allocated RAM." > -- > http://mail.python.org/mailman/listinfo/python-list Sorry if I may sound rude, but I have to do this on the windows applications comment - hahahahaha From john at castleamber.com Thu Aug 26 17:09:02 2010 From: john at castleamber.com (John Bokma) Date: Thu, 26 Aug 2010 16:09:02 -0500 Subject: Writing byte stream as jpeg format to disk References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <87vd6x13pt.fsf@castleamber.com> Navkirat Singh writes: >>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>> by the web browser over a socket, which looks like this: >>> >>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f You're mistaken that the content is part of the headers, it's not. The \r\n\r\n separates headers from the content. Why don't you use urllib to save you from all this hassle? -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From robert.kern at gmail.com Thu Aug 26 17:10:26 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:10:26 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 8/26/10 3:47 PM, Navkirat Singh wrote: > > On 27-Aug-2010, at 1:57 AM, MRAB wrote: > >> On 26/08/2010 21:14, Navkirat Singh wrote: >>> >>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>> >>>> Navkirat Singh wrote: >>>>> Hey guys, >>>>> >>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>> decoding them to a string. I wanted to know how i could write the >>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>> same string to a bytes and write them in binary format to disk, the >>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>> help me with this. >>>>> >>>>> >>>>> Regards, >>>>> Nav >>>> If by "decoding them to a string" you mean converting to Unicode, then >>>> you've already trashed the data. That's only valid if the bytes had >>>> been encoded from valid Unicode characters, and then only if you use >>>> the corresponding decoding technique. >>>> >>>> If you mean some other decoding, then the question is meaningless >>>> without telling us just what the decoding is, preferably with some code. >>>> >>>> It also might be useful to know what version of Python you're using, >>>> when you post the code. >>>> >>>> DaveA >>>> >>> >>> Dave, >>> >>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>> by the web browser over a socket, which looks like this: >>> >>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>> >>> From the above, I need to: >>> >>> a) Split the header content from the image content, which comes after >>> the keep-alive\r\n\r\n part >>> >>> b) Then write the image content to file for further use as a jpeg. >>> >> Try: >> >> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >> open(image_path, 'wb').write(image) >> -- >> http://mail.python.org/mailman/listinfo/python-list > > I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). > > @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes This is incorrect. Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> bytes = b'Connection: keep-alive\r\n\r\nbody' >>> bytes.split(b'\r\n\r\n', 1)[-1] b'body' FYI: the JPEG data is not in the header. The b'\r\n\r\n' sequence delimits the header from the body. Do not rely on "Connection: keep-alive" being the last header. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From navkirats at gmail.com Thu Aug 26 17:17:05 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:47:05 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76CE29.8080507@mrabarnett.plus.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 1:57 AM, MRAB wrote: > On 26/08/2010 21:14, Navkirat Singh wrote: >> >> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >> >>> Navkirat Singh wrote: >>>> Hey guys, >>>> >>>> I am programming a webserver, I receive a jpeg file with the POST >>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>> decoding them to a string. I wanted to know how i could write the >>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>> same string to a bytes and write them in binary format to disk, the >>>> file is not recognized as jpeg. I would be grateful if someone could >>>> help me with this. >>>> >>>> >>>> Regards, >>>> Nav >>> If by "decoding them to a string" you mean converting to Unicode, then >>> you've already trashed the data. That's only valid if the bytes had >>> been encoded from valid Unicode characters, and then only if you use >>> the corresponding decoding technique. >>> >>> If you mean some other decoding, then the question is meaningless >>> without telling us just what the decoding is, preferably with some code. >>> >>> It also might be useful to know what version of Python you're using, >>> when you post the code. >>> >>> DaveA >>> >> >> Dave, >> >> I am using Python3 and I receive a byte stream with a jpeg attached sent >> by the web browser over a socket, which looks like this: >> >> b': image/jpeg\r\nAccept: text/*\r\nReferer: >> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >> >> From the above, I need to: >> >> a) Split the header content from the image content, which comes after >> the keep-alive\r\n\r\n part >> >> b) Then write the image content to file for further use as a jpeg. >> > Try: > > image = header.split(b'keep-alive\r\n\r\n', 1)[-1] > open(image_path, 'wb').write(image) > -- > http://mail.python.org/mailman/listinfo/python-list Yay !! I figured it out....it was really very simple. And if I really feel guilty if I have wasted your time - @MRAB, @DAVE. Here is what I needed to do: a) Separate image content from header content of the byte stream received from the web browser. b) Save the image content to disk for further use. Here is what I did. Following is just a snippet: #-------------HERE IS WHERE I RECEIVE THE DATA while True: buff = socket.recv(8192) byteStr +=buff if not buff: break #--------------ENCODING/DECODING STARTS FROM HERE (since I want to use split/partition functions to separate header content from the image content) strMsg = byteStr.decode("ISO-8859-1") listMsg = strMsg.split('\r\n') #---------------------------- # do some more processing to search the list for the image content, say supposing index is 11 #--------------------------- imageStr = listMsg[11].encode("ISO-8859-1") #Transform the byte string just the way I found it f = open('received.jpg','w'b) f.write(imageStr) The resultant file is a jpg file. Thanks, Nav From python at mrabarnett.plus.com Thu Aug 26 17:18:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 26 Aug 2010 22:18:26 +0100 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <4C76DA22.7030404@mrabarnett.plus.com> On 26/08/2010 21:47, Navkirat Singh wrote: > > On 27-Aug-2010, at 1:57 AM, MRAB wrote: > >> On 26/08/2010 21:14, Navkirat Singh wrote: >>> >>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>> >>>> Navkirat Singh wrote: >>>>> Hey guys, >>>>> >>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>> decoding them to a string. I wanted to know how i could write the >>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>> same string to a bytes and write them in binary format to disk, the >>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>> help me with this. >>>>> >>>>> >>>>> Regards, >>>>> Nav >>>> If by "decoding them to a string" you mean converting to Unicode, then >>>> you've already trashed the data. That's only valid if the bytes had >>>> been encoded from valid Unicode characters, and then only if you use >>>> the corresponding decoding technique. >>>> >>>> If you mean some other decoding, then the question is meaningless >>>> without telling us just what the decoding is, preferably with some code. >>>> >>>> It also might be useful to know what version of Python you're using, >>>> when you post the code. >>>> >>>> DaveA >>>> >>> >>> Dave, >>> >>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>> by the web browser over a socket, which looks like this: >>> >>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>> >>> From the above, I need to: >>> >>> a) Split the header content from the image content, which comes after >>> the keep-alive\r\n\r\n part >>> >>> b) Then write the image content to file for further use as a jpeg. >>> >> Try: >> >> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >> open(image_path, 'wb').write(image) >> -- >> http://mail.python.org/mailman/listinfo/python-list > > I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). > > @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes > All i can say is that it works for me: >>> header = b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>> image b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' What error did you get? From navkirats at gmail.com Thu Aug 26 17:25:38 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:55:38 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <67C524B2-53CB-4E38-BA33-CF3999089CF2@gmail.com> On 27-Aug-2010, at 2:40 AM, Robert Kern wrote: > On 8/26/10 3:47 PM, Navkirat Singh wrote: >> >> On 27-Aug-2010, at 1:57 AM, MRAB wrote: >> >>> On 26/08/2010 21:14, Navkirat Singh wrote: >>>> >>>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>>> >>>>> Navkirat Singh wrote: >>>>>> Hey guys, >>>>>> >>>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>>> decoding them to a string. I wanted to know how i could write the >>>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>>> same string to a bytes and write them in binary format to disk, the >>>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>>> help me with this. >>>>>> >>>>>> >>>>>> Regards, >>>>>> Nav >>>>> If by "decoding them to a string" you mean converting to Unicode, then >>>>> you've already trashed the data. That's only valid if the bytes had >>>>> been encoded from valid Unicode characters, and then only if you use >>>>> the corresponding decoding technique. >>>>> >>>>> If you mean some other decoding, then the question is meaningless >>>>> without telling us just what the decoding is, preferably with some code. >>>>> >>>>> It also might be useful to know what version of Python you're using, >>>>> when you post the code. >>>>> >>>>> DaveA >>>>> >>>> >>>> Dave, >>>> >>>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>>> by the web browser over a socket, which looks like this: >>>> >>>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>>> >>>> From the above, I need to: >>>> >>>> a) Split the header content from the image content, which comes after >>>> the keep-alive\r\n\r\n part >>>> >>>> b) Then write the image content to file for further use as a jpeg. >>>> >>> Try: >>> >>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>> open(image_path, 'wb').write(image) >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). >> >> @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes > > This is incorrect. > > Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) > [GCC 4.0.1 (Apple Inc. build 5493)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > > >>> bytes = b'Connection: keep-alive\r\n\r\nbody' > >>> bytes.split(b'\r\n\r\n', 1)[-1] > b'body' > > > FYI: the JPEG data is not in the header. The b'\r\n\r\n' sequence delimits the header from the body. Do not rely on "Connection: keep-alive" being the last header. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks Everyone, @Robert - Thanks a lot for your time :-) , I did know that the body starts after the occurrence two CRLF sequences, but I was following RFC2616 as a guide, which specifically mentions: "The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer- Encoding header field in the request?s message-headers" Which has not been done by the author of the library, hence I said what I did. Or I have misunderstood the RFC Regards, Nav -------------- next part -------------- An HTML attachment was scrubbed... URL: From navkirats at gmail.com Thu Aug 26 17:28:08 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 02:58:08 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <4C76DA22.7030404@mrabarnett.plus.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 2:48 AM, MRAB wrote: > On 26/08/2010 21:47, Navkirat Singh wrote: >> >> On 27-Aug-2010, at 1:57 AM, MRAB wrote: >> >>> On 26/08/2010 21:14, Navkirat Singh wrote: >>>> >>>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>>> >>>>> Navkirat Singh wrote: >>>>>> Hey guys, >>>>>> >>>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>>> decoding them to a string. I wanted to know how i could write the >>>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>>> same string to a bytes and write them in binary format to disk, the >>>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>>> help me with this. >>>>>> >>>>>> >>>>>> Regards, >>>>>> Nav >>>>> If by "decoding them to a string" you mean converting to Unicode, then >>>>> you've already trashed the data. That's only valid if the bytes had >>>>> been encoded from valid Unicode characters, and then only if you use >>>>> the corresponding decoding technique. >>>>> >>>>> If you mean some other decoding, then the question is meaningless >>>>> without telling us just what the decoding is, preferably with some code. >>>>> >>>>> It also might be useful to know what version of Python you're using, >>>>> when you post the code. >>>>> >>>>> DaveA >>>>> >>>> >>>> Dave, >>>> >>>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>>> by the web browser over a socket, which looks like this: >>>> >>>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>>> >>>> From the above, I need to: >>>> >>>> a) Split the header content from the image content, which comes after >>>> the keep-alive\r\n\r\n part >>>> >>>> b) Then write the image content to file for further use as a jpeg. >>>> >>> Try: >>> >>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>> open(image_path, 'wb').write(image) >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). >> >> @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes >> > All i can say is that it works for me: > > >>> header = b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' > >>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] > >>> image > b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' > > What error did you get? > -- > http://mail.python.org/mailman/listinfo/python-list Hi MRAB, Here is the error: >>> b = b'asdf' >>> type(b) >>> s = b.split(':') Traceback (most recent call last): File "", line 1, in TypeError: Type str doesn't support the buffer API >>> From robert.kern at gmail.com Thu Aug 26 17:32:17 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:32:17 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 8/26/10 4:17 PM, Navkirat Singh wrote: > Here is what I needed to do: > > a) Separate image content from header content of the byte stream received from the web browser. > b) Save the image content to disk for further use. > > Here is what I did. Following is just a snippet: > > > #-------------HERE IS WHERE I RECEIVE THE DATA > while True: > buff = socket.recv(8192) > byteStr +=buff > if not buff: break > #--------------ENCODING/DECODING STARTS FROM HERE (since I want to use split/partition functions to separate header content from the image content) > strMsg = byteStr.decode("ISO-8859-1") > listMsg = strMsg.split('\r\n') > #---------------------------- > # do some more processing to search the list for the image content, say supposing index is 11 > #--------------------------- > imageStr = listMsg[11].encode("ISO-8859-1") #Transform the byte string just the way I found it If your JPEG happens to contain the bytes \r\n, then this will not work. Please follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 argument to make sure that you do not split on spurious b'\r\n\r\n' sequences inside the JPEG body. Do not decode the bytes. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Thu Aug 26 17:34:34 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:34:34 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: <67C524B2-53CB-4E38-BA33-CF3999089CF2@gmail.com> References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <67C524B2-53CB-4E38-BA33-CF3999089CF2@gmail.com> Message-ID: On 8/26/10 4:25 PM, Navkirat Singh wrote: > @Robert - Thanks a lot for your time :-) , I did know that the body starts after > the occurrence two CRLF sequences, but I was following RFC2616 as a guide, which > specifically mentions: > > "The presence of a message-body in a request is signaled by the inclusion of a > > Content-Length or Transfer- Encoding header field in the > > request?s message-headers" > > Which has not been done by the author of the library, hence I said what I did. > Or I have misunderstood the RFC It certainly looks like the data has a Content-length header: b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\n ... -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From navkirats at gmail.com Thu Aug 26 17:35:03 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 03:05:03 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 2:58 AM, Navkirat Singh wrote: > > On 27-Aug-2010, at 2:48 AM, MRAB wrote: > >> On 26/08/2010 21:47, Navkirat Singh wrote: >>> >>> On 27-Aug-2010, at 1:57 AM, MRAB wrote: >>> >>>> On 26/08/2010 21:14, Navkirat Singh wrote: >>>>> >>>>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>>>> >>>>>> Navkirat Singh wrote: >>>>>>> Hey guys, >>>>>>> >>>>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>>>> decoding them to a string. I wanted to know how i could write the >>>>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>>>> same string to a bytes and write them in binary format to disk, the >>>>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>>>> help me with this. >>>>>>> >>>>>>> >>>>>>> Regards, >>>>>>> Nav >>>>>> If by "decoding them to a string" you mean converting to Unicode, then >>>>>> you've already trashed the data. That's only valid if the bytes had >>>>>> been encoded from valid Unicode characters, and then only if you use >>>>>> the corresponding decoding technique. >>>>>> >>>>>> If you mean some other decoding, then the question is meaningless >>>>>> without telling us just what the decoding is, preferably with some code. >>>>>> >>>>>> It also might be useful to know what version of Python you're using, >>>>>> when you post the code. >>>>>> >>>>>> DaveA >>>>>> >>>>> >>>>> Dave, >>>>> >>>>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>>>> by the web browser over a socket, which looks like this: >>>>> >>>>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>>>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>>>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>>>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>>>> >>>>> From the above, I need to: >>>>> >>>>> a) Split the header content from the image content, which comes after >>>>> the keep-alive\r\n\r\n part >>>>> >>>>> b) Then write the image content to file for further use as a jpeg. >>>>> >>>> Try: >>>> >>>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>>> open(image_path, 'wb').write(image) >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>> >>> I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). >>> >>> @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes >>> >> All i can say is that it works for me: >> >>>>> header = b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >>>>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>>>> image >> b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >> >> What error did you get? >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Hi MRAB, > > Here is the error: > >>>> b = b'asdf' >>>> type(b) > >>>> s = b.split(':') > Traceback (most recent call last): > File "", line 1, in > TypeError: Type str doesn't support the buffer API >>>> > > I got your point The argument for the split I have give is a string, hence the error. From robert.kern at gmail.com Thu Aug 26 17:43:00 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:43:00 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: On 8/26/10 4:28 PM, Navkirat Singh wrote: > > On 27-Aug-2010, at 2:48 AM, MRAB wrote: > >> On 26/08/2010 21:47, Navkirat Singh wrote: >>> >>> On 27-Aug-2010, at 1:57 AM, MRAB wrote: >>> >>>> On 26/08/2010 21:14, Navkirat Singh wrote: >>>>> >>>>> On 27-Aug-2010, at 1:32 AM, Dave Angel wrote: >>>>> >>>>>> Navkirat Singh wrote: >>>>>>> Hey guys, >>>>>>> >>>>>>> I am programming a webserver, I receive a jpeg file with the POST >>>>>>> method.The file (.jpeg) is encoded in bytes, I parse the bytes by >>>>>>> decoding them to a string. I wanted to know how i could write the >>>>>>> file (now a string) as a jpeg image on disk. When I try to encode the >>>>>>> same string to a bytes and write them in binary format to disk, the >>>>>>> file is not recognized as jpeg. I would be grateful if someone could >>>>>>> help me with this. >>>>>>> >>>>>>> >>>>>>> Regards, >>>>>>> Nav >>>>>> If by "decoding them to a string" you mean converting to Unicode, then >>>>>> you've already trashed the data. That's only valid if the bytes had >>>>>> been encoded from valid Unicode characters, and then only if you use >>>>>> the corresponding decoding technique. >>>>>> >>>>>> If you mean some other decoding, then the question is meaningless >>>>>> without telling us just what the decoding is, preferably with some code. >>>>>> >>>>>> It also might be useful to know what version of Python you're using, >>>>>> when you post the code. >>>>>> >>>>>> DaveA >>>>>> >>>>> >>>>> Dave, >>>>> >>>>> I am using Python3 and I receive a byte stream with a jpeg attached sent >>>>> by the web browser over a socket, which looks like this: >>>>> >>>>> b': image/jpeg\r\nAccept: text/*\r\nReferer: >>>>> http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: >>>>> gzip, deflate\r\nContent-Length: 91783\r\nConnection: >>>>> keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f >>>>> >>>>> From the above, I need to: >>>>> >>>>> a) Split the header content from the image content, which comes after >>>>> the keep-alive\r\n\r\n part >>>>> >>>>> b) Then write the image content to file for further use as a jpeg. >>>>> >>>> Try: >>>> >>>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>>> open(image_path, 'wb').write(image) >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>> >>> I think I forgot to mention that the original is a stream of bytes decoded using ISO-8859-1 as utf-8 trhrew errors (lack of knowlegdge again). >>> >>> @MRAB - the split() method in python 3 works only on strings and throws an error if I try to use bytes >>> >> All i can say is that it works for me: >> >>>>> header = b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >>>>> image = header.split(b'keep-alive\r\n\r\n', 1)[-1] >>>>> image >> b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f' >> >> What error did you get? >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Hi MRAB, > > Here is the error: > >>>> b = b'asdf' >>>> type(b) > >>>> s = b.split(':') > Traceback (most recent call last): > File "", line 1, in > TypeError: Type str doesn't support the buffer API >>>> Follow MRAB's example. You need to use a bytes object for the *argument*, too. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Thu Aug 26 17:45:04 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Aug 2010 16:45:04 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 8/26/10 4:17 PM, Navkirat Singh wrote: > #-------------HERE IS WHERE I RECEIVE THE DATA > while True: > buff = socket.recv(8192) > byteStr +=buff > if not buff: break Also, you probably shouldn't bother writing an HTTP server using raw sockets. Use HTTPServer instead: http://docs.python.org/py3k/library/http.server.html or better, wsgiref: http://docs.python.org/py3k/library/wsgiref.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From navkirats at gmail.com Thu Aug 26 17:48:56 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 03:18:56 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <9B50381E-AEA2-4573-BB6E-314DFB5B0DF6@gmail.com> On 27-Aug-2010, at 3:02 AM, Robert Kern wrote: > On 8/26/10 4:17 PM, Navkirat Singh wrote: > >> Here is what I needed to do: >> >> a) Separate image content from header content of the byte stream received from the web browser. >> b) Save the image content to disk for further use. >> >> Here is what I did. Following is just a snippet: >> >> >> #-------------HERE IS WHERE I RECEIVE THE DATA >> while True: >> buff = socket.recv(8192) >> byteStr +=buff >> if not buff: break >> #--------------ENCODING/DECODING STARTS FROM HERE (since I want to use split/partition functions to separate header content from the image content) >> strMsg = byteStr.decode("ISO-8859-1") >> listMsg = strMsg.split('\r\n') >> #---------------------------- >> # do some more processing to search the list for the image content, say supposing index is 11 >> #--------------------------- >> imageStr = listMsg[11].encode("ISO-8859-1") #Transform the byte string just the way I found it > > If your JPEG happens to contain the bytes \r\n, then this will not work. Please follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 argument to make sure that you do not split on spurious b'\r\n\r\n' sequences inside the JPEG body. Do not decode the bytes. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks Robert, My method worked too, I was able to do the above and save the jpeg flawlessly, but your method seems better as I will not have to take the extra step of encoding/decoding. From navkirats at gmail.com Thu Aug 26 17:51:49 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 03:21:49 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <67C524B2-53CB-4E38-BA33-CF3999089CF2@gmail.com> Message-ID: <27CFAC22-56FD-43BA-80F1-15041A46F779@gmail.com> On 27-Aug-2010, at 3:04 AM, Robert Kern wrote: > On 8/26/10 4:25 PM, Navkirat Singh wrote: > >> @Robert - Thanks a lot for your time :-) , I did know that the body starts after >> the occurrence two CRLF sequences, but I was following RFC2616 as a guide, which >> specifically mentions: >> >> "The presence of a message-body in a request is signaled by the inclusion of a >> >> Content-Length or Transfer- Encoding header field in the >> >> request?s message-headers" >> >> Which has not been done by the author of the library, hence I said what I did. >> Or I have misunderstood the RFC > > It certainly looks like the data has a Content-length header: > > b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\n > ... > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list Once again you opened my eyes, I think its been a tough night for me. Seeing too much and nothing at the same time. Regards From navkirats at gmail.com Thu Aug 26 18:18:07 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 03:48:07 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: On 27-Aug-2010, at 3:15 AM, Robert Kern wrote: > On 8/26/10 4:17 PM, Navkirat Singh wrote: > >> #-------------HERE IS WHERE I RECEIVE THE DATA >> while True: >> buff = socket.recv(8192) >> byteStr +=buff >> if not buff: break > > Also, you probably shouldn't bother writing an HTTP server using raw sockets. Use HTTPServer instead: > > http://docs.python.org/py3k/library/http.server.html > > or better, wsgiref: > > http://docs.python.org/py3k/library/wsgiref.html > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks a lot guys, you all have been a lot of help !! From thomas at jollybox.de Thu Aug 26 18:22:36 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Fri, 27 Aug 2010 00:22:36 +0200 Subject: Python Editor or IDE ActiveX control In-Reply-To: References: Message-ID: <201008270022.37040.thomas@jollybox.de> On Thursday 26 August 2010, it occurred to Sathish S to exclaim: > Hi Ppl, > > Is there any python IDE or editor that has an ActiveX control which could > be embed in other Windows applications. I'm basically looking to write a > application that can show the indentations of python, change the color of > keywords etc on a application, which will save this python script and run > it from command prompt. It sounds to me like you're just looking for any old halfway decent embeddable programmer's editor that happens to have syntax definitions for Python. I'd suggest you have a look at Scintilla. Quite a good editing control, I don't think it comes wrapped in ActiveX or anything like that, just interface it in your favourite language using the DLL's C API. From tjreedy at udel.edu Thu Aug 26 18:53:08 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Aug 2010 18:53:08 -0400 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: On 8/26/2010 5:28 PM, Navkirat Singh wrote: >>>> b = b'asdf' >>>> type(b) > >>>> s = b.split(':') You are trying to split bytes with a string, which is impossible. Split bytes with bytes, strings with strings. > Traceback (most recent call last): > File "", line 1, in > TypeError: Type str doesn't support the buffer API -- Terry Jan Reedy From navkirats at gmail.com Thu Aug 26 18:57:57 2010 From: navkirats at gmail.com (Navkirat Singh) Date: Fri, 27 Aug 2010 04:27:57 +0530 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <4C76DA22.7030404@mrabarnett.plus.com> Message-ID: <820C2670-61F1-4587-8ACA-189FC78EC61A@gmail.com> On 27-Aug-2010, at 4:23 AM, Terry Reedy wrote: > On 8/26/2010 5:28 PM, Navkirat Singh wrote: > >>>>> b = b'asdf' >>>>> type(b) >> >>>>> s = b.split(':') > > You are trying to split bytes with a string, which is impossible. > Split bytes with bytes, strings with strings. > >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: Type str doesn't support the buffer API > > > -- > Terry Jan Reedy > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks ! From stef.mientki at gmail.com Thu Aug 26 19:17:34 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 27 Aug 2010 01:17:34 +0200 Subject: Python Editor or IDE ActiveX control In-Reply-To: <201008270022.37040.thomas@jollybox.de> References: <201008270022.37040.thomas@jollybox.de> Message-ID: <4C76F60E.9090708@gmail.com> On 27-08-2010 00:22, Thomas Jollans wrote: > On Thursday 26 August 2010, it occurred to Sathish S to exclaim: >> Hi Ppl, >> >> Is there any python IDE or editor that has an ActiveX control which could >> be embed in other Windows applications. I'm basically looking to write a >> application that can show the indentations of python, change the color of >> keywords etc on a application, which will save this python script and run >> it from command prompt. > It sounds to me like you're just looking for any old halfway decent embeddable > programmer's editor that happens to have syntax definitions for Python. > > I'd suggest you have a look at Scintilla. Quite a good editing control, I > don't think it comes wrapped in ActiveX or anything like that, just interface > it in your favourite language using the DLL's C API. Scintilla is full embedded in wxPython. cheers, Stef From joshua.r.english at gmail.com Thu Aug 26 19:30:46 2010 From: joshua.r.english at gmail.com (Josh English) Date: Thu, 26 Aug 2010 16:30:46 -0700 (PDT) Subject: pyxser-1.5r --- Python Object to XML serializer/deserializer References: Message-ID: <72aa2291-d979-4deb-9e9b-147af2c9d0af@b4g2000pra.googlegroups.com> It looks nice, but it's a shame it doesn't work on Windows. This could solve a lot of the problems I'm running into in my own attempt to build a python Class implementation of an XML Validation object. From cliff.martin at gmail.com Thu Aug 26 23:08:42 2010 From: cliff.martin at gmail.com (Cliff Martin) Date: Thu, 26 Aug 2010 20:08:42 -0700 (PDT) Subject: Trouble importing cx_Oracle on HPUX Message-ID: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> I have just gotten done building Python 3.1.2 on HPUX 11.31 Itanium (IA64) using gcc 4.4.3, and have tried building cx_Oracle to go with it. The build succeeds, but test and importing does not. I have tried building Python with threads and without. The only exotic thing I do with the configure for python is to supply -mlp64, which makes it a 64 bit build. Python 3 appears to work just fine, and cx_Oracle has worked on this same architecture in the past with Python 2.6.5. Help! I would really like to use Python 3, but Oracle support is a requirement. Everything I've read indicates it should work, but there is not a lot of people doing this or posting notes about their install problems or successes on HP-UX. Cliff From stefan_ml at behnel.de Fri Aug 27 01:02:03 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 27 Aug 2010 07:02:03 +0200 Subject: pyxser-1.5r --- Python Object to XML serializer/deserializer In-Reply-To: <72aa2291-d979-4deb-9e9b-147af2c9d0af@b4g2000pra.googlegroups.com> References: <72aa2291-d979-4deb-9e9b-147af2c9d0af@b4g2000pra.googlegroups.com> Message-ID: Josh English, 27.08.2010 01:30: > solve a lot of the problems I'm running into in my own attempt to > build a python Class implementation of an XML Validation object. How would object serialisation help here? Stefan From yooots2 at gmail.com Fri Aug 27 01:38:05 2010 From: yooots2 at gmail.com (yooots) Date: Thu, 26 Aug 2010 22:38:05 -0700 (PDT) Subject: ipad Message-ID: <6c99818e-9daa-4b58-bf76-dabfe784c195@s17g2000prh.googlegroups.com> I was in a foreign trade company in New York, a sales manager. Because I often need to travel, a powerful laptop for me is essential. However, the computers I used before can not satisfy my request in many ways. However, I recently ordered an ipad online. I really feel the prompt wireless Internet access speed, and the easy controlling. What?s more ,it?s cheap .So I want to share the experience with you, my friends. Terms of quality, iPad is a new type of computer, can be run through a simple interface similar to PC's complex software, large screen, it also brings more. But iPad is a new type of computer, only after the full experience and use, ,you can feel it is so convenient. Terms of powerful e-book function, the iPad make a modern discovery, iBook software in the App Store is also a free download through the free software now, and as if I carry a small library daily with updated best-selling book, making my reading full offun. Also read the file is quite easy! When I get iPad, first of all want to do is browse the web, and check whether the virtual keyboard easy to use. In the new iPad screen, I like the site has a good display. iPad's screen is 9.7 inches, while the iPhone is only 3.5 inches. The iPad the wide side facing down will go to landscape mode, the larger screen more convenient typing. I use Facebook and other web page, select the picture or article for browsing, but very comfortable! In the video, and photo area, iPad's performance is very good. I can watch HD video in YouTube, zoom mode is also very clear. Browse pictures is also very easy .Slideshow is also very good to meet my work requirements, built-in speaker can also play background music. IPad's music player interface is simple and very convenient to use. In particular, I think that reading better when the reading with the iPad. Simple and comfortable, full of fun, so I experience the multi- use benefits. Game features: iPad can run all the App Store process. While waiting for the metro I can play my favorite Need for Speed and MIB.COM so I experienced the powerful entertainment features of ipad. In the spare time I enjoy the short game fun! On the electronic map function, ipad has a strong electronic map function, when I drove away in a strange neighborhood, I will not need the help of GPS, a ipad can save a lot of extra cost! It provided me with many other applications also! All in all, ipad has its own value, carry on business when deal in the PPT, read e-books, search in the wireless network information, check maps and other applications, will demonstrate the advantages of more convenient. Ipad used, I have love it up. I will not use the other laptop, since they can not meet the needs of my operation, and www.Yooots.com company provided me with very good after-sales service . Cheap prices, high quality service, so I'm very satisfied ! From enleverLesX_XXmcX at XmclavXeauX.com.invalid Fri Aug 27 01:55:11 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Fri, 27 Aug 2010 07:55:11 +0200 Subject: Python Editor or IDE ActiveX control References: Message-ID: <4c775348$0$5428$ba4acef3@reader.news.orange.fr> Hi! Scintilla come like a "control" (a piece for a window), raleted to the file SciLexer.DLL For call the scintilla-componant, use "messages". Example : SendMessage(Sci, SCI_GOTOLINE, line, 0) For the constant SCI_GOTOLINE, I suggest scintillacon.py, include in Pywin32. @-salutations -- Michel Claveau From bryanjugglercryptographer at yahoo.com Fri Aug 27 02:56:26 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Thu, 26 Aug 2010 23:56:26 -0700 (PDT) Subject: Writing byte stream as jpeg format to disk References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> Message-ID: <6dd639c4-f5e0-4df8-8816-9cad28ae2460@q40g2000prg.googlegroups.com> Robert Kern wrote: > Please > follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 argument to > make sure that you do not split on spurious b'\r\n\r\n' sequences inside the > JPEG body. Do not decode the bytes. Correct, and I'll add that this is a case where we might want to be better than correct. BaseHTTPRequestHandler in the Python standard library accommodates clients that incorrectly omit the '\r' and end header lines with just '\n'. Such apps have been seen in the wild. Since bare '\n' never appears in correctly formed HTTP headers, interpreting it as equivalent to '\r\n' doesn't break anything. The re module offers a split that does what we want. import re boundary_re = re.compile(br'\r?\n\r?\n') then you can use: (headers, content) = boundary_re.split(rawdata, 1) I like Robert's suggestion to use the HTTP server or wsgiref in the Python library. There's significant arcane wisdom programmed in already. From rami.chowdhury at merton.oxon.org Fri Aug 27 03:28:46 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Fri, 27 Aug 2010 13:28:46 +0600 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: On Wed, Aug 25, 2010 at 05:04, Lawrence D'Oliveiro wrote: > In message , Nobody wrote: > >> Having this as a separate permission allows normal users to add entries to >> log files but not to erase existing entries. > > Unix/Linux systems can do this already. Ooh, I didn't know that -- what combination of permissions would I have to use to get such an effect? -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From nobody at nowhere.com Fri Aug 27 04:16:49 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 27 Aug 2010 09:16:49 +0100 Subject: Reading the access attributes of directories in Windows References: Message-ID: On Fri, 27 Aug 2010 13:28:46 +0600, Rami Chowdhury wrote: >>> Having this as a separate permission allows normal users to add entries >>> to log files but not to erase existing entries. >> >> Unix/Linux systems can do this already. > > Ooh, I didn't know that -- what combination of permissions would I have to > use to get such an effect? You can't do it with permissions, you need to use ext2 attributes. Specifically, "chattr +a " will set the "append" attribute, which prevents the file being opened for write except in append mode. Changing this attribute requires root privilege or the CAP_LINUX_IMMUTABLE capability. From nobody at nowhere.com Fri Aug 27 04:30:37 2010 From: nobody at nowhere.com (Nobody) Date: Fri, 27 Aug 2010 09:30:37 +0100 Subject: Writing byte stream as jpeg format to disk References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <6dd639c4-f5e0-4df8-8816-9cad28ae2460@q40g2000prg.googlegroups.com> Message-ID: On Thu, 26 Aug 2010 23:56:26 -0700, Bryan wrote: >> follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 >> argument to make sure that you do not split on spurious b'\r\n\r\n' >> sequences inside the JPEG body. Do not decode the bytes. > > Correct, and I'll add that this is a case where we might want to be better > than correct. BaseHTTPRequestHandler in the Python standard library > accommodates clients that incorrectly omit the '\r' and end header lines > with just '\n'. Such apps have been seen in the wild. Since bare '\n' > never appears in correctly formed HTTP headers, interpreting it as > equivalent to '\r\n' doesn't break anything. Yes it does. It breaks upstream filtering rules which are intended to prohibit, remove or modify certain headers. This class of attack is known as "HTTP request smuggling". By appending a header preceded by a bare '\r' or '\n' to the end of another header, the header can be "smuggled" past a filter which parses headers using the correct syntax, but will still be treated as a header by software which incorrectly parses headers using bare '\r' or '\n' as separators. The safest solution would be to simply reject any request (or response) which contains bare '\r' or '\n' characters within headers, at least by default. Force the programmer to read the documentation (where the risks would be described) if they want the "fault tolerant" behaviour. From raoulbia at gmail.com Fri Aug 27 04:53:17 2010 From: raoulbia at gmail.com (Baba) Date: Fri, 27 Aug 2010 01:53:17 -0700 (PDT) Subject: palindrome iteration Message-ID: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> level: beginner the following code looks ok to me but it doesn't work. I would like some hints as to where my reasoning / thought goes wrong def i_palindrome(pal): while len(pal)>1: if pal[0] == pal[-1]: pal=pal[1:-1] return True print i_palindrome('annab') my reasoning: - i check the length of the string: if > 1 continue - i check first and last char: if they are equal continue - create a new, shorter string starting at index 1 and ending at second last index (up to but not including index-1 -restart the while loop as long as length of string is > 1 - exiting this loop means all compared chars were identical hence it is a palindrome and i return True tnx Baba From contact at xavierho.com Fri Aug 27 05:03:35 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 27 Aug 2010 19:03:35 +1000 Subject: palindrome iteration In-Reply-To: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: One possible reason I can think of - "- exiting this loop means all compared chars were identical hence it is a palindrome and i return True" is probably incorrect reasoning. Think again. Also, you may consider posting your code in a way that preserves the whitespace characters. Cheers, Xav On 27 August 2010 18:53, Baba wrote: > level: beginner > > the following code looks ok to me but it doesn't work. I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] > return True > > print i_palindrome('annab') > > > my reasoning: > - i check the length of the string: if > 1 continue > - i check first and last char: if they are equal continue > - create a new, shorter string starting at index 1 and ending at > second last index (up to but not including index-1 > -restart the while loop as long as length of string is > 1 > - exiting this loop means all compared chars were identical hence it > is a palindrome and i return True > > tnx > Baba > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Aug 27 05:33:15 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Aug 2010 11:33:15 +0200 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Baba wrote: > level: beginner > > the following code looks ok to me but it doesn't work. I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] > return True Do yourself a favour and use 4-space indent. That makes the structure of your code more obvious. > print i_palindrome('annab') > > > my reasoning: > - i check the length of the string: if > 1 continue > - i check first and last char: if they are equal continue > - create a new, shorter string starting at index 1 and ending at > second last index (up to but not including index-1 > -restart the while loop as long as length of string is > 1 > - exiting this loop means all compared chars were identical hence it > is a palindrome and i return True If the test pal[0] == pal[-1] fails, i. e. the two compared characters differ, what happens? More generally, if pal is not a palindrome, can your function ever return False? If not, at what point should it? Peter From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 27 05:52:08 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Aug 2010 11:52:08 +0200 Subject: palindrome iteration In-Reply-To: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4c778ab6$0$4778$426a74cc@news.free.fr> Baba a ?crit : > level: beginner > > the following code looks ok to me but it doesn't work. "doesn't work" is about the most useless description of a problem. Please specify what you expected and what actually happens. > I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] Can you explain what happens if pal[0] != pal[-1] ? (answer below) > return True > print i_palindrome('annab') And then you go in an infinite loop !-) > > my reasoning: > - i check the length of the string: if > 1 continue > - i check first and last char: if they are equal continue > - create a new, shorter string starting at index 1 and ending at > second last index (up to but not including index-1 > -restart the while loop as long as length of string is > 1 > - exiting this loop means all compared chars were identical hence it > is a palindrome and i return True Your problem is that when first and last char are not equal, you don't exit the while loop. You need a "return False" somewhere here, ie: def is_palindrom(pal): while len(pal)>1: # NB : inverted the test here to make exit more obvious if pal[0] != pal[-1]: return False pal=pal[1:-1] return True Now there is another solution. A palindrom is made of two symetric halves, with (odd len) or without (even len) a single char between the symetric halves, ie : * odd : ABCBA ('AB' + 'C' + 'BA') * even : ABCCBA ('ABC' + 'CBA') So you just have to extract the symetric halves, reverse one, and compare both (case insensitive compare while we're at it). Here's a possible (and a bit tricky) Python 2.x implementation: def is_palindrom(s): s = s.lower() slen = len(s) until = slen / 2 # Python 2x integer division offset = int(not(slen % 2)) runtil = until - offset return s[0:until] == s[-1:runtil:-1] From arts.richard at gmail.com Fri Aug 27 06:40:01 2010 From: arts.richard at gmail.com (Richard Arts) Date: Fri, 27 Aug 2010 12:40:01 +0200 Subject: palindrome iteration In-Reply-To: <4c778ab6$0$4778$426a74cc@news.free.fr> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: > Now there is another solution. A palindrom is made of two symetric halves, > with (odd len) or without (even len) a single char between the symetric > halves, ie : > > * odd : ABCBA ('AB' + 'C' + 'BA') > * even : ABCCBA ('ABC' + 'CBA') > > So you just have to extract the symetric halves, reverse one, and compare > both (case insensitive compare while we're at it). Yes, this is a correct observation, but it is not necessary to compare the halves; Simply compare the complete string with its reverse. If they match, it is a palindrome. > Here's a possible (and a > bit tricky) Python 2.x implementation: > > def is_palindrom(s): > ? ?s = s.lower() > ? ?slen = len(s) > ? ?until = slen / 2 # Python 2x integer division > ? ?offset = int(not(slen % 2)) > ? ?runtil = until - offset > ? ?return s[0:until] == s[-1:runtil:-1] > > At first glance this seems to be correct, but it is tricky indeed. Particularly the assignment of the offset variable, casting a bool to an integer of a negated expression. Given that Baba notes that this is a beginners level query, it wouldn't have hurt to be a little bit more verbose there. Richard From stephan0h at yahoo.de Fri Aug 27 07:23:36 2010 From: stephan0h at yahoo.de (steph) Date: Fri, 27 Aug 2010 04:23:36 -0700 (PDT) Subject: pil and reportlab: image compression References: <0e89301b-2cb3-42fe-ba24-4018b5343c4d@v41g2000yqv.googlegroups.com> Message-ID: On 26 Aug., 13:16, steph wrote: > Hi group, > > I've written a small application that puts images into a pdf document. > It works ok, but my problem is that the pdf-files become quite huge, > bigger than the original jpegs. The problem seems to arise because I > use PIL to resize the pictures - and the images seem to get > uncompressed in the process. Unfortunately I have not found a way to > compress them again before rendering them to the pdf. Any clues? > > Thanks, > Stephan Solved this by writung to anonymous mmap. Works nicely :-) From landimatte at gmail.com Fri Aug 27 07:43:16 2010 From: landimatte at gmail.com (Matteo Landi) Date: Fri, 27 Aug 2010 13:43:16 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: > Yes, this is a correct observation, but it is not necessary to compare > the halves; Simply compare the complete string with its reverse. If > they match, it is a palindrome. I've always used to implement the is_palindrome function as you suggest, i.e. comparing the original string with the reverse one, but while reading, I tought about a imho nicer version which prevent from creating another string. Here are both the recursive/iterative versions of the function: def palindrome(str, i=0, j=-1): try: if str[i] == str[j]: return palindrome(str, i + 1, j - 1) return False except IndexError: return True def palindrome(str, i=0, j=-1): try: while True: if str[i] != str[j]: return False i, j = i + 1, j - 1 return True except IndexError: return True Regards, Matteo > >> Here's a possible (and a >> bit tricky) Python 2.x implementation: >> >> def is_palindrom(s): >> ? ?s = s.lower() >> ? ?slen = len(s) >> ? ?until = slen / 2 # Python 2x integer division >> ? ?offset = int(not(slen % 2)) >> ? ?runtil = until - offset >> ? ?return s[0:until] == s[-1:runtil:-1] >> >> > > At first glance this seems to be correct, but it is tricky indeed. > Particularly the assignment of the offset variable, casting a bool to > an integer of a negated expression. Given that Baba notes that this is > a beginners level query, it wouldn't have hurt to be a little bit more > verbose there. > > Richard > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From davea at ieee.org Fri Aug 27 09:14:02 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 27 Aug 2010 09:14:02 -0400 Subject: palindrome iteration In-Reply-To: <4c778ab6$0$4778$426a74cc@news.free.fr> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: <4C77BA1A.4040601@ieee.org> Bruno Desthuilliers wrote: >
Baba a > ?crit : >> level: beginner >> >> the following code looks ok to me but it doesn't work. > > "doesn't work" is about the most useless description of a problem. > Please specify what you expected and what actually happens. > >> I would like >> some hints as to where my reasoning / thought goes wrong >> >> def i_palindrome(pal): >> while len(pal)>1: >> if pal[0] == pal[-1]: >> pal=pal[1:-1] > > Can you explain what happens if pal[0] != pal[-1] ? (answer below) > >> return True > >> print i_palindrome('annab') > > And then you go in an infinite loop !-) > >> >> my reasoning: >> - i check the length of the string: if > 1 continue >> - i check first and last char: if they are equal continue >> - create a new, shorter string starting at index 1 and ending at >> second last index (up to but not including index-1 >> -restart the while loop as long as length of string is > 1 >> - exiting this loop means all compared chars were identical hence it >> is a palindrome and i return True > > Your problem is that when first and last char are not equal, you don't > exit the while loop. You need a "return False" somewhere here, ie: > > def is_palindrom(pal): > while len(pal)>1: > # NB : inverted the test here to make exit more obvious > if pal[0] != pal[-1]: > return False > pal=pal[1:-1] > return True > > > Now there is another solution. A palindrom is made of two symetric > halves, with (odd len) or without (even len) a single char between the > symetric halves, ie : > > * odd : ABCBA ('AB' + 'C' + 'BA') > * even : ABCCBA ('ABC' + 'CBA') > > So you just have to extract the symetric halves, reverse one, and > compare both (case insensitive compare while we're at it). Here's a > possible (and a bit tricky) Python 2.x implementation: > > def is_palindrom(s): > s = s.lower() > slen = len(s) > until = slen / 2 # Python 2x integer division > offset = int(not(slen % 2)) > runtil = until - offset > return s[0:until] == s[-1:runtil:-1] > > or (untested) def is_palindrom(s): s = s.lower() return s == s[::-1] DaveA From bryanjugglercryptographer at yahoo.com Fri Aug 27 09:53:30 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Fri, 27 Aug 2010 06:53:30 -0700 (PDT) Subject: Writing byte stream as jpeg format to disk References: <526CA2D6-4260-4E8B-854C-2A26583F3D98@gmail.com> <4C76C85C.7030505@ieee.org> <5B0A982D-B05F-46C1-A35F-CD7C90A23B37@gmail.com> <4C76CE29.8080507@mrabarnett.plus.com> <6dd639c4-f5e0-4df8-8816-9cad28ae2460@q40g2000prg.googlegroups.com> Message-ID: <09ef926c-6622-41c3-a303-f33782f087fe@u4g2000prn.googlegroups.com> Nobody wrote: > Bryan wrote: > > this is a case where we might want to be better > > than correct. BaseHTTPRequestHandler in the Python standard library > > accommodates clients that incorrectly omit the '\r' and end header lines > > with just '\n'. Such apps have been seen in the wild. Since bare '\n' > > never appears in correctly formed HTTP headers, interpreting it as > > equivalent to '\r\n' doesn't break anything. > > Yes it does. It breaks upstream filtering rules which are intended to > prohibit, remove or modify certain headers. > > This class of attack is known as "HTTP request smuggling". By > appending a header preceded by a bare '\r' or '\n' to the end of > another header, the header can be "smuggled" past a filter which > parses headers using the correct syntax, How does a bare '\r' or '\n' get past a filter which parses headers using the correct syntax? I don't see where the correct syntax of the HTTP protocol allows that. > but will still be treated as a > header by software which incorrectly parses headers using bare '\r' or > '\n' as separators. Why blame software that incorrectly accepts '\n' as a line break, and not the filter that incorrectly accepted '\n' in the middle of a header? Both are accepting incorrect syntax, but only the former has good reason to do so. > The safest solution would be to simply reject any request (or response) > which contains bare '\r' or '\n' characters within headers, at least by > default. Force the programmer to read the documentation (where the risks > would be described) if they want the "fault tolerant" behaviour. The Internet has a tradition of protocols above the transport level being readable by eye and writable by hand. The result has been quick development, but many mistakes that can induce unforeseen consequences. This case is somewhat subtle. Within a text entity-body, HTTP allows any one of the three end-of-line delimiters. That's just the body; the header portion is more rigid. In HTTP 1.0: "This flexibility regarding line breaks applies only to text media in the Entity-Body; a bare CR or LF should not be substituted for CRLF within any of the HTTP control structures (such as header fields and multipart boundaries)." -- RFC 1945 While in HTTP 1.1: "This flexibility regarding line breaks applies only to text media in the entity-body; a bare CR or LF MUST NOT be substituted for CRLF within any of the HTTP control structures (such as header fields and multipart boundaries)." -- RFC 2616 Note the change from "should not" to "MUST NOT". In reality our code might be called upon to work with apps that botch the technically- correct HTTP end-of-line marker. Rejecting bare '\n' may be safe from a technical security perspective, but if our safe code breaks a previously working system, then it will appear in a bug database and not in production. 'Nobody' makes a fair point. I'd love to see Internet protocols defined with mechanical rigor. Our discipline commonly specifies programming language syntax formally, and Internet protocols are syntactically simpler than programming languages. For now, HTTP is a bit of a mess, so write it absolutely correctly but read it a bit flexibly. From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 27 10:41:28 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Aug 2010 16:41:28 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: <4c77ce84$0$20290$426a74cc@news.free.fr> Richard Arts a ?crit : >> Now there is another solution. A palindrom is made of two symetric halves, >> with (odd len) or without (even len) a single char between the symetric >> halves, ie : >> >> * odd : ABCBA ('AB' + 'C' + 'BA') >> * even : ABCCBA ('ABC' + 'CBA') >> >> So you just have to extract the symetric halves, reverse one, and compare >> both (case insensitive compare while we're at it). > > Yes, this is a correct observation, but it is not necessary to compare > the halves; Simply compare the complete string with its reverse. If > they match, it is a palindrome. Duh :( I kinda feel stupid right now, thanks Richard :-/ From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 27 10:43:16 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Aug 2010 16:43:16 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> Message-ID: <4c77cef1$0$20290$426a74cc@news.free.fr> Dave Angel a ?crit : (snip) > or (untested) > def is_palindrom(s): > s = s.lower() > return s == s[::-1] > Right, go on, make me feel a bit more stupid :-/ Who's next ? From aahz at pythoncraft.com Fri Aug 27 11:03:53 2010 From: aahz at pythoncraft.com (Aahz) Date: 27 Aug 2010 08:03:53 -0700 Subject: Confused: Newbie Function Calls References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> Message-ID: In article <2dd74ab4-5ed6-40ac-aea7-705977b61b21 at g21g2000prn.googlegroups.com>, fuglyducky wrote: > >I am a complete newbie to Python (and programming in general) and I >have no idea what I'm missing. Below is a script that I am trying to >work with and I cannot get it to work. Side note: while it's fine to ask newbie questions on comp.lang.python, you may want to use resources oriented more toward newbies, such as the tutor list: http://www.python.org/about/help/ http://www.python.org/mailman/listinfo/tutor -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From darcy at druid.net Fri Aug 27 11:49:42 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 27 Aug 2010 11:49:42 -0400 Subject: palindrome iteration In-Reply-To: <4c77cef1$0$20290$426a74cc@news.free.fr> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> Message-ID: <20100827114942.0b1210cd.darcy@druid.net> On Fri, 27 Aug 2010 16:43:16 +0200 Bruno Desthuilliers wrote: > Dave Angel a ?crit : > > def is_palindrom(s): > > s = s.lower() > > return s == s[::-1] > > > Right, go on, make me feel a bit more stupid :-/ > Who's next ? How about a one-liner? is_palindrome = lambda x: len(x)> 0 and x == x.lower()[::-1] Note that the above assumes that single characters are palindromes but empty strings are not. I'm not 100% sure that that last is true. If not then this can be simplified. is_palindrome = lambda x: x == x.lower()[::-1] -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Fri Aug 27 12:02:39 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 27 Aug 2010 12:02:39 -0400 Subject: palindrome iteration In-Reply-To: <20100827114942.0b1210cd.darcy@druid.net> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> <20100827114942.0b1210cd.darcy@druid.net> Message-ID: <20100827120239.5a0b2396.darcy@druid.net> On Fri, 27 Aug 2010 11:49:42 -0400 "D'Arcy J.M. Cain" wrote: > is_palindrome = lambda x: x == x.lower()[::-1] Oops. Simple and wrong. is_palindrome = lambda x: x.lower() == x.lower()[::-1] -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From aahz at pythoncraft.com Fri Aug 27 12:16:52 2010 From: aahz at pythoncraft.com (Aahz) Date: 27 Aug 2010 09:16:52 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: In article , MRAB wrote: > >An object will be available for garbage collection when nothing refers >to it either directly or indirectly. If it's unreferenced then it will >go away. This isn't actually garbage collection as most people think of it. Refcounting semantics mean that objects get reaped as soon as nothing points at them. OTOH, CPython does also have garbage collection to back up refcounting so that when you have unreferenced object cycles they don't stay around. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From breamoreboy at yahoo.co.uk Fri Aug 27 12:20:30 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 27 Aug 2010 17:20:30 +0100 Subject: palindrome iteration In-Reply-To: <4c77cef1$0$20290$426a74cc@news.free.fr> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> Message-ID: On 27/08/2010 15:43, Bruno Desthuilliers wrote: > Dave Angel a ?crit : > (snip) > >> or (untested) >> def is_palindrom(s): >> s = s.lower() >> return s == s[::-1] >> > > > Right, go on, make me feel a bit more stupid :-/ > Who's next ? It could be worse, try responding to issue 9702. :) Cheers. Mark Lawrence. From ms18817 at googlemail.com Fri Aug 27 12:28:21 2010 From: ms18817 at googlemail.com (marianne rosen) Date: Fri, 27 Aug 2010 09:28:21 -0700 (PDT) Subject: layer geld verdienen , leicht geldverdienen , wie kann ich onlinespiele geld gewinnen , geldgewinnspiele , zu geld machen , geld machen beim , pennergame geld verdienen , schnell geld vedienen , ohne geld online , geld mit online casino , * * * + Message-ID: layer geld verdienen , leicht geldverdienen , wie kann ich onlinespiele geld gewinnen , geldgewinnspiele , zu geld machen , geld machen beim , pennergame geld verdienen , schnell geld vedienen , ohne geld online , geld mit online casino , * * * +++ SOFORT GEWINN +++ REICH WERDEN +++ * http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET http://WWW.SOFORT-GEWINN-JETZT-1.NET * * * ich will bargeld gewinn leicht viel geld verdienen wie kann ich online casino geld gewinnen wo kann ich geld am pc verdienen schnell geld verdienen im internet man mit dem internet geld schnell geld verdienen ohne internet viel geld verdienen drakensang geld machen uploads geld verdienen internet noch geld geld im internet forum geld verdienen durch internet ws schnell sofort geld gewinnen shop geld verdienen wie kann ich geld gewinnen bei mann schnell geld machen man leicht geld texte schreiben geld verdienen mit internet geld machen geld verdienen leicht gemacht wo kann ich geld gewinn spiel eigenen fotos geld verdienen kann man geld gewinnen pennergame geld machen einfach online geld verdienen wo kann ich geld am pc verdienen ich schnelles geld machen werbung internet geld geld verdienen im internet forum kann man online geld verdienen gewinnspiel gewinnen jetzt sofort mann geld machen schnell und legal geld verdienen online um echtes geld spielen sofort geld gewonnen wie kann ich geld gewinnen bei internet leicht geld uploaded to geld verdienen leichtes geld verdienen From hobson42 at gmaiil.com Fri Aug 27 12:37:36 2010 From: hobson42 at gmaiil.com (Ian) Date: Fri, 27 Aug 2010 17:37:36 +0100 Subject: palindrome iteration In-Reply-To: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4C77E9D0.5070401@gmaiil.com> On 27/08/2010 09:53, Baba wrote: > level: beginner > > the following code looks ok to me but it doesn't work. I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] > return True > > print i_palindrome('annab') > If you want to or must do it recursively. (Shown in pseudo code to make the logic clearer) def isPalindrome(pal) ''' test pal (a list) is a palindrome ''' if length of pal = 1 return True # all one letter strings are palindromes. if first equals last # pal could be a palindrome # so test inner part p = pal with first and last removed return isPalendrome(p) # and true - implied else return False # it can't be Of course, the simpler way is to use the definition of a Palindrome as the same backwards and forwards. def isPalindrome(pal) return pal == pal.reverse From justpark78 at gmail.com Fri Aug 27 12:40:03 2010 From: justpark78 at gmail.com (justin) Date: Fri, 27 Aug 2010 09:40:03 -0700 (PDT) Subject: numpy is not installed with Python2. Message-ID: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> My university has a cluster computer, on which I want to run my python program that uses numpy. I am installing my Python2.7 locally separated from the main system, and trying to install numpy, attach it with Python2.7. I used many different versions of numpys to make it happen, but I got stuck with the same following error on every trial, "[hp6 at login1 numpy]$ python2.7 setup.py install Running from numpy source directory.Traceback (most recent call last): File "setup.py", line 210, in setup_package() File "setup.py", line 187, in setup_package from numpy.distutils.core import setup File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in from numpy.distutils.command import config, config_compiler, \ File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", line 9, in from distutils.command.build_ext import build_ext as old_build_ext File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ build_ext.py", line 13, in from site import USER_BASE, USER_SITE ImportError: cannot import name USER_BASE" It seems the error is related to the inability of Python2.7 to process "from site import USER_BASE, USER_SITE", since the machine I succeeded to install numpy with Python2.7 doesn't prompt an error from this command, whereas this machine in which I failed to do so cannot handle this. My question is: How can I make Python2.7 to process this, since the manual says this package is the one that's automatically turned on in startup. Thanks, Justin. From python at mrabarnett.plus.com Fri Aug 27 12:53:42 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 27 Aug 2010 17:53:42 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> Message-ID: <4C77ED96.7090306@mrabarnett.plus.com> On 27/08/2010 17:20, Mark Lawrence wrote: > On 27/08/2010 15:43, Bruno Desthuilliers wrote: >> Dave Angel a ?crit : >> (snip) >> >>> or (untested) >>> def is_palindrom(s): >>> s = s.lower() >>> return s == s[::-1] >>> >> >> >> Right, go on, make me feel a bit more stupid :-/ >> Who's next ? > > It could be worse, try responding to issue 9702. :) > As a wise man once said: Ay caramba! :-) From robert.kern at gmail.com Fri Aug 27 13:10:44 2010 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Aug 2010 12:10:44 -0500 Subject: numpy is not installed with Python2. In-Reply-To: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> References: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> Message-ID: On 8/27/10 11:40 AM, justin wrote: > My university has a cluster computer, on which I want to run my python > program that uses numpy. > I am installing my Python2.7 locally separated from the main system, > and trying to install numpy, attach it with Python2.7. > I used many different versions of numpys to make it happen, but I got > stuck with the same following error on every trial, > > "[hp6 at login1 numpy]$ python2.7 setup.py install > Running from numpy source directory.Traceback (most recent call last): > File "setup.py", line 210, in > setup_package() > File "setup.py", line 187, in setup_package > from numpy.distutils.core import setup > File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in > > from numpy.distutils.command import config, config_compiler, \ > File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", > line 9, in > from distutils.command.build_ext import build_ext as old_build_ext > File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ > build_ext.py", line 13, in > from site import USER_BASE, USER_SITE > ImportError: cannot import name USER_BASE" > > It seems the error is related to the inability of Python2.7 to process > "from site import USER_BASE, USER_SITE", > since the machine I succeeded to install numpy with Python2.7 doesn't > prompt an error from this command, > whereas this machine in which I failed to do so cannot handle this. Your Python installation appears to be broken. Find the site.py module that you are actually importing. I.e. from the numpy source directory: $ python2.7 -c "import site; print site.__file__" This will tell you the site.pyc file that actually gets imported. Find the associated site.py file (it should be in the same directory) and check to see if it has USER_BASE defined. The filename should be /users/hp6/apps/python27/lib/python2.7/site.pyc If it isn't, that may be the source of your problem. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From breamoreboy at yahoo.co.uk Fri Aug 27 13:28:06 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 27 Aug 2010 18:28:06 +0100 Subject: palindrome iteration In-Reply-To: <4C77ED96.7090306@mrabarnett.plus.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> <4C77ED96.7090306@mrabarnett.plus.com> Message-ID: On 27/08/2010 17:53, MRAB wrote: > On 27/08/2010 17:20, Mark Lawrence wrote: >> On 27/08/2010 15:43, Bruno Desthuilliers wrote: >>> Dave Angel a ?crit : >>> (snip) >>> >>>> or (untested) >>>> def is_palindrom(s): >>>> s = s.lower() >>>> return s == s[::-1] >>>> >>> >>> >>> Right, go on, make me feel a bit more stupid :-/ >>> Who's next ? >> >> It could be worse, try responding to issue 9702. :) >> > As a wise man once said: Ay caramba! :-) Isn't that a syntax error? Shouldn't it be ?Ay caramba! :) Cheers. Mark Lawrence. From tjreedy at udel.edu Fri Aug 27 13:39:08 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Aug 2010 13:39:08 -0400 Subject: palindrome iteration In-Reply-To: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: On 8/27/2010 4:53 AM, Baba wrote: > level: beginner > > the following code looks ok to me but it doesn't work. I would like > some hints as to where my reasoning / thought goes wrong > > def i_palindrome(pal): > while len(pal)>1: > if pal[0] == pal[-1]: > pal=pal[1:-1] > return True > > print i_palindrome('annab') General practical debugging procedurewhen logic inspection fails: insert print statements at key points. In the case above, put "print pal" before the if statement and you should see the problem. And/or "print 'equal'" after the if. -- Terry Jan Reedy From python at mrabarnett.plus.com Fri Aug 27 13:46:56 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 27 Aug 2010 18:46:56 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> <4C77ED96.7090306@mrabarnett.plus.com> Message-ID: <4C77FA10.6040505@mrabarnett.plus.com> On 27/08/2010 18:28, Mark Lawrence wrote: > On 27/08/2010 17:53, MRAB wrote: >> On 27/08/2010 17:20, Mark Lawrence wrote: >>> On 27/08/2010 15:43, Bruno Desthuilliers wrote: >>>> Dave Angel a ?crit : >>>> (snip) >>>> >>>>> or (untested) >>>>> def is_palindrom(s): >>>>> s = s.lower() >>>>> return s == s[::-1] >>>>> >>>> >>>> >>>> Right, go on, make me feel a bit more stupid :-/ >>>> Who's next ? >>> >>> It could be worse, try responding to issue 9702. :) >>> >> As a wise man once said: Ay caramba! :-) > > Isn't that a syntax error? Shouldn't it be ?Ay caramba! :) > I stand (OK, sit) corrected. From jpiitula at ling.helsinki.fi Fri Aug 27 14:05:55 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 27 Aug 2010 21:05:55 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Ian writes: > If you want to or must do it recursively. > (Shown in pseudo code to make the logic clearer) > > def isPalindrome(pal) > ''' test pal (a list) is a palindrome ''' > if length of pal = 1 > return True # all one letter strings are palindromes. > if first equals last > # pal could be a palindrome > # so test inner part > p = pal with first and last removed > return isPalendrome(p) # and true - implied > else > return False # it can't be def palindromep(s): return ( s == "" or ( s[0] == s[-1] and palindromep(s[1:-1]) ) ) > Of course, the simpler way is to use the definition of a Palindrome > as the same backwards and forwards. > > def isPalindrome(pal) > return pal == pal.reverse Agreed. But is there any nicer way to spell .reverse than [::-1] in Python? There is .swapcase() but no .reverse(), right? From chrisj at puffin.com Fri Aug 27 14:22:51 2010 From: chrisj at puffin.com (Chris Jewell) Date: Fri, 27 Aug 2010 11:22:51 -0700 Subject: mailbox.mbox not locking mbox properly References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: <7rtymfrk3o.fsf@pileated.puffin.com> Even if you replace the python mbox code with something that uses fcntl.flock() to protect against concurrent updating, you should also understand that NFS does *not* provide full Unix filesystem semantics. In particular, Unix flock(2) (which Python's fcntl.flock() wraps) doesn't work over NFS. That's why if you want to access mail over NFS, you should use maildir, rather than mbox, no matter what your programming language. -- Chris Jewell chrisj at puffin.com PO Box 1396 Gualala CA USA 95445-1396 From justpark78 at gmail.com Fri Aug 27 14:38:56 2010 From: justpark78 at gmail.com (justin) Date: Fri, 27 Aug 2010 11:38:56 -0700 (PDT) Subject: numpy is not installed with Python2. References: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> Message-ID: On Aug 27, 12:10?pm, Robert Kern wrote: > On 8/27/10 11:40 AM, justin wrote: > > > > > > > My university has a cluster computer, on which I want to run my python > > program that uses numpy. > > I am installing my Python2.7 locally separated from the main system, > > and trying to install numpy, attach it with Python2.7. > > I used many different versions of numpys to make it happen, but I got > > stuck with the same following error on every trial, > > > "[hp6 at login1 numpy]$ python2.7 setup.py install > > Running from numpy source directory.Traceback (most recent call last): > > ? ?File "setup.py", line 210, in > > ? ? ?setup_package() > > ? ?File "setup.py", line 187, in setup_package > > ? ? ?from numpy.distutils.core import setup > > ? ?File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in > > > > ? ? ?from numpy.distutils.command import config, config_compiler, \ > > ? ?File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", > > line 9, in > > ? ? ?from distutils.command.build_ext import build_ext as old_build_ext > > ? ?File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ > > build_ext.py", line 13, in > > ? ? ?from site import USER_BASE, USER_SITE > > ImportError: cannot import name USER_BASE" > > > It seems the error is related to the inability of Python2.7 to process > > "from site import USER_BASE, USER_SITE", > > since the machine I succeeded to install numpy with Python2.7 doesn't > > prompt an error from this command, > > whereas this machine in which I failed to do so cannot handle this. > > Your Python installation appears to be broken. Find the site.py module that you > are actually importing. I.e. from the numpy source directory: > > ? ?$ python2.7 -c "import site; print site.__file__" > > This will tell you the site.pyc file that actually gets imported. Find the > associated site.py file (it should be in the same directory) and check to see if > it has USER_BASE defined. The filename should be > > ? ?/users/hp6/apps/python27/lib/python2.7/site.pyc > > If it isn't, that may be the source of your problem. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco Dear Kern, Thanks a lot. Your quick and detailed comment saves me a lot of time and effort now. It seems the file path links are out of order as you diagnosed. Like you said, there is a site.py on /users/hp6/apps/python27/lib/ python2.7/. But when I typed in "$ python2.7 -c "import site; print site.__file__", it refers to another place: "/opt/apps/gurobi/3.0.0/linux64/lib/python2.5/site.pyc", and it doesn't have USER_BASE! So I changed the value of PYTHONPATH accordingly. Thanks again, Justin. From davea at ieee.org Fri Aug 27 15:15:25 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 27 Aug 2010 15:15:25 -0400 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4C780ECD.8010204@ieee.org> Jussi Piitulainen wrote: > Ian writes: > > >> If you want to or must do it recursively. >> (Shown in pseudo code to make the logic clearer) >> >> def isPalindrome(pal) >> ''' test pal (a list) is a palindrome ''' >> if length of pal = 1 >> return True # all one letter strings are palindromes. >> if first equals last >> # pal could be a palindrome >> # so test inner part >> p = pal with first and last removed >> return isPalendrome(p) # and true - implied >> else >> return False # it can't be >> > > def palindromep(s): > return ( s == "" or > ( s[0] == s[-1] and > palindromep(s[1:-1]) ) ) > > >> Of course, the simpler way is to use the definition of a Palindrome >> as the same backwards and forwards. >> >> def isPalindrome(pal) >> return pal == pal.reverse >> > > Agreed. But is there any nicer way to spell .reverse than [::-1] in > Python? There is .swapcase() but no .reverse(), right? > > There can't be a .reverse() method on string, because it's immutable. You could use "".join(reversed(pal)) but I'd prefer pal[::-1] as I said earlier. DaveA From jdixon at omniti.com Fri Aug 27 15:34:20 2010 From: jdixon at omniti.com (Jason Dixon) Date: Fri, 27 Aug 2010 15:34:20 -0400 Subject: Surge 2010 Early Registration ends Tuesday! Message-ID: <20100827193420.GN1736@omniti.com> Early Bird Registration for Surge Scalability Conference 2010 ends next Tuesday, August 31. We have a killer lineup of speakers and architects from across the Internet. Listen to experts talk about the newest methods and technologies for scaling your Web presence. http://omniti.com/surge/2010/register This year's event is all about the challenges faced (and overcome) in real-life production architectures. Meet the engineering talent from some of the best and brightest throughout the Internet: John Allspaw, Etsy Theo Schlossnagle, OmniTI Bryan Cantrill, Joyent Rasmus Lerdorf, creator of PHP Tom Cook, Facebook Benjamin Black, fast_ip Christopher Brown, Opscode Artur Bergman, Wikia Baron Schwartz, Percona Paul Querna, Cloudkick Surge 2010 takes place at the Tremont Grand Historic Venue on Sept 30 and Oct 1, 2010 in Baltimore, MD. Register NOW for the Early Bird discount and guarantee your seat to this year's event! -- Jason Dixon OmniTI Computer Consulting, Inc. jdixon at omniti.com 443.325.1357 x.241 From robert.kern at gmail.com Fri Aug 27 15:37:40 2010 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Aug 2010 14:37:40 -0500 Subject: numpy is not installed with Python2. In-Reply-To: References: <0e763657-06d3-4a39-ae0b-a21938ba93d4@5g2000yqz.googlegroups.com> Message-ID: On 8/27/10 1:38 PM, justin wrote: > On Aug 27, 12:10 pm, Robert Kern wrote: >> On 8/27/10 11:40 AM, justin wrote: >> >> >> >> >> >>> My university has a cluster computer, on which I want to run my python >>> program that uses numpy. >>> I am installing my Python2.7 locally separated from the main system, >>> and trying to install numpy, attach it with Python2.7. >>> I used many different versions of numpys to make it happen, but I got >>> stuck with the same following error on every trial, >> >>> "[hp6 at login1 numpy]$ python2.7 setup.py install >>> Running from numpy source directory.Traceback (most recent call last): >>> File "setup.py", line 210, in >>> setup_package() >>> File "setup.py", line 187, in setup_package >>> from numpy.distutils.core import setup >>> File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in >>> >>> from numpy.distutils.command import config, config_compiler, \ >>> File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", >>> line 9, in >>> from distutils.command.build_ext import build_ext as old_build_ext >>> File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ >>> build_ext.py", line 13, in >>> from site import USER_BASE, USER_SITE >>> ImportError: cannot import name USER_BASE" >> >>> It seems the error is related to the inability of Python2.7 to process >>> "from site import USER_BASE, USER_SITE", >>> since the machine I succeeded to install numpy with Python2.7 doesn't >>> prompt an error from this command, >>> whereas this machine in which I failed to do so cannot handle this. >> >> Your Python installation appears to be broken. Find the site.py module that you >> are actually importing. I.e. from the numpy source directory: >> >> $ python2.7 -c "import site; print site.__file__" >> >> This will tell you the site.pyc file that actually gets imported. Find the >> associated site.py file (it should be in the same directory) and check to see if >> it has USER_BASE defined. The filename should be >> >> /users/hp6/apps/python27/lib/python2.7/site.pyc >> >> If it isn't, that may be the source of your problem. >> >> -- >> Robert Kern >> >> "I have come to believe that the whole world is an enigma, a harmless enigma >> that is made terrible by our own mad attempt to interpret it as though it had >> an underlying truth." >> -- Umberto Eco > > Dear Kern, > > Thanks a lot. > Your quick and detailed comment saves me a lot of time and effort > now. > > It seems the file path links are out of order as you diagnosed. > Like you said, there is a site.py on /users/hp6/apps/python27/lib/ > python2.7/. > But when I typed in "$ python2.7 -c "import site; print > site.__file__", it refers to another place: > "/opt/apps/gurobi/3.0.0/linux64/lib/python2.5/site.pyc", and it > doesn't have USER_BASE! > > So I changed the value of PYTHONPATH accordingly. You should not set PYTHONPATH to those directories ever. The correct one will already be on the sys.path. In a multiple-Python environment, you simply shouldn't use PYTHONPATH at all since all of the interpreters will try to use it. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From darcy at druid.net Fri Aug 27 15:42:18 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 27 Aug 2010 15:42:18 -0400 Subject: palindrome iteration In-Reply-To: <20100827120239.5a0b2396.darcy@druid.net> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> <20100827114942.0b1210cd.darcy@druid.net> <20100827120239.5a0b2396.darcy@druid.net> Message-ID: <20100827154218.b8193916.darcy@druid.net> On Fri, 27 Aug 2010 12:02:39 -0400 "D'Arcy J.M. Cain" wrote: > On Fri, 27 Aug 2010 11:49:42 -0400 > "D'Arcy J.M. Cain" wrote: > > is_palindrome = lambda x: x == x.lower()[::-1] > > Oops. Simple and wrong. > > is_palindrome = lambda x: x.lower() == x.lower()[::-1] slightly more efficient I think. is_palindrome = lambda y: (lambda x: x == x[::-1])(y.lower()) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From jpiitula at ling.helsinki.fi Fri Aug 27 15:43:10 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 27 Aug 2010 22:43:10 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Dave Angel writes: > Jussi Piitulainen wrote: >> Ian writes: >>> Of course, the simpler way is to use the definition of a >>> Palindrome as the same backwards and forwards. >>> >>> def isPalindrome(pal) >>> return pal == pal.reverse >> >> Agreed. But is there any nicer way to spell .reverse than [::-1] in >> Python? There is .swapcase() but no .reverse(), right? >> > There can't be a .reverse() method on string, because it's > immutable. You could use > > "".join(reversed(pal)) > > but I'd prefer pal[::-1] as I said earlier. There could easily be a .reverse() method on strings. It would return the reversed string, like .swapcase() returns the swapcased string. From nagle at animats.com Fri Aug 27 15:57:42 2010 From: nagle at animats.com (John Nagle) Date: Fri, 27 Aug 2010 12:57:42 -0700 Subject: Queue cleanup In-Reply-To: <9b270554-e7cb-48ec-aa0e-c78690a81b54@q26g2000vbn.googlegroups.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39ulysnz.fsf@ruckus.brouhaha.com> <7xd3tpqaki.fsf@ruckus.brouhaha.com> <36556b36-b28e-40eb-bfd0-8fcb1824a165@c16g2000vbp.googlegroups.com> <7xvd7h2d90.fsf@ruckus.brouhaha.com> <9b270554-e7cb-48ec-aa0e-c78690a81b54@q26g2000vbn.googlegroups.com> Message-ID: <4c7818c5$0$1664$742ec2ed@news.sonic.net> On 8/11/2010 1:26 PM, EW wrote: > On Aug 11, 2:52 pm, Paul Rubin wrote: >> EW writes: >>> Well I cared because I thought garbage collection would only happen >>> when the script ended - the entire script. Since I plan on running >>> this as a service it'll run for months at a time without ending. So I >>> thought I was going to have heaps of Queues hanging out in memory, >>> unreferenced and unloved. It seemed like bad practice so I wanted to >>> get out ahead of it. >> >> Even if GC worked that way it wouldn't matter, if you use just one queue >> per type of task. That number should be a small constant so the memory >> consumption is small. > > Well I can't really explain it but 1 Queue per task for what I'm > designing just doesn't feel right to me. It feels like it will lack > future flexibility. I like having 1 Queue per producer thread object > and the person instantiating that object can do whatever he wants with > that Queue. I can't prove I'll need that level of flexibility but I > don't see why it' bad to have. It's still a small number of Queues, > it's just a small, variable, number of Queues. That's backwards. Usually, you want one queue per unique consumer. That is, if you have a queue that contains one kind of request, there's one thread reading the queue, blocked until some other thread puts something on the queue. No polling is needed. One consumer reading multiple queues is difficult to implement well. Note, by the way, that CPython isn't really concurrent. Only one thread runs at a time, due to an archaic implementation. So if your threads are compute-bound, even on a multicore CPU threading will not help. There's a "multiprocessing module" which allows spreading work over several processes instead of threads. That can be helpful as a workaround. John Nagle From nagle at animats.com Fri Aug 27 16:09:25 2010 From: nagle at animats.com (John Nagle) Date: Fri, 27 Aug 2010 13:09:25 -0700 Subject: mailbox.mbox not locking mbox properly In-Reply-To: References: <7u96j7-l8i.ln1@chris.zbmc.eu> Message-ID: <4c781b84$0$1619$742ec2ed@news.sonic.net> On 8/10/2010 2:25 AM, Chris Rebert wrote: > On Tue, Aug 10, 2010 at 2:01 AM, wrote: >> Tim Roberts wrote: >>> tinnews at isbd.co.uk wrote: >>>> >>>> I'm using the python mailbox class in a script that processes incoming >>>> mail and delivers it to various mbox format mailboxes. It appears >>>> that, although I am calling the lock method on the destination before >>>> writing to the mbox and calling unlock afterwards the locking isn't >>>> working correctly. >>>> ... >>>> So it seems that python's mailbox class locking isn't playing nicely >>>> with mutt's mailbox locking whereas postfix's locking does work >>>> correctly. >>> >>> Correct. The "dest.flush()" method creates a temporary file, copies the >>> entire modified mailbox into it, removed the original file, and renames the >>> temp file into place. >>> >> Yes, I just took a look at the mailbox.py code and it does exactly >> that which of course screws up just about any normal MUA looking at >> the mbox. Grrrrrr! >> >> >>> The Postfix MDA, like most MDAs, just opens the existing file and appends >>> the new data to it. >>> >>>> Has anyone seen this problem before, and/or do I need to anything more >>>> than the following for the locking to work correctly:- >>> >>> It's not the locking. It's the flush mechanism. The mbox class doesn't >>> know that the ONLY thing you did was an append. You might have modified >>> other messages in the middle. If you want to do an append, you'll need to >>> write your own subclass of mbox. >> >> OK, thanks. In reality I can probably just use straightforward file >> reading and writing as the *only* thing I will ever be doing is to >> append a message to a mailbox file. >> >> I think there should be a big warning in the mailbox documentation to >> this effect as doing it the way that Python's mailbox class does it >> will break all sorts of things. There should maybe be a specific >> 'append' method. > > File a documentation and/or library bug: > http://bugs.python.org/ > > Cheers, > Chris From python at mrabarnett.plus.com Fri Aug 27 16:14:44 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 27 Aug 2010 21:14:44 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4C781CB4.5080108@mrabarnett.plus.com> On 27/08/2010 20:43, Jussi Piitulainen wrote: > Dave Angel writes: > >> Jussi Piitulainen wrote: >>> Ian writes: >>>> Of course, the simpler way is to use the definition of a >>>> Palindrome as the same backwards and forwards. >>>> >>>> def isPalindrome(pal) >>>> return pal == pal.reverse >>> >>> Agreed. But is there any nicer way to spell .reverse than [::-1] in >>> Python? There is .swapcase() but no .reverse(), right? >>> >> There can't be a .reverse() method on string, because it's >> immutable. You could use >> >> "".join(reversed(pal)) >> >> but I'd prefer pal[::-1] as I said earlier. > > There could easily be a .reverse() method on strings. It would return > the reversed string, like .swapcase() returns the swapcased string. Lists have a .reverse method, but it's an in-place reversal. In order to reduce confusion, a string method which returned the string reversed would be better called .reversed(). From jpiitula at ling.helsinki.fi Fri Aug 27 16:51:17 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 27 Aug 2010 23:51:17 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: MRAB writes: > On 27/08/2010 20:43, Jussi Piitulainen wrote: >> Dave Angel writes: >>> Jussi Piitulainen wrote: >>>> Agreed. But is there any nicer way to spell .reverse than [::-1] >>>> in Python? There is .swapcase() but no .reverse(), right? >>>> >>> There can't be a .reverse() method on string, because it's >>> immutable. You could use >>> >>> "".join(reversed(pal)) >>> >>> but I'd prefer pal[::-1] as I said earlier. >> >> There could easily be a .reverse() method on strings. It would >> return the reversed string, like .swapcase() returns the swapcased >> string. > > Lists have a .reverse method, but it's an in-place reversal. In > order to reduce confusion, a string method which returned the string > reversed would be better called .reversed(). Yes, agreed. Meanwhile, I have decided to prefer this: def palindromep(s): def reversed(s): return s[::-1] return s == reversed(s) From tjreedy at udel.edu Fri Aug 27 17:41:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Aug 2010 17:41:07 -0400 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: > Dave Angel writes: > There could easily be a .reverse() method on strings. It would return > the reversed string, like .swapcase() returns the swapcased string. Could be, but the main use case seems to be for palindrome testing ;-) Given that slicing and reversed() can do the same thing, the need is thin. -- Terry Jan Reedy From arts.richard at gmail.com Fri Aug 27 17:47:26 2010 From: arts.richard at gmail.com (Richard Arts) Date: Fri, 27 Aug 2010 23:47:26 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: On Fri, Aug 27, 2010 at 10:51 PM, Jussi Piitulainen wrote: > MRAB writes: >> On 27/08/2010 20:43, Jussi Piitulainen wrote: >>> Dave Angel writes: >>>> Jussi Piitulainen wrote: >>>>> Agreed. But is there any nicer way to spell .reverse than [::-1] >>>>> in Python? There is .swapcase() but no .reverse(), right? >>>>> >>>> There can't be a .reverse() method on string, because it's >>>> immutable. You could use >>>> >>>> ? ? ?"".join(reversed(pal)) >>>> >>>> but I'd prefer ?pal[::-1] ?as I said earlier. >>> >>> There could easily be a .reverse() method on strings. It would >>> return the reversed string, like .swapcase() returns the swapcased >>> string. >> >> Lists have a .reverse method, but it's an in-place reversal. In >> order to reduce confusion, a string method which returned the string >> reversed would be better called .reversed(). > > Yes, agreed. > > Meanwhile, I have decided to prefer this: > > def palindromep(s): > ? ?def reversed(s): > ? ? ? ?return s[::-1] > ? ?return s == reversed(s) > -- > http://mail.python.org/mailman/listinfo/python-list > That seems like a bit of overkill... Why would you want to define a function in a function for something trivial like this? Just def palindrome(s): return s[::-1] will do fine. Of course, you can stick the inner function in a library somewhere if you like. Regards, Richard From arts.richard at gmail.com Fri Aug 27 17:52:39 2010 From: arts.richard at gmail.com (Richard Arts) Date: Fri, 27 Aug 2010 23:52:39 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: On Fri, Aug 27, 2010 at 11:47 PM, Richard Arts wrote: > On Fri, Aug 27, 2010 at 10:51 PM, Jussi Piitulainen > wrote: >> MRAB writes: >>> On 27/08/2010 20:43, Jussi Piitulainen wrote: >>>> Dave Angel writes: >>>>> Jussi Piitulainen wrote: >>>>>> Agreed. But is there any nicer way to spell .reverse than [::-1] >>>>>> in Python? There is .swapcase() but no .reverse(), right? >>>>>> >>>>> There can't be a .reverse() method on string, because it's >>>>> immutable. You could use >>>>> >>>>> ? ? ?"".join(reversed(pal)) >>>>> >>>>> but I'd prefer ?pal[::-1] ?as I said earlier. >>>> >>>> There could easily be a .reverse() method on strings. It would >>>> return the reversed string, like .swapcase() returns the swapcased >>>> string. >>> >>> Lists have a .reverse method, but it's an in-place reversal. In >>> order to reduce confusion, a string method which returned the string >>> reversed would be better called .reversed(). >> >> Yes, agreed. >> >> Meanwhile, I have decided to prefer this: >> >> def palindromep(s): >> ? ?def reversed(s): >> ? ? ? ?return s[::-1] >> ? ?return s == reversed(s) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > That seems like a bit of overkill... Why would you want to define a > function in a function for something trivial like this? Just > > def palindrome(s): > ? ?return s[::-1] > > will do fine. > > Of course, you can stick the inner function in a library somewhere if you like. > > Regards, > Richard > Duh, of course I mean def palindrome(s): return s == s[::-1] I'm sorry. Richard From ldo at geek-central.gen.new_zealand Fri Aug 27 18:58:59 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 10:58:59 +1200 Subject: Writing byte stream as jpeg format to disk References: Message-ID: In message , Navkirat Singh wrote: > I receive a jpeg file with the POST method.The file (.jpeg) is encoded in > bytes, I parse the bytes by decoding them to a string. I wanted to know > how i could write the file (now a string) as a jpeg image on disk. I assume the JPEG data is received along with other field values in the POST. You?ll be saving those other fields in a database, right? So why not save the JPEG image there as well? From ldo at geek-central.gen.new_zealand Fri Aug 27 19:01:04 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 11:01:04 +1200 Subject: Writing byte stream as jpeg format to disk References: <874oeh2sdg.fsf@castleamber.com> Message-ID: In message , Navkirat Singh wrote: > The image bytes are a part of a HTTP header content ( not the message body > ). In which case, won?t they be in some encoding like Base-64? I don?t think you?re allowed arbitrary binary bytes in an HTTP header. From ldo at geek-central.gen.new_zealand Fri Aug 27 19:07:30 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 11:07:30 +1200 Subject: Reading the access attributes of directories in Windows References: Message-ID: In message , Rami Chowdhury wrote: > On Wed, Aug 25, 2010 at 05:04, Lawrence D'Oliveiro > wrote: > >> In message , Nobody wrote: >> >>> Having this as a separate permission allows normal users to add entries >>> to log files but not to erase existing entries. >> >> Unix/Linux systems can do this already. > > Ooh, I didn't know that -- what combination of permissions would I > have to use to get such an effect? No special permissions needed at all?just use the syslog(3) functions. And the nice thing is, you don?t have to know whether the system logs are kept on the local machine or on a remote machine, or how different categories of messages are divided up into different files, how log rotation is done, or anything like that?it?s all transparent. From robert.kern at gmail.com Fri Aug 27 19:14:05 2010 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Aug 2010 18:14:05 -0500 Subject: Writing byte stream as jpeg format to disk In-Reply-To: References: Message-ID: On 8/27/10 5:58 PM, Lawrence D'Oliveiro wrote: > In message > , Navkirat Singh wrote: > >> I receive a jpeg file with the POST method.The file (.jpeg) is encoded in >> bytes, I parse the bytes by decoding them to a string. I wanted to know >> how i could write the file (now a string) as a jpeg image on disk. > > I assume the JPEG data is received along with other field values in the > POST. You?ll be saving those other fields in a database, right? So why not > save the JPEG image there as well? No, the only thing in the body of the POST are the bytes of the JPEG. He was incorrect in thinking that the JPEG data was arriving in the header. See the later posts in the thread for complete answers to his problem. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sridharr at activestate.com Fri Aug 27 19:24:36 2010 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Fri, 27 Aug 2010 16:24:36 -0700 Subject: ANN: ActivePython 2.6.6.15 is now available Message-ID: <4C784934.6090809@activestate.com> ActiveState is pleased to announce ActivePython 2.6.6.15, a complete, ready-to-install binary distribution of Python 2.6.6. http://www.activestate.com/activepython What's New in ActivePython-2.6.6.15 =================================== *Release date: 25-Aug-2010* New Features & Upgrades ----------------------- - Upgrade to Python 2.6.6 (`release notes `__) - Security upgrade to openssl-0.9.8o - [MacOSX] 64-bit support (PPC and 10.4 are no longer supported) - Upgrade to PyPM 1.1.1; noteworthy changes: - Custom config file support w/ new repository settings (-R free,be instead of -L) - Support for installing a local package, eg: ``pypm install /path/to/foo.pypm`` - Bug #87687: Prevent partial downloading of repo index cache - Upgraded the following packages: - Distribute-0.6.14 - pip-0.8 - SQLAlchemy-0.6.3 Noteworthy Changes & Bug Fixes ------------------------------ - [MacOSX] Fix Help index on Snow Leopard (10.6) - Bug #87290 - [Windows] Add file extension to Tools\scripts\2to3.py - Bug #87465 What's New in ActivePython-2.6.5.14 =================================== *Release date: 07-Jul-2010* New Features & Upgrades ----------------------- - Upgrade to PyPM 1.0.2 - 'pypm search' now also shows if a package is installed and upgradeable - 'pypm info' now prints a concise representation by default - 'pypm list --short' will show only packages names; for scripting purposes - Respect distutils install schemes (purelib, scripts) Noteworthy Changes & Bug Fixes ------------------------------ - [MacOSX] Fix /usr/local/bin symlinks to not use the 'Current' symlink - [MacOSX] Fix uninstall on Snow Leopard (10.6) - [Windows] Include IDLE in the Start Menu shortcut, instead of PythonWin See the release notes for full details: http://docs.activestate.com/activepython/2.6/relnotes.html#changes What is ActivePython? ===================== ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and AIX builds, and access to older versions are available in ActivePython Business, Enterprise and OEM editions: http://www.activestate.com/python ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. ActivePython 2.6 and 2.7 also include a binary package manager for Python (PyPM) that can be used to install packages much easily. For example: C:\>pypm install mysql-python [...] C:\>python >>> import MySQLdb >>> See this page for full details: http://docs.activestate.com/activepython/2.6/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/2.6/ We would welcome any and all feedback to: activepython-feedback at activestate.com Please file bugs against ActivePython at: http://bugs.activestate.com/enter_bug.cgi?product=ActivePython Supported Platforms =================== ActivePython is available for the following platforms: - Windows/x86 (32-bit) - Windows/x64 (64-bit) (aka "AMD64") - Mac OS X - Linux/x86 (32-bit) - Linux/x86_64 (64-bit) (aka "AMD64") - Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) - Solaris/x86 (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/PA-RISC (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/IA-64 (32-bit and 64-bit) (Enterprise or OEM edition only) - AIX/PowerPC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) More information about the Business Edition can be found here: http://www.activestate.com/business-edition Custom builds are available in the Enterprise Edition: http://www.activestate.com/enterprise-edition Thanks, and enjoy! The Python Team -- Sridhar Ratnakumar sridharr at activestate.com From sridharr at activestate.com Fri Aug 27 19:29:20 2010 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Fri, 27 Aug 2010 16:29:20 -0700 Subject: ANN: ActivePython 2.7.0.2 is now available Message-ID: <4C784A50.5050608@activestate.com> ActiveState is pleased to announce ActivePython 2.7.0.2, a complete, ready-to-install binary distribution of Python 2.7. http://www.activestate.com/activepython What's New in ActivePython-2.7.0.2 ================================== *Release date: 25-Aug-2010* New Features & Upgrades ----------------------- - Security upgrade to openssl-0.9.8o - Upgrade to PyPM 1.1.1; noteworthy changes: - Custom config file support w/ new repository settings (-R free,be instead of -L) - Support for installing a local package, eg: ``pypm install /path/to/foo.pypm`` - Bug #87687: Prevent partial downloading of repo index cache - Upgraded the following packages: - Distribute-0.6.14 - pip-0.8 - SQLAlchemy-0.6.3 Noteworthy Changes & Bug Fixes ------------------------------ - [MacOSX] Fix Help index on Snow Leopard (10.6) - Bug #87290 - [Windows] Add file extension to Tools\scripts\2to3.py - Bug #87465 What is ActivePython? ===================== ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and AIX builds, and access to older versions are available in ActivePython Business, Enterprise and OEM editions: http://www.activestate.com/python ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. ActivePython 2.6 and 2.7 also include a binary package manager for Python (PyPM) that can be used to install packages much easily. For example: C:\>pypm install mysql-python [...] C:\>python >>> import MySQLdb >>> See this page for full details: http://docs.activestate.com/activepython/2.7/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/2.7/ We would welcome any and all feedback to: activepython-feedback at activestate.com Please file bugs against ActivePython at: http://bugs.activestate.com/enter_bug.cgi?product=ActivePython Supported Platforms =================== ActivePython is available for the following platforms: - Windows/x86 (32-bit) - Windows/x64 (64-bit) (aka "AMD64") - Mac OS X - Linux/x86 (32-bit) - Linux/x86_64 (64-bit) (aka "AMD64") - Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) - Solaris/x86 (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/PA-RISC (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/IA-64 (32-bit and 64-bit) (Enterprise or OEM edition only) - AIX/PowerPC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) More information about the Business Edition can be found here: http://www.activestate.com/business-edition Custom builds are available in the Enterprise Edition: http://www.activestate.com/enterprise-edition Thanks, and enjoy! The Python Team -- Sridhar Ratnakumar sridharr at activestate.com From ldo at geek-central.gen.new_zealand Fri Aug 27 19:49:35 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 11:49:35 +1200 Subject: ftplib limitations? References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74E604.6090208@sschwarzer.net> Message-ID: In message <4C74E604.6090208 at sschwarzer.net>, Stefan Schwarzer wrote: > Now it may be that the data connection, after having started > the transfer, works as it should, but the control connection > times out because the duration of the transfer is too long. It might not be the fault of the FTP server. If you?re going through a router doing NAT, that could be where the timeout is happening. From no.email at please.post Fri Aug 27 20:01:27 2010 From: no.email at please.post (kj) Date: Sat, 28 Aug 2010 00:01:27 +0000 (UTC) Subject: How to convert (unicode) text to image? Message-ID: Hi! Does anyone know of an easy way to convert a Unicode string into an image file (either jpg or png)? TIA! ~k From jrmy.lnrd at gmail.com Fri Aug 27 20:03:09 2010 From: jrmy.lnrd at gmail.com (genxtech) Date: Fri, 27 Aug 2010 17:03:09 -0700 (PDT) Subject: Overload print References: Message-ID: <88356697-058e-4ae5-ab2b-782a593f51de@z28g2000yqh.googlegroups.com> On Aug 25, 5:18?pm, Ross Williamson wrote: > Hi All > > Is there anyway in a class to overload the print function? > > >> class foo_class(): > >> ? ? ?pass > >> cc = foo_class() > >> print cc > > Gives: > > <__main__.foo_class instance at ....> > > Can I do something like: > > >> class foo_class(): > >> ? ? def __print__(self): > >> ? ? ? ? ? print "hello" > >> cc = foo_class() > >> print cc > > Gives: > > hello > > I'm looking at finding nice way to print variables in a class just by > asking to print it > > Cheers > > Ross > > -- > Ross Williamson > University of Chicago > Department of Astronomy & Astrophysics > 773-834-9785 (office) > 312-504-3051 (Cell) Are you talking about overriding print(), kind of like overloading the << operator in c++ so that you can determine how the foo_class gets printed? From steve at REMOVE-THIS-cybersource.com.au Fri Aug 27 20:24:12 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 00:24:12 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> Message-ID: <4c78572c$0$28655$c3e8da3@news.astraweb.com> On Fri, 27 Aug 2010 09:16:52 -0700, Aahz wrote: > In article , MRAB > wrote: >> >>An object will be available for garbage collection when nothing refers >>to it either directly or indirectly. If it's unreferenced then it will >>go away. > > This isn't actually garbage collection as most people think of it. > Refcounting semantics mean that objects get reaped as soon as nothing > points at them. OTOH, CPython does also have garbage collection to back > up refcounting so that when you have unreferenced object cycles they > don't stay around. I've repeatedly asked, both here and elsewhere, why reference counting isn't "real" garbage collection. Nobody has been able to give me a satisfactory answer. As far as I can tell, it's a bit of pretentiousness with no basis in objective fact. http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) http://en.wikipedia.org/wiki/Reference_counting Reference counting is one specific kind of garbage collection, and like all gc strategies, it has strengths as well as weaknesses. It is *simple* to implement (which may be why a certain class of programmer likes to think it isn't "real" gc). When it runs is deterministic, and is immediate upon the resource being freed. The overhead is very light (a plus) and continuous (which can be both a plus and a minus). It is better suited to managing scarce resources like open files than are tracing garbage collectors. It avoids the "embarrassing pause" of tracing collectors. It doesn't deal well with reference cycles, and (at least with Python's implementation of ref counting) it causes performance issues with threaded applications. http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) http://en.wikipedia.org/wiki/Reference_counting So CPython has two garbage collectors -- a reference counting implementation, and a tracing implementation. Jython and IronPython use the native garbage collectors from Java and .Net. Other Pythons may use something else. -- Steven From benjamin.kaplan at case.edu Fri Aug 27 20:34:54 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 27 Aug 2010 20:34:54 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: References: Message-ID: On Fri, Aug 27, 2010 at 8:01 PM, kj wrote: > > > Hi! ?Does anyone know of an easy way to convert a Unicode string into an image file (either jpg or png)? > Do you mean you have some text and you want an image containing that text? PIL's ImageDraw module can do that. From no.email at nospam.invalid Fri Aug 27 21:06:19 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Fri, 27 Aug 2010 18:06:19 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> Message-ID: <7x4oeftuk4.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I've repeatedly asked, both here and elsewhere, why reference counting > isn't "real" garbage collection. Nobody has been able to give me a > satisfactory answer. As far as I can tell, it's a bit of pretentiousness > with no basis in objective fact. Well, it's a bit of a subjective matter. I'd say it's not real gc because 1) it's unsound (misses reference cycles), and 2) it requires constant attention from the mutator to incr and decr the reference counts. So developing modules for the CPython API means endlessly finding and fixing refcount bugs that lead to either crashes/security failures, or memory leaks. If you program the Java JNI or a typical Lisp FFI, you'll find that real gc is a lot simpler to use since you avoid all the refcount maintenance hassles. You allocate memory and shut your eyes, and the gc takes care of freeing it when it figures out that you are done. Refcounting is basically a form of manual memory management, while gc is automatic. Someone said here recently that as a program gets larger, saying "this will work as long as we do X every time without fail" becomes equal to saying "this won't work". Substitute "properly maintain all ref counts" for X and you can see the problem. I've seen released "production" "tested" Python C modules with subtle refcount bugs on more than one occasion. In gc'd systems there are fewer places for the code to go wrong. From mahaboobnisha at gmail.com Fri Aug 27 22:42:30 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Fri, 27 Aug 2010 19:42:30 -0700 (PDT) Subject: comp.lang.python Message-ID: <4acae78f-3e8b-4781-b23b-8ced464c5021@f20g2000pro.googlegroups.com> www.127760.blogspot.com From 2011.love.me at gmail.com Fri Aug 27 22:50:53 2010 From: 2011.love.me at gmail.com (love me) Date: Fri, 27 Aug 2010 19:50:53 -0700 (PDT) Subject: love me Message-ID: <7a78b3e7-6616-4f25-899f-7dbb48e87c2d@f42g2000yqn.googlegroups.com> 1st step like me on facbook at this link http://www.facebook.com/pages/loveme/145529285481739 2nd step visit this link http://www.kqzyfj.com/click-3778203-10786395 From donn.ingle at gmail.com Fri Aug 27 23:21:09 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 05:21:09 +0200 Subject: Walking deeply nested lists Message-ID: <4C7880A5.1070304@gmail.com> This is all about walking trees, recursion and generators. None of which fit my brain at all! From an XML tree (an SVG file) I build a bunch of Tag objects. [I use lxml, but I am combining multiple svg files into a 'forest' of trees, so I can't use the lxml walking methods because they all stop at the 'end' of a branch where there is actually a 'link' over to another tree.] Each Tag has a flatwalk() method. The return from that is a list which can be deeply nested. As an example, something like this: L=[1, [2, 3, [4, [5, 6], 7], 8], [9, 10] ] (The numbers in the example would actually be Tag Instances.) Aim 1 --- I'm trying to write a generator around such lists so that I can 'walk' them: for parent, child in mystery_generator(L): print level, item Right now, I am running a 'flatten' function on the entire list (which I don't savvy, I found it online) and then I iterate over that flattened list. This doesn't feel right to me. (Code at end.) Aim 2 --- The Objects that represent the svg tags use that flatwalk() method to build the nested list, I'd far prefer flatwalk() to be directly useable in something like this way: for container, child in some_tag.flatwalk(): print container, child The flatwalk() function is (and this is another puzzle see *) kind of recursive. "For each of my children, tell that child to go flatwalk()". (Code at end.) I am not sure how to turn such a thing into a generator. I keep wondering how os.walk() does its thing. My hierarchy of Tag objects can be thought of as directories (tags:g, symbol, svg), files (path, circle, etc.) and soft-links (use tags). * If an Instance calls a method on *another* Instance of the *same* class, is this still recursion? And how does this 'stack up'? I mean, literally, on the stack. Does each instance get its own stack, or does all the push, call, pop stuff happen in one main stack? (I worry about recursion depth limits because svg trees can get quite deep.) The walking code so far: ## Found code. def flatten(input): output = [] stack = [] stack.extend(reversed(input)) while stack: top = stack.pop() if isinstance(top, list): stack.extend(reversed(top)) else: output.append(top) return output ## My walker def test_walk(e): #lxml Element comes in obj = ebag_get(e)['obj'] #get a tag object l=obj.flatwalk() ll= flatten(l) #No current solution to get 'parent' in this iterator #ie. for parent, child in ... for tag in ll: print tag Here's one of my Tag objects: class Brancher(object): def __init__(self, elem): self.elem = elem self.children = [] def flatwalk(self): l=[self] for child in self.children: l.append( child.flatwalk() ) #recur(ish)ion here return l class G( Brancher ): #Object for tags. pass \d From ldo at geek-central.gen.new_zealand Sat Aug 28 00:39:59 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 16:39:59 +1200 Subject: Reading the access attributes of directories in Windows References: <953e253c-c1d5-496d-abe1-7f7fc586a1ce@l20g2000yqm.googlegroups.com> <32569d65-9c3b-4a71-9b8e-a3724b55e755@a36g2000yqc.googlegroups.com> <44e90a60-7943-4077-bcd8-ab33a82323c2@j18g2000yqd.googlegroups.com> <323e1952-3c9b-42d9-8c3b-140f96a49eeb@s9g2000yqd.googlegroups.com> Message-ID: In message , Tim Golden wrote: > Can you run Python from within a Run-As-Administrator command > prompt? Kind of worrying, isn?t it, when the answer to ?my program won?t work? is ?give it more privileges?? Defeats the point of having such a complex security system, doesn?t it, when people are no longer able to understand its ramifications, and have to resort to bypassing it to get work done? From maral.nikfar at gmail.com Sat Aug 28 01:57:34 2010 From: maral.nikfar at gmail.com (sarah) Date: Fri, 27 Aug 2010 22:57:34 -0700 (PDT) Subject: rfile.readline() Message-ID: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> i want to know that what this function returns??? and what does this function do?? From jpiitula at ling.helsinki.fi Sat Aug 28 02:22:13 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 09:22:13 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Terry Reedy writes: > On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: > > Dave Angel writes: > > > There could easily be a .reverse() method on strings. It would return > > the reversed string, like .swapcase() returns the swapcased string. > > Could be, but the main use case seems to be for palindrome testing ;-) > Given that slicing and reversed() can do the same thing, the need is thin. The need is quite thin, but immutability of strings is not an issue, just like there can be .swapcase() though strings are immutable. That is all I am saying above. From __peter__ at web.de Sat Aug 28 02:43:07 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 08:43:07 +0200 Subject: Walking deeply nested lists References: Message-ID: donn wrote: > * If an Instance calls a method on another Instance of the same > class, is this still recursion? And how does this 'stack up'? I mean, > literally, on the stack. Does each instance get its own stack, or does > all the push, call, pop stuff happen in one main stack? > (I worry about recursion depth limits because svg trees can get quite > deep.) If you call functions within functions (or methods, it doesn't matter) they consume stack space, e. g: >>> def alpha(): ... return beta() ... >>> def beta(): ... return gamma() ... >>> import random >>> def gamma(): ... return random.choice([alpha, beta, gamma])() ... >>> import sys >>> sys.setrecursionlimit(10) >>> alpha() Traceback (most recent call last): File "", line 1, in File "", line 2, in alpha File "", line 2, in beta File "", line 2, in gamma File "", line 2, in gamma File "", line 2, in alpha File "", line 2, in beta File "", line 2, in gamma File "", line 2, in beta File "", line 2, in gamma RuntimeError: maximum recursion depth exceeded The normal recursion limit is 1000, I'm reducing it to give you a smaller traceback. Peter From __peter__ at web.de Sat Aug 28 02:57:02 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 08:57:02 +0200 Subject: rfile.readline() References: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> Message-ID: sarah wrote: > i want to know that what this function returns??? > and what does this function do?? Where do you get rfile from? The readline() function (or method) could read one line from a file (likely) or wipe your harddisk (unlikely). Without some context it is impossible to tell. Peter From jpiitula at ling.helsinki.fi Sat Aug 28 02:57:26 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 09:57:26 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: Richard Arts writes: > On Fri, Aug 27, 2010 at 10:51 PM, Jussi Piitulainen wrote: >> >> Meanwhile, I have decided to prefer this: >> >> def palindromep(s): >> ? ?def reversed(s): >> ? ? ? ?return s[::-1] >> ? ?return s == reversed(s) > > That seems like a bit of overkill... Why would you want to define a > function in a function for something trivial like this? Just > > def palindrome(s): > return s[::-1] > > will do fine. I'm sure your version will do something just fine, but what that something is, I can not tell. The body of your version is quite obscure and does not seem to agree with the name of the function. I find (s == reversed(s)) a clearer expression than (s == s[::-1]), and I found a simple way to use my preferred expression. > Of course, you can stick the inner function in a library somewhere > if you like. >From my point of view, it would be an understatement to say that setting up a library for this would be an overkill. A simple local auxiliary function is nothing. From clp2 at rebertia.com Sat Aug 28 03:06:52 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 28 Aug 2010 00:06:52 -0700 Subject: rfile.readline() In-Reply-To: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> References: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> Message-ID: On Fri, Aug 27, 2010 at 10:57 PM, sarah wrote: > i want to know that what this function returns??? > > and what does this function do?? RTFM: http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects Honestly, it's the 2nd google hit for "python readline". Regards, Chris From arnodel at googlemail.com Sat Aug 28 03:21:31 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 28 Aug 2010 08:21:31 +0100 Subject: Walking deeply nested lists References: Message-ID: donn writes: > This is all about walking trees, recursion and generators. None of > which fit my brain at all! > > From an XML tree (an SVG file) I build a bunch of Tag objects. > > [I use lxml, but I am combining multiple svg files into a 'forest' of > trees, so I can't use the lxml walking methods because they all stop > at the 'end' of a branch where there is actually a 'link' over to > another tree.] > > Each Tag has a flatwalk() method. The return from that is a list which > can be deeply nested. As an example, something like this: > L=[1, [2, 3, [4, [5, 6], 7], 8], [9, 10] ] > > (The numbers in the example would actually be Tag Instances.) > > Aim 1 > --- > I'm trying to write a generator around such lists so that I can 'walk' them: > > for parent, child in mystery_generator(L): > print level, item > > Right now, I am running a 'flatten' function on the entire list (which > I don't savvy, I found it online) and then I iterate over that > flattened list. This doesn't feel right to me. (Code at end.) > > Aim 2 > --- > The Objects that represent the svg tags use that flatwalk() method to > build the nested list, I'd far prefer flatwalk() to be directly > useable in something like this way: > > for container, child in some_tag.flatwalk(): > print container, child > > The flatwalk() function is (and this is another puzzle see *) kind of > recursive. "For each of my children, tell that child to go > flatwalk()". > (Code at end.) > I am not sure how to turn such a thing into a generator. > > I keep wondering how os.walk() does its thing. My hierarchy of Tag > objects can be thought of as directories (tags:g, symbol, svg), files > (path, circle, etc.) and soft-links (use tags). > > * If an Instance calls a method on *another* Instance of the *same* > class, is this still recursion? And how does this 'stack up'? I mean, > literally, on the stack. Does each instance get its own stack, or does > all the push, call, pop stuff happen in one main stack? > (I worry about recursion depth limits because svg trees can get quite deep.) > > > The walking code so far: > > ## Found code. > def flatten(input): > output = [] > stack = [] > stack.extend(reversed(input)) > while stack: > top = stack.pop() > if isinstance(top, list): > stack.extend(reversed(top)) > else: > output.append(top) > return output not a bad idea. I would rather write it as: def flatten(input): output = [] stack = list(input) while stack: top = stack.pop() if isinstance(top, list): stack.extend(top) else: output.append(top) output.reverse() return output If you want to make it a generator function though, the initial version is better. All you need to do is: * change the line "output.append(top)" to "yield top" * delete the line "return output" Or you can go for the simple recursive approach: def flatten(lst): for el in lst: if isinstance(el, list): for x in flatten(el): yield x else: yield el > ## My walker > def test_walk(e): #lxml Element comes in > obj = ebag_get(e)['obj'] #get a tag object > l=obj.flatwalk() > ll= flatten(l) > #No current solution to get 'parent' in this iterator > #ie. for parent, child in ... > for tag in ll: > print tag > > Here's one of my Tag objects: > > class Brancher(object): > def __init__(self, elem): > self.elem = elem > self.children = [] > > def flatwalk(self): > l=[self] > for child in self.children: > l.append( child.flatwalk() ) #recur(ish)ion here > return l This flattens the list in the flatwalk method (which IMHO it should do given its name!): def flatwalk(self): flatlist = [self] for child in self.children: for el is child.flatwalk(): flatlist.append(el) return flatlist This turns it into a generator method: def flatwalk(self): yield self for child in self.children: for el is child.flatwalk(): yield el This turns it into a generator method which yields parents as well: def flatwalk(self, parent=None): yield self, parent for child in self.children: for el is child.flatwalk(self): yield el Then you can write: for tag, parent in mytag.flatwalk(): ... Of course, for the above to work, "leaf" objects need a modified flatwalk method, e.g.: Class LeafTag: def flatwalk(self, parent=None): yield self, parent HTH (warning: all code untested). -- Arnaud From donn.ingle at gmail.com Sat Aug 28 03:29:26 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 09:29:26 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C78BAD6.2010202@gmail.com> On 28/08/2010 08:43, Peter Otten wrote: > If you call functions within functions (or methods, it doesn't matter) they > consume stack space Right, got it. Darn, but at least there's that setrecursionlimit call. Thanks, \e From no.email at nospam.invalid Sat Aug 28 03:33:10 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 28 Aug 2010 00:33:10 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> Message-ID: <7x39tz42fd.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > The nice thing about it [reference counting] is that it is sort > of deterministic -- one can examine code and determine that an object > is collected at some point in the execution... > Heap marking, OTOH, tends to run at indeterminate times, which could > have an impact if one needs predictable response timings Reference counting has the same problem. If you drop the last reference to a complex structure, it could take quite a long time to free all the components. By contrast there are provably real-time tracing gc schemes, including some parallelizeable ones. One reason CPython still can't run threads on parallel cores is it would have to lock the reference counts every time they're updated, and the slowdown from that is terrible. From donn.ingle at gmail.com Sat Aug 28 03:37:44 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 09:37:44 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C78BCC8.6000009@gmail.com> On 28/08/2010 09:21, Arnaud Delobelle wrote: > This flattens the list in the flatwalk method (which IMHO it should > do given its name!): Heh, I often name things ahead of my actual capacity to implement them! > el is child.flatwalk(): Ah, I see what you mean. I think 'is' is 'in', but I kind of get the idea. > This turns it into a generator method: And thanks for the generator versions too. I shall hack them in and poke them with a stick. > Of course, for the above to work, "leaf" objects need a modified > flatwalk method, e.g.: Yes, My 'stubs' (leaves) do have such, but I will edit to use yield. Thanks a mill. \d From sschwarzer at sschwarzer.net Sat Aug 28 04:42:53 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 28 Aug 2010 10:42:53 +0200 Subject: ftplib limitations? In-Reply-To: References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74E604.6090208@sschwarzer.net> Message-ID: <4C78CC0D.8050606@sschwarzer.net> Hi Lawrence, On 2010-08-28 01:49, Lawrence D'Oliveiro wrote: >> Now it may be that the data connection, after having started >> the transfer, works as it should, but the control connection >> times out because the duration of the transfer is too long. > > It might not be the fault of the FTP server. If you?re going through a > router doing NAT, that could be where the timeout is happening. Good point, thanks! That may explain why it's a low-level socket error instead of a 4xx timeout message from the server which I would have expected. If it's the router, the OP might try to change their router settings to get rid of the problem. Stefan From hobson42 at gmaiil.com Sat Aug 28 04:48:47 2010 From: hobson42 at gmaiil.com (Ian) Date: Sat, 28 Aug 2010 09:48:47 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4C78CD6F.2070008@gmaiil.com> On 27/08/2010 21:51, Jussi Piitulainen wrote: > Meanwhile, I have decided to prefer this: > > def palindromep(s): > def reversed(s): > return s[::-1] > return s == reversed(s) I like this. s[::-1] is obscure and non-obvious, especially to Python noobs. This makes it clear what is going on and why at a cost of very little code. Very helpful to the maintenance programming in 18 months time! Regards Ian From pavlovevidence at gmail.com Sat Aug 28 05:17:06 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 28 Aug 2010 02:17:06 -0700 (PDT) Subject: Walking deeply nested lists References: Message-ID: On Aug 27, 8:21?pm, donn wrote: > Each Tag has a flatwalk() method. The return from that is a list which > can be deeply nested. As an example, something like this: > L=[1, [2, 3, [4, [5, 6], 7], 8], [9, 10] ] > > (The numbers in the example would actually be Tag Instances.) > > Aim 1 > --- > I'm trying to write a generator around such lists so that I can 'walk' them: > > for parent, child in mystery_generator(L): > ? print level, item > > Right now, I am running a 'flatten' function on the entire list (which I > don't savvy, I found it online) and then I iterate over that flattened > list. This doesn't feel right to me. (Code at end.) Hmm. In the past I've argued that iterative techniques are superior to recursive approaches in terms of readability, understandability, and conciseness, and thus Python made the right decision to stress iteration over the Lisp/functional preference for recursion. I did consider recursion to be superior to operate on branched structures like trees. However, lately I've started thinking it's better to use iterative techniques even for situations like that. I say that as someone with no problem getting my head around recursion. Even if you disagree, I think there's value in learning iterative approaches to nested problems, in the same way that there's value to learning recursive approaches to linear problems. So here it is: def flatten_iter(s): stack = list() stack.extend(reversed(s)) while stack: item = stack.pop() if isinstance(item,list): stack.extend(reversed(item)) else: yield item It's simple. Copy the object to flatten onto your stack. Pop one item off the stack. If the item you popped is a list, push each item of that list onto the stack. Otherwise yield the value. Loop until stack is empty. There's many advantages to iterative approaches: 1. Less function call overhead (in time and space, I'd think) 2. Opportunity to optimize by scanning through the stack, something you can't do *at all* with recursion 3. Might be able to avoid things like passing around a namespace 4. Iteration is more readable, understandable, and concise in general (though I'd expect recursion is more refactorable than iteration so as the system grows the refactorability of recursion will start to outweigh other factors) The main advantage of recursion is if you have baggage associated with processing a node which does needed to be passed around. In the iterative approach that state has to be stored on the stack. So in those cases recursion is better. So I'm not suggesting that recursion be avoided (I've probably written a dozen recursive functions in the last week), I'm just saying sometimes it makes sense to use iteration even for problems recursion is tailor-made for. Carl Banks From davea at ieee.org Sat Aug 28 05:18:15 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 28 Aug 2010 05:18:15 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: References: Message-ID: <4C78D457.8040501@ieee.org> kj wrote: > Hi! Does anyone know of an easy way to convert a Unicode string into an image file (either jpg or png)? > > TIA! > > ~k > > The question has no meaning as presently worded. If you have Unicode text that you need to render, so that you end up with an image of the text, as printed in some particular font and style, you'd probably start with PIL. Or perhaps one of the gui packages, like tkinter, wxpython, etc. If you have Unicode that was produced by trying to decode some jpeg image, then back up and don't do that. See the recent thread called "Writing byte stream as jpeg format to disk". The OP there had run a unicode decode on a byte stream that represented a jpeg file, and then tried to encode it again to get the jpeg data. Bad idea. If you have Unicode that specifies a file path that refers to a jpeg file, then you need to open the file, in "rb" mode, and copy it. If you have Unicode that gives the name of a person, and you want a portrait of that person, you need to call a photographer() function. The last one was a weak attempt at humor. DaveA From no.email at nospam.invalid Sat Aug 28 05:34:59 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 28 Aug 2010 02:34:59 -0700 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <7xaao7f5bw.fsf@ruckus.brouhaha.com> Ian writes: > On 27/08/2010 21:51, Jussi Piitulainen wrote: >> Meanwhile, I have decided to prefer this: >> >> def palindromep(s): >> def reversed(s): >> return s[::-1] >> return s == reversed(s) > I like this. > s[::-1] is obscure and non-obvious, especially to Python noobs. Overriding the 'reversed' builtin even in an inner scope is a little bit ugly. If you don't mind some overhead, list(s)==list(reversed(s)) (using the built-in reversed, not the special obscure one) is pretty clear. From davea at ieee.org Sat Aug 28 05:39:53 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 28 Aug 2010 05:39:53 -0400 Subject: rfile.readline() In-Reply-To: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> References: <623f5aeb-3bbb-4aad-8f74-8a8070d17705@s9g2000yqd.googlegroups.com> Message-ID: <4C78D969.5080707@ieee.org> sarah wrote: > i want to know that what this function returns??? > > and what does this function do?? > > rfile.readline() No way to tell what the function returns from your subject line. As for what calling it does, that depends entirely on the object rfile. If it's an instance of a class you wrote, you'll have to look up in your source code. If it's an instance of one of the built-in system types, or of a class in the standard library, then you can tell by looking up that type. I see standard classes bz2.BZ2File, codecs.StreamReader, distutils.text_file, file, imaplib, mmap, io.IOBase, io.TextIOBase, and multifile. These were from the docs for Python 2.6. Most of these are probably analogous to file, in which case I can elaborate. If rfile is an instance of file, perhaps by doing rfile = open("myfile.txt", "r") then rfile.readline() reads one line from that file, starting at the current position, and leaves the file position after that line. readline() stops when it reaches a newline (which it may convert, depending on the setting of 'rb' versus 'r'), or when it reaches end of file. The trailing newline (if any) is included in the returned string. That string may be in byte form (Python 2.x), or in unicode (Python 3.x). In the latter case, it has been decoded according to parameters of the particular open file. DaveA From arnodel at googlemail.com Sat Aug 28 05:57:52 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 28 Aug 2010 10:57:52 +0100 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <7xaao7f5bw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Ian writes: >> On 27/08/2010 21:51, Jussi Piitulainen wrote: >>> Meanwhile, I have decided to prefer this: >>> >>> def palindromep(s): >>> def reversed(s): >>> return s[::-1] >>> return s == reversed(s) >> I like this. >> s[::-1] is obscure and non-obvious, especially to Python noobs. It may be non-obvious to newcomers, but it is quite a well known idiom. Also, I an not aware that it is customary in python to name predicate functions with a "p" suffix - Python is not Lisp! > > Overriding the 'reversed' builtin even in an inner scope is a little bit > ugly. I agree. > If you don't mind some overhead, list(s)==list(reversed(s)) (using the > built-in reversed, not the special obscure one) is pretty clear. May I suggest a comment instead: def ispalindrome(s): # s[::-1] evaluates to the string s reversed return s == s[::-1] -- Arnaud From __peter__ at web.de Sat Aug 28 06:03:09 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 12:03:09 +0200 Subject: Walking deeply nested lists References: Message-ID: donn wrote: > On 28/08/2010 08:43, Peter Otten wrote: >> If you call functions within functions (or methods, it doesn't matter) >> they consume stack space > > Right, got it. Darn, but at least there's that setrecursionlimit call. But be warned that if you set the limit too high instead of giving you a RuntimeError your program will segfault. Peter From pavlovevidence at gmail.com Sat Aug 28 06:11:59 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 28 Aug 2010 03:11:59 -0700 (PDT) Subject: Walking deeply nested lists References: Message-ID: <1a1f7374-351f-4a57-9b77-cf98a5d90f0b@q40g2000prg.googlegroups.com> On Aug 28, 3:03?am, Peter Otten <__pete... at web.de> wrote: > donn wrote: > > On 28/08/2010 08:43, Peter Otten wrote: > >> If you call functions within functions (or methods, it doesn't matter) > >> they consume stack space > > > Right, got it. Darn, but at least there's that setrecursionlimit call. > > But be warned that if you set the limit too high instead of giving you a > RuntimeError your program will segfault. Ah, an advantage of iteration I forgot: no recursion limits or stack overflows. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 06:40:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 10:40:37 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> Message-ID: <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 00:33:10 -0700, Paul Rubin wrote: > Dennis Lee Bieber writes: >> The nice thing about it [reference counting] is that it is sort >> of deterministic -- one can examine code and determine that an object >> is collected at some point in the execution... >> Heap marking, OTOH, tends to run at indeterminate times, which could >> have an impact if one needs predictable response timings > > Reference counting has the same problem. In theory, yes, but in practice ref counting tends to spread out the performance impact more smoothly. There are exceptions, such as the one you mention below, but as a general rule ref counting isn't subject to the "embarrassing pauses" that tracing garbage collectors tend to be subject to. > If you drop the last reference > to a complex structure, it could take quite a long time to free all the > components. By contrast there are provably real-time tracing gc > schemes, including some parallelizeable ones. I could be wrong, but how can they not be subject to the same performance issue? If you have twenty thousand components that all have to be freed, they all have to be freed whether you do it when the last reference is cleared, or six seconds later when the gc does a sweep. > One reason CPython still > can't run threads on parallel cores is it would have to lock the > reference counts every time they're updated, and the slowdown from that > is terrible. On the other hand, the reason that CPython still has reference counting is that the alternatives tried so far are unacceptably for non-threaded code. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 06:51:16 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 10:51:16 GMT Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4c78ea24$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 09:48:47 +0100, Ian wrote: > On 27/08/2010 21:51, Jussi Piitulainen wrote: >> Meanwhile, I have decided to prefer this: >> >> def palindromep(s): >> def reversed(s): >> return s[::-1] >> return s == reversed(s) > I like this. It's silly, needlessly complicated, and inefficient. Why create a *one line* nested function that only gets called once? Every single time you call the function, it has to create the inner function again, then call it once, then throw it away. Admittedly Python does recreate the inner function from pre-compiled parts, which is quick, but still, it doesn't gain you anything that a simple comment wouldn't give: def palindromep(s): return s == s[::-1] # Compare s to its reverse. > s[::-1] is obscure and non-obvious, especially to Python noobs. *Only* to Python noobs. Slicing is fundamental to Python, and using a slice of [::-1] to reverse something is a basic Python idiom. > This makes it clear what is going on and why at a cost of very little > code. > > Very helpful to the maintenance programming in 18 months time! Only if writing three lines when one would do is your definition of "helpful". -- Steven From no.email at please.post Sat Aug 28 06:55:08 2010 From: no.email at please.post (kj) Date: Sat, 28 Aug 2010 10:55:08 +0000 (UTC) Subject: How to convert (unicode) text to image? References: Message-ID: In Benjamin Kaplan writes: >On Fri, Aug 27, 2010 at 8:01 PM, kj wrote: >> >> >> Hi! =A0Does anyone know of an easy way to convert a Unicode string into a= >n image file (either jpg or png)? >> >Do you mean you have some text and you want an image containing that >text? PIL's ImageDraw module can do that. Thanks for the pointer, but... The documentation I have found for PIL (at http://www.pythonware.com/library/pil/handbook) is beyond atrocious. If this is the only way to learn how to use this library, then I really don't understand how anyone who is not clairvoyant can do it. Example: I went to the docs page for ImageDraw. There I find that the constructor for an ImageDraw.Draw object takes an argument, but *what* this argument should be (integer? object? string?) is left entirely undefined. From the examples given I *guessed* that it was an object of class Image, so I repeated the exercise: I consulted the docs for the Image module. There I learn that the constructor for the Image class takes among its parameters one called "mode" and one called "color", but, here again, what these parameters are is left completely undefined. ("mode" is left both syntactically and semantically undefined; "color" is left syntactically undefined, though the documentation includes a bit by way of semantic definition of this parameter.) What's up with this practice of leaving parameters undefined like this??? Wasn't it obvious to the person writing the Image module docs that without explaining what these parameters should be the documentation is nearly useless? Is such poor documentation an unintended consequence of "duck typing"??? Sorry for the outburst, but unfortunately, PIL is not alone in this. Python is awash in poor documentation. The number two complaint I've heard from those who dislike Python is the poor quality of its documentation, and in particular the fact that function parameters are typically left undefined, as is the case in the PIL docs. I like Python a lot, but I have to agree with this criticism. (The number one complaint has to do with the syntactic significance of whitespace; of course, I find *this* criticism silly.) What is most frustrating about such poor documentation is that it is exactly the opposite from what one would expect from the carefulness and thoroughness found in the PEPs... I have been using Python as my primary scripting language for about one year, after many years of programming in Perl, and now Python is my language of choice. But I must say that the documentation standards I found in the Perl world are *well above* those in the Python world. This is not to say that Perl documentation is always excellent; it certainly has its gaps, as one would expect from volunteer-contributed software. But I don't recall being frustrated by Perl module docs anywhere nearly as often as I am by Python module docs. I have to conclude that the problem with Python docs is somehow "systemic"... From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 06:55:30 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 10:55:30 GMT Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <4c78eb21$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 09:22:13 +0300, Jussi Piitulainen wrote: > Terry Reedy writes: >> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: >> > Dave Angel writes: >> >> > There could easily be a .reverse() method on strings. It would return >> > the reversed string, like .swapcase() returns the swapcased string. >> >> Could be, but the main use case seems to be for palindrome testing ;-) >> Given that slicing and reversed() can do the same thing, the need is >> thin. > > The need is quite thin, but immutability of strings is not an issue, > just like there can be .swapcase() though strings are immutable. That is > all I am saying above. You're right, there could be a reversed() method for strings. There could also be a disemvowel method that removes vowels, a randomise method that shuffles the letters around, a studlycaps method that changes the case of each letter randomly, and a method to check that brackets () are well- formed. They would all be useful to somebody. There are lots of different methods that strings could have. Where do you draw the line? Not everything needs to be a built-in method. There is already a standard way to spell "reverse a string": astring[::-1] If you don't like that, you can do this: ''.join(reversed(astring)) I don't object to a hypothetical reverse() method on strings, but the gain is minimal. -- Steven From m.appalakonda at gmail.com Sat Aug 28 07:21:30 2010 From: m.appalakonda at gmail.com (Hot Hot Hot) Date: Sat, 28 Aug 2010 04:21:30 -0700 (PDT) Subject: Simple hack to get $5000 to your *Paypal account Message-ID: <6b9af75f-97a2-4542-8fd2-109544702ebd@g21g2000prn.googlegroups.com> Simple hack to get $5000 to your *Paypal account At http://ucanget.co.cc i have hidden the Paypal Form link in an image. in that website on Right Side below search box, click on image and enter your name and Paypal ID. From ldo at geek-central.gen.new_zealand Sat Aug 28 07:22:14 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 28 Aug 2010 23:22:14 +1200 Subject: ftplib limitations? References: <679c7e91-0a25-4134-afd2-b5fe77fb00a5@l20g2000yqm.googlegroups.com> <4C73D738.9030501@sschwarzer.net> <4C74E604.6090208@sschwarzer.net> <4C78CC0D.8050606@sschwarzer.net> Message-ID: In message <4C78CC0D.8050606 at sschwarzer.net>, Stefan Schwarzer wrote: > In message , Lawrence D'Oliveiro wrote: >> >> It might not be the fault of the FTP server. If you?re going through a >> router doing NAT, that could be where the timeout is happening. > > Good point, thanks! That may explain why it's a low-level > socket error instead of a 4xx timeout message from the > server which I would have expected. The reason why I thought of it was because it kept happening to me back when I was using a D-Link DSL-500 to provide my ADSL connection. Unfortunately... > If it's the router, the OP might try to change their router > settings to get rid of the problem. ... if they?re using a typical consumer ADSL router box like the above, they may not have any NAT table timeout settings to play with to cure the problem. I certainly couldn?t find any in mine. In my case, I solved the problem by using a Linux box as my router. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 07:25:05 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2010 11:25:05 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> Message-ID: <4c78f210$0$28655$c3e8da3@news.astraweb.com> On Fri, 27 Aug 2010 18:06:19 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> I've repeatedly asked, both here and elsewhere, why reference counting >> isn't "real" garbage collection. Nobody has been able to give me a >> satisfactory answer. As far as I can tell, it's a bit of >> pretentiousness with no basis in objective fact. > > Well, it's a bit of a subjective matter. I'd say it's not real gc > because 1) it's unsound (misses reference cycles), You can add cycle detection to a reference count gc, at the cost of more complexity. If you read the Wikipedia article I linked to, tracing algorithms can also be unsound: Some collectors running in a particular environment can correctly identify all pointers (references) in an object; these are called "precise" (also "exact" or "accurate") collectors, the opposite being a "conservative" or "partly conservative" collector. Conservative collectors have to assume that any bit pattern in memory could be a pointer if (when interpreted as a pointer) it would point into any allocated object. Thus, conservative collectors may have some false negatives, where storage is not released because of accidental fake pointers... http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) > and 2) it requires > constant attention from the mutator to incr and decr the reference > counts. Yes. And? > So developing modules for the CPython API means endlessly > finding and fixing refcount bugs that lead to either crashes/security > failures, or memory leaks. If you program the Java JNI or a typical > Lisp FFI, you'll find that real gc is a lot simpler to use since you > avoid all the refcount maintenance hassles. You allocate memory and > shut your eyes, and the gc takes care of freeing it when it figures out > that you are done. Refcounting is basically a form of manual memory > management, while gc is automatic. That's a problem with the CPython API, not reference counting. The problem is that the CPython API is written at too low a level, beneath that at which the garbage collector exists, so naturally you have to manually manage memory. > Someone said here recently that as a program gets larger, saying "this > will work as long as we do X every time without fail" becomes equal to > saying "this won't work". Substitute "properly maintain all ref counts" > for X and you can see the problem. I've seen released "production" > "tested" Python C modules with subtle refcount bugs on more than one > occasion. In gc'd systems there are fewer places for the code to go > wrong. On the other hand, tracing gcs have their own set of problems too, mostly due to the use of finalizers and attempts to make garbage collection run more predictably. See here: http://publib.boulder.ibm.com/infocenter/javasdk/v1r4m2/topic/com.ibm.java.doc.diagnostics.142j9/html/coexistwithgc.html Quote: For tidying Java resources, think about the use of a clean up routine. When you have finished with an object, call the routine to null out all references, deregister listeners, clear out hash tables, and so on. This is far more efficient than using a finalizer and has the useful side-benefit of speeding up garbage collection. The Garbage Collector does not have so many object references to chase in the next garbage collection cycle. Translated: "Rather than relying on the garbage collector to clean up resources after you, do it yourself, manually, so the garbage collector has less work to do." Tracing garbage collectors aren't a panacea. They're software themselves, and complex software, which means they're subject to bugs like the one which plagued Flash plugin 9: http://gskinner.com/blog/archives/2008/04/failure_to_unlo.html The more complicated the garbage collector, the more scope you have for some interaction between your high-level code and the gc leading to memory not be reclaimed or extreme slowdown. Like this: http://tech.puredanger.com/2009/02/11/linkedblockingqueue-garbagecollection/ -- Steven From arnodel at googlemail.com Sat Aug 28 07:29:08 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 28 Aug 2010 12:29:08 +0100 Subject: How to convert (unicode) text to image? References: Message-ID: kj writes: > Thanks for the pointer, but... > > > The documentation I have found for PIL (at > http://www.pythonware.com/library/pil/handbook) is beyond atrocious. > If this is the only way to learn how to use this library, then I > really don't understand how anyone who is not clairvoyant can do it. > > Example: I went to the docs page for ImageDraw. There I find that > the constructor for an ImageDraw.Draw object takes an argument, > but *what* this argument should be (integer? object? string?) is > left entirely undefined. From the examples given I *guessed* that > it was an object of class Image, so I repeated the exercise: I > consulted the docs for the Image module. There I learn that the > constructor for the Image class takes among its parameters one > called "mode" and one called "color", but, here again, what these > parameters are is left completely undefined. ("mode" is left both > syntactically and semantically undefined; "color" is left syntactically > undefined, though the documentation includes a bit by way of semantic > definition of this parameter.) The first time you read the PIL docs, read the introduction. After that I find the docs pretty easy to use, even though it is true that it is quite terse. E.g. for the mode, look at the "concepts" page in the intro: http://www.pythonware.com/library/pil/handbook/concepts.htm > What's up with this practice of leaving parameters undefined like > this??? Wasn't it obvious to the person writing the Image module > docs that without explaining what these parameters should be the > documentation is nearly useless? Is such poor documentation an > unintended consequence of "duck typing"??? > > Sorry for the outburst, but unfortunately, PIL is not alone in > this. Python is awash in poor documentation. > > The number two complaint I've heard from those who dislike Python > is the poor quality of its documentation, and in particular the > fact that function parameters are typically left undefined, as is > the case in the PIL docs. I like Python a lot, but I have to agree > with this criticism. (The number one complaint has to do with the > syntactic significance of whitespace; of course, I find *this* > criticism silly.) > > What is most frustrating about such poor documentation is that it > is exactly the opposite from what one would expect from the > carefulness and thoroughness found in the PEPs... I find the Python docs very good on the whole. > I have been using Python as my primary scripting language for about > one year, after many years of programming in Perl, and now Python > is my language of choice. But I must say that the documentation > standards I found in the Perl world are *well above* those in the > Python world. This is not to say that Perl documentation is always > excellent; it certainly has its gaps, as one would expect from > volunteer-contributed software. But I don't recall being frustrated > by Perl module docs anywhere nearly as often as I am by Python > module docs. I have to conclude that the problem with Python docs > is somehow "systemic"... I have never programmed in Perl (although I have needed to read some Perl) but over the years I have used C, C++, lisp variants, PHP, Ruby, Caml variants, Haskell, Javascript (and others before the era of the web). I don't find that Python online docs on the web are worse than online docs for any of those languages. -- Arnaud From donn.ingle at gmail.com Sat Aug 28 07:55:40 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 13:55:40 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C78F93C.5070609@gmail.com> On 28/08/2010 11:17, Carl Banks wrote: > It's simple. Copy the object to flatten onto your stack. Pop one item > off the stack. If the item you popped is a list, push each item of > that list onto the stack. Otherwise yield the value. Loop until stack > is empty. Nice. The reversed thing was throwing me, but I think it's so that what comes first in a list will thus come first (on the end) of the stack. > So I'm not suggesting that recursion be avoided (I've probably written > a dozen recursive functions in the last week), I'm just saying > sometimes it makes sense to use iteration even for problems recursion > is tailor-made for. > Thanks for that. In parsing the XML (using lxml) I actually did my own stack thing with while loops, to build the entire Tag object 'tree' ? just because I wanted to see how to do it sans recursion. I still get cold shakes when I scroll past that monster! On the subject of recursion, and looking at my OP object model: the Tag objects that model the tags in an SVG file; how would I 'walk' the object tree without employing recursion? I am stuck on the eventual need to call child.flatwalk() and bang! there's recursion. I get the sense that it would be an external walk() function that does some stackery-trickery and reuturns/yields the tree/branch ? all divorced from the actual objects. So, no flatwalk() methods needed at all. This kind of bothers me because it's nice to have objects 'know' what to do and addressing their siblings and children seems a vital part of that. Look at the case of asking a Tag for its XML source: Say g is a G() instance: print g.get_xml(), would have to do some string churning (specific to a g tag) and then start walking its children and ask them to do specific string stuff (in their contexts). This means I have short methods in each Tag instance that "know" how to represent themselves as XML and they can return that value. If I divorce the thing, it becomes a large loop with a lot of switchy-ifs to engage various blocks of string-fu. I hope that made sense. I can post my code if that would help. \d From donn.ingle at gmail.com Sat Aug 28 07:57:33 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 13:57:33 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C78F9AD.2020508@gmail.com> On 28/08/2010 12:03, Peter Otten wrote: > But be warned that if you set the limit too high instead of giving you a > RuntimeError your program will segfault. Silly question: is there any way to tell the future in this case? I mean, ask for X recursion limit, and catch an error (or something) if that won't fly. \d From jpiitula at ling.helsinki.fi Sat Aug 28 08:11:03 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 15:11:03 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Sat, 28 Aug 2010 09:22:13 +0300, Jussi Piitulainen wrote: >> Terry Reedy writes: >>> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: >>> > Dave Angel writes: >>> >>> > There could easily be a .reverse() method on strings. It would return >>> > the reversed string, like .swapcase() returns the swapcased string. >>> >>> Could be, but the main use case seems to be for palindrome testing ;-) >>> Given that slicing and reversed() can do the same thing, the need is >>> thin. >> >> The need is quite thin, but immutability of strings is not an issue, >> just like there can be .swapcase() though strings are immutable. That is >> all I am saying above. > > You're right, there could be a reversed() method for strings. There > could also be a disemvowel method that removes vowels, a randomise > method that shuffles the letters around, a studlycaps method that > changes the case of each letter randomly, and a method to check that > brackets () are well- formed. They would all be useful to > somebody. There are lots of different methods that strings could > have. Where do you draw the line? When I said that there could be such a method, I was merely objecting to a statement, made in response to me, that there could not be such a method because strings are immutable. You clearly agree with me that that statement was not correct. Would you have let it stand if it was made to you? To answer your question, I don't see a real need for .reversed() in strings, but I do think .reversed() would be much more useful than .swapcase() which is in Python now and for which I see no use at all. I have not proposed adding anything to Python. I have only asked if there is any nicer expression for string reversal than [::-1] in Python now, and corrected an incorrect statement that was made in response to me that there could not be a string reversal method because Python strings are immutable. I am still not proposing that anything be added to Python. I have not even criticized Python for not having a nicer expression for string reversal than [::-1]. I have merely asked if there is one, because I didn't know if there is one, and I have shown some snippets of code to illustrate what I might mean by nicer. Someone even understood me. (Thanks.) I think I have received the answer to my question by now - that there is no obviously nicer way, and all other string reversal expressions require some extra cruft and overhead. > Not everything needs to be a built-in method. There is already a > standard way to spell "reverse a string": > > astring[::-1] > > If you don't like that, you can do this: > > ''.join(reversed(astring)) I know. I agree. I was also shown a different way to test for palindromicity, list(s) == list(reversed(s)) which is quite nice apart from the overhead. > I don't object to a hypothetical reverse() method on strings, but > the gain is minimal. I have not suggested that such a method should be added to the language. I merely corrected a statement that there could not be such a method because strings are immutable. I would not have bothered to do even that if that incorrect statement had not been made in response to my own post. I agree that the gain would be minimal. There is no harm in the method either, so I would not object to it if somebody were to propose its addition, but just to clarify my position: I have not proposed it. Hope this helps. From jpiitula at ling.helsinki.fi Sat Aug 28 08:29:07 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 15:29:07 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <7xaao7f5bw.fsf@ruckus.brouhaha.com> Message-ID: Arnaud Delobelle writes: > Also, I an not aware that it is customary in python to name > predicate functions with a "p" suffix - Python is not Lisp! Just to clarify my position: I did not mean to imply that names like palindromep might be customary in Python - clearly they are not - and I am quite aware that Python is not Lisp. My background is elsewhere, I was not paying particular attention to the name at all, and I just could not be bothered to look up what implications any of palindrome, palindromic, ispalindrome, is_palindrome, isPalindrome, has_palindrome_nature, check_palindrome and so on might have in Python. Perhaps I should have used a neutral name like f or test or so, but it did not occur to me at the time. From xrgtn at yandex.ru Sat Aug 28 08:33:05 2010 From: xrgtn at yandex.ru (Alexander Gattin) Date: Sat, 28 Aug 2010 15:33:05 +0300 Subject: GSM to ISO / UCS2 to ISO In-Reply-To: References: Message-ID: <20100828123305.GA11764@xrgtn-q40> Hello, On Mon, Aug 16, 2010 at 08:01:36PM +1000, James Mills wrote: > In an effort to avoid re-inventing the wheel so to speak > I was wondering if anyone's come across libraries/tools, etc > that achieve the same kind of functionality as the tools > library in this java app. unfortunately, no (except some Perl implementations). I'd suggest to add GSM0338 module to standard GNU libc's iconv: /usr/lib/gconv/GSM0338.so /usr/lib/gconv/gconv-modules Probably I'm wrong, but this way it'd become readily available to all programs using iconv(3), including python. > http://code.google.com/p/ipddump/source/browse/trunk/src/ipddump/tools/Gsm2Iso.java I'm Amazed (c) Pixies. This Java code really sucks. -- With best regards, xrgtn From jpiitula at ling.helsinki.fi Sat Aug 28 08:34:07 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 28 Aug 2010 15:34:07 +0300 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <7xaao7f5bw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Ian writes: > > On 27/08/2010 21:51, Jussi Piitulainen wrote: > >> Meanwhile, I have decided to prefer this: > >> > >> def palindromep(s): > >> def reversed(s): > >> return s[::-1] > >> return s == reversed(s) > > I like this. > > s[::-1] is obscure and non-obvious, especially to Python noobs. > > Overriding the 'reversed' builtin even in an inner scope is a little > bit ugly. > > If you don't mind some overhead, list(s)==list(reversed(s)) (using > the built-in reversed, not the special obscure one) is pretty clear. Thanks for that. I'm beginning to like it - not its overhead but certainly its natural clarity. It wins over ''.join(reversed(s)) easily, in my eyes. From __peter__ at web.de Sat Aug 28 08:41:45 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 14:41:45 +0200 Subject: Walking deeply nested lists References: Message-ID: donn wrote: > On 28/08/2010 12:03, Peter Otten wrote: >> But be warned that if you set the limit too high instead of giving you a >> RuntimeError your program will segfault. > Silly question: is there any way to tell the future in this case? I > mean, ask for X recursion limit, and catch an error (or something) if > that won't fly. I don't think it's a silly question, and I don't think there is an exact answer, even for a given platform. You'll want to stay well below the number calculated by the following script: import os import subprocess SCRIPT = "tmp_check.py" def ok(n): return subprocess.call(["python", SCRIPT, str(n)]) == 0 if __name__ == "__main__": if not os.path.exists(SCRIPT): with open(SCRIPT, "w") as out: out.write("""\ import sys def f(): return f() if __name__ == "__main__": n = int(sys.argv[1]) sys.setrecursionlimit(n) try: f() except RuntimeError: pass """) low = 1000 while True: new_low = 2*low if not ok(new_low): high = new_low break low = new_low while high - low > 1: mid = (low + high) // 2 if ok(mid): low = mid else: high = mid print "max recursion limit", low, high BTW, I didn't expect it but I get different results on different runs. Peter From aahz at pythoncraft.com Sat Aug 28 08:42:55 2010 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2010 05:42:55 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> Message-ID: In article <4c78572c$0$28655$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Fri, 27 Aug 2010 09:16:52 -0700, Aahz wrote: >> In article , MRAB >> wrote: >>> >>>An object will be available for garbage collection when nothing refers >>>to it either directly or indirectly. If it's unreferenced then it will >>>go away. >> >> This isn't actually garbage collection as most people think of it. >> Refcounting semantics mean that objects get reaped as soon as nothing >> points at them. OTOH, CPython does also have garbage collection to back >> up refcounting so that when you have unreferenced object cycles they >> don't stay around. > >I've repeatedly asked, both here and elsewhere, why reference counting >isn't "real" garbage collection. Nobody has been able to give me a >satisfactory answer. As far as I can tell, it's a bit of pretentiousness >with no basis in objective fact. You'll notice that I was very careful to qualify my statement with "as most people think of it". Also, because CPython has two different memory management mechanisms, refcounting and cycle detection, and the module that controls cycle detection is called "gc", I think it's simpler to follow along with the Python docs -- and critically important to remind people that there are in fact two different systems. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From aahz at pythoncraft.com Sat Aug 28 08:44:17 2010 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2010 05:44:17 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> Message-ID: In article <4c78e7a5$0$28655$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > >On the other hand, the reason that CPython still has reference counting >is that the alternatives tried so far are unacceptably for non-threaded >code. No, it's *a* reason, the other main reason being that refcounting is much easier for a random C library. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From joncle at googlemail.com Sat Aug 28 08:57:25 2010 From: joncle at googlemail.com (Jon Clements) Date: Sat, 28 Aug 2010 05:57:25 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4648f9ab-5890-4018-aa4c-83bd38db4925@t20g2000yqa.googlegroups.com> On Aug 28, 11:55?am, Steven D'Aprano wrote: > On Sat, 28 Aug 2010 09:22:13 +0300, Jussi Piitulainen wrote: > > Terry Reedy writes: > >> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: > >> > Dave Angel writes: [snip] > Not everything needs to be a built-in method. There is already a standard > way to spell "reverse a string": > > astring[::-1] > > If you don't like that, you can do this: > > ''.join(reversed(astring)) I've had to debug code that assumed str(reversed('abc')) == 'cba' >>> str(reversed('abc')) '' So, a str doesn't "construct" like tuple/list...it's a call to __str__(). It's designated as a "friendly print out" (that's my phrasing). >>> list('abc') ['a', 'b', 'c'] I s'pose str is special (2.6) in some way, but it doesn't parallel the other builtins. [Not at Terry / Steve intended -- just most relevant post to respond to] Jon. From xrgtn at yandex.ru Sat Aug 28 09:11:29 2010 From: xrgtn at yandex.ru (Alexander Gattin) Date: Sat, 28 Aug 2010 16:11:29 +0300 Subject: Trouble importing cx_Oracle on HPUX In-Reply-To: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> References: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> Message-ID: <20100828131129.GB11764@xrgtn-q40> Hello, On Thu, Aug 26, 2010 at 08:08:42PM -0700, Cliff Martin wrote: > I have just gotten done building Python 3.1.2 on > HPUX 11.31 Itanium (IA64) using gcc 4.4.3, and > have tried building cx_Oracle to go with it. The > build succeeds, but test and importing does not. > I have tried building Python with threads and > without. The only exotic thing I do with the > configure for python is to supply -mlp64, which BTW, did you build all GNU toolchain in 64 bit mode? I made some tries to get 64bit python etc but stubmled over compilation errors and didn't get enough free time to finish the effort. > makes it a 64 bit build. Python 3 appears to > work just fine, and cx_Oracle has worked on this > same architecture in the past with Python 2.6.5. did you try to start python -d and >>> import cx_Oracle? It may reveal that some symbols in libnnz10 aren't resolvable. If this is the case, try linking with bith libttsh10 and libnnz10: .../cx_Oracle-x.y.z $ LDFLAGS="-lttsh10" python setup.py install Alternatively, try linking against "static" version of libclntsh10 -- libclntst10. -- With best regards, xrgtn From cliff.martin at gmail.com Sat Aug 28 09:27:05 2010 From: cliff.martin at gmail.com (Cliff Martin) Date: Sat, 28 Aug 2010 09:27:05 -0400 Subject: Trouble importing cx_Oracle on HPUX In-Reply-To: <20100828131129.GB11764@xrgtn-q40> References: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> <20100828131129.GB11764@xrgtn-q40> Message-ID: Hi, thank you for getting back to me. Yes, our entire toolchain is 64 bit - a mix of stuff I have downloaded and built and some packages from HP (in the form of depot files) GCC was downloaded from HP, for example. I had to manually add -mlp64 to the CC and CXX lines in the Python Makefile to get it to build 64 bit Python 3. I also had to define PATH_MAX in about 5 files, because it was not resolving it, and it was just easier to add it than to spend more time trying to make it work. I hate HP-UX, BTW. Python -d did not generate any additional information, and so was not helpful (should this work?). Python -v did, however, and it came up with a number of unresolved symbols all seeming to be from libnnz11.so. I tried linking against all of the *.so files in ORACLE_HOME/lib, but I don't remember trying libttsh11 specifically. I will try it again on Monday. -- Cliff On Sat, Aug 28, 2010 at 9:11 AM, Alexander Gattin wrote: > Hello, > > On Thu, Aug 26, 2010 at 08:08:42PM -0700, Cliff > Martin wrote: > > I have just gotten done building Python 3.1.2 on > > HPUX 11.31 Itanium (IA64) using gcc 4.4.3, and > > have tried building cx_Oracle to go with it. The > > build succeeds, but test and importing does not. > > I have tried building Python with threads and > > without. The only exotic thing I do with the > > configure for python is to supply -mlp64, which > > BTW, did you build all GNU toolchain in 64 bit > mode? I made some tries to get 64bit python etc > but stubmled over compilation errors and didn't > get enough free time to finish the effort. > > > makes it a 64 bit build. Python 3 appears to > > work just fine, and cx_Oracle has worked on this > > same architecture in the past with Python 2.6.5. > > did you try to start python -d and > >>> import cx_Oracle? > > It may reveal that some symbols in libnnz10 aren't > resolvable. If this is the case, try linking with > bith libttsh10 and libnnz10: > > .../cx_Oracle-x.y.z $ LDFLAGS="-lttsh10" python setup.py install > > Alternatively, try linking against "static" > version of libclntsh10 -- libclntst10. > > -- > With best regards, > xrgtn > -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Sat Aug 28 09:32:57 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 28 Aug 2010 09:32:57 -0400 Subject: palindrome iteration In-Reply-To: <4C78CD6F.2070008@gmaiil.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4C78CD6F.2070008@gmaiil.com> Message-ID: <20100828093257.e1bc7af6.darcy@druid.net> On Sat, 28 Aug 2010 09:48:47 +0100 Ian wrote: > > def palindromep(s): > > def reversed(s): > > return s[::-1] > > return s == reversed(s) > I like this. > > s[::-1] is obscure and non-obvious, especially to Python noobs. > > This makes it clear what is going on and why at a cost of very little code. It seems unnecessary to me. Even if you can't figure it out through simple inspection, it takes seconds to fire up Python and type "print 'abc'[::-1]" into it to see what that does. Then you have another tool in your toolbox. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From donn.ingle at gmail.com Sat Aug 28 10:39:16 2010 From: donn.ingle at gmail.com (donn) Date: Sat, 28 Aug 2010 16:39:16 +0200 Subject: Walking deeply nested lists In-Reply-To: References: Message-ID: <4C791F94.7090802@gmail.com> On 28/08/2010 14:41, Peter Otten wrote: > BTW, I didn't expect it but I get different results on different > runs. Clever code. I will give it a go soonest. Elec off for the next 24 hours in my neck of the woods. Urgh. Python can't "import electricity" just yet :) \d From 2011.love.me at gmail.com Sat Aug 28 11:03:35 2010 From: 2011.love.me at gmail.com (love me) Date: Sat, 28 Aug 2010 08:03:35 -0700 (PDT) Subject: love me Message-ID: <20915819-8858-4374-9442-4fc31885c0c8@x42g2000yqx.googlegroups.com> 1st step add me in like box on my facbook page at this link http://www.facebook.com/pages/loveme/145529285481739 2nd step visit this link http://www.kqzyfj.com/click-3778203-10786395 From xrgtn at yandex.ru Sat Aug 28 11:20:46 2010 From: xrgtn at yandex.ru (Alexander Gattin) Date: Sat, 28 Aug 2010 18:20:46 +0300 Subject: rouble importing cx_Oracle on HPUX In-Reply-To: References: <1f783847-199e-40cd-bebe-4d72e149c1bb@z28g2000yqh.googlegroups.com> <20100828131129.GB11764@xrgtn-q40> Message-ID: <20100828152046.GA16623@xrgtn-q40> Hello, On Sat, Aug 28, 2010 at 09:27:05AM -0400, Cliff Martin wrote: > Yes, our entire toolchain is 64 bit - a mix of > stuff I have downloaded and built and some > packages from HP (in the form of depot files) > GCC was downloaded from HP, for example. I see. I bootstrapped from bundled cc, hence all the problems. > Python -d did not generate any additional > information, and so was not helpful (should this > work?). Oops I was wrong about the python -d -- correct option is -v of course... > Python -v did, however, and it came up with a > number of unresolved symbols all seeming to be > from libnnz11.so. I tried linking against all of > the *.so files in ORACLE_HOME/lib, but I don't > remember trying libttsh11 specifically. I will > try it again on Monday. You're using Oracle 11 vs our v10 (we also have v8, v9 and v11 in production, but not on this HP-UX server), but I think the problem with the libnnz is the same: Oracle doesn't put correct shared library dependencies into the libnnzXX.so dynamic section header (it should list libttshXX.so as NEEDED but apperently doesn't). Probably their distribution for Solaris is better, I didn't check (I'll ask our DBAs on Monday). -- With best regards, xrgtn From deepud at gmail.com Sat Aug 28 12:14:53 2010 From: deepud at gmail.com (agnibhu) Date: Sat, 28 Aug 2010 09:14:53 -0700 (PDT) Subject: Tag parsing in python Message-ID: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Hi all, I'm a newbie in python. I'm trying to create a library for parsing certain keywords. For example say I've key words like abc: bcd: cde: like that... So the user may use like abc: How are you bcd: I'm fine cde: ok So I've to extract the "How are you" and "I'm fine" and "ok"..and assign them to abc:, bcd: and cde: respectively.. There may be combination of keyowords introduced in future. like abc: xy: How are you So new keywords qualifying the other keywords so on.. So I would like to know the python way of doing this. Is there any library already existing for making my work easier. ? ~ Agnibhu From lambdadmitry at gmail.com Sat Aug 28 13:30:39 2010 From: lambdadmitry at gmail.com (Dmitry Groshev) Date: Sat, 28 Aug 2010 21:30:39 +0400 Subject: Functional composition in python Message-ID: Hello all. Some time ago I wrote a little library: http://github.com/si14/python-functional-composition/ , inspired by modern functional languages like F#. In my opinion it is quite useful now, but I would like to discuss it. An example of usage: import os from pyfuncomp import composable, c, _ def comment_cutter(s): t = s.find("#") return s if t < 0 else s[0:t].strip() @composable #one can use a decorator to make a composable function def empty_tester(x): return len(x) > 0 and x[0] != "#" path_prefix = "test" config_parser = (c(open) >> #or use a transformer function c(str.strip).map >> #"map" acts like a function modifier c(comment_cutter).map >> empty_tester.filter >> #so does "filter" c(os.path.join)[path_prefix, _].map) #f[a, _, b] is used to make a partial. #f[a, foo:bar, baz:_] is also correct print config_parser("test.txt") print (c("[x ** %s for x in %s]")[2, _] << c(lambda x: x * 2).map)([1, 2, 3]) Any suggestions are appreciated. From python.list at tim.thechases.com Sat Aug 28 13:44:37 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 28 Aug 2010 12:44:37 -0500 Subject: Tag parsing in python In-Reply-To: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: <4C794B05.6010906@tim.thechases.com> On 08/28/10 11:14, agnibhu wrote: > For example say I've key words like abc: bcd: cde: like that... So the > user may use like > abc: How are you bcd: I'm fine cde: ok > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > assign them to abc:, bcd: and cde: respectively.. For this, you can do something like >>> s = "abc: how are you bcd: I'm fine cde: ok" >>> import re >>> r = re.compile(r'(\w+):\s*((?:[^:](?!\w+:))*)') >>> r.findall(s) [('abc', 'how are you'), ('bcd', "I'm fine"), ('cde', 'ok')] Yes, it's a bit of a gnarled regexp, but it seems to do the job. > There may be combination of keyowords introduced in future. > like abc: xy: How are you So new keywords qualifying the other > keywords so on. I'm not sure I understand this bit of what you're asking. If you have s = "abc: xy: How are you" why should that not be parsed as >>> r.findall("abc: xy: How are you") [('abc', ''), ('xy', 'How are you')] as your initial description prescribes? -tkc From cocolombo at gmail.com Sat Aug 28 13:48:14 2010 From: cocolombo at gmail.com (cocolombo) Date: Sat, 28 Aug 2010 10:48:14 -0700 (PDT) Subject: Object containing a list of objects. Message-ID: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Hello. I am putting objects (test) into a container object (tests) and the test object is also a container for a another list of object (scores). Problem is that all instances of class tests have the same value. To illustrate: class score(object): val = 0 def __init__(self, val): self.val = val def __str__(self): return str(self.val) + "\n" class test(object): listOfScores = [] def __str__(self): ret = "" for s in self.listOfScores: ret += str(s) return ret class tests(object): listOfTest = [] def __str__(self): ret = "" for t in self.listOfTest: ret += str(t) return ret Now I run the script : ====================== score1 = score(10) score2 = score(20) score3 = score(30) score4 = score(40) test1 = test() test2 = test() test1.listOfScores.append(score1) test1.listOfScores.append(score2) test2.listOfScores.append(score3) test2.listOfScores.append(score4) theTests = tests() theTests.listOfTest.append(test1) theTests.listOfTest.append(test2) print theTests.listOfTest[0] print theTests.listOfTest[1] ============== This is the data structure I am EXPECTING: theTests ----test1 ---score1=10 ---score2=20 ----test2 ---score3=30 ---score4=40 But what I get is this: theTests ----test1 ---score1=10 ---score2=20 ---score3=30 ---score4=40 ----test2 ---score1=10 ---score2=20 ---score3=30 ---score4=40 What is wrong ? Thanks From __peter__ at web.de Sat Aug 28 14:02:40 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 20:02:40 +0200 Subject: Object containing a list of objects. References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Message-ID: cocolombo wrote: > Problem is that all instances of class tests have the same value. > > To illustrate: > class tests(object): > listOfTest = [] This makes listOfTest a class attribute. To get one list per instance define it in the initializer: class Tests(object): def __init__(self): self.tests = [] Peter From python at mrabarnett.plus.com Sat Aug 28 14:04:16 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 19:04:16 +0100 Subject: Object containing a list of objects. In-Reply-To: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Message-ID: <4C794FA0.7050209@mrabarnett.plus.com> On 28/08/2010 18:48, cocolombo wrote: > Hello. > > I am putting objects (test) into a container object (tests) and the > test object is also a container for a another list of object > (scores). > > Problem is that all instances of class tests have the same value. > > To illustrate: > > class score(object): > val = 0 > def __init__(self, val): > self.val = val > def __str__(self): > return str(self.val) + "\n" > > class test(object): > listOfScores = [] > def __str__(self): > ret = "" > for s in self.listOfScores: > ret += str(s) > return ret > > class tests(object): > listOfTest = [] > def __str__(self): > ret = "" > for t in self.listOfTest: > ret += str(t) > return ret > > > Now I run the script > : > ====================== > score1 = score(10) > score2 = score(20) > score3 = score(30) > score4 = score(40) > > test1 = test() > test2 = test() > > > test1.listOfScores.append(score1) > test1.listOfScores.append(score2) > test2.listOfScores.append(score3) > test2.listOfScores.append(score4) > > theTests = tests() > theTests.listOfTest.append(test1) > theTests.listOfTest.append(test2) > > print theTests.listOfTest[0] > print theTests.listOfTest[1] > > ============== > > This is the data structure I am EXPECTING: > > theTests > ----test1 > ---score1=10 > ---score2=20 > ----test2 > ---score3=30 > ---score4=40 > > > But what I get is this: > > theTests > ----test1 > ---score1=10 > ---score2=20 > ---score3=30 > ---score4=40 > ----test2 > ---score1=10 > ---score2=20 > ---score3=30 > ---score4=40 > > What is wrong ? > When you write: class test(object): listOfScores = [] you're making 'listOfScores' an attribute of the class. If you want it to be an attribute of an instance you should write: class test(object): def __init__(self): self.listOfScores = [] From clp2 at rebertia.com Sat Aug 28 14:11:18 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 28 Aug 2010 11:11:18 -0700 Subject: Object containing a list of objects. In-Reply-To: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Message-ID: On Sat, Aug 28, 2010 at 10:48 AM, cocolombo wrote: > Hello. > > I am putting objects (test) into a container object (tests) and the > test object is also a container for a another list of object > (scores). > > Problem is that all instances of class tests have the same value. > > To illustrate: > > class score(object): > ? ?val = 0 The previous line does nothing useful; delete it. > ? ?def __init__(self, val): > ? ? ? ?self.val = val > ? ?def __str__(self): > ? ? ? ?return str(self.val) + "\n" > > class test(object): > ? ?listOfScores = [] No! This makes the list a class/static variable *shared between all instances*. Delete the previous line and define a proper initializer: def __init__(self): self.listOfScores = [] > ? ?def __str__(self): > ? ? ? ?ret = "" > ? ? ? ?for s in self.listOfScores: > ? ? ? ? ? ?ret += str(s) > ? ? ? ?return ret > > class tests(object): > ? ?listOfTest = [] Again, same problem. def __init__(self): self.listOfTest = [] > ? ?def __str__(self): > ? ? ? ?ret = "" > ? ? ? ?for t in self.listOfTest: > ? ? ? ? ? ?ret += str(t) > ? ? ? ?return ret That is more efficiently+concisely written as: return "".join(str(t) for t in self.listOfTest) > Now I run the script > : > ====================== > score1 = score(10) > score2 = score(20) > score3 = score(30) > score4 = score(40) > > test1 = test() > test2 = test() > > > test1.listOfScores.append(score1) > test1.listOfScores.append(score2) > test2.listOfScores.append(score3) > test2.listOfScores.append(score4) > > theTests = tests() > theTests.listOfTest.append(test1) > theTests.listOfTest.append(test2) > > print theTests.listOfTest[0] > print theTests.listOfTest[1] > > ============== > > This is the data structure I am EXPECTING: > But what I get is this: > What is wrong ? Python is not Java/C# and has no instance variable declarations. You just assign to an attribute of self in __init__ and *that* is what creates instance variables. Any variables you assign to directly in the class body (as you were doing with listOfScores and listOfTest) are made class variables (Java lingo: "static variables"), and are /shared between all instances/, which is rarely what one actually wants. To get regular instance variables, define a proper __init__() and assign the variables to self therein. Also, per PEP 8 (http://www.python.org/dev/peps/pep-0008/ ): - Classes are conventionally CapitalizedWords, so name your classes Score, Test, and Tests rather than score, test, and tests. - Variables/methods are conventionally underscored_between_words, so list_of_test rather than listOfTest. Cheers, Chris -- http://blog.rebertia.com From cocolombo at gmail.com Sat Aug 28 14:11:42 2010 From: cocolombo at gmail.com (cocolombo) Date: Sat, 28 Aug 2010 11:11:42 -0700 (PDT) Subject: Object containing a list of objects. References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> Message-ID: <31d02de9-c7f8-42d2-9390-70f7ddbda7e2@v41g2000yqv.googlegroups.com> Thanks MRAB and Peter Otten that solved the problem. From cocolombo at gmail.com Sat Aug 28 14:23:38 2010 From: cocolombo at gmail.com (cocolombo) Date: Sat, 28 Aug 2010 11:23:38 -0700 (PDT) Subject: Object containing a list of objects. References: <00bc3667-b13c-4864-9cfb-1a066ff449c5@v41g2000yqv.googlegroups.com> <31d02de9-c7f8-42d2-9390-70f7ddbda7e2@v41g2000yqv.googlegroups.com> Message-ID: <317b3a26-fbc8-45dc-9fcb-df252dc782d6@q22g2000yqm.googlegroups.com> Chris I take good notice of your comments and suggestions. Thanks. From nikos.the.gr33k at gmail.com Sat Aug 28 15:10:01 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 12:10:01 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> Message-ID: <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> On 20 ???, 09:04, Nik Gr wrote: > With regard to the "%" operator, it considers the string on the left to > be a format string with multiple %blah things in it to replace. The > thing on the right is a sequence of items to place into the format > string. Can you please clarify what you mean by that? > In you usage above you're supplying "page" instead of "(page,)". > The latter matches the .execute() method's requirements. I tried it and "page" as a string and not a as a single element tuple works ok. From __peter__ at web.de Sat Aug 28 15:13:25 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 21:13:25 +0200 Subject: Functional composition in python References: Message-ID: Dmitry Groshev wrote: > Hello all. Some time ago I wrote a little library: > http://github.com/si14/python-functional-composition/ , inspired by > modern functional languages like F#. In my opinion it is quite useful > now, but I would like to discuss it. > An example of usage: > > import os > from pyfuncomp import composable, c, _ > > def comment_cutter(s): > t = s.find("#") > return s if t < 0 else s[0:t].strip() > > @composable #one can use a decorator to make a composable function > def empty_tester(x): > return len(x) > 0 and x[0] != "#" > > path_prefix = "test" > > config_parser = (c(open) >> #or use a transformer function > c(str.strip).map >> #"map" acts like a function modifier > c(comment_cutter).map >> > empty_tester.filter >> #so does "filter" > c(os.path.join)[path_prefix, _].map) #f[a, _, b] is > used to make a partial. > #f[a, foo:bar, > baz:_] is also correct > > print config_parser("test.txt") > Any suggestions are appreciated. With some effort you could perhaps tweak your library to accept something like config_parser = c(open) | str.strip | comment_cutter | empty_tester | c(os.path.join)(path_prefix, _) This looks more like a shell pipe than a C++ print statement -- which I think is a good thing. More general: Yes, I know that the functional style is contagious. However, I find that more traditional Python code is easier to understand. Compare: import os def config_parser(configfile, folder): with open(configfile) as lines: for line in lines: name = line.partition("#")[0].strip() if name: yield os.path.join(folder, name) for path in config_parser("test.txt", "test"): print path (at least that's what I'm guessing your code is trying to achieve) Peter From python at mrabarnett.plus.com Sat Aug 28 15:35:08 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 20:35:08 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> Message-ID: <4C7964EC.4080500@mrabarnett.plus.com> On 28/08/2010 20:10, ????? wrote: > On 20 ???, 09:04, Nik Gr wrote: >> With regard to the "%" operator, it considers the string on the left to >> be a format string with multiple %blah things in it to replace. The >> thing on the right is a sequence of items to place into the format >> string. > > Can you please clarify what you mean by that? > Basically: format_string % (item_1, item_2, item_3) >> In you usage above you're supplying "page" instead of "(page,)". >> The latter matches the .execute() method's requirements. > > I tried it and "page" as a string and not a as a single element tuple > works ok. Although the .execute() method might accept a single string: cursor.execute(sql_query, page) as well as a tuple containing the string: cursor.execute(sql_query, (page, )) try to be consistent. As I said before: """When there's more than one value you provide a tuple. It's makes sense from the point of view of consistency that you also provide a tuple when there's only one value.""" From nikos.the.gr33k at gmail.com Sat Aug 28 15:37:09 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 28 Aug 2010 12:37:09 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> Message-ID: <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> On 22 ???, 10:27, ????? wrote: > On 16 ???, 14:31, Peter Otten <__pete... at web.de> wrote: > > > > > > > > > > > ????? wrote: > > > # initializecookie > > >cookie=Cookie.SimpleCookie() > > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > > mycookie =cookie.get('visitor') > > > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > > > yandex|13448|spider|crawl)', host ) is None: > > > ? ? blabla... > > > ======================== > > > > I checked and Chrome has acookienames visitor with a value ofnikos > > > within. > > > So, i have to ask why the if fails? > > > Maybe it's because != != == > > Iwant ti if code block to be executed only if the browsercookienames > visitor fetched doesnt cotnain the vbalue of 'nikos' > > Is there somethign wrong with the way i wrote it? Please do help me with this too becaus eif i dont solve this my website keeps count my each visit like iam a guest visitor! From nikos.the.gr33k at gmail.com Sat Aug 28 15:48:52 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 12:48:52 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> Message-ID: <877b27f8-061c-4a0e-bc96-aa66a889519f@f6g2000yqa.googlegroups.com> On 28 ???, 22:35, MRAB wrote: > On 28/08/2010 20:10, ????? wrote:> On 20 ???, 09:04, Nik Gr ?wrote: > >> With regard to the "%" operator, it considers the string on the left to > >> be a format string with multiple %blah things in it to replace. The > >> thing on the right is a sequence of items to place into the format > >> string. > > > Can you please clarify what you mean by that? > > Basically: > > ? ? ?format_string % (item_1, item_2, item_3) I still don't follow by means that i dotn see the point here... > > >> In you usage above you're supplying "page" instead of "(page,)". > >> The latter matches the .execute() method's requirements. > > > I tried it and "page" as a string and not a as a single element tuple > > works ok. > > Although the .execute() method might accept a single string: > > ? ? ?cursor.execute(sql_query, page) > > as well as a tuple containing the string: > > ? ? ?cursor.execute(sql_query, (page, )) > > try to be consistent. As I said before: > > """When there's more than one value you provide a tuple. It's makes sense > from the point of view of consistency that you also provide a tuple when > there's only one value.""" cursor.execute(sql_query, (page, )) is different than? cursor.execute(sql_query, page, ) ? =========================== Why in mysql string substitution example i have to use page='%s' and in the comma way(automatic mysql convertion i dont need the single quotes and use it as page=%s ? What is the diff? =========================== From nikos.the.gr33k at gmail.com Sat Aug 28 15:51:46 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 12:51:46 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> Message-ID: <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> On 28 ???, 22:35, MRAB wrote: > """When there's more than one value you provide a tuple. It's makes sense > from the point of view of consistency that you also provide a tuple when > there's only one value.""" Can you write something that make use of more than one value? Perhaps you mena somethign like? cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date = %s and host = %s''' , (page,) ) Is this what you mean? All those special format strign identifiers will grab their values out of the tuple? From rami.chowdhury at merton.oxon.org Sat Aug 28 16:07:27 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Sun, 29 Aug 2010 02:07:27 +0600 Subject: String substitution VS proper mysql escaping In-Reply-To: <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> Message-ID: 2010/8/29 ????? : > On 28 ???, 22:35, MRAB wrote: > >> """When there's more than one value you provide a tuple. It's makes sense >> from the point of view of consistency that you also provide a tuple when >> there's only one value.""" > > Can you write something that make use of more than one value? > > > Perhaps you mena somethign like? > > cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date > = %s and host = %s''' , (page,) ) > > Is this what you mean? > > All those special format strign identifiers will grab their values out > of the tuple? Yes, that's exactly right -- they'll try to grab values out of the tuple, and since in that particular code snippet the tuple doesn't contain enough items, you'll get an error :-) HTH, Rami -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From __peter__ at web.de Sat Aug 28 16:07:57 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 28 Aug 2010 22:07:57 +0200 Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> Message-ID: ????? wrote: > On 22 ???, 10:27, ????? wrote: >> On 16 ???, 14:31, Peter Otten <__pete... at web.de> wrote: >> > ????? wrote: >> > > # initializecookie >> > >cookie=Cookie.SimpleCookie() >> > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) >> > > mycookie =cookie.get('visitor') >> >> > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >> > > yandex|13448|spider|crawl)', host ) is None: >> > > blabla... >> > > ======================== >> >> > > I checked and Chrome has acookienames visitor with a value ofnikos >> > > within. >> > > So, i have to ask why the if fails? >> >> > Maybe it's because != != == >> >> Iwant ti if code block to be executed only if the browsercookienames >> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >> Is there somethign wrong with the way i wrote it? > > Please do help me with this too becaus eif i dont solve this my > website keeps count my each visit like iam a guest visitor! In your initial post it sounded like you wanted the if-branch to execute for a user named "nikos", but now it seems that I misunderstood you and swapping 'mycookie.value != "nikos"' for 'mycookie.value == "nikos"' won't help. Maybe you could add a print statement like print mycookie.value to start with your debugging efforts. Peter From python at mrabarnett.plus.com Sat Aug 28 16:09:11 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 21:09:11 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <877b27f8-061c-4a0e-bc96-aa66a889519f@f6g2000yqa.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <877b27f8-061c-4a0e-bc96-aa66a889519f@f6g2000yqa.googlegroups.com> Message-ID: <4C796CE7.8020508@mrabarnett.plus.com> On 28/08/2010 20:48, ????? wrote: > On 28 ???, 22:35, MRAB wrote: >> On 28/08/2010 20:10, ????? wrote:> On 20 ???, 09:04, Nik Gr wrote: >>>> With regard to the "%" operator, it considers the string on the left to >>>> be a format string with multiple %blah things in it to replace. The >>>> thing on the right is a sequence of items to place into the format >>>> string. >> >>> Can you please clarify what you mean by that? >> >> Basically: >> >> format_string % (item_1, item_2, item_3) > > I still don't follow by means that i dotn see the point here... > >> >>>> In you usage above you're supplying "page" instead of "(page,)". >>>> The latter matches the .execute() method's requirements. >> >>> I tried it and "page" as a string and not a as a single element tuple >>> works ok. >> >> Although the .execute() method might accept a single string: >> >> cursor.execute(sql_query, page) >> >> as well as a tuple containing the string: >> >> cursor.execute(sql_query, (page, )) >> >> try to be consistent. As I said before: >> >> """When there's more than one value you provide a tuple. It's makes sense >> from the point of view of consistency that you also provide a tuple when >> there's only one value.""" > > cursor.execute(sql_query, (page, )) > > is different than? > > cursor.execute(sql_query, page, ) > > ? > Yes. The first has 2 arguments: a string and a tuple containing the value of 'page'. The second has 2 arguments: a string and the value of 'page'. > =========================== > Why in mysql string substitution example i have to use page='%s' and > in the comma way(automatic mysql convertion i dont need the single > quotes and use it as page=%s ? > What is the diff? > =========================== In the first case you're doing the substitution yourself, but you might not get it right, leaving your website open an SQL injection attacks. In the second case you're letting the .execute method do the substitution. It will have been written to do it correctly and safely. From python at mrabarnett.plus.com Sat Aug 28 16:12:03 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 21:12:03 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> Message-ID: <4C796D93.20303@mrabarnett.plus.com> On 28/08/2010 20:51, ????? wrote: > On 28 ???, 22:35, MRAB wrote: > >> """When there's more than one value you provide a tuple. It's makes sense >> from the point of view of consistency that you also provide a tuple when >> there's only one value.""" > > Can you write something that make use of more than one value? > > > Perhaps you mena somethign like? > > cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date > = %s and host = %s''' , (page,) ) > > Is this what you mean? > > All those special format strign identifiers will grab their values out > of the tuple? Your example contains 3 placeholders, so it needs 3 values: cursor.execute('''SELECT hits FROM counters WHERE page = %s and date = %s and host = %s''', (page, date, host)) This will be safe. Any quoting that's needed will be done by .execute(). From python at mrabarnett.plus.com Sat Aug 28 16:15:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Aug 2010 21:15:59 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> Message-ID: <4C796E7F.4070105@mrabarnett.plus.com> On 28/08/2010 20:37, ????? wrote: > On 22 ???, 10:27, ????? wrote: >> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >> >> >> >> >> >> >> >> >>> ????? wrote: >>>> # initializecookie >>>> cookie=Cookie.SimpleCookie() >>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>> mycookie =cookie.get('visitor') >> >>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>> yandex|13448|spider|crawl)', host ) is None: >>>> blabla... >>>> ======================== >> >>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>> within. >>>> So, i have to ask why the if fails? >> >>> Maybe it's because != != == >> >> Iwant ti if code block to be executed only if the browsercookienames >> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >> Is there somethign wrong with the way i wrote it? > > Please do help me with this too becaus eif i dont solve this my > website keeps count my each visit like iam a guest visitor! Print out mycookie, repr(mycookie.value) (unless mycookie is None) and repr(host). Then follow the code yourself to see whether the condition is True. From rami.chowdhury at merton.oxon.org Sat Aug 28 16:17:05 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Sun, 29 Aug 2010 02:17:05 +0600 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: On Fri, Aug 27, 2010 at 14:16, Nobody wrote: > On Fri, 27 Aug 2010 13:28:46 +0600, Rami Chowdhury wrote: > >>>> Having this as a separate permission allows normal users to add entries >>>> to log files but not to erase existing entries. >>> >>> Unix/Linux systems can do this already. >> >> Ooh, I didn't know that -- what combination of permissions would I have to >> use to get such an effect? > > You can't do it with permissions, you need to use ext2 attributes. > Specifically, "chattr +a " will set the "append" attribute, > which prevents the file being opened for write except in append mode. > Changing this attribute requires root privilege or the CAP_LINUX_IMMUTABLE > capability. Fascinating, thank you! -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From rami.chowdhury at merton.oxon.org Sat Aug 28 16:19:02 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Sun, 29 Aug 2010 02:19:02 +0600 Subject: Reading the access attributes of directories in Windows In-Reply-To: References: Message-ID: On Sat, Aug 28, 2010 at 05:07, Lawrence D'Oliveiro wrote: > In message , Rami > Chowdhury wrote: > >> On Wed, Aug 25, 2010 at 05:04, Lawrence D'Oliveiro >> wrote: >> >>> In message , Nobody wrote: >>> >>>> Having this as a separate permission allows normal users to add entries >>>> to log files but not to erase existing entries. >>> >>> Unix/Linux systems can do this already. >> >> Ooh, I didn't know that -- what combination of permissions would I >> have to use to get such an effect? > > No special permissions needed at all?just use the syslog(3) functions. > > And the nice thing is, you don?t have to know whether the system logs are > kept on the local machine or on a remote machine, or how different > categories of messages are divided up into different files, how log rotation > is done, or anything like that?it?s all transparent. Ah, thanks -- I think I'd misread your first post as indicating that that kind of "append" effect would work for any file. Apologies for the misunderstanding! -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From davea at ieee.org Sat Aug 28 16:53:12 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 28 Aug 2010 16:53:12 -0400 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4C797738.70803@ieee.org> Jussi Piitulainen wrote: > Steven D'Aprano writes: > >> On Sat, 28 Aug 2010 09:22:13 +0300, Jussi Piitulainen wrote: >> >>> Terry Reedy writes: >>> >>>> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote: >>>> >>>>> Dave Angel writes: >>>>> >>>>> There could easily be a .reverse() method on strings. It would return >>>>> the reversed string, like .swapcase() returns the swapcased string. >>>>> >>>> Could be, but the main use case seems to be for palindrome testing ;-) >>>> Given that slicing and reversed() can do the same thing, the need is >>>> thin. >>>> >>> The need is quite thin, but immutability of strings is not an issue, >>> just like there can be .swapcase() though strings are immutable. That is >>> all I am saying above. >>> >> You're right, there could be a reversed() method for strings. There >> could also be a disemvowel method that removes vowels, a randomise >> method that shuffles the letters around, a studlycaps method that >> changes the case of each letter randomly, and a method to check that >> brackets () are well- formed. They would all be useful to >> somebody. There are lots of different methods that strings could >> have. Where do you draw the line? >> > > When I said that there could be such a method, I was merely objecting > to a statement, made in response to me, that there could not be such a > method because strings are immutable. You clearly agree with me that > that statement was not correct. Would you have let it stand if it was > made to you? > > Since you repeat that assertion three times, I figure you must think it's important. And it was I who asserted that a reverse() method wouldn't be possible on an immutable object. reverse() would reverse the characters in place, and return None. At least it would if it tried to be at all consistent with the list, array, and audioop methods of the same name. reversed() is certainly possible, and it'd make a new string with the reverse order of the original. DaveA From david at ombrepixel.com Sat Aug 28 17:37:39 2010 From: david at ombrepixel.com (David ROBERT) Date: Sat, 28 Aug 2010 22:37:39 +0100 Subject: InteractiveConsole and namespace Message-ID: Hi all, I want to use an InteractiveConsole at some stage in a program to interact with the local namespace: access, but also modify objects. When the interactive console ends (ctrl-d) I want the program to continue processing with the variables that may have been modified interactively. The code below works (block invoking the console is not in a function). During the interactive session, I can read value of a, I can change value of a and the new value is "updated" in the block namespace. import code if __name__ == '__main__': a=1 c = code.InteractiveConsole(locals()) c.interact() # Here I interactively change the value of a (a=2) print "Value of a: ", a print returns --> Value of a: 2 However, on the other code below (the console is invoked from within a function block), during the interactive session, I can read value of a, I can change value of a. But the local namespace of the function is not updated: import code def test(): a=1 c = code.InteractiveConsole(locals()) c.interact() # Here I interactively change the value of a (a=2) print "Value of a: ", a if __name__ == '__main__': test() print returns --> Value of a: 1 I need to run the InteractiveConsole from a function block. I tried different things with the local and parent frames (sys._getframe()) but nothing successful. If I put a in the global namespace it works, but I would like to find a nicer solution and also understand what the problem is. Thanks for any help -- David ROBERT http://blog.ombrepixel.com/ From joshua.r.english at gmail.com Sat Aug 28 18:09:16 2010 From: joshua.r.english at gmail.com (Josh English) Date: Sat, 28 Aug 2010 15:09:16 -0700 (PDT) Subject: pyxser-1.5r --- Python Object to XML serializer/deserializer References: <72aa2291-d979-4deb-9e9b-147af2c9d0af@b4g2000pra.googlegroups.com> Message-ID: <245507cb-9936-40bb-83f8-6db7c819ad62@t5g2000prd.googlegroups.com> On Aug 26, 10:02?pm, Stefan Behnel wrote: > Josh English, 27.08.2010 01:30: > > > solve a lot of the problems I'm running into in my own attempt to > > build a python Class implementation of an XML Validation object. > > How would object serialisation help here? > > I'm running into the same problem in a lot of projects I'm working on. I can't decide one the best way to serialize instances of classes. I want to be able to store these instances in a human-readable and editable format that I can reload back into their objects. The XML validation tool requires the rules of the XML to be written out in Python as classes and instances. I would love to have a consistent way to write the definition file and load it. For example, Relax NG can be written out, the rules loaded into a parser, and actual XML data can be validated against it. Since I started in Python, I want that bridge back to serialization. In this project, and others, subclassing plays a big role in using the code, so I need a reliable way of writing a definition, loading it into the proper subclass, and running with those subclasses. I am familiar with XML, but I've played with YAML and may try that. I'm hesitant to use YAML because it requires that I add the YAML.object. I even wrote a program to store data similar to GEDCOM format, which seemed the simplest from a user's perspective. Josh From joshua.r.english at gmail.com Sat Aug 28 18:12:17 2010 From: joshua.r.english at gmail.com (Josh English) Date: Sat, 28 Aug 2010 15:12:17 -0700 (PDT) Subject: Tag parsing in python References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: <83d3d6df-751e-4ef3-8ce9-3c329a0c32aa@s17g2000prh.googlegroups.com> On Aug 28, 9:14?am, agnibhu wrote: > Hi all, > > I'm a newbie in python. I'm trying to create a library for parsing > certain keywords. > For example say I've key words like abc: bcd: cde: like that... So the > user may use like > abc: How are you bcd: I'm fine cde: ok > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > assign them to abc:, bcd: and cde: respectively.. There may be > combination of keyowords introduced in future. like abc: xy: How are > you > So new keywords qualifying the other keywords so on.. > So I would like to know the python way of doing this. Is there any > library already existing for making my work easier. ? > > ~ > Agnibhu Have you looked at pyparsing? (http://pyparsing.wikispaces.com/) It may be possible to use that library to do this. Josh From kevinlcarlson at gmail.com Sat Aug 28 18:31:36 2010 From: kevinlcarlson at gmail.com (kevinlcarlson) Date: Sat, 28 Aug 2010 15:31:36 -0700 (PDT) Subject: Helper app for intranet site Message-ID: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> I'm exploring the possibility of developing a helper app for an existing internal company website. Basically, it would automatically scan the current page contents, including prepopulated forms, and provide context-related business rule comments to the user, via a stay- on-top wxPython panel. Any suggestions on how to do this? (The web developers are unavailable to do this within the site.) Thanks, Kevin From raoulbia at gmail.com Sat Aug 28 19:12:36 2010 From: raoulbia at gmail.com (Baba) Date: Sat, 28 Aug 2010 16:12:36 -0700 (PDT) Subject: Fibonacci: How to think recursively Message-ID: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Level: beginner I would like to know how to approach the following Fibonacci problem: How may rabbits do i have after n months? I'm not looking for the code as i could Google that very easily. I'm looking for a hint to put me on the right track to solve this myself without looking it up. my brainstorming so far brought me to a stand still as i can't seem to imagine a recursive way to code this: my attempted rough code: def fibonacci(n): # base case: result = fibonacci (n-1) + fibonacci (n-2) >> this will end up in a mess as it will create overlapping recursions OR def fibonacci(n): # base case: fibonacci(n+2) - fibonacci(n+1) - n = 0 >> this too would create overlapping recursions How to go about this? Thanks Baba From mwilson at the-wire.com Sat Aug 28 19:54:54 2010 From: mwilson at the-wire.com (Mel) Date: Sat, 28 Aug 2010 19:54:54 -0400 Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: Baba wrote: > Level: beginner > > I would like to know how to approach the following Fibonacci problem: > How may rabbits do i have after n months? > > I'm not looking for the code as i could Google that very easily. I'm > looking for a hint to put me on the right track to solve this myself > without looking it up. > > my brainstorming so far brought me to a stand still as i can't seem to > imagine a recursive way to code this: > > my attempted rough code: > > def fibonacci(n): > # base case: > result = fibonacci (n-1) + fibonacci (n-2) >>> this will end up in a mess as it will create overlapping recursions I don't think this is the base case. The base case would be one or more values of `n` that you already know the fibonacci number for. Your recursive function can just test for those and return the right answer right away. The the expression you've coded contains a good way to handle the non-base cases. There's no such problem as "overlapping recursions". Mel. From clp2 at rebertia.com Sat Aug 28 20:05:12 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 28 Aug 2010 17:05:12 -0700 Subject: InteractiveConsole and namespace In-Reply-To: References: Message-ID: On Sat, Aug 28, 2010 at 2:37 PM, David ROBERT wrote: > Hi all, > > I want to use an InteractiveConsole at some stage in a program to > interact with the local namespace: access, but also modify objects. > When the interactive console ends (ctrl-d) I want the program to > continue processing with the variables that may have been modified > interactively. > > The code below works (block invoking the console is not in a > function). During the interactive session, I can read value of a, I > can change value of a and the new value is "updated" in the block > namespace. > > import code > if __name__ == '__main__': > ? ?a=1 > ? ?c = code.InteractiveConsole(locals()) > ? ?c.interact() ?# Here I interactively change the value of a (a=2) > ? ?print "Value of a: ", a > > print returns --> Value of a: 2 > > However, on the other code below (the console is invoked from within a > function block), during the interactive session, I can read value of > a, I can change value of a. But the local namespace of the function is > not updated: > > import code > def test(): > ? ?a=1 > ? ?c = code.InteractiveConsole(locals()) > ? ?c.interact() # Here I interactively change the value of a (a=2) > ? ?print "Value of a: ", a > > if __name__ == '__main__': > ? ?test() > > print returns --> Value of a: 1 > > I need to run the InteractiveConsole from a function block. I tried > different things with the local and parent frames (sys._getframe()) > but nothing successful. If I put a in the global namespace it works, > but I would like to [...] > understand what the > problem is. Read http://docs.python.org/library/functions.html#locals (emphasis added): "locals() [...] Note: The contents of this dictionary should not be modified; ***changes may not affect the values of local and free variables used by the interpreter***." At the top-level / module scope, it just so happens that `locals() is globals() == True`; and unlike locals(), globals() does not have the aforequoted limitation. I don't know if there's a non-ugly workaround. Cheers, Chris -- http://blog.rebertia.com From ben+python at benfinney.id.au Sat Aug 28 20:23:52 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 29 Aug 2010 10:23:52 +1000 Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: <87hbiegtbb.fsf@benfinney.id.au> Baba writes: > my brainstorming so far brought me to a stand still as i can't seem to > imagine a recursive way to code this: > > my attempted rough code: > > def fibonacci(n): > # base case: > result = fibonacci (n-1) + fibonacci (n-2) > >> this will end up in a mess as it will create overlapping recursions It also never returns anything (which, in Python, means it returns the None object). Worse, it will endlessly recurse; every time it's called it will call itself (twice). Perhaps a way to approach the problem is: How will your function know when *not* to call itself? What will it do instead? Try writing that case first, and then write the rest of it on that basis. -- \ ?Science is a way of trying not to fool yourself. The first | `\ principle is that you must not fool yourself, and you are the | _o__) easiest person to fool.? ?Richard P. Feynman, 1964 | Ben Finney From landimatte at gmail.com Sat Aug 28 20:33:30 2010 From: landimatte at gmail.com (Matteo Landi) Date: Sun, 29 Aug 2010 02:33:30 +0200 Subject: Fibonacci: How to think recursively In-Reply-To: <87hbiegtbb.fsf@benfinney.id.au> References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <87hbiegtbb.fsf@benfinney.id.au> Message-ID: I suggest you to memoize results in order to prevent overlapping recursion. Regards, Matteo On Sun, Aug 29, 2010 at 2:23 AM, Ben Finney wrote: > Baba writes: > >> my brainstorming so far brought me to a stand still as i can't seem to >> imagine a recursive way to code this: >> >> my attempted rough code: >> >> def fibonacci(n): >> ? ? # base case: >> ? ? ? ? result = fibonacci (n-1) + fibonacci (n-2) >> >> this will end up in a mess as it will create overlapping recursions > > It also never returns anything (which, in Python, means it returns the > None object). > > Worse, it will endlessly recurse; every time it's called it will call > itself (twice). > > Perhaps a way to approach the problem is: How will your function know > when *not* to call itself? What will it do instead? Try writing that > case first, and then write the rest of it on that basis. > > -- > ?\ ? ? ? ? ?Science is a way of trying not to fool yourself. The first | > ?`\ ? ? principle is that you must not fool yourself, and you are the | > _o__) ? ? ? ? ? ? ? easiest person to fool.? ?Richard P. Feynman, 1964 | > Ben Finney > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From momo.reina at gmail.com Sat Aug 28 20:50:38 2010 From: momo.reina at gmail.com (mo reina) Date: Sat, 28 Aug 2010 17:50:38 -0700 (PDT) Subject: looking for open source python project Message-ID: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> looking for a python project (preferably something a bit small) that is looking for contributors. the small bit is because i've never worked in a team before and haven't really read source code that's 1000s of lines long, so i'm not too sure i can keep up. my python fu is decent (i think), i recently wrote a small archive/ grimoire program (command line only) that can store multiline text with title, tags, and basic search functionality (not using curses so the entry, once entered, can't be modified), entries are stored in a pickle file. anybody have any suggestions? i'm keen to work on something with others, both for learning and i'd like to do something a bit meaningful, plus i'm sure it's fun. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 21:00:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2010 01:00:10 GMT Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4c79b11a$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 15:11:03 +0300, Jussi Piitulainen wrote: [...] > When I said that there could be such a method, I was merely objecting to > a statement, made in response to me, that there could not be such a > method because strings are immutable. You clearly agree with me that > that statement was not correct. Would you have let it stand if it was > made to you? Ha ha, you're new here aren't you? > To answer your question, I don't see a real need for .reversed() in > strings, but I do think .reversed() would be much more useful than > .swapcase() which is in Python now and for which I see no use at all. It's hard to disagree with that. I'm not entirely sure what the use-case for swapcase is. It's not quite as specialised as sTUdlEycApS but not far off. [...] > I agree that the gain would be minimal. There is no harm in the method > either, so I would not object to it if somebody were to propose its > addition, but just to clarify my position: I have not proposed it. Then we are in agreement :) I think the only thing we disagree on is that I think [::-1] is a perfectly nice expression for reversal, while you don't. True, it's not entirely intuitive to newbies, or self-documenting, you need to learn slicing to understand it. But then, if you were Dutch and had not learned English, you would probably be looking for a method called omgekeerde and would find reverse equally unintuitive. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 21:14:56 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2010 01:14:56 GMT Subject: Functional composition in python References: Message-ID: <4c79b48f$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 21:30:39 +0400, Dmitry Groshev wrote: > Hello all. Some time ago I wrote a little library: > http://github.com/si14/python-functional-composition/ , inspired by > modern functional languages like F#. In my opinion it is quite useful > now, but I would like to discuss it. > An example of usage: > > import os > from pyfuncomp import composable, c, _ > > def comment_cutter(s): > t = s.find("#") > return s if t < 0 else s[0:t].strip() > > @composable #one can use a decorator to make a composable function > def empty_tester(x): > return len(x) > 0 and x[0] != "#" Why do you need a decorator to make a composable function? Surely all functions are composable -- it is the nature of functions that you can call one function with the output of another function. > path_prefix = "test" > > config_parser = (c(open) >> #or use a transformer function > c(str.strip).map >> #"map" acts like a function modifier > c(comment_cutter).map >> > empty_tester.filter >> #so does "filter" > c(os.path.join)[path_prefix, _].map) #f[a, _, b] is > used to make a partial. > #f[a, foo:bar, > baz:_] is also correct > > print config_parser("test.txt") > print (c("[x ** %s for x in %s]")[2, _] << c(lambda x: x * 2).map)([1, > 2, 3]) > > Any suggestions are appreciated. Did you expect us to guess what the above code would do? Without showing the output, the above is just line noise. What does c() do? What does compose() do that ordinary function composition doesn't do? You say that "map" acts as a function modifier, but don't tell us *what* it modifies or in what way. Same for filter. So anyone not familiar with C syntax, the use of << is just line noise. You need to at say what you're using it for. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 28 22:25:21 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2010 02:25:21 GMT Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: <4c79c510$0$28655$c3e8da3@news.astraweb.com> On Sat, 28 Aug 2010 16:12:36 -0700, Baba wrote: > Level: beginner > > I would like to know how to approach the following Fibonacci problem: > How may rabbits do i have after n months? > > I'm not looking for the code as i could Google that very easily. I'm > looking for a hint to put me on the right track to solve this myself > without looking it up. > > my brainstorming so far brought me to a stand still as i can't seem to > imagine a recursive way to code this: Perhaps you need to start with a simpler case to get your head around the ideas. Let's look at factorial first. fact(n) = n*(n-1)*(n-2)*(n-3)*...*2*1 Working upwards: fact(0) = 1 # this is by definition. fact(1) = 1 # also by definition. fact(2) = 2*1 = 2*fact(1) fact(3) = 3*2*1 = 3*fact(2) ... fact(n) = n*fact(n-1) So now you have the base case: if n is 1 or smaller, fact(n) returns 1 and the recursive case: otherwise fact(n) returns n*fact(n-1) Now write that as a Python function, and test it to see that it is correct. Come back once you've got it working satisfactorily. Now, can you apply the same reasoning to the Fibonacci problem? What is your base case? You need some way to halt the recursion, something that *doesn't* make a recursive call. def fib(n): if SOME_CONDITION: return SOME_VALUE else: return SOME_RECURSION is the most basic form you can have. Notice that you must *return* something. That's basic Python syntax -- if you don't call return, the function will return the special None object, which is not what you want. More generally, you could have multiple base cases and multiple recursive cases, not necessarily one of each. But there must be at least one non- recursive expression that gets returned, or the recursion can never terminate. > my attempted rough code: > > def fibonacci(n): > # base case: > result = fibonacci (n-1) + fibonacci (n-2) >>> this will end up in a mess as it will create overlapping recursions Mathematically, there is nothing wrong with overlapping recursion. It will work, and Python can handle it easily. But in practical terms, it can lead to great inefficiency. In this example, it should be avoided because it is slow. Very slow. To calculate the nth Fibonacci number using naive recursion requires *many* calls: fib(4) # first call => fib(3) + fib(2) # three calls => fib(2) + fib(1) + fib(1) + fib(0) # seven calls => fib(1) + fib(0) + 1 + 1 + 0 # nine calls => 1 + 0 + 1 + 1 + 0 = 3 So to get fib(4) = 3 requires nine calls to fib(). This growth function doesn't have a name (as far as I know), but it grows much faster than fib() itself: n = 0 1 2 3 4 5 6 ... 35 ... fib(n) = 0 1 1 2 3 5 8 ... 9227465 ... calls = 1 1 3 5 9 15 25 ... 29860703 ... As you can see, the number of calls is also calculable by a recursive expression R: R(0) = R(1) = 1 R(n) = R(n-1) + R(n-2) + 1 This is very similar to the Fibonacci recursion, only it grows more quickly. But I digress... You can make the recursive version more efficient if you give it a memory. In the call to fib(5), for example, it ends up calling fib(4) once, fib(3) twice, fib(2) three times, fib(1) four times, and fib(0) twice. If it could remember each value once it saw it, it could potentially save nine calls (out of fifteen). That's a less inefficient use of recursion. Think about ways to give it a short-term memory. You can make it even more efficient by giving fib() a long-term cache, so that each call to fib(5) requires one cache lookup rather than six (or fifteen) recursive calls. Other than the first time, obviously. This is called memoisation, but again I digress. There are other techniques, but this will do to get started. -- Steven From lambdadmitry at gmail.com Sat Aug 28 22:54:13 2010 From: lambdadmitry at gmail.com (Dmitry Groshev) Date: Sat, 28 Aug 2010 19:54:13 -0700 (PDT) Subject: Functional composition in python References: <4c79b48f$0$28655$c3e8da3@news.astraweb.com> Message-ID: <6bedbd75-2fc7-43d6-a3ba-e76e4b447db6@l20g2000yqe.googlegroups.com> On Aug 29, 5:14?am, Steven D'Aprano wrote: > On Sat, 28 Aug 2010 21:30:39 +0400, Dmitry Groshev wrote: > > Hello all. Some time ago I wrote a little library: > >http://github.com/si14/python-functional-composition/, inspired by > > modern functional languages like F#. In my opinion it is quite useful > > now, but I would like to discuss it. > > An example of usage: > > > import os > > from pyfuncomp import composable, c, _ > > > def comment_cutter(s): > > ? ? t = s.find("#") > > ? ? return s if t < 0 else s[0:t].strip() > > > @composable #one can use a decorator to make a composable function > > def empty_tester(x): > > ? ? return len(x) > 0 and x[0] != "#" > > Why do you need a decorator to make a composable function? Surely all > functions are composable -- it is the nature of functions that you can > call one function with the output of another function. > > > > > path_prefix = "test" > > > config_parser = (c(open) >> ?#or use a transformer function > > ? ? ? ? ? ? ?c(str.strip).map >> #"map" acts like a function modifier > > ? ? ? ? ? ? ?c(comment_cutter).map >> > > ? ? ? ? ? ? ?empty_tester.filter >> #so does "filter" > > ? ? ? ? ? ? ?c(os.path.join)[path_prefix, _].map) #f[a, _, b] is > > used to make a partial. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #f[a, foo:bar, > > baz:_] is also correct > > > print config_parser("test.txt") > > print (c("[x ** %s for x in %s]")[2, _] << c(lambda x: x * 2).map)([1, > > 2, 3]) > > > Any suggestions are appreciated. > > Did you expect us to guess what the above code would do? Without showing > the output, the above is just line noise. > > What does c() do? What does compose() do that ordinary function > composition doesn't do? You say that "map" acts as a function modifier, > but don't tell us *what* it modifies or in what way. Same for filter. > > So anyone not familiar with C syntax, the use of << is just line noise. > You need to at say what you're using it for. > > -- > Steven Yep, it's my mistake. I thought this syntax is quite intuitive. Here is some explanations in code: @composable def f1(x): return x * 2 @composable def f2(x): return x + 3 @composable def f3(x): return (-1) * x @composable def f4(a): return a + [0] @composable def sqrsum(x, y): return x ** 2 + y ** 2 print f1(2) #4 print f2(2) #5 print (f1 << f2 << f1)(2) #14 print (f3 >> f2)(2) #1 print (f2 >> f3)(2) #-5 print (c(float) << f1 << f2)(4) #14.0 print (sqrsum[_, 1] << f1)(2) #17 print (sqrsum[_, _].map)([1, 2, 3, 4, 5]) #[2, 8, 18, 32, 50] print (c(lambda x: x * 2).map >> c("[x * %s for x in %s]")[3, _])([1, 2, 3]) #[6, 12, 18] Generally, f1 >> f2 means "lambda x: f2(f1(x))" or "pass the result of f1 to f2". But in python function can return only one value, so a composable function should be a function of one argument. So some form of making partial is needed, and here comes a f[a, b, _] notation, which means "substitute 3rd argument of f, first twos are a and b". Finally, we need some form of syntactic sugar for this: c(map)[c(f),_], so we have a "map" modifier, which transforms function F to an isomorphism or mapping between lists. For example, c(lambda x: x * 2).map is equal to lambda x: map(lambda y: y * 2, x). "Filter" modifier is the same thing for boolean functions. >What does c() do? What does compose() do that ordinary function >composition doesn't do? I need c() or composable() to make an objects with overloaded operators. All in all, all this stuff is just a syntactic sugar for nested functions, maps and filters, which brings a new semantics for old operators (so one can call it edsl). From metolone+gmane at gmail.com Sat Aug 28 23:07:23 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 28 Aug 2010 20:07:23 -0700 Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: "Steven D'Aprano" wrote in message news:4c79c510$0$28655$c3e8da3 at news.astraweb.com... > On Sat, 28 Aug 2010 16:12:36 -0700, Baba wrote: > There are other techniques, but this will do to get started. Once you realize recursion for Fibonacci numbers is still fairly slow, look up generator functions :^) -Mark From clp2 at rebertia.com Sun Aug 29 00:19:05 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 28 Aug 2010 21:19:05 -0700 Subject: Fibonacci: How to think recursively In-Reply-To: <4c79c510$0$28655$c3e8da3@news.astraweb.com> References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: On Sat, Aug 28, 2010 at 7:25 PM, Steven D'Aprano wrote: > On Sat, 28 Aug 2010 16:12:36 -0700, Baba wrote: >> Level: beginner >> >> I would like to know how to approach the following Fibonacci problem: >> my attempted rough code: >> >> def fibonacci(n): >> ? ? # base case: >> ? ? ? ? result = fibonacci (n-1) + fibonacci (n-2) >>>> this will end up in a mess as it will create overlapping recursions > > Mathematically, there is nothing wrong with overlapping recursion. It > will work, and Python can handle it easily. > > But in practical terms, it can lead to great inefficiency. In this > example, it should be avoided because it is slow. Very slow. To calculate > the nth Fibonacci number using naive recursion requires *many* calls: > > ? ?fib(4) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# first call > ? ?=> fib(3) + fib(2) ? ? ? ? ? ? ? ? ? ?# three calls > ? ?=> fib(2) + fib(1) + fib(1) + fib(0) ?# seven calls > ? ?=> fib(1) + fib(0) + 1 + 1 + 0 ? ? ? ?# nine calls > ? ?=> 1 + 0 + 1 + 1 + 0 = 3 > > So to get fib(4) = 3 requires nine calls to fib(). > > This growth function doesn't have a name (as far as I know), It's A001595 in OEIS; http://www.research.att.com/~njas/sequences/A001595 "Sometimes called 'Leonardo numbers'" Also apparently "2-ranks of difference sets constructed from Segre hyperovals." > but it grows > much faster than fib() itself: > > n ? ? ?= 0 ? 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? ... 35 ? ? ? ... > fib(n) = 0 ? 1 ? 1 ? 2 ? 3 ? 5 ? 8 ? ... 9227465 ?... > calls ?= 1 ? 1 ? 3 ? 5 ? 9 ? 15 ?25 ?... 29860703 ... > > As you can see, the number of calls is also calculable by a recursive > expression R: > > R(0) = R(1) = 1 > R(n) = R(n-1) + R(n-2) + 1 > > This is very similar to the Fibonacci recursion, only it grows more > quickly. But I digress... Other formulations courtesy OEIS: R(n) = sum(fib(i) for i in range(1, n+1)) - fib(n-1) R(n) = 2*fib(n+1) - 1 Cheers, Chris -- http://blog.rebertia.com From ptmcg at austin.rr.com Sun Aug 29 00:23:13 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 28 Aug 2010 21:23:13 -0700 (PDT) Subject: Tag parsing in python References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: On Aug 28, 11:14?am, agnibhu wrote: > Hi all, > > I'm a newbie in python. I'm trying to create a library for parsing > certain keywords. > For example say I've key words like abc: bcd: cde: like that... So the > user may use like > abc: How are you bcd: I'm fine cde: ok > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > assign them to abc:, bcd: and cde: respectively.. There may be > combination of keyowords introduced in future. like abc: xy: How are > you > So new keywords qualifying the other keywords so on.. > So I would like to know the python way of doing this. Is there any > library already existing for making my work easier. ? > > ~ > Agnibhu Here's how pyparsing can parse your keyword/tags: from pyparsing import Combine, Word, alphas, Group, OneOrMore, empty, SkipTo, LineEnd text1 = "abc: How are you bcd: I'm fine cde: ok" text2 = "abc: xy: How are you" tag = Combine(Word(alphas)+":") tag_defn = Group(OneOrMore(tag))("tag") + empty + SkipTo(tag | LineEnd())("body") for text in (text1,text2): print text for td in tag_defn.searchString(text): print td.dump() print Prints: abc: How are you bcd: I'm fine cde: ok [['abc:'], 'How are you'] - body: How are you - tag: ['abc:'] [['bcd:'], "I'm fine"] - body: I'm fine - tag: ['bcd:'] [['cde:'], 'ok'] - body: ok - tag: ['cde:'] abc: xy: How are you [['abc:', 'xy:'], 'How are you'] - body: How are you - tag: ['abc:', 'xy:'] Now here's how to further use pyparsing to actually use those tags as substitution macros: from pyparsing import Forward, MatchFirst, Literal, And, replaceWith, FollowedBy # now combine macro detection with substitution macros = {} macro_substitution = Forward() def make_macro_sub(tokens): macros[tuple(tokens.tag)] = tokens.body # define macro substitution macro_substitution << MatchFirst( [(Literal(k[0]) if len(k)==1 else And([Literal(kk) for kk in k])).setParseAction(replaceWith(v)) for k,v in macros.items()] ) + ~FollowedBy(tag) return "" tag_defn.setParseAction(make_macro_sub) scan_pattern = macro_substitution | tag_defn test_text = text1 + "\nBob said, 'abc:?' I said, 'bcd:.'" + text2 + "\nThen Bob said 'abc: xy:?'" print test_text print scan_pattern.transformString(test_text) Prints: abc: How are you bcd: I'm fine cde: ok Bob said, 'abc:?' I said, 'bcd:.'abc: xy: How are you Then Bob said 'abc: xy:?' Bob said, 'How are you?' I said, 'I'm fine.' Then Bob said 'How are you?' From greg.ewing at canterbury.ac.nz Sun Aug 29 00:39:00 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 29 Aug 2010 16:39:00 +1200 Subject: palindrome iteration In-Reply-To: <4c79b11a$0$28655$c3e8da3@news.astraweb.com> References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: <8dunm7Fv5nU1@mid.individual.net> Steven D'Aprano wrote: > I'm not entirely sure what the use-case for swapcase is. Obviously it's for correcting things that were typed in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) -- Greg From nikos.the.gr33k at gmail.com Sun Aug 29 01:13:49 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 22:13:49 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> Message-ID: <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> On 28 ???, 23:12, MRAB wrote: > On 28/08/2010 20:51, ????? wrote: > > > > > > > > > > > On 28 ???, 22:35, MRAB ?wrote: > > >> """When there's more than one value you provide a tuple. It's makes sense > >> from the point of view of consistency that you also provide a tuple when > >> there's only one value.""" > > > Can you write something that make use of more than one value? > > > Perhaps you mena somethign like? > > > cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date > > = %s and host = %s''' , (page,) ) > > > Is this what you mean? > > > All those special format strign identifiers will grab their values out > > of the tuple? > > Your example contains 3 placeholders, so it needs 3 values: > > ? ? ?cursor.execute('''SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s''', (page, date, host)) > > This will be safe. Any quoting that's needed will be done by .execute(). Will this also work without the parentheses? > cursor.execute('''SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s''', page, date, host) or python will not allow it cause it might think there are 4 args isntead of two? > cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > date = '%s' and host = '%s' ''', (page, date, host)) Whats happens if i attempt to also quote by single or double quoting the above although now i'm aware that .execute method does the quoting for me? From nikos.the.gr33k at gmail.com Sun Aug 29 01:34:25 2010 From: nikos.the.gr33k at gmail.com (=?ISO-8859-7?B?zd/q7/I=?=) Date: Sat, 28 Aug 2010 22:34:25 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> Message-ID: <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> On 28 ???, 23:15, MRAB wrote: > On 28/08/2010 20:37, ????? wrote: > > > > > > > > > > > On 22 ???, 10:27, ????? ?wrote: > >> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ?wrote: > > >>> ????? wrote: > >>>> # initializecookie > >>>> cookie=Cookie.SimpleCookie() > >>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>> mycookie =cookie.get('visitor') > > >>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>> yandex|13448|spider|crawl)', host ) is None: > >>>> ? ? ?blabla... > >>>> ======================== > > >>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>> within. > >>>> So, i have to ask why the if fails? > > >>> Maybe it's because != != == > > >> Iwant ti if code block to be executed only if the browsercookienames > >> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >> Is there somethign wrong with the way i wrote it? > > > Please do help me with this too becaus eif i dont solve this my > > website keeps count my each visit like iam a guest visitor! > > Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > repr(host). Then follow the code yourself to see whether the condition > is True. print mycookie outputs 'None' Thts weird because i check with the browser and the cookie is there! print repr(host) outputs '78-236-176.adsl.cyta.gr' repr(mycookie.value) (unless mycookie is None) and also print mycookie.value gives an error too. Maybe there is not a value method? From nikos.the.gr33k at gmail.com Sun Aug 29 01:35:41 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sat, 28 Aug 2010 22:35:41 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> Message-ID: <7b1b4e8b-835b-4b9a-81fd-9957ec4e9ece@d8g2000yqf.googlegroups.com> On 28 ???, 23:07, Peter Otten <__pete... at web.de> wrote: > ????? wrote: > > On 22 ???, 10:27, ????? wrote: > >> On 16 ???, 14:31, Peter Otten <__pete... at web.de> wrote: > >> > ????? wrote: > >> > > # initializecookie > >> > >cookie=Cookie.SimpleCookie() > >> > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >> > > mycookie =cookie.get('visitor') > > >> > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >> > > yandex|13448|spider|crawl)', host ) is None: > >> > > blabla... > >> > > ======================== > > >> > > I checked and Chrome has acookienames visitor with a value ofnikos > >> > > within. > >> > > So, i have to ask why the if fails? > > >> > Maybe it's because != != == > > >> Iwant ti if code block to be executed only if the browsercookienames > >> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >> Is there somethign wrong with the way i wrote it? > > > Please do help me with this too becaus eif i dont solve this my > > website keeps count my each visit like iam a guest visitor! > > In your initial post it sounded like you wanted the if-branch to execute for > a user named "nikos", but now it seems that I misunderstood you and swapping > 'mycookie.value != "nikos"' for 'mycookie.value == "nikos"' won't help. > Maybe you could add a print statement like > > print mycookie.value > > to start with your debugging efforts. > > Peter Maybe > # initialize cookie > cookie = Cookie.SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > mycookie = cookie.get('visitor') wont load the cookie correctly? because print mycookie.value outputs an error. From mahaboobnisha at gmail.com Sun Aug 29 01:43:27 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Sat, 28 Aug 2010 22:43:27 -0700 (PDT) Subject: comp.lang.python Message-ID: www.127760.blogspot.com From kushal.kumaran+python at gmail.com Sun Aug 29 02:11:21 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sun, 29 Aug 2010 11:41:21 +0530 Subject: looking for open source python project In-Reply-To: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> References: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> Message-ID: On Sun, Aug 29, 2010 at 6:20 AM, mo reina wrote: > looking for a python project (preferably something a bit small) that > is looking for contributors. the small bit is because i've never > worked in a team before and haven't really read source code that's > 1000s of lines long, so i'm not too sure i can keep up. > > my python fu is decent (i think), i recently wrote a small archive/ > grimoire program (command line only) that can store multiline text > with title, tags, and basic search functionality (not using curses so > the entry, once entered, can't be modified), entries are stored in a > pickle file. > > anybody have any suggestions? i'm keen to work on something with > others, both for learning and i'd like to do something a bit > meaningful, plus i'm sure it's fun. You can take a look at http://openhatch.org/ -- regards, kushal From joshua.r.english at gmail.com Sun Aug 29 02:53:54 2010 From: joshua.r.english at gmail.com (Josh English) Date: Sat, 28 Aug 2010 23:53:54 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: This whole conversation got interesting, so I thought I'd run some speed tests: The code: from timeit import Timer def is_palindrome_recursive(s): if len(s) <= 1: return True if s[0] != s[-1]: return False else: return is_palindrome(s[1:-1]) def is_palindrome_slice(s): return s == s[::-1] def is_palindrome_list(s): l = list(s) l.reverse() return s == ''.join(l) def is_palindrome_reversed(s): return s == ''.join(reversed(s)) t = Timer("is_palindrome_recursive('madamimadam')", "from __main__ import is_palindrome_recursive") print "is_palindrome_recursive", min(t.repeat()) t = Timer("is_palindrome_slice('madamimadam')", "from __main__ import is_palindrome_slice") print "is_palindrome_slice", min(t.repeat()) t = Timer("is_palindrome_list('madamimadam')", "from __main__ import is_palindrome_list") print "is_palindrome_list", min(t.repeat()) t = Timer("is_palindrome_reversed('madamimadam')", "from __main__ import is_palindrome_reversed") print "is_palindrome_reversed", min(t.repeat()) The results: is_palindrome_recursive 6.32680866827 is_palindrome_slice 1.23618350114 is_palindrome_list 4.60104846653 is_palindrome_reversed 5.99355296513 The slice method is uglier, I have to admit, but it's the fastest of these four on my machine. Josh From fetchinson at googlemail.com Sun Aug 29 03:47:40 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 29 Aug 2010 09:47:40 +0200 Subject: looking for open source python project In-Reply-To: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> References: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> Message-ID: > looking for a python project (preferably something a bit small) that > is looking for contributors. the small bit is because i've never > worked in a team before and haven't really read source code that's > 1000s of lines long, so i'm not too sure i can keep up. > > my python fu is decent (i think), i recently wrote a small archive/ > grimoire program (command line only) that can store multiline text > with title, tags, and basic search functionality (not using curses so > the entry, once entered, can't be modified), entries are stored in a > pickle file. > > anybody have any suggestions? i'm keen to work on something with > others, both for learning and i'd like to do something a bit > meaningful, plus i'm sure it's fun. Have a look at http://wiki.python.org/moin/CodingProjectIdeas Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From niceshoes1 at 163.com Sun Aug 29 03:48:32 2010 From: niceshoes1 at 163.com (jersey-2009) Date: Sun, 29 Aug 2010 00:48:32 -0700 (PDT) Subject: basketball shoe ( http://www.brandtrade66.com/ Message-ID: hox Shoes (http:// www.brandtrade66.com/) shoes shox shoes (http:// www.brandtrade66.com/) nike shox shoe (http:// www.brandtrade66.com/) nike shox shoes ( http://www.brandtrade66.com/ ) shox shoe ( http://www.brandtrade66.com/ ) LV,coach,chanel boots wholesale ( http://www.brandtrade66.com/ ) air force ones (http:// www.brandtrade66.com/) nike trading ( http://www.brandtrade66.com/ ) nike shox ( http://www.brandtrade66.com/ ) shox air ( http://www.brandtrade66.com/) white shoe (http:// www.brandtrade66.com/ ) nike shoe ( http://www.brandtrade66.com/ ) nike air shox ( http://www.brandtrade66.com/) shox r4 tennis shoes (http:// www.brandtrade66.com/ ) tennis shoe ( http://www.brandtrade66.com/) basketball shoe ( http://www.brandtrade66.com/ ) jordan shoe (http:// www.brandtrade66.com/) From arnodel at googlemail.com Sun Aug 29 04:00:08 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 09:00:08 +0100 Subject: InteractiveConsole and namespace References: Message-ID: Chris Rebert writes: > On Sat, Aug 28, 2010 at 2:37 PM, David ROBERT wrote: >> Hi all, >> >> I want to use an InteractiveConsole at some stage in a program to >> interact with the local namespace: access, but also modify objects. >> When the interactive console ends (ctrl-d) I want the program to >> continue processing with the variables that may have been modified >> interactively. >> [...] >> However, on the other code below (the console is invoked from within a >> function block), during the interactive session, I can read value of >> a, I can change value of a. But the local namespace of the function is >> not updated: >> >> import code >> def test(): >> ? ?a=1 >> ? ?c = code.InteractiveConsole(locals()) >> ? ?c.interact() # Here I interactively change the value of a (a=2) >> ? ?print "Value of a: ", a >> >> if __name__ == '__main__': >> ? ?test() >> >> print returns --> Value of a: 1 >> >> I need to run the InteractiveConsole from a function block. I tried >> different things with the local and parent frames (sys._getframe()) >> but nothing successful. If I put a in the global namespace it works, >> but I would like to > [...] >> understand what the >> problem is. > > Read http://docs.python.org/library/functions.html#locals (emphasis added): > > "locals() > [...] > Note: The contents of this dictionary should not be modified; [...] Here is a solution: def test(): a=1 loc = dict(locals()) c = code.InteractiveConsole(loc) c.interact() # Here I interactively change the value of a (a=2) for key in loc: if key != '__builtins__': exec "%s = loc[%r]" % (key, key) print "Value of a: ", a HTH -- Arnaud From lamlbiro at optusnet.com.au Sun Aug 29 04:18:26 2010 From: lamlbiro at optusnet.com.au (L) Date: Sun, 29 Aug 2010 18:18:26 +1000 Subject: PyGeo Message-ID: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu 10.04) , the site says http://www.wspiegel.de/pymaxima/index_en.html "Note: The installation of PyGeo work's only under Python 2.4 (The further development of pygeo seems to be stopped)" is this to do with re-org of site-packages, dist_packages etc. any help most appreciated. TIA From landimatte at gmail.com Sun Aug 29 05:19:24 2010 From: landimatte at gmail.com (Matteo Landi) Date: Sun, 29 Aug 2010 11:19:24 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: Well, I tried the also the solution posted above (recursive w/o slicing and iterative), and I discovered they were the slowest.. is_palindrome_recursive 2.68151649808 is_palindrome_slice 0.44510699381 is_palindrome_list 1.93861944217 is_palindrome_reversed 3.28969831976 is_palindrome_recursive_no_slicing 6.78929775328 is_palindrome_iterative 4.88826141315 Nothing to say about the iterative function, but the benchmark of the recursive was unexpected, at least for my point of view: do you think it is due to the try/except overhead? On Sun, Aug 29, 2010 at 8:53 AM, Josh English wrote: > This whole conversation got interesting, so I thought I'd run some > speed tests: > > The code: > from timeit import Timer > > def is_palindrome_recursive(s): > ? ?if len(s) <= 1: > ? ? ? ?return True > ? ?if s[0] != s[-1]: > ? ? ? ?return False > ? ?else: > ? ? ? ?return is_palindrome(s[1:-1]) > > def is_palindrome_slice(s): > ? ?return s == s[::-1] > > def is_palindrome_list(s): > ? ?l = list(s) > ? ?l.reverse() > ? ?return s == ''.join(l) > > def is_palindrome_reversed(s): > ? ?return s == ''.join(reversed(s)) > > t = Timer("is_palindrome_recursive('madamimadam')", "from __main__ > import is_palindrome_recursive") > print "is_palindrome_recursive", min(t.repeat()) > > t = Timer("is_palindrome_slice('madamimadam')", "from __main__ import > is_palindrome_slice") > print "is_palindrome_slice", min(t.repeat()) > > t = Timer("is_palindrome_list('madamimadam')", "from __main__ import > is_palindrome_list") > print "is_palindrome_list", min(t.repeat()) > > t = Timer("is_palindrome_reversed('madamimadam')", "from __main__ > import is_palindrome_reversed") > print "is_palindrome_reversed", min(t.repeat()) > > The results: > is_palindrome_recursive 6.32680866827 > is_palindrome_slice 1.23618350114 > is_palindrome_list 4.60104846653 > is_palindrome_reversed 5.99355296513 > > The slice method is uglier, I have to admit, but it's the fastest of > these four on my machine. > > Josh > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From osmoma at gmail.com Sun Aug 29 05:39:43 2010 From: osmoma at gmail.com (Osmo Maatta) Date: Sun, 29 Aug 2010 11:39:43 +0200 Subject: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails. Message-ID: <4C7A2ADF.90800@gmail.com> Hello, Sub class test fails. ====================== I have a program that needs to load plugin-classes during runtime. The program has these subdirectories (modules). $ tree . `-- test.py | |-- plugins | |-- base_plugin.py | |-- base_plugin.pyc | |-- __init__.py | `-- oca | |-- __init__.py | |-- open_clipart.py The plugins (sub directory) contains one or more plugin modules, in this test-case there is only one; oca/open_clipart.py. The plugins/base_plugin.py (contains class Plugin()) is a base class of all plugins. I want to list and load all plugin-classes (that inherit from base_plugin.Plugin). I have a Python code that successfully browses the plugins, but the the test issubclass(x, base_plugin.Plugin) fails. Please see this Python code: http://futuredesktop.com/tmp/test6.tar.gz Why the issubclass(entry, cls) test fails? if issubclass(entry, cls): ....print "Found a subclass: " + key ....subclasses.append(entry) I can see that the class names are right, even objects of these classes are ok. My OS is Ubuntu 10.04. $ python --version Python 2.6.5 The actual, final product will be this http://www.futuredesktop.com/clipart-applet/clipart-applet.ogv It is a ClipArt query-engine and browser. It can translate queries from "any" language to english ;-) Most kindly Osmo Antero Maatta Gr?nland, Oslo From hansmu at xs4all.nl Sun Aug 29 05:45:26 2010 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 29 Aug 2010 11:45:26 +0200 Subject: Queue cleanup In-Reply-To: <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > On Sat, 28 Aug 2010 00:33:10 -0700, Paul Rubin wrote: >> If you drop the last reference >> to a complex structure, it could take quite a long time to free all the >> components. By contrast there are provably real-time tracing gc >> schemes, including some parallelizeable ones. > > I could be wrong, but how can they not be subject to the same performance > issue? If you have twenty thousand components that all have to be freed, > they all have to be freed whether you do it when the last reference is > cleared, or six seconds later when the gc does a sweep. Parallelizable garbage collectors have performance issues, but they're not the same issues as mark&sweep collectors have. Parallelizable GCs break up their work in a zillion little pieces and allow the VM to do some real work after each piece. They won't free your twenty thousand components all in one go and you won't have that embarrassing pause. Parallelizable garbage collectors require some careful coordination between the GC and the VM. This takes CPU time, so on the whole they're slower than traditional garbage collectors. So instead of unpredictable embarrassing pauses, you have a VM that's consistently slow. For some applications consistency is more important than raw speed and for these applications parallelizeable GCs are an improvement. HTH, -- HansM From arnodel at googlemail.com Sun Aug 29 06:36:57 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 11:36:57 +0100 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: Matteo Landi writes: > Well, I tried the also the solution posted above (recursive w/o > slicing and iterative), and I discovered they were the slowest.. > > is_palindrome_recursive 2.68151649808 > is_palindrome_slice 0.44510699381 > is_palindrome_list 1.93861944217 > is_palindrome_reversed 3.28969831976 > is_palindrome_recursive_no_slicing 6.78929775328 > is_palindrome_iterative 4.88826141315 What are the last two functions? I suggest another: def is_palindrome(s): return all(map(str.__eq__, s, reversed(s))) :) > Nothing to say about the iterative function, but the benchmark of the > recursive was unexpected, at least for my point of view: do you think > it is due to the try/except overhead? > > On Sun, Aug 29, 2010 at 8:53 AM, Josh English > wrote: >> This whole conversation got interesting, so I thought I'd run some >> speed tests: >> >> The code: >> from timeit import Timer >> >> def is_palindrome_recursive(s): >> ? ?if len(s) <= 1: >> ? ? ? ?return True >> ? ?if s[0] != s[-1]: >> ? ? ? ?return False >> ? ?else: >> ? ? ? ?return is_palindrome(s[1:-1]) This should be return is_palindrome_recursive(s[1:-1]). If this is copy-pasted, then you may call a different is_palindrome function and invalidate the timings! [...] -- Arnaud From arnodel at googlemail.com Sun Aug 29 06:40:28 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 11:40:28 +0100 Subject: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails. References: Message-ID: Osmo Maatta writes: > Hello, > > Sub class test fails. > ====================== > I have a program that needs to load plugin-classes during runtime. > > The program has these subdirectories (modules). > > $ tree > . > `-- test.py > | > |-- plugins > | |-- base_plugin.py > | |-- base_plugin.pyc > | |-- __init__.py > | `-- oca > | |-- __init__.py > | |-- open_clipart.py > > > The plugins (sub directory) contains one or more plugin modules, in this > test-case there is only one; oca/open_clipart.py. > > The plugins/base_plugin.py (contains class Plugin()) is a base class of > all plugins. > > I want to list and load all plugin-classes (that inherit from > base_plugin.Plugin). I have a Python code that successfully browses the > plugins, but the the test issubclass(x, base_plugin.Plugin) fails. > > Please see this Python code: > http://futuredesktop.com/tmp/test6.tar.gz > > Why the issubclass(entry, cls) test fails? > > if issubclass(entry, cls): > ....print "Found a subclass: " + key > ....subclasses.append(entry) > > I can see that the class names are right, even objects of these classes > are ok. > > My OS is Ubuntu 10.04. > $ python --version > Python 2.6.5 > > The actual, final product will be this > http://www.futuredesktop.com/clipart-applet/clipart-applet.ogv > It is a ClipArt query-engine and browser. > It can translate queries from "any" language to english ;-) > > Most kindly > Osmo Antero Maatta > Gr?nland, Oslo Hi, I haven't looked closely at your problem, but are you aware of the __subclasses__ class method? E.g. >>> class A(object): pass ... >>> class B(A): pass ... >>> class C(A): pass ... >>> A.__subclasses__() [, ] >>> This might help you. -- Arnaud From landimatte at gmail.com Sun Aug 29 06:45:54 2010 From: landimatte at gmail.com (Matteo Landi) Date: Sun, 29 Aug 2010 12:45:54 +0200 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: I thought they reached you. Here they are again: def palindrome(str, i=0, j=-1): try: if str[i] == str[j]: return palindrome(str, i + 1, j - 1) return False except IndexError: return True def palindrome(str, i=0, j=-1): try: while True: if str[i] != str[j]: return False i, j = i + 1, j - 1 return True except IndexError: return True On Sun, Aug 29, 2010 at 12:36 PM, Arnaud Delobelle wrote: > Matteo Landi writes: > >> Well, I tried the also the solution posted above (recursive w/o >> slicing and iterative), and I discovered they were the slowest.. >> >> is_palindrome_recursive 2.68151649808 >> is_palindrome_slice 0.44510699381 >> is_palindrome_list 1.93861944217 >> is_palindrome_reversed 3.28969831976 >> is_palindrome_recursive_no_slicing 6.78929775328 >> is_palindrome_iterative 4.88826141315 > > What are the last two functions? > > I suggest another: > > def is_palindrome(s): > ? ?return all(map(str.__eq__, s, reversed(s))) > > :) > >> Nothing to say about the iterative function, but the benchmark of the >> recursive was unexpected, at least for my point of view: do you think >> it is due to the try/except overhead? >> >> On Sun, Aug 29, 2010 at 8:53 AM, Josh English >> wrote: >>> This whole conversation got interesting, so I thought I'd run some >>> speed tests: >>> >>> The code: >>> from timeit import Timer >>> >>> def is_palindrome_recursive(s): >>> ? ?if len(s) <= 1: >>> ? ? ? ?return True >>> ? ?if s[0] != s[-1]: >>> ? ? ? ?return False >>> ? ?else: >>> ? ? ? ?return is_palindrome(s[1:-1]) > > This should be return is_palindrome_recursive(s[1:-1]). ?If this is > copy-pasted, then you may call a different is_palindrome function and > invalidate the timings! > > [...] > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From sazzadbinkamal at gmail.com Sun Aug 29 07:04:33 2010 From: sazzadbinkamal at gmail.com (Sazzad Kamal) Date: Sun, 29 Aug 2010 11:04:33 GMT Subject: setuptools msvc build References: Message-ID: <20108297426usenet@eggheadcafe.com> is it possible to build python setuptools with msvc? > On Monday, July 12, 2010 4:59 PM Alf P. Steinbach /Usenet wrote: > I let the setup.py script talk: > > > > > from distutils.core import setup, Extension > import distutils.ccompiler > > compilerName = distutils.ccompiler.get_default_compiler() > options = [] > if compilerName == "msvc": > options.append( "/W4" ) # Must be done in this script. > options.append( "/EHsc" ) # Could be done via CL env. var. > options.append( "/GR" ) # Could be done via CL env. var. > options.append( "/Zc:forScope,wchar_t" ) # Could be done via CL env. var. > > module1 = Extension( > name = "noddy", > sources = [ "noddy.cpp" ], > extra_compile_args = options > ) > > setup( > name = "noddy", > version = '1.0', > description = 'This is a demo package', > ext_modules = [module1] > ) > > > > Cheers, > > - Alf > > -- > Submitted via EggHeadCafe - Software Developer Portal of Choice > Custom Favorites Web Site with MongoDb and NoRM > http://www.eggheadcafe.com/tutorials/aspnet/7fbc7a01-5d30-4cd3-b373-51d4a0e1afa8/custom-favorites-web-site-with-mongodb-and-norm.aspx From __peter__ at web.de Sun Aug 29 07:06:33 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Aug 2010 13:06:33 +0200 Subject: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails. References: Message-ID: Osmo Maatta wrote: > Hello, > > Sub class test fails. > ====================== > I have a program that needs to load plugin-classes during runtime. > > The program has these subdirectories (modules). > > $ tree > . > `-- test.py > | > |-- plugins > | |-- base_plugin.py > | |-- base_plugin.pyc > | |-- __init__.py > | `-- oca > | |-- __init__.py > | |-- open_clipart.py > > > The plugins (sub directory) contains one or more plugin modules, in this > test-case there is only one; oca/open_clipart.py. > > The plugins/base_plugin.py (contains class Plugin()) is a base class of > all plugins. > > I want to list and load all plugin-classes (that inherit from > base_plugin.Plugin). I have a Python code that successfully browses the > plugins, but the the test issubclass(x, base_plugin.Plugin) fails. > > Please see this Python code: > http://futuredesktop.com/tmp/test6.tar.gz > > Why the issubclass(entry, cls) test fails? base_plugin.py is imported twice, once as plugins.base_plugin and a second time as base_plugin. You can see that when you add a bit more debug code into your test.py: --- a/test.py Sun Aug 29 12:57:25 2010 +0200 +++ b/test.py Sun Aug 29 12:58:25 2010 +0200 @@ -24,6 +24,8 @@ #print "entry's class<%s> -- cls's class=<%s>" % (obj1.get_name(), obj2.get_name(), ) print "Check %s against %s" % (entry, cls, ) + print entry.__bases__ + print cls if issubclass(entry, cls): print "Found a subclass: " + key $ python test.py Importing plugins.base_plugin Importing plugins.oca.open_clipart Check against (,) Got subclasses= [] The solution is to remove all sys.path gymnastics and to adapt your import statements accordingly: $ hg diff diff -r 9fe6129ba8fc plugins/oca/open_clipart.py --- a/plugins/oca/open_clipart.py Sun Aug 29 12:51:51 2010 +0200 +++ b/plugins/oca/open_clipart.py Sun Aug 29 13:02:55 2010 +0200 @@ -2,9 +2,7 @@ import os import threading, thread -sys.path.insert(0, '..') -import base_plugin -#sys.path.insert(0, '../..') +from .. import base_plugin # ------------------------------------------ # class OpenClipArt diff -r 9fe6129ba8fc test.py --- a/test.py Sun Aug 29 12:51:51 2010 +0200 +++ b/test.py Sun Aug 29 13:02:55 2010 +0200 @@ -1,7 +1,6 @@ import os, sys import inspect -sys.path.insert(0, "plugins") # Thanks to http://www.luckydonkey.com/2008/01/02/python-style-plugins- made-easy/ def find_subclasses(path, cls): $ python test.py Importing plugins.base_plugin Importing plugins.oca.open_clipart Check against Found a subclass: OpenClipArt Got subclasses= [] You should also remove the __init__.py from the folder containing test.py which is just begging for the same problem when you import your plugins as test.plugins.whatever. Peter From news1234 at free.fr Sun Aug 29 07:42:07 2010 From: news1234 at free.fr (News123) Date: Sun, 29 Aug 2010 13:42:07 +0200 Subject: Fibonacci: How to think recursively In-Reply-To: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: <4c7a4793$0$5857$426a74cc@news.free.fr> On 08/29/2010 01:12 AM, Baba wrote: > Level: beginner > > I would like to know how to approach the following Fibonacci problem: > How may rabbits do i have after n months? > > I'm not looking for the code as i could Google that very easily. I'm > looking for a hint to put me on the right track to solve this myself > without looking it up. > > my brainstorming so far brought me to a stand still as i can't seem to > imagine a recursive way to code this: > > my attempted rough code: > > def fibonacci(n): > # base case: > result = fibonacci (n-1) + fibonacci (n-2) >>> this will end up in a mess as it will create overlapping recursions > > OR > > def fibonacci(n): > # base case: > fibonacci(n+2) - fibonacci(n+1) - n = 0 >>> this too would create overlapping recursions > Hi Baba, Let's take another example: factorials: Trivial, but you 'just have to apply the same techniques FIbonacci n! = 1 * 2 * 3 . . . * n Very first thing is to always find a trivial case, or the terminal condition. Tjis is, when you reduced the problem to the most trivial case(s), for which you don't need anymore recursion for factorials this would be 0! = 1 for Fibonacci you might have multiple trivial cases and the recursive definition of factorial is\ n! = (n - 1) * n so the code for factorial looks something like: def factorial(n): if n == 0: # treat the trivial case / cases for which ou know the answer return 1 else: # reduce the problem by the recursive definition return factorial(n-1)*n Hope this helps. From ptmcg at austin.rr.com Sun Aug 29 08:43:49 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 29 Aug 2010 05:43:49 -0700 (PDT) Subject: Tag parsing in python References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: On Aug 28, 11:23?pm, Paul McGuire wrote: > On Aug 28, 11:14?am, agnibhu wrote: > > > > > > > Hi all, > > > I'm a newbie in python. I'm trying to create a library for parsing > > certain keywords. > > For example say I've key words like abc: bcd: cde: like that... So the > > user may use like > > abc: How are you bcd: I'm fine cde: ok > > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > > assign them to abc:, bcd: and cde: respectively.. There may be > > combination of keyowords introduced in future. like abc: xy: How are > > you > > So new keywords qualifying the other keywords so on.. I got to thinking more about your keywords-qualifying-keywords example, and I thought this would be a good way to support locale- specific tags. I also thought how one might want to have tags within tags, to be substituted later, requiring a "abc::" escaped form of "abc:", so that the tag is substituted with the value of tag "abc:" as a late binding. Wasn't too hard to modify what I posted yesterday, and now I rather like it. -- Paul # tag_substitute.py from pyparsing import (Combine, Word, alphas, FollowedBy, Group, OneOrMore, empty, SkipTo, LineEnd, Optional, Forward, MatchFirst, Literal, And, replaceWith) tag = Combine(Word(alphas) + ~FollowedBy("::") + ":") tag_defn = Group(OneOrMore(tag))("tag") + empty + SkipTo(tag | LineEnd())("body") + Optional(LineEnd().suppress()) # now combine macro detection with substitution macros = {} macro_substitution = Forward() def make_macro_sub(tokens): # unescape '::' and substitute any embedded tags tag_value = macro_substitution.transformString(tokens.body.replace("::",":")) # save this tag and value (or overwrite previous) macros[tuple(tokens.tag)] = tag_value # define overall macro substitution expression macro_substitution << MatchFirst( [(Literal(k[0]) if len(k)==1 else And([Literal(kk) for kk in k])).setParseAction(replaceWith(v)) for k,v in macros.items()] ) + ~FollowedBy(tag) # return empty string, so macro definitions don't show up in final # expanded text return "" tag_defn.setParseAction(make_macro_sub) # define pattern for macro scanning scan_pattern = macro_substitution | tag_defn sorry = """\ nm: Dave sorry: en: I'm sorry, nm::, I'm afraid I can't do that. sorry: es: Lo siento nm::, me temo que no puedo hacer eso. Hal said, "sorry: en:" Hal dijo, "sorry: es:" """ print scan_pattern.transformString(sorry) Prints: Hal said, "I'm sorry, Dave, I'm afraid I can't do that." Hal dijo, "Lo siento Dave, me temo que no puedo hacer eso." From osmoma at gmail.com Sun Aug 29 08:57:44 2010 From: osmoma at gmail.com (Osmo Maatta) Date: Sun, 29 Aug 2010 14:57:44 +0200 Subject: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails. In-Reply-To: References: Message-ID: <4C7A5948.1030306@gmail.com> Re-hi and thank you. That solved my problem. I can now see that the base_plugin.Plugin is loaded several times. The numeric id(the_class) is not the same in all places. Anyway, I thought that a class is always the same if it has been loaded from the same module (in Linux/Unix; from the same file and inode). So this experience was a bit confusing. I need to learn more about how to set the search path (sys.path) right. More Python! Thanks Osmo Antero Gr?nland, Oslo On 08/29/2010 01:06 PM, Peter Otten wrote: > Osmo Maatta wrote: > >> Hello, >> >> Sub class test fails. >> ====================== >> I have a program that needs to load plugin-classes during runtime. >> >> The program has these subdirectories (modules). >> >> $ tree >> . >> `-- test.py >> | >> |-- plugins >> | |-- base_plugin.py >> | |-- base_plugin.pyc >> | |-- __init__.py >> | `-- oca >> | |-- __init__.py >> | |-- open_clipart.py >> >> >> The plugins (sub directory) contains one or more plugin modules, in this >> test-case there is only one; oca/open_clipart.py. >> >> The plugins/base_plugin.py (contains class Plugin()) is a base class of >> all plugins. >> >> I want to list and load all plugin-classes (that inherit from >> base_plugin.Plugin). I have a Python code that successfully browses the >> plugins, but the the test issubclass(x, base_plugin.Plugin) fails. >> >> Please see this Python code: >> http://futuredesktop.com/tmp/test6.tar.gz >> >> Why the issubclass(entry, cls) test fails? > > base_plugin.py is imported twice, once as plugins.base_plugin and a second > time as base_plugin. You can see that when you add a bit more debug code > into your test.py: > > > --- a/test.py Sun Aug 29 12:57:25 2010 +0200 > +++ b/test.py Sun Aug 29 12:58:25 2010 +0200 > @@ -24,6 +24,8 @@ > #print "entry's class<%s> -- cls's class=<%s>" % > (obj1.get_name(), obj2.get_name(), ) > > print "Check %s against %s" % (entry, cls, ) > + print entry.__bases__ > + print cls > > if issubclass(entry, cls): > print "Found a subclass: " + key > > $ python test.py > Importing plugins.base_plugin > Importing plugins.oca.open_clipart > Check against 'plugins.base_plugin.Plugin'> > (,) > > Got subclasses= [] > > The solution is to remove all sys.path gymnastics and to adapt your import > statements accordingly: > > $ hg diff > diff -r 9fe6129ba8fc plugins/oca/open_clipart.py > --- a/plugins/oca/open_clipart.py Sun Aug 29 12:51:51 2010 +0200 > +++ b/plugins/oca/open_clipart.py Sun Aug 29 13:02:55 2010 +0200 > @@ -2,9 +2,7 @@ > import os > import threading, thread > > -sys.path.insert(0, '..') > -import base_plugin > -#sys.path.insert(0, '../..') > +from .. import base_plugin > > # ------------------------------------------ > # class OpenClipArt > diff -r 9fe6129ba8fc test.py > --- a/test.py Sun Aug 29 12:51:51 2010 +0200 > +++ b/test.py Sun Aug 29 13:02:55 2010 +0200 > @@ -1,7 +1,6 @@ > import os, sys > import inspect > > -sys.path.insert(0, "plugins") > > # Thanks to http://www.luckydonkey.com/2008/01/02/python-style-plugins- > made-easy/ > def find_subclasses(path, cls): > > > $ python test.py > Importing plugins.base_plugin > Importing plugins.oca.open_clipart > Check against 'plugins.base_plugin.Plugin'> > Found a subclass: OpenClipArt > Got subclasses= [] > > You should also remove the __init__.py from the folder containing test.py > which is just begging for the same problem when you import your plugins as > test.plugins.whatever. > > Peter > From gelonida at gmail.com Sun Aug 29 09:00:45 2010 From: gelonida at gmail.com (Gelonida) Date: Sun, 29 Aug 2010 15:00:45 +0200 Subject: controlling the mouse pointer on linux (or as vnc client) Message-ID: Hi, >From a python script I'd like to be able to move the mouse to certain absolute coordinates on the screen. There's no problems calling an external program with subprocess.popen, as I do not want to perform many movements. The mouse can jump it doesn't have to visibly move to the target coordinate. What would you suggest to achieve this on Linux Ubuntu 10.4? Lateron it would be intersting to acheive the same on a Windows PC One idea, that I had (for a cross platform solution) would be to start a VNC server on localhost and the current display and run a small custom VNC client, which will only control the mouse. However I have no idea how easy it would be to use a custom VNC client for moving the mouse. I read about python-vnc-viewer but don't know how complex it would be to use it as a base for 'just moving the mouse' Thanks for any suggestions and ideas From bruno.desthuilliers at gmail.com Sun Aug 29 09:19:01 2010 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 29 Aug 2010 06:19:01 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c778ab6$0$4778$426a74cc@news.free.fr> <4c77cef1$0$20290$426a74cc@news.free.fr> Message-ID: <9fd03df8-a8e3-4781-8d72-c129fee20d8f@z28g2000yqh.googlegroups.com> On 27 ao?t, 18:20, Mark Lawrence wrote: > On 27/08/2010 15:43, Bruno Desthuilliers wrote: > > > Dave Angel a ?crit : > > (snip) > > >> or (untested) > >> def is_palindrom(s): > >> s = s.lower() > >> return s == s[::-1] > > > Right, go on, make me feel a bit more stupid :-/ > > Who's next ? > > It could be worse, try responding to issue 9702. :) lol ! Nice one, indeed. From raoulbia at gmail.com Sun Aug 29 09:43:40 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 29 Aug 2010 06:43:40 -0700 (PDT) Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: On Aug 29, 3:25?am, Steven D'Aprano wrote: > Mathematically, there is nothing wrong with overlapping recursion. It > will work, and Python can handle it easily. Based on the advice by Steven and Mel i tried my initial 'guess' and it does seem to work fine. When looking at it using pencil and paper i thought "well, each recursive call will call 2 new ones and if n is large i will have a huge overlap, so it probably is the wrong approach". However it turns out to be fine in principle. It can be handled, as Steven pointed out. > But in practical terms, it can lead to great inefficiency. In this > example, it should be avoided because it is slow. Very slow. To calculate > the nth Fibonacci number using naive recursion requires *many* calls: > > You can make it even more efficient by giving fib() a long-term cache, so > that each call to fib(5) requires one cache lookup rather than six (or > fifteen) recursive calls. Other than the first time, obviously. This is > called memoisation, but again I digress. > I looked memoisation up and decided that for now i will not go near it. First i will try to build up some bacic skills but thank you very much for the hint. Memoisation will certainly be on the list of future exercises. However, the idea that memoisation is needed to make the computation more efficient confirms my initial feeling that a 'simple' recursive approach is somewhat not ideal. So here's my code. It does still cause me one headache. If i use f(0)=0 and f(1)=1 as base cases the result will be 144. I was expecting the result to be the next value in the series (233)... If i use f(1)=1 and f(2)=2 as base cases them i get my expected result. I assume this has to do with our understanding/defining the start of the Fibonacci series? def r_fib(n): if n == 1: return 1 elif n == 2: return 2 else: return r_fib(n-2) + r_fib(n-1) print r_fib(12) Thanks Baba From michael.a.powe at gmail.com Sun Aug 29 10:22:33 2010 From: michael.a.powe at gmail.com (naugiedoggie) Date: Sun, 29 Aug 2010 07:22:33 -0700 (PDT) Subject: Using a function for regular expression substitution Message-ID: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Hello, I'm having a problem with using a function as the replacement in re.sub(). Here is the function: def normalize(s) : return urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) The purpose of this function is to proper-case the words contained in a URL query string parameter value. I'm massaging data in web log files. In case it matters, the regex pattern looks like this: provider_pattern = r'(?PSearch_Provider)=(?P[^&]+)' The call looks like this: re.sub(matcher,normalize,line) Where line is the log line entry. What I get back is first the entire line with the normalization of the parameter value, but missing the parameter; then appended to that string is the entire line again, with the query parameter back in place pointing to the normalized string. >>> fileReader = open(log,'r') >>> >>> lines = fileReader.readlines() >>> for line in lines: if line.find('Search_Type') != -1 and line.find('Search_Provider') != -1 : re.sub(provider_matcher,normalize,line) print line,'\n' The output of the print is like this: 'log-entry parameter=value&normalized-string¶meter=value\n log-entry parameter=value¶meter=normalized-string¶meter=value' The goal is to massage the specified entries in the log files and write the entire log back into a new file. The new file has to be exactly the same as the old one, with the exception of the entries I've altered with my function. No doubt I'm doing something trivially wrong, but I've tried to reproduce the structure as defined in the documentation. Thanks. mp From john at castleamber.com Sun Aug 29 10:25:36 2010 From: john at castleamber.com (John Bokma) Date: Sun, 29 Aug 2010 09:25:36 -0500 Subject: controlling the mouse pointer on linux (or as vnc client) References: Message-ID: <87r5hhmr6n.fsf@castleamber.com> Gelonida writes: > Hi, > >>From a python script I'd like to be able to move the mouse to certain > absolute coordinates on the screen. > > > There's no problems calling an external program with subprocess.popen, > as I do not want to perform many movements. xte? sudo apt-get install xautomation xte 'mousemove 200 200' see: http://linux.die.net/man/1/xte -- John Bokma j3b Blog: http://johnbokma.com/ Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ From nfdisco at gmail.com Sun Aug 29 10:44:47 2010 From: nfdisco at gmail.com (ernest) Date: Sun, 29 Aug 2010 07:44:47 -0700 (PDT) Subject: in place functions from operator module Message-ID: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Hi, The operator module provides separate functions for "in place" operations, such as iadd(), isub(), etc. However, it appears that these functions don't really do the operation in place: In [34]: a = 4 In [35]: operator.iadd(a, 3) Out[35]: 7 In [36]: a Out[36]: 4 So, what's the point? If you have to make the assignment yourself... I don't understand. Cheers, Ernest From __peter__ at web.de Sun Aug 29 11:00:22 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Aug 2010 17:00:22 +0200 Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: ernest wrote: > The operator module provides separate functions for > "in place" operations, such as iadd(), isub(), etc. > However, it appears that these functions don't really > do the operation in place: > > In [34]: a = 4 > > In [35]: operator.iadd(a, 3) > Out[35]: 7 > > In [36]: a > Out[36]: 4 > > So, what's the point? If you have to make the > assignment yourself... I don't understand. Integers are immutable, and for instances a of immutable types a += b is equivalent to a = a + b For mutable types like list add() and iadd() may differ: >>> a = ["first"] >>> operator.iadd(a, [42]) ['first', 42] >>> a ['first', 42] >>> a = ["first"] >>> operator.add(a, [42]) ['first', 42] >>> a ['first'] Peter From roy at panix.com Sun Aug 29 11:10:37 2010 From: roy at panix.com (Roy Smith) Date: Sun, 29 Aug 2010 11:10:37 -0400 Subject: Using a function for regular expression substitution References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: In article <9170aad0-478a-4222-b6e2-88d00899d8b4 at t2g2000yqe.googlegroups.com>, naugiedoggie wrote: > Hello, > > I'm having a problem with using a function as the replacement in > re.sub(). > > Here is the function: > > def normalize(s) : > return > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) I read though this entire post, and I'm not quite sure what you're asking. May I suggest that you need to break this down into smaller pieces and find a minimal test case. I'm guessing this is a problem with the regex processing. To prove that, strip away everything else and verify that part in isolation. Compile your regex, and match it against a string that you expect it to match. Then, examine the groups returned by the match object. If they're not what you expect, then re-post your question, with just this minimal test code. From nfdisco at gmail.com Sun Aug 29 11:29:11 2010 From: nfdisco at gmail.com (ernest) Date: Sun, 29 Aug 2010 08:29:11 -0700 (PDT) Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: <18f9b1ad-a549-4922-b346-393cf72ddc20@y11g2000yqm.googlegroups.com> On 29 Ago, 17:00, Peter Otten <__pete... at web.de> wrote: > ernest wrote: > > The operator module provides separate functions for > > "in place" operations, such as iadd(), isub(), etc. > > However, it appears that these functions don't really > > do the operation in place: > > > In [34]: a = 4 > > > In [35]: operator.iadd(a, 3) > > Out[35]: 7 > > > In [36]: a > > Out[36]: 4 > > > So, what's the point? If you have to make the > > assignment yourself... I don't understand. > > Integers are immutable, and for instances a of immutable types > > a += b > > is equivalent to > > a = a + b > > For mutable types like list add() and iadd() may differ: > > >>> a = ["first"] > >>> operator.iadd(a, [42]) > ['first', 42] > >>> a > > ['first', 42] > > >>> a = ["first"] > >>> operator.add(a, [42]) > ['first', 42] > >>> a > > ['first'] It makes sense now. Thank you :) Ernest From arnodel at googlemail.com Sun Aug 29 11:33:58 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 16:33:58 +0100 Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: ernest writes: > Hi, > > The operator module provides separate functions for > "in place" operations, such as iadd(), isub(), etc. > However, it appears that these functions don't really > do the operation in place: > > In [34]: a = 4 > > In [35]: operator.iadd(a, 3) > Out[35]: 7 > > In [36]: a > Out[36]: 4 > > So, what's the point? If you have to make the > assignment yourself... I don't understand. > > Cheers, > Ernest That's because a += b is executed as: a = a.__iadd__(b) For immutable objects, (such as integers), a.__iadd__(b) returns a + b *and then* this value is assigned to a (or rather 'a' is bound to the value). So for immutables objects, iadd(a, b) is the same as a + b For mutable objects (such as lists), a.__iadd__(b) mutates the object *and then* returns self so that when the assignement is executed, 'a' will still be bound the the same object. E.g. if a = [1, 2] then a += [3] will first append 3 to the list and then reassign the list to 'a' (it is unnecessary in this case but if this step was omitted, the "in place" operators wouldn't work on immutables types). -- Arnaud From gelonida at gmail.com Sun Aug 29 11:35:31 2010 From: gelonida at gmail.com (Gelonida) Date: Sun, 29 Aug 2010 17:35:31 +0200 Subject: controlling the mouse pointer on linux (or as vnc client) In-Reply-To: <87r5hhmr6n.fsf@castleamber.com> References: <87r5hhmr6n.fsf@castleamber.com> Message-ID: Hi John, > Hi, > >>From a python script I'd like to be able to move the mouse to certain > absolute coordinates on the screen. > > > There's no problems calling an external program with subprocess.popen, > as I do not want to perform many movements. > > The mouse can jump it doesn't have to visibly move to the target coordinate. > > > > What would you suggest to achieve this on Linux Ubuntu 10.4? > > Lateron it would be intersting to acheive the same on a Windows PC > On 08/29/2010 04:25 PM, John Bokma wrote: > sudo apt-get install xautomation > xte 'mousemove 200 200' > Thanks a lot. This solution is perfect for Linux. Exactly what I was looking for. :-) I guess for Windows it would be a little more complicated? bye G From tjreedy at udel.edu Sun Aug 29 11:35:56 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Aug 2010 11:35:56 -0400 Subject: Using a function for regular expression substitution In-Reply-To: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: On 8/29/2010 10:22 AM, naugiedoggie wrote: > Hello, > > I'm having a problem with using a function as the replacement in > re.sub(). > > Here is the function: > > def normalize(s) : > return > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) To debug your problem, I would start with print(s) in the function and if still not clear, unnest the expression and print intermediate results. -- Terry Jan Reedy From alain at dpt-info.u-strasbg.fr Sun Aug 29 11:55:55 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 29 Aug 2010 17:55:55 +0200 Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> Message-ID: <87hbidqupg.fsf@dpt-info.u-strasbg.fr> Baba writes: > Level: beginner > > I would like to know how to approach the following Fibonacci problem: > How may rabbits do i have after n months? > > I'm not looking for the code as i could Google that very easily. I'm > looking for a hint to put me on the right track to solve this myself > without looking it up. fib(n) = fib(n-1) + fib(n-2), so you need the two previous values to compute the next one (that's the main difference between fibonacci and factorial). So here is a hint: instead of computing only fib(n), compute a pair (fib(n),fib(n-1)). It now becomes a problem very similar to factorial: for instance, what's (fib(7),fib(6)) if you have the values of (fib(6),fib(5))? Now write a recursive function fib2(n) that returns the last two values. And a simple wrapper fib(n) that calls fib2(n) and returns the first element of the pair. -- Alain. From python at mrabarnett.plus.com Sun Aug 29 13:14:15 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Aug 2010 18:14:15 +0100 Subject: Using a function for regular expression substitution In-Reply-To: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: <4C7A9567.6090401@mrabarnett.plus.com> On 29/08/2010 15:22, naugiedoggie wrote: > Hello, > > I'm having a problem with using a function as the replacement in > re.sub(). > > Here is the function: > > def normalize(s) : > return > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) This normalises the provider and returns only that, and none of the remainder of the string. I think you might want this: def normalize(s): return s[ : s.start('provider')] + urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + s[s.start('provider') : ] It returns the part before the provider, followed by the normalised provider, and then the part after the provider. > > The purpose of this function is to proper-case the words contained in > a URL query string parameter value. I'm massaging data in web log > files. > > In case it matters, the regex pattern looks like this: > > provider_pattern = r'(?PSearch_Provider)=(?P[^&]+)' > > The call looks like this: > > > re.sub(matcher,normalize,line) > > > Where line is the log line entry. > > What I get back is first the entire line with the normalization of the > parameter value, but missing the parameter; then appended to that > string is the entire line again, with the query parameter back in > place pointing to the normalized string. > > >>>> fileReader = open(log,'r') >>>> >>>> lines = fileReader.readlines() >>>> for line in lines: > if line.find('Search_Type') != -1 and line.find('Search_Provider') != > -1 : These can be replaced by: if 'Search_Type' in line and 'Search_Provider' in line: > re.sub(provider_matcher,normalize,line) re.sub is returning the result, which you're throwing away! line = re.sub(provider_matcher,normalize,line) > print line,'\n' > > > The output of the print is like this: > > > 'log-entry parameter=value&normalized-string¶meter=value\n > log-entry parameter=value¶meter=normalized-string¶meter=value' > > > The goal is to massage the specified entries in the log files and > write the entire log back into a new file. The new file has to be > exactly the same as the old one, with the exception of the entries > I've altered with my function. > > No doubt I'm doing something trivially wrong, but I've tried to > reproduce the structure as defined in the documentation. > From raoulbia at gmail.com Sun Aug 29 13:36:45 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 29 Aug 2010 10:36:45 -0700 (PDT) Subject: Fibonacci: returning a selection of the series Message-ID: level: beginner i would like to return a selection of the Fibonacci series. example: start = 5 ; end = 55 the function should then return [5, 8, 13, 21, 34, 55] it seems that this is best resolved using an iterative approach to generate the series. In another post (http://groups.google.ie/group/ comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach which seems best to compute the nth number but it seems to me that the recursive code is not suited for generating the actual list. my questios: - would you agree that recursive is not ideal for generating a list? (in this particular case and in general) - can my code below be optimised? - how to deal with 'start' and 'end' values that are not in the list e.g. 4,76 ? def i_fib(n): a = 0 b = 1 list = [] counter = 0 while counter < n: a, b = b, a+b counter += 1 list = list + [b,] return list def fib_range(start,end): list = i_fib(12) if start in list and end in list: start = list.index(start) end = list.index(end) print list[start:end+1] else: print 'not in list' fib_range(5,55) thanks Baba From alain at dpt-info.u-strasbg.fr Sun Aug 29 14:18:55 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 29 Aug 2010 20:18:55 +0200 Subject: Fibonacci: returning a selection of the series References: Message-ID: <87d3t1qo34.fsf@dpt-info.u-strasbg.fr> Baba writes: > i would like to return a selection of the Fibonacci series. > example: > start = 5 ; end = 55 > the function should then return [5, 8, 13, 21, 34, 55] [...] > my questios: > - would you agree that recursive is not ideal for generating a list? > (in this particular case and in general) I would not, in the general case. Well-known problems like fact or fib have been scrutinized in so much detail that I find it hard to conclude anything by looking at them. And problems producing lists are usually "easy" to transform from one version to the other. However in the general case, to me, the recursive version is usually much easier to understand, and the iterative version is just an optimization to save space. There are recursive algorithms that I would have trouble to write in an iterative way (unless I use an explicit stack, but that doesn't really count). We'll stay with the iterative version here, because you've started with that and you're not far from the solution. But when you're done, try to think about a recursive version. When the goal is to produce a list, the recursion scheme is almost immediate: produce one element per call, one after the other. > - can my code below be optimised? Sure. What's this 12 there? Why traversing the list three times (index() needs to traverse at least some part of it)? And... > - how to deal with 'start' and 'end' values that are not in the list > e.g. 4,76 ? In general, if you have a program that produces something just to remove/ignore it five lines later, you have a problem. In your case: 1) are you sure you need to append to list(*) at every iteration? When do you *really* need to? And... 2) your loop runs up to n (the index of the fib number), but you want to stop on some fib number value (not index). So, why not pass start and end to i_fib, and use them where appropriate? -- Alain. (*) Don't use "list" as a name, because it's a (useful) built-in function. Use more expressive names: fn instead of b, fn_1 instead of a, fibnumbers instead of list, etc. > > def i_fib(n): > a = 0 > b = 1 > list = [] > counter = 0 > while counter < n: > a, b = b, a+b > counter += 1 > list = list + [b,] > return list > > def fib_range(start,end): > list = i_fib(12) > if start in list and end in list: > start = list.index(start) > end = list.index(end) > print list[start:end+1] > else: print 'not in list' From python at mrabarnett.plus.com Sun Aug 29 14:34:02 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Aug 2010 19:34:02 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> Message-ID: <4C7AA81A.10705@mrabarnett.plus.com> On 29/08/2010 06:13, ????? wrote: > On 28 ???, 23:12, MRAB wrote: >> On 28/08/2010 20:51, ????? wrote: >> >> >> >> >> >> >> >> >> >>> On 28 ???, 22:35, MRAB wrote: >> >>>> """When there's more than one value you provide a tuple. It's makes sense >>>> from the point of view of consistency that you also provide a tuple when >>>> there's only one value.""" >> >>> Can you write something that make use of more than one value? >> >>> Perhaps you mena somethign like? >> >>> cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date >>> = %s and host = %s''' , (page,) ) >> >>> Is this what you mean? >> >>> All those special format strign identifiers will grab their values out >>> of the tuple? >> >> Your example contains 3 placeholders, so it needs 3 values: >> >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s''', (page, date, host)) >> >> This will be safe. Any quoting that's needed will be done by .execute(). > > Will this also work without the parentheses? > Have you tried it? I did. It didn't like it! It likes the values to be in a tuple. If there's one value, that's a 1-tuple: (page, ). >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s''', page, date, host) > > or python will not allow it cause it might think there are 4 args > isntead of two? > Not Python (the language) as such, but the method. As I said, it expects the value(s) to be in a tuple. > >> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and >> date = '%s' and host = '%s' ''', (page, date, host)) > > Whats happens if i attempt to also quote by single or double quoting > the above although now i'm aware that .execute method does the quoting > for me? The method will put in any quoting that's needed. If you also put in quotes then that'll result in 2 sets of quoting, one inside the other (or something like that). Why make more work for yourself? Let the method do it for you, safely and correctly! From news1234 at free.fr Sun Aug 29 14:35:02 2010 From: news1234 at free.fr (News123) Date: Sun, 29 Aug 2010 20:35:02 +0200 Subject: Fibonacci: How to think recursively In-Reply-To: References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4c7aa857$0$703$426a74cc@news.free.fr> Hi Baba, > So here's my code. It does still cause me one headache. If i use > f(0)=0 > and f(1)=1 as base cases the result will be 144. I was expecting the > result to be the next value in the series (233)... > If i use f(1)=1 and f(2)=2 as base cases them i get my expected > result. I assume this has to do with our understanding/defining the > start of the Fibonacci series? > > > def r_fib(n): > if n == 1: return 1 > elif n == 2: return 2 > else: return r_fib(n-2) + r_fib(n-1) > > print r_fib(12) > Let's calculate the first 12 Fobonacci numbers first manually: 0: 0 # as of its definition 1: 1 @ as of its definition 2: 0 + 1 = 1 3: 1 + 1 = 2 4: 1 + 2 = 3 5: 2 + 3 = 5 6: 3 + 5 = 8 7: 5 + 8 = 13 8: 8 + 13 = 21 9: 13 + 21 = 34 10: 21 + 34 = 55 11: 34 + 55 = 89 12: 55 + 89 = 144 So if you use f(0) = 0 and f(1) = 1 you seem to get the coorec result, right? Now the question is why you get the wrong result with your code: def r_fib(n): if n == 1: return 1 elif n == 2: return 2 else: return r_fib(n-2) + r_fib(n-1) The answer is very simple your result n=2 is wrong. You wrote, that it is 2, but it should be 1 From python at mrabarnett.plus.com Sun Aug 29 14:44:12 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Aug 2010 19:44:12 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> Message-ID: <4C7AAA7C.8050900@mrabarnett.plus.com> On 29/08/2010 06:34, ????? wrote: > On 28 ???, 23:15, MRAB wrote: >> On 28/08/2010 20:37, ????? wrote: >> >> >> >> >> >> >> >> >> >>> On 22 ???, 10:27, ????? wrote: >>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >>>>> ????? wrote: >>>>>> # initializecookie >>>>>> cookie=Cookie.SimpleCookie() >>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>>>> mycookie =cookie.get('visitor') >> >>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>>>> yandex|13448|spider|crawl)', host ) is None: >>>>>> blabla... >>>>>> ======================== >> >>>>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>>>> within. >>>>>> So, i have to ask why the if fails? >> >>>>> Maybe it's because != != == >> >>>> Iwant ti if code block to be executed only if the browsercookienames >>>> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >>>> Is there somethign wrong with the way i wrote it? >> >>> Please do help me with this too becaus eif i dont solve this my >>> website keeps count my each visit like iam a guest visitor! >> >> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and >> repr(host). Then follow the code yourself to see whether the condition >> is True. > > print mycookie outputs 'None' > > Thts weird because i check with the browser and the cookie is there! > Just because you can see it doesn't mean your code can. > print repr(host) outputs '78-236-176.adsl.cyta.gr' > > repr(mycookie.value) (unless mycookie is None) > > and also > > print mycookie.value gives an error too. Maybe there is not a value > method? > If mycookie is None, then it's not surprising that doesn't have 'value'. In summary, mycookie is None, so: mycookie and mycookie.value != 'nikos' is false (actually None, which is treated as false). host == '78-236-176.adsl.cyta.gr', so: re.search(r'(cyta|yandex|13448|spider|crawl)', host) finds 'cyta' and the search returns a match. false or false == false blabla... isn't executed. From news1234 at free.fr Sun Aug 29 14:47:57 2010 From: news1234 at free.fr (News123) Date: Sun, 29 Aug 2010 20:47:57 +0200 Subject: Fibonacci: returning a selection of the series In-Reply-To: References: Message-ID: <4c7aab61$0$18873$426a74cc@news.free.fr> On 08/29/2010 07:36 PM, Baba wrote: > level: beginner > > i would like to return a selection of the Fibonacci series. > example: > start = 5 ; end = 55 > the function should then return [5, 8, 13, 21, 34, 55] > > it seems that this is best resolved using an iterative approach to > generate the series. In another post (http://groups.google.ie/group/ > comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ > d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach > which seems best to compute the nth number but it seems to me that the > recursive code is not suited for generating the actual list. > > my questios: > - would you agree that recursive is not ideal for generating a list? Of course, This is probably the whole point of this exercise. Just because something can be defined recursively doesn't mean, that it should be calculated recursively > - can my code below be optimised? > - how to deal with 'start' and 'end' values that are not in the list > e.g. 4,76 ? > > def i_fib(n): > a = 0 > b = 1 > list = [] > counter = 0 > while counter < n: > a, b = b, a+b > counter += 1 > list = list + [b,] > return list lateron you should probably use a generator function for i_fib(n) Then you will only calculate what is needed. minor suggestion for above code. Instead of: list = list + [b,] it is common practice to write list.append(b) > > def fib_range(start,end): > list = i_fib(12) > if start in list and end in list: > start = list.index(start) > end = list.index(end) > print list[start:end+1] > else: print 'not in list' > > fib_range(5,55) you know, that the list returned by i_fib() is sorted. Knowing this you can look at the python module bisect. It allows you to identify the index of the closest entry in a list. Just read it up in the net: http://docs.python.org/library/bisect.html You could do this of course also do manually (perhaps better for learning python than just using exsitng funtions) Search for the first Fibonacci number which is bigger than your start number Then search for the first Fibonacci number, which is bigger than your end number Display all numbers between these two indices From debatem1 at gmail.com Sun Aug 29 14:55:17 2010 From: debatem1 at gmail.com (geremy condra) Date: Sun, 29 Aug 2010 11:55:17 -0700 Subject: Fibonacci: returning a selection of the series In-Reply-To: References: Message-ID: On Sun, Aug 29, 2010 at 10:36 AM, Baba wrote: > level: beginner > > i would like to return a selection of the Fibonacci series. > example: > start = 5 ; end ?= 55 > the function should then return [5, 8, 13, 21, 34, 55] > > it seems that this is best resolved using an iterative approach to > generate the series. In another post (http://groups.google.ie/group/ > comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ > d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach > which seems best to compute the nth number but it seems to me that the > recursive code is not suited for generating the actual list. > > my questios: > - would you agree that recursive is not ideal for generating a list? > (in this particular case and in general) > - can my code below be optimised? > - how to deal with 'start' and 'end' values that are not in the list > e.g. 4,76 ? > > def i_fib(n): > ? ?a = 0 > ? ?b = 1 > ? ?list = [] > ? ?counter = 0 > ? ?while counter < n: > ? ? ? ?a, b = b, a+b > ? ? ? ?counter += 1 > ? ? ? ?list = list + [b,] > ? ?return list > > def fib_range(start,end): > ? ?list = i_fib(12) > ? ?if start in list and end in list: > ? ? ? ?start = list.index(start) > ? ? ? ?end = list.index(end) > ? ? ? ?print list[start:end+1] > ? ?else: print 'not in list' > > fib_range(5,55) > > thanks > Baba Get the index of the start, use that to generate the second, and iterate until you hit the end. from math import sqrt, log, floor phi = (1 + sqrt(5))/2 def fibonacci_index(n): return floor(log(n * sqrt(5))/log(phi) + .5) def ith_fibonacci(i): return floor(phi**i/sqrt(5) + .5) def next_fibonacci(a, b): return a + b def fibonacci_between(start, stop): # find the index of the first i = fibonacci_index(start) # find the second value given the first second_fib = ith_fibonacci(i+1) # build the list from there fibs = [start, second_fib] while fibs[-1] != stop: fibs.append(next_fibonacci(fibs[-1], fibs[-2])) # and we're done return fibs Now try to understand *why* the above works, rather than just copy-pasting it. Geremy Condra From thomas at jollybox.de Sun Aug 29 15:00:56 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Sun, 29 Aug 2010 21:00:56 +0200 Subject: PyGeo In-Reply-To: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> Message-ID: <201008292100.57165.thomas@jollybox.de> On Sunday 29 August 2010, it occurred to L to exclaim: > has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu > 10.04) , > the site says > > http://www.wspiegel.de/pymaxima/index_en.html > > "Note: The installation of PyGeo work's only under Python 2.4 (The > further development of pygeo seems to be stopped)" > > is this to do with re-org of site-packages, dist_packages etc. > > any help most appreciated. I don't know. I haven't tried. Maybe somebody else here has, but don't count on it. Have you tried it? If not, then why not? Try it. Maybe it just works. As far as I know, distutils haven't changed much, carefully avoiding any changes that could break packages. I think it's entirely possible that the web page author claiming "the installation" doesn't work was referring only to the Windows installer. Have fun, Thomas From bruno.desthuilliers at gmail.com Sun Aug 29 15:01:39 2010 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 29 Aug 2010 12:01:39 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> Message-ID: <39148700-25c5-4534-8723-1c09d38bf2bb@q22g2000yqm.googlegroups.com> On 27 ao?t, 20:05, Jussi Piitulainen > def palindromep(s): > ? ? return ( s == "" or > ? ? ? ? ? ? ?( s[0] == s[-1] and > ? ? ? ? ? ? ? ?palindromep(s[1:-1]) ) ) > I-can-write-lisp-in-any-language-p !-) From bruno.desthuilliers at gmail.com Sun Aug 29 15:09:26 2010 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 29 Aug 2010 12:09:26 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> <8dunm7Fv5nU1@mid.individual.net> Message-ID: <944676c3-3f62-45c2-8259-2429bee5e7f6@n3g2000yqb.googlegroups.com> On 29 ao?t, 06:39, Gregory Ewing wrote: > Steven D'Aprano wrote: > > ?I'm not entirely sure what the use-case for swapcase is. > > Obviously it's for correcting things that were typed > in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) > +1 QOTW !-) From nagle at animats.com Sun Aug 29 15:12:52 2010 From: nagle at animats.com (John Nagle) Date: Sun, 29 Aug 2010 12:12:52 -0700 Subject: Performance: sets vs dicts. Message-ID: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Is the "in" test faster for a dict or a set? Is "frozenset" faster than "set"? Use case is for things like applying "in" on a list of 500 or so words while checking a large body of text. John Nagle From arnodel at googlemail.com Sun Aug 29 15:13:29 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 20:13:29 +0100 Subject: Fibonacci: returning a selection of the series References: Message-ID: Baba writes: > my questios: > - would you agree that recursive is not ideal for generating a list? > (in this particular case and in general) In Python that is probably correct in the vast majority of cases for two reasons: * lists in Python are implemented as arrays; * there is no tail call optimisation in Python. But not necessarily in other languages. In Lisp for example, recursion is *the* natural way of generating lists. -- Arnaud From arnodel at googlemail.com Sun Aug 29 15:24:04 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 29 Aug 2010 20:24:04 +0100 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: John Nagle writes: > Is the "in" test faster for a dict or a set? > Is "frozenset" faster than "set"? Use case is > for things like applying "in" on a list of 500 or so words > while checking a large body of text. > > John Nagle IIRC Frozensets are implemented more or less as sets with a hash function and immutability so I would expect "in" to perform exactly the same as for sets. For dicts, I would think that the set implementation is very close to the dict one. So I wouldn't expect any significant difference between any of them. -- Arnaud From __peter__ at web.de Sun Aug 29 15:43:02 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Aug 2010 21:43:02 +0200 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > Is the "in" test faster for a dict or a set? > Is "frozenset" faster than "set"? Use case is > for things like applying "in" on a list of 500 or so words > while checking a large body of text. As Arnaud suspects: no significant difference: $ python dictperf.py dict --> 0.210289001465 set --> 0.202902793884 frozenset --> 0.198950052261 $ cat dictperf.py import random import timeit with open("/usr/share/dict/words") as instream: words = [line.strip() for line in instream] #random.seed(42) sample = random.sample(words, 501) n = sample.pop() y = random.choice(sample) d = dict.fromkeys(sample) s = set(sample) f = frozenset(sample) for lookup in d, s, f: print type(lookup).__name__, "-->", timeit.timeit( "n in lookup; y in lookup", "from __main__ import lookup, n, y") Peter From roy at panix.com Sun Aug 29 16:34:16 2010 From: roy at panix.com (Roy Smith) Date: Sun, 29 Aug 2010 16:34:16 -0400 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> <8dunm7Fv5nU1@mid.individual.net> Message-ID: In article <8dunm7Fv5nU1 at mid.individual.net>, Gregory Ewing wrote: > Steven D'Aprano wrote: > > I'm not entirely sure what the use-case for swapcase is. > > Obviously it's for correcting things that were typed > in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) So it would seem (http://bugs.python.org/msg94026). It's also useful for when you're looking for a crypto algorithm and rot13 is too strong. It also provides a handy way to write is_alpha()... def is_alpha(c): return abs(ord(c) - ord(c.swapcase())) == 32 print is_alpha('a') print is_alpha('A') print is_alpha('1') print is_alpha('>') From joshua.r.english at gmail.com Sun Aug 29 16:38:22 2010 From: joshua.r.english at gmail.com (Josh English) Date: Sun, 29 Aug 2010 13:38:22 -0700 (PDT) Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> Message-ID: I have no idea. That's a lower level of programming than I'm used to dealing with. Josh (I also only tried the one value. Had I tried with other strings that would fail the test, some functions may have performed better.) On Aug 29, 2:19?am, Matteo Landi wrote: > Well, I tried the also the solution posted above (recursive w/o > slicing and iterative), and I discovered they were the slowest.. > > is_palindrome_recursive 2.68151649808 > is_palindrome_slice 0.44510699381 > is_palindrome_list 1.93861944217 > is_palindrome_reversed 3.28969831976 > is_palindrome_recursive_no_slicing 6.78929775328 > is_palindrome_iterative 4.88826141315 > > Nothing to say about the iterative function, but the benchmark of the > recursive was unexpected, at least for my point of view: do you think > it is due to the try/except overhead? > From python at mrabarnett.plus.com Sun Aug 29 16:47:41 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Aug 2010 21:47:41 +0100 Subject: palindrome iteration In-Reply-To: References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> <8dunm7Fv5nU1@mid.individual.net> Message-ID: <4C7AC76D.5060402@mrabarnett.plus.com> On 29/08/2010 21:34, Roy Smith wrote: > In article<8dunm7Fv5nU1 at mid.individual.net>, > Gregory Ewing wrote: > >> Steven D'Aprano wrote: >>> I'm not entirely sure what the use-case for swapcase is. >> >> Obviously it's for correcting things that were typed >> in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) > > So it would seem (http://bugs.python.org/msg94026). > > It's also useful for when you're looking for a crypto algorithm and > rot13 is too strong. > > It also provides a handy way to write is_alpha()... > > def is_alpha(c): > return abs(ord(c) - ord(c.swapcase())) == 32 > > print is_alpha('a') > print is_alpha('A') > print is_alpha('1') > print is_alpha('>') How is that better than: print 'a'.isalpha() print 'A'.isalpha() print '1'.isalpha() print '>'.isalpha() From roy at panix.com Sun Aug 29 17:01:29 2010 From: roy at panix.com (Roy Smith) Date: Sun, 29 Aug 2010 17:01:29 -0400 Subject: palindrome iteration References: <49c856c4-e6f4-4e4e-b1b4-694a50e56080@f6g2000yqa.googlegroups.com> <4c78eb21$0$28655$c3e8da3@news.astraweb.com> <4c79b11a$0$28655$c3e8da3@news.astraweb.com> <8dunm7Fv5nU1@mid.individual.net> Message-ID: In article , MRAB wrote: > On 29/08/2010 21:34, Roy Smith wrote: > > In article<8dunm7Fv5nU1 at mid.individual.net>, > > Gregory Ewing wrote: > > > >> Steven D'Aprano wrote: > >>> I'm not entirely sure what the use-case for swapcase is. > >> > >> Obviously it's for correcting things that were typed > >> in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) > > > > So it would seem (http://bugs.python.org/msg94026). > > > > It's also useful for when you're looking for a crypto algorithm and > > rot13 is too strong. > > > > It also provides a handy way to write is_alpha()... > > > > def is_alpha(c): > > return abs(ord(c) - ord(c.swapcase())) == 32 > > > > print is_alpha('a') > > print is_alpha('A') > > print is_alpha('1') > > print is_alpha('>') > > How is that better than: > > print 'a'.isalpha() > print 'A'.isalpha() > print '1'.isalpha() > print '>'.isalpha() Think of my post as an implemention of is_reader_humour_impaired(). From storm at chemicalstorm.org Sun Aug 29 17:57:18 2010 From: storm at chemicalstorm.org (Audric Schiltknecht) Date: Sun, 29 Aug 2010 23:57:18 +0200 Subject: Functional composition in python In-Reply-To: <6bedbd75-2fc7-43d6-a3ba-e76e4b447db6@l20g2000yqe.googlegroups.com> References: <4c79b48f$0$28655$c3e8da3@news.astraweb.com> <6bedbd75-2fc7-43d6-a3ba-e76e4b447db6@l20g2000yqe.googlegroups.com> Message-ID: <4c7ad78b$0$31660$426a34cc@news.free.fr> Le 29/08/2010 04:54, Dmitry Groshev a ?crit : > On Aug 29, 5:14 am, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 28 Aug 2010 21:30:39 +0400, Dmitry Groshev wrote: >>> Hello all. Some time ago I wrote a little library: >>> http://github.com/si14/python-functional-composition/, inspired by >>> modern functional languages like F#. In my opinion it is quite useful >>> now, but I would like to discuss it. >>> An example of usage: [snip] > > Generally, f1>> f2 means "lambda x: f2(f1(x))" or "pass the result of > f1 to f2". But in python function can return only one value, so a > composable function should be a function of one argument. You can use a tuple to return more than just one value: def f(a,b): return (a,b) >>> f(1,2) (1,2) Ok, technically, it is ONE value, but since you can access any member of this tuple :) From raoulbia at gmail.com Sun Aug 29 18:18:41 2010 From: raoulbia at gmail.com (Baba) Date: Sun, 29 Aug 2010 15:18:41 -0700 (PDT) Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> <4c7aa857$0$703$426a74cc@news.free.fr> Message-ID: <03ee4309-2aaf-49cc-bea0-9d22444582fe@g17g2000yqe.googlegroups.com> Thanks to All for your kind help! Baba From diazona at ellipsix.net Sun Aug 29 18:30:41 2010 From: diazona at ellipsix.net (David Zaslavsky) Date: Sun, 29 Aug 2010 18:30:41 -0400 Subject: Change case of package name on PyPI Message-ID: <201008291830.41656.diazona@ellipsix.net> Hi everyone, I recently uploaded a package to PyPI under a name with mixed-case letters, but in retrospect I think it'd be better to have the package name be all lowercase. Is there a way I can change it? Thanks, :) David From ben+python at benfinney.id.au Sun Aug 29 19:09:37 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 30 Aug 2010 09:09:37 +1000 Subject: Change case of package name on PyPI References: Message-ID: <87d3t1ggni.fsf@benfinney.id.au> David Zaslavsky writes: > I recently uploaded a package to PyPI under a name with mixed-case > letters, but in retrospect I think it'd be better to have the package > name be all lowercase. Is there a way I can change it? Your question is on-topic here. However, you might get a more focussed discussion at the forum specific for discussing PyPI, the catalog SIG . Try starting the same discussion there. -- \ ?[Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself.? ?_Hocus Pocus_, Kurt | _o__) Vonnegut | Ben Finney From seth at sthrs.me Sun Aug 29 19:13:01 2010 From: seth at sthrs.me (Seth Rees) Date: Sun, 29 Aug 2010 18:13:01 -0500 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: On 08/29/10 14:43, Peter Otten wrote: > John Nagle wrote: > >> Is the "in" test faster for a dict or a set? >> Is "frozenset" faster than "set"? Use case is >> for things like applying "in" on a list of 500 or so words >> while checking a large body of text. > > As Arnaud suspects: no significant difference: > > $ python dictperf.py > dict --> 0.210289001465 > set --> 0.202902793884 > frozenset --> 0.198950052261 > > $ cat dictperf.py > import random > import timeit > > with open("/usr/share/dict/words") as instream: > words = [line.strip() for line in instream] > > #random.seed(42) > sample = random.sample(words, 501) > > n = sample.pop() > y = random.choice(sample) > > d = dict.fromkeys(sample) > s = set(sample) > f = frozenset(sample) > > > for lookup in d, s, f: > print type(lookup).__name__, "-->", timeit.timeit( > "n in lookup; y in lookup", > "from __main__ import lookup, n, y") > > Peter What about lists versus tuples? From news1234 at free.fr Sun Aug 29 19:46:16 2010 From: news1234 at free.fr (News123) Date: Mon, 30 Aug 2010 01:46:16 +0200 Subject: how to find out, whether a path is socket or device Message-ID: <4c7af148$0$28551$426a74cc@news.free.fr> Hi, Under Linux I'd like to find out, whether I got a file, a character device or a socket as a parameter. What is the right way to do this How can I found out, whether a path name is: - a file ( os.isfile() ) - a character device - a socket - a named pipe thanks a lot for pointers From steve at REMOVE-THIS-cybersource.com.au Sun Aug 29 20:09:27 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 00:09:27 GMT Subject: how to find out, whether a path is socket or device References: <4c7af148$0$28551$426a74cc@news.free.fr> Message-ID: <4c7af6b7$0$11118$c3e8da3@news.astraweb.com> On Mon, 30 Aug 2010 01:46:16 +0200, News123 wrote: > Hi, > > Under Linux I'd like to find out, whether I got a file, a character > device or a socket as a parameter. See the stat module. -- Steven From diazona at ellipsix.net Sun Aug 29 20:10:20 2010 From: diazona at ellipsix.net (David Zaslavsky) Date: Sun, 29 Aug 2010 20:10:20 -0400 Subject: Change case of package name on PyPI In-Reply-To: <87d3t1ggni.fsf@benfinney.id.au> References: <87d3t1ggni.fsf@benfinney.id.au> Message-ID: <201008292010.20717.diazona@ellipsix.net> On Sunday 29 August 2010 7:09:37 pm Ben Finney wrote: > David Zaslavsky writes: > > I recently uploaded a package to PyPI under a name with mixed-case > > letters, but in retrospect I think it'd be better to have the package > > name be all lowercase. Is there a way I can change it? > > Your question is on-topic here. However, you might get a more focussed > discussion at the forum specific for discussing PyPI, the catalog SIG > . Try > starting the same discussion there. Thanks, I'll do that. :) David From steve at REMOVE-THIS-cybersource.com.au Sun Aug 29 20:12:30 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 00:12:30 GMT Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: <4c7af76e$0$28653$c3e8da3@news.astraweb.com> On Sun, 29 Aug 2010 07:44:47 -0700, ernest wrote: > Hi, > > The operator module provides separate functions for "in place" > operations, such as iadd(), isub(), etc. However, it appears that these > functions don't really do the operation in place: > > In [34]: a = 4 > > In [35]: operator.iadd(a, 3) > Out[35]: 7 > > In [36]: a > Out[36]: 4 > > So, what's the point? If you have to make the assignment yourself... I > don't understand. The point is that if you could modify the int 4 to become 7, you would then see horrible things like this: >>> a = 4 >>> operator.iadd(a, 3) >>> 4 + 1 # the int "4" has been changed to have the value 7 8 Nobody wants that. Some very early versions of Fortran allowed that sort of thing, apparently by accident. I've been told you can get it to work with Lisp too, and Python with ctypes. You don't want to go there. That is why ints are immutable in Python, and so "in-place" operations aren't really in-place for them. Remember that 4 is an actual *object*, and so the iadd function can only see the object, not the name it is bound to. It sees 4 as the first argument, not the memory location of "a". There's no way for it to know which name you are trying to modify, or even if the object 4 is bound to any name. -- Steven From aahz at pythoncraft.com Sun Aug 29 20:15:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2010 17:15:44 -0700 Subject: problem in using linalg solver in numpy References: <242fd242-5f29-4358-8c12-f5763b7be137@g21g2000prn.googlegroups.com> Message-ID: In article <242fd242-5f29-4358-8c12-f5763b7be137 at g21g2000prn.googlegroups.com>, Pramod wrote: > >When run the below program in python i got error like this , You may want to consider asking future questions on the NumPy list: http://projects.scipy.org/mailman/listinfo/numpy-discussion -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From steve at REMOVE-THIS-cybersource.com.au Sun Aug 29 20:16:55 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 00:16:55 GMT Subject: Fibonacci: How to think recursively References: <890665ce-4df5-4a6d-b18b-9170d743bd55@a36g2000yqc.googlegroups.com> <4c79c510$0$28655$c3e8da3@news.astraweb.com> Message-ID: <4c7af877$0$28653$c3e8da3@news.astraweb.com> On Sun, 29 Aug 2010 06:43:40 -0700, Baba wrote: > So here's my code. It does still cause me one headache. If i use f(0)=0 > and f(1)=1 as base cases the result will be 144. I was expecting the > result to be the next value in the series (233)... That's because you're not generating the Fibonacci series, but a similar unnamed(?) series with the same recurrence but different starting conditions. The Fibinacci series starts with f(0)=1, f(1)=1. > If i use f(1)=1 and > f(2)=2 as base cases them i get my expected result. Which implies that f(0) must be 1, not 0. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 29 20:25:29 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 00:25:29 GMT Subject: Fibonacci: returning a selection of the series References: Message-ID: <4c7afa79$0$28653$c3e8da3@news.astraweb.com> On Sun, 29 Aug 2010 10:36:45 -0700, Baba wrote: > level: beginner > > i would like to return a selection of the Fibonacci series. example: > start = 5 ; end = 55 > the function should then return [5, 8, 13, 21, 34, 55] Start with something to lazily generate Fibonacci numbers. It doesn't matter whether this is iterative or recursive, but it must be *lazy* -- only generating each number when you ask for the next one. Generators are ideal for this: # Untested. def fib(): """Generate the Fibonacci numbers.""" a, b = 1, 1 yield a while 1: yield b a, b = b, a+b Then pass it into a filter than skips numbers less than start, accumulates numbers until you exceed end, and stop. Then return the numbers that you collected. > it seems that this is best resolved using an iterative approach to > generate the series. In another post (http://groups.google.ie/group/ > comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ > d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach > which seems best to compute the nth number but it seems to me that the > recursive code is not suited for generating the actual list. In this specific case, you can get recursion to be much, much more efficient than the naive f(n) = f(n-1) + f(n-2) case, but iteration in Python is often more efficient. > my questios: > - would you agree that recursive is not ideal for generating a list? (in > this particular case and in general) In this particular case, an iterative approach to Fibonacci will probably be more effective. In general, no, recursion is fine for generating lists. -- Steven From no.email at nospam.invalid Sun Aug 29 20:39:21 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 17:39:21 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> Message-ID: <7xhbidndc6.fsf@ruckus.brouhaha.com> Hans Mulder writes: > Parallelizable garbage collectors have performance issues, but they're > not the same issues as mark&sweep collectors have. Parallelizable GCs > break up their work in a zillion little pieces and allow the VM to do > some real work after each piece. They won't free your twenty thousand > components all in one go and you won't have that embarrassing pause. Quibble: parallel GC just means any GC that runs in multiple threads simultaneously. A GC that guarantees no pauses (more technically, specifies a constant such that any GC pause is guaranteed to be shorter than the constant) is called a "real time" GC, and real-time GC's are usually single threaded. Parallel real-time GC's were once sort of a holy grail, though workable ones have been implemented. GHC for example currently uses a GC that is parallel (runs on multiple cores for speed) but is not real-time (there can be a pause), and I think the Sun JVM is the same way. These days I think the GC pause issue is overrated except for real-time control applications. GC's no longer frequently make the program freeze up for seconds at a time or anything like that. It was worse in the old days when CPU's were slower and memory was scarcer. Serious GC's are usually generational, with "minor" GC's taking microseconds and less frequent "major" GC's taking fractions of a second. So in an interactive program or animation on your desktop you might notice a little hiccup once in a while. For something like a web server an occasional slight variation in response time could easily be random network delays and so forth. From no.email at nospam.invalid Sun Aug 29 20:52:38 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 17:52:38 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> Message-ID: <7xd3t0orah.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > You can add cycle detection to a reference count gc, at the cost of more > complexity. But then it's not purely a refcount gc. ;) > If you read the Wikipedia article I linked to, tracing algorithms can > also be unsound: [describes "conservative" gc] Yeah, whether that counts as a real GC is subjective too. >> and 2) it requires constant attention from the mutator to incr and >> decr the reference counts. > Yes. And? I thought I made it clear, the purpose of gc is to improve programmer productivity and program reliability by relieving the programmer from the burden of memory allocation bookkeeping. If the programmer has to painstakingly manage refcounts by hand and the resulting programs are still prone to refcount bugs (both of which are the case with CPython), it's not really gc in a way that lives up to the name. > That's a problem with the CPython API, not reference counting. The > problem is that the CPython API is written at too low a level, beneath > that at which the garbage collector exists, so naturally you have to > manually manage memory. Care to give an example of a reference counted system that's written any other way? > On the other hand, tracing gcs have their own set of problems too, mostly > due to the use of finalizers and attempts to make garbage collection run > more predictably. See here: I think it's fairly common wisdom that finalizers and gc don't interact very well. Finalizers in general aren't in the gc spirit, which says the system should give the illusion that every object stays around forever. As for stuff like hash tables, a usual way to help out the gc is by populating the hash table with weak references, rather than by clearing it out manually when you're done with it. It's also possible for fancy compilers to use a mixture of gc and stack- or region-based allocation. > Tracing garbage collectors aren't a panacea. They're software themselves, > and complex software, which means they're subject to bugs like the one ... You could say the same thing about compilers instead of gc's. The idea in both cases is yes, they're complex, but they put the complexity in one place, so that the application program can rely on the complicated gc or compiler features while itself staying simple. From no.email at nospam.invalid Sun Aug 29 20:56:03 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 17:56:03 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> Message-ID: <7x8w3oor4s.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I could be wrong, but how can they not be subject to the same performance > issue? If you have twenty thousand components that all have to be freed, > they all have to be freed whether you do it when the last reference is > cleared, or six seconds later when the gc does a sweep. GC's on large machines these days do not sweep at all. They copy the live data to a new heap, then release the old heap. Because there is usually more garbage than live data, copying GC's that never touch the garbage are usually faster than any scheme involving freeing unused objects one by one. From nikos.the.gr33k at gmail.com Sun Aug 29 21:14:55 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 29 Aug 2010 18:14:55 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> Message-ID: <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> On 29 ???, 21:44, MRAB wrote: > On 29/08/2010 06:34, ????? wrote: > > > > > > > > > On 28 ???, 23:15, MRAB ?wrote: > >> On 28/08/2010 20:37, ????? wrote: > > >>> On 22 ???, 10:27, ????? ? ?wrote: > >>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ?wrote: > > >>>>> ????? wrote: > >>>>>> # initializecookie > >>>>>> cookie=Cookie.SimpleCookie() > >>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>>>> mycookie =cookie.get('visitor') > > >>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>>>> yandex|13448|spider|crawl)', host ) is None: > >>>>>> ? ? ? blabla... > >>>>>> ======================== > > >>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>>>> within. > >>>>>> So, i have to ask why the if fails? > > >>>>> Maybe it's because != != == > > >>>> Iwant ti if code block to be executed only if the browsercookienames > >>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >>>> Is there somethign wrong with the way i wrote it? > > >>> Please do help me with this too becaus eif i dont solve this my > >>> website keeps count my each visit like iam a guest visitor! > > >> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > >> repr(host). Then follow the code yourself to see whether the condition > >> is True. > > > print mycookie outputs 'None' > > > Thts weird because i check with the browser and the cookie is there! > > Just because you can see it doesn't mean your code can. > > > print repr(host) outputs '78-236-176.adsl.cyta.gr' > > > repr(mycookie.value) (unless mycookie is None) > > > and also > > > print mycookie.value gives an error too. Maybe there is not a value > > method? > > If mycookie is None, then it's not surprising that doesn't have 'value'. > > In summary, mycookie is None, so: > > ? ? ?mycookie and mycookie.value != 'nikos' > > is false (actually None, which is treated as false). > > host == '78-236-176.adsl.cyta.gr', so: > > ? ? ?re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > finds 'cyta' and the search returns a match. > > false or false == false > > blabla... isn't executed. Lets forget the 2nd or argument, ill put it off so we have this now if ( mycookie and mycookie.value != 'nikos' ): #do stuff as long as there ins't a cookie names visitor with a value of nikos in the broswer What does it mean practically that the mycookie equals to None? That mycookie doesnt exist? How should i write this if block to mkake sure it checks whether or not the cookie exists? From nikos.the.gr33k at gmail.com Sun Aug 29 21:38:42 2010 From: nikos.the.gr33k at gmail.com (=?UTF-8?B?zp3Or866zr/Pgg==?=) Date: Sun, 29 Aug 2010 18:38:42 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> Message-ID: <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> On 29 ???, 21:34, MRAB wrote: > It likes the values to be in a tuple. If there's one value, that's a > 1-tuple: (page, ). I noticed that if we are dealing with just a single value 'page' will do, no need to tuple for 1-value. it handles fine as a string. > >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and > >> date = %s and host = %s''', page, date, host) > > > or python will not allow it cause it might think there are 4 args > > isntead of two? > > Not Python (the language) as such, but the method. As I said, it > expects the value(s) to be in a tuple. If i dont parenthesize the execute method instead of getting 2 args(sql_query and tuple value) as it expects by deficition, it gets 4 args instead and thats why it fails? I need to know why ti fails. Is that it? Also in here, page, date, host is 3 separate variable values here while (page, date, host) is 3 separate variables values also but withing a tuple. Is this correct? > >> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > >> date = '%s' and host = '%s' ''', (page, date, host)) > > > Whats happens if i attempt to also quote by single or double quoting > > the above although now i'm aware that .execute method does the quoting > > for me? > > The method will put in any quoting that's needed. If you also put in > quotes then that'll result in 2 sets of quoting, one inside the other > (or something like that). > > Why make more work for yourself? Let the method do it for you, safely > and correctly! I'am askign this because i'm tryong to see why On 29 ???, 21:34, MRAB wrote: > It likes the values to be in a tuple. If there's one value, that's a > 1-tuple: (page, ). I noticed that if we are dealing with just a single value 'page' will do, no need to tuple for 1-value. it handles fine as a string. > >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and > >> date = %s and host = %s''', page, date, host) > > > or python will not allow it cause it might think there are 4 args > > isntead of two? > > Not Python (the language) as such, but the method. As I said, it > expects the value(s) to be in a tuple. If i dont parenthesize the execute method instead of getting 2 args(sql_query and tuple value) as it expects by deficition, it gets 4 args instead and thats why it fails? I need to know why ti fails. Is that it? ======================== Also in here, page, date, host is 3 separate variable values here while (page, date, host) is 3 separate variables values also but withing a tuple. Is this correct? ========================= I'm asking this to see why cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and date = '%s' and host = '%s' ''' % (page, date, host) ) does work, while same thign qithout the quotes cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' % (page, date, host) ) doesn't. Dont know why but quotes somehopw confuse me both in strings and sql_queries as well when it comes to substitutions. From python at mrabarnett.plus.com Sun Aug 29 21:51:08 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 02:51:08 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> Message-ID: <4C7B0E8C.1040707@mrabarnett.plus.com> On 30/08/2010 02:14, ????? wrote: > On 29 ???, 21:44, MRAB wrote: >> On 29/08/2010 06:34, ????? wrote: >> >> >> >> >> >> >> >>> On 28 ???, 23:15, MRAB wrote: >>>> On 28/08/2010 20:37, ????? wrote: >> >>>>> On 22 ???, 10:27, ????? wrote: >>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >>>>>>> ????? wrote: >>>>>>>> # initializecookie >>>>>>>> cookie=Cookie.SimpleCookie() >>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>>>>>> mycookie =cookie.get('visitor') >> >>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>>>>>> yandex|13448|spider|crawl)', host ) is None: >>>>>>>> blabla... >>>>>>>> ======================== >> >>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>>>>>> within. >>>>>>>> So, i have to ask why the if fails? >> >>>>>>> Maybe it's because != != == >> >>>>>> Iwant ti if code block to be executed only if the browsercookienames >>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >>>>>> Is there somethign wrong with the way i wrote it? >> >>>>> Please do help me with this too becaus eif i dont solve this my >>>>> website keeps count my each visit like iam a guest visitor! >> >>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and >>>> repr(host). Then follow the code yourself to see whether the condition >>>> is True. >> >>> print mycookie outputs 'None' >> >>> Thts weird because i check with the browser and the cookie is there! >> >> Just because you can see it doesn't mean your code can. >> >>> print repr(host) outputs '78-236-176.adsl.cyta.gr' >> >>> repr(mycookie.value) (unless mycookie is None) >> >>> and also >> >>> print mycookie.value gives an error too. Maybe there is not a value >>> method? >> >> If mycookie is None, then it's not surprising that doesn't have 'value'. >> >> In summary, mycookie is None, so: >> >> mycookie and mycookie.value != 'nikos' >> >> is false (actually None, which is treated as false). >> >> host == '78-236-176.adsl.cyta.gr', so: >> >> re.search(r'(cyta|yandex|13448|spider|crawl)', host) >> >> finds 'cyta' and the search returns a match. >> >> false or false == false >> >> blabla... isn't executed. > > Lets forget the 2nd or argument, ill put it off > > so we have this now > > if ( mycookie and mycookie.value != 'nikos' ): > #do stuff as long as there ins't a cookie names visitor with a > value of nikos in the broswer > > What does it mean practically that the mycookie equals to None? > That mycookie doesnt exist? > > How should i write this if block to mkake sure it checks whether or > not the cookie exists? Under what conditions do you want to execute the block? This: mycookie and mycookie.value != 'nikos' will be true if: there _is_ a cookie, but its value isn't 'nikos' I think that you want is to execute the block if someone else is visiting. Correct? How do you know when it _is_ you? There'll be a cookie which says it's you? If so, then you want to execute the block if there isn't any cookie, or if there's a cookie but it doesn't say it's you: not mycookie or mycookie.value != 'nikos' From python at mrabarnett.plus.com Sun Aug 29 22:04:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 03:04:32 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> Message-ID: <4C7B11B0.704@mrabarnett.plus.com> On 30/08/2010 02:38, ????? wrote: > On 29 ???, 21:34, MRAB wrote: > >> It likes the values to be in a tuple. If there's one value, that's a >> 1-tuple: (page, ). > > I noticed that if we are dealing with just a single value 'page' will > do, no need to tuple for 1-value. > it handles fine as a string. > I tried it with sqlite3, which it didn't like it. For consistency, and compatibility with other SQL engines, I recommend that you always provide a tuple. >>>> cursor.execute('''SELECT hits FROM counters WHERE page = %s and >>>> date = %s and host = %s''', page, date, host) >> >>> or python will not allow it cause it might think there are 4 args >>> isntead of two? >> >> Not Python (the language) as such, but the method. As I said, it >> expects the value(s) to be in a tuple. > > If i dont parenthesize the execute method instead of getting 2 > args(sql_query and tuple value) as it expects by deficition, it gets 4 > args instead and thats why it fails? I need to know why ti fails. Is > that it? > If the SQL query contains placeholder(s), the .execute method expects the value(s) to be provided in a tuple. It's as simple as that. > Also in here, > > page, date, host is 3 separate variable values here > > while > > (page, date, host) is 3 separate variables values also but withing a > tuple. Is this correct? > It doesn't care about the variables as such, only their values. You're putting the values into a tuple and then passing that tuple because that's what the method wants. > >>>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and >>>> date = '%s' and host = '%s' ''', (page, date, host)) >> >>> Whats happens if i attempt to also quote by single or double quoting >>> the above although now i'm aware that .execute method does the quoting >>> for me? >> >> The method will put in any quoting that's needed. If you also put in >> quotes then that'll result in 2 sets of quoting, one inside the other >> (or something like that). >> >> Why make more work for yourself? Let the method do it for you, safely >> and correctly! > > I'am askign this because i'm tryong to see why > > On 29 ???, 21:34, MRAB wrote: > >> It likes the values to be in a tuple. If there's one value, that's a >> 1-tuple: (page, ). > > I noticed that if we are dealing with just a single value 'page' will > do, no need to tuple for 1-value. > it handles fine as a string. > As I've said, for consistency I recommend that you always provide a tuple because some SQL engines require it, and if you need to provide multiple values then you'll need to anyway. >>>> cursor.execute('''SELECT hits FROM counters WHERE page = %s and >>>> date = %s and host = %s''', page, date, host) >> >>> or python will not allow it cause it might think there are 4 args >>> isntead of two? >> >> Not Python (the language) as such, but the method. As I said, it >> expects the value(s) to be in a tuple. > > If i dont parenthesize the execute method instead of getting 2 > args(sql_query and tuple value) as it expects by deficition, it gets 4 > args instead and thats why it fails? I need to know why ti fails. Is > that it? > > ======================== > Also in here, > > page, date, host is 3 separate variable values here > > while > > (page, date, host) is 3 separate variables values also but withing a > tuple. Is this correct? > > > ========================= > I'm asking this to see why > > cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > date = '%s' and host = '%s' ''' % (page, date, host) ) > > does work, while same thign qithout the quotes > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date > = %s and host = %s ''' % (page, date, host) ) > > doesn't. Dont know why but quotes somehopw confuse me both in strings > and sql_queries as well when it comes to substitutions. Don't quote the placeholders yourself. Let the method do it. From nikos.the.gr33k at gmail.com Sun Aug 29 22:07:16 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 19:07:16 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> Message-ID: On 30 ???, 04:51, MRAB wrote: > On 30/08/2010 02:14, ????? wrote: > > > > > > > > > > > On 29 ???, 21:44, MRAB ?wrote: > >> On 29/08/2010 06:34, ????? wrote: > > >>> On 28 ???, 23:15, MRAB ? ?wrote: > >>>> On 28/08/2010 20:37, ????? wrote: > > >>>>> On 22 ???, 10:27, ????? ? ? ?wrote: > >>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ? ?wrote: > > >>>>>>> ????? wrote: > >>>>>>>> # initializecookie > >>>>>>>> cookie=Cookie.SimpleCookie() > >>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>>>>>> mycookie =cookie.get('visitor') > > >>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>>>>>> yandex|13448|spider|crawl)', host ) is None: > >>>>>>>> ? ? ? ?blabla... > >>>>>>>> ======================== > > >>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>>>>>> within. > >>>>>>>> So, i have to ask why the if fails? > > >>>>>>> Maybe it's because != != == > > >>>>>> Iwant ti if code block to be executed only if the browsercookienames > >>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >>>>>> Is there somethign wrong with the way i wrote it? > > >>>>> Please do help me with this too becaus eif i dont solve this my > >>>>> website keeps count my each visit like iam a guest visitor! > > >>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > >>>> repr(host). Then follow the code yourself to see whether the condition > >>>> is True. > > >>> print mycookie outputs 'None' > > >>> Thts weird because i check with the browser and the cookie is there! > > >> Just because you can see it doesn't mean your code can. > > >>> print repr(host) outputs '78-236-176.adsl.cyta.gr' > > >>> repr(mycookie.value) (unless mycookie is None) > > >>> and also > > >>> print mycookie.value gives an error too. Maybe there is not a value > >>> method? > > >> If mycookie is None, then it's not surprising that doesn't have 'value'. > > >> In summary, mycookie is None, so: > > >> ? ? ? mycookie and mycookie.value != 'nikos' > > >> is false (actually None, which is treated as false). > > >> host == '78-236-176.adsl.cyta.gr', so: > > >> ? ? ? re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > >> finds 'cyta' and the search returns a match. > > >> false or false == false > > >> blabla... isn't executed. > > > Lets forget the 2nd or argument, ill put it off > > > so we have this now > > > if ( mycookie and mycookie.value != 'nikos' ): > > ? ? ?#do stuff as long as there ins't a cookie names visitor with a > > value of nikos in the broswer > > > What does it mean practically that the mycookie equals to None? > > That mycookie doesnt exist? > > > How should i write this if block to mkake sure it checks whether or > > not the cookie exists? > > Under what conditions do you want to execute the block? > > This: > > ? ? ?mycookie and mycookie.value != 'nikos' > > will be true if: > > ? ? ?there _is_ a cookie, but its value isn't 'nikos' > > I think that you want is to execute the block if someone else is > visiting. Correct? Yes that exactyl right! To make sure a cookie is set i have a script names koukos.py containing this: ============================== #!/usr/bin/python # -*- coding: utf-8 -*- import cgitb; cgitb.enable() import cgi, os, Cookie # initialize cookie cookie = Cookie.SimpleCookie() cookie.load( os.environ.get('HTTP_COOKIE', '') ) mycookie = cookie.get('visitor') htmlBody = [] # if visitor cookie does exist if ( mycookie and mycookie.value == 'nikos' ): htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? ????????? ?????????? ??? ???????!') cookie['visitor'] = 'nikos' cookie['visitor']['expires'] = -1 #this cookie will expire now else: htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? ?? ??????! ?? ????? ????? ? ??????? ??????????!!') cookie['visitor'] = 'nikos' cookie['visitor']['expires'] = 60*60*24*30*12 htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') print(cookie) print('\n'.join(htmlBody)) ============================= Which i seicth on and off according to my desire if i want to be counted or not! > How do you know when it _is_ you? There'll be a cookie which says it's > you? > > If so, then you want to execute the block if there isn't any cookie, or > if there's a cookie but it doesn't say it's you: > > ? ? ?not mycookie or mycookie.value != 'nikos' i tried this as you suggested: if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| yandex|13448|spider|crawl)', host ) is None: but the counter keeps increasing although the cookie named visitor on my browser exist and also has the valuie of 'nikos'. Why it keeps increasing? Doesn't the if code "sees" that the cookie with a value of "nikos" is present!?!! From wuwei23 at gmail.com Sun Aug 29 22:21:57 2010 From: wuwei23 at gmail.com (alex23) Date: Sun, 29 Aug 2010 19:21:57 -0700 (PDT) Subject: How to convert (unicode) text to image? References: Message-ID: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> kj wrote: > Example: I went to the docs page for ImageDraw. ?There I find that > the constructor for an ImageDraw.Draw object takes an argument, > but *what* this argument should be (integer? object? string?) is > left entirely undefined. ?From the examples given I *guessed* that > it was an object of class Image[...] The docs say: Draw(image) => Draw instance Creates an object that can be used to draw in the given image. It seems pretty obvious that the first argument is an 'image' to me, and when the lib itself defines an Image class... You "guessed" this was the case from this prominent example at the top of the page? import Image, ImageDraw im = Image.open("lena.pgm") draw = ImageDraw.Draw(im) How much more clear can this be made? > Sorry for the outburst, but unfortunately, PIL is not alone in > this. ?Python is awash in poor documentation. [...] > I have to conclude that the problem with Python docs > is somehow "systemic"... Yes, if everyone else disagrees with you, the problem is obviously "systemic". What helps are concrete suggestions to the package maintainers about how these improvements could be made, rather than huge sprawling attacks on the state of Python documentation (and trying to tie it into the state of Python itself) as a whole. Instead, what we get are huge pointless rants like yours whenever someone finds that something isn't spelled out for them in exactly the way that they want. These people are _volunteering_ their effort and their code, all you're providing is an over-excess of hyperbole and punctuation. What is frustrating to me is seeing people like yourself spend far more time slamming these projects than actually contributing useful changes back. From nikos.the.gr33k at gmail.com Sun Aug 29 22:33:56 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 19:33:56 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> Message-ID: On 30 ???, 05:04, MRAB wrote: when iam trying to pass a tuple to the execute methos should i pass it like this? cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' % (page, date, host) ) or like tuple = (page, host, date) cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' % (tuple) ) Or is it the same thing? > > ========================= > > I'm asking this to see why > > > cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > > date = '%s' and host = '%s' ''' % (page, date, host) ) > > > does work, while same thign qithout the quotes > > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date > > = %s and host = %s ''' % (page, date, host) ) > > > doesn't. Dont know why but quotes somehopw confuse me both in strings > > and sql_queries as well when it comes to substitutions. > > Don't quote the placeholders yourself. Let the method do it. No, iam taking substitution here not mysql escaping. Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and date = '%s' and host = '%s' ''' % (page, date, host) ) As it is above it works , with double quotes still works but if i leave it unquoted it doesn't. This is because without sigle or double quotes the the method doesn't know where a value begins and here it ends? That why it needs quoting? From niklasro at gmail.com Sun Aug 29 22:40:09 2010 From: niklasro at gmail.com (Niklasro(.appspot)) Date: Sun, 29 Aug 2010 19:40:09 -0700 (PDT) Subject: Combining 2 regexes to 1 Message-ID: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> Hello, Suspecting it's completely doable combining these 2 regexes to just 1 expression I'm looking for the working syntax. If you know then kindly inform. Thanks in advance ('/a/([^/]*)',List), #list ('/a([^/]*)',List), #list Niklas Rosencrantz From python at mrabarnett.plus.com Sun Aug 29 22:43:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 03:43:07 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> Message-ID: <4C7B1ABB.8080308@mrabarnett.plus.com> On 30/08/2010 03:07, Nik the Greek wrote: > On 30 ???, 04:51, MRAB wrote: >> On 30/08/2010 02:14, ????? wrote: >> >>> On 29 ???, 21:44, MRAB wrote: >>>> On 29/08/2010 06:34, ????? wrote: >> >>>>> On 28 ???, 23:15, MRAB wrote: >>>>>> On 28/08/2010 20:37, ????? wrote: >> >>>>>>> On 22 ???, 10:27, ????? wrote: >>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >>>>>>>>> ????? wrote: >>>>>>>>>> # initializecookie >>>>>>>>>> cookie=Cookie.SimpleCookie() >>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>>>>>>>> mycookie =cookie.get('visitor') >> >>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: >>>>>>>>>> blabla... >>>>>>>>>> ======================== >> >>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>>>>>>>> within. >>>>>>>>>> So, i have to ask why the if fails? >> >>>>>>>>> Maybe it's because != != == >> >>>>>>>> Iwant ti if code block to be executed only if the browsercookienames >>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >>>>>>>> Is there somethign wrong with the way i wrote it? >> >>>>>>> Please do help me with this too becaus eif i dont solve this my >>>>>>> website keeps count my each visit like iam a guest visitor! >> >>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and >>>>>> repr(host). Then follow the code yourself to see whether the condition >>>>>> is True. >> >>>>> print mycookie outputs 'None' >> >>>>> Thts weird because i check with the browser and the cookie is there! >> >>>> Just because you can see it doesn't mean your code can. >> >>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' >> >>>>> repr(mycookie.value) (unless mycookie is None) >> >>>>> and also >> >>>>> print mycookie.value gives an error too. Maybe there is not a value >>>>> method? >> >>>> If mycookie is None, then it's not surprising that doesn't have 'value'. >> >>>> In summary, mycookie is None, so: >> >>>> mycookie and mycookie.value != 'nikos' >> >>>> is false (actually None, which is treated as false). >> >>>> host == '78-236-176.adsl.cyta.gr', so: >> >>>> re.search(r'(cyta|yandex|13448|spider|crawl)', host) >> >>>> finds 'cyta' and the search returns a match. >> >>>> false or false == false >> >>>> blabla... isn't executed. >> >>> Lets forget the 2nd or argument, ill put it off >> >>> so we have this now >> >>> if ( mycookie and mycookie.value != 'nikos' ): >>> #do stuff as long as there ins't a cookie names visitor with a >>> value of nikos in the broswer >> >>> What does it mean practically that the mycookie equals to None? >>> That mycookie doesnt exist? >> >>> How should i write this if block to mkake sure it checks whether or >>> not the cookie exists? >> >> Under what conditions do you want to execute the block? >> >> This: >> >> mycookie and mycookie.value != 'nikos' >> >> will be true if: >> >> there _is_ a cookie, but its value isn't 'nikos' >> >> I think that you want is to execute the block if someone else is >> visiting. Correct? > > Yes that exactyl right! > > To make sure a cookie is set i have a script names koukos.py > containing this: > > ============================== > #!/usr/bin/python > # -*- coding: utf-8 -*- > > import cgitb; cgitb.enable() > import cgi, os, Cookie > > > # initialize cookie > cookie = Cookie.SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > mycookie = cookie.get('visitor') > > htmlBody = [] > > # if visitor cookie does exist > if ( mycookie and mycookie.value == 'nikos' ): > htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? > ????????? ?????????? ??? ???????!') > cookie['visitor'] = 'nikos' > cookie['visitor']['expires'] = -1 #this cookie will expire > now > else: > htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? > ?? ??????! ?? ????? ????? ? ??????? ??????????!!') > cookie['visitor'] = 'nikos' > cookie['visitor']['expires'] = 60*60*24*30*12 > > htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') > > print(cookie) > print('\n'.join(htmlBody)) > ============================= > > Which i seicth on and off according to my desire if i want to be > counted or not! > >> How do you know when it _is_ you? There'll be a cookie which says it's >> you? >> >> If so, then you want to execute the block if there isn't any cookie, or >> if there's a cookie but it doesn't say it's you: >> >> not mycookie or mycookie.value != 'nikos' > > i tried this as you suggested: > > if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| > yandex|13448|spider|crawl)', host ) is None: > > but the counter keeps increasing although the cookie named visitor on > my browser exist and also has the valuie of 'nikos'. > > Why it keeps increasing? Doesn't the if code "sees" that the cookie > with a value of "nikos" is present!?!! Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you said that host was '78-236-176.adsl.cyta.gr', so it matched. Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the condition is true. From python at mrabarnett.plus.com Sun Aug 29 22:48:34 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 03:48:34 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> Message-ID: <4C7B1C02.8070506@mrabarnett.plus.com> On 30/08/2010 03:33, Nik the Greek wrote: > On 30 ???, 05:04, MRAB wrote: > > when iam trying to pass a tuple to the execute methos should i pass it > like this? > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' % (page, date, host) ) > > > or like > > tuple = (page, host, date) > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' % (tuple) ) > > > Or is it the same thing? > 'tuple' is the name of a built-in. Don't use it. The first example is clearer. >>> ========================= >>> I'm asking this to see why >> >>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and >>> date = '%s' and host = '%s' ''' % (page, date, host) ) >> >>> does work, while same thign qithout the quotes >> >>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date >>> = %s and host = %s ''' % (page, date, host) ) >> >>> doesn't. Dont know why but quotes somehopw confuse me both in strings >>> and sql_queries as well when it comes to substitutions. >> >> Don't quote the placeholders yourself. Let the method do it. > > No, iam taking substitution here not mysql escaping. > > Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > date = '%s' and host = '%s' ''' % (page, date, host) ) > > As it is above it works , with double quotes still works but if i > leave it unquoted it doesn't. > > This is because without sigle or double quotes the the method doesn't > know where a value begins and here it ends? That why it needs quoting? Let the method do the substitution: cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''', (page, date, host) ) This is the best way. From clp2 at rebertia.com Sun Aug 29 22:51:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 29 Aug 2010 19:51:59 -0700 Subject: Combining 2 regexes to 1 In-Reply-To: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> References: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> Message-ID: On Sun, Aug 29, 2010 at 7:40 PM, Niklasro(.appspot) wrote: > Hello, Suspecting it's completely doable combining these 2 regexes to > just 1 expression I'm looking for the working syntax. If you know then > kindly inform. Thanks in advance > ('/a/([^/]*)',List), #list > ('/a([^/]*)',List), #list Er, /a(/?)([^/]*) ? Cheers, Chris -- Parentheses probably extraneous. From nikos.the.gr33k at gmail.com Sun Aug 29 22:55:56 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 19:55:56 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> Message-ID: <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> On 30 ???, 05:43, MRAB wrote: > On 30/08/2010 03:07, Nik the Greek wrote: > > > > > > > > > > > On 30 ???, 04:51, MRAB ?wrote: > >> On 30/08/2010 02:14, ????? wrote: > > >>> On 29 ???, 21:44, MRAB ? ?wrote: > >>>> On 29/08/2010 06:34, ????? wrote: > > >>>>> On 28 ???, 23:15, MRAB ? ? ?wrote: > >>>>>> On 28/08/2010 20:37, ????? wrote: > > >>>>>>> On 22 ???, 10:27, ????? ? ? ? ?wrote: > >>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ? ? ?wrote: > > >>>>>>>>> ????? wrote: > >>>>>>>>>> # initializecookie > >>>>>>>>>> cookie=Cookie.SimpleCookie() > >>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>>>>>>>> mycookie =cookie.get('visitor') > > >>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: > >>>>>>>>>> ? ? ? ? blabla... > >>>>>>>>>> ======================== > > >>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>>>>>>>> within. > >>>>>>>>>> So, i have to ask why the if fails? > > >>>>>>>>> Maybe it's because != != == > > >>>>>>>> Iwant ti if code block to be executed only if the browsercookienames > >>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >>>>>>>> Is there somethign wrong with the way i wrote it? > > >>>>>>> Please do help me with this too becaus eif i dont solve this my > >>>>>>> website keeps count my each visit like iam a guest visitor! > > >>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > >>>>>> repr(host). Then follow the code yourself to see whether the condition > >>>>>> is True. > > >>>>> print mycookie outputs 'None' > > >>>>> Thts weird because i check with the browser and the cookie is there! > > >>>> Just because you can see it doesn't mean your code can. > > >>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' > > >>>>> repr(mycookie.value) (unless mycookie is None) > > >>>>> and also > > >>>>> print mycookie.value gives an error too. Maybe there is not a value > >>>>> method? > > >>>> If mycookie is None, then it's not surprising that doesn't have 'value'. > > >>>> In summary, mycookie is None, so: > > >>>> ? ? ? ?mycookie and mycookie.value != 'nikos' > > >>>> is false (actually None, which is treated as false). > > >>>> host == '78-236-176.adsl.cyta.gr', so: > > >>>> ? ? ? ?re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > >>>> finds 'cyta' and the search returns a match. > > >>>> false or false == false > > >>>> blabla... isn't executed. > > >>> Lets forget the 2nd or argument, ill put it off > > >>> so we have this now > > >>> if ( mycookie and mycookie.value != 'nikos' ): > >>> ? ? ? #do stuff as long as there ins't a cookie names visitor with a > >>> value of nikos in the broswer > > >>> What does it mean practically that the mycookie equals to None? > >>> That mycookie doesnt exist? > > >>> How should i write this if block to mkake sure it checks whether or > >>> not the cookie exists? > > >> Under what conditions do you want to execute the block? > > >> This: > > >> ? ? ? mycookie and mycookie.value != 'nikos' > > >> will be true if: > > >> ? ? ? there _is_ a cookie, but its value isn't 'nikos' > > >> I think that you want is to execute the block if someone else is > >> visiting. Correct? > > > Yes that exactyl right! > > > To make sure a cookie is set i have a script names koukos.py > > containing this: > > > ============================== > > #!/usr/bin/python > > # -*- coding: utf-8 -*- > > > import cgitb; cgitb.enable() > > import cgi, os, Cookie > > > # initialize cookie > > cookie = Cookie.SimpleCookie() > > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > mycookie = cookie.get('visitor') > > > htmlBody = [] > > > # if visitor cookie does exist > > if ( mycookie and mycookie.value == 'nikos' ): > > ? ? ?htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? > > ????????? ?????????? ??? ???????!') > > ? ? ?cookie['visitor'] = 'nikos' > > ? ? ?cookie['visitor']['expires'] = -1 ? ? ?#this cookie will expire > > now > > else: > > ? ? ?htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? > > ?? ??????! ?? ????? ????? ? ??????? ??????????!!') > > ? ? ?cookie['visitor'] = 'nikos' > > ? ? ?cookie['visitor']['expires'] = 60*60*24*30*12 > > > htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') > > > print(cookie) > > print('\n'.join(htmlBody)) > > ============================= > > > Which i seicth on and off according to my desire if i want to be > > counted or not! > > >> How do you know when it _is_ you? There'll be a cookie which says it's > >> you? > > >> If so, then you want to execute the block if there isn't any cookie, or > >> if there's a cookie but it doesn't say it's you: > > >> ? ? ? not mycookie or mycookie.value != 'nikos' > > > i tried this as you suggested: > > > if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| > > yandex|13448|spider|crawl)', host ) is None: > > > but the counter keeps increasing although the cookie named visitor on > > my browser exist and also has the valuie of 'nikos'. > > > Why it keeps increasing? Doesn't the if code "sees" that the cookie > > with a value of "nikos" is present!?!! > > Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you > said that host was '78-236-176.adsl.cyta.gr', so it matched. > > Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still > '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the > condition is true. Thats what i want. If host doesnt contain substringsa of the regex to execute if block. if it does match i dont want then if block to execute, hence the counter too. The reason i had 'cyta' before is because not mycookie or mycookie.value != 'nikos' doesn't filter me out. The problem is what happens with the not mycookie or mycookie.value != 'nikos' Since cookie 'visitor' does contain the 'nikos' value why the if code blck gets executed? From nikos.the.gr33k at gmail.com Sun Aug 29 23:01:26 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 20:01:26 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> Message-ID: <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> On 30 ???, 05:48, MRAB wrote: > On 30/08/2010 03:33, Nik the Greek wrote: > > > > > > > > > On 30 ???, 05:04, MRAB ?wrote: > > > when iam trying to pass a tuple to the execute methos should i pass it > > like this? > > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > > date = %s and host = %s ''' % (page, date, host) ) > > > or like > > > tuple = (page, host, date) > > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > > date = %s and host = %s ''' % (tuple) ) > > > Or is it the same thing? > > 'tuple' is the name of a built-in. Don't use it. > > The first example is clearer. ok a_tuple = (page, hist, host) cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' , a_tuple ) would that syntax be correct? No need to enclose the tuple name inside parenthesis here right? > >>> ========================= > >>> I'm asking this to see why > > >>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > >>> date = '%s' and host = '%s' ''' % (page, date, host) ) > > >>> does work, while same thign qithout the quotes > > >>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date > >>> = %s and host = %s ''' % (page, date, host) ) > > >>> doesn't. Dont know why but quotes somehopw confuse me both in strings > >>> and sql_queries as well when it comes to substitutions. > > >> Don't quote the placeholders yourself. Let the method do it. > > > No, iam taking substitution here not mysql escaping. > > > Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and > > date = '%s' and host = '%s' ''' % (page, date, host) ) > > > As it is above it works , with double quotes still works but if i > > leave it unquoted it doesn't. > > > This is because without sigle or double quotes the the method doesn't > > know where a value begins and here it ends? That why it needs quoting? > > Let the method do the substitution: > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = > %s and host = %s ''', (page, date, host) ) > > This is the best way. Yes i will i just asked to know if i were to substitute what might be the problem so to understand why i need the quoting. why not like that? > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = > %s and host = %s ''' % (page, date, host) ) From python at mrabarnett.plus.com Sun Aug 29 23:07:13 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 04:07:13 +0100 Subject: Combining 2 regexes to 1 In-Reply-To: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> References: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> Message-ID: <4C7B2061.4080301@mrabarnett.plus.com> On 30/08/2010 03:40, Niklasro(.appspot) wrote: > Hello, Suspecting it's completely doable combining these 2 regexes to > just 1 expression I'm looking for the working syntax. If you know then > kindly inform. Thanks in advance > ('/a/([^/]*)',List), #list > ('/a([^/]*)',List), #list ('/a/?([^/]*)', List), #list From python at mrabarnett.plus.com Sun Aug 29 23:12:03 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 04:12:03 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> Message-ID: <4C7B2183.7000302@mrabarnett.plus.com> On 30/08/2010 03:55, Nik the Greek wrote: > On 30 ???, 05:43, MRAB wrote: >> On 30/08/2010 03:07, Nik the Greek wrote: >> >> >> >> >> >> >> >> >> >>> On 30 ???, 04:51, MRAB wrote: >>>> On 30/08/2010 02:14, ????? wrote: >> >>>>> On 29 ???, 21:44, MRAB wrote: >>>>>> On 29/08/2010 06:34, ????? wrote: >> >>>>>>> On 28 ???, 23:15, MRAB wrote: >>>>>>>> On 28/08/2010 20:37, ????? wrote: >> >>>>>>>>> On 22 ???, 10:27, ????? wrote: >>>>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> wrote: >> >>>>>>>>>>> ????? wrote: >>>>>>>>>>>> # initializecookie >>>>>>>>>>>> cookie=Cookie.SimpleCookie() >>>>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>>>>>>>>>>> mycookie =cookie.get('visitor') >> >>>>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| >>>>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: >>>>>>>>>>>> blabla... >>>>>>>>>>>> ======================== >> >>>>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos >>>>>>>>>>>> within. >>>>>>>>>>>> So, i have to ask why the if fails? >> >>>>>>>>>>> Maybe it's because != != == >> >>>>>>>>>> Iwant ti if code block to be executed only if the browsercookienames >>>>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' >> >>>>>>>>>> Is there somethign wrong with the way i wrote it? >> >>>>>>>>> Please do help me with this too becaus eif i dont solve this my >>>>>>>>> website keeps count my each visit like iam a guest visitor! >> >>>>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and >>>>>>>> repr(host). Then follow the code yourself to see whether the condition >>>>>>>> is True. >> >>>>>>> print mycookie outputs 'None' >> >>>>>>> Thts weird because i check with the browser and the cookie is there! >> >>>>>> Just because you can see it doesn't mean your code can. >> >>>>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' >> >>>>>>> repr(mycookie.value) (unless mycookie is None) >> >>>>>>> and also >> >>>>>>> print mycookie.value gives an error too. Maybe there is not a value >>>>>>> method? >> >>>>>> If mycookie is None, then it's not surprising that doesn't have 'value'. >> >>>>>> In summary, mycookie is None, so: >> >>>>>> mycookie and mycookie.value != 'nikos' >> >>>>>> is false (actually None, which is treated as false). >> >>>>>> host == '78-236-176.adsl.cyta.gr', so: >> >>>>>> re.search(r'(cyta|yandex|13448|spider|crawl)', host) >> >>>>>> finds 'cyta' and the search returns a match. >> >>>>>> false or false == false >> >>>>>> blabla... isn't executed. >> >>>>> Lets forget the 2nd or argument, ill put it off >> >>>>> so we have this now >> >>>>> if ( mycookie and mycookie.value != 'nikos' ): >>>>> #do stuff as long as there ins't a cookie names visitor with a >>>>> value of nikos in the broswer >> >>>>> What does it mean practically that the mycookie equals to None? >>>>> That mycookie doesnt exist? >> >>>>> How should i write this if block to mkake sure it checks whether or >>>>> not the cookie exists? >> >>>> Under what conditions do you want to execute the block? >> >>>> This: >> >>>> mycookie and mycookie.value != 'nikos' >> >>>> will be true if: >> >>>> there _is_ a cookie, but its value isn't 'nikos' >> >>>> I think that you want is to execute the block if someone else is >>>> visiting. Correct? >> >>> Yes that exactyl right! >> >>> To make sure a cookie is set i have a script names koukos.py >>> containing this: >> >>> ============================== >>> #!/usr/bin/python >>> # -*- coding: utf-8 -*- >> >>> import cgitb; cgitb.enable() >>> import cgi, os, Cookie >> >>> # initialize cookie >>> cookie = Cookie.SimpleCookie() >>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >>> mycookie = cookie.get('visitor') >> >>> htmlBody = [] >> >>> # if visitor cookie does exist >>> if ( mycookie and mycookie.value == 'nikos' ): >>> htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? >>> ????????? ?????????? ??? ???????!') >>> cookie['visitor'] = 'nikos' >>> cookie['visitor']['expires'] = -1 #this cookie will expire >>> now >>> else: >>> htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? >>> ?? ??????! ?? ????? ????? ? ??????? ??????????!!') >>> cookie['visitor'] = 'nikos' >>> cookie['visitor']['expires'] = 60*60*24*30*12 >> >>> htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') >> >>> print(cookie) >>> print('\n'.join(htmlBody)) >>> ============================= >> >>> Which i seicth on and off according to my desire if i want to be >>> counted or not! >> >>>> How do you know when it _is_ you? There'll be a cookie which says it's >>>> you? >> >>>> If so, then you want to execute the block if there isn't any cookie, or >>>> if there's a cookie but it doesn't say it's you: >> >>>> not mycookie or mycookie.value != 'nikos' >> >>> i tried this as you suggested: >> >>> if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| >>> yandex|13448|spider|crawl)', host ) is None: >> >>> but the counter keeps increasing although the cookie named visitor on >>> my browser exist and also has the valuie of 'nikos'. >> >>> Why it keeps increasing? Doesn't the if code "sees" that the cookie >>> with a value of "nikos" is present!?!! >> >> Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you >> said that host was '78-236-176.adsl.cyta.gr', so it matched. >> >> Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still >> '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the >> condition is true. > > Thats what i want. > > If host doesnt contain substringsa of the regex to execute if block. > if it does match i dont want then if block to execute, hence the > counter too. > > The reason i had 'cyta' before is because not mycookie or > mycookie.value != 'nikos' doesn't filter me out. > > The problem is what happens with the > > not mycookie or mycookie.value != 'nikos' > > Since cookie 'visitor' does contain the 'nikos' value why the if code > blck gets executed? This part: ( not mycookie or mycookie.value != 'nikos' ) is false but this part: re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None is true because host doesn't contain any of those substrings. From aahz at pythoncraft.com Sun Aug 29 23:28:27 2010 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2010 20:28:27 -0700 Subject: Pop return from stack? References: <4f471ef9-02e7-4105-a96a-f8a5a7e2c6fd@f6g2000pro.googlegroups.com> <4c684566$0$1619$742ec2ed@news.sonic.net> <40a6bfac-3f4b-43f4-990b-224cb2b654d3@i19g2000pro.googlegroups.com> Message-ID: In article <40a6bfac-3f4b-43f4-990b-224cb2b654d3 at i19g2000pro.googlegroups.com>, Carl Banks wrote: > >FWIW, I think it perfectly reasonable to let an application print a >traceback on an error. I've gotten a few bug reports on a little tool >I maintain where the user copies the traceback to me, it it's helped >me diagnose their issues a lot. That only really works for non-GUI applications. For GUI apps, log files are the way to go. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From nikos.the.gr33k at gmail.com Sun Aug 29 23:33:20 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Sun, 29 Aug 2010 20:33:20 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> Message-ID: <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> On 30 ???, 06:12, MRAB wrote: > This part: > > ? ? ?( not mycookie or mycookie.value != 'nikos' ) > > is false but this part: > > ? ? ?re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > is true because host doesn't contain any of those substrings. So, the if code does executed because one of the condition is true? How should i write it? I cannot think clearly on this at all. I just wan to tell it to get executed ONLY IF the cookie values is not 'nikos' or ( don't knwo if i have to use and or 'or' here) host does not contain any of the substrings. What am i doign wrong?! From steve-REMOVE-THIS at cybersource.com.au Sun Aug 29 23:38:06 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 03:38:06 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> <7xd3t0orah.fsf@ruckus.brouhaha.com> Message-ID: <4c7b279d$0$28650$c3e8da3@news.astraweb.com> On Sun, 29 Aug 2010 17:52:38 -0700, Paul Rubin wrote: >> That's a problem with the CPython API, not reference counting. The >> problem is that the CPython API is written at too low a level, beneath >> that at which the garbage collector exists, so naturally you have to >> manually manage memory. > > Care to give an example of a reference counted system that's written any > other way? The complexity of the ref counter is invisible when writing pure Python code, and I believe it is also invisible when writing code in Cython. The difficulty of dealing with ref counts is abstracted away. The argument that "it will work if we always do this" means that it won't work is a nice quip, but it doesn't stand up. It's possible to defeat even Pascal compilers' type checking and do unsafe things by dropping down into assembly. So don't do it! It's not hard to not do something, although sometimes you might choose to do it anyway, because otherwise there is no way to get the code you need/want. But such code should be a rare exception. I'm not saying that ref counting systems can avoid incrementing and decrementing the ref counts. That would be silly. But I'm saying that it is an accident of implementation that writing C extensions requires you to manually manage the counts yourself. That's a side-effect of permitting coders to write C extensions in pure C, rather than in some intermediate language which handles the ref counts for you but otherwise compiles like C. If people cared enough, they could (probably) make the C compiler handle it for them, just as it currently handles incrementing and decrementing the return stack. There's nothing *fundamental* to the idea of ref counting that says that you must handle the counts manually -- it depends on how well insulated you are from the underlying machine. -- Steven From ldo at geek-central.gen.new_zealand Sun Aug 29 23:46:39 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 30 Aug 2010 15:46:39 +1200 Subject: Helper app for intranet site References: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> Message-ID: In message <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5 at n19g2000prf.googlegroups.com>, kevinlcarlson wrote: > I'm exploring the possibility of developing a helper app for an > existing internal company website. Basically, it would automatically > scan the current page contents, including prepopulated forms, and > provide context-related business rule comments to the user, via a stay- > on-top wxPython panel. Seems like a roundabout way of doing it. Can?t you integrate into the server code which is generating the page contents, instead of trying to reverse- engineer those contents? From ldo at geek-central.gen.new_zealand Sun Aug 29 23:57:58 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 30 Aug 2010 15:57:58 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> Message-ID: In message <7x4oeftuk4.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > I'd say [reference-counting is] not real gc because 1) it's unsound > (misses reference cycles), and 2) it requires constant attention from the > mutator to incr and decr the reference counts. So developing modules for > the CPython API means endlessly finding and fixing refcount bugs that lead > to either crashes/security failures, or memory leaks. I don?t see why that should be so. It seems a very simple discipline to follow: initialize, allocate, free. Here?s an example snippet from my DVD Menu Animator : static void GetBufferInfo ( PyObject * FromArray, unsigned long * addr, unsigned long * len ) /* returns the address and length of the data in a Python array object. */ { PyObject * TheBufferInfo = 0; PyObject * AddrObj = 0; PyObject * LenObj = 0; do /*once*/ { TheBufferInfo = PyObject_CallMethod(FromArray, "buffer_info", ""); if (TheBufferInfo == 0) break; AddrObj = PyTuple_GetItem(TheBufferInfo, 0); LenObj = PyTuple_GetItem(TheBufferInfo, 1); if (PyErr_Occurred()) break; Py_INCREF(AddrObj); Py_INCREF(LenObj); *addr = PyInt_AsUnsignedLongMask(AddrObj); *len = PyInt_AsUnsignedLongMask(LenObj); if (PyErr_Occurred()) break; } while (false); Py_XDECREF(AddrObj); Py_XDECREF(LenObj); Py_XDECREF(TheBufferInfo); } /*GetBufferInfo*/ It?s quite easy to assure yourself that this is never going to leak memory. More complicated examples can simply nest constructs like these one within the other to arbitrary depth, while still giving the same assurance at every level. In short, this technique scales well. > If you program the Java JNI or a typical Lisp FFI, you'll find that real > gc is a lot simpler to use since you avoid all the refcount maintenance > hassles. You allocate memory and shut your eyes, and the gc takes care of > freeing it when it figures out that you are done. And how do you run such an application? You have to limit it to a predetermined amount of memory to begin with, otherwise it would easily gobble up everything you have. In the old days of ?classic? MacOS, every application had to run in a fixed- size application heap. I have no wish to return to those days. From niklasro at gmail.com Mon Aug 30 00:03:07 2010 From: niklasro at gmail.com (Niklasro(.appspot)) Date: Sun, 29 Aug 2010 21:03:07 -0700 (PDT) Subject: Combining 2 regexes to 1 References: <71f42e6b-8d44-44eb-9b5d-ad939446ddd0@k10g2000yqa.googlegroups.com> Message-ID: <2379250d-9cc5-4f07-a08c-1967e600c2f2@l20g2000yqe.googlegroups.com> Many thanks. It works. You also helped me refactor these ('/([0-9]*)/?([^/]*)',AById),#id2a ('/([0-9]*)',AById) to just 1 ('/([0-9]*)/?([^/]*)',AById),#id2a It's from the appspot framework. Sincerely Niklas R From rurpy at yahoo.com Mon Aug 30 00:23:08 2010 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sun, 29 Aug 2010 21:23:08 -0700 (PDT) Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On 08/29/2010 08:21 PM, alex23 wrote: > kj wrote: snip >> Sorry for the outburst, but unfortunately, PIL is not alone in >> this. Python is awash in poor documentation. [...] >> I have to conclude that the problem with Python docs >> is somehow "systemic"... > > Yes, if everyone else disagrees with you, the problem is obviously > "systemic". No, not everyone disagrees with him. There are many people who absolutely agree with him. > What helps are concrete suggestions to the package maintainers about > how these improvements could be made, rather than huge sprawling > attacks on the state of Python documentation (and trying to tie it > into the state of Python itself) as a whole. ] Nothing you quoted of what he wrote attempted to "tie it into the state of Python itself" > Instead, what we get are > huge pointless rants like yours whenever someone finds that something > isn't spelled out for them in exactly the way that they want. He never complained about spelling choices. > These people are _volunteering_ their effort and their code, Yes, we all know that. > all > you're providing is an over-excess of hyperbole It is hardly convincing when one criticizes hyperbole with hyperbole. > and punctuation. What > is frustrating to me is seeing people like yourself spend far more > time slamming these projects than actually contributing useful changes > back. Face the facts dude. The Python docs have some major problems. They were pretty good when Python was a new, cool, project used by a handful of geeks. They are good relative to the "average" (whatever that is) open source project -- but that bar is so low as to be a string lying on the ground. Your overly defensive and oppressive response does not help. All it (combined with similar knee-jerk responses) does is act to suppress any criticism leaving the impression that the Python docs are really great, an assertion commonly made here and often left unchallenged. Responses like yours create a force that works to maintain the status quo. From no.email at nospam.invalid Mon Aug 30 00:48:41 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 21:48:41 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> Message-ID: <7x39twpuxi.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: >> the CPython API means endlessly finding and fixing refcount bugs that lead >> to either crashes/security failures, or memory leaks. > > I don?t see why that should be so. It seems a very simple discipline to > follow: initialize, allocate, free. Here?s an example snippet from my DVD > Menu Animator : In practice it has been a problem. If it hasn't happened to you yet, you're either burning a bunch of effort that programmers of more automatic systems can put to more productive uses, or else you just haven't written enough such code to have gotten bitten yet. >> You allocate memory and shut your eyes, and the gc takes care of >> freeing it when it figures out that you are done. > > And how do you run such an application? You have to limit it to a > predetermined amount of memory to begin with, otherwise it would easily > gobble up everything you have. No that's usually not a problem-- the runtime system (generational gc) can figure out enough from your allocation pattern to prevent the heap from getting overlarge. From brian.curtin at gmail.com Mon Aug 30 00:57:51 2010 From: brian.curtin at gmail.com (Brian Curtin) Date: Sun, 29 Aug 2010 23:57:51 -0500 Subject: looking for open source python project In-Reply-To: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> References: <0ba0d50e-83b3-403a-9522-046c5fac8286@z28g2000yqh.googlegroups.com> Message-ID: On Sat, Aug 28, 2010 at 19:50, mo reina wrote: > looking for a python project (preferably something a bit small) that > is looking for contributors. the small bit is because i've never > worked in a team before and haven't really read source code that's > 1000s of lines long, so i'm not too sure i can keep up. > > my python fu is decent (i think), i recently wrote a small archive/ > grimoire program (command line only) that can store multiline text > with title, tags, and basic search functionality (not using curses so > the entry, once entered, can't be modified), entries are stored in a > pickle file. > > anybody have any suggestions? i'm keen to work on something with > others, both for learning and i'd like to do something a bit > meaningful, plus i'm sure it's fun. Check out http://bugs.python.org along with the pages of the Python development area at http://www.python.org/dev/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Mon Aug 30 02:07:03 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Aug 2010 23:07:03 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> Message-ID: <7xr5hg3a7s.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > static void GetBufferInfo > ( ... > do /*once*/ > { > TheBufferInfo = PyObject_CallMethod(FromArray, "buffer_info", ""); > if (TheBufferInfo == 0) > break; > AddrObj = PyTuple_GetItem(TheBufferInfo, 0); > LenObj = PyTuple_GetItem(TheBufferInfo, 1); > if (PyErr_Occurred()) > break; > ... > Py_INCREF(AddrObj); > Py_INCREF(LenObj); > } > while (false); > Py_XDECREF(AddrObj); > Py_XDECREF(LenObj); > Py_XDECREF(TheBufferInfo); > } /*GetBufferInfo*/ > > It?s quite easy to assure yourself that this is never going to leak memory. Actually that code looks suspicious. Suppose in AddrObj = PyTuple_GetItem(TheBufferInfo, 0); LenObj = PyTuple_GetItem(TheBufferInfo, 1); the first PyTuple_GetItem succeeds and the second one fails. Then AddrObj is a borrowed reference to the first tuple element and LenObj is null, the error flag is set, so you break out of the do/while. You then decrement the refcount of AddrObj even though you didn't increment it. Maybe there's an explanation that makes it ok somehow, but it still looks messy. This is the kind of problem I'm referring to in general. From python at rcn.com Mon Aug 30 02:25:12 2010 From: python at rcn.com (Raymond Hettinger) Date: Sun, 29 Aug 2010 23:25:12 -0700 (PDT) Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: On Aug 29, 12:12?pm, John Nagle wrote: > ? ? Is the "in" test faster for a dict or a set? > Is "frozenset" faster than "set"? ?Use case is > for things like applying "in" on a list of 500 or so words > while checking a large body of text. There is no significant difference. All three are implemented using substantially the same code. Raymond From julia.jacobson at arcor.de Mon Aug 30 02:29:43 2010 From: julia.jacobson at arcor.de (Julia Jacobson) Date: Mon, 30 Aug 2010 08:29:43 +0200 Subject: Passing variable to SQL statement when using psycopg2 Message-ID: <4c7b4fd3$0$6887$9b4e6d93@newsspool2.arcor-online.net> Dear python users, For passing a variable to a SQL query for psycopg2, I use: >>> my_var = xyz >>> print cur.mogrify("SELECT my_values FROM my_table WHERE my_column = %s",(my_var,)) This returns: >>> SELECT my_values FROM my_table WHERE my_column = E'xyz' Where does the "E" in front of 'xyz' come from? It's probably the reason, why my query doesn't work. Thanks in advance, Julia From deepud at gmail.com Mon Aug 30 02:35:26 2010 From: deepud at gmail.com (agnibhu) Date: Sun, 29 Aug 2010 23:35:26 -0700 (PDT) Subject: Tag parsing in python References: <5b968b40-ca90-449d-9123-b0abb470d46e@h37g2000pro.googlegroups.com> Message-ID: <944bfce7-6e5c-4460-bc75-2d3e44c9e6b1@a4g2000prm.googlegroups.com> On Aug 29, 5:43?pm, Paul McGuire wrote: > On Aug 28, 11:23?pm, Paul McGuire wrote: > > > > > On Aug 28, 11:14?am, agnibhu wrote: > > > > Hi all, > > > > I'm a newbie in python. I'm trying to create a library for parsing > > > certain keywords. > > > For example say I've key words like abc: bcd: cde: like that... So the > > > user may use like > > > abc: How are you bcd: I'm fine cde: ok > > > > So I've to extract the "How are you" and "I'm fine" and "ok"..and > > > assign them to abc:, bcd: and cde: respectively.. There may be > > > combination of keyowords introduced in future. like abc: xy: How are > > > you > > > So new keywords qualifying the other keywords so on.. > > I got to thinking more about your keywords-qualifying-keywords > example, and I thought this would be a good way to support locale- > specific tags. ?I also thought how one might want to have tags within > tags, to be substituted later, requiring a "abc::" escaped form of > "abc:", so that the tag is substituted with the value of tag "abc:" as > a late binding. > > Wasn't too hard to modify what I posted yesterday, and now I rather > like it. > > -- Paul > > # tag_substitute.py > > from pyparsing import (Combine, Word, alphas, FollowedBy, Group, > OneOrMore, > ? ? empty, SkipTo, LineEnd, Optional, Forward, MatchFirst, Literal, > And, replaceWith) > > tag = Combine(Word(alphas) + ~FollowedBy("::") + ":") > tag_defn = Group(OneOrMore(tag))("tag") + empty + SkipTo(tag | > LineEnd())("body") + Optional(LineEnd().suppress()) > > # now combine macro detection with substitution > macros = {} > macro_substitution = Forward() > def make_macro_sub(tokens): > ? ? # unescape '::' and substitute any embedded tags > ? ? tag_value = > macro_substitution.transformString(tokens.body.replace("::",":")) > > ? ? # save this tag and value (or overwrite previous) > ? ? macros[tuple(tokens.tag)] = tag_value > > ? ? # define overall macro substitution expression > ? ? macro_substitution << MatchFirst( > ? ? ? ? ? ? [(Literal(k[0]) if len(k)==1 > ? ? ? ? ? ? ? ? else And([Literal(kk) for kk in > k])).setParseAction(replaceWith(v)) > ? ? ? ? ? ? ? ? ? ? for k,v in macros.items()] ) + ~FollowedBy(tag) > > ? ? # return empty string, so macro definitions don't show up in final > ? ? # expanded text > ? ? return "" > > tag_defn.setParseAction(make_macro_sub) > > # define pattern for macro scanning > scan_pattern = macro_substitution | tag_defn > > sorry = """\ > nm: Dave > sorry: en: I'm sorry, nm::, I'm afraid I can't do that. > sorry: es: Lo siento nm::, me temo que no puedo hacer eso. > Hal said, "sorry: en:" > Hal dijo, "sorry: es:" """ > print scan_pattern.transformString(sorry) > > Prints: > > Hal said, "I'm sorry, Dave, I'm afraid I can't do that." > Hal dijo, "Lo siento Dave, me temo que no puedo hacer eso." Thanks all for giving me great solutions. I'm happy to see the respones. Will try out these and post the reply soon. Thanks once again, Agnibhu.. From __peter__ at web.de Mon Aug 30 02:36:06 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Aug 2010 08:36:06 +0200 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: Seth Rees wrote: > On 08/29/10 14:43, Peter Otten wrote: >> John Nagle wrote: >> >>> Is the "in" test faster for a dict or a set? >>> Is "frozenset" faster than "set"? Use case is >>> for things like applying "in" on a list of 500 or so words >>> while checking a large body of text. >> >> As Arnaud suspects: no significant difference: >> >> $ python dictperf.py >> dict --> 0.210289001465 >> set --> 0.202902793884 >> frozenset --> 0.198950052261 >> >> $ cat dictperf.py >> import random >> import timeit >> >> with open("/usr/share/dict/words") as instream: >> words = [line.strip() for line in instream] >> >> #random.seed(42) >> sample = random.sample(words, 501) >> >> n = sample.pop() >> y = random.choice(sample) >> >> d = dict.fromkeys(sample) >> s = set(sample) >> f = frozenset(sample) >> >> >> for lookup in d, s, f: >> print type(lookup).__name__, "-->", timeit.timeit( >> "n in lookup; y in lookup", >> "from __main__ import lookup, n, y") >> >> Peter > What about lists versus tuples? You trade O(1) for O(N) with both, a bad idea for all but the smallest lists/tuples. $ python dictperf.py dict --> 0.221934080124 set --> 0.220952987671 frozenset --> 0.225043058395 list --> 21.5041530132 tuple --> 20.8655071259 By the way, the script will run on your computer, too ;) Peter From python at rcn.com Mon Aug 30 02:41:42 2010 From: python at rcn.com (Raymond Hettinger) Date: Sun, 29 Aug 2010 23:41:42 -0700 (PDT) Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: On Aug 29, 8:33?am, Arnaud Delobelle wrote: > ernest writes: > > Hi, > > > The operator module provides separate functions for > > "in place" operations, such as iadd(), isub(), etc. > > However, it appears that these functions don't really > > do the operation in place: > > > In [34]: a = 4 > > > In [35]: operator.iadd(a, 3) > > Out[35]: 7 > > > In [36]: a > > Out[36]: 4 > > > So, what's the point? If you have to make the > > assignment yourself... I don't understand. > > > Cheers, > > Ernest > > That's because > > ? ?a += b > > is executed as: > > ? ?a = a.__iadd__(b) > > For immutable objects, (such as integers), a.__iadd__(b) returns a + b > *and then* this value is assigned to a (or rather 'a' is bound to the > value). ?So for immutables objects, iadd(a, b) is the same as a + b > > For mutable objects (such as lists), a.__iadd__(b) mutates the object > *and then* returns self so that when the assignement is executed, 'a' > will still be bound the the same object. ?E.g. if a = [1, 2] then > > ? ? a += [3] > > will first append 3 to the list and then reassign the list to 'a' (it is > unnecessary in this case but if this step was omitted, the "in place" > operators wouldn't work on immutables types). This is an excellent explanation. Perhaps, you can submit a documentation patch for the operator module so this doesn't get lost. Raymond From lamlbiro at optusnet.com.au Mon Aug 30 02:42:39 2010 From: lamlbiro at optusnet.com.au (L) Date: Mon, 30 Aug 2010 16:42:39 +1000 Subject: PyGeo In-Reply-To: References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> Message-ID: <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> On 30/08/10 05:00, Thomas Jollans wrote: > On Sunday 29 August 2010, it occurred to L to exclaim: > >> has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu >> 10.04) , >> the site says >> >> http://www.wspiegel.de/pymaxima/index_en.html >> >> "Note: The installation of PyGeo work's only under Python 2.4 (The >> further development of pygeo seems to be stopped)" >> >> is this to do with re-org of site-packages, dist_packages etc. >> >> any help most appreciated. >> > I don't know. I haven't tried. Maybe somebody else here has, but don't count > on it. Have you tried it? If not, then why not? Try it. Maybe it just works. > As far as I know, distutils haven't changed much, carefully avoiding any > changes that could break packages. > > I think it's entirely possible that the web page author claiming "the > installation" doesn't work was referring only to the Windows installer. > > Have fun, > Thomas > -------------------------------- I have tried it and as soon as you try any of the examples in the examples dir it cannot find numpy etc.... I have manually move the pygeo dirs and contents to /usr/lib/python2.6/dis-packages, (this is the directory where numpy, numeric and scipy were installed when using synaptic ) made sure that read and write permissions set for ALL FILES and DIRECTORIES to RW using sudo chmod 777 any ideas. From clp2 at rebertia.com Mon Aug 30 03:08:58 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 30 Aug 2010 00:08:58 -0700 Subject: Passing variable to SQL statement when using psycopg2 In-Reply-To: <4c7b4fd3$0$6887$9b4e6d93@newsspool2.arcor-online.net> References: <4c7b4fd3$0$6887$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sun, Aug 29, 2010 at 11:29 PM, Julia Jacobson wrote: > Dear python users, > > For passing a variable to a SQL query for psycopg2, I use: > > ?>>> my_var = xyz > ?>>> print cur.mogrify("SELECT my_values FROM my_table WHERE my_column = > %s",(my_var,)) > > This returns: > > ?>>> SELECT my_values FROM my_table WHERE my_column = E'xyz' > > Where does the "E" in front of 'xyz' come from? > It's probably the reason, why my query doesn't work. Quite doubtful, considering the example in the psycopg2 docs also has the E: http://initd.org/psycopg/docs/cursor.html#cursor.mogrify Cheers, Chris -- http://blog.rebertia.com From no.email at nospam.invalid Mon Aug 30 03:22:17 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 00:22:17 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> <7xd3t0orah.fsf@ruckus.brouhaha.com> <4c7b279d$0$28650$c3e8da3@news.astraweb.com> Message-ID: <7xmxs436qe.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I'm not saying that ref counting systems can avoid incrementing and > decrementing the ref counts. That would be silly. But I'm saying that it > is an accident of implementation that writing C extensions requires you > to manually manage the counts yourself. That's a side-effect of > permitting coders to write C extensions in pure C, rather than in some > intermediate language which handles the ref counts for you but otherwise > compiles like C. If people cared enough, they could (probably) make the C > compiler handle it for them, just as it currently handles incrementing > and decrementing the return stack. I guess that is how the so-called smart pointers in the Boost C++ template library work. I haven't used them so I don't have personal experience with how convenient or reliable they are, or what kinds of constraints they imposed on programming style. I've always felt a bit suspicious of them though, and I seem to remember Alex Martelli (I hope he shows up here again someday) advising against using them. I don't think a C compiler could really manage automatic decrementing while still being C. Think especially of the common style of exception handling in C using longjmp. From steve-REMOVE-THIS at cybersource.com.au Mon Aug 30 03:39:01 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2010 07:39:01 GMT Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> <7xd3t0orah.fsf@ruckus.brouhaha.com> <4c7b279d$0$28650$c3e8da3@news.astraweb.com> <7xmxs436qe.fsf@ruckus.brouhaha.com> Message-ID: <4c7b6015$0$28660$c3e8da3@news.astraweb.com> On Mon, 30 Aug 2010 00:22:17 -0700, Paul Rubin wrote: > I don't think a C compiler could really manage automatic decrementing > while still being C. Think especially of the common style of exception > handling in C using longjmp. You might very well be right. But that's the problem with C -- it's too low a level language to expect the compiler to protect you much. Or at all. There will always be some use cases for managing memory yourself, or even managing the return stack (as you can do in Forth, for example), and so there will always need to be some sort of high-level assembler like C. But it astounds me that in 2010 people still routinely use C for normal, everyday application programming. -- Steven From greg.ewing at canterbury.ac.nz Mon Aug 30 03:43:41 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 30 Aug 2010 19:43:41 +1200 Subject: Queue cleanup In-Reply-To: <7xhbidndc6.fsf@ruckus.brouhaha.com> References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> <7xhbidndc6.fsf@ruckus.brouhaha.com> Message-ID: <8e15pqFn89U1@mid.individual.net> Paul Rubin wrote: > These days I think the GC pause issue is overrated except for real-time > control applications. Also for games, which are a fairly common application these days. Even a few milliseconds can be too long when you're trying to achieve smooth animation. I'd be disappointed if CPython ditched refcounting and then became unsuitable for real-time games as a result. -- Greg From nikos.the.gr33k at gmail.com Mon Aug 30 04:01:24 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 01:01:24 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> Message-ID: On 30 ???, 06:12, MRAB wrote: > On 30/08/2010 03:55, Nik the Greek wrote: > > > > > > > > > > > On 30 ???, 05:43, MRAB ?wrote: > >> On 30/08/2010 03:07, Nik the Greek wrote: > > >>> On 30 ???, 04:51, MRAB ? ?wrote: > >>>> On 30/08/2010 02:14, ????? wrote: > > >>>>> On 29 ???, 21:44, MRAB ? ? ?wrote: > >>>>>> On 29/08/2010 06:34, ????? wrote: > > >>>>>>> On 28 ???, 23:15, MRAB ? ? ? ?wrote: > >>>>>>>> On 28/08/2010 20:37, ????? wrote: > > >>>>>>>>> On 22 ???, 10:27, ????? ? ? ? ? ?wrote: > >>>>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ? ? ? ?wrote: > > >>>>>>>>>>> ????? wrote: > >>>>>>>>>>>> # initializecookie > >>>>>>>>>>>> cookie=Cookie.SimpleCookie() > >>>>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>>>>>>>>>>> mycookie =cookie.get('visitor') > > >>>>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > >>>>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: > >>>>>>>>>>>> ? ? ? ? ?blabla... > >>>>>>>>>>>> ======================== > > >>>>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > >>>>>>>>>>>> within. > >>>>>>>>>>>> So, i have to ask why the if fails? > > >>>>>>>>>>> Maybe it's because != != == > > >>>>>>>>>> Iwant ti if code block to be executed only if the browsercookienames > >>>>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > >>>>>>>>>> Is there somethign wrong with the way i wrote it? > > >>>>>>>>> Please do help me with this too becaus eif i dont solve this my > >>>>>>>>> website keeps count my each visit like iam a guest visitor! > > >>>>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > >>>>>>>> repr(host). Then follow the code yourself to see whether the condition > >>>>>>>> is True. > > >>>>>>> print mycookie outputs 'None' > > >>>>>>> Thts weird because i check with the browser and the cookie is there! > > >>>>>> Just because you can see it doesn't mean your code can. > > >>>>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' > > >>>>>>> repr(mycookie.value) (unless mycookie is None) > > >>>>>>> and also > > >>>>>>> print mycookie.value gives an error too. Maybe there is not a value > >>>>>>> method? > > >>>>>> If mycookie is None, then it's not surprising that doesn't have 'value'. > > >>>>>> In summary, mycookie is None, so: > > >>>>>> ? ? ? ? mycookie and mycookie.value != 'nikos' > > >>>>>> is false (actually None, which is treated as false). > > >>>>>> host == '78-236-176.adsl.cyta.gr', so: > > >>>>>> ? ? ? ? re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > >>>>>> finds 'cyta' and the search returns a match. > > >>>>>> false or false == false > > >>>>>> blabla... isn't executed. > > >>>>> Lets forget the 2nd or argument, ill put it off > > >>>>> so we have this now > > >>>>> if ( mycookie and mycookie.value != 'nikos' ): > >>>>> ? ? ? ?#do stuff as long as there ins't a cookie names visitor with a > >>>>> value of nikos in the broswer > > >>>>> What does it mean practically that the mycookie equals to None? > >>>>> That mycookie doesnt exist? > > >>>>> How should i write this if block to mkake sure it checks whether or > >>>>> not the cookie exists? > > >>>> Under what conditions do you want to execute the block? > > >>>> This: > > >>>> ? ? ? ?mycookie and mycookie.value != 'nikos' > > >>>> will be true if: > > >>>> ? ? ? ?there _is_ a cookie, but its value isn't 'nikos' > > >>>> I think that you want is to execute the block if someone else is > >>>> visiting. Correct? > > >>> Yes that exactyl right! > > >>> To make sure a cookie is set i have a script names koukos.py > >>> containing this: > > >>> ============================== > >>> #!/usr/bin/python > >>> # -*- coding: utf-8 -*- > > >>> import cgitb; cgitb.enable() > >>> import cgi, os, Cookie > > >>> # initialize cookie > >>> cookie = Cookie.SimpleCookie() > >>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >>> mycookie = cookie.get('visitor') > > >>> htmlBody = [] > > >>> # if visitor cookie does exist > >>> if ( mycookie and mycookie.value == 'nikos' ): > >>> ? ? ? htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? > >>> ????????? ?????????? ??? ???????!') > >>> ? ? ? cookie['visitor'] = 'nikos' > >>> ? ? ? cookie['visitor']['expires'] = -1 ? ? ?#this cookie will expire > >>> now > >>> else: > >>> ? ? ? htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? > >>> ?? ??????! ?? ????? ????? ? ??????? ??????????!!') > >>> ? ? ? cookie['visitor'] = 'nikos' > >>> ? ? ? cookie['visitor']['expires'] = 60*60*24*30*12 > > >>> htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') > > >>> print(cookie) > >>> print('\n'.join(htmlBody)) > >>> ============================= > > >>> Which i seicth on and off according to my desire if i want to be > >>> counted or not! > > >>>> How do you know when it _is_ you? There'll be a cookie which says it's > >>>> you? > > >>>> If so, then you want to execute the block if there isn't any cookie, or > >>>> if there's a cookie but it doesn't say it's you: > > >>>> ? ? ? ?not mycookie or mycookie.value != 'nikos' > > >>> i tried this as you suggested: > > >>> if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| > >>> yandex|13448|spider|crawl)', host ) is None: > > >>> but the counter keeps increasing although the cookie named visitor on > >>> my browser exist and also has the valuie of 'nikos'. > > >>> Why it keeps increasing? Doesn't the if code "sees" that the cookie > >>> with a value of "nikos" is present!?!! > > >> Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you > >> said that host was '78-236-176.adsl.cyta.gr', so it matched. > > >> Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still > >> '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the > >> condition is true. > > > Thats what i want. > > > If host doesnt contain substringsa of the regex to execute if block. > > if it does match i dont want then if block to execute, hence the > > counter too. > > > The reason i had 'cyta' before is because not mycookie or > > mycookie.value != 'nikos' ?doesn't filter me out. > > > The problem is what happens with the > > > not mycookie or mycookie.value != 'nikos' > > > Since cookie 'visitor' does contain the 'nikos' value why the if code > > blck gets executed? > > This part: > > ? ? ?( not mycookie or mycookie.value != 'nikos' ) > > is false but this part: > > ? ? ?re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > is true because host doesn't contain any of those substrings. So what is the problem here? And why mycookie when i print it it says None? Perhpas its doenst get loaded like that? # initialize cookie cookie = SimpleCookie() cookie.load( os.environ.get('HTTP_COOKIE', '') ) mycookie = cookie.get('visitor') From greg.ewing at canterbury.ac.nz Mon Aug 30 04:11:06 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 30 Aug 2010 20:11:06 +1200 Subject: String substitution VS proper mysql escaping In-Reply-To: <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> Message-ID: <8e17d7FsbU1@mid.individual.net> Nik the Greek wrote: > Yes i will i just asked to know if i were to substitute what might be > the problem so to understand why i need the quoting. Because if you use % to build a query string, the result must be syntactically valid SQL. The values that you substitute into the placeholders must end up looking like SQL literals. That means string values need to be in quotes, and probably dates as well, although numbers don't. When you use the execute method's own parameter substitution mechanism, things are different. It's not a textual replacement, and you don't put quotes around the placeholders. There's no particular reason for that, it's just the way it's defined to work. -- Greg From ldo at geek-central.gen.new_zealand Mon Aug 30 04:21:00 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 30 Aug 2010 20:21 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7xr5hg3a7s.fsf@ruckus.brouhaha.com> Message-ID: In message <7xr5hg3a7s.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Actually that code looks suspicious. Suppose in > > AddrObj = PyTuple_GetItem(TheBufferInfo, 0); > LenObj = PyTuple_GetItem(TheBufferInfo, 1); > > the first PyTuple_GetItem succeeds and the second one fails. Admittedly, I did take a shortcut here: array.buffer_info returns a tuple of two items, so I?m not expecting one GetItem to succeed and the other to fail. From greg.ewing at canterbury.ac.nz Mon Aug 30 04:22:21 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 30 Aug 2010 20:22:21 +1200 Subject: Passing variable to SQL statement when using psycopg2 In-Reply-To: References: <4c7b4fd3$0$6887$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <8e182aF4o0U1@mid.individual.net> Chris Rebert wrote: > On Sun, Aug 29, 2010 at 11:29 PM, Julia Jacobson >>Where does the "E" in front of 'xyz' come from? >>It's probably the reason, why my query doesn't work. > > Quite doubtful, considering the example in the psycopg2 docs also has the E: > http://initd.org/psycopg/docs/cursor.html#cursor.mogrify Seems to be a postgres extension to the sql string literal syntax: http://issues.liferay.com/browse/LEP-3182 -- Greg From ldo at geek-central.gen.new_zealand Mon Aug 30 04:23:00 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 30 Aug 2010 20:23 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> Message-ID: In message <7x39twpuxi.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Lawrence D'Oliveiro writes: > >>> the CPython API means endlessly finding and fixing refcount bugs that >>> lead to either crashes/security failures, or memory leaks. >> >> I don?t see why that should be so. It seems a very simple discipline to >> follow: initialize, allocate, free. Here?s an example snippet from my DVD >> Menu Animator : > > In practice it has been a problem. Maybe people need to learn to write code in a more structured fashion. > If it hasn't happened to you yet, you're either burning a bunch of effort > that programmers of more automatic systems can put to more productive > uses ... What makes you say that? Avoiding bugs is not a ?productive use?? >> And how do you run such an application? You have to limit it to a >> predetermined amount of memory to begin with, otherwise it would easily >> gobble up everything you have. > > No that's usually not a problem-- the runtime system (generational gc) > can figure out enough from your allocation pattern to prevent the heap > from getting overlarge. And yet Java apps, for example, are (in)famous for excessive memory usage compared to those written in non-GC-dependent languages. From news1234 at free.fr Mon Aug 30 04:44:39 2010 From: news1234 at free.fr (News123) Date: Mon, 30 Aug 2010 10:44:39 +0200 Subject: how to find out, whether a path is socket or device In-Reply-To: <4c7af6b7$0$11118$c3e8da3@news.astraweb.com> References: <4c7af148$0$28551$426a74cc@news.free.fr> <4c7af6b7$0$11118$c3e8da3@news.astraweb.com> Message-ID: <4c7b6f77$0$5359$426a74cc@news.free.fr> On 08/30/2010 02:09 AM, Steven D'Aprano wrote: > On Mon, 30 Aug 2010 01:46:16 +0200, News123 wrote: > >> Hi, >> >> Under Linux I'd like to find out, whether I got a file, a character >> device or a socket as a parameter. > > See the stat module. > > Thks a lot. I was looking in os.path and forgot about stat (it obviously was too late :-( ) From mahaboobnisha at gmail.com Mon Aug 30 04:53:29 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Mon, 30 Aug 2010 01:53:29 -0700 (PDT) Subject: comp.lang.python Message-ID: <8c31f2b7-c6df-4621-ab87-99cd8da3c718@s17g2000prh.googlegroups.com> www.127760.blogspot.com From thomas at jollybox.de Mon Aug 30 04:59:10 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 30 Aug 2010 10:59:10 +0200 Subject: PyGeo In-Reply-To: <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> Message-ID: <201008301059.11218.thomas@jollybox.de> On Monday 30 August 2010, it occurred to L to exclaim: > I have tried it and as soon as you try any of the examples in the > examples dir it cannot find numpy etc.... > > I have manually move the pygeo dirs and contents to > /usr/lib/python2.6/dis-packages, > > (this is the directory where numpy, numeric and scipy were installed > when using synaptic ) > > made sure that read and write permissions set for ALL FILES and > DIRECTORIES to RW using sudo chmod 777 Wait -- did you just try to use pymaxima, or did you properly (try to) install the dependencies? You need VPython. It's in the ubuntu archives. http://packages.ubuntu.com/lucid/python-visual And then you need to download and install pygeo. http://pygeo.sourceforge.net/download.html It probably uses distutils, so you'd extract the source archive and run sudo python setup.py install If THAT gives you any errors, then please come back here, with the exact error messages. If it works, then PyGeo should be installed. If it still doesn't work, then there's certainly a chance it won't work, but you can still ask here for help, with the exact error messages, so we have something to build upon when trying to figure out what's wrong. - Thomas From sschwarzer at sschwarzer.net Mon Aug 30 05:24:34 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 30 Aug 2010 11:24:34 +0200 Subject: Confused: Newbie Function Calls In-Reply-To: <13e3dc53-f475-46ad-bd3c-ca023b7b6bcb@c38g2000vba.googlegroups.com> References: <2dd74ab4-5ed6-40ac-aea7-705977b61b21@g21g2000prn.googlegroups.com> <5cc5d255-1aad-4b01-a5b8-483ce5dc584d@t20g2000yqa.googlegroups.com> <13e3dc53-f475-46ad-bd3c-ca023b7b6bcb@c38g2000vba.googlegroups.com> Message-ID: <4C7B78D2.80308@sschwarzer.net> Hi Pinku, On 2010-08-11 21:35, Pinku Surana wrote: > Even though I used the same name "x" for a local and global variable, > they are actually completely different. When I call "fun(x)" it COPIES > the global value of "x" into the local variable "x" in "fun". [...] The global value isn't copied when calling the function. Instead, the global and the local name both point to the same object when the body of the function starts to run. > def fun(x_local): > y_local = 1 > x_local += y_local > print x_local Only after the assignment "x_local += y_local" x_local points to a new object which is the result of the addition of the previously "shared" object and y_local. Stefan From eckhardt at satorlaser.com Mon Aug 30 06:45:58 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 30 Aug 2010 12:45:58 +0200 Subject: help in code References: <4c73717c$0$28639$c3e8da3@news.astraweb.com> Message-ID: <6oesk7-7lt.ln1@satorlaser.homedns.org> Steven D'Aprano wrote: [reading Bengali] > In Python 2, you probably need to do this: > > f = open("filename") > bytes = f.read() > text = bytes.decode('which-encoding-you-use') > f.close() In Python 2, I'd rather take a look at the "codecs" module (see http://docs.python.org), namely the "codecs.open" function. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From no.email at nospam.invalid Mon Aug 30 06:46:23 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 03:46:23 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7xr5hg3a7s.fsf@ruckus.brouhaha.com> Message-ID: <7xvd6sv0n4.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: >> AddrObj = PyTuple_GetItem(TheBufferInfo, 0); >> LenObj = PyTuple_GetItem(TheBufferInfo, 1); >> >> the first PyTuple_GetItem succeeds and the second one fails. > > Admittedly, I did take a shortcut here: array.buffer_info returns a tuple of > two items, so I?m not expecting one GetItem to succeed and the other to > fail. FromArray is a parameter to the function, with no type check to make sure it's really an array. In fact your code allows for the possibility that it doesn't support the buffer_info operation (if I understand the purpose of the null return check after the PyObject_CallMethod) which means it's prepared for the argument to -not- be an array. In that case maybe it's some other object with a "buffer_info" operation that returns a 1-element tuple. If the function is callable from Python code, then that arg type is completely out of the C code's control. Even if it's only callable from C, you're still depending on not one but two different invariants (that the arg is an array, and that array.buffer_info returns a 2-tuple) that are undocumented and unchecked in the function. I cannot agree with your claim that the approach scales. From thomas at jollybox.de Mon Aug 30 06:50:32 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 30 Aug 2010 12:50:32 +0200 Subject: How to convert (unicode) text to image? In-Reply-To: References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: <201008301250.32415.thomas@jollybox.de> On Monday 30 August 2010, it occurred to rurpy at yahoo.com to exclaim: > Face the facts dude. The Python docs have some major problems. > They were pretty good when Python was a new, cool, project used > by a handful of geeks. They are good relative to the "average" > (whatever that is) open source project -- but that bar is so low > as to be a string lying on the ground. Actually, the Python standard library reference manual is excellent. At least that's my opinion. Granted, it's not necessarily the best in the world. It could probably be better. But that goes for just about every documentation effort there is. What exactly are you comparing the Python docs to, I wonder? Obviously not something like Vala, but that goes without saying. "kj" said that the Perl docs were better. I can't comment on that. I also won't comment on the sorry mess that the language "Perl" is, either. There are a few documentation efforts that I recognize are actually better than the Python docs: Firstly, the MSDN Library docs for the .Net framework. Not that I refer to it much, but it is excellent, and it probably was a pretty darn expensive project too. Secondly, the libc development manual pages on Linux and the BSDs. Provided you know your way around the C library, they are really a top-notch reference. If you were comparing it to the Java standard library documentation, please provide a link. I've tried and failed to find any coherent documentation of the standard classpath that anything like approaches the quality of the Python documentation. > > Your overly defensive and oppressive response does not help. > All it (combined with similar knee-jerk responses) does is > act to suppress any criticism leaving the impression that > the Python docs are really great, an assertion commonly made > here and often left unchallenged. Responses like yours > create a force that works to maintain the status quo. From no.email at nospam.invalid Mon Aug 30 07:00:33 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 04:00:33 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> Message-ID: <7xr5hguzzi.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: >> If it hasn't happened to you yet, you're either burning a bunch of effort >> that programmers of more automatic systems can put to more productive >> uses ... > > What makes you say that? Avoiding bugs is not a ?productive use?? Avoiding any particular bug through constant and pervasive vigilance is far less productive than using a system where causing that particular type of bug is impossible to begin with. IMO the code you posted has latent bugs as discussed in the other post. It might work at the moment you checked it in but it is brittle. I wouldn't have signed off on it in a code review. > And yet Java apps, for example, are (in)famous for excessive memory > usage compared to those written in non-GC-dependent languages. I think that may mostly be an issue with the bloated nature of most Java apps. Certainly Lisp systems have run in production for decades on machines with much less memory than we would consider acceptable these days for any substantial Python app. It's probably true that gc copying-style gc is more memory hungry than Python's refcount system. Mark-sweep gc should have comparable memory consumption and better speed than refcounting, though less speed than copying. JHC (experimental Haskell compiler) recently started using a mixture of gc and region inference. It will be interesting to see how that works out. From no.email at nospam.invalid Mon Aug 30 07:10:06 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 04:10:06 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> <7xhbidndc6.fsf@ruckus.brouhaha.com> <8e15pqFn89U1@mid.individual.net> Message-ID: <7xmxs4uzjl.fsf@ruckus.brouhaha.com> Gregory Ewing writes: >> These days I think the GC pause issue is overrated except for real-time >> control applications. > > Also for games, which are a fairly common application > these days. Even a few milliseconds can be too long when > you're trying to achieve smooth animation. The usual hack with games is you do a major gc when the user advances between game levels. You can do minor gc's during the screen refresh interval. > I'd be disappointed if CPython ditched refcounting and > then became unsuitable for real-time games as a result. Refcounting is susceptable to the same pauses for reasons already discussed. From no.email at nospam.invalid Mon Aug 30 07:14:56 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 04:14:56 -0700 Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: <7xiq2suzbj.fsf@ruckus.brouhaha.com> Thomas Jollans writes: > Actually, the Python standard library reference manual is excellent. At least > that's my opinion.... > What exactly are you comparing the Python docs to, I wonder? Obviously not > something like Vala, but that goes without saying. I didn't know Vala had especially good docs. I think GCC's docs are pretty good. Python's are mostly ok but have significant gaps. For example, tkinter has been part of the stdlib for at least a decade but is totally undocumented in the Python library manual. From aahz at pythoncraft.com Mon Aug 30 08:40:03 2010 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2010 05:40:03 -0700 Subject: Simple Problem but tough for me if i want it in linear time References: <998cb922-e6e3-46cf-9ae1-8564f52bc8bd@i18g2000pro.googlegroups.com> <4c6c9b3f$0$28637$c3e8da3@news.astraweb.com> Message-ID: In article , Tim Chase wrote: >On 08/18/10 21:47, Steven D'Aprano wrote: >> >> Frankly, I think the OP doesn't really know what he wants, other than >> premature optimization. It's amazing how popular that is :) > >You see, the trick to prematurely optimizing is to have a good >algorithm for prematurely optimizing...the real question them >becomes "How can I optimize my premature-optimization algorithms >to O(1) instead of O(newsgroup)?" > >:-) > >-tkc > >PS: I'm not positive, but O(newsgroup) may asymptotically >approach O(log n) if the question is well formed, but O(2^n) if >flaming, indentation/line-length preferences, the meaning of OOP, >SQL-parameter escaping, McNugget combinations, or suggestions that >Python is "just a scripting language" are involved... +1 QOTW -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From thomas at jollybox.de Mon Aug 30 08:42:28 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 30 Aug 2010 14:42:28 +0200 Subject: How to convert (unicode) text to image? In-Reply-To: <7xiq2suzbj.fsf@ruckus.brouhaha.com> References: <7xiq2suzbj.fsf@ruckus.brouhaha.com> Message-ID: <201008301442.29025.thomas@jollybox.de> On Monday 30 August 2010, it occurred to Paul Rubin to exclaim: > Thomas Jollans writes: > > Actually, the Python standard library reference manual is excellent. At > > least that's my opinion.... > > What exactly are you comparing the Python docs to, I wonder? Obviously > > not something like Vala, but that goes without saying. > > I didn't know Vala had especially good docs. Sorry for being imprecise. Let me clarify: they're practically non existent. The language docs are okay if you know C#, but there are no API docs that are more than auto-generated lists of classes and methods. > I think GCC's docs are > pretty good. Python's are mostly ok but have significant gaps. For > example, tkinter has been part of the stdlib for at least a decade but > is totally undocumented in the Python library manual. From aahz at pythoncraft.com Mon Aug 30 08:47:05 2010 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2010 05:47:05 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78f210$0$28655$c3e8da3@news.astraweb.com> <7xd3t0orah.fsf@ruckus.brouhaha.com> <4c7b279d$0$28650$c3e8da3@news.astraweb.com> Message-ID: In article <4c7b279d$0$28650$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Sun, 29 Aug 2010 17:52:38 -0700, Paul Rubin wrote: >>Attribution lost: >>> >>> That's a problem with the CPython API, not reference counting. The >>> problem is that the CPython API is written at too low a level, beneath >>> that at which the garbage collector exists, so naturally you have to >>> manually manage memory. >> >> Care to give an example of a reference counted system that's written any >> other way? > >The complexity of the ref counter is invisible when writing pure Python >code, and I believe it is also invisible when writing code in Cython. The >difficulty of dealing with ref counts is abstracted away. That's not completely true. You know perfectly well that it's almost trivially easy to leak memory with refcounting, and there are certain ways in which Python leaks memory invisibly if you don't know how it works. One recent example at work was when someone was arguing with me about whether we were leaking file handles and I had to prove that you could leak file handles if you didn't clean up exceptions -- but that cleaning up the exception *did* close the file handles. (This code was originally written in Python 2.4, and partly because of this we are making more of a push to use "with"....) If you're restricting your claim just to the actual management of the reference counter, you're correct, but it's especially not clear that your second sentence is so restricted. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From michael.a.powe at gmail.com Mon Aug 30 08:52:02 2010 From: michael.a.powe at gmail.com (naugiedoggie) Date: Mon, 30 Aug 2010 05:52:02 -0700 (PDT) Subject: Using a function for regular expression substitution References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: On Aug 29, 1:14?pm, MRAB wrote: > On 29/08/2010 15:22, naugiedoggie wrote: > > I'm having a problem with using a function as the replacement in > > re.sub(). > > Here is the function: > > def normalize(s) : > > ? ? ?return > > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) > > This normalises the provider and returns only that, and none of the > remainder of the string. > > I think you might want this: > > def normalize(s): > ? ? ?return s[ : s.start('provider')] + > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + > s[s.start('provider') : ] > > It returns the part before the provider, followed by the normalised > provider, and then the part after the provider. Hello, Thanks for the reply. There must be something basic about the re.sub() function that I'm missing. The documentation shows this example: >>> def dashrepl(matchobj): ... if matchobj.group(0) == '-': return ' ' ... else: return '-' >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') 'pro--gram files' >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) 'Baked Beans & Spam' According to the doc, the modifying function takes one parameter, the MatchObject. The re.sub function takes only a compiled regex object or a pattern, generates a MatchObject from that object/pattern and passes the MatchObject to the given function. Notice that in the examples, the re.sub() returns the entire line, with the changes made. But the function itself returns only the change. What is happening for me is that, if I have a line that contains &Search_Provider=chen&p=value, the processed line ends up with &Chen&p=value. Now, I did follow up with your suggestion. `s' is actually a MatchObject (bad param naming on my part, I started out passing a string into the function and then changed it to a MatchObject, but didn't change the param name), so I made the following change: return line[s.pos : s.start('provider')] + \ urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + \ line[s.end('provider') : ] In order to make this work (finally), I had to make the processing function look like this: def processLine(l) : global line line = l provider = getProvider(line) if provider == "No Provider" : return line scenario = getScenario(line) if filter (lambda a: a != None, [getOrg(s,scenario) for s in orgs]) == [] : line = re.sub(provider_pattern,normalize,line) else : line.replace(provider_parameter, org_parameter) return line And then the call: lines = fileReader.readlines() [ fileWriter.write(l) for l in [processLine(l) for l in lines]] Without this complicated gobbledigook, I could not get the correct result. I hate global vars and I completely do not understand why I have to go through this twisting and turning to get the desired result. [ ... ] > These can be replaced by: > > ? ? ? ? if 'Search_Type' in line and 'Search_Provider' in line: > > > ? ? ? ? ? ?re.sub(provider_matcher,normalize,line) > > re.sub is returning the result, which you're throwing away! > > ? ? ? ? ? ? ? ? line = re.sub(provider_matcher,normalize,line) I can't count the number of times I have forgotten the meaning of 'returns a string' when reading docs about doing substitutions. In this case, I had put the `line = ' in and taken it out. And I should know better, from years of programming in Java, where strings are immutable and you _always_ get a new, returned string. Should be second nature. Thanks for the help, much appreciated. mp From aahz at pythoncraft.com Mon Aug 30 09:03:02 2010 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2010 06:03:02 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: In article , Raymond Hettinger wrote: >On Aug 29, 12:12=A0pm, John Nagle wrote: >> >> Is the "in" test faster for a dict or a set? Is "frozenset" faster >> than "set"? Use case is for things like applying "in" on a list of >> 500 or so words while checking a large body of text. > >There is no significant difference. All three are implemented using >substantially the same code. That reminds me: one co-worker (who really should have known better ;-) had the impression that sets were O(N) rather than O(1). Although writing that off as a brain-fart seems appropriate, it's also the case that the docs don't really make that clear, it's implied from requiring elements to be hashable. Do you agree that there should be a comment? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From cutebhavanaa at gmail.com Mon Aug 30 09:31:04 2010 From: cutebhavanaa at gmail.com (sexy girl) Date: Mon, 30 Aug 2010 06:31:04 -0700 (PDT) Subject: ***SEX IN COLLEGE HOT AND SEXY VIDEOS*** Message-ID: http://cute-actress-images.blogspot.com/ http://cute-sexy-images.blogspot.com/ http://actress.0jet.com http://factson-globalwarming.blogspot.com/ http://mysteries-that-threats.blogspot.com/ http://healthtips.06fr.com http://actress.0jet.com http://dailyscience.youblog.net http://jobs4all.menblogs.net http://healthtips.06fr.com http://dailyscience.youblog.net http://jobs4all.menblogs.net http://schoolsuniversities.web-day.net http://cute-actress-images.blogspot.com/ http://science-vs-technology.blogspot.com/ http://my-jobs-4-u.blogspot.com/ http://cute-sexy-images.blogspot.com/ From michael.a.powe at gmail.com Mon Aug 30 09:31:33 2010 From: michael.a.powe at gmail.com (naugiedoggie) Date: Mon, 30 Aug 2010 06:31:33 -0700 (PDT) Subject: Using a function for regular expression substitution References: <9170aad0-478a-4222-b6e2-88d00899d8b4@t2g2000yqe.googlegroups.com> Message-ID: <291dd1c3-a63a-44d3-948d-bd88b27f92b4@j8g2000yqd.googlegroups.com> On Aug 30, 8:52?am, naugiedoggie wrote: > On Aug 29, 1:14?pm, MRAB wrote: > > > > > > > On 29/08/2010 15:22, naugiedoggie wrote: > > > I'm having a problem with using a function as the replacement in > > > re.sub(). > > > Here is the function: > > > def normalize(s) : > > > ? ? ?return > > > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) > > > This normalises the provider and returns only that, and none of the > > remainder of the string. > > > I think you might want this: > > > def normalize(s): > > ? ? ?return s[ : s.start('provider')] + > > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + > > s[s.start('provider') : ] > > > It returns the part before the provider, followed by the normalised > > provider, and then the part after the provider. > > Hello, > > Thanks for the reply. > > There must be something basic about the re.sub() function that I'm > missing. ?The documentation shows this example: > > >>> def dashrepl(matchobj): > > ... ? ? if matchobj.group(0) == '-': return ' ' > ... ? ? else: return '-'>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') > 'pro--gram files' > >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) > > 'Baked Beans & Spam' > > > According to the doc, the modifying function takes one parameter, the > MatchObject. ?The re.sub function takes only a compiled regex object > or a pattern, generates a MatchObject from that object/pattern and > passes the MatchObject to the given function. Notice that in the > examples, the re.sub() returns the entire line, with the changes made. > But the function itself returns only the change. ?What is happening > for me is that, if I have a line that contains > &Search_Provider=chen&p=value, the processed line ends up with > &Chen&p=value. > > Now, I did follow up with your suggestion. ?`s' is actually a > MatchObject (bad param naming on my part, I started out passing a > string into the function and then changed it to a MatchObject, but > didn't change the param name), so I made the following change: > > > return line[s.pos : s.start('provider')] + \ > > urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) + \ > ? ? ? ? line[s.end('provider') : ] > > > In order to make this work (finally), I had to make the processing > function look like this: > > > def processLine(l) : > ? ? ? ? global line > ? ? ? ? line = l > ? ? ? ? provider = getProvider(line) > ? ? ? ? if provider == "No Provider" : return line > ? ? ? ? scenario = getScenario(line) > ? ? ? ? if filter (lambda a: a != None, [getOrg(s,scenario) for s in > orgs]) == [] : > ? ? ? ? ? ? line = re.sub(provider_pattern,normalize,line) > ? ? ? ? else : > ? ? ? ? ? ? line.replace(provider_parameter, org_parameter) > ? ? ? ? return line > > > And then the call: > > > lines = fileReader.readlines() > [ fileWriter.write(l) for l in [processLine(l) for l in lines]] > > > Without this complicated gobbledigook, I could not get the correct > result. ?I hate global vars and I completely do not understand why I > have to go through this twisting and turning to get the desired > result. > > [ ... ] > > > These can be replaced by: > > > ? ? ? ? if 'Search_Type' in line and 'Search_Provider' in line: > > > > ? ? ? ? ? ?re.sub(provider_matcher,normalize,line) > > > re.sub is returning the result, which you're throwing away! > > > ? ? ? ? ? ? ? ? line = re.sub(provider_matcher,normalize,line) > > I can't count the number of times I have forgotten the meaning of > 'returns a string' when reading docs about doing substitutions. In > this case, I had put the `line = ' in and taken it out. ?And I should > know better, from years of programming in Java, where strings are > immutable and you _always_ get a new, returned string. ?Should be > second nature. > > Thanks for the help, much appreciated. > > mp Hello, Well, that turned out to be still wrong. I did start getting the proper param=value back from my `normalize' function, but I got "extra" data as well. This works: def normalize(s) : return s.group('search') +'='+urllib.quote(string.capwords(urllib.unquote(s.group('provider')))) Essentially, the pattern contained two groups, one identifying the parameter name and one the value. By concat'ing the two back together, I was able to achieve the desired result. I suppose the lesson is, the function replaces the entire match rather than just the specified text captured. Thanks. mp From no.email at nospam.invalid Mon Aug 30 09:39:50 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 06:39:50 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: <7xiq2sqkwp.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > That reminds me: one co-worker (who really should have known better ;-) > had the impression that sets were O(N) rather than O(1). Although > writing that off as a brain-fart seems appropriate, it's also the case > that the docs don't really make that clear, it's implied from requiring > elements to be hashable. Do you agree that there should be a comment? It's O(1) with reasonable input distributions but can be O(N) for adverse distributions. The docs should say something like that, and include this link: http://www.cs.rice.edu/~scrosby/hash/CrosbyWallach_UsenixSec2003/index.html From nikos.the.gr33k at gmail.com Mon Aug 30 09:48:33 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 06:48:33 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> Message-ID: <6676c33f-0012-4051-bc75-b35af37df367@z28g2000yqh.googlegroups.com> On 30 ???, 11:01, Nik the Greek wrote: > On 30 ???, 06:12, MRAB wrote: > > > > > > > > > > > On 30/08/2010 03:55, Nik the Greek wrote: > > > > On 30 ???, 05:43, MRAB ?wrote: > > >> On 30/08/2010 03:07, Nik the Greek wrote: > > > >>> On 30 ???, 04:51, MRAB ? ?wrote: > > >>>> On 30/08/2010 02:14, ????? wrote: > > > >>>>> On 29 ???, 21:44, MRAB ? ? ?wrote: > > >>>>>> On 29/08/2010 06:34, ????? wrote: > > > >>>>>>> On 28 ???, 23:15, MRAB ? ? ? ?wrote: > > >>>>>>>> On 28/08/2010 20:37, ????? wrote: > > > >>>>>>>>> On 22 ???, 10:27, ????? ? ? ? ? ?wrote: > > >>>>>>>>>> On 16 ???, 14:31, Peter Otten<__pete... at web.de> ? ? ? ? ?wrote: > > > >>>>>>>>>>> ????? wrote: > > >>>>>>>>>>>> # initializecookie > > >>>>>>>>>>>> cookie=Cookie.SimpleCookie() > > >>>>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > >>>>>>>>>>>> mycookie =cookie.get('visitor') > > > >>>>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > > >>>>>>>>>>>> yandex|13448|spider|crawl)', host ) is None: > > >>>>>>>>>>>> ? ? ? ? ?blabla... > > >>>>>>>>>>>> ======================== > > > >>>>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos > > >>>>>>>>>>>> within. > > >>>>>>>>>>>> So, i have to ask why the if fails? > > > >>>>>>>>>>> Maybe it's because != != == > > > >>>>>>>>>> Iwant ti if code block to be executed only if the browsercookienames > > >>>>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos' > > > >>>>>>>>>> Is there somethign wrong with the way i wrote it? > > > >>>>>>>>> Please do help me with this too becaus eif i dont solve this my > > >>>>>>>>> website keeps count my each visit like iam a guest visitor! > > > >>>>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and > > >>>>>>>> repr(host). Then follow the code yourself to see whether the condition > > >>>>>>>> is True. > > > >>>>>>> print mycookie outputs 'None' > > > >>>>>>> Thts weird because i check with the browser and the cookie is there! > > > >>>>>> Just because you can see it doesn't mean your code can. > > > >>>>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr' > > > >>>>>>> repr(mycookie.value) (unless mycookie is None) > > > >>>>>>> and also > > > >>>>>>> print mycookie.value gives an error too. Maybe there is not a value > > >>>>>>> method? > > > >>>>>> If mycookie is None, then it's not surprising that doesn't have 'value'. > > > >>>>>> In summary, mycookie is None, so: > > > >>>>>> ? ? ? ? mycookie and mycookie.value != 'nikos' > > > >>>>>> is false (actually None, which is treated as false). > > > >>>>>> host == '78-236-176.adsl.cyta.gr', so: > > > >>>>>> ? ? ? ? re.search(r'(cyta|yandex|13448|spider|crawl)', host) > > > >>>>>> finds 'cyta' and the search returns a match. > > > >>>>>> false or false == false > > > >>>>>> blabla... isn't executed. > > > >>>>> Lets forget the 2nd or argument, ill put it off > > > >>>>> so we have this now > > > >>>>> if ( mycookie and mycookie.value != 'nikos' ): > > >>>>> ? ? ? ?#do stuff as long as there ins't a cookie names visitor with a > > >>>>> value of nikos in the broswer > > > >>>>> What does it mean practically that the mycookie equals to None? > > >>>>> That mycookie doesnt exist? > > > >>>>> How should i write this if block to mkake sure it checks whether or > > >>>>> not the cookie exists? > > > >>>> Under what conditions do you want to execute the block? > > > >>>> This: > > > >>>> ? ? ? ?mycookie and mycookie.value != 'nikos' > > > >>>> will be true if: > > > >>>> ? ? ? ?there _is_ a cookie, but its value isn't 'nikos' > > > >>>> I think that you want is to execute the block if someone else is > > >>>> visiting. Correct? > > > >>> Yes that exactyl right! > > > >>> To make sure a cookie is set i have a script names koukos.py > > >>> containing this: > > > >>> ============================== > > >>> #!/usr/bin/python > > >>> # -*- coding: utf-8 -*- > > > >>> import cgitb; cgitb.enable() > > >>> import cgi, os, Cookie > > > >>> # initialize cookie > > >>> cookie = Cookie.SimpleCookie() > > >>> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > >>> mycookie = cookie.get('visitor') > > > >>> htmlBody = [] > > > >>> # if visitor cookie does exist > > >>> if ( mycookie and mycookie.value == 'nikos' ): > > >>> ? ? ? htmlBody.append('??? ??? ??????? ???????? ??? ?? ?? ????????? ?? > > >>> ????????? ?????????? ??? ???????!') > > >>> ? ? ? cookie['visitor'] = 'nikos' > > >>> ? ? ? cookie['visitor']['expires'] = -1 ? ? ?#this cookie will expire > > >>> now > > >>> else: > > >>> ? ? ? htmlBody.append('??? ?? ??? ??? ???? ??? ?? ????, ??? ?? ????, ??? > > >>> ?? ??????! ?? ????? ????? ? ??????? ??????????!!') > > >>> ? ? ? cookie['visitor'] = 'nikos' > > >>> ? ? ? cookie['visitor']['expires'] = 60*60*24*30*12 > > > >>> htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n') > > > >>> print(cookie) > > >>> print('\n'.join(htmlBody)) > > >>> ============================= > > > >>> Which i seicth on and off according to my desire if i want to be > > >>> counted or not! > > > >>>> How do you know when it _is_ you? There'll be a cookie which says it's > > >>>> you? > > > >>>> If so, then you want to execute the block if there isn't any cookie, or > > >>>> if there's a cookie but it doesn't say it's you: > > > >>>> ? ? ? ?not mycookie or mycookie.value != 'nikos' > > > >>> i tried this as you suggested: > > > >>> if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn| > > >>> yandex|13448|spider|crawl)', host ) is None: > > > >>> but the counter keeps increasing although the cookie named visitor on > > >>> my browser exist and also has the valuie of 'nikos'. > > > >>> Why it keeps increasing? Doesn't the if code "sees" that the cookie > > >>> with a value of "nikos" is present!?!! > > > >> Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you > > >> said that host was '78-236-176.adsl.cyta.gr', so it matched. > > > >> Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still > > >> '78-236-176.adsl.cyta.gr' then of course it doesn't match, so the > > >> condition is true. > > > > Thats what i want. > > > > If host doesnt contain substringsa of the regex to execute if block. > > > if it does match i dont want then if block to execute, hence the > > > counter too. > > > > The reason i had 'cyta' before is because not mycookie or > > > mycookie.value != 'nikos' ?doesn't filter me out. > > > > The problem is what happens with the > > > > not mycookie or mycookie.value != 'nikos' > > > > Since cookie 'visitor' does contain the 'nikos' value why the if code > > > blck gets executed? > > > This part: > > > ? ? ?( not mycookie or mycookie.value != 'nikos' ) > > > is false but this part: > > > ? ? ?re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > > is true because host doesn't contain any of those substrings. > > So what is the problem here? > > And why mycookie when i print it it says None? > > Perhpas its doenst get loaded like that? > > # initialize cookie > cookie = SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > mycookie = cookie.get('visitor') Please someone else has an idea on how this to work? From python at bdurham.com Mon Aug 30 09:54:04 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 30 Aug 2010 09:54:04 -0400 Subject: shlex, unicode, and subprocess.Popen on Windows Message-ID: <1283176444.5865.1392429397@webmail.messagingengine.com> Python 2.6/Windows: shlex.split() does not support unicode strings. Is this simply a limitation of the current shlex implementation or is this an intentional design decision that reflects the behavior of how the Windows shell supports unicode values? Specifically, it doesn't appear that subprocess.Popen() has any restrictions on unicode args, but perhaps I'm missing some edge cases where this may be true? If this is simply a limitation of the current shlex implementation, does anyone see any risks to encoding a command string using 'xmlreplace' ( command.encode( 'utf8', 'xmlreplace' ) ) in order to hide unicode chars, splitting the now ASCII string using shlex.split, and then walking the list of strings returned by shlex.split, decoding them back to Unicode ( .decode( 'utf8' ) ) before passing this list to subprocess.Popen() for execution? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Mon Aug 30 10:02:33 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 31 Aug 2010 00:02:33 +1000 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> Message-ID: <878w3ogpvq.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > That reminds me: one co-worker (who really should have known better ;-) > had the impression that sets were O(N) rather than O(1). For settling exactly this kind of confusion, Python's standard library comes with a module, the ?timeit? module. Your co-worker should have known better: don't guess about timing performance, measure it. Or am I missing something here? -- \ ?If you don't know what your program is supposed to do, you'd | `\ better not start writing it.? ?Edsger W. Dijkstra | _o__) | Ben Finney From clp2 at rebertia.com Mon Aug 30 10:04:24 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 30 Aug 2010 07:04:24 -0700 Subject: shlex, unicode, and subprocess.Popen on Windows In-Reply-To: <1283176444.5865.1392429397@webmail.messagingengine.com> References: <1283176444.5865.1392429397@webmail.messagingengine.com> Message-ID: On Mon, Aug 30, 2010 at 6:54 AM, wrote: > Python 2.6/Windows: shlex.split() does not support unicode strings. Is this > simply a limitation of the current shlex implementation or is this an > intentional design decision that reflects the behavior of how the Windows > shell supports unicode values? It's a bug: http://bugs.python.org/issue1170 Also, shlex is cross-platform; the limitation has nothing to do with Windows. As a matter of fact, the docs mention how shlex's functionality is based off of Unix and POSIX. Cheers, Chris -- Kudos for avoiding shell=True http://blog.rebertia.com From ethan at stoneleaf.us Mon Aug 30 10:10:49 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 30 Aug 2010 07:10:49 -0700 Subject: meta-class troubles Message-ID: <4C7BBBE9.8090003@stoneleaf.us> Good Day! I am stuck... hopefully a few fresh pairs of eyes will spot what I am missing. I have a metaclass, Traits, and two different testing files, test_traits.py and tests.py. test_traits works fine, tests generates the following error: C:\Python31\Lib\site-packages\traits\tests>\python31\python tests.py Traceback (most recent call last): File "tests.py", line 4, in class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): TypeError: type() takes 1 or 3 arguments Working code from test_traits.py: class DerivedClass(metaclass=Traits, traits=(TBundle1, TBundle2)): def repeat(yo, text, count): print('whatever...') def whatsit(yo, arg1): print("calling baseclass's whatsit...") print(super().whatsit(arg1)) Failing code from tests.py: class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): def useless(yo): print("this class won't compile") Any clues or pointers *greatly* appreciated! ~Ethan~ -- Traits is homegrown, the idea based on Michele Simionato's Simple Traits experiment. It was intrigueing, and I wanted to see if I could implement something similar in Python 3. Any ideas now on what to do with it will also be greatly appreciated! :) From contact at xavierho.com Mon Aug 30 10:16:55 2010 From: contact at xavierho.com (Xavier Ho) Date: Tue, 31 Aug 2010 00:16:55 +1000 Subject: meta-class troubles In-Reply-To: <4C7BBBE9.8090003@stoneleaf.us> References: <4C7BBBE9.8090003@stoneleaf.us> Message-ID: Ethan, are you trying to write the constructor in the class statement? Cheers, Xav On 31 August 2010 00:10, Ethan Furman wrote: > Good Day! > > I am stuck... hopefully a few fresh pairs of eyes will spot what I am > missing. > > I have a metaclass, Traits, and two different testing files, test_traits.py > and tests.py. test_traits works fine, tests generates the following error: > > C:\Python31\Lib\site-packages\traits\tests>\python31\python tests.py > Traceback (most recent call last): > File "tests.py", line 4, in > class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): > TypeError: type() takes 1 or 3 arguments > > > Working code from test_traits.py: > class DerivedClass(metaclass=Traits, traits=(TBundle1, TBundle2)): > def repeat(yo, text, count): > print('whatever...') > def whatsit(yo, arg1): > print("calling baseclass's whatsit...") > print(super().whatsit(arg1)) > > Failing code from tests.py: > class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): > def useless(yo): > print("this class won't compile") > > > Any clues or pointers *greatly* appreciated! > > ~Ethan~ > -- > Traits is homegrown, the idea based on Michele Simionato's Simple Traits > experiment. It was intrigueing, and I wanted to see if I could implement > something similar in Python 3. Any ideas now on what to do with it will > also be greatly appreciated! :) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Aug 30 10:17:24 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 30 Aug 2010 07:17:24 -0700 Subject: meta-class troubles In-Reply-To: <4C7BBBE9.8090003@stoneleaf.us> References: <4C7BBBE9.8090003@stoneleaf.us> Message-ID: On Mon, Aug 30, 2010 at 7:10 AM, Ethan Furman wrote: > Good Day! > > I am stuck... hopefully a few fresh pairs of eyes will spot what I am > missing. > > I have a metaclass, Traits, and two different testing files, test_traits.py > and tests.py. ?test_traits works fine, tests generates the following error: > > C:\Python31\Lib\site-packages\traits\tests>\python31\python tests.py > Traceback (most recent call last): > ?File "tests.py", line 4, in > ? ?class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): > TypeError: type() takes 1 or 3 arguments > > > Working code from test_traits.py: > class DerivedClass(metaclass=Traits, traits=(TBundle1, TBundle2)): > ? ?def repeat(yo, text, count): > ? ? ? ?print('whatever...') > ? ?def whatsit(yo, arg1): > ? ? ? ?print("calling baseclass's whatsit...") > ? ? ? ?print(super().whatsit(arg1)) > > Failing code from tests.py: > class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): > ? ?def useless(yo): > ? ? ? ?print("this class won't compile") Shouldn't meta= instead be metaclass= ? Cheers, Chris -- http://blog.rebertia.com From contact at xavierho.com Mon Aug 30 10:20:01 2010 From: contact at xavierho.com (Xavier Ho) Date: Tue, 31 Aug 2010 00:20:01 +1000 Subject: meta-class troubles In-Reply-To: References: <4C7BBBE9.8090003@stoneleaf.us> Message-ID: Actually, scrape what I said. I think you need to have metaclass in the class statement, not just meta. -Xav On 31 August 2010 00:16, Xavier Ho wrote: > Ethan, are you trying to write the constructor in the class statement? > > Cheers, > Xav > > > On 31 August 2010 00:10, Ethan Furman wrote: > >> Good Day! >> >> I am stuck... hopefully a few fresh pairs of eyes will spot what I am >> missing. >> >> I have a metaclass, Traits, and two different testing files, >> test_traits.py and tests.py. test_traits works fine, tests generates the >> following error: >> >> C:\Python31\Lib\site-packages\traits\tests>\python31\python tests.py >> Traceback (most recent call last): >> File "tests.py", line 4, in >> class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): >> TypeError: type() takes 1 or 3 arguments >> >> >> Working code from test_traits.py: >> class DerivedClass(metaclass=Traits, traits=(TBundle1, TBundle2)): >> def repeat(yo, text, count): >> print('whatever...') >> def whatsit(yo, arg1): >> print("calling baseclass's whatsit...") >> print(super().whatsit(arg1)) >> >> Failing code from tests.py: >> class TraitConflict(meta=Traits, traits=(BoxPrint, BigBoxPrint)): >> def useless(yo): >> print("this class won't compile") >> >> >> Any clues or pointers *greatly* appreciated! >> >> ~Ethan~ >> -- >> Traits is homegrown, the idea based on Michele Simionato's Simple Traits >> experiment. It was intrigueing, and I wanted to see if I could implement >> something similar in Python 3. Any ideas now on what to do with it will >> also be greatly appreciated! :) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Mon Aug 30 10:24:26 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 30 Aug 2010 10:24:26 -0400 Subject: shlex, unicode, and subprocess.Popen on Windows In-Reply-To: <1283178224.12933.1392434421@webmail.messagingengine.com> References: <1283176444.5865.1392429397@webmail.messagingengine.com> <1283178224.12933.1392434421@webmail.messagingengine.com> Message-ID: <1283178266.13167.1392435533@webmail.messagingengine.com> Hi Chris, > It's a bug: http://bugs.python.org/issue1170 Thanks for pointing out the shlex bug. My concern was that shlex had Windows specific Unicode limitations because of the way the Windows shell so poorly supports unicode output. > Kudos for avoiding shell=True My understanding is that the only time one needs to use shell=True is when they are 'executing' a non-executable file whose executable must be discovered via file association rules? Does that sound accurate? Malcolm From jal at bethere.co.uk Mon Aug 30 10:29:59 2010 From: jal at bethere.co.uk (jal) Date: Mon, 30 Aug 2010 07:29:59 -0700 (PDT) Subject: python 2.6.6 installation problems on osx Message-ID: <15352d95-125c-41bb-8eca-7c5bc6b4bd94@k10g2000yqa.googlegroups.com> Hi All, I'm attempting a framework install of python 2.6.6 from source, on an intel mac running osx 10.6.4. At the end of the install the following errors occur. install: mkdir /usr/local/bin: Permission denied make[1]: *** [altinstallunixtools] Error 71 make: *** [frameworkaltinstallunixtools] Error 2 Does anyone one know of a fix? Kind regards, Jal From ritchy_gato at hotmail.com Mon Aug 30 10:51:34 2010 From: ritchy_gato at hotmail.com (Ritchy lelis) Date: Mon, 30 Aug 2010 07:51:34 -0700 (PDT) Subject: How to implement a pipeline...??? Please help References: <5242b005-31b6-4a9c-afd9-6fbb82e28db7@l14g2000yql.googlegroups.com> <08ce00ca-f58e-4ff4-a95e-54f7a4d5071f@w30g2000yqw.googlegroups.com> Message-ID: <4f39596e-2fa0-492f-9695-1397528e95a3@a36g2000yqc.googlegroups.com> On 26 Ago, 08:52, Dennis Lee Bieber wrote: > On Tue, 24 Aug 2010 22:21:34 -0700 (PDT), Ritchy lelis > declaimed the following in > gmane.comp.python.general: > > > hi friend Dennis Lee Bieber > > > I have watching your code sujestion and now i can understand more of > > what you have there.. > > ? ? ? ? Take warning -- I think I had a major flaw in the summation part of > the logic... It's probably easier just to use a list of lists (one list > per stage, and each list as long as the number of stages) and sum the > diagonal > > ? ? ? ? result = sum([list_of_lists[i][i] for i in range(number_of_stages)]) > > > i would like to show you them but i need to now if you still > > interested in the challenge it self and also in helping me with your > > extraordinary tips. > > > Can i count on your help? I hope so gratefully. > > ? ? ? ? My apologies... much more help and I'll have done the work for you > (though I'm still perplexed at simulating a hardware A/D converter when > the input is already a floating point digital, and the output is integer > digital) > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ My apologies... much more help and I'll have done the work for you Until now you were the only person who helped me so far... your help has served a lot. Already learned a lot with you so please do not stop helping me. To show you that you have not done it alone, i'll show you that i have made some arrangements. About the pipeline Class still have some errors and i'm working on it. Hope this link help. http://www.eetimes.com/design/automotive-design/4010021/SIGNAL-CHAIN-BASICS-Part-8--Flash-and-Pipeline-Converter-Operation-Explored though I'm still perplexed at simulating a hardware A/D converter when > the input is already a floating point digital, and the output is integer > digital I believe that de residuals that we're getting at the output, already are the wave forms that we should get if we had a Oscilloscope and analyzing the behavior of a A/D hardware and the digital parts is to quantify the analog input ie first we analyze and translate the analog input to a known residue and then quantifies to the digital output. I already initialized the "non linear" issues with the Class Calculate, and after this we will start to see how A/D converter really works. I would love you to help me at this one to Class Calculate: 1 - http://www.national.com/appinfo/adc/files/ABCs_of_ADCs.pdf 2 - http://www.atmel.com/dyn/resources/prod_documents/doc2559.pdf And now my new arrangements: # -*- coding: cp1252 -*- #######################################ADC##################################### ##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Incluir as Bibliotecas>>>>>>>>>>>>>>>>>>>>>>>> import matplotlib.pyplot as plt import numpy as np from numpy.random import * from numpy.fft import * from pylab import * ##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>CLASS ADC>>>>>>>>>>>>>>>>>>>>>>>>>>>> class ADC(object): def __init__(self, Inc, V_in, V_ref, Cs, Cf): ##Guarda o n?mero de est?gio e a tens?o de refer?ncia ## Stores the number of stage and reference voltage self.Inc = Inc self.V_ref = V_ref self.Cs = Cs self.Cf = Cs ##calcula os limiares da tens?o do comparador ##calculates the threshold voltage of the comparator self.V_H = self.V_ref * 0.25 self.V_L = -self.V_H self.V_in = V_in #define dois array de "Inc" elementos todos a uns e zeros respectivamente ##sets two array "Inc" elements all the ones and zeros respectively self.ones = np.ones(Inc, dtype=np.float) self.zeros = np.zeros(Inc, dtype=np.float) ##fun??o flash 1.5 bit ##1.5 bit flash function def flash1b5(self): # calcula as posi??es onde a tens?o de entrada excede o limiar alto ## calculates the positions where the input voltage exceeds the high threshold highBits = np.where(self.V_in > self.V_H, self.ones, self.zeros) # calcula as posi??es onde a tens?o de entrada ? menor que o limiar baixo ## calculates the positions where the input voltage is less than the low threshold lowBits = np.where(self.V_in < self.V_L, self.ones, self.zeros) # calcula as posi??es onde a tens?o de entrada ? maior que o limiar baixo e n?o excede o limiar alto ## calculates the positions where the input voltage is greater than the low threshold and does not exceed the high threshold midleBits = np.where(highBits + lowBits == 0, self.ones, self.zeros) # "digital" output pode ser obtido somando 1 e o highBits e subtraindo lowBits ## "Digital" output can be obtained by adding and subtracting 1 and highBits lowBits self.digital_out = 1 + highBits + -lowBits # calcular residuo ## Calculate residue self.residuals = (((1+self.Cs/self.Cf)* self.V_in) -((self.Cs/self.Cf) * self.V_ref)) * highBits + ((1+self.Cs/ self.Cf)* self.V_in )* midleBits + (((1+self.Cs/self.Cf)* self.V_in) + ((self.Cs/ self.Cf)* self.V_ref)) * lowBits # retorno da saida digital e do residuo ## return of the digital output and the residue out = [self.digital_out, self.residuals] return out ##fun??o flash 2 bit ## 2 bit flash function def flash2b(self): # calcula as posi??es onde a tens?o de entrada excede o limiar alto ## calculates the positions where the input voltage exceeds the high threshold # (2X the threshold of the 1.5B stages) highBits1 = np.where(self.V_in > 2*self.V_H, [3], self.zeros) # calcula as posi??es onde a tens?o de entrada est? entre zero e o limiar alto ## calculates the positions where the input voltage is between zero and the high threshold if any(self.V_in <= 2*self.V_H) and any(self.V_in > 0.0): highBits2 = np.where((self.V_in <= 2*self.V_H) & (self.V_in > 0.0), [2], self.zeros) # calcula as posi??es onde a tens?o de entrada est? entre zero e o limiar baixo ## calculates the positions where the input voltage is between zero and low threshold if any(self.V_in <= 0.0) and any(self.V_in > 2*self.V_L): lowBits1 = np.where((self.V_in <= 0.0) & (self.V_in > 2*self.V_L), self.ones,self.zeros) # calcula as posi??es onde a tens?o de entrada ? menor que o limiar baixo ## calculates the positions where the input voltage is less than the low threshold lowBits2 = np.where(self.V_in <= 2*self.V_L, self.zeros, self.zeros) # "digital" output pode ser obtido somando todas as posi?oes desta forma. ## "Digital" output can be obtained by adding all the positions in this way self.digital_out = lowBits2 + lowBits1 + highBits2+ highBits1 # retorno da saida digital ## Digital output return out = [self.digital_out] return out ##fun??o flash 2.5 bit ## 2.5 bit flash function def flash2b5(self): ## calculates the positions where the input voltage exceeds the high threshold highBits1 = np.where(self.V_in > (self.V_H*5/2), self.ones, self.zeros) ## calculates the positions where the input voltage is between zero and the high threshold if any(self.V_in <= (self.V_H*5/2)) and any(self.V_in >=(self.V_H*3/2)): highBits2 = np.where((self.V_in <= (self.V_H*5/2)) & (self.V_in >=(self.V_H*3/2)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*3/2)) and any(self.V_in >=(self.V_H*1/2)): highBits3 = np.where((self.V_in <= (self.V_H*3/2)) & (self.V_in >=(self.V_H*1/2)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*1/2)) and any(self.V_in >=(self.V_L*1/2)): midleBits = np.where((self.V_in <= (self.V_H*1/2)) & (self.V_in >=(self.V_L*1/2)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*1/2)) and any(self.V_in >=(self.V_L*3/2)): lowBits1 = np.where((self.V_in <= (self.V_L*1/2)) & (self.V_in >=(self.V_L*3/2)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*3/2)) and any(self.V_in >=(self.V_L*5/2)): lowBits2 = np.where((self.V_in <= (self.V_L*3/2)) & (self.V_in >=(self.V_L*5/2)), self.ones, self.zeros) ## calculates the positions where the input voltage is less than the low threshold lowBits3 = np.where(self.V_in < (self.V_L*5/2), self.ones, self.zeros) ## Calculate residue 2.5 Bit self.residuals = ((4*self.V_in - 3*self.V_ref)*highBits1 + (4*self.V_in - 2*self.V_ref) * highBits2 + (4*self.V_in - self.V_ref) * highBits3 + (4 * self.V_in) * midleBits + (4*self.V_in + self.V_ref) * lowBits1 + (4*self.V_in + 2*self.V_ref) * lowBits2 + (4*self.V_in + 3*self.V_ref) * lowBits3) ## Residue output return out = [self.residuals] return out ## ## ##fun??o flash 3 Bit ## 3 Bit flash function def flash3b(self): ## calculates the positions where the input voltage exceeds the high threshold highBits1 = np.where(self.V_in > (self.V_H*3), [7], self.zeros) ## calculates the positions where the input voltage is between zero and the high threshold if any(self.V_in <= (self.V_H*3)) and any(self.V_in >=self.V_H*2): highBits2 = np.where((self.V_in <= (self.V_H*3)) & (self.V_in >=(self.V_H*2)), [6], self.zeros) if any(self.V_in <= (self.V_H*2)) and any(self.V_in >=(self.V_H)): highBits3 = np.where((self.V_in <= (self.V_H*2)) & (self.V_in >=(self.V_H)), [5], self.zeros) if any(self.V_in <= (self.V_H)) and any(self.V_in >=0.0): highBits4 = np.where((self.V_in <= (self.V_H)) & (self.V_in >=0.0), [4], self.zeros) if any(self.V_in <= 0.0) and any(self.V_in >= (self.V_L)): lowBits1 = np.where((self.V_in <= 0.0) & (self.V_in >= (self.V_L)), [3], self.zeros) if any(self.V_in <= (self.V_L)) and any(self.V_in >=(self.V_L*2)): lowBits2 = np.where((self.V_in <= (self.V_L)) & (self.V_in >=(self.V_L*2)), [2], self.zeros) if any(self.V_in <= (self.V_L*2)) and any(self.V_in >=(self.V_L*3)): lowBits3 = np.where((self.V_in <= (self.V_L*2)) & (self.V_in >=(self.V_L*3)), [1], self.zeros) ## calculates the positions where the input voltage is less than the low threshold lowBits4 = np.where(self.V_in < (self.V_L*3), self.zeros, self.zeros) ## "Digital" output can be obtained by adding all the positions in this way self.digital_out = lowBits4 + lowBits3 + lowBits2 + lowBits1 + highBits4 + highBits3 + highBits2 +highBits1 # retorno da saida digital ## Digital output return out = [self.digital_out] return out ## ## ##fun??o flash 3.5 bit ## 3.5 Bit flash function def flash3b5(self): ## calculates the positions where the input voltage exceeds the high threshold highBits1 = np.where(self.V_in > (self.V_H*13/4), self.ones, self.zeros) ## calculates the positions where the input voltage is between zero and the high threshold if any(self.V_in <= (self.V_H*13/4)) and any(self.V_in >=(self.V_H*11/4)): highBits2 = np.where((self.V_in <= (self.V_H*13/4)) & (self.V_in >=(self.V_H*11/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*11/4)) and any(self.V_in >=(self.V_H*9/4)): highBits3 = np.where((self.V_in <= (self.V_H*11/4)) & (self.V_in >=(self.V_H*9/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*9/4)) and any(self.V_in >=(self.V_H*7/4)): highBits4 = np.where((self.V_in <= (self.V_H*9/4)) & (self.V_in >=(self.V_H*7/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*7/4)) and any(self.V_in >=(self.V_H*5/4)): highBits5 = np.where((self.V_in <= (self.V_H*7/4)) & (self.V_in >=(self.V_H*5/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*5/4)) and any(self.V_in >=(self.V_H*3/4)): highBits6 = np.where((self.V_in <= (self.V_H*5/4)) & (self.V_in >=(self.V_H*3/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*3/4)) and any(self.V_in >=(self.V_H*1/4)): highBits7 = np.where((self.V_in <= (self.V_H*3/4)) & (self.V_in >=(self.V_H*1/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_H*1/4)) and any(self.V_in >=(self.V_L*1/4)): midleBits = np.where((self.V_in <= (self.V_H*1/4)) & (self.V_in >=(self.V_L*1/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*1/4)) and any(self.V_in >=(self.V_L*3/4)): lowBits1 = np.where((self.V_in <= (self.V_L*1/4)) & (self.V_in >=(self.V_L*3/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*3/4)) and any(self.V_in >=(self.V_L*5/4)): lowBits2 = np.where((self.V_in <= (self.V_L*3/4)) & (self.V_in >=(self.V_L*5/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*5/4)) and any(self.V_in >=(self.V_L*7/4)): lowBits3 = np.where((self.V_in <= (self.V_L*5/4)) & (self.V_in >=(self.V_L*7/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*7/4)) and any(self.V_in >=(self.V_L*9/4)): lowBits4 = np.where((self.V_in <= (self.V_L*7/4)) & (self.V_in >=(self.V_L*9/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*9/4)) and any(self.V_in >=(self.V_L*11/4)): lowBits5 = np.where((self.V_in <= (self.V_L*9/4)) & (self.V_in >=(self.V_L*11/4)), self.ones, self.zeros) if any(self.V_in <= (self.V_L*11/4)) and any(self.V_in >=(self.V_L*13/4)): lowBits6 = np.where((self.V_in <= (self.V_L*11/4)) & (self.V_in >=(self.V_L*13/4)), self.ones, self.zeros) ## calculates the positions where the input voltage is less than the low threshold lowBits7 = np.where(self.V_in < (self.V_L*13/4), self.ones, self.zeros) ## Calculate residue 3.5 Bit self.residuals = ((8*self.V_in - 7*self.V_ref) *highBits1 + (8*self.V_in - 6*self.V_ref)* highBits2 + (8*self.V_in - 5*self.V_ref)*highBits3 + (8*self.V_in - 4*self.V_ref) * highBits4 + (8*self.V_in - 3*self.V_ref) * highBits5 + (8*self.V_in - 2*self.V_ref) * highBits6 + (8*self.V_in - self.V_ref) * highBits7 + (8 * self.V_in) * midleBits + (8*self.V_in + self.V_ref) * lowBits1 + (8*self.V_in + 2*self.V_ref) * lowBits2 + (8*self.V_in + 3*self.V_ref) * lowBits3 + (8*self.V_in + 4*self.V_ref) * lowBits4 + (8*self.V_in + 5*self.V_ref) * lowBits5 + (8*self.V_in + 6*self.V_ref) * lowBits6 + (8*self.V_in + 7*self.V_ref) * lowBits7 ) ## Residue output return out = [self.residuals] return out ## ## ## ##fun??o Pipeline ## def pipeline(self): ##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>CLASS CALCULATE>>>>>>>>>>>>>>>>>>>>>>>>>>>> ##class calculate(ADC): ## ## def __init__ (self): ## ## ## def AC_Errors(self): ## ## ## def Offset_Errors(self): ## ## ## def plot_fft(self): ## ## ## def DNL_INL(self): ##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>SIMULA??O>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ## if __name__=='__main__': V_in = np.linspace(-1, 1, 10000) F1B5 = ADC(10000, V_in, 1, 2, 2).flash1b5() F2B = ADC(10000, V_in, 1, 2, 2).flash2b() F2B5 = ADC(10000, V_in, 1, 2, 2).flash2b5() F3B5 = ADC(10000, V_in, 1, 2, 2).flash3b5() F3B = ADC(10000, V_in, 1, 2, 2).flash3b() fig1 = figure(1,figsize=(8,5)) ax1 = fig1.add_subplot(111, autoscale_on=True) ax1.plot(V_in, F1B5[1], lw = 1, color='b') grid(True); xlabel('IN'); ylabel('OUT'); title('RESIDUALS 1B5') fig2 = figure(2,figsize=(8,5)) ax2 = fig2.add_subplot(111, autoscale_on=False,xlim=(-1,1), ylim=(-1,3)) ax2.plot(V_in, F1B5[0], lw=1, color='r') grid(True); xlabel('IN'); ylabel('OUT'); title('DIGITAL OUT 1B5') fig3 = figure(3,figsize=(8,5)) ax3 = fig3.add_subplot(111, autoscale_on=False,xlim=(-1,1), ylim=(-1,4)) ax3.plot(V_in, F2B[0], lw=1, color='g') grid(True); xlabel('IN'); ylabel('OUT'); title('DIGITAL OUT 2B') fig4 = figure(4,figsize=(8,5)) ax4 = fig4.add_subplot(111, autoscale_on=True) ax4.plot(V_in, F2B5[0], lw=1, color='y') grid(True); xlabel('IN'); ylabel('OUT'); title('RESIDUALS 2B5') fig5 = figure(5,figsize=(8,5)) ax5 = fig5.add_subplot(111, autoscale_on=False,xlim=(-1,1), ylim=(-1,8)) ax5.plot(V_in, F3B[0], lw=1, color='brown') grid(True); xlabel('IN'); ylabel('OUT'); title('DIGITAL OUT 3B') fig6 = figure(6,figsize=(8,5)) ax6 = fig6.add_subplot(111, autoscale_on=False, xlim=(-1,1), ylim=(-1,1)) ax6.plot(V_in, F3B5[0], lw=1, color='purple') grid(True); xlabel('IN'); ylabel('OUT'); title('RESIDUALS 3B5') plt.show() Ps: How can i put my messages just for you to read it like you always do? From wyj1046 at gmail.com Mon Aug 30 10:57:57 2010 From: wyj1046 at gmail.com (villorent) Date: Mon, 30 Aug 2010 07:57:57 -0700 (PDT) Subject: PyGeo References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> Message-ID: <6ffec87d-e86e-4143-8bef-055a606da929@x20g2000pro.googlegroups.com> Maybe you could try this: http://hyry.dip.jp/files/pygeo.7z I found it on this page: http://hyry.dip.jp/blogt.py?file=0432.blog From cliff.martin at gmail.com Mon Aug 30 11:06:39 2010 From: cliff.martin at gmail.com (Cliff Martin) Date: Mon, 30 Aug 2010 11:06:39 -0400 Subject: Trouble importing cx_Oracle on HPUX Message-ID: including libttsh11 fixed the problem. Thank you! Now I can get on with fixing everything that Python 3 broke... err changed. :) -- Cliff On Sat, Aug 28, 2010 at 11:20 AM, Alexander Gattin wrote: > Hello, > > On Sat, Aug 28, 2010 at 09:27:05AM -0400, Cliff > Martin wrote: > > Yes, our entire toolchain is 64 bit - a mix of > > stuff I have downloaded and built and some > > packages from HP (in the form of depot files) > > GCC was downloaded from HP, for example. > > I see. I bootstrapped from bundled cc, hence all > the problems. > > > Python -d did not generate any additional > > information, and so was not helpful (should this > > work?). > > Oops I was wrong about the python -d -- > correct option is -v of course... > > > Python -v did, however, and it came up with a > > number of unresolved symbols all seeming to be > > from libnnz11.so. I tried linking against all of > > the *.so files in ORACLE_HOME/lib, but I don't > > remember trying libttsh11 specifically. I will > > try it again on Monday. > > You're using Oracle 11 vs our v10 (we also have > v8, v9 and v11 in production, but not on this > HP-UX server), but I think the problem with the > libnnz is the same: Oracle doesn't put correct > shared library dependencies into the libnnzXX.so > dynamic section header (it should list > libttshXX.so as NEEDED but apperently doesn't). > > Probably their distribution for Solaris is better, > I didn't check (I'll ask our DBAs on Monday). > > -- > With best regards, > xrgtn > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Mon Aug 30 11:32:15 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 30 Aug 2010 11:32:15 -0400 Subject: python 2.6.6 installation problems on osx In-Reply-To: <15352d95-125c-41bb-8eca-7c5bc6b4bd94@k10g2000yqa.googlegroups.com> References: <15352d95-125c-41bb-8eca-7c5bc6b4bd94@k10g2000yqa.googlegroups.com> Message-ID: On Mon, Aug 30, 2010 at 10:29 AM, jal wrote: > Hi All, > > I'm attempting a framework install of python 2.6.6 from source, on an > intel mac running osx 10.6.4. > > At the end of the install the following errors occur. > > install: mkdir /usr/local/bin: Permission denied > make[1]: *** [altinstallunixtools] Error 71 > make: *** [frameworkaltinstallunixtools] Error 2 > > Does anyone one know of a fix? > did you sudo make install or just make install? From ethan at stoneleaf.us Mon Aug 30 11:39:02 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 30 Aug 2010 08:39:02 -0700 Subject: meta-class troubles In-Reply-To: References: <4C7BBBE9.8090003@stoneleaf.us> Message-ID: <4C7BD096.5090905@stoneleaf.us> Chris Rebert wrote: > Shouldn't meta= instead be metaclass= ? Xavier Ho wrote: > I think you need to have metaclass in the class statement, not just meta. Argh. Thank you both. I'm glad it was simple! ~Ethan~ From thomas at jollybox.de Mon Aug 30 11:53:24 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Mon, 30 Aug 2010 17:53:24 +0200 Subject: Optimising literals away In-Reply-To: References: Message-ID: <201008301753.25177.thomas@jollybox.de> On Monday 30 August 2010, it occurred to Tobias Weber to exclaim: > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. > > def m(arg): > if arg & set([1,2,3]): > return 4 > > Is the set created every time the method is called? What about a > frozenset? Or tuple vs list? After how many calls per second does it pay > to save it at the module level? Would anybody else find this ugly? That creates a list, and then calls "set" with the list as an argument. Every time, because that's what the code says: call "set" with a new list containing 1, 2, and 3. If you use a tuple instead of the list, the tuple can be loaded as a whole -- as tuples are immutable, it doesn't have to be re-created every time, it can be the same object. If you use a set literal instead of calling "set", the set is constructed directly, like a list would be. Details: >>> def m_l(arg): ... if arg & set([1,2,3]): ... return 4 ... >>> def m_t(arg): ... if arg & set((1,2,3)): ... return 4 ... >>> def m_s(arg): ... if arg & {1, 2, 3}: ... return 4 ... >>> from dis import dis >>> dis(m_l) 2 0 LOAD_FAST 0 (arg) 3 LOAD_GLOBAL 0 (set) 6 LOAD_CONST 1 (1) 9 LOAD_CONST 2 (2) 12 LOAD_CONST 3 (3) 15 BUILD_LIST 3 18 CALL_FUNCTION 1 21 BINARY_AND 22 POP_JUMP_IF_FALSE 29 3 25 LOAD_CONST 4 (4) 28 RETURN_VALUE >> 29 LOAD_CONST 0 (None) 32 RETURN_VALUE >>> dis(m_t) 2 0 LOAD_FAST 0 (arg) 3 LOAD_GLOBAL 0 (set) 6 LOAD_CONST 5 ((1, 2, 3)) 9 CALL_FUNCTION 1 12 BINARY_AND 13 POP_JUMP_IF_FALSE 20 3 16 LOAD_CONST 4 (4) 19 RETURN_VALUE >> 20 LOAD_CONST 0 (None) 23 RETURN_VALUE >>> dis(m_s) 2 0 LOAD_FAST 0 (arg) 3 LOAD_CONST 1 (1) 6 LOAD_CONST 2 (2) 9 LOAD_CONST 3 (3) 12 BUILD_SET 3 15 BINARY_AND 16 POP_JUMP_IF_FALSE 23 3 19 LOAD_CONST 4 (4) 22 RETURN_VALUE >> 23 LOAD_CONST 0 (None) 26 RETURN_VALUE >>> From benjamin at python.org Mon Aug 30 12:00:13 2010 From: benjamin at python.org (Benjamin Peterson) Date: Mon, 30 Aug 2010 16:00:13 +0000 (UTC) Subject: Optimising literals away References: Message-ID: Tobias Weber gmx.net> writes: > > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. > > def m(arg): > if arg & set([1,2,3]): > return 4 > > Is the set created every time the method is called? Yes, and the list. > What about a > frozenset? Yep. > Or tuple vs list? Tuples containing other immutable literals can be optimized. (In cpython anyway.) > After how many calls per second does it pay > to save it at the module level? Ask the profiler. Probably not many. > Would anybody else find this ugly? I do it all the time. From arnodel at googlemail.com Mon Aug 30 12:02:37 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 30 Aug 2010 17:02:37 +0100 Subject: Optimising literals away References: Message-ID: Tobias Weber writes: > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. > > def m(arg): > if arg & set([1,2,3]): > return 4 > > Is the set created every time the method is called? What about a > frozenset? Or tuple vs list? After how many calls per second does it pay > to save it at the module level? Would anybody else find this ugly? > > Also I never profiled the regular expression cache... the dis module can help you for these: >>> import dis >>> def m(arg): ... if arg & set([1,2,3]): ... return 4 ... >>> dis.dis(m) 2 0 LOAD_FAST 0 (arg) 3 LOAD_GLOBAL 0 (set) 6 LOAD_CONST 1 (1) 9 LOAD_CONST 2 (2) 12 LOAD_CONST 3 (3) 15 BUILD_LIST 3 18 CALL_FUNCTION 1 21 BINARY_AND 22 JUMP_IF_FALSE 5 (to 30) 25 POP_TOP 3 26 LOAD_CONST 4 (4) 29 RETURN_VALUE >> 30 POP_TOP 31 LOAD_CONST 0 (None) 34 RETURN_VALUE As you can see, the list literal is built every time the function code is executed. -- Arnaud From nikos.the.gr33k at gmail.com Mon Aug 30 12:09:48 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 09:09:48 -0700 (PDT) Subject: String substitution VS proper mysql escaping References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> Message-ID: <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> On 30 ???, 11:11, Gregory Ewing wrote: > Nik the Greek wrote: > > Yes i will i just asked to know if i were to substitute what might be > > the problem so to understand why i need the quoting. > > Because if you use % to build a query string, the result must > be syntactically valid SQL. The values that you substitute > into the placeholders must end up looking like SQL literals. > That means string values need to be in quotes, and probably > dates as well, although numbers don't. > > When you use the execute method's own parameter substitution > mechanism, things are different. It's not a textual replacement, > and you don't put quotes around the placeholders. There's no > particular reason for that, it's just the way it's defined > to work. > > -- > Greg cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' , a_tuple ) and cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' , (a_tuple) ) are both syntactically correct right? buw what about cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date = %s and host = %s ''' , (a_tuple,) ) From __peter__ at web.de Mon Aug 30 12:21:09 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Aug 2010 18:21:09 +0200 Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <6676c33f-0012-4051-bc75-b35af37df367@z28g2000yqh.googlegroups.com> Message-ID: Nik the Greek wrote: >> Perhpas its doenst get loaded like that? >> >> # initialize cookie >> cookie = SimpleCookie() >> cookie.load( os.environ.get('HTTP_COOKIE', '') ) >> mycookie = cookie.get('visitor') > > Please someone else has an idea on how this to work? Add a print statement to verify that HTTP_COOKIE does indeed have a visitor. Or use the stuff below as a template. Here is a minimal script to set the visitor: #!/usr/bin/env python import cgitb cgitb.enable() import cgi import Cookie import os import sys form = cgi.FieldStorage() name = form.getfirst("name", "Unknown") cookie = Cookie.SimpleCookie() cookie["visitor"] = name sys.stdout.write(cookie.output()) sys.stdout.write("\r\nContent-type: text/plain\r\n\r\n") print "Hello, your new name is", name Invoke it with the equivalent of http://localhost:8000/cgi-bin/set_visitor.py?name=Nikos for your website. Then proceed with a small script to show the visitor's name: #!/usr/bin/env python import cgitb cgitb.enable() import cgi import Cookie import os import sys cookie = Cookie.SimpleCookie() cookie.load(os.environ.get("HTTP_COOKIE")) visitor = cookie.get("visitor") if visitor is None: visitor_name = "Unknown" else: visitor_name = visitor.value sys.stdout.write("Content-type: text/plain\r\n\r\n") print "Hello,", visitor_name print print print "HTTP_COOKIE=%r" % os.environ.get("HTTP_COOKIE") which you can invoke with the equivalent of http://localhost:8000/cgi-bin/show_visitor.py With some luck you should see your name and can proceed to adapt your script accordingly. Peter From bthate at gmail.com Mon Aug 30 12:21:50 2010 From: bthate at gmail.com (Bart Thate) Date: Mon, 30 Aug 2010 09:21:50 -0700 (PDT) Subject: JSONBOT 0.3 RELEASE Message-ID: <53e76eb1-a5cf-4588-805e-d1cdf4a47ba3@t2g2000yqe.googlegroups.com> Hello world ! I just released version 0.3 of JSONBOT. JSONBOT is a remote event driven framework for building bots that talk JSON to each other over XMPP. This distribution provides bots built on this framework for console, IRC, XMPP for the shell and WWW and XMPP for the Google Application engine. JSONBOT 0.3 provides the following programs: jsb - console version of jsonbot jsb-import - import data from another bot jsb-installplug - install remote plugins jsb-irc - IRC version of jsonbot (socket) jsb-xmpp - XMPP version of jsonbot (socket) jsb-fleet - mix IRC and XMPP bots jsb-release - create a new release directory jsb-rollback - rollback a release jsb-run - run a release in the GAE dev_appserver jsb-stop - stop a running bot jsb-upload - upload a release to the GAE A plugin infrastructure is in place to program the functionality that is needed. JSONBOT 0.3 plugins: 8b - eight ball admin - administator related commands alias - keep aliases (per user) ask - plugin for asking "experts" a question choice - choice out of a list .. used in pipelines controlchar - set the control character of a channel forward - forward events of a channel to another bot clone - clone waves into new ones core - core bot commands count - count the numbers in a result .. used in pipelines data - provide data dumps of channels, bots, events fleet - support multiple bots in a running instance (list of bots) gae - provide GAE commands like flush cache or cache stats gadget - wave gadget support gcalc - use google to calculate grep - grep the result .. used in pipelines hubbub - pubsubhubbub plugin providing subscribe functionality ipcalc - ipcalculator irc - IRC related commands jsondata - enable/disable sharing of files through the jsonserver (not enabled right now) kickban - channel control commands for IRC misc - other commands more - do a more on buffered output nickcapture - retake nick (IRC) nickserv - nickserver support (IRC) not - negated grep .. used in pipelines outputcache - show outputcache data rss - provide RSS and Atom pollers relay - relay to other waves/xmpp restserver - provide REST functionality to the bot reload - reloading of plugins reverse - rever see the result .. also used in pipelines seen - keep track of users shop - keep shopping lists sort - sort the result .. used in pipelines tail - tail the result .. used in pipelines test - test commands tinyurl - get a tinyurl todo - keep a todo list underauth - undernet auth support (IRC) uniq - make the result unique .. used in pipelines user - user management userstate - userstate management watcher - watch channels that get forwarded to the bot. wave - wave related commands weather - show weather in a city welcome - welcome messages shown in the gadget wikipedia - query wikipedia xmpp - xmpp related functions account Project home is at http://jsonbot.googlecode.com Have fun with it! From alex.kapps at web.de Mon Aug 30 12:34:04 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Mon, 30 Aug 2010 18:34:04 +0200 Subject: String substitution VS proper mysql escaping In-Reply-To: <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> Message-ID: <4C7BDD7C.6010501@web.de> Nik the Greek wrote: > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , a_tuple ) > > and > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , (a_tuple) ) > > are both syntactically correct right? > > buw what about > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , (a_tuple,) ) Python has a wonderful interactive mode which is perfect for trying this out: >>> a_tuple = 1,2,3 >>> a_tuple (1, 2, 3) >>> (a_tuple) (1, 2, 3) >>> (a_tuple,) ((1, 2, 3),) >>> First note, that tuples are not created with parentheses, but with the comma. So, the first two are the same. The parens are only needed to remove ambiguity in certain situations, but are meaningless here. The third case is a tuple containing a_tuple as its only element. From python at mrabarnett.plus.com Mon Aug 30 12:41:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 17:41:52 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: <4C7BDF50.9030804@mrabarnett.plus.com> On 30/08/2010 04:33, Nik the Greek wrote: > On 30 ???, 06:12, MRAB wrote: > >> This part: >> >> ( not mycookie or mycookie.value != 'nikos' ) >> >> is false but this part: >> >> re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None >> >> is true because host doesn't contain any of those substrings. > > So, the if code does executed because one of the condition is true? > > How should i write it? > > I cannot think clearly on this at all. > > I just wan to tell it to get executed ONLY IF > > the cookie values is not 'nikos' > > or ( don't knwo if i have to use and or 'or' here) > > host does not contain any of the substrings. > > What am i doign wrong?! > It might be clearer if you reverse the condition and say: me_visiting = ... if not me_visiting: ... From python at mrabarnett.plus.com Mon Aug 30 12:43:34 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 17:43:34 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> Message-ID: <4C7BDFB6.1040404@mrabarnett.plus.com> On 30/08/2010 17:09, Nik the Greek wrote: > On 30 ???, 11:11, Gregory Ewing wrote: >> Nik the Greek wrote: >>> Yes i will i just asked to know if i were to substitute what might be >>> the problem so to understand why i need the quoting. >> >> Because if you use % to build a query string, the result must >> be syntactically valid SQL. The values that you substitute >> into the placeholders must end up looking like SQL literals. >> That means string values need to be in quotes, and probably >> dates as well, although numbers don't. >> >> When you use the execute method's own parameter substitution >> mechanism, things are different. It's not a textual replacement, >> and you don't put quotes around the placeholders. There's no >> particular reason for that, it's just the way it's defined >> to work. >> >> -- >> Greg > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , a_tuple ) > > and > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , (a_tuple) ) > > are both syntactically correct right? > > buw what about > > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and > date = %s and host = %s ''' , (a_tuple,) ) That's syntactically correct, but not the same thing. From python at mrabarnett.plus.com Mon Aug 30 12:52:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 17:52:18 +0100 Subject: String substitution VS proper mysql escaping In-Reply-To: <4C7BDD7C.6010501@web.de> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> <272ffc97-66a1-45e4-af9b-c426331db555@m1g2000yqo.googlegroups.com> <4C7BDD7C.6010501@web.de> Message-ID: <4C7BE1C2.2050107@mrabarnett.plus.com> On 30/08/2010 17:34, Alexander Kapps wrote: > Nik the Greek wrote: > >> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s ''' , a_tuple ) >> >> and >> >> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s ''' , (a_tuple) ) >> >> are both syntactically correct right? >> >> buw what about >> >> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and >> date = %s and host = %s ''' , (a_tuple,) ) > > Python has a wonderful interactive mode which is perfect for trying this > out: > > >>> a_tuple = 1,2,3 > >>> a_tuple > (1, 2, 3) > >>> (a_tuple) > (1, 2, 3) > >>> (a_tuple,) > ((1, 2, 3),) > >>> > > > First note, that tuples are not created with parentheses, but with the > comma. So, the first two are the same. The parens are only needed to > remove ambiguity in certain situations, but are meaningless here. > There's only one exception: the empty tuple (). > The third case is a tuple containing a_tuple as its only element. From chris at simplistix.co.uk Mon Aug 30 12:55:53 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 30 Aug 2010 17:55:53 +0100 Subject: bug? pkgutil.walk_packages returns packages that result in an ImportError In-Reply-To: References: Message-ID: <4C7BE299.8080201@simplistix.co.uk> Peter Otten wrote: >> My expectation of this is that if onerrors is left as None, names >> yielded will be importable. > > I would infer no such promise, especially as the generator also yields > modules, and no attempt at all is made to import those. Really? I thought the __import__ fired over everything? > I've never worked with that function; I'd like to hear more about your > usecase. It's becoming a common use case for packages like martian [1] and venutian [2] that need to scan whole packages for things. In my case, I'm scanning for declaratively mapped SQLAlchemy models. It would be great if this function became part of the public API and got some more definition on what it will and won't do. When should I take this to Python-Dev? cheers, Chris [1] http://pypi.python.org/pypi/martian [2] http://pypi.python.org/pypi/venusian -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From denisg640 at gmail.com Mon Aug 30 13:07:34 2010 From: denisg640 at gmail.com (Denis Gomes) Date: Mon, 30 Aug 2010 13:07:34 -0400 Subject: python+sqlite3 in memory database Message-ID: Hi Everyone, I am using sqlite3 with python2.5 and the pysqlite wrapper. I am trying to copy tables from one database (in memory) to another database (file) using ATTACH. I looked on the internet and found a couple of sites that show how to do this but the table schema is not copied. def SaveToFile(self,filename): # Attach external db file - give it handle filename # Attaching automatically creates a database by default self.__curs.execute("ATTACH %s AS %s" % (filename,filename)) table_names=self.__curs.execute("SELECT name FROM main.sqlite_master WHERE type='table'").fetchall() for table_name, in table_names: #copy in mem db to persistent db self.__curs.execute("CREATE TABLE %s.%s AS SELECT * FROM main.%s" % (filename,table_name,table_name)) self.__curs.execute("DETACH %s" % filename) # Detach external db""" Is there a way to copy the schema from the sqlite_master table. I know we can used iter.dump from within python to dump to text based SQL but I would prefer not to do this. Eventually my goal is to dynamically load and unload sections of a file based database (could be tables or rows) in and out of memory for effeciency purposes. Any help is appreciated. Thanks in advance. Denis -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikos.the.gr33k at gmail.com Mon Aug 30 13:16:42 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 10:16:42 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: On 30 ???, 19:41, MRAB wrote: > On 30/08/2010 04:33, Nik the Greek wrote: > > > > > > > > > On 30 ???, 06:12, MRAB ?wrote: > > >> This part: > > >> ? ? ? ( not mycookie or mycookie.value != 'nikos' ) > > >> is false but this part: > > >> ? ? ? re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > >> is true because host doesn't contain any of those substrings. > > > So, the if code does executed because one of the condition is true? > > > How should i write it? > > > I cannot think clearly on this at all. > > > I just wan to tell it to get executed ?ONLY IF > > > the cookie values is not 'nikos' > > > or ( don't knwo if i have to use and or 'or' here) > > > host does not contain any of the substrings. > > > What am i doign wrong?! > > It might be clearer if you reverse the condition and say: > > ? ? ?me_visiting = ... > ? ? ?if not me_visiting: > ? ? ? ? ?... I don't understand what are you trying to say Please provide a full example. You mean i should try it like this? unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn| yandex|13448|spider|crawl)', host ) not None: But isnt it the same thing like the if? From nikos.the.gr33k at gmail.com Mon Aug 30 13:17:25 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 10:17:25 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <6676c33f-0012-4051-bc75-b35af37df367@z28g2000yqh.googlegroups.com> Message-ID: <04e256a3-3bc3-44ef-a754-da913261f3f7@i15g2000yqe.googlegroups.com> On 30 ???, 19:21, Peter Otten <__pete... at web.de> wrote: > Nik the Greek wrote: > >> Perhpas its doenst get loaded like that? > > >> # initialize cookie > >> cookie = SimpleCookie() > >> cookie.load( os.environ.get('HTTP_COOKIE', '') ) > >> mycookie = cookie.get('visitor') > > > Please someone else has an idea on how this to work? > > Add a print statement to verify that HTTP_COOKIE does indeed have a visitor. > Or use the stuff below as a template. > > Here is a minimal script to set the visitor: > > #!/usr/bin/env python > import cgitb > cgitb.enable() > > import cgi > import Cookie > import os > import sys > > form = cgi.FieldStorage() > name = form.getfirst("name", "Unknown") > > cookie = Cookie.SimpleCookie() > cookie["visitor"] = name > > sys.stdout.write(cookie.output()) > sys.stdout.write("\r\nContent-type: text/plain\r\n\r\n") > print "Hello, your new name is", name > > Invoke it with the equivalent of > > http://localhost:8000/cgi-bin/set_visitor.py?name=Nikos > > for your website. Then proceed with a small script to show the visitor's > name: > > #!/usr/bin/env python > import cgitb > cgitb.enable() > > import cgi > import Cookie > import os > import sys > > cookie = Cookie.SimpleCookie() > cookie.load(os.environ.get("HTTP_COOKIE")) > > visitor = cookie.get("visitor") > if visitor is None: > ? ? visitor_name = "Unknown" > else: > ? ? visitor_name = visitor.value > > sys.stdout.write("Content-type: text/plain\r\n\r\n") > print "Hello,", visitor_name > print > print > print "HTTP_COOKIE=%r" % os.environ.get("HTTP_COOKIE") > > which you can invoke with the equivalent of > > http://localhost:8000/cgi-bin/show_visitor.py > > With some luck you should see your name and can proceed to adapt your script > accordingly. > > Peter The cookie is set tyo the browser with the code i provided few posts back The problem is that i for soemreason cant check correctly its existance. From kevinlcarlson at gmail.com Mon Aug 30 13:24:49 2010 From: kevinlcarlson at gmail.com (kevinlcarlson) Date: Mon, 30 Aug 2010 10:24:49 -0700 (PDT) Subject: Helper app for intranet site References: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> Message-ID: <61894f54-90ff-4e0e-9c81-860b6e9cdc15@p12g2000prn.googlegroups.com> On Aug 29, 8:46?pm, Lawrence D'Oliveiro wrote: > In message > <45e0772c-24a8-4cbb-a4fc-74a1b6c25... at n19g2000prf.googlegroups.com>, > > kevinlcarlson wrote: > > I'm exploring the possibility of developing a helper app for an > > existing internal company website. ?Basically, it would automatically > > scan the current page contents, including prepopulated forms, and > > provide context-related business rule comments to the user, via a stay- > > on-top wxPython panel. > > Seems like a roundabout way of doing it. Can?t you integrate into the server > code which is generating the page contents, instead of trying to reverse- > engineer those contents? Absolutely - that would be the best way to accomplish this. Unfortunately, our group has no access to the web server and the developers have this functionality scheduled about a year into the future, but we need it ASAP. Also, our group would like to be in control of the code and business rule contents, rather than wait for updates from the busy web team... So far, it looks like PAMIE could be a good choice for the page scraping code - it includes WinGuiAuto.py which could be used to identify the correct window handle and parse the contents. Business rule data could be stored locally in Sqlite, since it changes rarely and there is a small user base... Does this seem like the right track? Thanks, Kevin From nikos.the.gr33k at gmail.com Mon Aug 30 13:36:01 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 10:36:01 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> On 30 ???, 19:41, MRAB wrote: > On 30/08/2010 04:33, Nik the Greek wrote: > > > > > > > > > On 30 ???, 06:12, MRAB ?wrote: > > >> This part: > > >> ? ? ? ( not mycookie or mycookie.value != 'nikos' ) > > >> is false but this part: > > >> ? ? ? re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > >> is true because host doesn't contain any of those substrings. > > > So, the if code does executed because one of the condition is true? > > > How should i write it? > > > I cannot think clearly on this at all. > > > I just wan to tell it to get executed ?ONLY IF > > > the cookie values is not 'nikos' > > > or ( don't knwo if i have to use and or 'or' here) > > > host does not contain any of the substrings. > > > What am i doign wrong?! > > It might be clearer if you reverse the condition and say: > > ? ? ?me_visiting = ... > ? ? ?if not me_visiting: > ? ? ? ? ?... # initialize cookie cookie = SimpleCookie() cookie.load( os.environ.get('HTTP_COOKIE', '') ) visitor = cookie.get('visitor') This statement if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| spider|crawl)', host ) is None: produces the following error: /home/webville/public_html/cgi-bin/counter.py 93 # do not increment the counter if a Cookie is set to the visitors browser already 94 # ================================================================================================================= 95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| spider|crawl)', host ) is None: 96 97 print visitor visitor = None, visitor.value undefined, re = , re.search = , host = '178-128-217.dynamic.cyta.gr', builtin None = None Why visitor.value is undefined? From mail at timgolden.me.uk Mon Aug 30 13:45:29 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Aug 2010 18:45:29 +0100 Subject: shlex, unicode, and subprocess.Popen on Windows In-Reply-To: <1283178266.13167.1392435533@webmail.messagingengine.com> References: <1283176444.5865.1392429397@webmail.messagingengine.com> <1283178224.12933.1392434421@webmail.messagingengine.com> <1283178266.13167.1392435533@webmail.messagingengine.com> Message-ID: <4C7BEE39.6020002@timgolden.me.uk> On 30/08/2010 3:24 PM, python at bdurham.com wrote: > My understanding is that the only time one needs to use shell=True is > when they are 'executing' a non-executable file whose executable must be > discovered via file association rules? Does that sound accurate? I'm not entirely sure what you mean by that last piece. Certainly, shell must be used if you're trying to run, eg, dir or copy which aren't executables in their own right but are sub-executables [a word I've just invented] of the command processor (cmd.exe). There's a slightly open question as to whether you need to say shell=True when running batch files (.bat/.cmd). My experience is not; others say yes. The ".... must be discovered via file association rules" looks out of place in your explanation above. (read: I can't see what you're getting at :) ) TJG From rami.chowdhury at merton.oxon.org Mon Aug 30 13:48:14 2010 From: rami.chowdhury at merton.oxon.org (Rami Chowdhury) Date: Mon, 30 Aug 2010 23:48:14 +0600 Subject: Problem checking an existing browser cookie In-Reply-To: <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> Message-ID: On Mon, Aug 30, 2010 at 23:36, Nik the Greek wrote: > # initialize cookie > cookie = SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > visitor = cookie.get('visitor') > > This statement > > if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > spider|crawl)', host ) is None: > > produces the following error: > > ?/home/webville/public_html/cgi-bin/counter.py > ? 93 # do not increment the counter if a Cookie is set to the > visitors browser already > ? 94 # > ================================================================================================================= > ? 95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > spider|crawl)', host ) is None: > ? 96 > ? 97 ? ? ? ? print visitor > visitor = None, visitor.value undefined, re = lib64/python2.4/re.pyc'>, re.search = , host = > '178-128-217.dynamic.cyta.gr', builtin None = None > > Why visitor.value is undefined? Because, as the traceback tells you, visitor is None. As you said, the cookie is not recognized. Try inserting the following line at the top of your script: print "Content-type:text/html\r\n\r\n", os.environ.get('HTTP_COOKIE', 'NO COOKIE DATA') That should give you the value of the cookie, which might help you debug why it is not being loaded. -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From python at mrabarnett.plus.com Mon Aug 30 13:50:21 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 18:50:21 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: <4C7BEF5D.20602@mrabarnett.plus.com> On 30/08/2010 18:16, Nik the Greek wrote: > On 30 ???, 19:41, MRAB wrote: >> On 30/08/2010 04:33, Nik the Greek wrote: >> >> >> >> >> >> >> >>> On 30 ???, 06:12, MRAB wrote: >> >>>> This part: >> >>>> ( not mycookie or mycookie.value != 'nikos' ) >> >>>> is false but this part: >> >>>> re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None >> >>>> is true because host doesn't contain any of those substrings. >> >>> So, the if code does executed because one of the condition is true? >> >>> How should i write it? >> >>> I cannot think clearly on this at all. >> >>> I just wan to tell it to get executed ONLY IF >> >>> the cookie values is not 'nikos' >> >>> or ( don't knwo if i have to use and or 'or' here) >> >>> host does not contain any of the substrings. >> >>> What am i doign wrong?! >> >> It might be clearer if you reverse the condition and say: >> >> me_visiting = ... >> if not me_visiting: >> ... > > I don't understand what are you trying to say > > Please provide a full example. > > You mean i should try it like this? > > unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn| > yandex|13448|spider|crawl)', host ) not None: > > But isnt it the same thing like the if? My point is that the logic might be clearer to you if you think first about how you know when you _are_ the visitor. From python at mrabarnett.plus.com Mon Aug 30 13:53:05 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 30 Aug 2010 18:53:05 +0100 Subject: Problem checking an existing browser cookie In-Reply-To: <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <745f6977-cf83-42f3-998a-c045a4ded4fd@t2g2000yqe.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> Message-ID: <4C7BF001.1000904@mrabarnett.plus.com> On 30/08/2010 18:36, Nik the Greek wrote: > On 30 ???, 19:41, MRAB wrote: >> On 30/08/2010 04:33, Nik the Greek wrote: >> >> >> >> >> >> >> >>> On 30 ???, 06:12, MRAB wrote: >> >>>> This part: >> >>>> ( not mycookie or mycookie.value != 'nikos' ) >> >>>> is false but this part: >> >>>> re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None >> >>>> is true because host doesn't contain any of those substrings. >> >>> So, the if code does executed because one of the condition is true? >> >>> How should i write it? >> >>> I cannot think clearly on this at all. >> >>> I just wan to tell it to get executed ONLY IF >> >>> the cookie values is not 'nikos' >> >>> or ( don't knwo if i have to use and or 'or' here) >> >>> host does not contain any of the substrings. >> >>> What am i doign wrong?! >> >> It might be clearer if you reverse the condition and say: >> >> me_visiting = ... >> if not me_visiting: >> ... > > > # initialize cookie > cookie = SimpleCookie() > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > visitor = cookie.get('visitor') > > This statement > > if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > spider|crawl)', host ) is None: > > produces the following error: > > /home/webville/public_html/cgi-bin/counter.py > 93 # do not increment the counter if a Cookie is set to the > visitors browser already > 94 # > ================================================================================================================= > 95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > spider|crawl)', host ) is None: > 96 > 97 print visitor > visitor = None, visitor.value undefined, re = lib64/python2.4/re.pyc'>, re.search =, host = > '178-128-217.dynamic.cyta.gr', builtin None = None > > Why visitor.value is undefined? Because visitor is None. It's not seeing any cookie. From nikos.the.gr33k at gmail.com Mon Aug 30 13:59:43 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Mon, 30 Aug 2010 10:59:43 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> Message-ID: <4aa14cf9-38b4-4240-a796-c8ba56093e46@z7g2000yqg.googlegroups.com> On 30 ???, 20:53, MRAB wrote: > > Why visitor.value is undefined? > > Because visitor is None. It's not seeing any cookie. WHY NOT?! THE COOKIE _DOES_EXIST !!! What am i missing here?! From jal at bethere.co.uk Mon Aug 30 14:01:58 2010 From: jal at bethere.co.uk (jal) Date: Mon, 30 Aug 2010 11:01:58 -0700 (PDT) Subject: python 2.6.6 installation problems on osx References: <15352d95-125c-41bb-8eca-7c5bc6b4bd94@k10g2000yqa.googlegroups.com> Message-ID: I just did 'make install' because according to the osx section of the README: On a clean OSX /usr/local does not exist. Do a "sudo mkdir -m 775 /usr/local" before you do a make install. It is probably not a good idea to do "sudo make install" which installs everything as superuser, as this may later cause problems when installing distutils- based additions. jal. On Aug 30, 4:32?pm, Benjamin Kaplan wrote: > On Mon, Aug 30, 2010 at 10:29 AM, jal wrote: > > Hi All, > > > I'm attempting a framework install of python 2.6.6 from source, on an > > intel mac running osx 10.6.4. > > > At the end of the install the following errors occur. > > > install: mkdir /usr/local/bin: Permission denied > > make[1]: *** [altinstallunixtools] Error 71 > > make: *** [frameworkaltinstallunixtools] Error 2 > > > Does anyone one know of a fix? > > did you sudo make install or just make install? From erik.reppen at gmail.com Mon Aug 30 14:21:50 2010 From: erik.reppen at gmail.com (Erik Reppen) Date: Mon, 30 Aug 2010 11:21:50 -0700 (PDT) Subject: Looking for Python and Python/Django workplaces in Chicago Message-ID: <894aa094-70c8-4c0e-b2c6-f2b783f68929@l20g2000yqe.googlegroups.com> I'm a really strong front end web dev with an interest in becoming more of a generalist web and app dev through Python. Anybody aware of studios/agencies that actually prefer Python in Chicago I could keep an eye on. From arnodel at googlemail.com Mon Aug 30 14:51:52 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 30 Aug 2010 19:51:52 +0100 Subject: in place functions from operator module References: <4465ed91-e06a-45be-b7a8-5a822c019fc1@h19g2000yqb.googlegroups.com> Message-ID: Raymond Hettinger writes: > On Aug 29, 8:33?am, Arnaud Delobelle wrote: >> ernest writes: >> > Hi, >> >> > The operator module provides separate functions for >> > "in place" operations, such as iadd(), isub(), etc. >> > However, it appears that these functions don't really >> > do the operation in place: >> >> > In [34]: a = 4 >> >> > In [35]: operator.iadd(a, 3) >> > Out[35]: 7 >> >> > In [36]: a >> > Out[36]: 4 >> >> > So, what's the point? If you have to make the >> > assignment yourself... I don't understand. >> >> > Cheers, >> > Ernest >> >> That's because >> >> ? ?a += b >> >> is executed as: >> >> ? ?a = a.__iadd__(b) >> >> For immutable objects, (such as integers), a.__iadd__(b) returns a + b >> *and then* this value is assigned to a (or rather 'a' is bound to the >> value). ?So for immutables objects, iadd(a, b) is the same as a + b >> >> For mutable objects (such as lists), a.__iadd__(b) mutates the object >> *and then* returns self so that when the assignement is executed, 'a' >> will still be bound the the same object. ?E.g. if a = [1, 2] then >> >> ? ? a += [3] >> >> will first append 3 to the list and then reassign the list to 'a' (it is >> unnecessary in this case but if this step was omitted, the "in place" >> operators wouldn't work on immutables types). > > This is an excellent explanation. > Perhaps, you can submit a documentation > patch for the operator module so this > doesn't get lost. > > > Raymond I have submitted a documentation patch: http://bugs.python.org/issue9717 -- Arnaud From benjamin at python.org Mon Aug 30 15:00:11 2010 From: benjamin at python.org (Benjamin Peterson) Date: Mon, 30 Aug 2010 19:00:11 +0000 (UTC) Subject: python+sqlite3 in memory database References: Message-ID: Denis Gomes gmail.com> writes: > > Eventually my goal is to dynamically load and unload sections of a file based database (could be tables or rows) in and out of memory for effeciency purposes. Have you actually found this to be an useful optimization? SQLite already internally caches database information in memory. From tjreedy at udel.edu Mon Aug 30 15:08:57 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Aug 2010 15:08:57 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: <7xiq2suzbj.fsf@ruckus.brouhaha.com> References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> <7xiq2suzbj.fsf@ruckus.brouhaha.com> Message-ID: On 8/30/2010 7:14 AM, Paul Rubin wrote: > example, tkinter has been part of the stdlib for at least a decade but > is totally undocumented in the Python library manual. I have trouble equating 'totally undocumented' to about 400 lines + 200 for tix + 600 for ttk ;-). Yes, 400, while more than most modules get, is inadequate as a complete reference. But no one has volunteered to reproduce the material available elsewhere. I am not sure that that is the highest priority for doc improvement yet. You are welcome to have a go at expanding the tkinter page. -- Terry Jan Reedy From nobody at nowhere.com Mon Aug 30 15:09:30 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 30 Aug 2010 20:09:30 +0100 Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On Mon, 30 Aug 2010 12:50:32 +0200, Thomas Jollans wrote: >> Face the facts dude. The Python docs have some major problems. >> They were pretty good when Python was a new, cool, project used >> by a handful of geeks. They are good relative to the "average" >> (whatever that is) open source project -- but that bar is so low >> as to be a string lying on the ground. > > Actually, the Python standard library reference manual is excellent. At > least that's my opinion. The core library documentation isn't as bad as most Python documentation, but it's still far from adequate for core language functionality. Anyone who thinks that the library documentation is "good" has become too accustomed to FOSS "documentation" which is little more than an HTMLified copy of the header files, with each function's documentation consisting of a prototype and a one-sentence description which provides no information which couldn't have been guessed from the function name. For add-ons, you can get away with second-rate documentation. If the documentation isn't sufficient to allow the module to be used, don't use it; write your own instead. But that doesn't work for core language features. From tjreedy at udel.edu Mon Aug 30 15:14:48 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Aug 2010 15:14:48 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On 8/30/2010 12:23 AM, rurpy at yahoo.com wrote: > The Python docs have some major problems. And I have no idea what you think they are. I have participated in 71 doc improvement issues on the tracker. Most of those I either initiated or provided suggestions. How many have you helped with? -- Terry Jan Reedy From nobody at nowhere.com Mon Aug 30 15:25:42 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 30 Aug 2010 20:25:42 +0100 Subject: shlex, unicode, and subprocess.Popen on Windows References: <1283176444.5865.1392429397@webmail.messagingengine.com> <1283178224.12933.1392434421@webmail.messagingengine.com> Message-ID: On Mon, 30 Aug 2010 10:24:26 -0400, python wrote: >> Kudos for avoiding shell=True > > My understanding is that the only time one needs to use shell=True is > when they are 'executing' a non-executable file whose executable must be > discovered via file association rules? Does that sound accurate? You also need to use it to execute commands which are built into the shell rather than being separate executables. On Windows, whether "shell" is True or False and whether "args" is a string or list are orthogonal. If args is a list, it will be converted to a string using the same rules regardless of whether the shell is used. From denisg640 at gmail.com Mon Aug 30 15:33:55 2010 From: denisg640 at gmail.com (Denis Gomes) Date: Mon, 30 Aug 2010 15:33:55 -0400 Subject: python+sqlite3 in memory database In-Reply-To: References: Message-ID: Hey Benjamin, Take a look at this website I found about cached and in-memory databases. I think the gist of the article is that caching is good if you are doing SELECTs on data that is frequently used whereas in-memory speeds up writes, (inserts and updates) to the db as well as querying. Maybe I am missing something? http://www.mcobject.com/in_memory_database Denis On Mon, Aug 30, 2010 at 3:00 PM, Benjamin Peterson wrote: > Denis Gomes gmail.com> writes: > > > > > Eventually my goal is to dynamically load and unload sections of a file > based > database (could be tables or rows) in and out of memory for effeciency > purposes. > > Have you actually found this to be an useful optimization? SQLite already > internally caches database information in memory. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From a_jtim at bellsouth.net Mon Aug 30 15:38:18 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Mon, 30 Aug 2010 12:38:18 -0700 (PDT) Subject: triangle python user's group? Message-ID: <3c95f09c-1fa7-4c63-9f13-3f2776c2ab41@j18g2000yqd.googlegroups.com> Hi, Is there a python users group in the Research Triangle Park area (North Carolina, USA)? If there is not one and you're in the area and would be interested, please send an email to jtim.arnold at gmail.com and I'll organize a get-together to get one started. I'll try to find a locale convenient to Chapel Hill, Durham, Raleigh, Cary, and Apex. thanks, --Tim From benjamin at python.org Mon Aug 30 15:51:34 2010 From: benjamin at python.org (Benjamin Peterson) Date: Mon, 30 Aug 2010 19:51:34 +0000 (UTC) Subject: python+sqlite3 in memory database References: Message-ID: Denis Gomes gmail.com> writes: > > > Hey Benjamin, > ? > ?Take a look at this website I found about cached and in-memory databases.? I think the gist of?the article?is that caching is good if you are doing SELECTs on data that is?frequently used whereas in-memory speeds up writes,?(inserts and updates)?to the db as well as querying.?Maybe I am missing something? Well, of course, but there's little point to doing INSERTs and UPDATEs if you don't write them to disk at some point. You could just have a long running transaction which will not write to the database file (though depending on how you have sqlite setup it may write to a journal file) until you commit it. From __peter__ at web.de Mon Aug 30 16:39:32 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Aug 2010 22:39:32 +0200 Subject: bug? pkgutil.walk_packages returns packages that result in an ImportError References: Message-ID: Chris Withers wrote: > Peter Otten wrote: >>> My expectation of this is that if onerrors is left as None, names >>> yielded will be importable. >> >> I would infer no such promise, especially as the generator also yields >> modules, and no attempt at all is made to import those. > > Really? Yes, and the docstring gives a hint: """ Note that this function must import all *packages* (NOT all modules!) on the given path, in order to access the __path__ attribute to find submodules. """ Emphasis *not* mine ;) > I thought the __import__ fired over everything? If in doubt have a look at the source code or make a little testcase. > It's becoming a common use case for packages like martian [1] and > venutian [2] that need to scan whole packages for things. In my case, > I'm scanning for declaratively mapped SQLAlchemy models. > > It would be great if this function became part of the public API and got > some more definition on what it will and won't do. When should I take > this to Python-Dev? My impression is that it was a conscious decision to import as little as necessary. It is easy to import the modules once you have their names, but impossible to undo an unwanted import. If you think the approach you expected is superior you can also escalate to python-ideas and see if you get more feedback there or make a feature request on the bug tracker. Peter From marduk at letterboxes.org Mon Aug 30 16:42:43 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Mon, 30 Aug 2010 16:42:43 -0400 Subject: triangle python user's group? In-Reply-To: <3c95f09c-1fa7-4c63-9f13-3f2776c2ab41@j18g2000yqd.googlegroups.com> References: <3c95f09c-1fa7-4c63-9f13-3f2776c2ab41@j18g2000yqd.googlegroups.com> Message-ID: <1283200963.512722.2.camel@paska> On Mon, 2010-08-30 at 12:38 -0700, Tim Arnold wrote: > Hi, > Is there a python users group in the Research Triangle Park area > (North Carolina, USA)? Google "triangle python user's group" From nagle at animats.com Mon Aug 30 16:43:32 2010 From: nagle at animats.com (John Nagle) Date: Mon, 30 Aug 2010 13:43:32 -0700 Subject: String substitution VS proper mysql escaping In-Reply-To: <8e17d7FsbU1@mid.individual.net> References: <4C6D7D0D.7040703@gmail.com> <20100820052243.GA23046@cskk.homeip.net> <8d45526c-5524-41b4-8977-2483d7c9bfb4@h19g2000yqb.googlegroups.com> <0ebf7bfd-3d52-476b-b85f-d06a937d49e1@l20g2000yqm.googlegroups.com> <2905f8f3-adfb-4b9c-8ef5-2bcc6b026e2d@f42g2000yqn.googlegroups.com> <5f249b6f-8151-4b9a-ae5c-71e56ae9b7b9@t2g2000yqe.googlegroups.com> <5e703722-fad0-4352-bd9c-8e054429a877@t2g2000yqe.googlegroups.com> <8e17d7FsbU1@mid.individual.net> Message-ID: <4c7c17f4$0$1654$742ec2ed@news.sonic.net> On 8/30/2010 1:11 AM, Gregory Ewing wrote: > Nik the Greek wrote: > >> Yes i will i just asked to know if i were to substitute what might be >> the problem so to understand why i need the quoting. > > Because if you use % to build a query string, the result must > be syntactically valid SQL. The values that you substitute > into the placeholders must end up looking like SQL literals. > That means string values need to be in quotes, and probably > dates as well, although numbers don't. > > When you use the execute method's own parameter substitution > mechanism, things are different. It's not a textual replacement, > and you don't put quotes around the placeholders. There's no > particular reason for that, it's just the way it's defined > to work. Actually, it IS a textual replacement. What cursor.execute(sqlstring, values) is doing is essentially quotedstr = sqlstring % map(MySQLdb.escape_string, values) cursor.execute(quotedstr) There's much confusion about this, but it isn't complicated. John Nagle From nagle at animats.com Mon Aug 30 16:50:36 2010 From: nagle at animats.com (John Nagle) Date: Mon, 30 Aug 2010 13:50:36 -0700 Subject: python+sqlite3 in memory database In-Reply-To: References: Message-ID: <4c7c199d$0$1646$742ec2ed@news.sonic.net> On 8/30/2010 12:00 PM, Benjamin Peterson wrote: > Denis Gomes gmail.com> writes: > >> >> Eventually my goal is to dynamically load and unload sections of a file based > database (could be tables or rows) in and out of memory for effeciency purposes. > > Have you actually found this to be an useful optimization? SQLite already > internally caches database information in memory. In general, if you find yourself concerned about sqlite performance, it's time to move to MySQL or Postgres. "sqlite" is for simple, lightweight databases mostly accessed by one process at a time. You store your program's configuration options in sqlite. You store your web site's business transactions in MySQL. "sqlite" has reasonably good SELECT performance on simple indices, but anything beyond that isn't all that great. Multiple processes updating the same sqlite database will have terrible performance, because the locking mechanism not only locks the entire table, the wait mechanism is a timed retry. John Nagle From denisg640 at gmail.com Mon Aug 30 16:50:37 2010 From: denisg640 at gmail.com (Denis Gomes) Date: Mon, 30 Aug 2010 16:50:37 -0400 Subject: python+sqlite3 in memory database In-Reply-To: References: Message-ID: Yep, I see what you are saying. I am going to do a bit more research to see how sqlite3 works internally, ie. cache size, page size, etc, and then decide if I will need to mess with in-memory databases. Thanks for your insight, appreciate it. Denis On Mon, Aug 30, 2010 at 3:51 PM, Benjamin Peterson wrote: > Denis Gomes gmail.com> writes: > > > > > > > Hey Benjamin, > > > > Take a look at this website I found about cached and in-memory > databases. I > think the gist of the article is that caching is good if you are doing > SELECTs > on data that is frequently used whereas in-memory speeds up > writes, (inserts and > updates) to the db as well as querying. Maybe I am missing something? > > Well, of course, but there's little point to doing INSERTs and UPDATEs if > you > don't write them to disk at some point. You could just have a long running > transaction which will not write to the database file (though depending on > how > you have sqlite setup it may write to a journal file) until you commit it. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin at python.org Mon Aug 30 18:27:16 2010 From: benjamin at python.org (Benjamin Peterson) Date: Mon, 30 Aug 2010 22:27:16 +0000 (UTC) Subject: python+sqlite3 in memory database References: <4c7c199d$0$1646$742ec2ed@news.sonic.net> Message-ID: John Nagle animats.com> writes: > "sqlite" has reasonably good SELECT performance on simple indices, > but anything beyond that isn't all that great. Multiple processes > updating the same sqlite database will have terrible performance, > because the locking mechanism not only locks the entire table, > the wait mechanism is a timed retry. This is been improved significantly in recent versions with support for write ahead logging and different lock levels to prevent writer starvation. From ldo at geek-central.gen.new_zealand Mon Aug 30 19:13:26 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 31 Aug 2010 11:13:26 +1200 Subject: Helper app for intranet site References: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> <61894f54-90ff-4e0e-9c81-860b6e9cdc15@p12g2000prn.googlegroups.com> Message-ID: In message <61894f54-90ff-4e0e-9c81-860b6e9cdc15 at p12g2000prn.googlegroups.com>, kevinlcarlson wrote: > On Aug 29, 8:46 pm, Lawrence D'Oliveiro > wrote: >> >> In message >> <45e0772c-24a8-4cbb-a4fc-74a1b6c25... at n19g2000prf.googlegroups.com>, >> kevinlcarlson wrote: >>> >>> I'm exploring the possibility of developing a helper app for an >>> existing internal company website. Basically, it would automatically >>> scan the current page contents, including prepopulated forms, and >>> provide context-related business rule comments to the user, via a stay- >>> on-top wxPython panel. >> >> Seems like a roundabout way of doing it. Can?t you integrate into the >> server code which is generating the page contents, instead of trying to >> reverse- engineer those contents? > > Absolutely - that would be the best way to accomplish this. > Unfortunately, our group has no access to the web server and the > developers have this functionality scheduled about a year into the > future, but we need it ASAP. Also, our group would like to be in > control of the code and business rule contents, rather than wait for > updates from the busy web team... Conway?s Law: any piece of software reflects the organizational structure that produced it. From ldo at geek-central.gen.new_zealand Mon Aug 30 19:17:09 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 31 Aug 2010 11:17:09 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> <7xr5hguzzi.fsf@ruckus.brouhaha.com> Message-ID: In message <7xr5hguzzi.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > JHC (experimental Haskell compiler) recently started using a mixture of > gc and region inference. It will be interesting to see how that works > out. That?s what people have been saying about garbage collection for about half a century: ?this new experimental technique will solve all the problems, just you wait and see?. Meanwhile, real-world programmers get on to writing real-world code that is productive and efficient on real-world systems. From aahz at pythoncraft.com Mon Aug 30 19:42:11 2010 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2010 16:42:11 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: In article <878w3ogpvq.fsf at benfinney.id.au>, Ben Finney wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> That reminds me: one co-worker (who really should have known better ;-) >> had the impression that sets were O(N) rather than O(1). > >For settling exactly this kind of confusion, Python's standard library >comes with a module, the timeit module. Your co-worker should have >known better: don't guess about timing performance, measure it. > >Or am I missing something here? Possibly; IMO, people should not need to run timeit to determine basic algorithmic speed for standard Python datatypes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From bradley.h at aggiemail.usu.edu Mon Aug 30 20:05:28 2010 From: bradley.h at aggiemail.usu.edu (Bradley Hintze) Date: Mon, 30 Aug 2010 20:05:28 -0400 Subject: Functions continuing to ru after returning something? Message-ID: I may be having a brain fart, but is it at all possible to have a function first return a value then continue its calculation. Like this simple example: my_var = 5 def my_function(): return my_var my_var +=1 This obviously won't work as written but is there a cleaver way around this. -- Bradley J. Hintze Graduate Student Duke University School of Medicine 801-712-8799 From python at mrabarnett.plus.com Mon Aug 30 20:12:09 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 01:12:09 +0100 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4C7C48D9.7020800@mrabarnett.plus.com> On 31/08/2010 01:05, Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. > Do you mean a generator? From no.email at nospam.invalid Mon Aug 30 21:09:50 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 18:09:50 -0700 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> <7xr5hguzzi.fsf@ruckus.brouhaha.com> Message-ID: <7xtymbzixt.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > Meanwhile, real-world programmers get on to writing real-world code that is > productive and efficient on real-world systems. It's pretty well established by now that GC doesn't have any significant speed penalty compared with manual allocation. It does consume more memory, which is acceptable a lot of the time. It certainly leads to more reliable programs. From no.email at nospam.invalid Mon Aug 30 21:14:32 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 18:14:32 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: <7xpqwzzipz.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > Possibly; IMO, people should not need to run timeit to determine basic > algorithmic speed for standard Python datatypes. Indeed. Alex Stepanov (designer of C++ Standard Template Library) was emphatic that algorithm complexity assertions should be part of the interface of any STL function: http://www.sgi.com/tech/stl/drdobbs-interview.html He also said it should be part of the "unwritten contract" between the module and its user, but I don't understand why he said "unwritten", since in the C++ STL the complexity statements are part of the written spec. From reply-to at works.fine.invalid Mon Aug 30 21:45:47 2010 From: reply-to at works.fine.invalid (NickC) Date: 31 Aug 2010 01:45:47 GMT Subject: Structured programming with optionParser Message-ID: <4c7c5eca$0$11121$c3e8da3@news.astraweb.com> I'm writing a short (200 lines) script that has half-a-dozen parameter options, and using optionParser to process the options. I try to write well-written procedural programmes with functions doing one thing well, and so on. The problem I'm getting is that, inevitably, the function that uses OptionParser ends up doing all the work. So, I have a brief 6-line main() that calls other functions, a setup(), a couple of ancillary functions, and a whopping doOptionParsing() that is over 100 lines long. doOptionParsing is doing all the work. I'm struggling to see how you could refactor the option parsing function. After all, it has to process the options, so it has to do all the setup for those options, and then process them. Does anyone have some sort of design pattern or standard template approach to doing option parsing? Or perhaps should I make optionParser variables global? Thanks, -- NickC From michael.a.powe at gmail.com Mon Aug 30 21:55:20 2010 From: michael.a.powe at gmail.com (naugiedoggie) Date: Mon, 30 Aug 2010 18:55:20 -0700 (PDT) Subject: Installing Python as Scripting Language in IIS Message-ID: <4154f088-f746-4891-83ee-f64138c81e2e@x25g2000yqj.googlegroups.com> Hello, Windows 2003, 64-bit, standard edition server with IIS 6.0. I followed the MS instruction sheets on setting up CGI application with Python as scripting engine. I'm just getting 404 for the test script, whereas an html file in the same virtual directory is properly displayed. Here: Creating Applications in IIS 6.0 (IIS 6.0) http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/bc0c4729-e892-4871-b8f3-fcbf489f2f09.mspx?mfr=true Setting Application Mappings in IIS 6.0 (IIS 6.0) http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/bc0c4729-e892-4871-b8f3-fcbf489f2f09.mspx?mfr=true I mapped the exe thus: c:\Python26\python.exe -u "%s %s" to extension `py' for all verbs and checked the `script engine' box. There are no errors in the script itself, i ran it from the command line to be sure. Further, I enabled ASP and tried using python as the scripting language. That generates this error: Active Server Pages error 'ASP 0129' Unknown scripting language /cgi/index.asp, line 1 The scripting language 'Python' is not found on the server. I can't find any good references for dealing with this, either. I've dicked around with this for so long, now I don't know which way is up, anymore. Any thoughts on where I might be going wrong, much appreciated. Thanks. mp From vicente.soler at gmail.com Mon Aug 30 22:00:24 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 30 Aug 2010 19:00:24 -0700 (PDT) Subject: Source code for itertools Message-ID: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> I'm interested in studying the itertools source code, especially the permutations function. However, I cannot find the library. Where could I find it? Running Python 3.1 Thank you From ldo at geek-central.gen.new_zealand Mon Aug 30 22:14:29 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 31 Aug 2010 14:14:29 +1200 Subject: Source code for itertools References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: In message <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8 at t20g2000yqa.googlegroups.com>, vsoler wrote: > I'm interested in studying the itertools source code, especially the > permutations function. > > However, I cannot find the library. Where could I find it? ldo at theon:python> apt-get source python3.1 Reading package lists... Done Building dependency tree Reading state information... Done Need to get 12.0MB of source archives. Get:1 http://ftp.nz.debian.org sid/main python3.1 3.1.2+20100829-1 (dsc) [1,776B] Get:2 http://ftp.nz.debian.org sid/main python3.1 3.1.2+20100829-1 (tar) [11.8MB] Get:3 http://ftp.nz.debian.org sid/main python3.1 3.1.2+20100829-1 (diff) [239kB] Fetched 12.0MB in 28s (417kB/s) dpkg-source: info: extracting python3.1 in python3.1-3.1.2+20100829 dpkg-source: info: unpacking python3.1_3.1.2+20100829.orig.tar.gz dpkg-source: info: applying python3.1_3.1.2+20100829-1.diff.gz ldo at theon:python> find . -iname \*itertools\* ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c ./python3.1-3.1.2+20100829/Lib/test/test_itertools.py ./python3.1-3.1.2+20100829/Lib/lib2to3/fixes/fix_itertools_imports.py ./python3.1-3.1.2+20100829/Lib/lib2to3/fixes/fix_itertools.py ./python3.1-3.1.2+20100829/Doc/library/itertools.rst From anand.shashwat at gmail.com Mon Aug 30 22:22:34 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Tue, 31 Aug 2010 07:52:34 +0530 Subject: Source code for itertools In-Reply-To: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: On Tue, Aug 31, 2010 at 7:30 AM, vsoler wrote: > I'm interested in studying the itertools source code, especially the > permutations function. > > However, I cannot find the library. Where could I find it? > > Running Python 3.1 > > Thank you > Either you can download it or browse it on the net. http://svn.python.org/view/python/trunk/Modules/itertoolsmodule.c?view=markup > -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Mon Aug 30 22:27:29 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 30 Aug 2010 19:27:29 -0700 (PDT) Subject: Source code for itertools References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: On 31 ago, 04:14, Lawrence D'Oliveiro wrote: > In message <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad... at t20g2000yqa.googlegroups.com>, vsoler wrote: > > > I'm interested in studying the itertools source code, especially the > > permutations function. > > > However, I cannot find the library. Where could I find it? > > ldo at theon:python> apt-get source python3.1 > Reading package lists... Done > Building dependency tree ? ? ? > Reading state information... Done > Need to get 12.0MB of source archives. > Get:1http://ftp.nz.debian.orgsid/main python3.1 3.1.2+20100829-1 (dsc) [1,776B] > Get:2http://ftp.nz.debian.orgsid/main python3.1 3.1.2+20100829-1 (tar) [11.8MB] > Get:3http://ftp.nz.debian.orgsid/main python3.1 3.1.2+20100829-1 (diff) [239kB] ? ? ? ? ? ? ? ? ? > Fetched 12.0MB in 28s (417kB/s) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > dpkg-source: info: extracting python3.1 in python3.1-3.1.2+20100829 > dpkg-source: info: unpacking python3.1_3.1.2+20100829.orig.tar.gz > dpkg-source: info: applying python3.1_3.1.2+20100829-1.diff.gz > ldo at theon:python> find . -iname \*itertools\* > ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c > ./python3.1-3.1.2+20100829/Lib/test/test_itertools.py > ./python3.1-3.1.2+20100829/Lib/lib2to3/fixes/fix_itertools_imports.py > ./python3.1-3.1.2+20100829/Lib/lib2to3/fixes/fix_itertools.py > ./python3.1-3.1.2+20100829/Doc/library/itertools.rst I was expecting an itertools.py file, but I don't see it in your list. I can instead see the test_itertools.py file, but my understanding is that it is not the file I am looking for. Is it possible that it is a built-in module whose source code is not available for watching it? Thank you very much From no.email at nospam.invalid Mon Aug 30 22:42:33 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Aug 2010 19:42:33 -0700 Subject: Source code for itertools References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: <7xmxs3sdt2.fsf@ruckus.brouhaha.com> vsoler writes: > I was expecting an itertools.py file, but I don't see it in your list. >> ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c looks promising. Lots of stdlib modules are written in C for speed or access to system facilities. From vicente.soler at gmail.com Mon Aug 30 23:06:31 2010 From: vicente.soler at gmail.com (vsoler) Date: Mon, 30 Aug 2010 20:06:31 -0700 (PDT) Subject: Source code for itertools References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> <7xmxs3sdt2.fsf@ruckus.brouhaha.com> Message-ID: On 31 ago, 04:42, Paul Rubin wrote: > vsoler writes: > > I was expecting an itertools.py file, but I don't see it in your list. > >> ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c > > looks promising. ?Lots of stdlib modules are written in C for speed or > access to system facilities. Lawrence, Paul, You seem to be running a utility I am not familiar with. Perhaps this is because I am using Windows, and most likely you are not. How could I have found the answer in a windows environment? Thank you very much From michele.simionato at gmail.com Mon Aug 30 23:23:44 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 30 Aug 2010 20:23:44 -0700 (PDT) Subject: Structured programming with optionParser References: <4c7c5eca$0$11121$c3e8da3@news.astraweb.com> Message-ID: <5ff8c04d-6fbc-4385-af3c-92e2bef62c63@i13g2000yqd.googlegroups.com> On Aug 31, 3:45?am, NickC wrote: > I'm struggling to see how you could refactor the option parsing function. > After all, it has to process the options, so it has to do all the setup > for those options, and then process them. Perhaps plac could simplify your life, by removing most of the boilerplate of option parsing: http://pypi.python.org/pypi/plac From aweraw at gmail.com Mon Aug 30 23:28:23 2010 From: aweraw at gmail.com (Aidan) Date: Tue, 31 Aug 2010 13:28:23 +1000 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4c7c77b0$1@dnews.tpgi.com.au> Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. > def my_function(): my_var = 5 while my_var <= 10: yield my_var my_var += 1 >>> for x in my_function(): ... print x 5 6 7 8 9 10 >>> From darkrho at gmail.com Mon Aug 30 23:33:24 2010 From: darkrho at gmail.com (Rolando Espinoza La Fuente) Date: Mon, 30 Aug 2010 23:33:24 -0400 Subject: Source code for itertools In-Reply-To: References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> <7xmxs3sdt2.fsf@ruckus.brouhaha.com> Message-ID: On Mon, Aug 30, 2010 at 11:06 PM, vsoler wrote: > On 31 ago, 04:42, Paul Rubin wrote: >> vsoler writes: >> > I was expecting an itertools.py file, but I don't see it in your list. >> >> ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c >> >> looks promising. ?Lots of stdlib modules are written in C for speed or >> access to system facilities. > > Lawrence, Paul, > > You seem to be running a utility I am not familiar with. Perhaps this > is because I am using Windows, and most likely you are not. > > How could I have found the answer in a windows environment? Hard question. They are using standard unix utilities. But you can find the source file of a python module within python: >>> import itertools >>> print(itertools.__file__) /usr/lib/python2.6/lib-dynload/itertools.so Yours should point to a windows path. If the file ends with a ".py", you can open the file with any editor. If ends with ".so" or something else likely is a compiled module in C and you should search in the source distribution, not the binary distribution. Hope it helps. Regards, Rolando Espinoza La fuente www.insophia.com From brian.curtin at gmail.com Mon Aug 30 23:37:05 2010 From: brian.curtin at gmail.com (Brian Curtin) Date: Mon, 30 Aug 2010 22:37:05 -0500 Subject: Source code for itertools In-Reply-To: References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> <7xmxs3sdt2.fsf@ruckus.brouhaha.com> Message-ID: On Mon, Aug 30, 2010 at 22:06, vsoler wrote: > On 31 ago, 04:42, Paul Rubin wrote: > > vsoler writes: > > > I was expecting an itertools.py file, but I don't see it in your list. > > >> ./python3.1-3.1.2+20100829/Modules/itertoolsmodule.c > > > > looks promising. Lots of stdlib modules are written in C for speed or > > access to system facilities. > > Lawrence, Paul, > > You seem to be running a utility I am not familiar with. Perhaps this > is because I am using Windows, and most likely you are not. > > How could I have found the answer in a windows environment? > > Thank you very much > -- > http://mail.python.org/mailman/listinfo/python-list > You need to checkout the source from svn (or pull from applicable hg mirrors). For example: 1. svn co http://svn.python.org/projects/python/branches/release31-maint 2. open Modules/itertoolsmodule.c The C code for extension modules doesn't get distributed with the installers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From crebert at ucsd.edu Mon Aug 30 23:42:22 2010 From: crebert at ucsd.edu (Chris Rebert) Date: Mon, 30 Aug 2010 20:42:22 -0700 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: On Mon, Aug 30, 2010 at 5:05 PM, Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > ? ?return my_var > ? ?my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. And what do you want to happen with the code the value was returned to? Cheers, Chris From tjreedy at udel.edu Mon Aug 30 23:47:34 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Aug 2010 23:47:34 -0400 Subject: Source code for itertools In-Reply-To: References: <9aa266f0-be9b-4c9a-bfbd-6cdfc86ad2c8@t20g2000yqa.googlegroups.com> Message-ID: On 8/30/2010 10:27 PM, vsoler wrote: > I was expecting an itertools.py file, but I don't see it in your > list. The manual page has the original python source for each function. I recommend you look at that. Itertool was rewritten in C for speed but the C source will not tell you any more about the functions themselves. -- Terry Jan Reedy From michele.simionato at gmail.com Tue Aug 31 00:19:08 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 30 Aug 2010 21:19:08 -0700 (PDT) Subject: Structured programming with optionParser References: <4c7c5eca$0$11121$c3e8da3@news.astraweb.com> Message-ID: Perhaps, I should give an example of using plac. For instance, here is how you could implement a SVN-like tool with two commands ``checkout`` and ``commit``. The trick is to write a class with two methods ``checkout`` and ``commit`` and an attribute ``.commands`` listing them, and to call the class with ``plac.Interpreter.call``:: $ cat vcs.py class VCS(object): "A fictitious version control tool" commands = ['checkout', 'commit'] def checkout(self, url): return 'ok' def commit(self): return 'ok' if __name__ == '__main__': import plac; plac.Interpreter.call(VCS) The line ``plac.Interpreter.call`` instantiates the ``VCS`` class by passing to it the arguments in the command line and then calls the appropriate method. You can use the script as follows:: $ python vcs.py -h usage: vcs.py [-h] [args [args ...]] positional arguments: args optional arguments: -h, --help show this help message and exit $ python vcs.py checkout url ok $ python vcs.py commit ok plac_ takes care of parsing the command line, giving the correct error message if you pass wrong arguments or not enough arguments:: $ python vcs.py checkout usage: checkout url checkout: error: too few arguments You should realize that there is no real difference between a command-line argument parser featuring subcommands and an command interpreter, therefore the previous script also works as an interactive interpreter:: $ python vcs.py -i i> .help special commands ================ .help .last_tb custom commands =============== checkout commit i> checkout url ok i> commit ok There is full help support, i.e. you can ask for ``.help `` for any command, including the special ones such as ``.help`` and ``.last_tb``. There is full support for autocompletion and command history too, provided you have the readline library installed (on Unices) or the pyreadline library (on Windows). plac also support a batch mode: you can write a set of commands on a file and have them executed by the plac runner. :: $ echo vcs-commands.plac #!vcs.py:VCS checkout url # nontrivial commands here commit $ plac_runner.py --batch vcs-commands.plac ok skip # ok For more (including managing options, which I have not shown here) you should check the full documentation of plac. I have just uploaded release 0.7.2, which is required for this example to work. From rurpy at yahoo.com Tue Aug 31 00:44:06 2010 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 30 Aug 2010 21:44:06 -0700 (PDT) Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: <28a1b252-e0fb-4992-bfff-be9b3f99cffc@t2g2000yqe.googlegroups.com> On 08/30/2010 04:50 AM, Thomas Jollans wrote: > On Monday 30 August 2010, it occurred to rurpy at yahoo.com to exclaim: >> Face the facts dude. The Python docs have some major problems. >> They were pretty good when Python was a new, cool, project used >> by a handful of geeks. They are good relative to the "average" >> (whatever that is) open source project -- but that bar is so low >> as to be a string lying on the ground. > > Actually, the Python standard library reference manual is excellent. At least > that's my opinion. > > Granted, it's not necessarily the best in the world. It could probably be > better. But that goes for just about every documentation effort there is. > > What exactly are you comparing the Python docs to, I wonder? Obviously not > something like Vala, but that goes without saying. "kj" said that the Perl > docs were better. I can't comment on that. I also won't comment on the sorry > mess that the language "Perl" is, either. > There are a few documentation efforts that I recognize are actually better > than the Python docs: Firstly, the MSDN Library docs for the .Net framework. > Not that I refer to it much, but it is excellent, and it probably was a pretty > darn expensive project too. Secondly, the libc development manual pages on > Linux and the BSDs. Provided you know your way around the C library, they are > really a top-notch reference. The Postgresql docs have always seemed pretty good to me. And I'll second kj's nomination of Perl. The Perl docs have plenty of faults but many years ago I was able to learn Perl with nothing more than those docs. It was well over five years later that I ever got around to buying a commercial Perl book. In contrast, I made several, honest efforts to learn Python the same way but found it impossible and never got a handle on it until I bought Lutz's and Beazley's books. (Of which Bealey's was by far the most useful; Lutz became a doorstop pretty quickly. And yes, I knew about but didn't use the tutorial -- tutorials are one way of presenting information that aren't appropriate for everyone or in every situation, and the existence of one in no way excuses inadequate reference material.) If one is comparing the Python docs to others, comparing it to Beazley's book is informative. Most of the faults I find with the book are the places he took material from the Python docs nearly verbatim. The material he interprets and explains (usually quite tersely) is much clearer that similar material (if it even exists) in the Python docs. Finally, it it not really necessary to compare the Python docs to others to make a judgment -- simply looking at the hours taken to solve some problem that could have been avoided with a couple more sentences in the docs -- the number of hours spent trying figure out some behavior by pouring over the standard lib code -- the number of times one decides how to write code by "trying it", with fingers crossed that one isn't relying on some accidental effect that will change with the next version or platform -- these can give a pretty good indication of the magnitude of the doc problems. I think one reason for the frequent "Python docs are great" opinions here is that eventually one figures out the hard way how things work, and tends to rely less on the docs as documentation, and more as a memmonic. And for that the existing docs are adequate. From rurpy at yahoo.com Tue Aug 31 00:47:17 2010 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 30 Aug 2010 21:47:17 -0700 (PDT) Subject: How to convert (unicode) text to image? References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On 08/30/2010 01:14 PM, Terry Reedy wrote: > On 8/30/2010 12:23 AM, rurpy at yahoo.com wrote: >> The Python docs have some major problems. > > And I have no idea what you think they are. I have written about a few of them here in the past. I sure Google will turn up something. > I have participated in 71 doc improvement issues on the tracker. Most of > those I either initiated or provided suggestions. How many have you > helped with? Certainly not 71. But there is, for example, http://bugs.python.org/issue1397474 Please note the date on it. From lamlbiro at optusnet.com.au Tue Aug 31 02:17:33 2010 From: lamlbiro at optusnet.com.au (L) Date: Tue, 31 Aug 2010 16:17:33 +1000 Subject: PyGeo In-Reply-To: References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> Message-ID: <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> On 30/08/10 18:59, Thomas Jollans wrote: > On Monday 30 August 2010, it occurred to L to exclaim: > >> I have tried it and as soon as you try any of the examples in the >> examples dir it cannot find numpy etc.... >> >> I have manually move the pygeo dirs and contents to >> /usr/lib/python2.6/dis-packages, >> >> (this is the directory where numpy, numeric and scipy were installed >> when using synaptic ) >> >> made sure that read and write permissions set for ALL FILES and >> DIRECTORIES to RW using sudo chmod 777 >> > Wait -- did you just try to use pymaxima, or did you properly (try to) install > the dependencies? > > You need VPython. It's in the ubuntu archives. > http://packages.ubuntu.com/lucid/python-visual > > And then you need to download and install pygeo. > http://pygeo.sourceforge.net/download.html > It probably uses distutils, so you'd extract the source archive and run > sudo python setup.py install > > If THAT gives you any errors, then please come back here, with the exact error > messages. If it works, then PyGeo should be installed. If it still doesn't > work, then there's certainly a chance it won't work, but you can still ask > here for help, with the exact error messages, so we have something to build > upon when trying to figure out what's wrong. > > - Thomas > No, I have not tried pymaxma ( I have maxima and wxmaxima install via synaptic, tested and all works OK) yes, that is what I did for install. Vpython already install via synaptic, ran a number of examples and all produced the expected output. also the PyGeo readme text mentions Numerical python (I think it means Numeric, but I also have NumPy installed) to install i did the following steps PyGeo downloaded form sourceforge tar xvfc PyGeo-1.0a1.tar.gz cd PyGeo-1.0a1 python setup.py install NO ERROR MESSAGES ecountered IT DID NOT WORK coplaing about the NUMERIC module I repeated the install and issued the parameter to 'python steup.py install.....) to force the directory name to be the same where the other python modules are (see listing below) NO ERROR MESSAGES ecountered Note what I did to ensure permissions etc (see my second post for directories etc) install successful, but running the example from ...examples/real/ using IDLE I get IDLE 2.6.5 ==== No Subprocess ==== >>> Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/pygeo/examples/real/dandelinspheres2.py", line 2, in from pygeo.base.abstract_elements_real import _Sphere, _Point File "/usr/lib/python2.6/dist-packages/pygeo/__init__.py", line 3, in from pygeo.vpyframe import display File "/usr/lib/python2.6/dist-packages/pygeo/vpyframe.py", line 38, in class display( visual.ui.display): AttributeError: 'module' object has no attribute 'ui' >>> /usr/lib/python2.6/dist-packages has the following directories and permissions.... drwxr-xr-x 2 root root 4096 2010-04-29 22:42 appindicator drwxr-xr-x 3 root root 4096 2010-04-29 22:43 apport drwxr-xr-x 2 root root 4096 2010-07-29 17:56 AppTools-3.3.0.egg-info drwxr-xr-x 3 root root 4096 2010-08-10 12:43 apt drwxr-xr-x 2 root root 4096 2010-04-29 22:43 aptdaemon drwxr-xr-x 2 root root 4096 2010-08-10 12:43 aptsources drwxr-xr-x 3 root root 4096 2010-04-29 22:43 AptUrl drwxr-xr-x 5 root root 4096 2010-07-28 21:14 butterfly drwxr-xr-x 5 root root 4096 2010-04-29 22:41 checkbox drwxr-xr-x 2 root root 4096 2010-04-29 22:43 checkbox_gtk drwxr-xr-x 2 root root 4096 2010-04-29 22:43 CommandNotFound drwxr-xr-x 2 root root 4096 2010-08-10 12:43 computerjanitor drwxr-xr-x 3 root root 4096 2010-04-29 22:42 configglue drwxr-xr-x 2 root root 4096 2010-04-29 22:42 configglue-0.2dev.egg-info drwxr-xr-x 7 root root 4096 2010-04-29 22:42 Crypto drwxr-xr-x 7 root root 4096 2010-04-29 22:44 desktopcouch drwxr-xr-x 2 root root 4096 2010-08-28 17:36 distribute-0.6.10.egg-info drwxr-xr-x 2 root root 4096 2010-08-10 12:43 DistUpgrade drwxr-xr-x 3 root root 4096 2010-08-28 17:36 DistUtilsExtra drwxr-xr-x 26 root root 4096 2010-07-29 17:56 enthought drwxr-xr-x 2 root root 4096 2010-07-29 17:56 EnthoughtBase-3.0.3.egg-info drwxr-xr-x 2 root root 4096 2010-07-29 17:56 EnvisageCore-3.1.1.egg-info drwxr-xr-x 2 root root 4096 2010-07-29 17:56 EnvisagePlugins-3.1.1.egg-info drwxr-xr-x 2 root root 4096 2010-08-15 11:38 GDebi drwxr-xr-x 7 root root 4096 2010-04-29 22:28 glchess drwxr-xr-x 2 root root 4096 2010-04-29 22:43 gnome_app_install-0.4.2ubuntu2.egg-info drwxr-xr-x 2 root root 4096 2010-04-29 22:43 GnomeCodecInstall drwxr-xr-x 3 root root 4096 2010-04-29 22:28 gnome_sudoku drwxr-xr-x 2 root root 4096 2010-08-28 18:02 Gnuplot drwxr-xr-x 3 root root 4096 2010-04-29 22:32 gst-0.10 drwxr-xr-x 3 root root 4096 2010-04-29 22:32 gtk-2.0 drwxr-xr-x 4 root root 4096 2010-07-28 21:14 gwibber drwxr-xr-x 2 root root 4096 2010-04-29 22:42 indicate drwxr-xr-x 3 root root 4096 2010-07-29 17:56 integrationtests drwxr-xr-x 2 root root 4096 2010-07-28 21:14 jockey drwxr-xr-x 2 root root 4096 2010-07-29 20:31 kiki drwxr-xr-x 3 root root 4096 2010-07-28 21:14 LanguageSelector drwxr-xr-x 3 root root 4096 2010-08-11 16:45 lxml drwxr-xr-x 2 root root 4096 2010-07-29 17:56 Mayavi-3.3.0.egg-info drwxr-xr-x 5 root root 4096 2010-04-29 22:42 mx *drwxr-xr-x 7 root root 4096 2010-08-28 18:03 Numeric drwxr-xr-x 13 root root 4096 2010-07-29 17:56 numpy* drwxr-xr-x 2 root root 4096 2010-08-28 18:03 NumTut drwxr-xr-x 2 root root 4096 2010-04-29 22:42 NvidiaDetector drwxr-xr-x 2 root root 4096 2010-04-29 22:41 oauth drwxr-xr-x 2 root root 4096 2010-04-29 22:41 oauth-1.0a.egg-info drwxr-xr-x 2 root root 4096 2010-04-29 22:43 Onboard drwxr-xr-x 2 root root 4096 2010-08-15 11:38 packagekit drwxr-xr-x 2 root root 12288 2010-08-28 18:02 PIL drwxr-xr-x 2 root root 4096 2010-07-28 21:14 pyatspi *drwxrwx--- 11 root lou 4096 2010-08-29 12:49 pygeo* drwxr-xr-x 2 root root 4096 2010-08-28 17:36 python_distutils_extra-2.18.egg-info drwxr-xr-x 2 root root 4096 2010-08-28 18:03 pytz drwxr-xr-x 2 root root 4096 2010-08-28 18:03 pytz-2010b.egg-info drwxr-xr-x 7 root root 4096 2010-08-11 16:45 reportlab drwxr-xr-x 16 root root 4096 2010-08-28 18:03 Scientific drwxr-xr-x 23 root root 4096 2010-08-28 18:03 scipy drwxr-xr-x 2 root root 4096 2010-04-29 22:43 ScreenResolution drwxr-xr-x 2 root root 4096 2010-04-29 22:42 serial drwxr-xr-x 4 root root 4096 2010-08-28 17:36 setuptools drwxr-xr-x 4 root root 4096 2010-08-15 11:38 softwareproperties drwxr-xr-x 2 root root 4096 2010-04-29 22:41 speechd drwxr-xr-x 2 root root 4096 2010-04-29 22:41 speechd_config drwxr-xr-x 9 root root 4096 2010-08-28 18:03 tables drwxr-xr-x 5 root root 4096 2010-04-29 22:42 telepathy drwxr-xr-x 2 root root 4096 2010-07-29 17:56 Traits-3.2.0.egg-info drwxr-xr-x 2 root root 4096 2010-07-29 17:56 TraitsBackendWX-3.2.0.egg-info drwxr-xr-x 2 root root 4096 2010-07-29 17:56 TraitsGUI-3.1.0.egg-info drwxr-xr-x 18 root root 4096 2010-04-29 22:43 twisted drwxr-xr-x 5 root root 4096 2010-07-28 21:14 ubuntuone drwxr-xr-x 2 root root 4096 2010-08-05 16:41 UbuntuSystemService drwxr-xr-x 10 root root 4096 2010-08-24 11:21 ubuntutweak drwxr-xr-x 2 root root 4096 2010-08-24 11:21 ubuntu_tweak-0.5.6.egg-info drwxr-xr-x 2 root root 4096 2010-04-29 22:41 ufw drwxr-xr-x 4 root root 4096 2010-08-15 11:38 UpdateManager drwxr-xr-x 4 root root 4096 2010-04-29 22:43 usbcreator drwxr-xr-x 2 root root 4096 2010-08-11 17:04 visual drwxr-xr-x 4 root root 4096 2010-07-29 17:49 wx-2.6-gtk2-unicode drwxr-xr-x 4 root root 4096 2010-07-29 17:49 wx-2.8-gtk2-unicode drwxr-xr-x 6 root root 4096 2010-07-29 20:31 wxglade drwxr-xr-x 2 root root 4096 2010-04-29 22:42 XKit drwxr-xr-x 3 root root 4096 2010-04-29 22:43 zope drwxr-xr-x 2 root root 4096 2010-04-29 22:43 zope.interface-3.5.3.egg-info does this help somewhat?? From arnodel at googlemail.com Tue Aug 31 03:01:22 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 31 Aug 2010 08:01:22 +0100 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> <7xpqwzzipz.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > aahz at pythoncraft.com (Aahz) writes: >> Possibly; IMO, people should not need to run timeit to determine basic >> algorithmic speed for standard Python datatypes. > > Indeed. Alex Stepanov (designer of C++ Standard Template Library) was > emphatic that algorithm complexity assertions should be part of the > interface of any STL function: > > http://www.sgi.com/tech/stl/drdobbs-interview.html > > He also said it should be part of the "unwritten contract" between the > module and its user, but I don't understand why he said "unwritten", > since in the C++ STL the complexity statements are part of the written > spec. The spec is written, not the contract :) -- Arnaud From maxwellhansen at hotmail.com Tue Aug 31 03:56:00 2010 From: maxwellhansen at hotmail.com (Maxwell Hansen) Date: Tue, 31 Aug 2010 00:56:00 -0700 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4c7ca51f$0$2504$815e3792@news.qwest.net> On 08/30/2010 05:05 PM, Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. > return stops execution of any code remaining in the function, but just out of curiosity, why do you need to do this? From nikos.the.gr33k at gmail.com Tue Aug 31 04:02:33 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Tue, 31 Aug 2010 01:02:33 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> <226e0eb2-d18e-4145-a39e-71f27979e717@i31g2000yqm.googlegroups.com> Message-ID: <0a7d62f1-6a0a-42d2-88c6-f0f42ef24aab@m1g2000yqo.googlegroups.com> On 30 ???, 20:48, Rami Chowdhury wrote: > On Mon, Aug 30, 2010 at 23:36, Nik the Greek wrote: > > > > > > > > > > > # initialize cookie > > cookie = SimpleCookie() > > cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > visitor = cookie.get('visitor') > > > This statement > > > if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > > spider|crawl)', host ) is None: > > > produces the following error: > > > ?/home/webville/public_html/cgi-bin/counter.py > > ? 93 # do not increment the counter if a Cookie is set to the > > visitors browser already > > ? 94 # > > =========================================================================== ====================================== > > ? 95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448| > > spider|crawl)', host ) is None: > > ? 96 > > ? 97 ? ? ? ? print visitor > > visitor = None, visitor.value undefined, re = > lib64/python2.4/re.pyc'>, re.search = , host = > > '178-128-217.dynamic.cyta.gr', builtin None = None > > > Why visitor.value is undefined? > > Because, as the traceback tells you, visitor is None. As you said, the > cookie is not recognized. Try inserting the following line at the top > of your script: > > print "Content-type:text/html\r\n\r\n", os.environ.get('HTTP_COOKIE', > 'NO COOKIE DATA') > > That should give you the value of the cookie, which might help you > debug why it is not being loaded. > > -- > Rami Chowdhury > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) Unfortunately it produces an Internal Server Error :( From __peter__ at web.de Tue Aug 31 04:03:54 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 31 Aug 2010 10:03:54 +0200 Subject: Functions continuing to ru after returning something? References: Message-ID: Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around > this. >>> n = 1 >>> def f(): ... global n ... try: ... return n ... finally: ... n += 1 ... >>> f() 1 >>> f() 2 >>> f() 3 However, I would prefer the generator as Aidan has shown because it doesn't rely on a global variable. Peter From nikos.the.gr33k at gmail.com Tue Aug 31 04:07:56 2010 From: nikos.the.gr33k at gmail.com (Nik the Greek) Date: Tue, 31 Aug 2010 01:07:56 -0700 (PDT) Subject: Problem checking an existing browser cookie References: <14868a50-f20d-49bb-8ed6-2c290619d2af@a36g2000yqc.googlegroups.com> <7ea71fa4-cf50-47fe-9cc6-366b0b5de215@j8g2000yqd.googlegroups.com> <8fe0540e-1818-4891-b165-f6731e918e6d@v41g2000yqv.googlegroups.com> <3ff780f9-1b6e-45ef-a530-0726eacb6064@g17g2000yqe.googlegroups.com> <809138c7-4ec3-404e-8863-dddb214c4100@s15g2000yqm.googlegroups.com> Message-ID: On 30 ???, 20:50, MRAB wrote: > On 30/08/2010 18:16, Nik the Greek wrote: > > > > > > > > > > > On 30 ???, 19:41, MRAB ?wrote: > >> On 30/08/2010 04:33, Nik the Greek wrote: > > >>> On 30 ???, 06:12, MRAB ? ?wrote: > > >>>> This part: > > >>>> ? ? ? ?( not mycookie or mycookie.value != 'nikos' ) > > >>>> is false but this part: > > >>>> ? ? ? ?re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None > > >>>> is true because host doesn't contain any of those substrings. > > >>> So, the if code does executed because one of the condition is true? > > >>> How should i write it? > > >>> I cannot think clearly on this at all. > > >>> I just wan to tell it to get executed ?ONLY IF > > >>> the cookie values is not 'nikos' > > >>> or ( don't knwo if i have to use and or 'or' here) > > >>> host does not contain any of the substrings. > > >>> What am i doign wrong?! > > >> It might be clearer if you reverse the condition and say: > > >> ? ? ? me_visiting = ... > >> ? ? ? if not me_visiting: > >> ? ? ? ? ? ... > > > I don't understand what are you trying to say > > > Please provide a full example. > > > You mean i should try it like this? > > > unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn| > > yandex|13448|spider|crawl)', host ) not None: > > > But isnt it the same thing like the if? > > My point is that the logic might be clearer to you if you think first > about how you know when you _are_ the visitor. Well my idea was to set a cookie on my browser with the name visitor and a value of "nikos" and then check each time that cooki. if value is "nikos" then dont count! I could also pass an extra url string like http://webville.gr?show=nikos and check that but i dont like the idea very much of giving an extra string each time i want to visit my webpage. So form the 2 solution mentioned the 1st one is better but cant come into action for some reason. Aprt form those too solution i cant think of anyhting else that would identify me and filter me out of the actual guest of my website. I'm all ears if you can think of something else. From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 31 04:18:56 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 31 Aug 2010 10:18:56 +0200 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4c7cbacb$0$4541$426a34cc@news.free.fr> Peter Otten a ?crit : >>>> n = 1 >>>> def f(): > ... global n > ... try: > ... return n > ... finally: > ... n += 1 > ... The same without a global: def f(_n=[0]): try: return _n[0] finally: _n[0] += 1 But yeps, using a generator would be better. From sandricionut at yahoo.com Tue Aug 31 04:25:50 2010 From: sandricionut at yahoo.com (sandric ionut) Date: Tue, 31 Aug 2010 01:25:50 -0700 (PDT) Subject: sendmail error Message-ID: <284495.60490.qm@web51302.mail.re2.yahoo.com> Hello: I have a script for sending email from python (it is attached bellow). When I am launching the script I get the error: TypeError: cannot concatenate 'str' and 'type' objects if I use sys.argv[1], but if I input from the begging an email address like "email at email.com", the script is working OK What could be the problem? Thank you, Ionut import mesaj = email.MIMEMultipart.MIMEMultipart() fromEmail = sys.argv[ toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ mesaj[ mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ atasament = r"Date"] = email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = email.MIMEBase.MIMEBase( atasamentP.set_payload(open(atasament, email.Encoders.encode_base64(atasamentP) atasamentP.add_header( mesaj.attach(atasamentP) mesaj.attach(email.MIMEText.MIMEText( smtpObj = smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attachement; filename="%s"'% os.path.basename(atasament))"Email transmis la data: ", email.Utils.formatdate(localtime=False)))"192.168.1.2")try smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ smtplib.SMTPException -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Tue Aug 31 04:25:52 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 31 Aug 2010 01:25:52 -0700 Subject: Functions continuing to ru after returning something? References: Message-ID: <7x62yrtchb.fsf@ruckus.brouhaha.com> Bradley Hintze writes: > my_var = 5 > def my_function(): > return my_var > my_var +=1 def my_function(): temp = my_var my_var += 1 return temp From brendan.simon at etrix.com.au Tue Aug 31 04:49:53 2010 From: brendan.simon at etrix.com.au (Brendan Simon (eTRIX)) Date: Tue, 31 Aug 2010 18:49:53 +1000 Subject: Can't find elements using ElementTree find method Message-ID: <4C7CC231.1040403@etrix.com.au> I am trying to use ElementTree (with Python 2.7) and can't seem to find elements at the top level. The find() and findall() methods seem to find elements within the top level, but not if it the elements are at the top level. How do I find top level elements ?? Here is my code. import xml.etree.ElementTree as ET xml = '''\ Fred Australia ''' root = ET.fromstring( xml ) ### This pattern is not found :( comps = root.find( './/components' ) ### These patterns are found ok :) comp = root.find( './/component' ) name = root.find( './/name' ) print 'comps =', comps print 'comp =', comp print 'name =', name Thanks, Brendan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitinpawar432 at gmail.com Tue Aug 31 04:57:21 2010 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Tue, 31 Aug 2010 14:27:21 +0530 Subject: Can't find elements using ElementTree find method In-Reply-To: <4C7CC231.1040403@etrix.com.au> References: <4C7CC231.1040403@etrix.com.au> Message-ID: Try using getroot() I think your root is components so its searching in root On Tue, Aug 31, 2010 at 2:19 PM, Brendan Simon (eTRIX) < brendan.simon at etrix.com.au> wrote: > I am trying to use ElementTree (with Python 2.7) and can't seem to find > elements at the top level. The find() and findall() methods seem to find > elements within the top level, but not if it the elements are at the top > level. > > How do I find top level elements ?? > Here is my code. > > import xml.etree.ElementTree as ET > > xml = '''\ > > > > Fred > Australia > > > ''' > > root = ET.fromstring( xml ) > > ### This pattern is not found :( > comps = root.find( './/components' ) > > ### These patterns are found ok :) > comp = root.find( './/component' ) > name = root.find( './/name' ) > > print 'comps =', comps > print 'comp =', comp > print 'name =', name > > > Thanks, Brendan. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Aug 31 05:00:41 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Aug 2010 11:00:41 +0200 Subject: Can't find elements using ElementTree find method In-Reply-To: <4C7CC231.1040403@etrix.com.au> References: <4C7CC231.1040403@etrix.com.au> Message-ID: Brendan Simon (eTRIX), 31.08.2010 10:49: > I am trying to use ElementTree (with Python 2.7) and can't seem to find > elements at the top level. The find() and findall() methods seem to > find elements within the top level, but not if it the elements are at > the top level. > > How do I find top level elements ?? > Here is my code. > > import xml.etree.ElementTree as ET > > xml = '''\ > > > > Fred > Australia > > > ''' > > root = ET.fromstring( xml ) > > ### This pattern is not found :( > comps = root.find( './/components' ) "." matches the current element, so the path expression looks for all "components" nodes *below* the current element. You can either wrap the root in an ElementTree and search globally (i.e. without the leading "."), or you can test the root node yourself. Stefan From thomas at jollybox.de Tue Aug 31 06:23:24 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 12:23:24 +0200 Subject: PyGeo In-Reply-To: <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> Message-ID: <201008311223.24696.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to L to exclaim: > Traceback (most recent call last): > File > "/usr/lib/python2.6/dist-packages/pygeo/examples/real/dandelinspheres2.py", > line 2, in > from pygeo.base.abstract_elements_real import _Sphere, _Point > File "/usr/lib/python2.6/dist-packages/pygeo/__init__.py", line 3, in > > from pygeo.vpyframe import display > File "/usr/lib/python2.6/dist-packages/pygeo/vpyframe.py", line 38, > in > class display( visual.ui.display): > AttributeError: 'module' object has no attribute 'ui' THAT's the information I was waiting for. So, it looks like everything is working together, except that the visual module appears to have changed somewhat since PyGeo was written. Importing "visual" within PyGeo appears to have worked, but "visual.ui" doesn't exist. After having a brief look at the documentation, I found no mention of a "ui" object, but there appears to be visual.display -- so, if you wanted to port the package to the latest VPython, that would be a place to start: replace "visual.ui.display" with "visual.display", and try again. And the fix the next problem, and so on, until it works, when you can send a patch to the old maintainer. http://www.vpython.org/webdoc/visual/index.html - Thomas From brendan.simon at etrix.com.au Tue Aug 31 06:51:53 2010 From: brendan.simon at etrix.com.au (Brendan Simon (eTRIX)) Date: Tue, 31 Aug 2010 20:51:53 +1000 Subject: Can't find elements using ElementTree find method In-Reply-To: References: <4C7CC231.1040403@etrix.com.au> Message-ID: <4C7CDEC9.8080805@etrix.com.au> I can't use getroot() when using fromstring() -- as fromstring() returns an Element, not an ElementTree object. Yes, my root is the 'components' element, but find() seems to insist on searching for sub-elements. Ideally, I would like root.find('components') or root.find('./components') to find the components element at the top-level. I'd also like to be able to do root.find('./components/component') or root.find('./components/component/name') and so on. I guess I just have to check that root.tag == 'components' first, then search for './component', './component/name' and so on. It's a bit ugly, but heaps better than using minidom :) Cheers, Brendan. On 31/08/10 6:57 PM, Nitin Pawar wrote: > Try using getroot() > > I think your root is components so its searching in root > > On Tue, Aug 31, 2010 at 2:19 PM, Brendan Simon (eTRIX) > > wrote: > > I am trying to use ElementTree (with Python 2.7) and can't seem to > find elements at the top level. The find() and findall() methods > seem to find elements within the top level, but not if it the > elements are at the top level. > > How do I find top level elements ?? > Here is my code. > > import xml.etree.ElementTree as ET > > xml = '''\ > > > > Fred > Australia > > > ''' > > root = ET.fromstring( xml ) > > ### This pattern is not found :( > comps = root.find( './/components' ) > > ### These patterns are found ok :) > comp = root.find( './/component' ) > name = root.find( './/name' ) > > print 'comps =', comps > print 'comp =', comp > print 'name =', name > > > Thanks, Brendan. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Nitin Pawar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Aug 31 07:49:29 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 31 Aug 2010 07:49:29 -0400 Subject: sendmail error In-Reply-To: <284495.60490.qm@web51302.mail.re2.yahoo.com> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> Message-ID: <4C7CEC49.9030209@ieee.org> sandric ionut wrote: > Hello: > > I have a script for sending email from python (it is attached bellow). When I am > launching the script I get the error: > TypeError: cannot concatenate 'str' and 'type' objects if I use sys.argv[1], but > if I input from the begging an email address like "email at email.com", the script > is working OK > > What could be the problem? > > Thank you, > > Ionut > > import > mesaj = email.MIMEMultipart.MIMEMultipart() > fromEmail = sys.argv[ > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > mesaj[ > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > atasament = r"Date"] = > email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = > email.MIMEBase.MIMEBase( > atasamentP.set_payload(open(atasament, > email.Encoders.encode_base64(atasamentP) > atasamentP.add_header( > mesaj.attach(atasamentP) > mesaj.attach(email.MIMEText.MIMEText( > smtpObj = > smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attachement; > filename="%s"'% os.path.basename(atasament))"Email transmis la data: ", > email.Utils.formatdate(localtime=False)))"192.168.1.2")try > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ > smtplib.SMTPException > > > Three things: When quoting code, do it exactly, and without wordwrap in your mail program. There are so many typos in that code sample that it's useless, presumably because you didn't use copy/paste. When quoting an error message, get it all. Since you omit the stacktrace part, we can't tell what line might be giving you that error. Once you've noticed which line, just examine the types of each of the elements you're combining. If you're using the + operator, and the left operand is a string, then the right one must also be string. Figure out why it's not and you have your own answer. DaveA > > From giacomo.boffi at polimi.it Tue Aug 31 08:21:32 2010 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Tue, 31 Aug 2010 14:21:32 +0200 Subject: PyGeo References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> Message-ID: <86bp8j7z1v.fsf@aiuole.stru.polimi.it> L writes: > also the PyGeo readme text mentions Numerical python (I think it > means Numeric, but I also have NumPy installed) afaict, Numerical python is numpy --- if you look at pygeo home page, the reference to Numerical python is a link to numpy home page on the contrary, there is no "import numpy" in all the sources of pygeo, and a couples or so of "import Numeric", so that the situation is unclear aiuole/../PyGeo-1.0a1 $ find build| grep py$ | xargs grep -n import'.*'numpy aiuole/../PyGeo-1.0a1 $ find build| grep py$ | xargs grep -n import'.*'Numeric build/lib.linux-i686-2.6/pygeo/base/pygeomath.py:1:import Numeric as N build/lib.linux-i686-2.6/pygeo/base/wiresphere.py:2:import Numeric aiuole/../PyGeo-1.0a1 $ to complicate matters, it is not possible to install python-numeric using the apt system on debian unstable i don't know if it is possible to build numeric against the default python (2.6) on my system, further i don't know if it is worthwhile because, at a first sight, it looks like pygeo does not use advanced features of numeric, and replacing numeric with numpy should be very easy From malaclypse2 at gmail.com Tue Aug 31 08:24:55 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 31 Aug 2010 08:24:55 -0400 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: On Mon, Aug 30, 2010 at 7:42 PM, Aahz wrote: > Possibly; IMO, people should not need to run timeit to determine basic > algorithmic speed for standard Python datatypes. http://wiki.python.org/moin/TimeComplexity takes a stab at it. IIRC, last time this came up, there was some resistance to making promises about time complexity in the official docs, since that would make those numbers part of the language, and thus binding on other implementations. -- Jerry From sandricionut at yahoo.com Tue Aug 31 08:57:14 2010 From: sandricionut at yahoo.com (sandric ionut) Date: Tue, 31 Aug 2010 05:57:14 -0700 (PDT) Subject: Fw: sendmail error In-Reply-To: <4C7CEC49.9030209@ieee.org> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <4C7CEC49.9030209@ieee.org> Message-ID: <191591.90081.qm@web51308.mail.re2.yahoo.com> ----- Forwarded Message ---- From: sandric ionut To: Dave Angel Sent: Tue, August 31, 2010 3:56:40 PM Subject: Re: sendmail error ________________________________ From: Dave Angel To: sandric ionut Cc: Python List Sent: Tue, August 31, 2010 2:49:29 PM Subject: Re: sendmail error The code was COPY and PASTE -> presume wrong ?? When quoting an error message, get it all.? Since you omit the stacktrace part, we can't tell what line might be giving you that error That is all the error code!!! ??? Once you've noticed which line, just examine the types of each of the elements you're combining.? If you're using the + operator, and the left operand is a string, then the right one must also be string.? Figure out why it's not and you have your own answer Do you really think that I didn't do it? What a... response. This + or , is really USELESS. Please don't bother to send useless replays This is the line where I get the error: smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) I.S. DaveA >? ? ? ? sandric ionut wrote: > Hello: > > I have a script for sending email from python (it is attached bellow). When I >am launching the script I get the error: > TypeError: cannot concatenate 'str' and 'type' objects if I use sys.argv[1], >but if I input from the begging an email address like "email at email.com", the >script is working OK > > What could be the problem? > > Thank you, > > Ionut > > import > mesaj = email.MIMEMultipart.MIMEMultipart() > fromEmail = sys.argv[ > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > mesaj[ > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > atasament = r"Date"] = >email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = >email.MIMEBase.MIMEBase( > atasamentP.set_payload(open(atasament, > email.Encoders.encode_base64(atasamentP) > atasamentP.add_header( > mesaj.attach(atasamentP) > mesaj.attach(email.MIMEText.MIMEText( > smtpObj = >smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attachement; > >? filename="%s"'% os.path.basename(atasament))"Email transmis la data: ", >email.Utils.formatdate(localtime=False)))"192.168.1.2")try > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ >smtplib.SMTPException > > >? ? Three things:? When quoting code, do it exactly, and without wordwrap in your mail program.? There are so many typos in that code sample that it's???? useless, presumably because you didn't use copy/paste -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.kapps at web.de Tue Aug 31 09:41:23 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Tue, 31 Aug 2010 15:41:23 +0200 Subject: Fw: sendmail error In-Reply-To: <191591.90081.qm@web51308.mail.re2.yahoo.com> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <4C7CEC49.9030209@ieee.org> <191591.90081.qm@web51308.mail.re2.yahoo.com> Message-ID: <4C7D0683.9000409@web.de> sandric ionut wrote: >> Three things: When quoting code, do it exactly, and without wordwrap >> in your mail program. There are so many typos in that code sample that >> it's useless, presumably because you didn't use copy/paste > > The code was COPY and PASTE -> presume wrong > >> When quoting an error message, get it all. Since you omit the >> stacktrace part, we can't tell what line might be giving you that error > > That is all the error code!!! > >> Once you've noticed which line, just examine the types of each of >> the elements you're combining. If you're using the + operator, and the >> left operand is a string, then the right one must also be string. >> Figure out why it's not and you have your own answer > > Do you really think that I didn't do it? What a... response. This + or , > is really USELESS. Please don't bother to send useless replays > This is the line where I get the error: smtpObj.sendmail(fromEmail, > toEmail, mesaj.as_string()) Indeed, what a response. But from you. Do you always attack people who tried to help you? Dave Angel, gave you a very useful hint on how to debug such errors. In particular, he asked you to paste the *full* traceback. And if your mail/news client messes up the code so heavily, it's probably time to move to a better client. And the mention of + is not useless. If you would have tried a little harder, you would probably find, that concatenating a string and an exception object, gives exactly the error you got. So, the problem is probably here: print "eroare: " + smtplib.SMTPException Instead you want something like: except smtplib.SMTPException, msg print "eroare: " + msg If you are sure, that's not the line which gave the error, again, post the *full* traceback. Next time, show a little more civility and follow the advices you got. "Help us, to help you." is the word. HTH From thomas at jollybox.de Tue Aug 31 09:46:58 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 15:46:58 +0200 Subject: sendmail error In-Reply-To: <284495.60490.qm@web51302.mail.re2.yahoo.com> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> Message-ID: <201008311546.59595.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to sandric ionut to exclaim: > Hello: > > I have a script for sending email from python (it is attached bellow). When > I am launching the script I get the error: > TypeError: cannot concatenate 'str' and 'type' objects if I use > sys.argv[1], but if I input from the begging an email address like > "email at email.com", the script is working OK > > What could be the problem? > > Thank you, > > Ionut > > import > mesaj = email.MIMEMultipart.MIMEMultipart() > fromEmail = sys.argv[ > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > mesaj[ > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > atasament = r"Date"] = > email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = > email.MIMEBase.MIMEBase( > atasamentP.set_payload(open(atasament, > email.Encoders.encode_base64(atasamentP) > atasamentP.add_header( > mesaj.attach(atasamentP) > mesaj.attach(email.MIMEText.MIMEText( > smtpObj = > smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attach > ement; filename="%s"'% os.path.basename(atasament))"Email transmis la data: > ", email.Utils.formatdate(localtime=False)))"192.168.1.2")try > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ > smtplib.SMTPException I struggle to imagine what one might do to a piece of code to garble it this badly. If this was actually the script you're trying to run, then it would have blown up in your face with a angry SyntaxError, not the helpful TypeError you quoted. As far as I can see, you never actually use sys.argv[1], so this can't be the right code. To paraphrase what you failed to spell correctly in your other message, please don't bother sending useless inquiries to this list. If you want to get a useful reply, please: - Quote the code correctly. Before sending, check that it actually makes sense. The above is quite simply nothing like Python. - Quote the entire stack trace and error message. You might have looked at it already, but we haven't. This information is not useless! Also, when replying: - Quote properly. While top posting is discouraged, the most important bit is to clearly distinguish quoted material from new material. Make it possible from the structure of the message you're sending which parts you wrote and which parts you're just quoting. - Keep your reply on-list. - Thomas From aahz at pythoncraft.com Tue Aug 31 10:09:30 2010 From: aahz at pythoncraft.com (Aahz) Date: 31 Aug 2010 07:09:30 -0700 Subject: Performance: sets vs dicts. References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: In article , Jerry Hill wrote: >On Mon, Aug 30, 2010 at 7:42 PM, Aahz wrote: >> >> Possibly; IMO, people should not need to run timeit to determine basic >> algorithmic speed for standard Python datatypes. > >http://wiki.python.org/moin/TimeComplexity takes a stab at it. IIRC, >last time this came up, there was some resistance to making promises >about time complexity in the official docs, since that would make >those numbers part of the language, and thus binding on other >implementations. I'm thoroughly aware of that page and updated it yesterday to make it easier to find. ;-) However, I think there are some rock-bottom basic guarantees we can make regardless of implementation. Does anyone seriously think that an implementation would be accepted that had anything other than O(1) for index access into tuples and lists? Dicts that were not O(1) for access with non-pathological hashing? That we would accept sets having O() performance worse than dicts? I suggest that we should agree on these guarantees and document them in the core. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells From stefan_ml at behnel.de Tue Aug 31 10:19:49 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Aug 2010 16:19:49 +0200 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: Jerry Hill, 31.08.2010 14:24: > On Mon, Aug 30, 2010 at 7:42 PM, Aahz wrote: >> Possibly; IMO, people should not need to run timeit to determine basic >> algorithmic speed for standard Python datatypes. > > http://wiki.python.org/moin/TimeComplexity takes a stab at it. IIRC, > last time this came up, there was some resistance to making promises > about time complexity in the official docs, since that would make > those numbers part of the language, and thus binding on other > implementations. The docs start getting clearer about what's language specification and what's implementation specific to CPython, so that would just add another couple of CPython-only bits to what's there already. Although I do consider facts like list indexing being O(1) pretty much at the language-rather-than-implementation level. Most Python code simply expects that and it would degrade a lot of code if that ever changed in whatever implementation. Stefan From hobson42 at gmaiil.com Tue Aug 31 10:42:25 2010 From: hobson42 at gmaiil.com (Ian) Date: Tue, 31 Aug 2010 15:42:25 +0100 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: <4C7D14D1.9060702@gmaiil.com> On 31/08/2010 15:09, Aahz wrote: > I suggest that we should agree on these guarantees and document them in > the core. I suspect that documenting them will be the easy part ;) From malaclypse2 at gmail.com Tue Aug 31 10:45:57 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 31 Aug 2010 10:45:57 -0400 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: On Tue, Aug 31, 2010 at 10:09 AM, Aahz wrote: > I suggest that we should agree on these guarantees and document them in > the core. I can't get to the online python-dev archives from work (stupid filter!) so I can't give you a link to the archives, but the original thread that resulted in the creation of that wiki page was started on March 9th, 2008 and was titled "Complexity documentation request". At the time, opposition to formally documenting this seemed pretty widespread, including from yourself and Guido. You've obviously changed your mind on the subject, so maybe it's something that would be worth revisiting, assuming someone wants to write the doc change. -- Jerry From AmFreak at web.de Tue Aug 31 10:49:36 2010 From: AmFreak at web.de (AmFreak at web.de) Date: Tue, 31 Aug 2010 16:49:36 +0200 Subject: Saving (unusual) linux filenames Message-ID: Hi, i have a script that reads and writes linux paths in a file. I save the path (as unicode) with 2 other variables. I save them seperated by "," and the "packets" by newlines. So my file looks like this: path1, var1A, var1B path2, var2A, var2B path3, var3A, var3B .... this works for "normal" paths but as soon as i have a path that does include a "," it breaks. The problem now is that (afaik) linux allows every char (aside from "/" and null) to be used in filenames. The only solution i can think of is using null as a seperator, but there have to a cleaner version ? Thanks for any help Biene_Maja From romsok.tech at gmail.com Tue Aug 31 10:58:04 2010 From: romsok.tech at gmail.com (Roman Sokolyuk) Date: Tue, 31 Aug 2010 10:58:04 -0400 Subject: Stackless Python and EVE Online Message-ID: Hi, I am new to Python and I wanted to understand something... The EVE Online Client is build using Stackless Python So when I install the client on my machine, how doe sit get run if I do not have Python installed? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollybox.de Tue Aug 31 11:05:32 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 17:05:32 +0200 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: <201008311705.32747.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to Roman Sokolyuk to exclaim: > Hi, > > I am new to Python and I wanted to understand something... > > The EVE Online Client is build using Stackless Python > > So when I install the client on my machine, how doe sit get run if I do not > have Python installed? If this program uses Stackless, and you do not have Stackless installed system-wide, then the program includes Stackless. This is probably not a bad idea, since the likelihood of Stackless Python being installed is realtively small. Stackless Python is not the same as Python -- as far as I know, it adds some new features not found in the actual Python language to the "PyPy" implementation of the language. From benjamin.kaplan at case.edu Tue Aug 31 11:10:16 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 31 Aug 2010 11:10:16 -0400 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: On Tuesday, August 31, 2010, Roman Sokolyuk wrote: > Hi, > > I am new to Python and I wanted to understand something... > The EVE Online Client is build using Stackless Python > So when I install the client on my machine, how doe sit get run if I do not have Python installed? > We call it "freezing" the program. There are several tools that do this with py2exe being the most popular. These tools create an executable that includes a bundled python interpreter along with all the scripts and modules needed to run the program. > Thanks. From invalid at invalid.invalid Tue Aug 31 11:22:00 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 31 Aug 2010 15:22:00 +0000 (UTC) Subject: Saving (unusual) linux filenames References: Message-ID: On 2010-08-31, AmFreak at web.de wrote: > Hi, > > i have a script that reads and writes linux paths in a file. I save the > path (as unicode) with 2 other variables. I save them seperated by "," and > the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B > .... > > this works for "normal" paths but as soon as i have a path that does > include a "," it breaks. The problem now is that (afaik) linux allows > every char (aside from "/" and null) to be used in filenames. The only > solution i can think of is using null as a seperator, but there have to a > cleaner version ? The normal thing to do is to escape the delimiter when it appears in data. There are lots of plenty of escaping standards to choose from, and some of them (e.g. the one used for URLs) are already present in various bits of Python's standard library. -- Grant Edwards grant.b.edwards Yow! ... the HIGHWAY is at made out of LIME JELLO and gmail.com my HONDA is a barbequeued OYSTER! Yum! From robert.kern at gmail.com Tue Aug 31 11:36:23 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 31 Aug 2010 10:36:23 -0500 Subject: PyGeo In-Reply-To: <86bp8j7z1v.fsf@aiuole.stru.polimi.it> References: <4c7a17d2$0$3030$afc38c87@news.optusnet.com.au> <4c7b52e0$0$1903$afc38c87@news.optusnet.com.au> <4c7c9e7e$0$28492$afc38c87@news.optusnet.com.au> <86bp8j7z1v.fsf@aiuole.stru.polimi.it> Message-ID: On 8/31/10 7:21 AM, Giacomo Boffi wrote: > L writes: > >> also the PyGeo readme text mentions Numerical python (I think it >> means Numeric, but I also have NumPy installed) > > afaict, Numerical python is numpy --- if you look at pygeo home page, > the reference to Numerical python is a link to numpy home page > > on the contrary, there is no "import numpy" in all the sources of > pygeo, and a couples or so of "import Numeric", so that the situation > is unclear numpy supercedes the older Numeric package. However, "numpy" used to be a colloquial name for Numeric, too. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From python at bdurham.com Tue Aug 31 11:42:07 2010 From: python at bdurham.com (python at bdurham.com) Date: Tue, 31 Aug 2010 11:42:07 -0400 Subject: Find closest matching string based on collection of strings in list/dict/set Message-ID: <1283269327.22774.1392642985@webmail.messagingengine.com> I'm parsing a simple, domain specific scripting language that has commands like the following: *page, *title, *text, *footer, etc. There are about 100 of these '*' commands. When we see a command that we don't recognize, I would like to find the closest match possible (from a list of all legal commands) and include this suggestion in our diagnostic output. I'm not sure what you would call the type of algorithm I'm looking for: closest matching string or auto-correct? Any suggestions on algorithms or python libraries that would help me do what I'm looking for? Here's my short-list of ideas based on my research so far: - Soundex - Lawrence Philips' Metaphone Algorithm (from aspell?) - Edit Distance Algorithm - Levenstein Word Distance Any suggestions, comments on the above techniques, or ideas on a simpler algorithm for finding close string matches based on a list, dict, or set of possible strings? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 31 12:19:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 17:19:25 +0100 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D2B8D.20401@mrabarnett.plus.com> On 31/08/2010 15:49, AmFreak at web.de wrote: > Hi, > > i have a script that reads and writes linux paths in a file. I save the > path (as unicode) with 2 other variables. I save them seperated by "," > and the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B > .... > > this works for "normal" paths but as soon as i have a path that does > include a "," it breaks. The problem now is that (afaik) linux allows > every char (aside from "/" and null) to be used in filenames. The only > solution i can think of is using null as a seperator, but there have to > a cleaner version ? > You could use a tab character '\t' instead. From alekseymv at gmail.com Tue Aug 31 12:33:49 2010 From: alekseymv at gmail.com (Aleksey) Date: Tue, 31 Aug 2010 09:33:49 -0700 (PDT) Subject: Optimising literals away References: Message-ID: <69a8fbbc-5f45-491a-adf3-2fb5a4d79660@s9g2000yqd.googlegroups.com> On Aug 30, 10:38?pm, Tobias Weber wrote: > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. > > def m(arg): > ? if arg & set([1,2,3]): > ? ? return 4 > > Is the set created every time the method is called? What about a > frozenset? Or tuple vs list? After how many calls per second does it pay > to save it at the module level? Would anybody else find this ugly? > > Also I never profiled the regular expression cache... > > -- > ? Tobias Weber I test time creation of any types ang get next result: dictionary = 393 000 * 10 frozenset = 267 000 * 10 list = 519 000 * 10 set = 268 000 * 10 tuple = 5 935 500 * 10 global assign = 5 882 700 * 10 All results multiple by 10 becouse i do 10 creations in one loop and count loops per second. As you see create global variable is more faster (20 times) then create list and from it create set! Assigments is ~ 5 882 000*10,>>> set creation is 268 000*10 My test system is Ubuntu 10.04, Dell Inspiron 1525, Core2Duo, T8300, 2Gb , Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3]. I make tests with XPyLIB.timetest module. (XPyLIB hosted at sourceforge - http://sourceforge.net/apps/trac/xpylib/wiki/CookBook/TimeTest) Assign global (pre declared by "global") function is next (N - is a times of repeating): gset = set((1,2,3)) def t_set_assign_global(ntimes = N, funcloop=u'funcloop', excludecall=u'excludecall'): """Set assigment from global : global=(1,2,3); loop a = global 10 times in while. @UID@ e710b888-bacd-4248-9ff7-1f7a348e1c8f @author@ Mazhugin Aleksey @score_common@ 1 """ a = 0 global gset while ntimes > 0: a = gset a = gset a = gset a = gset a = gset a = gset a = gset a = gset a = gset a = gset ntimes -= 1 Set function is next: def t_set_create(ntimes = N, funcloop=u'funcloop', excludecall=u'excludecall'): """Set creation : t=(1,2,3); loop a = set(t) 10 times in while. @UID@ a021a756-f9a5-44ec-b9e6-e5532b56c09f @author@ Mazhugin Aleksey @score_common@ 1 """ a = 0 t = (1,2,3) while ntimes > 0: a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) a = set(t) ntimes -= 1 Also i test regular expression compiled pattern vs non-compiled: compiled = 343 000*2 not compiled = 164 000*2 Functions is next: patt5 = u'*.tmp,*.pyc,*.pyo,*.bak,*.log' path1 = u'/home/user/project/src/file.ext' path2 = u'/home/user/project/logs/debug.log' def t_rematch(ntimes=10, funcloop=u'funcloop', excludecall='excludecall'): """ Compiled. @UID@ 665f4014-9c11-4668-baae-e49230027bd4 @author@ Mazhugin Aleksey @score_common@ 1 """ ci = patt5.replace(u'\\',u'\\\\').replace(u'|',u'\ \|').replace(u'.',u'\\.').replace(u'*',u'.*'). \ replace(u'?',u'.?').replace(u'$',u'\\$').replace(u'^',u'\ \^').replace(u'{',u'\\{'). \ replace(u'(',u'\\(').replace(u'[',u'\\[').replace(u'+',u'\\ +').split(u',') repat = u'|'.join([u'('+i+u'$)' for i in ci]) rec = re.compile(repat) r = 0 while ntimes: r = rec.match(path1) is not None r = rec.match(path2) is not None ntimes -= 1 def t_rematch_string(ntimes=10, funcloop=u'funcloop', excludecall='excludecall'): """ Not compiled. @UID@ 80fa1ca3-5d51-4f6e-8ac2-4ccafe4c1160 @author@ Mazhugin Aleksey @score_common@ 1 """ ci = patt5.replace(u'\\',u'\\\\').replace(u'|',u'\ \|').replace(u'.',u'\\.').replace(u'*',u'.*'). \ replace(u'?',u'.?').replace(u'$',u'\\$').replace(u'^',u'\ \^').replace(u'{',u'\\{'). \ replace(u'(',u'\\(').replace(u'[',u'\\[').replace(u'+',u'\\ +').split(u',') repat = u'|'.join([u'('+i+u'$)' for i in ci]) #rec = re.compile(repat) r = 0 while ntimes: r = re.match(repat, path1) is not None r = re.match(repat, path2) is not None ntimes -= 1 From tim.arnold at sas.com Tue Aug 31 12:38:41 2010 From: tim.arnold at sas.com (Tim Arnold) Date: Tue, 31 Aug 2010 12:38:41 -0400 Subject: triangle python user's group? References: <3c95f09c-1fa7-4c63-9f13-3f2776c2ab41@j18g2000yqd.googlegroups.com> Message-ID: "Albert Hopkins" wrote in message news:mailman.219.1283200967.29448.python-list at python.org... > On Mon, 2010-08-30 at 12:38 -0700, Tim Arnold wrote: >> Hi, >> Is there a python users group in the Research Triangle Park area >> (North Carolina, USA)? > > Google "triangle python user's group" > thanks for the pointer.... --Tim From invalid at invalid.invalid Tue Aug 31 12:58:41 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 31 Aug 2010 16:58:41 +0000 (UTC) Subject: Saving (unusual) linux filenames References: Message-ID: On 2010-08-31, MRAB wrote: > On 31/08/2010 15:49, AmFreak at web.de wrote: >> Hi, >> >> i have a script that reads and writes linux paths in a file. I save the >> path (as unicode) with 2 other variables. I save them seperated by "," >> and the "packets" by newlines. So my file looks like this: >> path1, var1A, var1B >> path2, var2A, var2B >> path3, var3A, var3B >> .... >> >> this works for "normal" paths but as soon as i have a path that does >> include a "," it breaks. The problem now is that (afaik) linux allows >> every char (aside from "/" and null) to be used in filenames. The only >> solution i can think of is using null as a seperator, but there have to >> a cleaner version ? > > You could use a tab character '\t' instead. That just breaks with a different set of filenames. -- Grant Edwards grant.b.edwards Yow! ! Everybody out of at the GENETIC POOL! gmail.com From jeremy at jeremysanders.net Tue Aug 31 12:58:55 2010 From: jeremy at jeremysanders.net (Jeremy Sanders) Date: Tue, 31 Aug 2010 17:58:55 +0100 Subject: Saving (unusual) linux filenames References: Message-ID: AmFreak at web.de wrote: > i have a script that reads and writes linux paths in a file. I save the > path (as unicode) with 2 other variables. I save them seperated by "," and > the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B If you're generating the file and it is safe to do so (you're not getting the data from the internet), you could use repr((path1, v1, v2)) to save the line to the file and eval to interpret back the tuple. Alternatively you could use // as a separator, making sure that you replace multiple slashes in the path which a single slash (which are equivalent). Jeremy From python at mrabarnett.plus.com Tue Aug 31 13:13:44 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 18:13:44 +0100 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D3848.90106@mrabarnett.plus.com> On 31/08/2010 17:58, Grant Edwards wrote: > On 2010-08-31, MRAB wrote: >> On 31/08/2010 15:49, AmFreak at web.de wrote: >>> Hi, >>> >>> i have a script that reads and writes linux paths in a file. I save the >>> path (as unicode) with 2 other variables. I save them seperated by "," >>> and the "packets" by newlines. So my file looks like this: >>> path1, var1A, var1B >>> path2, var2A, var2B >>> path3, var3A, var3B >>> .... >>> >>> this works for "normal" paths but as soon as i have a path that does >>> include a "," it breaks. The problem now is that (afaik) linux allows >>> every char (aside from "/" and null) to be used in filenames. The only >>> solution i can think of is using null as a seperator, but there have to >>> a cleaner version ? >> >> You could use a tab character '\t' instead. > > That just breaks with a different set of filenames. > How many filenames contain control characters? Surely that's a bad idea. From sandricionut at yahoo.com Tue Aug 31 13:14:03 2010 From: sandricionut at yahoo.com (sandric ionut) Date: Tue, 31 Aug 2010 10:14:03 -0700 (PDT) Subject: sendmail error In-Reply-To: <201008311546.59595.thomas@jollybox.de> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <201008311546.59595.thomas@jollybox.de> Message-ID: <492442.26155.qm@web51305.mail.re2.yahoo.com> This is the only message that I will send to this list regarding my question: 1. I have copied and paste my code from Eclipe PyDev and I have used web interface for yahoo email to send the email. I don't know why the message arrived like that. I consider that the message from Dave was rude and just a replay considering the structure of the script would have been enough 2. Regarding the useless of the question: I consider that you two are also rude! There are some many more "useless" questions than my question on this forum! Do not bother to replay to this email because I would not receive the message. Your replays were enough to make me unsubscribe from the list I.S. ________________________________ From: Thomas Jollans To: python-list at python.org Sent: Tue, August 31, 2010 4:46:58 PM Subject: Re: sendmail error On Tuesday 31 August 2010, it occurred to sandric ionut to exclaim: > Hello: > > I have a script for sending email from python (it is attached bellow). When > I am launching the script I get the error: > TypeError: cannot concatenate 'str' and 'type' objects if I use > sys.argv[1], but if I input from the begging an email address like > "email at email.com", the script is working OK > > What could be the problem? > > Thank you, > > Ionut > > import > mesaj = email.MIMEMultipart.MIMEMultipart() > fromEmail = sys.argv[ > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > mesaj[ > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > atasament = r"Date"] = > email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = > email.MIMEBase.MIMEBase( > atasamentP.set_payload(open(atasament, > email.Encoders.encode_base64(atasamentP) > atasamentP.add_header( > mesaj.attach(atasamentP) > mesaj.attach(email.MIMEText.MIMEText( > smtpObj = > smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','attach > ement; filename="%s"'% os.path.basename(atasament))"Email transmis la data: > ", email.Utils.formatdate(localtime=False)))"192.168.1.2")try > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ > smtplib.SMTPException I struggle to imagine what one might do to a piece of code to garble it this badly. If this was actually the script you're trying to run, then it would have blown up in your face with a angry SyntaxError, not the helpful TypeError you quoted. As far as I can see, you never actually use sys.argv[1], so this can't be the right code. To paraphrase what you failed to spell correctly in your other message, please don't bother sending useless inquiries to this list. If you want to get a useful reply, please: - Quote the code correctly. Before sending, check that it actually makes sense. The above is quite simply nothing like Python. - Quote the entire stack trace and error message. You might have looked at it already, but we haven't. This information is not useless! Also, when replying: - Quote properly. While top posting is discouraged, the most important bit is to clearly distinguish quoted material from new material. Make it possible from the structure of the message you're sending which parts you wrote and which parts you're just quoting. - Keep your reply on-list. - Thomas -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at simplistix.co.uk Tue Aug 31 13:17:47 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 31 Aug 2010 18:17:47 +0100 Subject: Fw: sendmail error In-Reply-To: <4C7D0683.9000409@web.de> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <4C7CEC49.9030209@ieee.org> <191591.90081.qm@web51308.mail.re2.yahoo.com> <4C7D0683.9000409@web.de> Message-ID: <4C7D393B.9030100@simplistix.co.uk> Alexander Kapps wrote: > Instead you want something like: > > except smtplib.SMTPException, msg > print "eroare: " + msg Err, that's still concatenating a string and an exception object. What *would* work is: except smtplib.SMTPException, msg print "eroare: " + str(msg) ...not that it's particularly good coding style, what with hiding the traceback and all... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From chris at simplistix.co.uk Tue Aug 31 13:18:52 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 31 Aug 2010 18:18:52 +0100 Subject: sendmail error In-Reply-To: <201008311546.59595.thomas@jollybox.de> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <201008311546.59595.thomas@jollybox.de> Message-ID: <4C7D397C.6020501@simplistix.co.uk> Thomas Jollans wrote: > I struggle to imagine what one might do to a piece of code to garble it this > badly. You viewed the text/plain part of his message, the text/html part showed the code almost correctly, complete with pasted-from-IDE colour formatting ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From alex.kapps at web.de Tue Aug 31 13:53:59 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Tue, 31 Aug 2010 19:53:59 +0200 Subject: Fw: sendmail error In-Reply-To: <4C7D393B.9030100@simplistix.co.uk> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <4C7CEC49.9030209@ieee.org> <191591.90081.qm@web51308.mail.re2.yahoo.com> <4C7D0683.9000409@web.de> <4C7D393B.9030100@simplistix.co.uk> Message-ID: <4C7D41B7.8080505@web.de> Chris Withers wrote: > Alexander Kapps wrote: >> Instead you want something like: >> >> except smtplib.SMTPException, msg >> print "eroare: " + msg > > Err, that's still concatenating a string and an exception object. OUCH! What a stupid error. Thanks for correction. :-) > What *would* work is: > > except smtplib.SMTPException, msg > print "eroare: " + str(msg) > > ...not that it's particularly good coding style, what with hiding the > traceback and all... Full Ack. > cheers, > > Chris > From marduk at letterboxes.org Tue Aug 31 14:10:28 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 31 Aug 2010 14:10:28 -0400 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <1283278228.892888.3.camel@paska> On Tue, 2010-08-31 at 16:49 +0200, AmFreak at web.de wrote: > i have a script that reads and writes linux paths in a file. I save > the > path (as unicode) with 2 other variables. I save them seperated by "," > and > the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B > .... > > this works for "normal" paths but as soon as i have a path that does > include a "," it breaks. The problem now is that (afaik) linux > allows > every char (aside from "/" and null) to be used in filenames. The > only > solution i can think of is using null as a seperator, but there have > to a > cleaner version ? Why is your impression that the null character is "dirty"? E.g. that's how find|xargs etc. usually work. Another alternative would be if you gaurantee that your varn's don't have commas then put the path last. But that doesn't account for filenames containing newlines. Another alternative would be to wrap with some kind of serialization library. But really, what's so dirty about null? From nobody at nowhere.com Tue Aug 31 14:33:26 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 31 Aug 2010 19:33:26 +0100 Subject: Saving (unusual) linux filenames References: Message-ID: On Tue, 31 Aug 2010 18:13:44 +0100, MRAB wrote: >>>> this works for "normal" paths but as soon as i have a path that does >>>> include a "," it breaks. The problem now is that (afaik) linux allows >>>> every char (aside from "/" and null) to be used in filenames. The only >>>> solution i can think of is using null as a seperator, but there have to >>>> a cleaner version ? >>> >>> You could use a tab character '\t' instead. >> >> That just breaks with a different set of filenames. >> > How many filenames contain control characters? Surely that's a bad idea. It may be a bad idea, but it's permitted by the OS. If you're writing a general-purpose tool, having it flake out whenever it encounters an "unusual" filename is also a bad idea. FWIW, my usual solution is URL-encoding (i.e. replacing any "awkward" character by a "%" followed by two hex digits representing the byte's value). It has the advantage that you can extend the set of bytes which need encoding as needed without having to change the code (e.g. you can provide a command-line argument or configuration file setting which specifies which bytes need to be encoded). From thomas at jollybox.de Tue Aug 31 14:33:53 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 20:33:53 +0200 Subject: sendmail error In-Reply-To: <492442.26155.qm@web51305.mail.re2.yahoo.com> References: <284495.60490.qm@web51302.mail.re2.yahoo.com> <201008311546.59595.thomas@jollybox.de> <492442.26155.qm@web51305.mail.re2.yahoo.com> Message-ID: <201008312033.54015.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to sandric ionut to exclaim: > This is the only message that I will send to this list regarding my > question: > > 1. I have copied and paste my code from Eclipe PyDev and I have used web > interface for yahoo email to send the email. I will try never to use Yahoo! mail then. > I don't know why the message > arrived like that. I consider that the message from Dave was rude and just > a replay considering the structure of the script would have been enough 2. > Regarding the useless of the question: I consider that you two are also > rude! There are some many more "useless" questions than my question on > this forum! > > Do not bother to replay to this email because I would not receive the > message. Your replays were enough to make me unsubscribe from the list Charming. Replay indeed. > > > > ________________________________ > From: Thomas Jollans > To: python-list at python.org > Sent: Tue, August 31, 2010 4:46:58 PM > Subject: Re: sendmail error > > On Tuesday 31 August 2010, it occurred to sandric ionut to exclaim: > > Hello: > > > > I have a script for sending email from python (it is attached bellow). > > When I am launching the script I get the error: > > TypeError: cannot concatenate 'str' and 'type' objects if I use > > sys.argv[1], but if I input from the begging an email address like > > "email at email.com", the script is working OK > > > > What could be the problem? > > > > Thank you, > > > > Ionut > > > > import > > mesaj = email.MIMEMultipart.MIMEMultipart() > > fromEmail = sys.argv[ > > toEmail = os, sys, smtplib, email1]"toEmail"mesaj[ > > mesaj[ > > mesaj["From"] = fromEmail"To"] = toEmail"Subject"] = "Teste"mesaj[ > > atasament = r"Date"] = > > email.Utils.formatdate(localtime=True)"d:\Doc1.zip"atasamentP = > > email.MIMEBase.MIMEBase( > > atasamentP.set_payload(open(atasament, > > email.Encoders.encode_base64(atasamentP) > > atasamentP.add_header( > > mesaj.attach(atasamentP) > > mesaj.attach(email.MIMEText.MIMEText( > > smtpObj = > > smtplib.SMTP('application','zip')"rb").read())'Content-Disposition','atta > > ch ement; filename="%s"'% os.path.basename(atasament))"Email transmis la > > data: ", email.Utils.formatdate(localtime=False)))"192.168.1.2")try > > smtpObj.sendmail(fromEmail, toEmail, mesaj.as_string()) > > smtpObj.close():exceptsmtplib.SMTPException:print"eroare: "+ > > smtplib.SMTPException > > I struggle to imagine what one might do to a piece of code to garble it > this badly. If this was actually the script you're trying to run, then it > would have blown up in your face with a angry SyntaxError, not the helpful > TypeError you quoted. As far as I can see, you never actually use > sys.argv[1], so this can't be the right code. > > To paraphrase what you failed to spell correctly in your other message, > please don't bother sending useless inquiries to this list. If you want to > get a useful reply, please: > > - Quote the code correctly. Before sending, check that it actually makes > sense. The above is quite simply nothing like Python. > > - Quote the entire stack trace and error message. You might have looked at > it already, but we haven't. This information is not useless! > > Also, when replying: > > - Quote properly. While top posting is discouraged, the most important > bit is to clearly distinguish quoted material from new material. Make it > possible from the structure of the message you're sending which parts you > wrote and which parts you're just quoting. > > - Keep your reply on-list. > > - Thomas From invalid at invalid.invalid Tue Aug 31 14:49:33 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 31 Aug 2010 18:49:33 +0000 (UTC) Subject: Saving (unusual) linux filenames References: Message-ID: On 2010-08-31, MRAB wrote: > On 31/08/2010 17:58, Grant Edwards wrote: >> On 2010-08-31, MRAB wrote: >>> On 31/08/2010 15:49, AmFreak at web.de wrote: >>>> Hi, >>>> >>>> i have a script that reads and writes linux paths in a file. I save the >>>> path (as unicode) with 2 other variables. I save them seperated by "," >>>> and the "packets" by newlines. So my file looks like this: >>>> path1, var1A, var1B >>>> path2, var2A, var2B >>>> path3, var3A, var3B >>>> .... >>>> >>>> this works for "normal" paths but as soon as i have a path that does >>>> include a "," it breaks. The problem now is that (afaik) linux allows >>>> every char (aside from "/" and null) to be used in filenames. The only >>>> solution i can think of is using null as a seperator, but there have to >>>> a cleaner version ? >>> >>> You could use a tab character '\t' instead. >> >> That just breaks with a different set of filenames. >> > How many filenames contain control characters? How many filenames contain ","? Not many, but the OP wants his program to be bulletproof. Can't fault him for that. If I had a nickle for every Unix program or shell-script that failed when a filename had a space it it.... > Surely that's a bad idea. Of course it's a bad idea. That doesn't stop people from doing it. -- Grant Edwards grant.b.edwards Yow! ! Now I understand at advanced MICROBIOLOGY and gmail.com th' new TAX REFORM laws!! From python at mrabarnett.plus.com Tue Aug 31 14:57:33 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 19:57:33 +0100 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D509D.8090607@mrabarnett.plus.com> On 31/08/2010 19:33, Nobody wrote: > On Tue, 31 Aug 2010 18:13:44 +0100, MRAB wrote: > >>>>> this works for "normal" paths but as soon as i have a path that does >>>>> include a "," it breaks. The problem now is that (afaik) linux allows >>>>> every char (aside from "/" and null) to be used in filenames. The only >>>>> solution i can think of is using null as a seperator, but there have to >>>>> a cleaner version ? >>>> >>>> You could use a tab character '\t' instead. >>> >>> That just breaks with a different set of filenames. >>> >> How many filenames contain control characters? Surely that's a bad idea. > > It may be a bad idea, but it's permitted by the OS. [snip] So are viruses. :-) From python.koda at gmail.com Tue Aug 31 14:57:36 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 14:57:36 -0400 Subject: Dumb Stupid Question About List and String Message-ID: Hi all, Im stuck on this problem: I have a function which return me a list of string (basically the result looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] In other hand, I have another list full of that kind of entries: ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] I would like to do something like this: myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] mySecondList = ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] for n in myFirstList: if n in mySecondList: mySecondList.remove(n) In fact, what I want to do it to remove entries with the secondlist which content the entries of the first one. But it seems to not work like this. Someone can help me please ? did I miss something ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Tue Aug 31 15:03:33 2010 From: nagle at animats.com (John Nagle) Date: Tue, 31 Aug 2010 12:03:33 -0700 Subject: Optimising literals away In-Reply-To: References: Message-ID: <4c7d5204$0$1582$742ec2ed@news.sonic.net> On 8/30/2010 8:38 AM, Tobias Weber wrote: > Hi, > whenever I type an "object literal" I'm unsure what optimisation will do > to it. CPython is a "naive interpreter". It has almost no optimization. It doesn't even really comprehend "constants". This is an implementation problem, not a language problem. Shed Skin has serious optimization but limits the language. PyPy has been trying for years, but it still barely works. Iron Python seems to be nearing end of life, as Microsoft phases it out. Unladen Swallow seems to be in trouble; it's been almost a year since the last "quarterly release". John Nagle From arnodel at googlemail.com Tue Aug 31 15:12:41 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 31 Aug 2010 20:12:41 +0100 Subject: Saving (unusual) linux filenames References: Message-ID: AmFreak at web.de writes: > Hi, > > i have a script that reads and writes linux paths in a file. I save > the path (as unicode) with 2 other variables. I save them seperated by > "," and the "packets" by newlines. So my file looks like this: > path1, var1A, var1B > path2, var2A, var2B > path3, var3A, var3B > .... > > this works for "normal" paths but as soon as i have a path that does > include a "," it breaks. The problem now is that (afaik) linux allows > every char (aside from "/" and null) to be used in filenames. The only > solution i can think of is using null as a seperator, but there have > to a cleaner version ? > > Thanks for any help > > Biene_Maja A simple solution would be to save each line of data using JSON with the json module: >>> import json >>> >>> >>> path = "x,y,z" >>> varA = 12 >>> varB = "abc" >>> line = json.dumps([path, varA, varB]) >>> print line ["x,y,z", 12, "abc"] >>> loadpathA, loadvarA, loadvarB = json.loads(line) >>> print loadpathA x,y,z >>> print loadvarA 12 >>> print loadvarB abc HTH -- Arnaud From python.koda at gmail.com Tue Aug 31 15:20:39 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 15:20:39 -0400 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: Ok, here a solution: myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] mySecondList = ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] for n in myFirstList: var = str(n) for n in mySecondList: if var in n: mySecondList.remove(n) print mySecondList :) 2010/8/31 Alban Nona > Hi all, > > Im stuck on this problem: > I have a function which return me a list of string (basically the result > looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > In other hand, I have another list full of that kind of entries: > > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > I would like to do something like this: > > myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > mySecondList = > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > for n in myFirstList: > if n in mySecondList: > mySecondList.remove(n) > > In fact, what I want to do it to remove entries with the secondlist which > content the entries of the first one. But it seems to not work like this. > Someone can help me please ? did I miss something ? > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 31 15:25:46 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 20:25:46 +0100 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: <4C7D573A.9050602@mrabarnett.plus.com> On 31/08/2010 19:57, Alban Nona wrote: > Hi all, > > Im stuck on this problem: > I have a function which return me a list of string (basically the result > looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > In other hand, I have another list full of that kind of entries: > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > I would like to do something like this: > > myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > mySecondList = > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > for n in myFirstList: > if n in mySecondList: > mySecondList.remove(n) > > In fact, what I want to do it to remove entries with the secondlist > which content the entries of the first one. But it seems to not work > like this. > Someone can help me please ? did I miss something ? > Your code is asking whether, for example, "FN067_098_MEN" is in mySecondList. It isn't. mySecondList contains "FN067_098_MEN_Hair_PUZ_v001.0001.exr", but that's not the same as "FN067_098_MEN". If I understand you correctly, you want to remove entries from mySecondList which have an entry of myFirstList as a substring. Here's one solution: result_list = [] for second in mySecondList: if not any(first in second for first in myFirstList): result_list.append(second) mySecondList = result_list From clp2 at rebertia.com Tue Aug 31 15:26:02 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 31 Aug 2010 12:26:02 -0700 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: On Tue, Aug 31, 2010 at 12:20 PM, Alban Nona wrote: > Ok, here a solution: > for n in myFirstList: > ???? var = str(n) n is already a string, so the previous line doesn't do anything useful. Cheers, Chris From stefan_ml at behnel.de Tue Aug 31 15:28:24 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Aug 2010 21:28:24 +0200 Subject: Optimising literals away In-Reply-To: <4c7d5204$0$1582$742ec2ed@news.sonic.net> References: <4c7d5204$0$1582$742ec2ed@news.sonic.net> Message-ID: John Nagle, 31.08.2010 21:03: > On 8/30/2010 8:38 AM, Tobias Weber wrote: >> whenever I type an "object literal" I'm unsure what optimisation will do >> to it. > > CPython is a "naive interpreter". It has almost no optimization. > It doesn't even really comprehend "constants". > This is an implementation problem, not a language problem. > > Shed Skin has serious optimization but limits the language. > PyPy has been trying for years, but it still barely works. > Iron Python seems to be nearing end of life, as Microsoft > phases it out. Unladen Swallow seems to be in trouble; it's > been almost a year since the last "quarterly release". To continue the list, Cython also has a couple of optimisations for literals. It caches simple immutable constants, applies numeric constant folding and it's obviously a lot faster in packing tuples and lists than CPython as it avoids the interpreter loop. It also optimises away the literal sequences in "in" tests such as if x in (1,2,3): ... which, in the best case of integer literals, even compile down into C switch statements. Stefan From python at mrabarnett.plus.com Tue Aug 31 15:42:55 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 20:42:55 +0100 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: <4C7D5B3F.5070102@mrabarnett.plus.com> On 31/08/2010 20:20, Alban Nona wrote: > Ok, here a solution: > > myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] > > mySecondList = > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > for n in myFirstList: > var = str(n) Why str(n)? Also, it would be clearer if you used different variables for the different loops. > for n in mySecondList: > if var in n: > mySecondList.remove(n) You shouldn't change the length of a list over which you're iterating. Python will step along the list one entry at a time and won't notice when you remove an entry, so the next one will be skipped. For example: >>> letters = ["a", "b", "c", "d", "e"] >>> for i in letters: ... if i == "b" or i == "c": ... letters.remove(i) ... >>> print letters ['a', 'c', 'd', 'e'] It removed "b" and then moved on to the next entry, which is "d" because "b" has been removed and all the following entries have moved down one place. It never sees "c". > > print mySecondList > [snip] From anand.shashwat at gmail.com Tue Aug 31 15:44:22 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Wed, 1 Sep 2010 01:14:22 +0530 Subject: Dumb Stupid Question About List and String In-Reply-To: References: Message-ID: On Wed, Sep 1, 2010 at 12:27 AM, Alban Nona wrote: > Hi all, > > Im stuck on this problem: > I have a function which return me a list of string (basically the result > looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > In other hand, I have another list full of that kind of entries: > > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > I would like to do something like this: > > myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"] > mySecondList = > ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] > > for n in myFirstList: > if n in mySecondList: > mySecondList.remove(n) > > In fact, what I want to do it to remove entries with the secondlist which > content the entries of the first one. But it seems to not work like this. > Someone can help me please ? did I miss something ? > You can try this if you don't care about the order. >>> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] >>> mySecondList = ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] >>> list(set(mySecondList).difference(myFirstList)) ['FN067_098_MEN_Jin_MVE_v001.0001.exr', 'FN067_098_MEN_Hair_PUZ_v001.0001.exr', 'FR043_010_GEN_NRM_v001.0001.exr', 'FN067_098_JIN_Hair_SPC_v001.0001.exr'] Another example to make this clear. >>> a = range(10) >>> b = range(5,15) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> b [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> list(set(b).difference(a)) [10, 11, 12, 13, 14] -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Tue Aug 31 15:57:22 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Wed, 1 Sep 2010 01:27:22 +0530 Subject: Find closest matching string based on collection of strings in list/dict/set In-Reply-To: <1283269327.22774.1392642985@webmail.messagingengine.com> References: <1283269327.22774.1392642985@webmail.messagingengine.com> Message-ID: On Tue, Aug 31, 2010 at 9:12 PM, wrote: > I'm parsing a simple, domain specific scripting language that has commands > like the following: *page, *title, *text, *footer, etc. There are about 100 > of these '*' commands. When we see a command that we don't recognize, I > would like to find the closest match possible (from a list of all legal > commands) and include this suggestion in our diagnostic output. > > I'm not sure what you would call the type of algorithm I'm looking for: > closest matching string or auto-correct? > > Any suggestions on algorithms or python libraries that would help me do > what I'm looking for? > > Here's my short-list of ideas based on my research so far: > - Soundex > - Lawrence Philips' Metaphone Algorithm (from aspell?) > - Edit Distance Algorithm > - Levenstein Word Distance > > Any suggestions, comments on the above techniques, or ideas on a simpler > algorithm for finding close string matches based on a list, dict, or set of > possible strings? > You are looking possibly for autocompletion/spell correction algorithm. You can write a HMM based Pos Tagger. > Thank you, > Malcolm > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Aug 31 15:59:40 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Aug 2010 15:59:40 -0400 Subject: How to convert (unicode) text to image? In-Reply-To: References: <206c2bdf-7103-4bff-8e78-7ba67006f7d8@w15g2000pro.googlegroups.com> Message-ID: On 8/31/2010 12:47 AM, rurpy at yahoo.com wrote: >> I have participated in 71 doc improvement issues on the tracker. Most of >> those I either initiated or provided suggestions. How many have you >> helped with? > > Certainly not 71. But there is, for example, http://bugs.python.org/issue1397474 > Please note the date on it. Ugh. Some doc issues get resolved in hours. That didn't. I built on your proposed change and properly assigned the issue, so it is more likely to get attention. Please comment there on my revision. -- Terry Jan Reedy From tjreedy at udel.edu Tue Aug 31 16:18:13 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Aug 2010 16:18:13 -0400 Subject: Optimising literals away In-Reply-To: <69a8fbbc-5f45-491a-adf3-2fb5a4d79660@s9g2000yqd.googlegroups.com> References: <69a8fbbc-5f45-491a-adf3-2fb5a4d79660@s9g2000yqd.googlegroups.com> Message-ID: On 8/31/2010 12:33 PM, Aleksey wrote: > On Aug 30, 10:38 pm, Tobias Weber wrote: >> Hi, >> whenever I type an "object literal" I'm unsure what optimisation will do >> to it. Optimizations are generally implentation dependent. CPython currently creates numbers, strings, and tuple literals just once. Mutable literals must be created each time as they may be bound and saved. >> def m(arg): >> if arg& set([1,2,3]): set() is a function call, not a literal. When m is called, who knows what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, which is much faster as it avoids creating and deleting a list. On my machine, .35 versus .88 usec. Even then, it must be calculated each time because sets are mutable and could be returned to the calling code. >> return 4 >> >> Is the set created every time the method is called? What about a >> frozenset? Or tuple vs list? After how many calls per second does it pay >> to save it at the module level? Would anybody else find this ugly? Defining module level constants is considered good practice in some circles, especially if is something you might want to change. That is what function definitions are (as long as the name is not redefined. This is different from having lots of module level variables. To see what CPython does, you can use the dis module. -- Terry Jan Reedy From hexusnexus at gmail.com Tue Aug 31 16:37:01 2010 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Tue, 31 Aug 2010 13:37:01 -0700 (PDT) Subject: Python libs on Windows ME Message-ID: I'm not guessing that this is a problem on Windows 98, but on Windows ME modules in /Lib don't seem to load. Examples include site.py and os.py which are both located in the top level Lib directory. The same thing happens with Python 2.3, 2.4, and 2.5. I can't get IDLE to load and the Python interpreter always complains that it can't load the "site" module even if Python is run from the same directory as the module (note: this does not happen if a module is loaded from the current working directory while in the interpreter). I would use another os like Linux or Windows 2000, but this particular computer can't even seem to handle even the most minimal graphical Linux distributions. From hexusnexus at gmail.com Tue Aug 31 16:41:19 2010 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Tue, 31 Aug 2010 13:41:19 -0700 (PDT) Subject: Installing Python as Scripting Language in IIS References: <4154f088-f746-4891-83ee-f64138c81e2e@x25g2000yqj.googlegroups.com> Message-ID: <125c518f-d418-4f3f-ae8f-4f0fdcae00df@y12g2000prb.googlegroups.com> On Aug 30, 6:55?pm, naugiedoggie wrote: > Hello, > > Windows 2003, 64-bit, standard edition server with IIS 6.0. ?I > followed the MS instruction sheets on setting up CGI application with > Python as scripting engine. ?I'm just getting 404 for the test script, > whereas an html file in the same virtual directory is properly > displayed. > > Here: > > Creating Applications in IIS 6.0 (IIS 6.0)http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Librar... > > Setting Application Mappings in IIS 6.0 (IIS 6.0)http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Librar... > > I mapped the exe thus: ?c:\Python26\python.exe -u "%s %s" > to extension `py' for all verbs and checked the `script engine' box. > > There are no errors in the script itself, i ran it from the command > line to be sure. ?Further, I enabled ASP and tried using python as the > scripting language. ?That generates this error: > > > Active Server Pages error 'ASP 0129' > Unknown scripting language > /cgi/index.asp, line 1 > The scripting language 'Python' is not found on the server. > > > I can't find any good references for dealing with this, either. > > I've dicked around with this for so long, now I don't know which way > is up, anymore. > > Any thoughts on where I might be going wrong, much appreciated. > > Thanks. > > mp I had the same problem with Python 2.5 and IIS on Windows XP. I wonder if using ActivePython would make any difference? From kevinlcarlson at gmail.com Tue Aug 31 16:53:09 2010 From: kevinlcarlson at gmail.com (kevinlcarlson) Date: Tue, 31 Aug 2010 13:53:09 -0700 (PDT) Subject: Helper app for intranet site References: <45e0772c-24a8-4cbb-a4fc-74a1b6c250d5@n19g2000prf.googlegroups.com> <61894f54-90ff-4e0e-9c81-860b6e9cdc15@p12g2000prn.googlegroups.com> Message-ID: <8a994714-4e42-4e53-8f67-c1357407a02e@h37g2000pro.googlegroups.com> On Aug 30, 4:13?pm, Lawrence D'Oliveiro wrote: > In message > <61894f54-90ff-4e0e-9c81-860b6e9cd... at p12g2000prn.googlegroups.com>, > > > > kevinlcarlson wrote: > > On Aug 29, 8:46 pm, Lawrence D'Oliveiro > > wrote: > > >> In message > >> <45e0772c-24a8-4cbb-a4fc-74a1b6c25... at n19g2000prf.googlegroups.com>, > >> kevinlcarlson wrote: > > >>> I'm exploring the possibility of developing a helper app for an > >>> existing internal company website. ?Basically, it would automatically > >>> scan the current page contents, including prepopulated forms, and > >>> provide context-related business rule comments to the user, via a stay- > >>> on-top wxPython panel. > > >> Seems like a roundabout way of doing it. Can?t you integrate into the > >> server code which is generating the page contents, instead of trying to > >> reverse- engineer those contents? > > > Absolutely - that would be the best way to accomplish this. > > Unfortunately, our group has no access to the web server and the > > developers have this functionality scheduled about a year into the > > future, but we need it ASAP. ?Also, our group would like to be in > > control of the code and business rule contents, rather than wait for > > updates from the busy web team... > > Conway?s Law: any piece of software reflects the organizational structure > that produced it. Hard to disagree with that sentiment - I've come across a fair amount of disorganized software in my day... ;) In any case, I'll try the WinGuiAuto approach and see how that works... From python.koda at gmail.com Tue Aug 31 16:56:26 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 16:56:26 -0400 Subject: Dumb Stupid Question About List and String In-Reply-To: <4C7D5B3F.5070102@mrabarnett.plus.com> References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: Well, I have a lot to learn :) Thank you very much both of you ! it seems to work now :p 2010/8/31 MRAB > On 31/08/2010 20:20, Alban Nona wrote: > >> Ok, here a solution: >> >> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] >> >> mySecondList = >> >> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] >> >> for n in myFirstList: >> var = str(n) >> > > Why str(n)? > > Also, it would be clearer if you used different variables for the > different loops. > > > for n in mySecondList: >> if var in n: >> mySecondList.remove(n) >> > > You shouldn't change the length of a list over which you're iterating. > Python will step along the list one entry at a time and won't notice when > you remove an entry, so the next one will be skipped. For example: > > >>> letters = ["a", "b", "c", "d", "e"] > >>> for i in letters: > ... if i == "b" or i == "c": > ... letters.remove(i) > ... > >>> print letters > ['a', 'c', 'd', 'e'] > > It removed "b" and then moved on to the next entry, which is "d" > because "b" has been removed and all the following entries have moved > down one place. It never sees "c". > > >> print mySecondList >> >> [snip] > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at columbuswebmakers.com Tue Aug 31 17:01:26 2010 From: joel.goldstick at columbuswebmakers.com (Joel Goldstick) Date: Tue, 31 Aug 2010 17:01:26 -0400 Subject: Find closest matching string based on collection of strings in list/dict/set In-Reply-To: <1283269327.22774.1392642985@webmail.messagingengine.com> References: <1283269327.22774.1392642985@webmail.messagingengine.com> Message-ID: <4C7D6DA6.80304@columbuswebmakers.com> python at bdurham.com wrote: > I'm parsing a simple, domain specific scripting language that has > commands like the following: *page, *title, *text, *footer, etc. > There are about 100 of these '*' commands. When we see a command > that we don't recognize, I would like to find the closest match > possible (from a list of all legal commands) and include this > suggestion in our diagnostic output. > > I'm not sure what you would call the type of algorithm I'm > looking for: closest matching string or auto-correct? > > Any suggestions on algorithms or python libraries that would help > me do what I'm looking for? > > Here's my short-list of ideas based on my research so far: > - Soundex > - Lawrence Philips' Metaphone Algorithm (from aspell?) > - Edit Distance Algorithm > - Levenstein Word Distance > > Any suggestions, comments on the above techniques, or ideas on a > simpler algorithm for finding close string matches based on a > list, dict, or set of possible strings? > > Thank you, > Malcolm > > Have you looked at difflib? From thomas at jollybox.de Tue Aug 31 17:04:56 2010 From: thomas at jollybox.de (Thomas Jollans) Date: Tue, 31 Aug 2010 23:04:56 +0200 Subject: Python libs on Windows ME In-Reply-To: References: Message-ID: <201008312304.57338.thomas@jollybox.de> On Tuesday 31 August 2010, it occurred to hexusnexus at gmail.com to exclaim: > I'm not guessing that this is a problem on Windows 98, but on Windows > ME modules in /Lib don't seem to load. Examples include site.py and > os.py which are both located in the top level Lib directory. The same > thing happens with Python 2.3, 2.4, and 2.5. I can't get IDLE to load > and the Python interpreter always complains that it can't load the > "site" module even if Python is run from the same directory as the > module (note: this does not happen if a module is loaded from the > current working directory while in the interpreter). What is sys.path set to ? python.exe -c "import sys; print(sys.path)" It sounds like the stdlib directory is not on sys.path. Couldn't say why though... > > I would use another os like Linux or Windows 2000, but this particular > computer can't even seem to handle even the most minimal graphical > Linux distributions. Really? I'm sure you can get Linux on there somehow. It might not be trivial, but it should definitely be possible. Out of interest: what distros did you try? From sschwarzer at sschwarzer.net Tue Aug 31 17:16:10 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 31 Aug 2010 23:16:10 +0200 Subject: Functions continuing to ru after returning something? In-Reply-To: References: Message-ID: <4C7D711A.5030907@sschwarzer.net> Hi, On 2010-08-31 02:05, Bradley Hintze wrote: > I may be having a brain fart, but is it at all possible to have a > function first return a value then continue its calculation. Like this > simple example: > > my_var = 5 > def my_function(): > return my_var > my_var +=1 > > This obviously won't work as written but is there a cleaver way around this. At least in CPython 2.6.5 the above code results in Traceback (most recent call last): File "test.py", line 7, in my_function() File "test.py", line 3, in my_function return my_var UnboundLocalError: local variable 'my_var' referenced before assignment as soon as the function is called. If you want to have the global my_var modified, you need a "global my_var" statement in the function body. Stefan From arnodel at googlemail.com Tue Aug 31 17:24:23 2010 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 31 Aug 2010 22:24:23 +0100 Subject: Find closest matching string based on collection of strings in list/dict/set References: <1283269327.22774.1392642985@webmail.messagingengine.com> Message-ID: Joel Goldstick writes: > python at bdurham.com wrote: >> I'm parsing a simple, domain specific scripting language that has >> commands like the following: *page, *title, *text, *footer, etc. >> There are about 100 of these '*' commands. When we see a command >> that we don't recognize, I would like to find the closest match >> possible (from a list of all legal commands) and include this >> suggestion in our diagnostic output. >> >> I'm not sure what you would call the type of algorithm I'm >> looking for: closest matching string or auto-correct? >> >> Any suggestions on algorithms or python libraries that would help >> me do what I'm looking for? >> >> Here's my short-list of ideas based on my research so far: >> - Soundex >> - Lawrence Philips' Metaphone Algorithm (from aspell?) >> - Edit Distance Algorithm >> - Levenstein Word Distance >> >> Any suggestions, comments on the above techniques, or ideas on a >> simpler algorithm for finding close string matches based on a >> list, dict, or set of possible strings? >> >> Thank you, >> Malcolm >> >> > Have you looked at difflib? You only have a few words to compare with, so why not try this naive solution? >>> commands = ["page", "text", "footer", "header", "title"] >>> def closest(u): ... return min(commands, key=lambda v: len(set(u) ^ set(v))) ... >>> closest("paige") 'page' >>> closest("heeder") 'header' >>> closest("tilte") 'title' -- Arnaud PS: oddly, I didn't see the OP (reading newsgroup). From anand.shashwat at gmail.com Tue Aug 31 17:25:58 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Wed, 1 Sep 2010 02:55:58 +0530 Subject: Find closest matching string based on collection of strings in list/dict/set In-Reply-To: <4C7D6DA6.80304@columbuswebmakers.com> References: <1283269327.22774.1392642985@webmail.messagingengine.com> <4C7D6DA6.80304@columbuswebmakers.com> Message-ID: On Wed, Sep 1, 2010 at 2:31 AM, Joel Goldstick < joel.goldstick at columbuswebmakers.com> wrote: > python at bdurham.com wrote: > >> I'm parsing a simple, domain specific scripting language that has >> commands like the following: *page, *title, *text, *footer, etc. >> There are about 100 of these '*' commands. When we see a command >> that we don't recognize, I would like to find the closest match >> possible (from a list of all legal commands) and include this >> suggestion in our diagnostic output. >> >> I'm not sure what you would call the type of algorithm I'm >> looking for: closest matching string or auto-correct? >> >> Any suggestions on algorithms or python libraries that would help >> me do what I'm looking for? >> >> Here's my short-list of ideas based on my research so far: >> - Soundex >> - Lawrence Philips' Metaphone Algorithm (from aspell?) >> - Edit Distance Algorithm >> - Levenstein Word Distance >> >> Any suggestions, comments on the above techniques, or ideas on a >> simpler algorithm for finding close string matches based on a >> list, dict, or set of possible strings? >> >> Thank you, >> Malcolm >> >> >> Have you looked at difflib? > On a side note, you can read this awesome article by Peter Norvig. http://norvig.com/spell-correct.html > -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.kapps at web.de Tue Aug 31 17:33:27 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Tue, 31 Aug 2010 23:33:27 +0200 Subject: Python libs on Windows ME In-Reply-To: <201008312304.57338.thomas@jollybox.de> References: <201008312304.57338.thomas@jollybox.de> Message-ID: <4C7D7527.2040703@web.de> Thomas Jollans wrote: >> I would use another os like Linux or Windows 2000, but this particular >> computer can't even seem to handle even the most minimal graphical >> Linux distributions. > > Really? I'm sure you can get Linux on there somehow. It might not be trivial, > but it should definitely be possible. Out of interest: what distros did you > try? In my experiences, getting /some/ Linux on a usual, say, post-1995 PC is almost trivial, even with GUI. It's just a matter of choosing the right distro (and desktop environment). If the OP would post the exact hardware specs, I'm almost sure, that we can find a distro that works without much hassle. From sschwarzer at sschwarzer.net Tue Aug 31 17:35:07 2010 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 31 Aug 2010 23:35:07 +0200 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D758B.7090406@sschwarzer.net> Hi Grant, On 2010-08-31 20:49, Grant Edwards wrote: > How many filenames contain ","? CVS repository files end with ,v . However, just let's agree that nobody uses CVS anymore. :-) > Not many, but the OP wants his > program to be bulletproof. Can't fault him for that. What about using the csv (not CVS) module? Stefan From AmFreak at web.de Tue Aug 31 17:45:13 2010 From: AmFreak at web.de (AmFreak at web.de) Date: Tue, 31 Aug 2010 23:45:13 +0200 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: Thanks for all the nice answers! > The normal thing to do is to escape the delimiter when it appears in > data. There are lots of plenty of escaping standards to choose from, > and some of them (e.g. the one used for URLs) are already present > in various bits of Python's standard library. The CSV module has something like that, but im using unicode and it doesn't work with that. > Why is your impression that the null character is "dirty"? >E.g. that's how find|xargs etc. usually work. >Another alternative would be if you gaurantee that your varn's don't > have commas then put the path last. But that doesn't account for > filenames containing newlines. >Another alternative would be to wrap with some kind of serialization > library. But really, what's so dirty about null? I think i just prefer a little formated file instead of one loooong row :) > A simple solution would be to save each line of data using JSON with the > json > module: >>> import json >>> path = "x,y,z" >>> varA = 12 >>> varB = "abc" >>> line = json.dumps([path, varA, varB]) >>> print line ["x,y,z", 12, "abc"] >>> loadpathA, loadvarA, loadvarB = json.loads(line) >>> print loadpathA x,y,z >>> print loadvarA 12 >>> print loadvarB abc Thanks, just tried it - so simple, but seems to work like a charm. Really aprecciated :D. From krister.svanlund at gmail.com Tue Aug 31 17:45:57 2010 From: krister.svanlund at gmail.com (Krister Svanlund) Date: Tue, 31 Aug 2010 23:45:57 +0200 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: On Tue, Aug 31, 2010 at 5:10 PM, Benjamin Kaplan wrote: > On Tuesday, August 31, 2010, Roman Sokolyuk wrote: >> Hi, >> >> I am new to Python and I wanted to understand something... >> The EVE Online Client is build using Stackless Python >> So when I install the client on my machine, how doe sit get run if I do not have Python installed? >> > We call it "freezing" the program. There are several tools that do > this with py2exe being the most popular. These tools create an > executable that includes a bundled python interpreter along with all > the scripts and modules needed to run the program. >> Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > I'm not sure but I do believe it is mainly the servers that are written in stackless... From benjamin.kaplan at case.edu Tue Aug 31 17:50:21 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 31 Aug 2010 17:50:21 -0400 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: On Tue, Aug 31, 2010 at 5:45 PM, Krister Svanlund wrote: > On Tue, Aug 31, 2010 at 5:10 PM, Benjamin Kaplan > wrote: >> On Tuesday, August 31, 2010, Roman Sokolyuk wrote: >>> Hi, >>> >>> I am new to Python and I wanted to understand something... >>> The EVE Online Client is build using Stackless Python >>> So when I install the client on my machine, how doe sit get run if I do not have Python installed? >>> >> We call it "freezing" the program. There are several tools that do >> this with py2exe being the most popular. These tools create an >> executable that includes a bundled python interpreter along with all >> the scripts and modules needed to run the program. >>> Thanks. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I'm not sure but I do believe it is mainly the servers that are > written in stackless... > You'd have a hard time scripting the game with Python if only the server used it. http://wiki.eveonline.com/en/wiki/How_is_the_game_logic_implemented_in_EVE From python at mrabarnett.plus.com Tue Aug 31 17:53:50 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 22:53:50 +0100 Subject: Optimising literals away In-Reply-To: References: <69a8fbbc-5f45-491a-adf3-2fb5a4d79660@s9g2000yqd.googlegroups.com> Message-ID: <4C7D79EE.8010402@mrabarnett.plus.com> On 31/08/2010 21:18, Terry Reedy wrote: > On 8/31/2010 12:33 PM, Aleksey wrote: >> On Aug 30, 10:38 pm, Tobias Weber wrote: >>> Hi, >>> whenever I type an "object literal" I'm unsure what optimisation will do >>> to it. > > Optimizations are generally implentation dependent. CPython currently > creates numbers, strings, and tuple literals just once. Mutable literals > must be created each time as they may be bound and saved. > >>> def m(arg): >>> if arg& set([1,2,3]): > > set() is a function call, not a literal. When m is called, who knows > what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, > which is much faster as it avoids creating and deleting a list. On my > machine, .35 versus .88 usec. Even then, it must be calculated each time > because sets are mutable and could be returned to the calling code. > There's still the possibility of some optimisation. If the resulting set is never stored anywhere (bound to a name, for example) then it could be created once. When the expression is evaluated there could be a check so see whether 'set' is bound to the built-in class, and, if it is, then just use the pre-created set. >>> return 4 >>> >>> Is the set created every time the method is called? What about a >>> frozenset? Or tuple vs list? After how many calls per second does it pay >>> to save it at the module level? Would anybody else find this ugly? > > Defining module level constants is considered good practice in some > circles, especially if is something you might want to change. That is > what function definitions are (as long as the name is not redefined. > This is different from having lots of module level variables. > > To see what CPython does, you can use the dis module. > From python.koda at gmail.com Tue Aug 31 17:57:45 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 17:57:45 -0400 Subject: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: Just Another Question on this one, Im trying to create that kind of thing in code now: #GENERE ET INCREMENT LE NOM DES ELEMENTS val = 0 list = ["0", "1", "2", "3"] listEl = [] for n in list: val = val + 1 next = "00" +str(val) elem = "ELM"+next listEl.append(elem) #INCREMENT LE NOM DES ELEMENTS AVEC LE NOM DES PASSES listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE", "DPF", "SDW", "MAT", "WPP"] listElem = [] for first in listEl: for second in listPass: listElem.append(first+"_"+second) print listElem print listEl What I would like to do is: if 'ELM001' Contained in one of the entries of listElem, create a new list with only 'ELM001' Elements (eg: newList=['ELM001_DIF', 'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS', 'ELM001_REFR', 'ELM001_ALB', 'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE', 'ELM001_DPF', 'ELM001_SDW', 'ELM001_MAT', 'ELM001_WPP'] Damn Im sooooooooo lost with this tables and loop, Im always trying to understand in which way I should do it.... :/ Any Ideas please ? 2010/8/31 Alban Nona > Well, I have a lot to learn :) > > Thank you very much both of you ! it seems to work now :p > > 2010/8/31 MRAB > >> On 31/08/2010 20:20, Alban Nona wrote: >> >> Ok, here a solution: >>> >>> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"] >>> >>> mySecondList = >>> >>> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"] >>> >>> for n in myFirstList: >>> var = str(n) >>> >> >> Why str(n)? >> >> Also, it would be clearer if you used different variables for the >> different loops. >> >> >> for n in mySecondList: >>> if var in n: >>> mySecondList.remove(n) >>> >> >> You shouldn't change the length of a list over which you're iterating. >> Python will step along the list one entry at a time and won't notice when >> you remove an entry, so the next one will be skipped. For example: >> >> >>> letters = ["a", "b", "c", "d", "e"] >> >>> for i in letters: >> ... if i == "b" or i == "c": >> ... letters.remove(i) >> ... >> >>> print letters >> ['a', 'c', 'd', 'e'] >> >> It removed "b" and then moved on to the next entry, which is "d" >> because "b" has been removed and all the following entries have moved >> down one place. It never sees "c". >> >> >>> print mySecondList >>> >>> [snip] >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hexusnexus at gmail.com Tue Aug 31 18:09:07 2010 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Tue, 31 Aug 2010 15:09:07 -0700 (PDT) Subject: Python libs on Windows ME References: Message-ID: On Aug 31, 2:04?pm, Thomas Jollans wrote: > On Tuesday 31 August 2010, it occurred to hexusne... at gmail.com to exclaim: > > > I'm not guessing that this is a problem on Windows 98, but on Windows > > ME modules in /Lib don't seem to load. ?Examples include site.py and > > os.py which are both located in the top level Lib directory. ?The same > > thing happens with Python 2.3, 2.4, and 2.5. ?I can't get IDLE to load > > and the Python interpreter always complains that it can't load the > > "site" module even if Python is run from the same directory as the > > module (note: this does not happen if a module is loaded from the > > current working directory while in the interpreter). > > What is sys.path set to ? > > python.exe -c "import sys; print(sys.path)" > > It sounds like the stdlib directory is not on sys.path. Couldn't say why > though... > > > > > I would use another os like Linux or Windows 2000, but this particular > > computer can't even seem to handle even the most minimal graphical > > Linux distributions. > > Really? I'm sure you can get Linux on there somehow. It might not be trivial, > but it should definitely be possible. Out of interest: what distros did you > try? I think Puppy Linux might work, but I'd need GTK for wxPython, and I assume that means version 2 of GTK which I'm not sure comes with Puppy Linux and I've experienced problems in the past compiling GTK with './ configure && make' and so on. Yeah, for some reason, the sys.path variable was set with 'python' instead of 'Python25'. Funny how I never had that problem on Windows XP. Renaming the directory or appending to sys.path fixes that problem. From cs at zip.com.au Tue Aug 31 18:11:28 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 1 Sep 2010 08:11:28 +1000 Subject: Optimising literals away In-Reply-To: <4C7D79EE.8010402@mrabarnett.plus.com> References: <4C7D79EE.8010402@mrabarnett.plus.com> Message-ID: <20100831221128.GA25577@cskk.homeip.net> On 31Aug2010 22:53, MRAB wrote: [...] | >>>def m(arg): | >>>if arg& set([1,2,3]): | > | >set() is a function call, not a literal. When m is called, who knows | >what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, | >which is much faster as it avoids creating and deleting a list. On my | >machine, .35 versus .88 usec. Even then, it must be calculated each time | >because sets are mutable and could be returned to the calling code. | > | There's still the possibility of some optimisation. If the resulting | set is never stored anywhere (bound to a name, for example) then it | could be created once. When the expression is evaluated there could be | a check so see whether 'set' is bound to the built-in class, and, if it | is, then just use the pre-created set. Wouldn't you need to repeat that check every time, otherwise "set" may no longer be the builtin? -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ From sci.physics: tron at mailzone.com: The only problem is, how do you send a message from Earth to Mars instantly? Does anyone have any ideas about where we can start? John Baez References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: <4C7D81A9.9040006@mrabarnett.plus.com> On 31/08/2010 22:57, Alban Nona wrote: > Just Another Question on this one, Im trying to create that kind of > thing in code now: > > #GENERE ET INCREMENT LE NOM DES ELEMENTS > > val = 0 > > list = ["0", "1", "2", "3"] > > listEl = [] > > for n in list: > > val = val + 1 > > next = "00" +str(val) > > elem = "ELM"+next > > listEl.append(elem) > > > > #INCREMENT LE NOM DES ELEMENTS AVEC LE NOM DES PASSES > > listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", > "MVE", "DPF", "SDW", "MAT", "WPP"] > > listElem = [] > > for first in listEl: > > for second in listPass: > > listElem.append(first+"_"+second) > > > print listElem > > print listEl > > > What I would like to do is: > > if 'ELM001' Contained in one of the entries of listElem, create a new > list with only 'ELM001' Elements (eg: newList=['ELM001_DIF', > 'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS', 'ELM001_REFR', 'ELM001_ALB', > 'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE', 'ELM001_DPF', 'ELM001_SDW', > 'ELM001_MAT', 'ELM001_WPP'] > > Damn Im sooooooooo lost with this tables and loop, Im always trying to > understand in which way I should do it.... :/ > Any Ideas please ? > How about: newList = [] for elem in listElem: if 'ELM001' in elem: newList.append(elem) From contact at xavierho.com Tue Aug 31 18:29:51 2010 From: contact at xavierho.com (Xavier Ho) Date: Wed, 1 Sep 2010 08:29:51 +1000 Subject: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: On 1 September 2010 07:57, Alban Nona wrote: > listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE", > "DPF", "SDW", "MAT", "WPP"] > Out of curiosity, could you briefly mention what "SDW" and "WPP" passes are? I've worked out the rest, and these two are riddling my brain. (On topic: If you want only the elements starting with ELM001, or whatever, use a if condition like what MRAB posted.) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 31 18:38:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 31 Aug 2010 23:38:26 +0100 Subject: Optimising literals away In-Reply-To: <20100831221128.GA25577@cskk.homeip.net> References: <4C7D79EE.8010402@mrabarnett.plus.com> <20100831221128.GA25577@cskk.homeip.net> Message-ID: <4C7D8462.8060505@mrabarnett.plus.com> On 31/08/2010 23:11, Cameron Simpson wrote: > On 31Aug2010 22:53, MRAB wrote: > [...] > |>>>def m(arg): > |>>>if arg& set([1,2,3]): > |> > |>set() is a function call, not a literal. When m is called, who knows > |>what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, > |>which is much faster as it avoids creating and deleting a list. On my > |>machine, .35 versus .88 usec. Even then, it must be calculated each time > |>because sets are mutable and could be returned to the calling code. > |> > | There's still the possibility of some optimisation. If the resulting > | set is never stored anywhere (bound to a name, for example) then it > | could be created once. When the expression is evaluated there could be > | a check so see whether 'set' is bound to the built-in class, and, if it > | is, then just use the pre-created set. > > Wouldn't you need to repeat that check every time, otherwise "set" may > no longer be the builtin? Isn't that what I said? My point is that if you have a set of constants which is created and then discarded you can cache it and reuse it next time. You check every time whether 'set' is bound to the set class. From oliver.saunders at gmail.com Tue Aug 31 18:46:11 2010 From: oliver.saunders at gmail.com (Ollie Saunders) Date: Tue, 31 Aug 2010 15:46:11 -0700 (PDT) Subject: Ed Lambda: Functional programming meetup in Edinburgh Message-ID: <4038fe03-28d9-42eb-a982-8b6fff52c794@v41g2000yqv.googlegroups.com> Hi guys, I'm running a meetup for functional programming in Edinburgh. The first one will be on the 13th of September at Malone's Irish Bar (14 Forrest Road) and will continue every 2nd monday of each month. For the first meetup I think we'll just be having a chat and getting to know each other but I hope to be able to expand it to talks and coding dojos once we have some regular numbers. For more details: http://meetup.com/ed-lambda/ And we're on Twitter: http://twitter.com/ed_lambda From tjreedy at udel.edu Tue Aug 31 19:24:19 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Aug 2010 19:24:19 -0400 Subject: Performance: sets vs dicts. In-Reply-To: References: <4c7ab135$0$1591$742ec2ed@news.sonic.net> <878w3ogpvq.fsf@benfinney.id.au> Message-ID: On 8/31/2010 10:09 AM, Aahz wrote: > In article, > Jerry Hill wrote: >> On Mon, Aug 30, 2010 at 7:42 PM, Aahz wrote: >>> >>> Possibly; IMO, people should not need to run timeit to determine basic >>> algorithmic speed for standard Python datatypes. >> >> http://wiki.python.org/moin/TimeComplexity takes a stab at it. IIRC, >> last time this came up, there was some resistance to making promises >> about time complexity in the official docs, since that would make >> those numbers part of the language, and thus binding on other >> implementations. > > I'm thoroughly aware of that page and updated it yesterday to make it > easier to find. ;-) > > However, I think there are some rock-bottom basic guarantees we can make > regardless of implementation. Does anyone seriously think that an > implementation would be accepted that had anything other than O(1) for > index access into tuples and lists? Does anyone seriously think that an implementation should be rejected as an implementation if it intellegently did seq[n] lookups in log2(n)/31 time units for all n (as humans would do), instead of stupidly taking 1 time unit for all n < 2**31 and rejecting all larger values (as 32-bit CPython does)? > Dicts that were not O(1) for access with non-pathological hashing? You would actually be unhappy if small dicts ran even faster than they do now (while large dicts ran the same)? Not me! > I suggest that we should agree on these guarantees and document them in > the core. I disagree for several reasons. 1. It would a category mistake. Python is an abstract algorithm language. The concept of speed is not applicable. I happen to think it one of the best, which is why I once dubbed it 'executable pseudocode', to compare it to similar but inferior, non-executable algorithm languages too often used still today. To human readers, as readers, speed of CPython or anything else is not relevant. 2. A Python interpreter is an abstract algorithm. Algorithms can be characterized by operation counts, but not by physical universe time. 3. Algorithms, including Python interpreters, can be embodied in anything that can compute, including humans, VonNeuman machines of various types, and possible future non-VonNeuman machines. To limit 'python interpreter' to current vonNeuman machines would be short sighted. Human interpretation of Python code (and other specifications) is part of development, testing, and debugging. 4. Guarantee? Who will pay what to who if what is not performed ;-?. The Python license intentionally disclaims any guarantee of performance. If you are using 'guarantee' metaphorically, perhaps try another word. 5. Accepted? If you want to claim that an interpreter that is useless for your purposes is not really an interpreter, you are free to, I suppose. Asking the PSF to impose your view on me would, to me, violate its diversity policy. 6. O-notation was developed for characterizing the asymptotic (large-N) behavior of abstract algorithms in terms of abstract operation counts. Left out are differences between operations, lower order terms, multiplicative constants, how large N must be to get large-N behavior, and what happens for smaller N. These and other factors make the translation of O(f(n)) into real time extremely mushy or even wrong. I already suggested that O(1) lookup is a symption of simple-minded arithmetic stupidity, of doing unnecessary work when adding small numbers. When it is a result doing most additions slower than necessary, it is a bad thing, not a good thing, and a bad criteria for an acceptable algorithm and acceptable interpreter. Similarly, books say that O(n*logn) sorting is 'better' that O(n**2) sorting. However, Tim Peters verified that the opposite is true for real times for small n, and hence the current list.sort smartly uses a fast O(n**2) algorithm for small lists (len < 64) and small runs in larger lists. Rejecting list.sort for this reason would be stupid. -- Terry Jan Reedy From aurfalien at gmail.com Tue Aug 31 19:24:26 2010 From: aurfalien at gmail.com (aurfalien at gmail.com) Date: Tue, 31 Aug 2010 16:24:26 -0700 Subject: msg.attach multiple attachments and passing vars to html Message-ID: Hi, Few questions as I've been at this for dayz. Can I do multiple attachments in order via msg.attach as so; part1 = MIMEText(html, 'html') msg.attach(part1) part2 = MIMEText(text, 'plain') msg.attach(part2) part3 = MIMEText(html, 'html') msg.attach(part3) I desire to attach part1, part2 and part3 in that order. Also, is it somehow possible to pas python vars to html? My goal to to have an email that says something like; Welcome to ACME. A few LINKS to get you started. Your user name is USRNM and your password is PASS Where USRNM and PASS are python vars but the rest is an html based email. LINKS is an actual hyperlink, hence the desire to do html based emails. Thanks in advance, - aurf From tjreedy at udel.edu Tue Aug 31 19:33:12 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Aug 2010 19:33:12 -0400 Subject: Stackless Python and EVE Online In-Reply-To: References: Message-ID: On 8/31/2010 11:10 AM, Benjamin Kaplan wrote: > On Tuesday, August 31, 2010, Roman Sokolyuk wrote: >> Hi, >> >> I am new to Python and I wanted to understand something... >> The EVE Online Client is build using Stackless Python >> So when I install the client on my machine, how doe sit get run if I do not have Python installed? >> > We call it "freezing" the program. There are several tools that do > this with py2exe being the most popular. These tools create an > executable that includes a bundled python interpreter along with all > the scripts and modules needed to run the program. Bundling Python with an app adds a few megabytes, depending on how many modules are included. For a 10K script, that is a big nuisance. For a 100M+ app, it is trivial. While I have not yet tried Eve, both for lack of a good enough machine and fear of having my life sucked away, it has been a positive for Python. Beyond the publicity, Eve is a pretty good stress test, and they have contributed a few bug reports and patches back to the core. -- Terry Jan Reedy From alex.kapps at web.de Tue Aug 31 19:36:14 2010 From: alex.kapps at web.de (Alexander Kapps) Date: Wed, 01 Sep 2010 01:36:14 +0200 Subject: Python libs on Windows ME In-Reply-To: References: Message-ID: <4C7D91EE.3060108@web.de> hexusnexus at gmail.com wrote: > On Aug 31, 2:04 pm, Thomas Jollans wrote: >> On Tuesday 31 August 2010, it occurred to hexusne... at gmail.com to exclaim: >> >>> I'm not guessing that this is a problem on Windows 98, but on Windows >>> ME modules in /Lib don't seem to load. Examples include site.py and >>> os.py which are both located in the top level Lib directory. The same >>> thing happens with Python 2.3, 2.4, and 2.5. I can't get IDLE to load >>> and the Python interpreter always complains that it can't load the >>> "site" module even if Python is run from the same directory as the >>> module (note: this does not happen if a module is loaded from the >>> current working directory while in the interpreter). >> What is sys.path set to ? >> >> python.exe -c "import sys; print(sys.path)" >> >> It sounds like the stdlib directory is not on sys.path. Couldn't say why >> though... >> >> >> >>> I would use another os like Linux or Windows 2000, but this particular >>> computer can't even seem to handle even the most minimal graphical >>> Linux distributions. >> Really? I'm sure you can get Linux on there somehow. It might not be trivial, >> but it should definitely be possible. Out of interest: what distros did you >> try? > > I think Puppy Linux might work, but I'd need GTK for wxPython, and I > assume that means version 2 of GTK which I'm not sure comes with Puppy > Linux and I've experienced problems in the past compiling GTK with './ > configure && make' and so on. Well, just try. AFAIK, Puppy has GTK2 (actually, it would surprise me if not) From ameyer2 at yahoo.com Tue Aug 31 20:20:12 2010 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 31 Aug 2010 20:20:12 -0400 Subject: Saving (unusual) linux filenames In-Reply-To: References: Message-ID: <4C7D9C3C.70706@yahoo.com> On 8/31/2010 2:33 PM, Nobody wrote: ... > FWIW, my usual solution is URL-encoding (i.e. replacing any "awkward" > character by a "%" followed by two hex digits representing the byte's > value). It has the advantage that you can extend the set of bytes which > need encoding as needed without having to change the code (e.g. you can > provide a command-line argument or configuration file setting which > specifies which bytes need to be encoded). I like that one. A similar solution is to use an escape character, e.g., backslash, e.g., "This is a backslash\\ and this is a comma\,." However, because the comma won't appear at all in the URL-encoded version, it has the virtue of still allowing you to split on commas. You must of course also URL encode the '%' as %25, e.g., "Here is a comma (%2C) and this (%2C) is a percent sign." Alan From nobody at nowhere.com Tue Aug 31 20:25:37 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 01 Sep 2010 01:25:37 +0100 Subject: Saving (unusual) linux filenames References: Message-ID: On Tue, 31 Aug 2010 18:49:33 +0000, Grant Edwards wrote: >> How many filenames contain control characters? > > How many filenames contain ","? Not many, Unless you only ever deal with "Unix folk", it's not /that/ uncommon to encounter filenames which are essentially complete sentences, punctuation included. FWIW, I've found that a significant proportion of "why can't I burn this file to a CD" queries are because the Joliet extension to ISO-9660 "only" allows 64 characters in a filename. From python at mrabarnett.plus.com Tue Aug 31 20:44:10 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 01 Sep 2010 01:44:10 +0100 Subject: msg.attach multiple attachments and passing vars to html In-Reply-To: References: Message-ID: <4C7DA1DA.9040205@mrabarnett.plus.com> On 01/09/2010 00:24, aurfalien at gmail.com wrote: > Hi, > > Few questions as I've been at this for dayz. > > Can I do multiple attachments in order via msg.attach as so; > > part1 = MIMEText(html, 'html') > msg.attach(part1) > part2 = MIMEText(text, 'plain') > msg.attach(part2) > part3 = MIMEText(html, 'html') > msg.attach(part3) > > I desire to attach part1, part2 and part3 in that order. > This might help: http://snippets.dzone.com/posts/show/2038 > Also, is it somehow possible to pas python vars to html? > > My goal to to have an email that says something like; > > Welcome to ACME. > > A few LINKS to get you started. > > Your user name is USRNM and your password is PASS > > Where USRNM and PASS are python vars but the rest is an html based email. > > LINKS is an actual hyperlink, hence the desire to do html based emails. > Create a template HTML with placeholders and then the individual HTML by replacing the placeholders with the values, something like: template_html = "Your user name is %USRNM% and your password is %PASS%." ... user_html = template_html.replace("%USRNM%", username).replace("%PASS%", password) That's the general idea. From ldo at geek-central.gen.new_zealand Tue Aug 31 20:47:47 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 01 Sep 2010 12:47:47 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x4oeftuk4.fsf@ruckus.brouhaha.com> <7x39twpuxi.fsf@ruckus.brouhaha.com> <7xr5hguzzi.fsf@ruckus.brouhaha.com> <7xtymbzixt.fsf@ruckus.brouhaha.com> Message-ID: In message <7xtymbzixt.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > It's pretty well established by now that GC doesn't have any significant > speed penalty compared with manual allocation. It does consume more > memory, which is acceptable a lot of the time. It certainly leads to > more reliable programs. And yet Java code, for example, doesn?t have a reputation for greater reliability compared to, say code written in Ada or C++, or even C. What is the Java runtime written in? C. Why not use Java, if there is no speed penalty in doing so? From Eric_Dexter at msn.com Tue Aug 31 20:51:59 2010 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Tue, 31 Aug 2010 17:51:59 -0700 (PDT) Subject: ride tab editor 2.03 has been released Message-ID: <5f352ccf-71ba-45a9-9139-50eecf3d0d40@f6g2000yqa.googlegroups.com> ride tab editor 2.03 has been released. ride tab editor features customizable instruments and an editable tool menu (alpha help would be nice). also included are some scripts showing how you can use the output files in csound. The 2 series is an expansion of ride guitar tab editor that managed to get over 2000 downloads. http://dexrowem.blogspot.com/search?q=ride+tab+editor From clp2 at rebertia.com Tue Aug 31 20:53:48 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 31 Aug 2010 17:53:48 -0700 Subject: msg.attach multiple attachments and passing vars to html In-Reply-To: <4C7DA1DA.9040205@mrabarnett.plus.com> References: <4C7DA1DA.9040205@mrabarnett.plus.com> Message-ID: On Tue, Aug 31, 2010 at 5:44 PM, MRAB wrote: > On 01/09/2010 00:24, aurfalien at gmail.com wrote: >> Also, is it somehow possible to pas python vars to html? >> >> My goal to to have an email that says something like; >> >> Welcome to ACME. >> A few LINKS to get you started. >> Your user name is USRNM and your password is PASS >> >> Where USRNM and PASS are python vars but the rest is an html based email. >> LINKS is an actual hyperlink, hence the desire to do html based emails. >> > Create a template HTML with placeholders and then the individual HTML > by replacing the placeholders with the values, something like: > > ? ?template_html = "Your user name is %USRNM% and your password is %PASS%." > ? ... > ? user_html = template_html.replace("%USRNM%", username).replace("%PASS%", > password) > > That's the general idea. In the general case though, one needs to be sure to properly escape the inserted text: from cgi import escape user_html = template_html.replace("%USRNM%", escape(username)).replace("%PASS%", escape(password)) Also, string formatting would probably be safer than .replace() in the unlikely but not impossible event that user input and the magic placeholder names overlap. Cheers, Chris -- http://blog.rebertia.com From ldo at geek-central.gen.new_zealand Tue Aug 31 20:55:57 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 01 Sep 2010 12:55:57 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> Message-ID: In message <7x39tz42fd.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Dennis Lee Bieber writes: > >> Heap marking, OTOH, tends to run at indeterminate times, which could >> have an impact if one needs predictable response timings > > Reference counting has the same problem. If you drop the last reference > to a complex structure, it could take quite a long time to free all the > components. One difference is the interaction with caching behaviour. When a reference- counted object is freed, the odds are that happens fairly soon after the last access, so the object will still be in the CPU cache, and access will be fast. Whereas garbage collection will happen at some indeterminate time long after the last access to the object, when it very likely will no longer be in the cache, and have to be brought back in just to be freed, quite likely bumping out something else that the running program needs to access. This is one reason why garbage collection is still considered an expensive technique. Computing power has improved by something like five orders of magnitude over the last half-century, making possible all kinds of productivity-enhancing techniques that were once considered expensive to become commonplace: high-level languages, dynamic memory allocation, stacks, hardware floating-point, memory protection and so on. But alone of all of these, garbage collection still remains just as costly to implement as ever. That should tell you something about how poorly it matches the characteristics of modern computing hardware. From ldo at geek-central.gen.new_zealand Tue Aug 31 20:57:11 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 01 Sep 2010 12:57:11 +1200 Subject: Queue cleanup References: <08bd9595-10b1-4b4c-9577-baa65032933a@y3g2000vbm.googlegroups.com> <4c78572c$0$28655$c3e8da3@news.astraweb.com> <7x39tz42fd.fsf@ruckus.brouhaha.com> <4c78e7a5$0$28655$c3e8da3@news.astraweb.com> <4c7a2c3b$0$22941$e4fe514c@news.xs4all.nl> <7xhbidndc6.fsf@ruckus.brouhaha.com> <8e15pqFn89U1@mid.individual.net> <7xmxs4uzjl.fsf@ruckus.brouhaha.com> Message-ID: In message <7xmxs4uzjl.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Gregory Ewing writes: > >> I'd be disappointed if CPython ditched refcounting and >> then became unsuitable for real-time games as a result. > > Refcounting is susceptable to the same pauses for reasons already > discussed. Doesn?t seem to happen in the real world, though. From cs at zip.com.au Tue Aug 31 21:22:45 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 1 Sep 2010 11:22:45 +1000 Subject: Optimising literals away In-Reply-To: <4C7D8462.8060505@mrabarnett.plus.com> References: <4C7D8462.8060505@mrabarnett.plus.com> Message-ID: <20100901012244.GA23427@cskk.homeip.net> On 31Aug2010 23:38, MRAB wrote: | On 31/08/2010 23:11, Cameron Simpson wrote: | >On 31Aug2010 22:53, MRAB wrote: | >| There's still the possibility of some optimisation. If the resulting | >| set is never stored anywhere (bound to a name, for example) then it | >| could be created once. When the expression is evaluated there could be | >| a check so see whether 'set' is bound to the built-in class, and, if it | >| is, then just use the pre-created set. | > | >Wouldn't you need to repeat that check every time, otherwise "set" may | >no longer be the builtin? | | Isn't that what I said? Yes. It's not what my brain decided to read to me. | My point is that if you have a set of constants which is created and | then discarded you can cache it and reuse it next time. You check every | time whether 'set' is bound to the set class. Ok then. I was thinking, for some reason, a JIT-like behaviour that didn't just reuse the previously made set but replaced the set([1,2,3]) itself, thus omitting the test you mentioned:-( Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ It's hard to make a man understand something when his livelihood depends on him not understanding it. - Upton Sinclair From mahaboobnisha at gmail.com Tue Aug 31 21:26:01 2010 From: mahaboobnisha at gmail.com (roshini begum) Date: Tue, 31 Aug 2010 18:26:01 -0700 (PDT) Subject: comp.lang.python Message-ID: www.127760.blogspot.com From reply-to at works.fine.invalid Tue Aug 31 21:51:25 2010 From: reply-to at works.fine.invalid (NickC) Date: 01 Sep 2010 01:51:25 GMT Subject: Structured programming with optionParser References: <4c7c5eca$0$11121$c3e8da3@news.astraweb.com> Message-ID: <4c7db19d$0$11121$c3e8da3@news.astraweb.com> On Mon, 30 Aug 2010 21:19:08 -0700, Michele Simionato wrote: > Perhaps, I should give an example of using plac. > > For more (including managing options, which I have not shown here) you > should check the full documentation of plac. I have just uploaded > release 0.7.2, which is required for this example to work. Many thanks, very useful. -- NickC From python.koda at gmail.com Tue Aug 31 22:00:45 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 22:00:45 -0400 Subject: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: @MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ? is there a way to do it automaticaly ? @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as WordPointCloud passe) :) Anyway, thank you ! 2010/8/31 Xavier Ho > On 1 September 2010 07:57, Alban Nona wrote: > >> listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE", >> "DPF", "SDW", "MAT", "WPP"] >> > > Out of curiosity, could you briefly mention what "SDW" and "WPP" passes > are? I've worked out the rest, and these two are riddling my brain. > > (On topic: If you want only the elements starting with ELM001, or whatever, > use a if condition like what MRAB posted.) > > Cheers, > Xav > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Aug 31 22:18:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 01 Sep 2010 03:18:07 +0100 Subject: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> Message-ID: <4C7DB7DF.5050906@mrabarnett.plus.com> On 01/09/2010 03:00, Alban Nona wrote: > @MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ? > is there a way to do it automaticaly ? > If you can do it for 'Elem001', I'm sure you could write some code to produce a list of 'Elem001', 'Elem002', etc, and check whether any are substrings, just as was done for 'Elem001'. > @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as > WordPointCloud passe) :) > > Anyway, thank you ! > [snip] Do you want separate lists for 'Elem001', 'Elem002', etc, or all in the same list? From bussiere at gmail.com Tue Aug 31 22:33:50 2010 From: bussiere at gmail.com (bussiere bussiere) Date: Wed, 1 Sep 2010 04:33:50 +0200 Subject: [Pickle]dirty problem 3 lines Message-ID: i know it's dirty, i know i should use json but i want to know, it's quiet late here : import pickle dump = """b'\x80\x03]q\x00(K\x00K\x01e.'""" print(pickle.loads(dump)) how can i get back my object from this string ? the string is : b'\x80\x03]q\x00(K\x00K\x01e.' and i'am using python3 help will be appreciated i'am chewing on this for a long time now. Regards B. fan of dresden files From python at mrabarnett.plus.com Tue Aug 31 23:23:57 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 01 Sep 2010 04:23:57 +0100 Subject: [Pickle]dirty problem 3 lines In-Reply-To: References: Message-ID: <4C7DC74D.6060702@mrabarnett.plus.com> On 01/09/2010 03:33, bussiere bussiere wrote: > i know it's dirty, i know i should use json but i want to know, it's > quiet late here : > import pickle > dump = """b'\x80\x03]q\x00(K\x00K\x01e.'""" > print(pickle.loads(dump)) > > how can i get back my object from this string ? > the string is : b'\x80\x03]q\x00(K\x00K\x01e.' > and i'am using python3 > help will be appreciated i'am chewing on this for a long time now. Well, pickle.loads(b'\x80\x03]q\x00(K\x00K\x01e.') works. That, of course, is not the same as """b'\x80\x03]q\x00(K\x00K\x01e.'""". Do you mean r"""b'\x80\x03]q\x00(K\x00K\x01e.'"""? (It's also late here, well, actually, so late it's early... Time to sleep. :-)) From python.koda at gmail.com Tue Aug 31 23:47:08 2010 From: python.koda at gmail.com (Alban Nona) Date: Tue, 31 Aug 2010 23:47:08 -0400 Subject: Fwd: Dumb Stupid Question About List and String In-Reply-To: References: <4C7D5B3F.5070102@mrabarnett.plus.com> <4C7DB7DF.5050906@mrabarnett.plus.com> Message-ID: In fact, the First list (wich contain "Elm001, Elm002, Elm003) will be generated automatically from files that I have in a directory, that's why I cant write the same code for Elm002, 003, etc... Because Ill not know how many Elm there will be. 2010/8/31 MRAB > On 01/09/2010 03:00, Alban Nona wrote: > > @MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ? >> is there a way to do it automaticaly ? >> >> If you can do it for 'Elem001', I'm sure you could write some code to > produce a list of 'Elem001', 'Elem002', etc, and check whether any are > substrings, just as was done for 'Elem001'. > > > @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as >> WordPointCloud passe) :) >> >> Anyway, thank you ! >> >> [snip] > Do you want separate lists for 'Elem001', 'Elem002', etc, or all in the > same list? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL:

%s %s %s
%s %s %s
%s %s %s
%s") Though I think I'd make it a bit clearer by naming the fields: for host, hits, dt in dataset: print ("
%s
%s
%s
%s
Some Date String SomeTag A Title Some Comment
Some Date String SomeTag > ? ? ? ? A Title > ? ? ? > ? ? ? ? ? ? ? ? ? Click > ? ? ? ? > ? ? ? Some Comment
Some Date String SomeTag > A Title > > Click > > Some Comment
Some Date String SomeTag > ? ? ? ? A Title > ? ? ? > ? ? ? ? ? ? ? ? ?Click > ? ? ? ? > ? ? ? Some Comment
Some Date String SomeTag >> A Title >> >> > Click >> >> Some Comment
Some Date String SomeTag > A Title > > Click > > Some Comment
Some Date String SomeTag > A Title > > Click > > Some Comment
Some Date String SomeTag > >> ? ? ? ? A Title > >> ? ? ? > >> ? ? ? ? >> ? ? ? ? ? Click > >> ? ? ? ? > >> ? ? ? Some Comment